File: scenegraph.h

package info (click to toggle)
embree 4.3.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 100,656 kB
  • sloc: cpp: 228,918; xml: 40,944; ansic: 2,685; python: 812; sh: 635; makefile: 228; csh: 42
file content (1660 lines) | stat: -rw-r--r-- 55,062 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
// Copyright 2009-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0

#pragma once

#include "lights.h"
#include "../../../include/embree4/rtcore.h"
RTC_NAMESPACE_USE
#include "../math/random_sampler.h"

namespace embree
{  
  struct Material;
  
  namespace SceneGraph
  {
    struct Node;
    struct MaterialNode;
    struct Transformations;
    struct TriangleMeshNode;
    struct QuadMeshNode;
    struct GridMeshNode;

    Ref<Node> load(const FileName& fname, bool singleObject = false);
    void store(Ref<Node> root, const FileName& fname, bool embedTextures, bool referenceMaterials, bool binaryFormat);
    void extend_animation(Ref<Node> node0, Ref<Node> node1);
    void optimize_animation(Ref<Node> node0);
    void set_motion_vector(Ref<Node> node, const Vec3fa& dP);
    void set_motion_vector(Ref<Node> node, const avector<Vec3fa>& motion_vector);
    void set_time_range(Ref<SceneGraph::Node> node, const BBox1f& time_range);
    void resize_randomly(RandomSampler& sampler, Ref<Node> node, const size_t N);
    Ref<Node> convert_triangles_to_quads(Ref<Node> node, float prop);
    Ref<Node> convert_triangles_to_quads( Ref<TriangleMeshNode> tmesh);
    Ref<Node> convert_quads_to_subdivs(Ref<Node> node);
    Ref<Node> my_merge_quads_to_grids(Ref<SceneGraph::Node> node);
    Ref<Node> convert_bezier_to_lines(Ref<Node> node);
    Ref<Node> convert_bezier_to_bspline(Ref<Node> node);
    Ref<Node> convert_bezier_to_hermite(Ref<Node> node);
    Ref<Node> convert_bspline_to_bezier(Ref<Node> node);
    Ref<Node> convert_flat_to_round_curves(Ref<Node> node);
    Ref<Node> convert_round_to_flat_curves(Ref<Node> node);
    Ref<Node> convert_quads_to_grids( Ref<QuadMeshNode> qmesh,  const unsigned resX, const unsigned resY );
    Ref<Node> convert_quads_to_grids( Ref<Node> node, const unsigned resX, const unsigned resY );
    Ref<Node> convert_grids_to_quads( Ref<GridMeshNode> gmesh);
    Ref<Node> convert_grids_to_quads( Ref<Node> node);

    Ref<Node> remove_mblur(Ref<Node> node, bool mblur);
    void convert_mblur_to_nonmblur(Ref<Node> node);

    extern void (*opaque_geometry_destruction)(void*);

    struct Statistics
    {
      Statistics ()
      : numTriangleMeshes(0), numTriangles(0), numTriangleBytes(0),
        numQuadMeshes(0),     numQuads(0),     numQuadBytes(0),
        numSubdivMeshes(0),   numPatches(0),   numSubdivBytes(0),
        numCurveSets(0),      numCurves(0),    numCurveBytes(0),
        numGridMeshNodes(0),  numGrids(0),     numGridBytes(0),
        numPointSets(0),      numPoints(0),    numPointBytes(0),
        numTransformNodes(0),
        numTransformedObjects(0),
        numLights(0),
        numCameras(0),
        numMaterials(0) {}

      void print();
      
      size_t numTriangleMeshes;
      size_t numTriangles;
      size_t numTriangleBytes;
      
      size_t numQuadMeshes;
      size_t numQuads;
      size_t numQuadBytes;
      
      size_t numSubdivMeshes;
      size_t numPatches;
      size_t numSubdivBytes;
      
      size_t numCurveSets;
      size_t numCurves;
      size_t numCurveBytes;
      
      size_t numGridMeshNodes;
      size_t numGrids;
      size_t numGridBytes;
      
      size_t numPointSets;
      size_t numPoints;
      size_t numPointBytes;

      size_t numTransformNodes;
      size_t numTransformedObjects;
      
      size_t numLights;
      size_t numCameras;
      size_t numMaterials;
    };
    
    struct Node : public RefCount
    {
      Node (bool closed = false)
        : indegree(0), closed(closed), hasLightOrCamera(false), id(-1), geometry(nullptr) {}

      Node (const std::string& name) 
        : name(name), indegree(0), closed(false), id(-1), geometry(nullptr) {}

      ~Node() {
        if (opaque_geometry_destruction)
          opaque_geometry_destruction(geometry);
      }

      /* prints scenegraph */
      virtual void print(std::ostream& cout, int depth = 0) = 0;

      /* sets material */
      virtual void setMaterial(Ref<MaterialNode> material) {};

      /* calculates the number of parent nodes pointing to this node */
      virtual void calculateInDegree();

      /* calculates for each node if its subtree is closed, indegrees have to be calculated first */
      virtual bool calculateClosed(bool group_instancing);

      /* resets the number of parent nodes pointing to this node */
      virtual void resetInDegree();

      /* calculates statistics */
      virtual void calculateStatistics(Statistics& stat);

      /* checks if the node is closed */
      __forceinline bool isClosed() const { return closed; }

      /* calculates bounding box of node */
      virtual BBox3fa bounds() const {
        return empty;
      }

      virtual BBox3fa bounds(size_t i) const {
        return empty;
      }

      /* calculates linear bounding box of node */
      virtual LBBox3fa lbounds() const {
        return empty;
      }

      virtual LBBox3fa lbounds(size_t i) const {
        return empty;
      }

      /* calculates number of primitives */
      virtual size_t numPrimitives() const {
        return 0;
      }

      Ref<Node> set_motion_vector(const Vec3fa& dP) {
        SceneGraph::set_motion_vector(this,dP); return this;
      }

      Ref<Node> set_motion_vector(const avector<Vec3fa>& motion_vector) {
        SceneGraph::set_motion_vector(this,motion_vector); return this;
      }

    public:
      std::string fileName; // when set to some filename the exporter references this file
      std::string name;     // name of this node
      size_t indegree;      // number of nodes pointing to us
      bool closed;          // determines if the subtree may represent an instance
      bool hasLightOrCamera;
      unsigned int id;
      void* geometry;
    };

    struct Transformations
    {
      __forceinline Transformations() {}

      __forceinline Transformations(OneTy)
        : time_range(0.0f,1.0f)
      {
        spaces.push_back(one);
      }

      __forceinline Transformations( const BBox1f& time_range, size_t N ) 
        : time_range(time_range), spaces(N) {}
      
      __forceinline Transformations(const AffineSpace3fa& space)
        : time_range(0.0f,1.0f)
      {
        spaces.push_back(space);
      }

      __forceinline Transformations(const AffineSpace3fa& space0, const AffineSpace3fa& space1)
        : time_range(0.0f,1.0f)
      {
        spaces.push_back(space0);
        spaces.push_back(space1);
      }

      __forceinline Transformations(const avector<AffineSpace3ff>& spaces)
        : time_range(0.0f,1.0f), spaces(spaces) { assert(spaces.size()); }

      __forceinline size_t size() const {
        return spaces.size();
      }

      __forceinline       AffineSpace3ff& operator[] ( const size_t i )       { return spaces[i]; }
      __forceinline const AffineSpace3ff& operator[] ( const size_t i ) const { return spaces[i]; }

      BBox3fa bounds ( const BBox3fa& cbounds ) const 
      {
        BBox3fa r = empty;
        for (size_t i=0; i<spaces.size(); i++)
          r.extend(xfmBounds(spaces[i],cbounds));
        return r;
      }

      LBBox3fa lbounds ( const LBBox3fa& cbounds ) const 
      {
        assert(spaces.size());
        if (spaces.size() == 1) 
        {
          return LBBox3fa(xfmBounds(spaces[0],cbounds.bounds0),
                          xfmBounds(spaces[0],cbounds.bounds1));
        }
        else
        {
          avector<BBox3fa> bounds(spaces.size());
          for (size_t i=0; i<spaces.size(); i++) {
            const float f = float(i)/float(spaces.size()-1);
            bounds[i] = xfmBounds(spaces[i],cbounds.interpolate(f));
          }
          return LBBox3fa(bounds);
        }
      }

      void add (const Transformations& other) {
        for (size_t i=0; i<other.size(); i++) spaces.push_back(other[i]);
      }

      static __forceinline bool isIdentity(AffineSpace3ff const& M, bool q)
      {
        if (M.l.vx.x      != 1.f) return false;
        if (M.l.vx.y      != 0.f) return false;
        if (M.l.vx.z      != 0.f) return false;
        if (q && M.l.vx.w != 0.f) return false;

        if (M.l.vy.x      != 0.f) return false;
        if (M.l.vy.y      != 1.f) return false;
        if (M.l.vy.z      != 0.f) return false;
        if (q && M.l.vy.w != 0.f) return false;

        if (M.l.vz.x      != 0.f) return false;
        if (M.l.vz.y      != 0.f) return false;
        if (M.l.vz.z      != 1.f) return false;
        if (q && M.l.vz.w != 0.f) return false;

        if (M.p.x         != 0.f) return false;
        if (M.p.y         != 0.f) return false;
        if (M.p.z         != 0.f) return false;
        if (q && M.p.w    != 1.f) return false;

        return true;
      }

      static __forceinline AffineSpace3ff mul(AffineSpace3ff const& M0, AffineSpace3ff const& M1, bool q0, bool q1, bool& q)
      {
        q = false;
        if (isIdentity(M0, q0)) { q = q1; return M1; }
        if (isIdentity(M1, q1)) { q = q0; return M0; }

        // simple case non of the transformations is a quaternion
        if (q0 == false && q1 == false)
        {
          return M0 * M1;
        }
        else if (q0 == true && q1 == true)
        {
          std::cout << "warning: cannot multiply two quaternion decompositions. will convert to regular transforms and multiply" << std::endl;
          return quaternionDecompositionToAffineSpace(M0) * quaternionDecompositionToAffineSpace(M1);
        }
        else if (q0 == true && q1 == false)
        {
          AffineSpace3fa S; Quaternion3f Q; Vec3fa T;
          quaternionDecomposition(M0, T, Q, S);
          S = S * AffineSpace3fa(M1);
          if (S.l.vx.y != 0.f || S.l.vx.z != 0 || S.l.vy.z != 0)
            std::cout << "warning: cannot multiply quaternion and general transformation matrix. will ignore lower diagonal" << std::endl;
          q = true;
          return quaternionDecomposition(T, Q, S);
        }
        else {
          if (M0.l.vx.y != 0.f || M0.l.vx.z != 0 || M0.l.vy.z != 0 || M0.l.vy.x != 0.f || M0.l.vz.x != 0 || M0.l.vz.y != 0)
            std::cout << "warning: cannot multiply general transformation matrix and quaternion. will only consider translation and diagonal as scale factors" << std::endl;
          AffineSpace3ff M = M1;
          M.l.vx.y += M0.p.x;
          M.l.vx.z += M0.p.y;
          M.l.vy.z += M0.p.z;
          M.l.vx.x *= M0.l.vx.x;
          M.l.vy.y *= M0.l.vy.y;
          M.l.vz.z *= M0.l.vz.z;
          q = true;
          return M;
        }
      }

      friend __forceinline Transformations operator* ( const Transformations& a, const Transformations& b )
      {
        if (a.size() == 1)
        {
          Transformations c(intersect(a.time_range,b.time_range),b.size());
          for (size_t i=0; i<b.size(); i++) c[i] = mul(a[0], b[i], a.quaternion, b.quaternion, c.quaternion);
          return c;
        } 
        else if (b.size() == 1)
        {
          Transformations c(intersect(a.time_range,b.time_range),a.size());
          c.quaternion = a.quaternion || b.quaternion;
          for (size_t i=0; i<a.size(); i++) c[i] = mul(a[i], b[0], a.quaternion, b.quaternion, c.quaternion);
          return c;
        }
        else if (a.size() == b.size())
        {
          Transformations c(intersect(a.time_range,b.time_range),a.size());
          c.quaternion = a.quaternion || b.quaternion;
          for (size_t i=0; i<a.size(); i++) c[i] = mul(a[i], b[i], a.quaternion, b.quaternion, c.quaternion);
          return c;
        }
        else
          THROW_RUNTIME_ERROR("number of transformations does not match");
      }

      friend __forceinline std::vector<Transformations> operator* ( const std::vector<Transformations>& a, const Transformations& b )
      {
        std::vector<Transformations> result;
        for (size_t i = 0; i < a.size(); ++i) {
          result.push_back(a[i] * b);
        }
        return result;
      }

      friend __forceinline std::vector<Transformations> operator* ( const Transformations& a, const std::vector<Transformations>& b )
      {
        return b * a;
      }

      friend __forceinline std::vector<Transformations> operator* ( const std::vector<Transformations>& a, const std::vector<Transformations>& b )
      {
        if(a.size() != b.size())
          THROW_RUNTIME_ERROR("number of transformations does not match");

        std::vector<Transformations> result;
        for (size_t i = 0; i < a.size(); ++i) {
          result.push_back(a[i] * b[i]);
        }

        return result;
      }

      AffineSpace3ff interpolate (const float gtime) const
      {
        assert(time_range.lower == 0.0f && time_range.upper == 1.0f);
        if (spaces.size() == 1) return spaces[0];

        /* calculate time segment itime and fractional time ftime */
        const int time_segments = int(spaces.size()-1);
        const float time = gtime*float(time_segments);
        const int itime = clamp(int(floor(time)),0,time_segments-1);
        const float ftime = time - float(itime);
        return lerp(spaces[itime+0],spaces[itime+1],ftime);
      }

    public:
      BBox1f time_range;
      avector<AffineSpace3ff> spaces;
      bool quaternion = false;
    };

    template<typename Vertex>
       std::vector<avector<Vertex>> transformMSMBlurBuffer(const std::vector<avector<Vertex>>& positions_in, const Transformations& spaces)
    {
      std::vector<avector<Vertex>> positions_out;
      const size_t num_time_steps = positions_in.size(); assert(num_time_steps);
      const size_t num_vertices = positions_in[0].size();

      /* if we have only one set of vertices, use transformation to generate more vertex sets */
      if (num_time_steps == 1)
      {
        for (size_t i=0; i<spaces.size(); i++) 
        {
          avector<Vertex> verts(num_vertices);
          for (size_t j=0; j<num_vertices; j++) {
            verts[j] = xfmPoint(spaces[i],positions_in[0][j]);
            verts[j].w = positions_in[0][j].w;
          }
          positions_out.push_back(std::move(verts));
        }
      } 
      /* otherwise transform all vertex sets with interpolated transformation */
      else
      {
        for (size_t t=0; t<num_time_steps; t++) 
        {
          float time = num_time_steps > 1 ? float(t)/float(num_time_steps-1) : 0.0f;
          const AffineSpace3ff space = spaces.interpolate(time);
          avector<Vertex> verts(num_vertices);
          for (size_t i=0; i<num_vertices; i++) {
            verts[i] = xfmPoint (space,positions_in[t][i]);
            verts[i].w = positions_in[t][i].w;
          }
          positions_out.push_back(std::move(verts));
        }
      }
      return positions_out;
    }

    inline std::vector<avector<Vec3fa>> transformMSMBlurVec3faBuffer(const std::vector<avector<Vec3fa>>& positions_in, const Transformations& spaces)
    {
      std::vector<avector<Vec3fa>> positions_out;
      const size_t num_time_steps = positions_in.size(); assert(num_time_steps);
      const size_t num_vertices = positions_in[0].size();

      /* if we have only one set of vertices, use transformation to generate more vertex sets */
      if (num_time_steps == 1)
      {
        for (size_t i=0; i<spaces.size(); i++) 
        {
          avector<Vec3fa> verts(num_vertices);
          for (size_t j=0; j<num_vertices; j++) {
            verts[j] = xfmPoint((AffineSpace3fa)spaces[i],positions_in[0][j]);
          }
          positions_out.push_back(std::move(verts));
        }
      } 
      /* otherwise transform all vertex sets with interpolated transformation */
      else
      {
        for (size_t t=0; t<num_time_steps; t++) 
        {
          float time = num_time_steps > 1 ? float(t)/float(num_time_steps-1) : 0.0f;
          const AffineSpace3ff space = spaces.interpolate(time);
          avector<Vec3fa> verts(num_vertices);
          for (size_t i=0; i<num_vertices; i++) {
            verts[i] = xfmPoint ((AffineSpace3fa)space,positions_in[t][i]);
          }
          positions_out.push_back(std::move(verts));
        }
      }
      return positions_out;
    }

    template<typename Vertex>
       std::vector<avector<Vertex>> transformMSMBlurVectorBuffer(const std::vector<avector<Vertex>>& vectors_in, const Transformations& spaces)
    {
      if (vectors_in.size() == 0)
        return vectors_in;
      
      std::vector<avector<Vertex>> vectors_out;
      const size_t num_time_steps = vectors_in.size();
      const size_t num_vertices = vectors_in[0].size();

      /* if we have only one set of vertices, use transformation to generate more vertex sets */
      if (num_time_steps == 1)
      {
        for (size_t i=0; i<spaces.size(); i++) 
        {
          avector<Vertex> vecs(num_vertices);
          for (size_t j=0; j<num_vertices; j++) {
            vecs[j] = xfmVector(spaces[i],vectors_in[0][j]);
            vecs[j].w = vectors_in[0][j].w;
          }
          vectors_out.push_back(std::move(vecs));
        }
      } 
      /* otherwise transform all vertex sets with interpolated transformation */
      else
      {
        for (size_t t=0; t<num_time_steps; t++) 
        {
          float time = num_time_steps > 1 ? float(t)/float(num_time_steps-1) : 0.0f;
          const AffineSpace3ff space = spaces.interpolate(time);
          avector<Vertex> vecs(num_vertices);
          for (size_t i=0; i<num_vertices; i++) {
            vecs[i] = xfmVector (space,vectors_in[t][i]);
            vecs[i].w = vectors_in[t][i].w;
          }
          vectors_out.push_back(std::move(vecs));
        }
      }
      return vectors_out;
    }

    template<typename Vertex>
       std::vector<avector<Vertex>> transformMSMBlurVectorVec3faBuffer(const std::vector<avector<Vertex>>& vectors_in, const Transformations& spaces)
    {
      if (vectors_in.size() == 0)
        return vectors_in;
      
      std::vector<avector<Vertex>> vectors_out;
      const size_t num_time_steps = vectors_in.size();
      const size_t num_vertices = vectors_in[0].size();

      /* if we have only one set of vertices, use transformation to generate more vertex sets */
      if (num_time_steps == 1)
      {
        for (size_t i=0; i<spaces.size(); i++) 
        {
          avector<Vertex> vecs(num_vertices);
          for (size_t j=0; j<num_vertices; j++) {
            vecs[j] = xfmVector((AffineSpace3fa)spaces[i],vectors_in[0][j]);
          }
          vectors_out.push_back(std::move(vecs));
        }
      } 
      /* otherwise transform all vertex sets with interpolated transformation */
      else
      {
        for (size_t t=0; t<num_time_steps; t++) 
        {
          float time = num_time_steps > 1 ? float(t)/float(num_time_steps-1) : 0.0f;
          const AffineSpace3ff space = spaces.interpolate(time);
          avector<Vertex> vecs(num_vertices);
          for (size_t i=0; i<num_vertices; i++) {
            vecs[i] = xfmVector ((AffineSpace3fa)space,vectors_in[t][i]);
          }
          vectors_out.push_back(std::move(vecs));
        }
      }
      return vectors_out;
    }

    template<typename Vertex>
       std::vector<avector<Vertex>> transformMSMBlurNormalBuffer(const std::vector<avector<Vertex>>& normals_in, const Transformations& spaces)
    {
      if (normals_in.size() == 0)
        return normals_in;
      
      std::vector<avector<Vertex>> normals_out;
      const size_t num_time_steps = normals_in.size();
      const size_t num_vertices = normals_in[0].size();

      /* if we have only one set of vertices, use transformation to generate more vertex sets */
      if (num_time_steps == 1)
      {
        for (size_t i=0; i<spaces.size(); i++) 
        {
          avector<Vertex> norms(num_vertices);
          for (size_t j=0; j<num_vertices; j++) {
            norms[j] = xfmNormal((AffineSpace3fa)spaces[i],normals_in[0][j]);
          }
          normals_out.push_back(std::move(norms));
        }
      } 
      /* otherwise transform all vertex sets with interpolated transformation */
      else
      {
        for (size_t t=0; t<num_time_steps; t++) 
        {
          float time = num_time_steps > 1 ? float(t)/float(num_time_steps-1) : 0.0f;
          const AffineSpace3ff space = spaces.interpolate(time);
          avector<Vertex> norms(num_vertices);
          for (size_t i=0; i<num_vertices; i++) {
            norms[i] = xfmNormal ((AffineSpace3fa)space,normals_in[t][i]);
          }
          normals_out.push_back(std::move(norms));
        }
      }
      return normals_out;
    }

    struct PerspectiveCameraData
    {
      PerspectiveCameraData()
        : from(1,0,0), to(0,0,0), up(0,1,0), fov(30) {}
      
      PerspectiveCameraData (const Vec3fa& from, const Vec3fa& to, const Vec3fa& up, const float fov)
        : from(from), to(to), up(up), fov(fov) {}

      PerspectiveCameraData (const PerspectiveCameraData& other, const AffineSpace3fa& space)
        : from(xfmPoint(space,other.from)), to(xfmPoint(space,other.to)), up(xfmVector(space,other.up)), fov(other.fov) {}

      friend PerspectiveCameraData lerp(const PerspectiveCameraData& a, const PerspectiveCameraData& b, const float t)
      {
        const Vec3fa from = embree::lerp(a.from, b.from, t);
        const Vec3fa to   = embree::lerp(a.to  , b.to  , t);
        const Vec3fa up   = embree::lerp(a.up  , b.up  , t);
        const float  fov  = embree::lerp(a.fov , b.fov , t);
        return PerspectiveCameraData(from,to,up,fov);
      }

    public:
      Vec3fa from;   //!< position of camera
      Vec3fa to;     //!< look at point
      Vec3fa up;     //!< up vector
      float fov;     //!< vertical field of view
    };

    struct PerspectiveCameraNode : public Node
    {
      ALIGNED_STRUCT_(16);

      PerspectiveCameraNode (std::string name = "")
        : Node(name) {}
      
      PerspectiveCameraNode (const Vec3fa& from, const Vec3fa& to, const Vec3fa& up, const float fov)
        : data(from, to, up, fov) {}

      PerspectiveCameraNode (const Ref<PerspectiveCameraNode>& other, const AffineSpace3fa& space, const std::string& id = "")
        : Node(id), data(other->data,space) {}

      virtual bool isAnimated() const {
        return false;
      }

      virtual PerspectiveCameraData get(float time) const {
        return data;
      }
      
      virtual void print(std::ostream& cout, int depth);
      
      virtual void calculateStatistics(Statistics& stat);
      virtual bool calculateClosed(bool group_instancing);
            
    public:
      PerspectiveCameraData data;
    };

    struct AnimatedPerspectiveCameraNode : public PerspectiveCameraNode
    {
      AnimatedPerspectiveCameraNode (std::vector<Ref<PerspectiveCameraNode>>&& cameras, BBox1f time_range, const std::string& id = "")
        : time_range(time_range), cameras(cameras) {}

      AnimatedPerspectiveCameraNode (const Ref<AnimatedPerspectiveCameraNode>& other, const AffineSpace3fa& space, const std::string& id)
        : PerspectiveCameraNode(id), time_range(other->time_range)
      {
        cameras.resize(other->size());
        for (size_t i=0; i<other->size(); i++)
          cameras[i] = new PerspectiveCameraNode(other->cameras[i],space);
      }

      virtual bool isAnimated() const {
        return true;
      }

      virtual PerspectiveCameraData get(float time) const
      {
        time = frac((time-time_range.lower)/time_range.size());
        time = (cameras.size()-1)*time;
        int   itime = (int)floor(time);
        itime = min(max(itime,0),(int)cameras.size()-2);
        float ftime = time - (float)itime;
        return lerp(cameras[itime+0]->get(time), cameras[itime+1]->get(time), ftime);
      }
      
      virtual void print(std::ostream& cout, int depth);

      virtual void calculateStatistics(Statistics& stat);
      virtual bool calculateClosed(bool group_instancing);

      size_t size() const { return cameras.size(); }

    public:
      BBox1f time_range;
      std::vector<Ref<PerspectiveCameraNode>> cameras;
    };

    struct TransformNode : public Node
    {
      ALIGNED_STRUCT_(16);

      TransformNode (const AffineSpace3fa& xfm, const Ref<Node>& child)
        : spaces((AffineSpace3ff)xfm), child(child) {}

      TransformNode (const AffineSpace3fa& xfm0, const AffineSpace3fa& xfm1, const Ref<Node>& child)
        : spaces((AffineSpace3ff)xfm0,(AffineSpace3ff)xfm1), child(child) {}

      TransformNode (const avector<AffineSpace3ff>& spaces, const Ref<Node>& child)
        : spaces(spaces), child(child) {}

      TransformNode(const Transformations& spaces, const Ref<Node>& child)
        : spaces(spaces), child(child) {}

      virtual void setMaterial(Ref<MaterialNode> material) {
        child->setMaterial(material);
      }

      virtual void print(std::ostream& cout, int depth);
      
      virtual void calculateStatistics(Statistics& stat);
      virtual void calculateInDegree();
      virtual bool calculateClosed(bool group_instancing);
      virtual void resetInDegree();
      
      virtual BBox3fa bounds() const {
        return spaces.bounds(child->bounds());
      }

      virtual LBBox3fa lbounds() const {
        return spaces.lbounds(child->lbounds());
      }

      virtual size_t numPrimitives() const {
        return child->numPrimitives();
      }

      virtual AffineSpace3ff get(float time) const
      {
        if (spaces.size() <= 1) return spaces[0];

        int numTimeSteps = spaces.size();
        
        BBox1f time_range = spaces.time_range;
        time = frac((time-time_range.lower)/time_range.size());
        time = (numTimeSteps-1)*time;
        int   itime = (int)floor(time);
        itime = min(max(itime,0),(int)numTimeSteps-2);
        float ftime = time - (float)itime;
    
        const AffineSpace3ff xfm0 = spaces[itime+0];
        const AffineSpace3ff xfm1 = spaces[itime+1];
        const AffineSpace3ff xfm  = lerp(xfm0,xfm1,ftime);
        return xfm;
      }

    public:
      Transformations spaces;
      Ref<Node> child;
    };

    struct MultiTransformNode : public Node
    {
      ALIGNED_STRUCT_(16);

      MultiTransformNode (const avector<AffineSpace3fa>& xfm, const Ref<Node>& child)
        : child(child)
      {
        for (const AffineSpace3fa& space : xfm) {
          spaces.push_back(Transformations(space));
        }
      }

      MultiTransformNode (const avector<AffineSpace3fa>& xfm0, const avector<AffineSpace3fa>& xfm1, const Ref<Node>& child)
        : child(child)
      {
        assert(xfm0.size() == xfm1.size());
        for (size_t i = 0; i < xfm0.size(); ++i) {
          spaces.push_back(Transformations(xfm0[i], xfm1[i]));
        }
      }

      MultiTransformNode (const avector<avector<AffineSpace3ff>>& spaces_in, const Ref<Node>& child)
        : child(child)
      {
        assert(spaces_in.size() > 0);
        const size_t time_steps = spaces_in.size();
        const size_t array_size = spaces_in[0].size();
        for (size_t i = 0; i < array_size; ++i) {
          avector<AffineSpace3ff> s;
          for (size_t j = 0; j < time_steps; ++j) {
            s.push_back(spaces_in[j][i]);
          }
          spaces.push_back(Transformations(s));
        }
      }

      MultiTransformNode(const std::vector<Transformations>& spaces, const Ref<Node>& child)
        : spaces(spaces), child(child) {}

      virtual void setMaterial(Ref<MaterialNode> material) {
        child->setMaterial(material);
      }

      virtual void print(std::ostream& cout, int depth);

      virtual void calculateStatistics(Statistics& stat);
      virtual void calculateInDegree();
      virtual bool calculateClosed(bool group_instancing);
      virtual void resetInDegree();

      virtual BBox3fa bounds(size_t i) const {
        return spaces[i].bounds(child->bounds());
      }

      virtual LBBox3fa lbounds(size_t i) const {
        return spaces[i].lbounds(child->lbounds());
      }

      virtual size_t numPrimitives() const {
        return child->numPrimitives();
      }

      virtual AffineSpace3ff get(size_t i, float time) const
      {
        if (spaces[i].size() <= 1) return spaces[i][0];

        int numTimeSteps = spaces[i].size();

        BBox1f time_range = spaces[i].time_range;
        time = frac((time-time_range.lower)/time_range.size());
        time = (numTimeSteps-1)*time;
        int   itime = (int)floor(time);
        itime = min(max(itime,0),(int)numTimeSteps-2);
        float ftime = time - (float)itime;

        const AffineSpace3ff xfm0 = spaces[i][itime+0];
        const AffineSpace3ff xfm1 = spaces[i][itime+1];
        const AffineSpace3ff xfm  = lerp(xfm0,xfm1,ftime);
        return xfm;
      }

    public:
      std::vector<Transformations> spaces;
      Ref<Node> child;
    };

    struct GroupNode : public Node
    { 
      GroupNode (const size_t N = 0) { 
        children.resize(N); 
      }

      GroupNode (std::vector<Ref<Node>>& children)
        : children(children) {}

      size_t size() const {
        return children.size();
      }
      
      void add(const Ref<Node>& node) {
        if (node) children.push_back(node);
      }
      
      void set(const size_t i, const Ref<Node>& node) {
        children[i] = node;
      }
 
      Ref<Node> child ( size_t i ) const {
        return children[i];
      }

      virtual BBox3fa bounds() const
      {
        BBox3fa b = empty;
        for (auto& c : children) b.extend(c->bounds());
        return b;
      }

      virtual LBBox3fa lbounds() const
      {
        LBBox3fa b = empty;
        for (auto& c : children) b.extend(c->lbounds());
        return b;
      }

      virtual size_t numPrimitives() const 
      {
        size_t n = 0;
        for (auto& child : children) n += child->numPrimitives();
        return n;
      }

      void triangles_to_quads(float prop = inf)
      {
        for (size_t i=0; i<children.size(); i++)
          children[i] = convert_triangles_to_quads(children[i],prop);
      }

      void quads_to_grids(unsigned int resX, unsigned int resY)
      {
        for (size_t i=0; i<children.size(); i++)
          children[i] = convert_quads_to_grids(children[i],resX, resY);
      }

      void grids_to_quads()
      {
        for (size_t i=0; i<children.size(); i++)
          children[i] = convert_grids_to_quads(children[i]);
      }

      void quads_to_subdivs()
      {
        for (size_t i=0; i<children.size(); i++)
          children[i] = convert_quads_to_subdivs(children[i]);
      }
      
      void bezier_to_lines()
      {
        for (size_t i=0; i<children.size(); i++)
          children[i] = convert_bezier_to_lines(children[i]);
      }

      void flat_to_round_curves()
      {
        for (size_t i=0; i<children.size(); i++)
          children[i] = convert_flat_to_round_curves(children[i]);
      }

      void round_to_flat_curves()
      {
        for (size_t i=0; i<children.size(); i++)
          children[i] = convert_round_to_flat_curves(children[i]);
      }

      void bezier_to_bspline()
      {
        for (size_t i=0; i<children.size(); i++)
          children[i] = convert_bezier_to_bspline(children[i]);
      }

      void bezier_to_hermite()
      {
        for (size_t i=0; i<children.size(); i++)
          children[i] = convert_bezier_to_hermite(children[i]);
      }

      void bspline_to_bezier()
      {
        for (size_t i=0; i<children.size(); i++)
          children[i] = convert_bspline_to_bezier(children[i]);
      }

      void merge_quads_to_grids()
      {
        for (size_t i=0; i<children.size(); i++)
          children[i] = my_merge_quads_to_grids(children[i]);
      }

      void remove_mblur(bool mblur)
      {
        for (size_t i=0; i<children.size(); i++)
          SceneGraph::remove_mblur(children[i], mblur);
      }

      virtual void setMaterial(Ref<MaterialNode> material) {
        for (auto& child : children) child->setMaterial(material);
      }

      virtual void print(std::ostream& cout, int depth);
      
      virtual void calculateStatistics(Statistics& stat);
      virtual void calculateInDegree();
      virtual bool calculateClosed(bool group_instancing);
      virtual void resetInDegree();
      
    public:
      std::vector<Ref<Node> > children;
    };

    struct LightNode : public Node
    {
      virtual void print(std::ostream& cout, int depth);
      virtual void calculateStatistics(Statistics& stat);
      virtual bool calculateClosed(bool group_instancing);

      virtual LightType getType() const = 0;
      virtual Ref<LightNode> transform(const AffineSpace3fa& space) const = 0;
      virtual Ref<LightNode> lerp(const Ref<LightNode>& light1_in, float f) const = 0;
      virtual Ref<LightNode> get(float time) const = 0;
    };

    template<typename Light>
    struct LightNodeImpl : public LightNode
    {
      ALIGNED_STRUCT_(16);
      
      LightNodeImpl (const Light& light)
        : light(light) {}

      virtual LightType getType() const {
        return light.getType();
      }
      
      virtual Ref<LightNode> transform(const AffineSpace3fa& space) const {
        return new LightNodeImpl(light.transform(space));
      }

      virtual Ref<LightNode> get(float time) const {
        return (LightNode*) this;
      }

      virtual Ref<LightNode> lerp(const Ref<LightNode>& light1_in, float f) const
      {
        const Ref<LightNodeImpl<Light>> light1 = light1_in.dynamicCast<LightNodeImpl<Light>>();
        assert(light1);
        return new LightNodeImpl(Light::lerp(light,light1->light,f));
      }
      
      Light light;
    };

    struct AnimatedLightNode : public LightNode
    {
      AnimatedLightNode (const std::vector<Ref<LightNode>>&& lights, BBox1f time_range)
        : lights(lights), time_range(time_range) {}

      virtual LightType getType() const {
        return lights[0]->getType();
      }
      
      virtual Ref<LightNode> transform(const AffineSpace3fa& space) const
      {
        std::vector<Ref<LightNode>> xfm_lights(lights.size());
        for (size_t i=0; i<lights.size(); i++)
          xfm_lights[i] = lights[i]->transform(space);
        return new AnimatedLightNode(std::move(xfm_lights), time_range);
      }

      virtual Ref<LightNode> get(float time) const
      {
        time = frac((time-time_range.lower)/time_range.size());
        time = (lights.size()-1)*time;
        int   itime = (int)floor(time);
        itime = min(max(itime,0),(int)lights.size()-2);
        float ftime = time - (float)itime;
        Ref<LightNode> light0 = lights[itime+0]->get(time);
        Ref<LightNode> light1 = lights[itime+1]->get(time);
        return light0->lerp(light1,ftime);
      }

      virtual Ref<LightNode> lerp(const Ref<LightNode>& light1_in, float f) const {
        assert(false); return nullptr;
      }
      
    public: 
      std::vector<Ref<LightNode>> lights;
      BBox1f time_range;
    };

    
    struct MaterialNode : public Node
    {
      ALIGNED_STRUCT_USM_(16)

      MaterialNode(const std::string& name = "")
        : Node(name) {}

      virtual Material* material() = 0;

      virtual void print(std::ostream& cout, int depth);
      virtual void calculateStatistics(Statistics& stat);
    };

    /*! Mesh. */
    struct TriangleMeshNode : public Node
    {
      typedef Vec3fa Vertex;

      struct Triangle 
      {
      public:
        Triangle() {}
        Triangle (unsigned v0, unsigned v1, unsigned v2) 
        : v0(v0), v1(v1), v2(v2) {}
      public:
        unsigned v0, v1, v2;
      };
      
    public:
      TriangleMeshNode (const avector<Vertex>& positions_in, 
                        const avector<Vertex>& normals_in, 
                        const std::vector<Vec2f>& texcoords,
                        const std::vector<Triangle>& triangles,
                        Ref<MaterialNode> material) 
        : Node(true), time_range(0.0f,1.0f), texcoords(texcoords), triangles(triangles), material(material) 
      {
        positions.push_back(positions_in);
        normals.push_back(normals_in);
      }

      TriangleMeshNode (Ref<MaterialNode> material, const BBox1f time_range = BBox1f(0,1), size_t numTimeSteps = 0) 
        : Node(true), time_range(time_range), material(material) 
      {
        for (size_t i=0; i<numTimeSteps; i++)
          positions.push_back(avector<Vertex>());
      }

      TriangleMeshNode (Ref<SceneGraph::TriangleMeshNode> imesh, const Transformations& spaces)
        : Node(true),
          time_range(imesh->time_range),
          positions(transformMSMBlurVec3faBuffer(imesh->positions,spaces)),
          normals(transformMSMBlurNormalBuffer(imesh->normals,spaces)),
          texcoords(imesh->texcoords), triangles(imesh->triangles), material(imesh->material) {}
      
      virtual void setMaterial(Ref<MaterialNode> material) {
        this->material = material;
      }

      virtual BBox3fa bounds() const
      {
        BBox3fa b = empty;
        for (const auto& p : positions)
          for (auto& x : p)
            b.extend(x);
        return b;
      }

      virtual LBBox3fa lbounds() const
      {
        avector<BBox3fa> bboxes(positions.size());
        for (size_t t=0; t<positions.size(); t++) {
          BBox3fa b = empty;
          for (auto& x : positions[t]) b.extend(x);
          bboxes[t] = b;
        }
        return LBBox3fa(bboxes);
      }

      virtual size_t numPrimitives() const {
        return triangles.size();
      }

      size_t numVertices() const {
        assert(positions.size());
        return positions[0].size();
      }

      size_t numTimeSteps() const {
        return positions.size();
      }

      size_t numBytes() const {
        return numPrimitives()*sizeof(Triangle) + numVertices()*numTimeSteps()*sizeof(Vertex);
      }

      void verify() const;

      virtual void print(std::ostream& cout, int depth);
      virtual void calculateStatistics(Statistics& stat);
      virtual void calculateInDegree();
      virtual void resetInDegree();
      
    public:
      BBox1f time_range;
      std::vector<avector<Vertex>> positions;
      std::vector<avector<Vertex>> normals;
      std::vector<Vec2f> texcoords;
      std::vector<Triangle> triangles;
      Ref<MaterialNode> material;
    };

    /*! Mesh. */
    struct QuadMeshNode : public Node
    {
      typedef Vec3fa Vertex;

      struct Quad
      {
      public:
        Quad() {}
        Quad (unsigned int v0, unsigned int v1, unsigned int v2, unsigned int v3) 
        : v0(v0), v1(v1), v2(v2), v3(v3) {}
      public:
        unsigned int v0, v1, v2, v3;
      };
      
    public:
      QuadMeshNode (Ref<MaterialNode> material, const BBox1f time_range = BBox1f(0,1), size_t numTimeSteps = 0 ) 
        : Node(true), time_range(time_range), material(material) 
      {
        for (size_t i=0; i<numTimeSteps; i++)
          positions.push_back(avector<Vertex>());
      }

      QuadMeshNode (Ref<SceneGraph::QuadMeshNode> imesh, const Transformations& spaces)
        : Node(true),
          time_range(imesh->time_range),
          positions(transformMSMBlurVec3faBuffer(imesh->positions,spaces)),
          normals(transformMSMBlurNormalBuffer(imesh->normals,spaces)),
          texcoords(imesh->texcoords), quads(imesh->quads), material(imesh->material) {}
   
      virtual void setMaterial(Ref<MaterialNode> material) {
        this->material = material;
      }

      virtual BBox3fa bounds() const
      {
        BBox3fa b = empty;
        for (const auto& p : positions)
          for (auto& x : p)
            b.extend(x);
        return b;
      }

      virtual LBBox3fa lbounds() const
      {
        avector<BBox3fa> bboxes(positions.size());
        for (size_t t=0; t<positions.size(); t++) {
          BBox3fa b = empty;
          for (auto& x : positions[t]) b.extend(x);
          bboxes[t] = b;
        }
        return LBBox3fa(bboxes);
      }
      
      virtual size_t numPrimitives() const {
        return quads.size();
      }

      size_t numVertices() const {
        assert(positions.size());
        return positions[0].size();
      }

      size_t numTimeSteps() const {
        return positions.size();
      }

      size_t numBytes() const {
        return numPrimitives()*sizeof(Quad) + numVertices()*numTimeSteps()*sizeof(Vertex);
      }
      
      void verify() const;

      virtual void print(std::ostream& cout, int depth);
      virtual void calculateStatistics(Statistics& stat);
      virtual void calculateInDegree();
      virtual void resetInDegree();
            
    public:
      BBox1f time_range;
      std::vector<avector<Vertex>> positions;
      std::vector<avector<Vertex>> normals;
      std::vector<Vec2f> texcoords;
      std::vector<Quad> quads;
      Ref<MaterialNode> material;
    };

    /*! Subdivision Mesh. */
    struct SubdivMeshNode : public Node
    {
      typedef Vec3fa Vertex;

      SubdivMeshNode (Ref<MaterialNode> material, const BBox1f time_range = BBox1f(0,1), size_t numTimeSteps = 0) 
        : Node(true),
          time_range(time_range),
          position_subdiv_mode(RTC_SUBDIVISION_MODE_SMOOTH_BOUNDARY), 
          normal_subdiv_mode(RTC_SUBDIVISION_MODE_SMOOTH_BOUNDARY),
          texcoord_subdiv_mode(RTC_SUBDIVISION_MODE_SMOOTH_BOUNDARY),
          material(material), tessellationRate(2.0f) 
      {
        for (size_t i=0; i<numTimeSteps; i++)
          positions.push_back(avector<Vertex>());
        zero_pad_arrays();
      }

      SubdivMeshNode (Ref<SceneGraph::SubdivMeshNode> imesh, const Transformations& spaces)
        : Node(true),
        time_range(imesh->time_range),
        positions(transformMSMBlurVec3faBuffer(imesh->positions,spaces)),
        normals(transformMSMBlurNormalBuffer(imesh->normals,spaces)),
        texcoords(imesh->texcoords),
        position_indices(imesh->position_indices),
        normal_indices(imesh->normal_indices),
        texcoord_indices(imesh->texcoord_indices),
        position_subdiv_mode(imesh->position_subdiv_mode), 
        normal_subdiv_mode(imesh->normal_subdiv_mode),
        texcoord_subdiv_mode(imesh->texcoord_subdiv_mode),
        verticesPerFace(imesh->verticesPerFace),
        holes(imesh->holes),
        edge_creases(imesh->edge_creases),
        edge_crease_weights(imesh->edge_crease_weights),
        vertex_creases(imesh->vertex_creases),
        vertex_crease_weights(imesh->vertex_crease_weights),
        material(imesh->material), 
        tessellationRate(imesh->tessellationRate)
      {
        zero_pad_arrays();
      }

      void zero_pad_arrays()
      {
        if (texcoords.size()) { // zero pad to 16 bytes
          texcoords.reserve(texcoords.size()+1);
          texcoords.data()[texcoords.size()] = zero;
        }
      }
      
      virtual void setMaterial(Ref<MaterialNode> material) {
        this->material = material;
      }

      virtual BBox3fa bounds() const
      {
        BBox3fa b = empty;
        for (const auto& p : positions)
          for (auto& x : p)
            b.extend(x);
        return b;
      }

      virtual LBBox3fa lbounds() const
      {
        avector<BBox3fa> bboxes(positions.size());
        for (size_t t=0; t<positions.size(); t++) {
          BBox3fa b = empty;
          for (auto& x : positions[t]) b.extend(x);
          bboxes[t] = b;
        }
        return LBBox3fa(bboxes);
      }

      virtual size_t numPrimitives() const {
        return verticesPerFace.size();
      }

      size_t numPositions() const {
        assert(positions.size());
        return positions[0].size();
      }

      size_t numNormals() const {
        if (normals.size()) return normals[0].size();
        else return 0;
      }

      size_t numEdges() const {
        return position_indices.size();
      }

      size_t numTimeSteps() const {
        return positions.size();
      }

      size_t numBytes() const {
        return numPrimitives()*sizeof(unsigned) + numEdges()*sizeof(unsigned) + numPositions()*numTimeSteps()*sizeof(Vertex);
      }
      
      void verify() const;

      virtual void print(std::ostream& cout, int depth);
      virtual void calculateStatistics(Statistics& stat);
      virtual void calculateInDegree();
      virtual void resetInDegree();

    public:
      BBox1f time_range;                      //!< geometry time range for motion blur
      std::vector<avector<Vertex>> positions; //!< vertex positions for multiple timesteps
      std::vector<avector<Vertex>> normals;    //!< vertex normals
      std::vector<Vec2f> texcoords;             //!< face texture coordinates
      std::vector<unsigned> position_indices;        //!< position indices for all faces
      std::vector<unsigned> normal_indices;          //!< normal indices for all faces
      std::vector<unsigned> texcoord_indices;        //!< texcoord indices for all faces
      RTCSubdivisionMode position_subdiv_mode;  
      RTCSubdivisionMode normal_subdiv_mode;
      RTCSubdivisionMode texcoord_subdiv_mode;
      std::vector<unsigned> verticesPerFace;         //!< number of indices of each face
      std::vector<unsigned> holes;                   //!< face ID of holes
      std::vector<Vec2i> edge_creases;          //!< index pairs for edge crease 
      std::vector<float> edge_crease_weights;   //!< weight for each edge crease
      std::vector<unsigned> vertex_creases;          //!< indices of vertex creases
      std::vector<float> vertex_crease_weights; //!< weight for each vertex crease
      Ref<MaterialNode> material;
      float tessellationRate;
    };

    /*! Hair Set. */
    struct HairSetNode : public Node
    {
      typedef Vec3ff Vertex;

      struct Hair
      {
      public:
        Hair () {}
        Hair (unsigned vertex, unsigned id) 
        : vertex(vertex), id(id) {}
      public:
        unsigned vertex, id;  //!< index of first control point and hair ID
      };
      
    public:
      HairSetNode (RTCGeometryType type, Ref<MaterialNode> material, const BBox1f time_range = BBox1f(0,1), size_t numTimeSteps = 0)
        : Node(true), time_range(time_range), type(type), material(material), tessellation_rate(4)
      {
        for (size_t i=0; i<numTimeSteps; i++)
          positions.push_back(avector<Vertex>());
      }

      HairSetNode (const avector<Vertex>& positions_in, const std::vector<Hair>& hairs, Ref<MaterialNode> material, RTCGeometryType type)
        : Node(true), time_range(0.0f,1.0f), type(type), hairs(hairs), material(material), tessellation_rate(4)
      {
        positions.push_back(positions_in);
      }
   
      HairSetNode (Ref<SceneGraph::HairSetNode> imesh, const Transformations& spaces)
        : Node(true),
        time_range(imesh->time_range),
        type(imesh->type),
        positions(transformMSMBlurBuffer(imesh->positions,spaces)),
        normals(transformMSMBlurNormalBuffer(imesh->normals,spaces)),
        tangents(transformMSMBlurVectorBuffer(imesh->tangents,spaces)),
        dnormals(transformMSMBlurVectorVec3faBuffer(imesh->dnormals,spaces)),
        hairs(imesh->hairs), flags(imesh->flags), material(imesh->material), tessellation_rate(imesh->tessellation_rate) {}

      virtual void setMaterial(Ref<MaterialNode> material) {
        this->material = material;
      }

      virtual BBox3fa bounds() const
      {
        BBox3fa b = empty;
        for (const auto& p : positions)
          for (auto& x : p)
            b.extend(x);
        return b;
      }

      virtual LBBox3fa lbounds() const
      {
        avector<BBox3fa> bboxes(positions.size());
        for (size_t t=0; t<positions.size(); t++) {
          BBox3fa b = empty;
          for (auto& x : positions[t]) b.extend(x);
          bboxes[t] = b;
        }
        return LBBox3fa(bboxes);
      }

      virtual size_t numPrimitives() const {
        return hairs.size();
      }

      size_t numVertices() const {
        assert(positions.size());
        return positions[0].size();
      }

      size_t numTimeSteps() const {
        return positions.size();
      }

      size_t numBytes() const {
        return numPrimitives()*sizeof(Hair) + numVertices()*numTimeSteps()*sizeof(Vertex);
      }

      void convert_bezier_to_bspline();
      void convert_bspline_to_bezier();
      void convert_bezier_to_hermite();
      void compact_vertices();

      void verify() const;

      virtual void print(std::ostream& cout, int depth);
      virtual void calculateStatistics(Statistics& stat);
      virtual void calculateInDegree();
      virtual void resetInDegree();

    public:
      BBox1f time_range;                      //!< geometry time range for motion blur
      RTCGeometryType type;                   //!< type of curve
      std::vector<avector<Vertex>> positions; //!< hair control points (x,y,z,r) for multiple timesteps
      std::vector<avector<Vec3fa>> normals;   //!< hair control normals (nx,ny,nz) for multiple timesteps
      std::vector<avector<Vertex>> tangents;  //!< hair control tangents (tx,ty,tz,tr) for multiple timesteps
      std::vector<avector<Vec3fa>> dnormals;  //!< hair control normal derivatives (nx,ny,nz) for multiple timesteps
      std::vector<Hair> hairs;                //!< list of hairs
      std::vector<unsigned char> flags;       //!< left, right end cap flags

      Ref<MaterialNode> material;
      unsigned tessellation_rate;
    };

    /*! Point Set. */
    struct PointSetNode : public Node
    {
      typedef Vec3ff Vertex;

    public:
      PointSetNode (RTCGeometryType type, Ref<MaterialNode> material, const BBox1f time_range = BBox1f(0,1), size_t numTimeSteps = 0)
        : Node(true), time_range(time_range), type(type), material(material)
      {
        for (size_t i=0; i<numTimeSteps; i++)
          positions.push_back(avector<Vertex>());
      }

      PointSetNode (const avector<Vertex>& positions_in, Ref<MaterialNode> material, RTCGeometryType type)
        : Node(true), time_range(0.0f, 1.0f), type(type), material(material)
      {
        positions.push_back(positions_in);
      }

      PointSetNode (Ref<SceneGraph::PointSetNode> imesh, const Transformations& spaces)
        : Node(true), time_range(imesh->time_range), type(imesh->type), positions(transformMSMBlurBuffer(imesh->positions,spaces)),
          normals(transformMSMBlurNormalBuffer(imesh->normals,spaces)),
        material(imesh->material) {}

      virtual void setMaterial(Ref<MaterialNode> material) {
        this->material = material;
      }

      virtual BBox3fa bounds() const
      {
        BBox3fa b = empty;
        for (const auto& p : positions)
          for (auto& x : p)
            b.extend(x);
        return b;
      }

      virtual LBBox3fa lbounds() const
      {
        avector<BBox3fa> bboxes(positions.size());
        for (size_t t=0; t<positions.size(); t++) {
          BBox3fa b = empty;
          for (auto& x : positions[t])
            b.extend(x);
          bboxes[t] = b;
        }
        return LBBox3fa(bboxes);
      }

      virtual size_t numPrimitives() const {
        return numVertices();
      }

      size_t numVertices() const {
        assert(positions.size());
        return positions[0].size();
      }

      size_t numTimeSteps() const {
        return positions.size();
      }

      size_t numBytes() const {
        return numVertices()*numTimeSteps()*sizeof(Vertex);
      }

      void verify() const;

      virtual void print(std::ostream& cout, int depth);
      virtual void calculateStatistics(Statistics& stat);
      virtual void calculateInDegree();
      virtual void resetInDegree();

    public:
      BBox1f time_range;                      //!< geometry time range for motion blur
      RTCGeometryType type;                   //!< type of point
      std::vector<avector<Vertex>> positions; //!< point control points (x,y,z,r) for multiple timesteps
      std::vector<avector<Vec3fa>> normals;   //!< point control normals (nx,ny,nz) for multiple timesteps (oriented only)

      Ref<MaterialNode> material;
    };

    struct GridMeshNode : public Node
    {
      typedef Vec3fa Vertex;

      static const unsigned int GRID_RES_MAX = 0x7FFF;

      struct Grid
      {
      public:
        Grid() {}
        Grid (unsigned int startVtx, unsigned int lineStride, unsigned int resX_in, unsigned int resY_in)
         : startVtx(startVtx), lineStride(lineStride), resX(resX_in), resY(resY_in)
        {
          assert(resX_in <= GRID_RES_MAX);
          assert(resY_in <= GRID_RES_MAX);
        }
      public:
        unsigned int startVtx;
        unsigned int lineStride;
        unsigned short resX,resY;
      };
      
    public:
      GridMeshNode (Ref<MaterialNode> material, const BBox1f time_range = BBox1f(0,1), size_t numTimeSteps = 0) 
        : Node(true), time_range(time_range), material(material) 
      {
        for (size_t i=0; i<numTimeSteps; i++)
          positions.push_back(avector<Vertex>());
      }

      GridMeshNode (Ref<SceneGraph::GridMeshNode> imesh, const Transformations& spaces)
        : Node(true),
         time_range(imesh->time_range),
          positions(transformMSMBlurVec3faBuffer(imesh->positions,spaces)),
        grids(imesh->grids), material(imesh->material) {}
   
      virtual void setMaterial(Ref<MaterialNode> material) {
        this->material = material;
      }

      virtual BBox3fa bounds() const
      {
        BBox3fa b = empty;
        for (const auto& p : positions)
          for (auto& x : p)
            b.extend(x);
        return b;
      }

      virtual LBBox3fa lbounds() const
      {
        avector<BBox3fa> bboxes(positions.size());
        for (size_t t=0; t<positions.size(); t++) {
          BBox3fa b = empty;
          for (auto& x : positions[t]) b.extend(x);
          bboxes[t] = b;
        }
        return LBBox3fa(bboxes);
      }
      
      virtual size_t numPrimitives() const {
        return grids.size();
      }

      size_t numVertices() const {
        assert(positions.size());
        return positions[0].size();
      }

      size_t numTimeSteps() const {
        return positions.size();
      }

      size_t numBytes() const {
        return numPrimitives()*sizeof(Grid) + numVertices()*numTimeSteps()*sizeof(Vertex);
      }

      void verify() const;

      virtual void print(std::ostream& cout, int depth);
      virtual void calculateStatistics(Statistics& stat);
      virtual void calculateInDegree();
      virtual void resetInDegree();

    public:
      BBox1f time_range;
      std::vector<avector<Vertex>> positions; 
      std::vector<Grid> grids;
      Ref<MaterialNode> material;
    };

    
    enum InstancingMode { INSTANCING_NONE, INSTANCING_GEOMETRY, INSTANCING_GROUP, INSTANCING_FLATTENED, INSTANCING_MULTI_LEVEL };
    Ref<Node> flatten(Ref<Node> node, InstancingMode mode);
    Ref<GroupNode> flatten(Ref<GroupNode> node, InstancingMode mode);

    Statistics calculateStatistics(Ref<Node> node);

    enum CurveSubtype
    {
      ROUND_CURVE,
      FLAT_CURVE
    };

    enum PointSubtype
    {
      SPHERE,
      DISC,
      ORIENTED_DISC
    };
  }
}

#include "materials.h"