aboutsummaryrefslogtreecommitdiff
path: root/APEX_1.4/module/destructible/src/DestructibleAssetImpl.cpp
blob: f4e98624beb92f58aee6f31e57baba49d5239aef (plain) (blame)
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
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of NVIDIA CORPORATION nor the names of its
//    contributors may be used to endorse or promote products derived
//    from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2018 NVIDIA Corporation. All rights reserved.



#include "ApexDefs.h"
#include "Apex.h"
#include "DestructibleAssetImpl.h"
#include "DestructibleActorProxy.h"
#include "DestructiblePreviewProxy.h"
#include "ModuleDestructibleImpl.h"
#include "PxCooking.h"
#include "PxPhysics.h"
#include <PxScene.h>
#include "ModulePerfScope.h"
#include "ApexUsingNamespace.h"
#include "RenderMeshAssetIntl.h"
#include "Cof44.h"
#include "nvparameterized/NvParamUtils.h"
#include "PsMemoryBuffer.h"
#if APEX_USE_PARTICLES
#include "EmitterAsset.h"
#else
static const char* EMITTER_AUTHORING_TYPE_NAME = "ApexEmitterAsset";
#endif

#include "../../../framework/include/autogen/RenderMeshAssetParameters.h"
#include "../../../framework/include/ApexRenderMeshAsset.h"


#include "ApexSharedSerialization.h"
#include "ApexRand.h"

#include "ApexMerge.h"
#include "ApexFind.h"

namespace nvidia
{
namespace destructible
{
using namespace physx;

struct ChunkSortElement
{
	int32_t index;
	int32_t parentIndex;
	int32_t depth;
};

struct IndexSortedEdge
{
	IndexSortedEdge() {}
	IndexSortedEdge(uint32_t _i0, uint32_t _i1, uint32_t _submeshIndex, const PxVec3& _triangleNormal)
	{
		if (_i0 <= _i1)
		{
			i0 = _i0;
			i1 = _i1;
		}
		else
		{
			i0 = _i1;
			i1 = _i0;
		}
		submeshIndex = _submeshIndex;
		triangleNormal = _triangleNormal;
	}

	uint32_t i0;
	uint32_t i1;
	uint32_t submeshIndex;
	PxVec3 triangleNormal;
};

// We'll use this struct to store trim planes for each hull in each part
struct TrimPlane
{
	uint32_t partIndex;
	uint32_t hullIndex;
	PxPlane plane;

	struct LessThan
	{
		PX_INLINE bool operator()(const TrimPlane& x, const TrimPlane& y) const
		{
			return x.partIndex != y.partIndex ? (x.partIndex < y.partIndex) : (x.hullIndex < y.hullIndex);
		}
	};
};

#ifndef WITHOUT_APEX_AUTHORING
static int compareChunkParents(
    const void* A,
    const void* B)
{
	ChunkSortElement& eA = *(ChunkSortElement*)A;
	ChunkSortElement& eB = *(ChunkSortElement*)B;

	const int32_t depthDiff = eA.depth - eB.depth;
	if (depthDiff)
	{
		return depthDiff;
	}

	const int32_t parentDiff = eA.parentIndex - eB.parentIndex;
	if (parentDiff)
	{
		return parentDiff;
	}

	return eA.index - eB.index;	// Keeps sort stable
}
#endif

void DestructibleAssetImpl::setParameters(const DestructibleParameters& parameters)
{
	setParameters(parameters, mParams->destructibleParameters);

	NvParameterized::Handle handle(*mParams);
	mParams->getParameterHandle("depthParameters", handle);
	mParams->resizeArray(handle, (int32_t)parameters.depthParametersCount);
	for (uint32_t i = 0; i < parameters.depthParametersCount; ++i)
	{
		DestructibleAssetParametersNS::DestructibleDepthParameters_Type& d = mParams->depthParameters.buf[i];
		const DestructibleDepthParameters& dparm = parameters.depthParameters[i];
		d.OVERRIDE_IMPACT_DAMAGE		= (dparm.flags & DestructibleDepthParametersFlag::OVERRIDE_IMPACT_DAMAGE) ? true : false;
		d.OVERRIDE_IMPACT_DAMAGE_VALUE	= (dparm.flags & DestructibleDepthParametersFlag::OVERRIDE_IMPACT_DAMAGE_VALUE) ? true : false;
		d.IGNORE_POSE_UPDATES			= (dparm.flags & DestructibleDepthParametersFlag::IGNORE_POSE_UPDATES) ? true : false;
		d.IGNORE_RAYCAST_CALLBACKS		= (dparm.flags & DestructibleDepthParametersFlag::IGNORE_RAYCAST_CALLBACKS) ? true : false;
		d.IGNORE_CONTACT_CALLBACKS		= (dparm.flags & DestructibleDepthParametersFlag::IGNORE_CONTACT_CALLBACKS) ? true : false;
		d.USER_FLAG_0					= (dparm.flags & DestructibleDepthParametersFlag::USER_FLAG_0) ? true : false;
		d.USER_FLAG_1					= (dparm.flags & DestructibleDepthParametersFlag::USER_FLAG_1) ? true : false;
		d.USER_FLAG_2					= (dparm.flags & DestructibleDepthParametersFlag::USER_FLAG_2) ? true : false;
		d.USER_FLAG_3					= (dparm.flags & DestructibleDepthParametersFlag::USER_FLAG_3) ? true : false;
	}
}

void DestructibleAssetImpl::setParameters(const DestructibleParameters& parameters, DestructibleAssetParametersNS::DestructibleParameters_Type& destructibleParameters)
{
	destructibleParameters.damageCap                             = parameters.damageCap;
	destructibleParameters.debrisDepth                           = parameters.debrisDepth;
	destructibleParameters.debrisLifetimeMax                     = parameters.debrisLifetimeMax;
	destructibleParameters.debrisLifetimeMin                     = parameters.debrisLifetimeMin;
	destructibleParameters.debrisMaxSeparationMax                = parameters.debrisMaxSeparationMax;
	destructibleParameters.debrisMaxSeparationMin                = parameters.debrisMaxSeparationMin;
	destructibleParameters.debrisDestructionProbability          = parameters.debrisDestructionProbability;
	destructibleParameters.dynamicChunkDominanceGroup            = parameters.dynamicChunksDominanceGroup;
	destructibleParameters.dynamicChunksGroupsMask.useGroupsMask = parameters.useDynamicChunksGroupsMask;
	destructibleParameters.dynamicChunksGroupsMask.bits0         = parameters.dynamicChunksFilterData.word0;
	destructibleParameters.dynamicChunksGroupsMask.bits1         = parameters.dynamicChunksFilterData.word1;
	destructibleParameters.dynamicChunksGroupsMask.bits2         = parameters.dynamicChunksFilterData.word2;
	destructibleParameters.dynamicChunksGroupsMask.bits3         = parameters.dynamicChunksFilterData.word3;
	destructibleParameters.supportStrength						 = parameters.supportStrength;
	destructibleParameters.legacyChunkBoundsTestSetting			 = parameters.legacyChunkBoundsTestSetting;
	destructibleParameters.legacyDamageRadiusSpreadSetting		 = parameters.legacyDamageRadiusSpreadSetting;
    destructibleParameters.alwaysDrawScatterMesh	             = parameters.alwaysDrawScatterMesh; 

	destructibleParameters.essentialDepth = parameters.essentialDepth;
	destructibleParameters.flags.ACCUMULATE_DAMAGE       = (parameters.flags & DestructibleParametersFlag::ACCUMULATE_DAMAGE) ? true : false;
	destructibleParameters.flags.DEBRIS_TIMEOUT          = (parameters.flags & DestructibleParametersFlag::DEBRIS_TIMEOUT) ? true : false;
	destructibleParameters.flags.DEBRIS_MAX_SEPARATION   = (parameters.flags & DestructibleParametersFlag::DEBRIS_MAX_SEPARATION) ? true : false;
	destructibleParameters.flags.CRUMBLE_SMALLEST_CHUNKS = (parameters.flags & DestructibleParametersFlag::CRUMBLE_SMALLEST_CHUNKS) ? true : false;
	destructibleParameters.flags.ACCURATE_RAYCASTS       = (parameters.flags & DestructibleParametersFlag::ACCURATE_RAYCASTS) ? true : false;
	destructibleParameters.flags.USE_VALID_BOUNDS        = (parameters.flags & DestructibleParametersFlag::USE_VALID_BOUNDS) ? true : false;
	destructibleParameters.flags.CRUMBLE_VIA_RUNTIME_FRACTURE = (parameters.flags & DestructibleParametersFlag::CRUMBLE_VIA_RUNTIME_FRACTURE) ? true : false;
	destructibleParameters.forceToDamage                 = parameters.forceToDamage;
	destructibleParameters.fractureImpulseScale          = parameters.fractureImpulseScale;
	destructibleParameters.damageDepthLimit              = parameters.damageDepthLimit;
	destructibleParameters.impactVelocityThreshold       = parameters.impactVelocityThreshold;
	destructibleParameters.maxChunkSpeed                 = parameters.maxChunkSpeed;
	destructibleParameters.minimumFractureDepth          = parameters.minimumFractureDepth;
	destructibleParameters.impactDamageDefaultDepth      = parameters.impactDamageDefaultDepth;
	destructibleParameters.debrisDestructionProbability  = parameters.debrisDestructionProbability;
	destructibleParameters.validBounds                   = parameters.validBounds;

	// RT Fracture Parameters
	destructibleParameters.runtimeFracture.sheetFracture			= parameters.rtFractureParameters.sheetFracture;
	destructibleParameters.runtimeFracture.depthLimit				= parameters.rtFractureParameters.depthLimit;
	destructibleParameters.runtimeFracture.destroyIfAtDepthLimit	= parameters.rtFractureParameters.destroyIfAtDepthLimit;
	destructibleParameters.runtimeFracture.minConvexSize			= parameters.rtFractureParameters.minConvexSize;
	destructibleParameters.runtimeFracture.impulseScale				= parameters.rtFractureParameters.impulseScale;
	destructibleParameters.runtimeFracture.glass.numSectors			= parameters.rtFractureParameters.glass.numSectors;
	destructibleParameters.runtimeFracture.glass.sectorRand			= parameters.rtFractureParameters.glass.sectorRand;
	destructibleParameters.runtimeFracture.glass.firstSegmentSize	= parameters.rtFractureParameters.glass.firstSegmentSize;
	destructibleParameters.runtimeFracture.glass.segmentScale		= parameters.rtFractureParameters.glass.segmentScale;
	destructibleParameters.runtimeFracture.glass.segmentRand		= parameters.rtFractureParameters.glass.segmentRand;
	destructibleParameters.runtimeFracture.attachment.posX			= parameters.rtFractureParameters.attachment.posX;
	destructibleParameters.runtimeFracture.attachment.negX			= parameters.rtFractureParameters.attachment.negX;
	destructibleParameters.runtimeFracture.attachment.posY			= parameters.rtFractureParameters.attachment.posY;
	destructibleParameters.runtimeFracture.attachment.negY			= parameters.rtFractureParameters.attachment.negY;
	destructibleParameters.runtimeFracture.attachment.posZ			= parameters.rtFractureParameters.attachment.posZ;
	destructibleParameters.runtimeFracture.attachment.negZ			= parameters.rtFractureParameters.attachment.negZ;
}

void DestructibleAssetImpl::setInitParameters(const DestructibleInitParameters& parameters)
{
	mParams->supportDepth = parameters.supportDepth;
	mParams->formExtendedStructures      = (parameters.flags & DestructibleInitParametersFlag::FORM_EXTENDED_STRUCTURES) ? true : false;
	mParams->useAssetDefinedSupport		 = (parameters.flags & DestructibleInitParametersFlag::ASSET_DEFINED_SUPPORT) ? true : false;
	mParams->useWorldSupport			 = (parameters.flags & DestructibleInitParametersFlag::WORLD_SUPPORT) ? true : false;
}

DestructibleParameters DestructibleAssetImpl::getParameters() const
{
	return getParameters(mParams->destructibleParameters, &mParams->depthParameters);
}

DestructibleParameters DestructibleAssetImpl::getParameters(const DestructibleAssetParametersNS::DestructibleParameters_Type& destructibleParameters,
														  const DestructibleAssetParametersNS::DestructibleDepthParameters_DynamicArray1D_Type* destructibleDepthParameters)
{
	DestructibleParameters parameters;

	parameters.damageCap                  = destructibleParameters.damageCap;
	parameters.debrisDepth                = destructibleParameters.debrisDepth;
	parameters.debrisLifetimeMax          = destructibleParameters.debrisLifetimeMax;
	parameters.debrisLifetimeMin          = destructibleParameters.debrisLifetimeMin;
	parameters.debrisMaxSeparationMax     = destructibleParameters.debrisMaxSeparationMax;
	parameters.debrisMaxSeparationMin     = destructibleParameters.debrisMaxSeparationMin;
	parameters.dynamicChunksDominanceGroup   = (uint8_t)destructibleParameters.dynamicChunkDominanceGroup;
	parameters.useDynamicChunksGroupsMask = destructibleParameters.dynamicChunksGroupsMask.useGroupsMask;
	parameters.dynamicChunksFilterData.word0 = destructibleParameters.dynamicChunksGroupsMask.bits0;
	parameters.dynamicChunksFilterData.word1 = destructibleParameters.dynamicChunksGroupsMask.bits1;
	parameters.dynamicChunksFilterData.word2 = destructibleParameters.dynamicChunksGroupsMask.bits2;
	parameters.dynamicChunksFilterData.word3 = destructibleParameters.dynamicChunksGroupsMask.bits3;
	parameters.essentialDepth = destructibleParameters.essentialDepth;
	parameters.flags = 0;
	parameters.alwaysDrawScatterMesh = destructibleParameters.alwaysDrawScatterMesh;
	if (destructibleParameters.flags.ACCUMULATE_DAMAGE)
	{
		parameters.flags |= DestructibleParametersFlag::ACCUMULATE_DAMAGE;
	}
	if (destructibleParameters.flags.DEBRIS_TIMEOUT)
	{
		parameters.flags |= DestructibleParametersFlag::DEBRIS_TIMEOUT;
	}
	if (destructibleParameters.flags.DEBRIS_MAX_SEPARATION)
	{
		parameters.flags |= DestructibleParametersFlag::DEBRIS_MAX_SEPARATION;
	}
	if (destructibleParameters.flags.CRUMBLE_SMALLEST_CHUNKS)
	{
		parameters.flags |= DestructibleParametersFlag::CRUMBLE_SMALLEST_CHUNKS;
	}
	if (destructibleParameters.flags.ACCURATE_RAYCASTS)
	{
		parameters.flags |= DestructibleParametersFlag::ACCURATE_RAYCASTS;
	}
	if (destructibleParameters.flags.USE_VALID_BOUNDS)
	{
		parameters.flags |= DestructibleParametersFlag::USE_VALID_BOUNDS;
	}
	if (destructibleParameters.flags.CRUMBLE_VIA_RUNTIME_FRACTURE)
	{
		parameters.flags |= DestructibleParametersFlag::CRUMBLE_VIA_RUNTIME_FRACTURE;
	}
	parameters.forceToDamage            = destructibleParameters.forceToDamage;
	parameters.fractureImpulseScale     = destructibleParameters.fractureImpulseScale;
	parameters.damageDepthLimit         = destructibleParameters.damageDepthLimit;
	parameters.impactVelocityThreshold  = destructibleParameters.impactVelocityThreshold;
	parameters.maxChunkSpeed            = destructibleParameters.maxChunkSpeed;
	parameters.minimumFractureDepth     = destructibleParameters.minimumFractureDepth;
	parameters.impactDamageDefaultDepth = destructibleParameters.impactDamageDefaultDepth;
	parameters.debrisDestructionProbability = destructibleParameters.debrisDestructionProbability;
	parameters.validBounds              = destructibleParameters.validBounds;

	if (destructibleDepthParameters)
	{
		//NvParameterized::Handle handle(*mParams);
		//mParams->getParameterHandle("depthParameters", handle);
		parameters.depthParametersCount = PxMin((uint32_t)DestructibleParameters::kDepthParametersCountMax,
														(uint32_t)destructibleDepthParameters->arraySizes[0]);
	for (int i = 0; i < (int)parameters.depthParametersCount; ++i)
	{
			DestructibleAssetParametersNS::DestructibleDepthParameters_Type& d = destructibleDepthParameters->buf[i];
		DestructibleDepthParameters& dparm = parameters.depthParameters[i];
		dparm.flags = 0;
		if (d.OVERRIDE_IMPACT_DAMAGE)
		{
			dparm.flags |= DestructibleDepthParametersFlag::OVERRIDE_IMPACT_DAMAGE;
		}
		if (d.OVERRIDE_IMPACT_DAMAGE_VALUE)
		{
			dparm.flags |= DestructibleDepthParametersFlag::OVERRIDE_IMPACT_DAMAGE_VALUE;
		}
		if (d.IGNORE_POSE_UPDATES)
		{
			dparm.flags |= DestructibleDepthParametersFlag::IGNORE_POSE_UPDATES;
		}
		if (d.IGNORE_RAYCAST_CALLBACKS)
		{
			dparm.flags |= DestructibleDepthParametersFlag::IGNORE_RAYCAST_CALLBACKS;
		}
		if (d.IGNORE_CONTACT_CALLBACKS)
		{
			dparm.flags |= DestructibleDepthParametersFlag::IGNORE_CONTACT_CALLBACKS;
		}
		if (d.USER_FLAG_0)
		{
			dparm.flags |= DestructibleDepthParametersFlag::USER_FLAG_0;
		}
		if (d.USER_FLAG_1)
		{
			dparm.flags |= DestructibleDepthParametersFlag::USER_FLAG_1;
		}
		if (d.USER_FLAG_2)
		{
			dparm.flags |= DestructibleDepthParametersFlag::USER_FLAG_2;
		}
		if (d.USER_FLAG_3)
		{
			dparm.flags |= DestructibleDepthParametersFlag::USER_FLAG_3;
		}
	}
	}

	// RT Fracture Parameters
	parameters.rtFractureParameters.sheetFracture			= destructibleParameters.runtimeFracture.sheetFracture;
	parameters.rtFractureParameters.depthLimit				= destructibleParameters.runtimeFracture.depthLimit;
	parameters.rtFractureParameters.destroyIfAtDepthLimit	= destructibleParameters.runtimeFracture.destroyIfAtDepthLimit;
	parameters.rtFractureParameters.minConvexSize			= destructibleParameters.runtimeFracture.minConvexSize;
	parameters.rtFractureParameters.impulseScale			= destructibleParameters.runtimeFracture.impulseScale;
	parameters.rtFractureParameters.glass.numSectors		= destructibleParameters.runtimeFracture.glass.numSectors;
	parameters.rtFractureParameters.glass.sectorRand		= destructibleParameters.runtimeFracture.glass.sectorRand;
	parameters.rtFractureParameters.glass.firstSegmentSize	= destructibleParameters.runtimeFracture.glass.firstSegmentSize;
	parameters.rtFractureParameters.glass.segmentScale		= destructibleParameters.runtimeFracture.glass.segmentScale;
	parameters.rtFractureParameters.glass.segmentRand		= destructibleParameters.runtimeFracture.glass.segmentRand;
	parameters.rtFractureParameters.attachment.posX			= destructibleParameters.runtimeFracture.attachment.posX;
	parameters.rtFractureParameters.attachment.negX			= destructibleParameters.runtimeFracture.attachment.negX;
	parameters.rtFractureParameters.attachment.posY			= destructibleParameters.runtimeFracture.attachment.posY;
	parameters.rtFractureParameters.attachment.negY			= destructibleParameters.runtimeFracture.attachment.negY;
	parameters.rtFractureParameters.attachment.posZ			= destructibleParameters.runtimeFracture.attachment.posZ;
	parameters.rtFractureParameters.attachment.negZ			= destructibleParameters.runtimeFracture.attachment.negZ;
	parameters.supportStrength								= destructibleParameters.supportStrength;
	parameters.legacyChunkBoundsTestSetting					 = destructibleParameters.legacyChunkBoundsTestSetting;
	parameters.legacyDamageRadiusSpreadSetting				 = destructibleParameters.legacyDamageRadiusSpreadSetting;

	return parameters;
}

DestructibleInitParameters DestructibleAssetImpl::getInitParameters() const
{
	DestructibleInitParameters parameters;

	parameters.supportDepth = mParams->supportDepth;
	parameters.flags = 0;
	if (mParams->formExtendedStructures)
	{
		parameters.flags |= DestructibleInitParametersFlag::FORM_EXTENDED_STRUCTURES;
	}
	if (mParams->useAssetDefinedSupport)
	{
		parameters.flags |= DestructibleInitParametersFlag::ASSET_DEFINED_SUPPORT;
	}
	if (mParams->useWorldSupport)
	{
		parameters.flags |= DestructibleInitParametersFlag::WORLD_SUPPORT;
	}

	return parameters;
}

void DestructibleAssetImpl::setCrumbleEmitterName(const char* name)
{
	NvParameterized::Handle handle(*mParams);
	mParams->getParameterHandle("crumbleEmitterName", handle);
	mParams->setParamString(handle, name ? name : "");
}

const char* DestructibleAssetImpl::getCrumbleEmitterName() const
{
	const char* name = mParams->crumbleEmitterName;
	return (name && *name) ? name : NULL;
}

void DestructibleAssetImpl::setDustEmitterName(const char* name)
{
	NvParameterized::Handle handle(*mParams);
	mParams->getParameterHandle("dustEmitterName", handle);
	mParams->setParamString(handle, name ? name : "");
}

const char* DestructibleAssetImpl::getDustEmitterName() const
{
	const char* name = mParams->dustEmitterName;
	return (name && *name) ? name : NULL;
}

void DestructibleAssetImpl::setFracturePatternName(const char* name)
{
	NvParameterized::Handle handle(*mParams);
	mParams->getParameterHandle("fracturePatternName", handle);
	mParams->setParamString(handle, name ? name : "");
}

const char* DestructibleAssetImpl::getFracturePatternName() const
{
	// TODO: Add to asset params
	const char* name = "";//mParams->fracturePatternName;
	return (name && *name) ? name : NULL;
}

void DestructibleAssetImpl::setChunkOverlapsCacheDepth(int32_t depth)
{
	chunkOverlapCacheDepth = depth;
}

void DestructibleAssetImpl::calculateChunkDepthStarts()
{
	const uint32_t chunkCount = (uint32_t)mParams->chunks.arraySizes[0];

	NvParameterized::Handle handle(*mParams);
	mParams->getParameterHandle("firstChunkAtDepth", handle);
	mParams->resizeArray(handle, (int32_t)mParams->depthCount + 1);
	mParams->firstChunkAtDepth.buf[mParams->depthCount] = chunkCount;

	uint32_t stopIndex = 0;
	for (uint32_t depth = 0; depth < mParams->depthCount; ++depth)
	{
		mParams->firstChunkAtDepth.buf[depth] = stopIndex;
		while (stopIndex < chunkCount)
		{
			if (mParams->chunks.buf[stopIndex].depth != depth)
			{
				break;
			}
			++stopIndex;
		}
	}
}

CachedOverlapsNS::IntPair_DynamicArray1D_Type* DestructibleAssetImpl::getOverlapsAtDepth(uint32_t depth, bool create) const
{
	if (depth >= mParams->depthCount)
	{
		return NULL;
	}

	int size = mParams->overlapsAtDepth.arraySizes[0];
	if (size <= (int)depth && !create)
	{
		return NULL;
	}

	NvParameterized::Handle handle(*mParams);
	mParams->getParameterHandle("overlapsAtDepth", handle);

	if (create)
	{
		mParams->resizeArray(handle, (int32_t)mParams->depthCount);
		NvParameterized::Traits* traits = GetInternalApexSDK()->getParameterizedTraits();
		while (size < (int)mParams->depthCount)
		{
			CachedOverlaps* cachedOverlaps = DYNAMIC_CAST(CachedOverlaps*)(traits->createNvParameterized(CachedOverlaps::staticClassName()));
			mParams->overlapsAtDepth.buf[size++] = cachedOverlaps;
			cachedOverlaps->isCached = false;
		}
	}

	CachedOverlaps* cachedOverlapsAtDepth = DYNAMIC_CAST(CachedOverlaps*)(mParams->overlapsAtDepth.buf[depth]);
	if (!cachedOverlapsAtDepth->isCached)
	{
		if (!create)
		{
			return NULL;
		}
		physx::Array<IntPair> overlaps;
		calculateChunkOverlaps(overlaps, depth);
		NvParameterized::Handle overlapsHandle(*cachedOverlapsAtDepth);
		cachedOverlapsAtDepth->getParameterHandle("overlaps", overlapsHandle);
		overlapsHandle.resizeArray(2*(int32_t)overlaps.size());
		for (uint32_t i = 0; i < overlaps.size(); ++i)
		{
			IntPair& pair = overlaps[i];
			
			CachedOverlapsNS::IntPair_Type& ppair = cachedOverlapsAtDepth->overlaps.buf[2*i];
			ppair.i0 = pair.i0;
			ppair.i1 = pair.i1;

			CachedOverlapsNS::IntPair_Type& ppairSymmetric = cachedOverlapsAtDepth->overlaps.buf[2*i+1];
			ppairSymmetric.i0 = pair.i1;
			ppairSymmetric.i1 = pair.i0;
		}
		qsort(cachedOverlapsAtDepth->overlaps.buf, (uint32_t)cachedOverlapsAtDepth->overlaps.arraySizes[0], sizeof(IntPair), IntPair::compare);

		cachedOverlapsAtDepth->isCached = 1;
	}

	return &cachedOverlapsAtDepth->overlaps;
}

void DestructibleAssetImpl::calculateChunkOverlaps(physx::Array<IntPair>& overlaps, uint32_t depth) const
{
	const float padding = mParams->neighborPadding * (mParams->bounds.maximum - mParams->bounds.minimum).magnitude();

	const PxTransform identityTM(PxIdentity);
	const PxVec3 identityScale(1.0f);

	const uint32_t startIndex = mParams->firstChunkAtDepth.buf[depth];
	const uint32_t stopIndex = mParams->firstChunkAtDepth.buf[depth + 1];
	const uint32_t chunksAtDepth = stopIndex - startIndex;

	// Find AABB overlaps
	physx::Array<BoundsRep> chunkBoundsReps;
	chunkBoundsReps.reserve(chunksAtDepth);
	for (uint32_t chunkIndex = startIndex; chunkIndex < stopIndex; ++chunkIndex)
	{
		BoundsRep& chunkBoundsRep = chunkBoundsReps.insert();
		chunkBoundsRep.aabb = getChunkActorLocalBounds(chunkIndex);
		PX_ASSERT(!chunkBoundsRep.aabb.isEmpty());
		chunkBoundsRep.aabb.fattenFast(padding);
	}
	if (chunkBoundsReps.size() > 0)
	{
		boundsCalculateOverlaps(overlaps, Bounds3XYZ, &chunkBoundsReps[0], chunkBoundsReps.size(), sizeof(chunkBoundsReps[0]));
	}

	// Now do detailed overlap test
	uint32_t overlapCount = 0;
	for (uint32_t overlapIndex = 0; overlapIndex < overlaps.size(); ++overlapIndex)
	{
		IntPair& AABBOverlap = overlaps[overlapIndex];
		AABBOverlap.i0 += startIndex;
		AABBOverlap.i1 += startIndex;
		if (chunksInProximity(*this, (uint16_t)AABBOverlap.i0, identityTM, identityScale, *this, (uint16_t)AABBOverlap.i1, identityTM, identityScale, 2 * padding))
		{
			overlaps[overlapCount++] = AABBOverlap;
		}
	}

	overlaps.resize(overlapCount);
}

void DestructibleAssetImpl::cacheChunkOverlapsUpToDepth(int32_t depth)
{
	if (mParams->depthCount < 1)
	{
		return;
	}

	if (depth < 0)
	{
		depth = (int32_t)mParams->supportDepth;
	}

	depth = PxMin(depth, (int32_t)mParams->depthCount - 1);

	for (uint32_t d = 0; d <= (uint32_t)depth; ++d)
	{
		getOverlapsAtDepth(d);
	}

	for (uint32_t d = (uint32_t)depth + 1; d < (uint32_t)mParams->overlapsAtDepth.arraySizes[0]; ++d)
	{
		CachedOverlaps* cachedOverlaps = DYNAMIC_CAST(CachedOverlaps*)(mParams->overlapsAtDepth.buf[d]);
		NvParameterized::Handle handle(*cachedOverlaps);
		cachedOverlaps->getParameterHandle("overlaps", handle);
		cachedOverlaps->resizeArray(handle, 0);
	}
}


void DestructibleAssetImpl::clearChunkOverlaps(int32_t depth, bool keepCachedFlag)
{
	int32_t depthStart = (depth < 0) ? 0 : depth;
	int32_t depthEnd = (depth < 0) ? mParams->overlapsAtDepth.arraySizes[0] : PxMin(depth+1, mParams->overlapsAtDepth.arraySizes[0]);
	for (int32_t d = depthStart; d < depthEnd; ++d)
	{
		CachedOverlaps* cachedOverlaps = DYNAMIC_CAST(CachedOverlaps*)(mParams->overlapsAtDepth.buf[d]);
		NvParameterized::Handle handle(*cachedOverlaps);
		cachedOverlaps->getParameterHandle("overlaps", handle);
		cachedOverlaps->resizeArray(handle, 0);
		if (!keepCachedFlag)
		{
			cachedOverlaps->isCached = false;
		}
	}
}


void DestructibleAssetImpl::addChunkOverlaps(IntPair* supportGraphEdges, uint32_t supportGraphEdgeCount)
{
	if (supportGraphEdgeCount == 0)
		return;

	uint32_t numChunks = (uint32_t)mParams->chunks.arraySizes[0];

	Array< Array<IntPair> > overlapsAtDepth(mParams->depthCount);

	// store symmetric pairs at corresponding depth
	for (uint32_t i = 0; i < supportGraphEdgeCount; ++i)
	{
		uint32_t chunkIndex0 = (uint32_t)supportGraphEdges[i].i0;
		uint32_t chunkIndex1 = (uint32_t)supportGraphEdges[i].i1;

		if (chunkIndex0 >= numChunks || chunkIndex1 >= numChunks)
		{
			APEX_DEBUG_WARNING("Edge %i supportGraphEdges has indices (%i,%i), but only a total of %i chunks are provided. supportEdges will be ignored.", i, chunkIndex0, chunkIndex1, numChunks);
			overlapsAtDepth.clear();
			break;
		}

		const DestructibleAssetParametersNS::Chunk_Type& chunk0 = mParams->chunks.buf[chunkIndex0];
		const DestructibleAssetParametersNS::Chunk_Type& chunk1 = mParams->chunks.buf[chunkIndex1];

		if (chunk0.depth != chunk1.depth)
		{
			APEX_DEBUG_WARNING("Support graph can only have edges between sibling chunks. supportEdges will be ignored.");
			overlapsAtDepth.clear();
			break;
		}

		PX_ASSERT(chunk0.depth < mParams->depthCount);

		IntPair pair;
		pair.i0 = (int32_t)chunkIndex0;
		pair.i1 = (int32_t)chunkIndex1;
		overlapsAtDepth[chunk0.depth].pushBack(pair);

		pair.i0 = (int32_t)chunkIndex1;
		pair.i1 = (int32_t)chunkIndex0;
		overlapsAtDepth[chunk0.depth].pushBack(pair);
	}

	if (overlapsAtDepth.size() == 0)
		return;


	// for each depth
	for (uint32_t depth = 0; depth < overlapsAtDepth.size(); ++depth)
	{
		if (overlapsAtDepth[depth].size() > 0)
		{
			// sort overlaps pairs
			qsort(&overlapsAtDepth[depth][0], overlapsAtDepth[depth].size(), sizeof(IntPair), IntPair::compare);
		}

		if (overlapsAtDepth[depth].size() == 0)
			continue;

		// resize parameterized array
		uint32_t numCachedDepths = (uint32_t)mParams->overlapsAtDepth.arraySizes[0];
		if (depth >= numCachedDepths)
		{
			NvParameterized::Handle handle(*mParams);
			mParams->getParameterHandle("overlapsAtDepth", handle);
			mParams->resizeArray(handle, (int32_t)depth+1);

			NvParameterized::Traits* traits = GetInternalApexSDK()->getParameterizedTraits();
			for (uint32_t d = numCachedDepths; d < depth+1; ++d)
			{
				CachedOverlaps* cachedOverlaps = DYNAMIC_CAST(CachedOverlaps*)(traits->createNvParameterized(CachedOverlaps::staticClassName()));
				mParams->overlapsAtDepth.buf[d] = cachedOverlaps;
				cachedOverlaps->isCached = false;
			}
		}

		CachedOverlaps* cachedOverlapsAtDepth = DYNAMIC_CAST(CachedOverlaps*)(mParams->overlapsAtDepth.buf[depth]);
		NvParameterized::Handle overlapsHandle(*cachedOverlapsAtDepth);
		cachedOverlapsAtDepth->getParameterHandle("overlaps", overlapsHandle);
		int32_t oldSize = cachedOverlapsAtDepth->overlaps.arraySizes[0];
		overlapsHandle.resizeArray(cachedOverlapsAtDepth->overlaps.arraySizes[0] + (int32_t)overlapsAtDepth[depth].size());

		// merge new pairs into existing graph
		bool ok = ApexMerge<IntPair>(	(IntPair*)cachedOverlapsAtDepth->overlaps.buf, (uint32_t)oldSize,
										&overlapsAtDepth[depth][0], overlapsAtDepth[depth].size(),
										(IntPair*)cachedOverlapsAtDepth->overlaps.buf, (uint32_t)cachedOverlapsAtDepth->overlaps.arraySizes[0],
										IntPair::compare);

		PX_UNUSED(ok);
		PX_ASSERT(ok);

		// check for duplicates
		if (cachedOverlapsAtDepth->overlaps.arraySizes[0] > 1)
		{
			Array<uint32_t> toRemove;
			for (uint32_t j = 1; j < (uint32_t)cachedOverlapsAtDepth->overlaps.arraySizes[0]; ++j)
			{
				if (cachedOverlapsAtDepth->overlaps.buf[j].i1 == cachedOverlapsAtDepth->overlaps.buf[j-1].i1 &&
					cachedOverlapsAtDepth->overlaps.buf[j].i0 == cachedOverlapsAtDepth->overlaps.buf[j-1].i0)
				{
					toRemove.pushBack(j);
				}
			}

			// remove duplicates
			toRemove.pushBack((uint32_t)cachedOverlapsAtDepth->overlaps.arraySizes[0]); // add guard
			uint32_t shift = 0;
			for (uint32_t j = 0; j < toRemove.size()-1; ++j)
			{
				++shift;
				for (uint32_t index = toRemove[j]+1; index < toRemove[j+1]; ++index)
				{
					cachedOverlapsAtDepth->overlaps.buf[index - shift] = cachedOverlapsAtDepth->overlaps.buf[index];
				}
			}
			NvParameterized::Handle overlapsHandle(*cachedOverlapsAtDepth);
			cachedOverlapsAtDepth->getParameterHandle("overlaps", overlapsHandle);
			overlapsHandle.resizeArray(cachedOverlapsAtDepth->overlaps.arraySizes[0] - (int32_t)shift);
		}

		cachedOverlapsAtDepth->isCached = cachedOverlapsAtDepth->overlaps.arraySizes[0] > 0;
	}
}


void DestructibleAssetImpl::removeChunkOverlaps(IntPair* supportGraphEdges, uint32_t numSupportGraphEdges, bool keepCachedFlagIfEmpty)
{
	Array< Array<uint32_t> > toRemoveAtDepth(mParams->depthCount);
	for (uint32_t i = 0; i < numSupportGraphEdges; ++i)
	{
		CachedOverlapsNS::IntPair_Type& pair = (CachedOverlapsNS::IntPair_Type&)supportGraphEdges[i];
		
		if (pair.i0 >= mParams->chunks.arraySizes[0] || pair.i1 >= mParams->chunks.arraySizes[0])
			continue;

		const DestructibleAssetParametersNS::Chunk_Type& chunk0 = mParams->chunks.buf[pair.i0];
		const DestructibleAssetParametersNS::Chunk_Type& chunk1 = mParams->chunks.buf[pair.i1];

		if (chunk0.depth != chunk1.depth)
			continue;

		if (chunk0.depth >= mParams->overlapsAtDepth.arraySizes[0])
			continue;

		if (chunk0.depth >= mParams->depthCount)
			continue;

		CachedOverlaps* cachedOverlapsAtDepth = DYNAMIC_CAST(CachedOverlaps*)(mParams->overlapsAtDepth.buf[chunk0.depth]);

		// binary search for pair and add add to index to removal list
		int32_t index = ApexFind(cachedOverlapsAtDepth->overlaps.buf, (uint32_t)cachedOverlapsAtDepth->overlaps.arraySizes[0], pair, IntPair::compare);
		if (index != -1)
		{
			toRemoveAtDepth[chunk0.depth].pushBack((uint32_t)index);
		}

		CachedOverlapsNS::IntPair_Type symmetricPair;
		symmetricPair.i0 = pair.i1;
		symmetricPair.i1 = pair.i0;
		index = ApexFind(cachedOverlapsAtDepth->overlaps.buf, (uint32_t)cachedOverlapsAtDepth->overlaps.arraySizes[0], symmetricPair, IntPair::compare);
		if (index != -1)
		{
			toRemoveAtDepth[chunk0.depth].pushBack((uint32_t)index);
		}
	}

	// go through removal list of each depth and shift remaining entries to overwrite the removed ones
	for (uint32_t depth = 0; depth < toRemoveAtDepth.size(); ++depth)
	{
		CachedOverlaps* cachedOverlapsAtDepth = DYNAMIC_CAST(CachedOverlaps*)(mParams->overlapsAtDepth.buf[depth]);
		toRemoveAtDepth[depth].pushBack((uint32_t)cachedOverlapsAtDepth->overlaps.arraySizes[0]); // add guard
		uint32_t shift = 0;
		for (uint32_t j = 1; j < toRemoveAtDepth[depth].size(); ++j)
		{
			++shift;
			for (uint32_t index = toRemoveAtDepth[depth][j-1]+1; index < toRemoveAtDepth[depth][j]; ++index)
			{
				cachedOverlapsAtDepth->overlaps.buf[index - shift] = cachedOverlapsAtDepth->overlaps.buf[index];
			}
		}

		NvParameterized::Handle overlapsHandle(*cachedOverlapsAtDepth);
		cachedOverlapsAtDepth->getParameterHandle("overlaps", overlapsHandle);
		overlapsHandle.resizeArray(cachedOverlapsAtDepth->overlaps.arraySizes[0] - (int32_t)shift);

		if (!keepCachedFlagIfEmpty)
		{
			cachedOverlapsAtDepth->isCached = cachedOverlapsAtDepth->overlaps.arraySizes[0] > 0;
		}
	}
}


DestructibleAssetImpl::DestructibleAssetImpl(ModuleDestructibleImpl* inModule, DestructibleAsset* api, const char* name) :
	mCrumbleAssetTracker(inModule->mSdk, EMITTER_AUTHORING_TYPE_NAME),
	mDustAssetTracker(inModule->mSdk, EMITTER_AUTHORING_TYPE_NAME),
	m_instancedChunkMeshCount(0)
{
	mApexDestructibleActorParams = 0;
	init();

	module = inModule;
	mNxAssetApi  = api;
	mName = name;

	NvParameterized::Traits* traits = GetInternalApexSDK()->getParameterizedTraits();
	mParams = DYNAMIC_CAST(DestructibleAssetParameters*)(traits->createNvParameterized(DestructibleAssetParameters::staticClassName()));
	mOwnsParams = mParams != NULL;
	PX_ASSERT(mOwnsParams);
}

DestructibleAssetImpl::DestructibleAssetImpl(ModuleDestructibleImpl* inModule, DestructibleAsset* api, NvParameterized::Interface* params, const char* name) 
	: mCrumbleAssetTracker(inModule->mSdk, EMITTER_AUTHORING_TYPE_NAME)
	, mDustAssetTracker(inModule->mSdk, EMITTER_AUTHORING_TYPE_NAME)
	, mRuntimeCookedConvexCount(0)
	, m_instancedChunkMeshCount(0)
{
	mApexDestructibleActorParams = 0;
	init();

	module = inModule;
	mNxAssetApi  = api;
	mName = name;

	mParams = DYNAMIC_CAST(DestructibleAssetParameters*)(params);

	// The pattern for NvParameterized assets is that the params pointer now belongs to the asset
	mOwnsParams = true;

	// there's no deserialize, so init the ARMs
	if (mParams->renderMeshAsset)
	{
		ApexSimpleString meshName = mName + ApexSimpleString("RenderMesh");
		module->mSdk->getInternalResourceProvider()->generateUniqueName(module->mSdk->getApexMeshNameSpace(), meshName);

		setRenderMeshAsset(static_cast<RenderMeshAsset*>(module->mSdk->createAsset(mParams->renderMeshAsset,  meshName.c_str())));
	}

	// scatter meshes
	bool scatterMeshAssetsValid = true;
	physx::Array<RenderMeshAsset*> scatterMeshAssetArray((uint32_t)mParams->scatterMeshAssets.arraySizes[0]);
	for (uint32_t i = 0; i < (uint32_t)mParams->scatterMeshAssets.arraySizes[0]; ++i)
	{
		if (i > 65535 || mParams->scatterMeshAssets.buf[i] == NULL)
		{
			scatterMeshAssetsValid = false;
			break;
		}
		char suffix[20];
		sprintf(suffix, "ScatterMesh%d", i);
		ApexSimpleString meshName = mName + ApexSimpleString(suffix);
		module->mSdk->getInternalResourceProvider()->generateUniqueName(module->mSdk->getApexMeshNameSpace(), meshName);
		scatterMeshAssetArray[i] = static_cast<RenderMeshAsset*>(module->mSdk->createAsset(mParams->scatterMeshAssets.buf[i], meshName.c_str()));
	}

	bool success = false;
	if (scatterMeshAssetsValid && mParams->scatterMeshAssets.arraySizes[0] > 0)
	{
		success = setScatterMeshAssets(&scatterMeshAssetArray[0], (uint32_t)mParams->scatterMeshAssets.arraySizes[0]);
	}
	if (!success)
	{
		for (uint32_t i = 0; i < scatterMeshAssetArray.size(); ++i)
		{
			if (scatterMeshAssetArray[i] != NULL)
			{
				scatterMeshAssetArray[i]->release();
			}
		}
	}

	bool hullWarningGiven = false;

	// Connect contained classes to referenced parameters
	chunkConvexHulls.resize((uint32_t)mParams->chunkConvexHulls.arraySizes[0]);
	for (uint32_t i = 0; i < chunkConvexHulls.size(); ++i)
	{
		chunkConvexHulls[i].init(mParams->chunkConvexHulls.buf[i]);

		// Fix convex hulls to account for adjacentFaces bug
		if (chunkConvexHulls[i].mParams->adjacentFaces.arraySizes[0] != chunkConvexHulls[i].mParams->edges.arraySizes[0])
		{
			chunkConvexHulls[i].buildFromPoints(chunkConvexHulls[i].mParams->vertices.buf, (uint32_t)chunkConvexHulls[i].mParams->vertices.arraySizes[0], 
				(uint32_t)chunkConvexHulls[i].mParams->vertices.elementSize);
			if (!hullWarningGiven)
			{
				GetInternalApexSDK()->reportError(PxErrorCode::eDEBUG_WARNING, __FILE__, __LINE__, __FUNCTION__,
					"Chunk convex hull data bad in asset %s, rebuilding.  Asset should be re-exported.", name);
				hullWarningGiven = true;
			}
		}
	}

	m_currentInstanceBufferActorAllowance = mParams->initialDestructibleActorAllowanceForInstancing;

	physx::Array<uint16_t> tempPartToActorMap;
	tempPartToActorMap.resize(renderMeshAsset->getPartCount(), 0xFFFF);

	m_instancedChunkMeshCount = 0;

	m_instancedChunkActorMap.resize((uint32_t)mParams->chunkInstanceInfo.arraySizes[0]);
	for (uint32_t i = 0; i < (uint32_t)mParams->chunkInstanceInfo.arraySizes[0]; ++i)
	{
		uint16_t partIndex = mParams->chunkInstanceInfo.buf[i].partIndex;
		if (tempPartToActorMap[partIndex] == 0xFFFF)
		{
			tempPartToActorMap[partIndex] = m_instancedChunkMeshCount++;
		}
		m_instancedChunkActorMap[i] = tempPartToActorMap[partIndex];
	}

	m_instancedChunkActorVisiblePart.resize(m_instancedChunkMeshCount);
	for (uint32_t i = 0; i < (uint32_t)mParams->chunks.arraySizes[0]; ++i)
	{
		DestructibleAssetParametersNS::Chunk_Type& chunk = mParams->chunks.buf[i];
		if ((chunk.flags & DestructibleAssetImpl::Instanced) != 0)
		{
			uint16_t partIndex = mParams->chunkInstanceInfo.buf[chunk.meshPartIndex].partIndex;
			m_instancedChunkActorVisiblePart[m_instancedChunkActorMap[chunk.meshPartIndex]] = partIndex;
		}
	}

	m_instancingRepresentativeActorIndex = -1;	// not set

	reduceAccordingToLOD();

	initializeAssetNameTable();

	mStaticMaterialIDs.resize((uint32_t)mParams->staticMaterialNames.arraySizes[0]);
	ResourceProviderIntl* resourceProvider = GetInternalApexSDK()->getInternalResourceProvider();
	ResID materialNS = GetInternalApexSDK()->getMaterialNameSpace();
	// Resolve material names using the NRP...
	for (uint32_t i = 0; i < (uint32_t)mParams->staticMaterialNames.arraySizes[0]; ++i)
	{
		if (resourceProvider)
		{
			mStaticMaterialIDs[i] = resourceProvider->createResource(materialNS, mParams->staticMaterialNames.buf[i]);
		}
		else
		{
			mStaticMaterialIDs[i] = INVALID_RESOURCE_ID;
		}
	}
}

DestructibleAssetImpl::~DestructibleAssetImpl()
{
	// Release named resources
	ResourceProviderIntl* resourceProvider = GetInternalApexSDK()->getInternalResourceProvider();
	for (uint32_t i = 0 ; i < mStaticMaterialIDs.size() ; i++)
	{
		resourceProvider->releaseResource(mStaticMaterialIDs[i]);
	}

	if (mParams != NULL && mOwnsParams)
	{
		mParams->destroy();
	}
	mParams = NULL;
	mOwnsParams = false;

	if (mApexDestructibleActorParams)
	{
		mApexDestructibleActorParams->destroy();
		mApexDestructibleActorParams = 0;
	}
	/* Assets that were forceloaded or loaded by actors will be automatically
	 * released by the ApexAssetTracker member destructors.
	 */
}

void DestructibleAssetImpl::init()
{
	module = NULL;
	chunkOverlapCacheDepth = -1;
	renderMeshAsset = NULL;
	runtimeRenderMeshAsset = NULL;
	mCollisionMeshes = NULL;
	m_currentInstanceBufferActorAllowance = 0;
	m_needsInstanceBufferDataResize = false;
	m_needsInstanceBufferResize = false;
	m_needsScatterMeshInstanceInfoCreation = false;
}

uint32_t DestructibleAssetImpl::forceLoadAssets()
{
	uint32_t assetLoadedCount = 0;

	assetLoadedCount += mCrumbleAssetTracker.forceLoadAssets();
	assetLoadedCount += mDustAssetTracker.forceLoadAssets();

	if (renderMeshAsset != NULL)
	{
		assetLoadedCount += renderMeshAsset->forceLoadAssets();
	}

	ResourceProviderIntl* nrp = GetInternalApexSDK()->getInternalResourceProvider();
	ResID materialNS = GetInternalApexSDK()->getMaterialNameSpace();
	for (uint32_t i = 0; i < mStaticMaterialIDs.size(); i++)
	{
		if (!nrp->checkResource(materialNS, mParams->staticMaterialNames.buf[i]))
		{
			/* we know for SURE that createResource() has already been called, so just getResource() */
			nrp->getResource(mStaticMaterialIDs[i]);
			assetLoadedCount++;
		}
	}

	return assetLoadedCount;
}

void DestructibleAssetImpl::initializeAssetNameTable()
{
	if (mParams->dustEmitterName && *mParams->dustEmitterName)
	{
		mDustAssetTracker.addAssetName(mParams->dustEmitterName, false);
	}

	if (mParams->crumbleEmitterName && *mParams->crumbleEmitterName)
	{
		mCrumbleAssetTracker.addAssetName(mParams->crumbleEmitterName, false);
	}
}

void DestructibleAssetImpl::cleanup()
{
	// Release internal RenderMesh, preview instances, and authoring instance

	while (m_previewList.getSize())
	{
		DestructiblePreviewProxy* proxy = DYNAMIC_CAST(DestructiblePreviewProxy*)(m_previewList.getResource(m_previewList.getSize() - 1));
		PX_ASSERT(proxy != NULL);
		if (proxy == NULL)
		{
			m_previewList.remove(m_previewList.getSize() - 1);	// To avoid an infinite loop
		}
		else
		{
			proxy->release();
		}
	}

	m_previewList.clear();
	m_destructibleList.clear();

	setRenderMeshAsset(NULL);

	// release chunk instance render resources
	m_chunkInstanceBufferDataLock.lock();
	m_needsInstanceBufferResize = false;
	m_chunkInstanceBufferData.clear();
	updateChunkInstanceRenderResources(false, NULL);
	m_chunkInstanceBufferDataLock.unlock();

	setScatterMeshAssets(NULL, 0);

	m_instancedChunkActorMap.resize(0);
	m_instancedChunkActorVisiblePart.resize(0);

	if (module->mCachedData != NULL)
	{
		module->mCachedData->clearAssetCollisionSet(*this);
	}
}

void DestructibleAssetImpl::prepareForNewInstance()
{
	if (m_currentInstanceBufferActorAllowance < m_destructibleList.getSize() + 1)	// Add 1 to predict new actor
	{
		// This loop should only be hit once
		do
		{
			m_currentInstanceBufferActorAllowance = m_currentInstanceBufferActorAllowance > 0 ? 2*m_currentInstanceBufferActorAllowance : 1;
			m_needsInstanceBufferDataResize = true;
		}
		while (m_currentInstanceBufferActorAllowance < m_destructibleList.getSize());	// Add 1 to predict new actor
	}
}



void DestructibleAssetImpl::resetInstanceData()
{
	PX_PROFILE_ZONE("DestructibleAsset::resetInstanceData", GetInternalApexSDK()->getContextId());

	m_chunkInstanceBufferDataLock.lock();
	m_chunkInstanceBufferData.resize(m_instancedChunkMeshCount);
	if (m_needsInstanceBufferDataResize)
	{
		//
		// reserve the right amount of memory in the per chunk mesh arrays
		// 
		for (uint32_t index = 0; index < m_instancedChunkMeshCount; ++index)
		{
			if (m_currentInstanceBufferActorAllowance > 0)
			{
				// Find out how many potential instances there are
				uint32_t maxInstanceCount = 0;
				for (int32_t i = 0; i < mParams->chunkInstanceInfo.arraySizes[0]; ++i)
				{
					if (mParams->chunkInstanceInfo.buf[i].partIndex == m_instancedChunkActorVisiblePart[index])
					{
						maxInstanceCount += m_currentInstanceBufferActorAllowance;
					}
				}

				// Instance buffer data
				m_chunkInstanceBufferData[index].reserve(maxInstanceCount);
			}
			
			m_chunkInstanceBufferData[index].resize(0);
		}

		m_needsInstanceBufferDataResize = false;
		m_needsInstanceBufferResize = true;
	}
	else
	{
		for (uint32_t j = 0; j < m_chunkInstanceBufferData.size(); ++j)
		{
			m_chunkInstanceBufferData[j].resize(0);
		}
	}
	m_chunkInstanceBufferDataLock.unlock();


	for (uint32_t j = 0; j < m_scatterMeshInstanceInfo.size(); ++j)
	{
		m_scatterMeshInstanceInfo[j].m_instanceBufferData.resize(0);
	}
	m_instancingRepresentativeActorIndex = -1;	// not set
}


template <class ParamType>
DestructibleActor* createDestructibleActorImpl(ParamType& params, 
												 DestructibleAssetImpl& destructibleAsset,
												 ResourceList& destructibleList,
												 DestructibleScene* destructibleScene)
{
	if (NULL == destructibleScene)
		return NULL;

	destructibleAsset.prepareForNewInstance();

	return PX_NEW(DestructibleActorProxy)(params, destructibleAsset, destructibleList, *destructibleScene);
}

DestructibleActor* DestructibleAssetImpl::createDestructibleActorFromDeserializedState(NvParameterized::Interface* params, Scene& scene)
{
	PX_PROFILE_ZONE("DestructibleCreateActor", GetInternalApexSDK()->getContextId());

	if (NULL == params || !isValidForActorCreation(*params, scene))
		return NULL;

	return createDestructibleActorImpl(params, *this, m_destructibleList, module->getDestructibleScene(scene));
}

DestructibleActor* DestructibleAssetImpl::createDestructibleActor(const NvParameterized::Interface& params, Scene& scene)
{
	PX_PROFILE_ZONE("DestructibleCreateActor", GetInternalApexSDK()->getContextId());

	return createDestructibleActorImpl(params, *this, m_destructibleList, module->getDestructibleScene(scene));
}

void DestructibleAssetImpl::releaseDestructibleActor(DestructibleActor& nxactor)
{
	DestructibleActorProxy* proxy = DYNAMIC_CAST(DestructibleActorProxy*)(&nxactor);
	proxy->destroy();
}

bool DestructibleAssetImpl::setRenderMeshAsset(RenderMeshAsset* newRenderMeshAsset)
{
	if (newRenderMeshAsset == renderMeshAsset)
	{
		return false;
	}

	for (uint32_t i = 0; i < m_instancedChunkRenderMeshActors.size(); ++i)
	{
		if (m_instancedChunkRenderMeshActors[i] != NULL)
		{
			m_instancedChunkRenderMeshActors[i]->release();
			m_instancedChunkRenderMeshActors[i] = NULL;
		}
	}

	if (renderMeshAsset != NULL)
	{
		if(mOwnsParams && mParams != NULL)
		{
			// set isReferenced to false, so that the parameterized object
			// for the render mesh asset is destroyed in renderMeshAsset->release
			NvParameterized::ErrorType e;
			if (mParams->renderMeshAsset != NULL)
			{
				NvParameterized::Handle h(*mParams->renderMeshAsset);
				e = mParams->renderMeshAsset->getParameterHandle("isReferenced", h);
				PX_ASSERT(e == NvParameterized::ERROR_NONE);
				if (e == NvParameterized::ERROR_NONE)
				{
					h.setParamBool(false);
				}
				mParams->renderMeshAsset = NULL;
			}
		}
		renderMeshAsset->release();
	}

	renderMeshAsset = newRenderMeshAsset;
	if (renderMeshAsset != NULL)
	{
		mParams->renderMeshAsset = (NvParameterized::Interface*)renderMeshAsset->getAssetNvParameterized();
		NvParameterized::ErrorType e;
		NvParameterized::Handle h(*mParams->renderMeshAsset);
		e = mParams->renderMeshAsset->getParameterHandle("isReferenced", h);
		PX_ASSERT(e == NvParameterized::ERROR_NONE);
		if (e == NvParameterized::ERROR_NONE)
		{
			h.setParamBool(true);
		}

		for (uint32_t i = 0; i < m_instancedChunkRenderMeshActors.size(); ++i)
		{
			// Create actor
			RenderMeshActorDesc renderableMeshDesc;
			renderableMeshDesc.maxInstanceCount = m_chunkInstanceBufferData[i].capacity();
			renderableMeshDesc.renderWithoutSkinning = true;
			renderableMeshDesc.visible = false;
			m_instancedChunkRenderMeshActors[i] = newRenderMeshAsset->createActor(renderableMeshDesc);
			m_instancedChunkRenderMeshActors[i]->setInstanceBuffer(m_chunkInstanceBuffers[i]);
			m_instancedChunkRenderMeshActors[i]->setVisibility(true, m_instancedChunkActorVisiblePart[i]);
			m_instancedChunkRenderMeshActors[i]->setReleaseResourcesIfNothingToRender(false);
		}
	}

	return true;
}

bool DestructibleAssetImpl::setScatterMeshAssets(RenderMeshAsset** scatterMeshAssetArray, uint32_t scatterMeshAssetArraySize)
{
	if (scatterMeshAssetArray == NULL && scatterMeshAssetArraySize > 0)
	{
		return false;
	}

	for (uint32_t i = 0; i < scatterMeshAssetArraySize; ++i)
	{
		if (scatterMeshAssetArray[i] == NULL)
		{
			return false;
		}
	}

	// First clear instance information
	m_scatterMeshInstanceInfo.resize(0);	// Ensure we delete all instanced actors
	m_scatterMeshInstanceInfo.resize(scatterMeshAssetArraySize);

	// Clear out scatter mesh assets, including parameterized data
	for (int32_t i = 0; mParams && (i < mParams->scatterMeshAssets.arraySizes[0]); ++i)
	{
		if (mParams->scatterMeshAssets.buf[i] != NULL)
		{
			NvParameterized::ErrorType e;
			NvParameterized::Handle h(*mParams->scatterMeshAssets.buf[i]);
			e = mParams->scatterMeshAssets.buf[i]->getParameterHandle("isReferenced", h);
			PX_ASSERT(e == NvParameterized::ERROR_NONE);
			if (e == NvParameterized::ERROR_NONE)
			{
				h.setParamBool(false);
			}
			mParams->scatterMeshAssets.buf[i] = NULL;
		}
	}

	for (uint32_t i = 0; i < scatterMeshAssets.size(); ++i)
	{
		if (scatterMeshAssets[i] != NULL)
		{
			scatterMeshAssets[i]->release();
			scatterMeshAssets[i] = NULL;
		}
	}

	if (mParams != NULL)
	{
	scatterMeshAssets.resize(scatterMeshAssetArraySize, NULL);
	NvParameterized::Handle h(*mParams, "scatterMeshAssets");
	h.resizeArray((int32_t)scatterMeshAssetArraySize);

	for (uint32_t i = 0; i < scatterMeshAssetArraySize; ++i)
	{
		// Create new asset
		scatterMeshAssets[i] = scatterMeshAssetArray[i];
		mParams->scatterMeshAssets.buf[i] = (NvParameterized::Interface*)scatterMeshAssets[i]->getAssetNvParameterized();
		NvParameterized::ErrorType e;
		NvParameterized::Handle h(*mParams->scatterMeshAssets.buf[i]);
		e = mParams->scatterMeshAssets.buf[i]->getParameterHandle("isReferenced", h);
		PX_ASSERT(e == NvParameterized::ERROR_NONE);
		if (e == NvParameterized::ERROR_NONE)
		{
			h.setParamBool(true);
		}
	}

	m_needsScatterMeshInstanceInfoCreation = true;
	}


	return true;
}

void DestructibleAssetImpl::createScatterMeshInstanceInfo()
{
	if (!m_needsScatterMeshInstanceInfoCreation)
		return;

	m_needsScatterMeshInstanceInfoCreation = false;

	UserRenderResourceManager* rrm = GetInternalApexSDK()->getUserRenderResourceManager();

	physx::Array<uint32_t> totalInstanceCounts(scatterMeshAssets.size(), 0);
	for (int32_t i = 0; i < mParams->scatterMeshIndices.arraySizes[0]; ++i)
	{
		const uint8_t scatterMeshIndex = mParams->scatterMeshIndices.buf[i];
		if (scatterMeshIndex < scatterMeshAssets.size())
		{
			++totalInstanceCounts[scatterMeshIndex];
		}
	}

	for (uint32_t i = 0; i < scatterMeshAssets.size(); ++i)
	{
		// Create instanced info
		ScatterMeshInstanceInfo& info = m_scatterMeshInstanceInfo[i];
		RenderMeshActorDesc renderableMeshDesc;
		renderableMeshDesc.maxInstanceCount = totalInstanceCounts[i];
		renderableMeshDesc.renderWithoutSkinning = true;
		renderableMeshDesc.visible = true;
		info.m_actor = scatterMeshAssets[i]->createActor(renderableMeshDesc);

		// Create instance buffer
		info.m_instanceBuffer = NULL;
		info.m_IBSize = totalInstanceCounts[i];
		if (totalInstanceCounts[i] > 0)
		{
			UserRenderInstanceBufferDesc instanceBufferDesc = getScatterMeshInstanceBufferDesc();
			instanceBufferDesc.maxInstances = totalInstanceCounts[i];
			info.m_instanceBuffer = rrm->createInstanceBuffer(instanceBufferDesc);
		}

		// Instance buffer data
		info.m_instanceBufferData.reset();
		info.m_instanceBufferData.reserve(totalInstanceCounts[i]);

		info.m_actor->setInstanceBuffer(info.m_instanceBuffer);
		info.m_actor->setReleaseResourcesIfNothingToRender(false);
	}
}

UserRenderInstanceBufferDesc DestructibleAssetImpl::getScatterMeshInstanceBufferDesc()
{
	UserRenderInstanceBufferDesc instanceBufferDesc;
	instanceBufferDesc.hint = RenderBufferHint::DYNAMIC;
	instanceBufferDesc.semanticOffsets[RenderInstanceLayoutElement::POSITION_FLOAT3] = ScatterInstanceBufferDataElement::translationOffset();
	instanceBufferDesc.semanticOffsets[RenderInstanceLayoutElement::ROTATION_SCALE_FLOAT3x3] = ScatterInstanceBufferDataElement::scaledRotationOffset();
	instanceBufferDesc.semanticOffsets[RenderInstanceLayoutElement::DENSITY_FLOAT1] = ScatterInstanceBufferDataElement::alphaOffset();
	instanceBufferDesc.stride = sizeof(ScatterInstanceBufferDataElement);

	return instanceBufferDesc;
}

void DestructibleAssetImpl::updateChunkInstanceRenderResources(bool rewriteBuffers, void* userRenderData)
{
	PX_PROFILE_ZONE("DestructibleAsset::updateChunkInstanceRenderResources", GetInternalApexSDK()->getContextId());

	UserRenderResourceManager* rrm = GetInternalApexSDK()->getUserRenderResourceManager();

	Mutex::ScopedLock scopeLock(m_chunkInstanceBufferDataLock);

	uint32_t oldCount = m_chunkInstanceBuffers.size();
	uint32_t count = m_chunkInstanceBufferData.size();

	//
	// release resources
	//
	// release all on resize for recreation lateron
	uint32_t startIndexForRelease = m_needsInstanceBufferResize ? 0 : count;
	for (uint32_t i = startIndexForRelease; i < oldCount; ++i)
	{
		if (m_instancedChunkRenderMeshActors[i] != NULL)
		{
			m_instancedChunkRenderMeshActors[i]->release();
			m_instancedChunkRenderMeshActors[i] = NULL;
		}
		if (m_chunkInstanceBuffers[i] != NULL)
		{
			rrm->releaseInstanceBuffer(*m_chunkInstanceBuffers[i]);
			m_chunkInstanceBuffers[i] = NULL;
		}
	}

	// resize and init arrays
	m_chunkInstanceBuffers.resize(count);
	m_instancedChunkRenderMeshActors.resize(count);
	for (uint32_t index = oldCount; index < count; ++index)
	{
		m_instancedChunkRenderMeshActors[index] = NULL;
		m_chunkInstanceBuffers[index] = NULL;
	}


	//
	// create resources when needed
	//

	for (uint32_t index = 0; index < count; ++index)
	{
		// if m_chunkInstanceBufferData[index] contains any data there's an instance to render
		if (m_chunkInstanceBuffers[index] == NULL && m_chunkInstanceBufferData[index].size() > 0)
		{
			// Find out how many potential instances there are
			uint32_t maxInstanceCount = 0;
			for (int32_t i = 0; i < mParams->chunkInstanceInfo.arraySizes[0]; ++i)
			{
				if (mParams->chunkInstanceInfo.buf[i].partIndex == m_instancedChunkActorVisiblePart[index])
				{
					maxInstanceCount += m_currentInstanceBufferActorAllowance;
				}
			}

			// Create instance buffer
			UserRenderInstanceBufferDesc instanceBufferDesc;
			instanceBufferDesc.maxInstances = maxInstanceCount;
			instanceBufferDesc.hint = RenderBufferHint::DYNAMIC;
			instanceBufferDesc.semanticOffsets[RenderInstanceLayoutElement::POSITION_FLOAT3] = ChunkInstanceBufferDataElement::translationOffset();
			instanceBufferDesc.semanticOffsets[RenderInstanceLayoutElement::ROTATION_SCALE_FLOAT3x3] = ChunkInstanceBufferDataElement::scaledRotationOffset();
			instanceBufferDesc.semanticOffsets[RenderInstanceLayoutElement::UV_OFFSET_FLOAT2] = ChunkInstanceBufferDataElement::uvOffsetOffset();
			instanceBufferDesc.semanticOffsets[RenderInstanceLayoutElement::LOCAL_OFFSET_FLOAT3] = ChunkInstanceBufferDataElement::localOffsetOffset();
			instanceBufferDesc.stride = sizeof(ChunkInstanceBufferDataElement);
			m_chunkInstanceBuffers[index] = rrm->createInstanceBuffer(instanceBufferDesc);

			// Create actor
			if (renderMeshAsset != NULL)
			{
				PX_ASSERT(m_instancedChunkRenderMeshActors[index] == NULL);

				RenderMeshActorDesc renderableMeshDesc;
				renderableMeshDesc.maxInstanceCount = maxInstanceCount;
				renderableMeshDesc.renderWithoutSkinning = true;
				renderableMeshDesc.visible = false;
				m_instancedChunkRenderMeshActors[index] = renderMeshAsset->createActor(renderableMeshDesc);
				m_instancedChunkRenderMeshActors[index]->setInstanceBuffer(m_chunkInstanceBuffers[index]);
				m_instancedChunkRenderMeshActors[index]->setVisibility(true, m_instancedChunkActorVisiblePart[index]);
				m_instancedChunkRenderMeshActors[index]->setReleaseResourcesIfNothingToRender(false);
			}
		}

		//
		// update with new data
		//
		PX_ASSERT(index < m_chunkInstanceBufferData.size());
		RenderMeshActorIntl* renderMeshActor = (RenderMeshActorIntl*)m_instancedChunkRenderMeshActors[index];
		if (renderMeshActor != NULL)
		{
			RenderInstanceBufferData data;
			const uint32_t instanceBufferSize = m_chunkInstanceBufferData[index].size();

			if (instanceBufferSize > 0)
			{
				m_chunkInstanceBuffers[index]->writeBuffer(&m_chunkInstanceBufferData[index][0], 0, instanceBufferSize);
			}

			renderMeshActor->setInstanceBufferRange(0, instanceBufferSize);
			renderMeshActor->updateRenderResources(false, rewriteBuffers, userRenderData);
		}
	}

	m_needsInstanceBufferResize = false;
}

bool DestructibleAssetImpl::setPlatformMaxDepth(PlatformTag platform, uint32_t maxDepth)
{
	bool isExistingPlatform = false;
	for (Array<PlatformKeyValuePair>::Iterator iter = m_platformFractureDepthMap.begin(); iter != m_platformFractureDepthMap.end(); ++iter)
	{
		if (nvidia::strcmp(iter->key, platform) == 0)
		{
			isExistingPlatform = true;
			iter->val = maxDepth; //overwrite if existing
			break;
		}
	}
	if (!isExistingPlatform)
	{
		m_platformFractureDepthMap.pushBack(PlatformKeyValuePair(platform, maxDepth));
	}
	return maxDepth < mParams->depthCount - 1; //depthCount == 1 => unfractured mesh
}

bool DestructibleAssetImpl::removePlatformMaxDepth(PlatformTag platform)
{
	bool isExistingPlatform = false;
	for (uint32_t index = 0; index < m_platformFractureDepthMap.size(); ++index)
	{
		if (nvidia::strcmp(m_platformFractureDepthMap[index].key, platform) == 0)
		{
			isExistingPlatform = true;
			m_platformFractureDepthMap.remove(index); //yikes! for lack of a map...
			break;
		}
	}
	return isExistingPlatform;
}

bool DestructibleAssetImpl::setDepthCount(uint32_t targetDepthCount) const
{
	if (mParams->depthCount <= targetDepthCount)
	{
		return false;
	}

	int newChunkCount = mParams->chunks.arraySizes[0];
	for (int i = newChunkCount; i--;)
	{
		if (mParams->chunks.buf[i].depth >= targetDepthCount)
		{
			newChunkCount = i;
		}
		else if (mParams->chunks.buf[i].depth == targetDepthCount - 1)
		{
			// These chunks must have no children
			DestructibleAssetParametersNS::Chunk_Type& chunk = mParams->chunks.buf[i];
			chunk.numChildren = 0;
			chunk.firstChildIndex = DestructibleAssetImpl::InvalidChunkIndex;
			chunk.flags &= ~(uint16_t)DescendantUnfractureable;
		}
		else
		{
			break;
		}
	}

	NvParameterized::Handle handle(*mParams);
	mParams->getParameterHandle("chunks", handle);
	mParams->resizeArray(handle, newChunkCount);

	mParams->getParameterHandle("overlapsAtDepth", handle);
	int size;
	mParams->getArraySize(handle, size);
	if ((int)targetDepthCount < size)
	{
		mParams->resizeArray(handle, (int32_t)targetDepthCount);
	}
	mParams->getParameterHandle("firstChunkAtDepth", handle);
	mParams->resizeArray(handle, (int32_t)targetDepthCount + 1);

	mParams->depthCount = targetDepthCount;

	return true;
}

bool DestructibleAssetImpl::prepareForPlatform(nvidia::apex::PlatformTag platform) const
{
	bool isExistingPlatform = false;
	bool isDepthLimitChanged = false;
	for (Array<PlatformKeyValuePair>::ConstIterator kIter = m_platformFractureDepthMap.begin(); kIter != m_platformFractureDepthMap.end(); ++kIter)
	{
		if (nvidia::strcmp(kIter->key, platform) == 0)
		{
			isExistingPlatform = true;
			isDepthLimitChanged = setDepthCount(kIter->val + 1); //targetDepthCount == 1 => unfractured mesh
			break;
		}
	}
	//if (!isExistingPlatform) {/*keep all depths, behaviour by default*/}
	return (isExistingPlatform & isDepthLimitChanged);
}

void DestructibleAssetImpl::reduceAccordingToLOD()
{
	if (module == NULL)
	{
		return;
	}

	const uint32_t targetDepthCount = mParams->originalDepthCount > module->m_maxChunkDepthOffset ? mParams->originalDepthCount - module->m_maxChunkDepthOffset : 1;

	setDepthCount(targetDepthCount);
}

void DestructibleAssetImpl::getStats(DestructibleAssetStats& stats) const
{
	memset(&stats, 0, sizeof(DestructibleAssetStats));

	if (renderMeshAsset)
	{
		renderMeshAsset->getStats(stats.renderMeshAssetStats);
	}

	// BRG - to do - need a way of getting the serialized size
	stats.totalBytes = 0;

	stats.chunkCount = (uint32_t)mParams->chunks.arraySizes[0];
	stats.chunkBytes = mParams->chunks.arraySizes[0] * sizeof(DestructibleAssetParametersNS::Chunk_Type);

	uint32_t maxEdgeCount = 0;

	for (uint16_t chunkIndex = 0; chunkIndex < getChunkCount(); ++chunkIndex)
	{
		for (uint32_t hullIndex = getChunkHullIndexStart(chunkIndex); hullIndex < getChunkHullIndexStop(chunkIndex); ++hullIndex)
		{
			const ConvexHullImpl& hullData = chunkConvexHulls[hullIndex];
			const uint32_t hullDataBytes = hullData.getVertexCount() * sizeof(PxVec3) +
											   hullData.getUniquePlaneNormalCount() * 4 * sizeof(float) +
											   hullData.getUniquePlaneNormalCount() * sizeof(float) +
											   hullData.getEdgeCount() * sizeof(uint32_t);
			stats.chunkHullDataBytes += hullDataBytes;
			stats.chunkBytes += hullDataBytes;

			// Get cooked convex mesh stats
			uint32_t numVerts = 0;
			uint32_t numPolys = 0;
			const uint32_t cookedHullDataBytes = hullData.calculateCookedSizes(numVerts, numPolys, true);
			stats.maxHullVertexCount = PxMax(stats.maxHullVertexCount, numVerts);
			stats.maxHullFaceCount = PxMax(stats.maxHullFaceCount, numPolys);
			const uint32_t numEdges = numVerts + numPolys - 2;
			if (numEdges > maxEdgeCount)
			{
				maxEdgeCount = numEdges;
				stats.chunkWithMaxEdgeCount = chunkIndex;
			}

			stats.chunkBytes += cookedHullDataBytes;
		}
	}

	stats.runtimeCookedConvexCount = mRuntimeCookedConvexCount;
	/* To do - count collision data in ApexScene! */
}

void DestructibleAssetImpl::applyTransformation(const PxMat44& transformation, float scale)
{
	/* For now, we'll just clear the current cached streams at scale. */
	/* transform and scale the PxConvexMesh(es) */
	if (mParams->collisionData)
	{
		APEX_DEBUG_WARNING("Cached collision data is already present, removing");
		mParams->collisionData->destroy();
		mParams->collisionData = NULL;
#if 0
		DestructibleAssetCollisionDataSet* cds =
		    DYNAMIC_CAST(DestructibleAssetCollisionDataSet*)(mParams->collisionData);

		for (int i = 0; i < cds->meshCookedCollisionStreamsAtScale.arraySizes[0]; ++i)
		{
			PX_ASSERT(cds->meshCookedCollisionStreamsAtScale.buf[i]);

			MeshCookedCollisionStreamsAtScale* meshStreamsAtScale =
			    DYNAMIC_CAST(MeshCookedCollisionStreamsAtScale*)(cds->meshCookedCollisionStreamsAtScale.buf[i]);
			for (int j = 0; j < meshStreamsAtScale->meshCookedCollisionStreams.arraySizes[0]; ++j)
			{
				PX_ASSERT(meshStreamsAtScale->meshCookedCollisionStreams.buf[i]);

				MeshCookedCollisionStream* meshStreamParams =
				    DYNAMIC_CAST(MeshCookedCollisionStream*)(meshStreamsAtScale->meshCookedCollisionStreams.buf[i]);

				/* stream it into the physx sdk */
				nvidia::PsMemoryBuffer memStream(meshStreamParams->bytes.buf, meshStreamParams->bytes.arraySizes[0]);
				memStream.setEndianMode(PxFileBuf::ENDIAN_NONE);
				PxStreamFromFileBuf nvs(memStream);
				PxConvexMesh* convexMesh = GetApexSDK()->getPhysXSDK()->createConvexMesh(nxs);

				PxConvexMeshDesc meshDesc;
				convexMesh->saveToDesc(meshDesc);
				meshDesc.

				uint32_t submeshCount = convexMesh->getSubmeshCount();
				(void)submeshCount;
			}
		}
#endif
	}

	/* chunk surface normal */
	for (int i = 0; i < mParams->chunks.arraySizes[0]; ++i)
	{
		PX_ASSERT(mParams->chunks.buf);

		DestructibleAssetParametersNS::Chunk_Type* chunk = &(mParams->chunks.buf[i]);

		chunk->surfaceNormal = transformation.rotate(chunk->surfaceNormal);
	}

	/* bounds */
	PX_ASSERT(!mParams->bounds.isEmpty());
	mParams->bounds.minimum *= scale;
	mParams->bounds.maximum *= scale;
	if (scale < 0.0f)
	{
		nvidia::swap(mParams->bounds.minimum, mParams->bounds.maximum);
	}
	mParams->bounds = PxBounds3::transformSafe(PxTransform(transformation), mParams->bounds);

	/* chunk convex hulls */
	for (int i = 0; i < mParams->chunkConvexHulls.arraySizes[0]; ++i)
	{
		PX_ASSERT(mParams->chunkConvexHulls.buf[i]);
		ConvexHullImpl chunkHull;
		chunkHull.mParams = DYNAMIC_CAST(ConvexHullParameters*)(mParams->chunkConvexHulls.buf[i]);
		chunkHull.mOwnsParams = false;
		chunkHull.applyTransformation(transformation, scale);
	}

	/* render mesh (just apply to both the asset and author if they both exist) */
	if (renderMeshAsset)
	{
		reinterpret_cast<RenderMeshAssetIntl*>(renderMeshAsset)->applyTransformation(transformation, scale);
	}

	/* scatter meshes */
	const PxMat33 m33(transformation.column0.getXYZ(), transformation.column1.getXYZ(), transformation.column2.getXYZ());
	for (int i = 0; i < mParams->scatterMeshTransforms.arraySizes[0]; ++i)
	{
		PxMat44& tm = mParams->scatterMeshTransforms.buf[i];
		PxMat33 tm33(tm.column0.getXYZ(), tm.column1.getXYZ(), tm.column2.getXYZ()); 

		tm33 = m33*tm33;
		tm33 *= scale;
		const PxVec3 pos = transformation.getPosition() + scale*(m33*tm.getPosition());
		tm.column0 = PxVec4(tm33.column0, 0);
		tm.column1 = PxVec4(tm33.column1, 0);
		tm.column2 = PxVec4(tm33.column2, 0);
		tm.setPosition(pos);
	}
	if (m33.getDeterminant() * scale < 0.0f)
	{
		for (uint32_t i = 0; i < scatterMeshAssets.size(); ++i)
		{
			RenderMeshAsset* scatterMesh = scatterMeshAssets[i];
			if (scatterMesh != NULL)
			{
				reinterpret_cast<RenderMeshAssetIntl*>(scatterMesh)->reverseWinding();
			}
		}
	}
}

void DestructibleAssetImpl::applyTransformation(const PxMat44& transformation)
{
	/* For now, we'll just clear the current cached streams at scale. */
	/* transform and scale the PxConvexMesh(es) */
	if (mParams->collisionData)
	{
		APEX_DEBUG_WARNING("Cached collision data is already present, removing");
		mParams->collisionData->destroy();
		mParams->collisionData = NULL;
	}

	Cof44 cofTM(transformation);

	/* chunk surface normal */
	for (int i = 0; i < mParams->chunks.arraySizes[0]; ++i)
	{
		PX_ASSERT(mParams->chunks.buf);

		DestructibleAssetParametersNS::Chunk_Type* chunk = &(mParams->chunks.buf[i]);

		chunk->surfaceNormal = cofTM.getBlock33().transform(chunk->surfaceNormal);
		chunk->surfaceNormal.normalize();
	}

	/* bounds */
	PX_ASSERT(!mParams->bounds.isEmpty());
	mParams->bounds = PxBounds3::transformSafe(PxTransform(transformation), mParams->bounds);

	/* chunk convex hulls */
	for (int i = 0; i < mParams->chunkConvexHulls.arraySizes[0]; ++i)
	{
		PX_ASSERT(mParams->chunkConvexHulls.buf[i]);
		ConvexHullImpl chunkHull;
		chunkHull.mParams = DYNAMIC_CAST(ConvexHullParameters*)(mParams->chunkConvexHulls.buf[i]);
		chunkHull.mOwnsParams = false;
		chunkHull.applyTransformation(transformation);
	}

	/* render mesh (just apply to both the asset and author if they both exist) */
	if (renderMeshAsset)
	{
		reinterpret_cast<RenderMeshAssetIntl*>(renderMeshAsset)->applyTransformation(transformation, 1.0f);	// This transformation function properly handles non-uniform scales
	}
}

void DestructibleAssetImpl::traceSurfaceBoundary(physx::Array<PxVec3>& outPoints, uint16_t chunkIndex, const PxTransform& localToWorldRT, const PxVec3& scale,
        float spacing, float jitter, float surfaceDistance, uint32_t maxPoints)
{
	outPoints.resize(0);

	// Removing this function's implementation for now

	PX_UNUSED(chunkIndex);
	PX_UNUSED(localToWorldRT);
	PX_UNUSED(scale);
	PX_UNUSED(spacing);
	PX_UNUSED(jitter);
	PX_UNUSED(surfaceDistance);
	PX_UNUSED(maxPoints);
}


bool DestructibleAssetImpl::rebuildCollisionGeometry(uint32_t partIndex, const DestructibleGeometryDesc& geometryDesc)
{
#ifdef WITHOUT_APEX_AUTHORING
	PX_UNUSED(partIndex);
	PX_UNUSED(geometryDesc);
	APEX_DEBUG_WARNING("DestructibleAsset::rebuildCollisionGeometry is not available in release builds.");
	return false;
#else
	NvParameterized::Handle handle(*mParams);
	mParams->getParameterHandle("chunkConvexHulls", handle);
	NvParameterized::Traits* traits = GetInternalApexSDK()->getParameterizedTraits();

	const uint32_t startHullIndex = mParams->chunkConvexHullStartIndices.buf[partIndex];
	uint32_t hullCount = geometryDesc.convexHullCount;
	const nvidia::ExplicitHierarchicalMesh::ConvexHull** convexHulls = geometryDesc.convexHulls;
	physx::Array<PartConvexHullProxy*> collision;
	if (hullCount == 0 && geometryDesc.collisionVolumeDesc != NULL)
	{
		physx::Array<PxVec3> vertices;
		physx::Array<uint32_t> indices;
		gatherPartMesh(vertices, indices, renderMeshAsset, partIndex);
		buildCollisionGeometry(collision, *geometryDesc.collisionVolumeDesc, vertices.begin(), vertices.size(), sizeof(PxVec3), indices.begin(), indices.size());
		convexHulls = (const nvidia::ExplicitHierarchicalMesh::ConvexHull**)collision.begin();
		hullCount = collision.size();
	}
	const uint32_t oldStopHullIndex = mParams->chunkConvexHullStartIndices.buf[partIndex + 1];
	const uint32_t oldHullCount = oldStopHullIndex - startHullIndex;
	const uint32_t stopHullIndex = startHullIndex + hullCount;
	const int32_t hullCountDelta = (int32_t)(hullCount - oldHullCount);

	// Adjust start indices
	for (uint32_t i = partIndex+1; i < (uint32_t)mParams->chunkConvexHullStartIndices.arraySizes[0]; ++i)
	{
		mParams->chunkConvexHullStartIndices.buf[i] += hullCountDelta;
	}
	const uint32_t totalHullCount = (uint32_t)mParams->chunkConvexHullStartIndices.buf[mParams->chunkConvexHullStartIndices.arraySizes[0]-1];

	// Eliminate hulls if the count has decreased
	if (hullCountDelta < 0)
	{
		for (uint32_t index = stopHullIndex; index < totalHullCount; ++index)
		{
			chunkConvexHulls[index].mParams->copy( *chunkConvexHulls[index-hullCountDelta].mParams );
		}
	}

	// Resize the hull arrays
	if (hullCountDelta != 0)
	{
		mParams->resizeArray(handle, (int32_t)totalHullCount);
		chunkConvexHulls.resize(totalHullCount);
	}

	// Insert hulls if the count has increased
	if (hullCountDelta > 0)
	{
		for (uint32_t index = totalHullCount; index-- > stopHullIndex;)
		{
			mParams->chunkConvexHulls.buf[index] = mParams->chunkConvexHulls.buf[index-hullCountDelta];
			chunkConvexHulls[index].init(mParams->chunkConvexHulls.buf[index]);
		}
		for (uint32_t index = oldStopHullIndex; index < stopHullIndex; ++index)
		{
			mParams->chunkConvexHulls.buf[index] = traits->createNvParameterized(ConvexHullParameters::staticClassName());
			chunkConvexHulls[index].init(mParams->chunkConvexHulls.buf[index]);
		}
	}

	if (hullCount > 0)
	{
		for (uint32_t hullNum = 0; hullNum < hullCount; ++hullNum)
		{
			ConvexHullImpl& chunkHullData = chunkConvexHulls[startHullIndex + hullNum];
			PartConvexHullProxy* convexHullProxy = (PartConvexHullProxy*)convexHulls[hullNum];
			chunkHullData.mParams->copy(*convexHullProxy->impl.mParams);
			if (chunkHullData.isEmpty())
			{
				chunkHullData.buildFromAABB(renderMeshAsset->getBounds(partIndex));	// \todo: need better way of simplifying
			}
		}
	}

	return hullCount > 0;
#endif
}


// DestructibleAssetAuthoring
#ifndef WITHOUT_APEX_AUTHORING



void gatherPartMesh(physx::Array<PxVec3>& vertices,
					physx::Array<uint32_t>& indices,
					const RenderMeshAsset* renderMeshAsset,
					uint32_t partIndex)
{
	if (renderMeshAsset == NULL || partIndex >= renderMeshAsset->getPartCount())
	{
		vertices.resize(0);
		indices.resize(0);
		return;
	}


	// Pre-count vertices and indices so we can allocate once
	uint32_t vertexCount = 0;
	uint32_t indexCount = 0;
	for (uint32_t submeshIndex = 0; submeshIndex < renderMeshAsset->getSubmeshCount(); ++submeshIndex)
	{
		const RenderSubmesh& submesh = renderMeshAsset->getSubmesh(submeshIndex);
		vertexCount += submesh.getVertexCount(partIndex);
		indexCount += submesh.getIndexCount(partIndex);
	}

	vertices.resize(vertexCount);
	indices.resize(indexCount);

	vertexCount = 0;
	indexCount = 0;
	for (uint32_t submeshIndex = 0; submeshIndex < renderMeshAsset->getSubmeshCount(); ++submeshIndex)
	{
		const RenderSubmesh& submesh = renderMeshAsset->getSubmesh(submeshIndex);
		if (submesh.getVertexCount(partIndex) > 0)
		{
			const VertexBuffer& vertexBuffer = submesh.getVertexBuffer();
			const VertexFormat& vertexFormat = vertexBuffer.getFormat();
			const int32_t bufferIndex = vertexFormat.getBufferIndexFromID(vertexFormat.getSemanticID(nvidia::RenderVertexSemantic::POSITION));
			if (bufferIndex >= 0)
			{
				vertexBuffer.getBufferData(&vertices[vertexCount], nvidia::RenderDataFormat::FLOAT3, sizeof(PxVec3), (uint32_t)bufferIndex, 
					submesh.getFirstVertexIndex(partIndex), submesh.getVertexCount(partIndex));
			}
			else
			{
				memset(&vertices[vertexCount], 0, submesh.getVertexCount(partIndex)*sizeof(PxVec3));
			}
			const uint32_t* partIndexBuffer = submesh.getIndexBuffer(partIndex);
			const uint32_t partIndexCount = submesh.getIndexCount(partIndex);
			for (uint32_t indexNum = 0; indexNum < partIndexCount; ++indexNum)
			{
				indices[indexCount++] = partIndexBuffer[indexNum] + vertexCount - submesh.getFirstVertexIndex(partIndex);
			}
			vertexCount += submesh.getVertexCount(partIndex);
		}
	}
}


/**
	Private function - it's way too finicky and really only meant to serve the (public) trimCollisionVolumes function.
	The chunkIndices array is expected to contain every member of an instanced set.  That is, if a chunk indexed by some element of chunkIndices
	references partIndex, then *every* chunk that references partIndex should be in the chunkIndices array.
	Also, all chunks in chunkIndices are expected to be at the same depth.
*/
void DestructibleAssetAuthoringImpl::trimCollisionGeometryInternal(const uint32_t* chunkIndices, uint32_t chunkIndexCount, const physx::Array<IntPair>& parentDepthOverlaps, uint32_t depth, float maxTrimFraction)
{
	/*
		1) Find overlaps between each chunk (hull to hull).
		2) For each overlap:
			a) Create a trim plane for the overlapping hulls (one for each).  Adjust the trim planes to respect maxTrimFraction.
		3) For each chunk:
			a) For each hull in the chunk:
				i) Add additional trim planes from all parent chunks' neighbors' hulls, and sibling's hulls.  Adjust trim planes to respect maxTrimFraction.
		4) Intersect the trimmed hull(s) from (2) and (3) with the trim planes.  This may cause some hulls to disappear.
		5) Recurse to children
	*/

	// Create an epslion
	PxBounds3 bounds = renderMeshAsset->getBounds();
	const float sizeScale = (bounds.minimum - bounds.maximum).magnitude();
	const float eps = 0.0001f * sizeScale;	// \todo - expose?

	//	1) Find overlaps between each chunk (hull to hull).
	const PxMat44 identityTM(PxVec4(1.0f));
	const PxVec3 identityScale(1.0f);

	// Find AABB overlaps
	physx::Array<BoundsRep> chunkBoundsReps;
	chunkBoundsReps.reserve(chunkIndexCount);
	for (uint32_t chunkNum = 0; chunkNum < chunkIndexCount; ++chunkNum)
	{
		const uint32_t chunkIndex = chunkIndices[chunkNum];
		BoundsRep& chunkBoundsRep = chunkBoundsReps.insert();
		chunkBoundsRep.aabb = getChunkActorLocalBounds(chunkIndex);
	}
	physx::Array<IntPair> overlaps;
	if (chunkBoundsReps.size() > 0)
	{
		boundsCalculateOverlaps(overlaps, Bounds3XYZ, &chunkBoundsReps[0], chunkBoundsReps.size(), sizeof(chunkBoundsReps[0]));
	}

	// We'll store the trim planes here
	physx::Array<TrimPlane> trimPlanes;

	// Now do detailed overlap test
	for (uint32_t overlapIndex = 0; overlapIndex < overlaps.size(); ++overlapIndex)
	{
		IntPair& AABBOverlap = overlaps[overlapIndex];
		const uint32_t chunkIndex0 = chunkIndices[AABBOverlap.i0];
		const uint32_t chunkIndex1 = chunkIndices[AABBOverlap.i1];

		// Offset chunks (in case they are instanced)
		const PxTransform tm0(getChunkPositionOffset(chunkIndex0));
		const PxTransform tm1(getChunkPositionOffset(chunkIndex1));
		for (uint32_t hullIndex0 = getChunkHullIndexStart(chunkIndex0); hullIndex0 < getChunkHullIndexStop(chunkIndex0); ++hullIndex0)
		{
			TrimPlane trimPlane0;
			trimPlane0.hullIndex = hullIndex0;
			trimPlane0.partIndex = getPartIndex(chunkIndex0);
			for (uint32_t hullIndex1 = getChunkHullIndexStart(chunkIndex1); hullIndex1 < getChunkHullIndexStop(chunkIndex1); ++hullIndex1)
			{
				TrimPlane trimPlane1;
				trimPlane1.hullIndex = hullIndex1;
				trimPlane1.partIndex = getPartIndex(chunkIndex1);
				ConvexHullImpl::Separation separation;
				if (ConvexHullImpl::hullsInProximity(chunkConvexHulls[hullIndex0], tm0, identityScale, chunkConvexHulls[hullIndex1], tm1, identityScale, 0.0f, &separation))
				{
					//	2) For each overlap:
					//		a) Create a trim plane for the overlapping hulls (one for each).  Adjust the trim planes to respect maxTrimFraction.
					trimPlane0.plane = separation.plane;
					trimPlane0.plane.d = PxMin(trimPlane0.plane.d, maxTrimFraction*(separation.max0-separation.min0) - separation.max0);	// Bound clip distance
					trimPlane0.plane.d += trimPlane0.plane.n.dot(tm0.p);	// Transform back into part local space
					trimPlanes.pushBack(trimPlane0);
					trimPlane1.plane = PxPlane(-separation.plane.n, -separation.plane.d);
					trimPlane1.plane.d = PxMin(trimPlane1.plane.d, maxTrimFraction*(separation.max1-separation.min1) + separation.min1);	// Bound clip distance
					trimPlane1.plane.d += trimPlane1.plane.n.dot(tm1.p);	// Transform back into part local space
					trimPlanes.pushBack(trimPlane1);
				}
			}
		}
	}

	// Get overlaps for this depth
	physx::Array<IntPair> overlapsAtDepth;
	calculateChunkOverlaps(overlapsAtDepth, depth);

	//	3) For each chunk:
	for (uint32_t chunkNum = 0; chunkNum < chunkIndexCount; ++chunkNum)
	{
		const uint32_t chunkIndex = chunkIndices[chunkNum];
		const PxTransform tm0(getChunkPositionOffset(chunkIndex));
		const int32_t chunkParentIndex = mParams->chunks.buf[chunkIndex].parentIndex;

		for (int ancestorLevel = 0; ancestorLevel < 2; ++ancestorLevel)	// First time iterate through uncles, second time through siblings
		{
			// Optimization opportunity: symmetrize, sort and index the overlap list
			uint32_t overlapCount;
			const IntPair* overlapArray;
			if (ancestorLevel == 0)
			{
				overlapCount = parentDepthOverlaps.size();
				overlapArray = parentDepthOverlaps.begin();
			}
			else
			{
				overlapCount = overlapsAtDepth.size();
				overlapArray = overlapsAtDepth.begin();
			}
			for (uint32_t overlapNum = 0; overlapNum < overlapCount; ++overlapNum)
			{
				const IntPair& overlap = overlapArray[overlapNum];
				uint32_t otherChunkIndex;
				const int32_t ignoreChunkIndex = ancestorLevel == 0 ? chunkParentIndex : (int32_t)chunkIndex;
				if (overlap.i0 == ignoreChunkIndex)
				{
					otherChunkIndex = (uint32_t)overlap.i1;
				}
				else
				if (overlap.i1 == ignoreChunkIndex)
				{
					otherChunkIndex = (uint32_t)overlap.i0;
				}
				else
				{
					continue;
				}
				// Make sure we're not trimming from a chunk already in our chunk list (we've handled that already)
				bool alreadyConsidered = false;
				if (ancestorLevel == 1)
				{
					for (uint32_t checkNum = 0; checkNum < chunkIndexCount; ++checkNum)
					{
						if (chunkIndices[checkNum] == otherChunkIndex)
						{
							alreadyConsidered = true;
							break;
						}
					}
				}
				if (alreadyConsidered)
				{
					continue;
				}
				// Check other Chunk
				const PxTransform tm1(getChunkPositionOffset(otherChunkIndex));
				//	a) For each hull in the chunk:
				for (uint32_t hullIndex0 = getChunkHullIndexStart(chunkIndex); hullIndex0 < getChunkHullIndexStop(chunkIndex); ++hullIndex0)
				{
					TrimPlane trimPlane;
					trimPlane.hullIndex = hullIndex0;
					trimPlane.partIndex = getPartIndex(chunkIndex);
					for (uint32_t hullIndex1 = getChunkHullIndexStart(otherChunkIndex); hullIndex1 < getChunkHullIndexStop(otherChunkIndex); ++hullIndex1)
					{
						ConvexHullImpl::Separation separation;
						if (ConvexHullImpl::hullsInProximity(chunkConvexHulls[hullIndex0], tm0, identityScale, chunkConvexHulls[hullIndex1], tm1, identityScale, 0.0f, &separation))
						{
							if (PxMax(separation.min0 - separation.max1, separation.min1 - separation.max0) < -eps)
							{
								trimPlane.plane = separation.plane;
								trimPlane.plane.d = -separation.min1;	// Allow for other hull to intrude completely
								trimPlane.plane.d = PxMin(trimPlane.plane.d, maxTrimFraction*(separation.max0-separation.min0) - separation.max0);	// Bound clip distance
								trimPlane.plane.d += trimPlane.plane.n.dot(tm0.p);	// Transform back into part local space
								trimPlanes.pushBack(trimPlane);
							}
						}
					}
				}
			}
		}
	}

	//	4) Intersect the trimmed hull(s) from (2) and (3) with the trim planes.  This may cause some hulls to disappear.

	// Sort by part, then by hull.  We're going to get a little rough with these parts.
	nvidia::sort<TrimPlane, TrimPlane::LessThan>(trimPlanes.begin(), trimPlanes.size(), TrimPlane::LessThan());

	// Create a lookup into the array
	physx::Array<uint32_t> trimPlaneLookup;
	createIndexStartLookup(trimPlaneLookup, 0, renderMeshAsset->getPartCount(), trimPlanes.size() > 0 ? (int32_t*)&trimPlanes[0].partIndex : NULL, trimPlanes.size(), sizeof(TrimPlane));

	// Trim
	for (uint32_t partIndex = 0; partIndex < renderMeshAsset->getPartCount(); ++partIndex)
	{
		bool hullCountChanged = false;
		for (uint32_t partTrimPlaneIndex = trimPlaneLookup[partIndex]; partTrimPlaneIndex < trimPlaneLookup[partIndex+1]; ++partTrimPlaneIndex)
		{
			TrimPlane& trimPlane = trimPlanes[partTrimPlaneIndex];
			ConvexHullImpl& hull = chunkConvexHulls[trimPlane.hullIndex];
			hull.intersectPlaneSide(trimPlane.plane);
			if (hull.isEmpty())
			{
				hullCountChanged = true;
			}
		}
		if (hullCountChanged)
		{
			// Re-apply hulls that haven't disappeared
			physx::Array<PartConvexHullProxy*> newHulls;
			for (uint32_t hullIndex = mParams->chunkConvexHullStartIndices.buf[partIndex]; hullIndex < mParams->chunkConvexHullStartIndices.buf[partIndex+1]; ++hullIndex)
			{
				ConvexHullImpl& hull = chunkConvexHulls[hullIndex];
				if (!hull.isEmpty())
				{
					PartConvexHullProxy* newHull = PX_NEW(PartConvexHullProxy);
					newHulls.pushBack(newHull);
					newHull->impl.init(hull.mParams);
				}
			}
			DestructibleGeometryDesc geometryDesc;
			CollisionVolumeDesc collisionVolumeDesc;
			if (newHulls.size() > 0)
			{
				geometryDesc.convexHulls = (const nvidia::ExplicitHierarchicalMesh::ConvexHull**)newHulls.begin();
				geometryDesc.convexHullCount = newHulls.size();
			}
			else
			{
				// We've lost all of the collision volume!  Quite a shame... create a hull to replace it.
				geometryDesc.collisionVolumeDesc = &collisionVolumeDesc;
				collisionVolumeDesc.mHullMethod = ConvexHullMethod::WRAP_GRAPHICS_MESH;
			}
			rebuildCollisionGeometry(partIndex, geometryDesc);
			for (uint32_t hullN = 0; hullN < newHulls.size(); ++hullN)
			{
				PX_DELETE(newHulls[hullN]);
			}
		}
	}

	//	5) Recurse to children

	// Iterate through chunks and collect children
	physx::Array<uint32_t> childChunkIndices;
	for (uint32_t chunkNum = 0; chunkNum < chunkIndexCount; ++chunkNum)
	{
		const uint32_t chunkIndex = chunkIndices[chunkNum];
		const uint16_t firstChildIndex = mParams->chunks.buf[chunkIndex].firstChildIndex;
		for (uint16_t childNum = 0; childNum < mParams->chunks.buf[chunkIndex].numChildren; ++childNum)
		{
			childChunkIndices.pushBack((uint32_t)(firstChildIndex + childNum));
		}
	}

	// Recurse
	if (childChunkIndices.size())
	{
		trimCollisionGeometryInternal(childChunkIndices.begin(), childChunkIndices.size(), overlapsAtDepth, depth+1, maxTrimFraction);
	}
}

struct PartAndChunk
{
	uint32_t chunkIndex;
	int32_t partIndex;

	struct LessThan
	{
		PX_INLINE bool operator()(const PartAndChunk& x, const PartAndChunk& y) const
		{
			return x.partIndex != y.partIndex ? (x.partIndex < y.partIndex) : (x.chunkIndex < y.chunkIndex);
		}
	};
};

// Here's our chunk list element, with depth (for sorting)
struct ChunkAndDepth
{
	uint32_t chunkIndex;
	int32_t depth;

	struct LessThan
	{
		PX_INLINE bool operator()(const ChunkAndDepth& x, const ChunkAndDepth& y) const
		{
			return x.depth != y.depth ? (x.depth < y.depth) : (x.chunkIndex < y.chunkIndex);
		}
	};
};

void DestructibleAssetAuthoringImpl::trimCollisionGeometry(const uint32_t* partIndices, uint32_t partIndexCount, float maxTrimFraction)
{
	/*
		1) Create a list of chunks which reference each partIndex. (If there is instancing, there may be more than one chunk per part.)
		2) Sort by depth (stable sort)
		3) For each depth:
			a) Collect a list of chunks at that depth, and call trimCollisionVolumesInternal.
	*/

	//	1) Create a list of chunks which reference each partIndex. (If there is instancing, there may be more than one chunk per part.)

	// Fill array and sort
	physx::Array<PartAndChunk> partAndChunkList;
	partAndChunkList.resize(getChunkCount());
	for (uint32_t chunkIndex = 0; chunkIndex < getChunkCount(); ++chunkIndex)
	{
		partAndChunkList[chunkIndex].chunkIndex = chunkIndex;
		partAndChunkList[chunkIndex].partIndex = (int32_t)getPartIndex(chunkIndex);
	}
	nvidia::sort<PartAndChunk, PartAndChunk::LessThan>(partAndChunkList.begin(), partAndChunkList.size(), PartAndChunk::LessThan());

	// Create a lookup into the array
	physx::Array<uint32_t> partAndChunkLookup;
	createIndexStartLookup(partAndChunkLookup, 0, renderMeshAsset->getPartCount(), &partAndChunkList[0].partIndex, getChunkCount(), sizeof(PartAndChunk));

	//	2) Sort by depth (stable sort)

	// Count how many chunks there will be
	uint32_t chunkListSize = 0;
	for (uint32_t partNum = 0; partNum < partIndexCount; ++partNum)
	{
		const uint32_t partIndex = partIndices[partNum];
		chunkListSize += partAndChunkLookup[partIndex+1] - partAndChunkLookup[partIndex];
	}

	// Fill and sort
	physx::Array<ChunkAndDepth> chunkAndDepthList;
	chunkAndDepthList.resize(chunkListSize);
	uint32_t chunkNum = 0;
	for (uint32_t partNum = 0; partNum < partIndexCount; ++partNum)
	{
		const uint32_t partIndex = partIndices[partNum];
		for (uint32_t partChunkNum = partAndChunkLookup[partIndex]; partChunkNum < partAndChunkLookup[partIndex+1]; ++partChunkNum, ++chunkNum)
		{
			const uint32_t chunkIndex = partAndChunkList[partChunkNum].chunkIndex;
			chunkAndDepthList[chunkNum].chunkIndex = chunkIndex;
			chunkAndDepthList[chunkNum].depth = mParams->chunks.buf[chunkIndex].depth;
		}
	}
	nvidia::sort<ChunkAndDepth, ChunkAndDepth::LessThan>(chunkAndDepthList.begin(), chunkAndDepthList.size(), ChunkAndDepth::LessThan());

	// And create a lookup into the array
	physx::Array<uint32_t> chunkAndDepthLookup;
	createIndexStartLookup(chunkAndDepthLookup, 0, mParams->depthCount, &chunkAndDepthList[0].depth, chunkListSize, sizeof(ChunkAndDepth));

	// 3) For each depth:
	for (uint32_t depth = 0; depth < mParams->depthCount; ++depth)
	{
		physx::Array<uint32_t> chunkIndexList;
		chunkIndexList.resize(chunkAndDepthLookup[depth+1] - chunkAndDepthLookup[depth]);
		if (chunkIndexList.size() == 0)
		{
			continue;
		}
		uint32_t chunkIndexListSize = 0;
		for (uint32_t depthChunkNum = chunkAndDepthLookup[depth]; depthChunkNum < chunkAndDepthLookup[depth+1]; ++depthChunkNum)
		{
			chunkIndexList[chunkIndexListSize++] = chunkAndDepthList[depthChunkNum].chunkIndex;
		}
		PX_ASSERT(chunkIndexListSize == chunkIndexList.size());
		physx::Array<IntPair> overlaps;
		if (depth > 0)
		{
			calculateChunkOverlaps(overlaps, depth-1);
		}
		trimCollisionGeometryInternal(chunkIndexList.begin(), chunkIndexList.size(), overlaps, depth, maxTrimFraction);
	}
}

void DestructibleAssetAuthoringImpl::setToolString(const char* toolString)
{
	if (mParams != NULL)
	{
		NvParameterized::Handle handle(*mParams, "comments");
		PX_ASSERT(handle.isValid());
		if (handle.isValid())
		{
			PX_ASSERT(handle.parameterDefinition()->type() == NvParameterized::TYPE_STRING);
			handle.setParamString(toolString);
		}
	}
}

void DestructibleAssetAuthoringImpl::cookChunks(const DestructibleAssetCookingDesc& cookingDesc, bool cacheOverlaps, uint32_t* chunkIndexMapUser2Apex, uint32_t* chunkIndexMapApex2User, uint32_t chunkIndexMapCount)
{
	if (!cookingDesc.isValid())
	{
		APEX_INVALID_PARAMETER("DestructibleAssetAuthoring::cookChunks: cookingDesc invalid.");
		return;
	}

	const uint32_t numChunks = cookingDesc.chunkDescCount;
	const uint32_t numBehaviorGroups = cookingDesc.behaviorGroupDescCount;
	const uint32_t numParts = renderMeshAsset->getPartCount();

	if ((chunkIndexMapUser2Apex != NULL || chunkIndexMapApex2User != NULL) && chunkIndexMapCount < numChunks)
	{
		APEX_INVALID_PARAMETER("DestructibleAssetAuthoring::cookChunks: chunkIndexMap is not big enough.");
		return;
	}

	NvParameterized::Handle handle(*mParams);

	mParams->getParameterHandle("chunks", handle);
	mParams->resizeArray(handle, (int32_t)numChunks);
	mParams->depthCount = 0;

	// Create convex hulls
	mParams->getParameterHandle("chunkConvexHulls", handle);
	mParams->resizeArray(handle, 0);
	chunkConvexHulls.reset();

	mParams->getParameterHandle("chunkConvexHullStartIndices", handle);
	mParams->resizeArray(handle, (int32_t)numParts + 1);
	for (uint32_t partIndex = 0; partIndex <= numParts; ++partIndex)
	{
		mParams->chunkConvexHullStartIndices.buf[partIndex] = 0;	// Initialize all to zero, so that the random-access rebuildCollisionGeometry does the right thing (below)
	}
	for (uint32_t partIndex = 0; partIndex < numParts; ++partIndex)
	{
		if (!rebuildCollisionGeometry(partIndex, cookingDesc.geometryDescs[partIndex]))
		{
			APEX_INVALID_PARAMETER("DestructibleAssetAuthoring::cookChunks: Could not find or generate collision hull for part.");
		}
	}

	// Sort - chunks must be in parent-sorted order
	Array<ChunkSortElement> sortElements;
	sortElements.resize(numChunks);
	for (uint32_t i = 0; i < numChunks; ++i)
	{
		const DestructibleChunkDesc& chunkDesc = cookingDesc.chunkDescs[i];
		sortElements[i].index = (int32_t)i;
		sortElements[i].parentIndex = chunkDesc.parentIndex;
		sortElements[i].depth = 0;
		int32_t parent = (int32_t)i;
		uint32_t counter = 0;
		while ((parent = cookingDesc.chunkDescs[parent].parentIndex) >= 0)
		{
			++sortElements[i].depth;
			if (++counter > numChunks)
			{
				APEX_INVALID_PARAMETER("DestructibleAssetAuthoring::cookChunks: loop found in cookingDesc parent indices.  Cannot build an DestructibleAsset.");
				return;
			}
		}
	}
	qsort(sortElements.begin(), numChunks, sizeof(ChunkSortElement), compareChunkParents);

	Array<uint32_t> ranks;
	if (chunkIndexMapUser2Apex == NULL && numChunks > 0)
	{
		ranks.resize(numChunks);
		chunkIndexMapUser2Apex = &ranks[0];
	}

	for (uint32_t i = 0; i < numChunks; ++i)
	{
		chunkIndexMapUser2Apex[sortElements[i].index] = i;
		if (chunkIndexMapApex2User != NULL)
		{
			chunkIndexMapApex2User[i] = (uint32_t)sortElements[i].index;
		}
	}

	// Count instanced chunks and allocate instanced info array
	uint32_t instancedChunkCount = 0;
	for (uint32_t i = 0; i < numChunks; ++i)
	{
		const DestructibleChunkDesc& chunkDesc = cookingDesc.chunkDescs[sortElements[i].index];
		if (chunkDesc.useInstancedRendering)
		{
			++instancedChunkCount;
		}
	}

	mParams->getParameterHandle("chunkInstanceInfo", handle);
	mParams->resizeArray(handle, (int32_t)instancedChunkCount);

	mParams->getParameterHandle("scatterMeshIndices", handle);
	mParams->resizeArray(handle, 0);
	mParams->getParameterHandle("scatterMeshTransforms", handle);
	mParams->resizeArray(handle, 0);

	const DestructibleChunkDesc defaultChunkDesc;

	instancedChunkCount = 0;	// reset and use as cursor

	for (uint32_t i = 0; i < numChunks; ++i)
	{
		DestructibleAssetParametersNS::Chunk_Type& chunk = mParams->chunks.buf[i];
		const DestructibleChunkDesc& chunkDesc = cookingDesc.chunkDescs[sortElements[i].index];
		chunk.flags = 0;
		if (chunkDesc.isSupportChunk)
		{
			chunk.flags |= SupportChunk;
		}
		if (chunkDesc.doNotFracture)
		{
			chunk.flags |= UnfracturableChunk;
		}
		if (chunkDesc.doNotDamage)
		{
			chunk.flags |= UndamageableChunk;
		}
		if (chunkDesc.doNotCrumble)
		{
			chunk.flags |= UncrumbleableChunk;
		}
#if APEX_RUNTIME_FRACTURE
		if (chunkDesc.runtimeFracture)
		{
			chunk.flags |= RuntimeFracturableChunk;
		}
#endif
		if (!chunkDesc.useInstancedRendering)
		{
			// Not instanced, meshPartIndex will be used to directly access the mesh part in the "normal" mesh
			chunk.meshPartIndex = chunkDesc.meshIndex;
		}
		else
		{
			// Instanced, meshPartIndex will be used to access instance info
			chunk.flags |= Instanced;
			chunk.meshPartIndex = (uint16_t)instancedChunkCount++;
			DestructibleAssetParametersNS::InstanceInfo_Type& instanceInfo = mParams->chunkInstanceInfo.buf[chunk.meshPartIndex];
			instanceInfo.partIndex = chunkDesc.meshIndex;
			instanceInfo.chunkPositionOffset = chunkDesc.instancePositionOffset;
			instanceInfo.chunkUVOffset = chunkDesc.instanceUVOffset;
		}
		if (sortElements[i].index == 0)
		{
			chunk.depth = 0;
			chunk.parentIndex = DestructibleAssetImpl::InvalidChunkIndex;
		}
		else
		{
			chunk.parentIndex = (uint16_t)chunkIndexMapUser2Apex[(int16_t)chunkDesc.parentIndex];
			DestructibleAssetParametersNS::Chunk_Type& parent = mParams->chunks.buf[chunk.parentIndex];
			PX_ASSERT(chunk.parentIndex >= mParams->chunks.buf[i - 1].parentIndex ||
			          mParams->chunks.buf[i - 1].parentIndex == DestructibleAssetImpl::InvalidChunkIndex);	// Parent-sorted order
			if (chunk.parentIndex != mParams->chunks.buf[i - 1].parentIndex)
			{
				parent.firstChildIndex = (uint16_t)i;
			}
			++parent.numChildren;
			chunk.depth = uint16_t(parent.depth + 1);
			if ((parent.flags & SupportChunk) != 0)
			{
				chunk.flags |= SupportChunk;	// All children of support chunks can be support chunks
			}
			if ((parent.flags & UnfracturableChunk) != 0)
			{
				chunk.flags |= UnfracturableChunk;	// All children of unfracturable chunks are unfracturable
			}
#if APEX_RUNTIME_FRACTURE
			if ((parent.flags & RuntimeFracturableChunk) != 0) // Runtime fracturable chunks cannot have any children
			{
				PX_ALWAYS_ASSERT();
			}
#endif
		}
		if ((chunk.flags & UnfracturableChunk) != 0)
		{
			// All ancestors of unfracturable chunks must be unfracturable or note that they have an unfracturable descendant
			uint16_t parentIndex = chunk.parentIndex;
			while (parentIndex != DestructibleAssetImpl::InvalidChunkIndex)
			{
				DestructibleAssetParametersNS::Chunk_Type& parent = mParams->chunks.buf[parentIndex];
				if ((parent.flags & UnfracturableChunk) == 0)
				{
					parent.flags |= DescendantUnfractureable;
				}
				parentIndex = parent.parentIndex;
			}
		}
		chunk.numChildren = 0;
		chunk.firstChildIndex = DestructibleAssetImpl::InvalidChunkIndex;
		mParams->depthCount = PxMax((uint16_t)mParams->depthCount, (uint16_t)(chunk.depth + 1));
		chunk.surfaceNormal = chunkDesc.surfaceNormal;
		chunk.behaviorGroupIndex = chunkDesc.behaviorGroupIndex;

		// Default behavior is to take on the parent's behavior group
		if (chunk.parentIndex != DestructibleAssetImpl::InvalidChunkIndex)
		{
			if (chunk.behaviorGroupIndex < 0)
			{
				chunk.behaviorGroupIndex = mParams->chunks.buf[chunk.parentIndex].behaviorGroupIndex;
			}
		}

		// Scatter mesh
		const int32_t oldScatterMeshCount = mParams->scatterMeshIndices.arraySizes[0];
		chunk.firstScatterMesh = (uint16_t)oldScatterMeshCount;
		chunk.scatterMeshCount = (uint16_t)chunkDesc.scatterMeshCount;
		if (chunk.scatterMeshCount > 0)
		{
			mParams->getParameterHandle("scatterMeshIndices", handle);
			mParams->resizeArray(handle, oldScatterMeshCount + (int32_t)chunk.scatterMeshCount);
			handle.setParamU8Array(chunkDesc.scatterMeshIndices, (int32_t)chunk.scatterMeshCount, oldScatterMeshCount);
			mParams->getParameterHandle("scatterMeshTransforms", handle);
			mParams->resizeArray(handle, oldScatterMeshCount + (int32_t)chunk.scatterMeshCount);
			for (uint16_t tmNum = 0; tmNum < chunk.scatterMeshCount; ++tmNum)
			{
				mParams->scatterMeshTransforms.buf[oldScatterMeshCount + tmNum] = chunkDesc.scatterMeshTransforms[tmNum];
			}
		}
	}
	
	mParams->getParameterHandle("behaviorGroups", handle);
	mParams->resizeArray(handle, (int32_t)numBehaviorGroups);

	struct {
		void operator() (const DestructibleBehaviorGroupDesc& behaviorGroupDesc, DestructibleAssetParameters* params, NvParameterized::Handle& elementHandle)
		{
			NvParameterized::Handle subElementHandle(*params);

			elementHandle.getChildHandle(params, "name", subElementHandle);
			params->setParamString(subElementHandle, behaviorGroupDesc.name);

			elementHandle.getChildHandle(params, "damageThreshold", subElementHandle);
			params->setParamF32(subElementHandle, behaviorGroupDesc.damageThreshold);
			
			elementHandle.getChildHandle(params, "damageToRadius", subElementHandle);
			params->setParamF32(subElementHandle, behaviorGroupDesc.damageToRadius);

			elementHandle.getChildHandle(params, "damageSpread.minimumRadius", subElementHandle);
			params->setParamF32(subElementHandle, behaviorGroupDesc.damageSpread.minimumRadius);

			elementHandle.getChildHandle(params, "damageSpread.radiusMultiplier", subElementHandle);
			params->setParamF32(subElementHandle, behaviorGroupDesc.damageSpread.radiusMultiplier);

			elementHandle.getChildHandle(params, "damageSpread.falloffExponent", subElementHandle);
			params->setParamF32(subElementHandle, behaviorGroupDesc.damageSpread.falloffExponent);

			elementHandle.getChildHandle(params, "damageColorSpread.minimumRadius", subElementHandle);
			params->setParamF32(subElementHandle, behaviorGroupDesc.damageColorSpread.minimumRadius);

			elementHandle.getChildHandle(params, "damageColorSpread.radiusMultiplier", subElementHandle);
			params->setParamF32(subElementHandle, behaviorGroupDesc.damageColorSpread.radiusMultiplier);

			elementHandle.getChildHandle(params, "damageColorSpread.falloffExponent", subElementHandle);
			params->setParamF32(subElementHandle, behaviorGroupDesc.damageColorSpread.falloffExponent);

			elementHandle.getChildHandle(params, "damageColorChange", subElementHandle);
			params->setParamVec4(subElementHandle, behaviorGroupDesc.damageColorChange);

			elementHandle.getChildHandle(params, "materialStrength", subElementHandle);
			params->setParamF32(subElementHandle, behaviorGroupDesc.materialStrength);

			elementHandle.getChildHandle(params, "density", subElementHandle);
			params->setParamF32(subElementHandle, behaviorGroupDesc.density);

			elementHandle.getChildHandle(params, "fadeOut", subElementHandle);
			params->setParamF32(subElementHandle, behaviorGroupDesc.fadeOut);

			elementHandle.getChildHandle(params, "maxDepenetrationVelocity", subElementHandle);
			params->setParamF32(subElementHandle, behaviorGroupDesc.maxDepenetrationVelocity);

			elementHandle.getChildHandle(params, "userData", subElementHandle);
			params->setParamU64(subElementHandle, behaviorGroupDesc.userData);
		}
	} ConvertBehaviorGroupDesc; // local function definitions illegal, eh?

	const uint32_t bufferCount = 128;
	char buffer[bufferCount] = {0};

	for (uint32_t i = 0; i < numBehaviorGroups; ++i)
	{
		const DestructibleBehaviorGroupDesc& chunkDesc = cookingDesc.behaviorGroupDescs[i];
		NvParameterized::Handle elementHandle(*mParams);

		shdfnd::snprintf(buffer, bufferCount, "behaviorGroups[%d]", i);
		mParams->getParameterHandle(buffer, elementHandle);

		ConvertBehaviorGroupDesc(chunkDesc, mParams, elementHandle);
	}

	mParams->getParameterHandle("defaultBehaviorGroup", handle);
	ConvertBehaviorGroupDesc(cookingDesc.defaultBehaviorGroupDesc, mParams, handle);

	mParams->RTFractureBehaviorGroup = cookingDesc.RTFractureBehaviorGroup;


	// Fill in default destructible parameters up to depth
	int oldDepthParametersSize = mParams->depthParameters.arraySizes[0];
	if (oldDepthParametersSize < (int)mParams->depthCount)
	{
		NvParameterized::Handle depthParametersHandle(*mParams);
		mParams->getParameterHandle("depthParameters", depthParametersHandle);
		mParams->resizeArray(depthParametersHandle, (int32_t)mParams->depthCount);
		for (int i = oldDepthParametersSize; i < (int)mParams->depthCount; ++i)
		{
			DestructibleAssetParametersNS::DestructibleDepthParameters_Type& depthParameters = mParams->depthParameters.buf[i];
			depthParameters.OVERRIDE_IMPACT_DAMAGE = false;
			depthParameters.OVERRIDE_IMPACT_DAMAGE_VALUE = false;
			depthParameters.IGNORE_POSE_UPDATES = false;
			depthParameters.IGNORE_RAYCAST_CALLBACKS = false;
			depthParameters.IGNORE_CONTACT_CALLBACKS = false;
			depthParameters.USER_FLAG_0 = false;
			depthParameters.USER_FLAG_1 = false;
			depthParameters.USER_FLAG_2 = false;
			depthParameters.USER_FLAG_3 = false;
		}
	}

	// Build collision data and bounds
	float skinWidth = 0.0025f;	// Default value
	if (GetApexSDK()->getCookingInterface())
	{
		const PxCookingParams& cookingParams = GetApexSDK()->getCookingInterface()->getParams();
		skinWidth = cookingParams.skinWidth;
	}

	mParams->bounds.setEmpty();
	for (uint32_t partIndex = 0; partIndex < numParts; ++partIndex)
	{
		const DestructibleGeometryDesc& geometryDesc = cookingDesc.geometryDescs[partIndex];
		const uint32_t startHullIndex = mParams->chunkConvexHullStartIndices.buf[partIndex];
		for (uint32_t hullIndex = 0; hullIndex < geometryDesc.convexHullCount; ++hullIndex)
		{
			ConvexHullImpl& chunkHullData = chunkConvexHulls[startHullIndex + hullIndex];
			PartConvexHullProxy* convexHullProxy = (PartConvexHullProxy*)geometryDesc.convexHulls[hullIndex];
			chunkHullData.mParams->copy(*convexHullProxy->impl.mParams);
			if (chunkHullData.isEmpty())
			{
				chunkHullData.buildFromAABB(renderMeshAsset->getBounds(partIndex));	// \todo: need better way of simplifying
			}
		}
	}

	for (uint32_t chunkIndex = 0; chunkIndex < numChunks; ++chunkIndex)
	{
		DestructibleAssetParametersNS::Chunk_Type& chunk = mParams->chunks.buf[chunkIndex];
		PxBounds3 bounds = getChunkActorLocalBounds(chunkIndex);
		mParams->bounds.include(bounds);
		chunk.surfaceNormal = PxVec3(0.0f);
	}
	PX_ASSERT(!mParams->bounds.isEmpty());
	mParams->bounds.fattenFast(skinWidth);

	mParams->originalDepthCount = mParams->depthCount;

	calculateChunkDepthStarts();

	if (cacheOverlaps)
	{
		cacheChunkOverlapsUpToDepth(chunkOverlapCacheDepth);
	}

	Array<IntPair> supportGraphEdgesInternal(cookingDesc.supportGraphEdgeCount);
	if (cookingDesc.supportGraphEdgeCount > 0)
	{
		for (uint32_t i = 0; i < cookingDesc.supportGraphEdgeCount; ++i)
		{
			supportGraphEdgesInternal[i].i0 = (int32_t)chunkIndexMapUser2Apex[(uint32_t)cookingDesc.supportGraphEdges[i].i0];
			supportGraphEdgesInternal[i].i1 = (int32_t)chunkIndexMapUser2Apex[(uint32_t)cookingDesc.supportGraphEdges[i].i1];
		}

		addChunkOverlaps(&supportGraphEdgesInternal[0], supportGraphEdgesInternal.size());
	}

	m_needsScatterMeshInstanceInfoCreation = true;
}

void DestructibleAssetAuthoringImpl::serializeFractureToolState(PxFileBuf& stream, nvidia::ExplicitHierarchicalMesh::Embedding& embedding) const
{
	stream.storeDword((uint32_t)ApexStreamVersion::Current);
	hMesh.serialize(stream, embedding);
	hMeshCore.serialize(stream, embedding);
	cutoutSet.serialize(stream);
}

void DestructibleAssetAuthoringImpl::deserializeFractureToolState(PxFileBuf& stream, nvidia::ExplicitHierarchicalMesh::Embedding& embedding)
{
	const uint32_t version = stream.readDword();
	PX_UNUSED(version);	// Initial version

	hMesh.deserialize(stream, embedding);
	hMeshCore.deserialize(stream, embedding);
	cutoutSet.deserialize(stream);
}
#endif

NvParameterized::Interface* DestructibleAssetImpl::getDefaultActorDesc()
{
	NvParameterized::Interface* ret = 0;

	NvParameterized::Traits* traits = GetInternalApexSDK()->getParameterizedTraits();

	// non-optimal.  Should use a copy-constructor so this only gets built once.
	if (!mApexDestructibleActorParams && traits)
	{
		mApexDestructibleActorParams = traits->createNvParameterized(DestructibleActorParam::staticClassName());
	}

	if (traits)
	{
		if (mApexDestructibleActorParams)
		{
			ret = mApexDestructibleActorParams;
			DestructibleActorParam* p = static_cast<DestructibleActorParam*>(ret);
			DestructibleActorParamNS::ParametersStruct* ps = static_cast<DestructibleActorParamNS::ParametersStruct*>(p);

			{
				NvParameterized::Handle handle(*p);
				if (p->getParameterHandle("crumbleEmitterName", handle) == NvParameterized::ERROR_NONE)
				{
					p->setParamString(handle, getCrumbleEmitterName());
				}
			}

			{
				NvParameterized::Handle handle(*p);
				if (p->getParameterHandle("dustEmitterName", handle) == NvParameterized::ERROR_NONE)
				{
					p->setParamString(handle, getDustEmitterName());
				}
			}

			DestructibleParameters destructibleParameters = getParameters();

			ps->destructibleParameters.damageCap								= destructibleParameters.damageCap;
			ps->destructibleParameters.forceToDamage							= destructibleParameters.forceToDamage;
			ps->destructibleParameters.impactVelocityThreshold					= destructibleParameters.impactVelocityThreshold;
			ps->destructibleParameters.minimumFractureDepth						= destructibleParameters.minimumFractureDepth;
			ps->destructibleParameters.damageDepthLimit							= destructibleParameters.damageDepthLimit;
			ps->destructibleParameters.impactDamageDefaultDepth					= destructibleParameters.impactDamageDefaultDepth;
			ps->destructibleParameters.debrisDepth								= destructibleParameters.debrisDepth;
			ps->destructibleParameters.essentialDepth							= destructibleParameters.essentialDepth;
			ps->destructibleParameters.debrisLifetimeMin						= destructibleParameters.debrisLifetimeMin;
			ps->destructibleParameters.debrisLifetimeMax						= destructibleParameters.debrisLifetimeMax;
			ps->destructibleParameters.debrisMaxSeparationMin					= destructibleParameters.debrisMaxSeparationMin;
			ps->destructibleParameters.debrisMaxSeparationMax					= destructibleParameters.debrisMaxSeparationMax;
			ps->destructibleParameters.dynamicChunksGroupsMask.useGroupsMask	= destructibleParameters.useDynamicChunksGroupsMask;
			ps->destructibleParameters.debrisDestructionProbability             = destructibleParameters.debrisDestructionProbability;
			ps->destructibleParameters.dynamicChunkDominanceGroup				= destructibleParameters.dynamicChunksDominanceGroup;
			ps->destructibleParameters.dynamicChunksGroupsMask.bits0			= destructibleParameters.dynamicChunksFilterData.word0;
			ps->destructibleParameters.dynamicChunksGroupsMask.bits1			= destructibleParameters.dynamicChunksFilterData.word1;
			ps->destructibleParameters.dynamicChunksGroupsMask.bits2			= destructibleParameters.dynamicChunksFilterData.word2;
			ps->destructibleParameters.dynamicChunksGroupsMask.bits3			= destructibleParameters.dynamicChunksFilterData.word3;
			ps->destructibleParameters.supportStrength							= destructibleParameters.supportStrength;
			ps->destructibleParameters.legacyChunkBoundsTestSetting				= destructibleParameters.legacyChunkBoundsTestSetting;
			ps->destructibleParameters.legacyDamageRadiusSpreadSetting			= destructibleParameters.legacyDamageRadiusSpreadSetting;
			ps->destructibleParameters.validBounds								= destructibleParameters.validBounds;
			ps->destructibleParameters.maxChunkSpeed							= destructibleParameters.maxChunkSpeed;
			ps->destructibleParameters.flags.ACCUMULATE_DAMAGE					= (destructibleParameters.flags & DestructibleParametersFlag::ACCUMULATE_DAMAGE) ? true : false;
			ps->destructibleParameters.flags.DEBRIS_TIMEOUT						= (destructibleParameters.flags & DestructibleParametersFlag::DEBRIS_TIMEOUT) ? true : false;
			ps->destructibleParameters.flags.DEBRIS_MAX_SEPARATION				= (destructibleParameters.flags & DestructibleParametersFlag::DEBRIS_MAX_SEPARATION) ? true : false;
			ps->destructibleParameters.flags.CRUMBLE_SMALLEST_CHUNKS			= (destructibleParameters.flags & DestructibleParametersFlag::CRUMBLE_SMALLEST_CHUNKS) ? true : false;
			ps->destructibleParameters.flags.ACCURATE_RAYCASTS					= (destructibleParameters.flags & DestructibleParametersFlag::ACCURATE_RAYCASTS) ? true : false;
			ps->destructibleParameters.flags.USE_VALID_BOUNDS					= (destructibleParameters.flags & DestructibleParametersFlag::USE_VALID_BOUNDS) ? true : false;
			ps->destructibleParameters.flags.CRUMBLE_VIA_RUNTIME_FRACTURE			= (destructibleParameters.flags & DestructibleParametersFlag::CRUMBLE_VIA_RUNTIME_FRACTURE) ? true : false;

			ps->supportDepth			= mParams->supportDepth;
			ps->formExtendedStructures	= mParams->formExtendedStructures;
			ps->useAssetDefinedSupport	= mParams->useAssetDefinedSupport;
			ps->useWorldSupport			= mParams->useWorldSupport;

			// RT Fracture Parameters
			ps->destructibleParameters.runtimeFracture.sheetFracture			= destructibleParameters.rtFractureParameters.sheetFracture;
			ps->destructibleParameters.runtimeFracture.depthLimit				= destructibleParameters.rtFractureParameters.depthLimit;
			ps->destructibleParameters.runtimeFracture.destroyIfAtDepthLimit	= destructibleParameters.rtFractureParameters.destroyIfAtDepthLimit;
			ps->destructibleParameters.runtimeFracture.minConvexSize			= destructibleParameters.rtFractureParameters.minConvexSize;
			ps->destructibleParameters.runtimeFracture.impulseScale				= destructibleParameters.rtFractureParameters.impulseScale;
			ps->destructibleParameters.runtimeFracture.glass.numSectors			= destructibleParameters.rtFractureParameters.glass.numSectors;
			ps->destructibleParameters.runtimeFracture.glass.sectorRand			= destructibleParameters.rtFractureParameters.glass.sectorRand;
			ps->destructibleParameters.runtimeFracture.glass.firstSegmentSize	= destructibleParameters.rtFractureParameters.glass.firstSegmentSize;
			ps->destructibleParameters.runtimeFracture.glass.segmentScale		= destructibleParameters.rtFractureParameters.glass.segmentScale;
			ps->destructibleParameters.runtimeFracture.glass.segmentRand		= destructibleParameters.rtFractureParameters.glass.segmentRand;
			ps->destructibleParameters.runtimeFracture.attachment.posX			= destructibleParameters.rtFractureParameters.attachment.posX;
			ps->destructibleParameters.runtimeFracture.attachment.negX			= destructibleParameters.rtFractureParameters.attachment.negX;
			ps->destructibleParameters.runtimeFracture.attachment.posY			= destructibleParameters.rtFractureParameters.attachment.posY;
			ps->destructibleParameters.runtimeFracture.attachment.negY			= destructibleParameters.rtFractureParameters.attachment.negY;
			ps->destructibleParameters.runtimeFracture.attachment.posZ			= destructibleParameters.rtFractureParameters.attachment.posZ;
			ps->destructibleParameters.runtimeFracture.attachment.negZ			= destructibleParameters.rtFractureParameters.attachment.negZ;

			uint32_t depth = destructibleParameters.depthParametersCount;
			if (depth > 0)
			{
				NvParameterized::Handle handle(*p);
				if (p->getParameterHandle("depthParameters", handle) == NvParameterized::ERROR_NONE)
				{
					p->resizeArray(handle, (int32_t)depth);
					for (uint32_t i = 0; i < depth; i++)
					{
						const DestructibleDepthParameters& dparm = destructibleParameters.depthParameters[i];
						ps->depthParameters.buf[i].OVERRIDE_IMPACT_DAMAGE		= (dparm.flags & DestructibleDepthParametersFlag::OVERRIDE_IMPACT_DAMAGE) ? true : false;
						ps->depthParameters.buf[i].OVERRIDE_IMPACT_DAMAGE_VALUE	= (dparm.flags & DestructibleDepthParametersFlag::OVERRIDE_IMPACT_DAMAGE_VALUE) ? true : false;
						ps->depthParameters.buf[i].IGNORE_POSE_UPDATES			= (dparm.flags & DestructibleDepthParametersFlag::IGNORE_POSE_UPDATES) ? true : false;
						ps->depthParameters.buf[i].IGNORE_RAYCAST_CALLBACKS		= (dparm.flags & DestructibleDepthParametersFlag::IGNORE_RAYCAST_CALLBACKS) ? true : false;
						ps->depthParameters.buf[i].IGNORE_CONTACT_CALLBACKS		= (dparm.flags & DestructibleDepthParametersFlag::IGNORE_CONTACT_CALLBACKS) ? true : false;
						ps->depthParameters.buf[i].USER_FLAG_0					= (dparm.flags & DestructibleDepthParametersFlag::USER_FLAG_0) ? true : false;
						ps->depthParameters.buf[i].USER_FLAG_1					= (dparm.flags & DestructibleDepthParametersFlag::USER_FLAG_1) ? true : false;
						ps->depthParameters.buf[i].USER_FLAG_2					= (dparm.flags & DestructibleDepthParametersFlag::USER_FLAG_2) ? true : false;
						ps->depthParameters.buf[i].USER_FLAG_3					= (dparm.flags & DestructibleDepthParametersFlag::USER_FLAG_3) ? true : false;
					}
				}
			}

			{
				NvParameterized::Handle handle(*p);
				if (p->getParameterHandle("behaviorGroups", handle) == NvParameterized::ERROR_NONE)
				{
					uint32_t behaviorGroupArraySize = (uint32_t)mParams->behaviorGroups.arraySizes[0];
					p->resizeArray(handle, (int32_t)behaviorGroupArraySize);

					struct {
						void operator() (const DestructibleAssetParametersNS::BehaviorGroup_Type& src,
										 DestructibleActorParamNS::BehaviorGroup_Type& dest)
						{
							dest.damageThreshold = src.damageThreshold;
							dest.damageToRadius = src.damageToRadius;
							dest.damageSpread.minimumRadius = src.damageSpread.minimumRadius;
							dest.damageSpread.radiusMultiplier = src.damageSpread.radiusMultiplier;
							dest.damageSpread.falloffExponent = src.damageSpread.falloffExponent;
							dest.materialStrength = src.materialStrength;
							dest.density = src.density;
							dest.fadeOut = src.fadeOut;
							dest.maxDepenetrationVelocity = src.maxDepenetrationVelocity;
						}						
					} ConvertBehaviorGroup;

					ConvertBehaviorGroup(mParams->defaultBehaviorGroup, ps->defaultBehaviorGroup);
					for (uint32_t i = 0; i < behaviorGroupArraySize; i++)
					{
						ConvertBehaviorGroup(mParams->behaviorGroups.buf[i],
											 ps->behaviorGroups.buf[i]);
					}
				}
			}
		}
	}
	return ret;
}

NvParameterized::Interface* DestructibleAssetImpl::getDefaultAssetPreviewDesc()
{
	NvParameterized::Interface* ret = NULL;

	if (module != NULL)
	{
		ret = module->getApexDestructiblePreviewParams();

		if (ret != NULL)
		{
			ret->initDefaults();
		}
	}

	return ret;
}

bool DestructibleAssetImpl::isValidForActorCreation(const ::NvParameterized::Interface& params, Scene& /*apexScene*/) const
{
	return nvidia::strcmp(params.className(), DestructibleActorParam::staticClassName()) == 0 ||
	       nvidia::strcmp(params.className(), DestructibleActorState::staticClassName()) == 0;
}

Actor* DestructibleAssetImpl::createApexActor(const NvParameterized::Interface& params, Scene& apexScene)
{
	if (!isValidForActorCreation(params, apexScene))
	{
		return NULL;
	}

	return createDestructibleActor(params, apexScene);
}

AssetPreview* DestructibleAssetImpl::createApexAssetPreview(const NvParameterized::Interface& params, AssetPreviewScene* /*previewScene*/)
{
	DestructiblePreviewProxy* proxy = NULL;

	proxy = PX_NEW(DestructiblePreviewProxy)(*this, m_previewList, &params);
	PX_ASSERT(proxy != NULL);

	return proxy;
}

void DestructibleAssetImpl::appendActorTransforms(const PxMat44* transforms, uint32_t transformCount)
		{
	NvParameterized::Handle handle(*mParams);
	mParams->getParameterHandle("actorTransforms", handle);
	const int32_t oldSize = mParams->actorTransforms.arraySizes[0];
	mParams->resizeArray(handle, (int32_t)(oldSize + transformCount));
	mParams->setParamMat44Array(handle, transforms, (int32_t)transformCount, oldSize);
		}

void DestructibleAssetImpl::clearActorTransforms()
{
	NvParameterized::Handle handle(*mParams);
	mParams->getParameterHandle("actorTransforms", handle);
	mParams->resizeArray(handle, 0);
}

bool DestructibleAssetImpl::chunksInProximity(const DestructibleAssetImpl& asset0, uint16_t chunkIndex0, const PxTransform& tm0, const PxVec3& scale0,
        const DestructibleAssetImpl& asset1, uint16_t chunkIndex1, const PxTransform& tm1, const PxVec3& scale1,
        float padding)
{
	PX_ASSERT(asset0.mParams != NULL);
	PX_ASSERT(asset1.mParams != NULL);

	// Offset chunks (in case they are instanced)
	PxTransform effectiveTM0(tm0);
	effectiveTM0.p = tm0.p + tm0.rotate(scale0.multiply(asset0.getChunkPositionOffset(chunkIndex0)));

	PxTransform effectiveTM1(tm1);
	effectiveTM1.p = tm1.p + tm1.rotate(scale1.multiply(asset1.getChunkPositionOffset(chunkIndex1)));

	for (uint32_t hullIndex0 = asset0.getChunkHullIndexStart(chunkIndex0); hullIndex0 < asset0.getChunkHullIndexStop(chunkIndex0); ++hullIndex0)
	{
		for (uint32_t hullIndex1 = asset1.getChunkHullIndexStart(chunkIndex1); hullIndex1 < asset1.getChunkHullIndexStop(chunkIndex1); ++hullIndex1)
		{
			if (ConvexHullImpl::hullsInProximity(asset0.chunkConvexHulls[hullIndex0], effectiveTM0, scale0, asset1.chunkConvexHulls[hullIndex1], effectiveTM1, scale1, padding))
			{
				return true;
			}
		}
	}
	return false;
}

bool DestructibleAssetImpl::chunkAndSphereInProximity(uint16_t chunkIndex, const PxTransform& chunkTM, const PxVec3& chunkScale, 
												  const PxVec3& sphereWorldCenter, float sphereRadius, float padding, float* distance)
{
	// Offset chunk (in case it is instanced)
	PxTransform effectiveTM = chunkTM;
	effectiveTM.p = chunkTM.p + chunkTM.rotate(chunkScale.multiply(getChunkPositionOffset(chunkIndex)));

	ConvexHullImpl::Separation testSeparation;
	ConvexHullImpl::Separation* testSeparationPtr = distance != NULL? &testSeparation : NULL;
	bool result = false;
	for (uint32_t hullIndex = getChunkHullIndexStart(chunkIndex); hullIndex < getChunkHullIndexStop(chunkIndex); ++hullIndex)
	{
		if (chunkConvexHulls[hullIndex].sphereInProximity(effectiveTM, chunkScale, sphereWorldCenter, sphereRadius, padding, testSeparationPtr))
		{
			result = true;
			if (distance != NULL)
			{
				const float testDistance = testSeparation.getDistance();
				if (testDistance < *distance)
				{
					*distance = testDistance;
				}
			}
		}
	}
	return result;
}


/*
	DestructibleAssetCollision
*/


DestructibleAssetCollision::DestructibleAssetCollision() :
	mAsset(NULL)
{
	NvParameterized::Traits* traits = GetInternalApexSDK()->getParameterizedTraits();
	mParams = DYNAMIC_CAST(DestructibleAssetCollisionDataSet*)(traits->createNvParameterized(DestructibleAssetCollisionDataSet::staticClassName()));
	mOwnsParams = mParams != NULL;
	PX_ASSERT(mOwnsParams);
}

DestructibleAssetCollision::DestructibleAssetCollision(NvParameterized::Interface* params) :
	mAsset(NULL)
{
	mParams = DYNAMIC_CAST(DestructibleAssetCollisionDataSet*)(params);
	mOwnsParams = false;
}

DestructibleAssetCollision::~DestructibleAssetCollision()
{
	resize(0);

	if (mParams != NULL && mOwnsParams)
	{
		mParams->destroy();
	}
	mParams = NULL;
	mOwnsParams = false;
}

void DestructibleAssetCollision::setDestructibleAssetToCook(DestructibleAssetImpl* asset)
{
	if (asset == NULL || getAssetName() == NULL || nvidia::strcmp(asset->getName(), getAssetName()))
	{
		resize(0);
	}

	mAsset = asset;

	NvParameterized::Handle handle(*mParams);
	mParams->getParameterHandle("assetName", handle);
	mParams->setParamString(handle, mAsset != NULL ? mAsset->getName() : "");
}

void DestructibleAssetCollision::resize(uint32_t hullCount)
{
	for (uint32_t i = 0; i < mConvexMeshContainer.size(); ++i)
	{
		physx::Array< PxConvexMesh* >& convexMeshSet = mConvexMeshContainer[i];
		for (uint32_t j = hullCount; j < convexMeshSet.size(); ++j)
		{
			if (convexMeshSet[j] != NULL)
			{
				convexMeshSet[j]->release();
			}
		}
		mConvexMeshContainer[i].resize(hullCount);
	}

	NvParameterized::Traits* traits = GetInternalApexSDK()->getParameterizedTraits();
	for (int i = 0; i < mParams->meshCookedCollisionStreamsAtScale.arraySizes[0]; ++i)
	{
		MeshCookedCollisionStreamsAtScale* streamsAtScale = DYNAMIC_CAST(MeshCookedCollisionStreamsAtScale*)(mParams->meshCookedCollisionStreamsAtScale.buf[i]);
		if (streamsAtScale == NULL)
		{
			streamsAtScale = DYNAMIC_CAST(MeshCookedCollisionStreamsAtScale*)(traits->createNvParameterized(MeshCookedCollisionStreamsAtScale::staticClassName()));
			mParams->meshCookedCollisionStreamsAtScale.buf[i] = streamsAtScale;
		}
		NvParameterized::Handle handle(*streamsAtScale);
		streamsAtScale->getParameterHandle("meshCookedCollisionStreams", handle);

		// resizing PxParam ref arrays doesn't call destroy(), do this here
		int32_t currentArraySize = 0;
		streamsAtScale->getArraySize(handle, currentArraySize);
		for (int j = currentArraySize - 1; j >= (int32_t)hullCount; j--)
		{
			NvParameterized::Interface*& hullStream = streamsAtScale->meshCookedCollisionStreams.buf[j];
			if (hullStream != NULL)
			{
				hullStream->destroy();
			}
			hullStream = NULL;
		}
		streamsAtScale->resizeArray(handle, (int32_t)hullCount);
	}
}

bool DestructibleAssetCollision::addScale(const PxVec3& scale)
{
	if (getScaleIndex(scale, kDefaultDestructibleAssetCollisionScaleTolerance) >= 0)
	{
		return false;	// Scale already exists
	}

	int scaleIndex = mParams->scales.arraySizes[0];

	NvParameterized::Handle handle(*mParams);
	mParams->getParameterHandle("scales", handle);
	mParams->resizeArray(handle, scaleIndex + 1);
	mParams->getParameterHandle("meshCookedCollisionStreamsAtScale", handle);
	mParams->resizeArray(handle, scaleIndex + 1);

	mConvexMeshContainer.resize((uint32_t)scaleIndex + 1);

	mParams->scales.buf[(uint32_t)scaleIndex] = scale;
	mParams->meshCookedCollisionStreamsAtScale.buf[(uint32_t)scaleIndex] = NULL;
	mConvexMeshContainer[(uint32_t)scaleIndex].reset();

	return true;
}

bool DestructibleAssetCollision::cookAll()
{
	bool result = true;
	for (int i = 0; i < mParams->scales.arraySizes[0]; ++i)
	{
		if (!cookScale(mParams->scales.buf[i]))
		{
			result = false;
		}
	}

	return result;
}

bool DestructibleAssetCollision::cookScale(const PxVec3& scale)
{
	if (mAsset == NULL)
	{
		return false;
	}

	const int32_t partCount = mAsset->mParams->chunkConvexHullStartIndices.arraySizes[0];
	if (partCount <= 0)
	{
		return false;
	}

	const uint32_t hullCount = mAsset->mParams->chunkConvexHullStartIndices.buf[partCount-1];

	bool result = true;
	for (uint16_t i = 0; i < hullCount; ++i)
	{
		PxConvexMesh* convexMesh = getConvexMesh(i, scale);
		if (convexMesh == NULL)
		{
			result = false;
		}
	}

	return result;
}

PxConvexMesh* DestructibleAssetCollision::getConvexMesh(uint32_t hullIndex, const PxVec3& scale)
{
	int32_t scaleIndex = getScaleIndex(scale, kDefaultDestructibleAssetCollisionScaleTolerance);

	if (scaleIndex >= 0)
	{
		if (scaleIndex < (int32_t)mConvexMeshContainer.size())
		{
			physx::Array<PxConvexMesh*>& convexMeshSet = mConvexMeshContainer[(uint32_t)scaleIndex];
			if (hullIndex < convexMeshSet.size())
			{
				PxConvexMesh* convexMesh = convexMeshSet[hullIndex];
				if (convexMesh != NULL)
				{
					return convexMesh;
				}
			}
		}
	}

	NvParameterized::Handle handle(*mParams);
	NvParameterized::Traits* traits = GetInternalApexSDK()->getParameterizedTraits();

	MeshCookedCollisionStreamsAtScale* streamsAtScale;
	if (scaleIndex < 0)
	{
		scaleIndex = mParams->scales.arraySizes[0];

		mParams->getParameterHandle("scales", handle);
		mParams->resizeArray(handle, scaleIndex + 1);
		mParams->getParameterHandle("meshCookedCollisionStreamsAtScale", handle);
		mParams->resizeArray(handle, scaleIndex + 1);

		mConvexMeshContainer.resize((uint32_t)scaleIndex + 1);

		mParams->scales.buf[(uint32_t)scaleIndex] = scale;
	}

	if (mParams->meshCookedCollisionStreamsAtScale.buf[scaleIndex] != NULL)
	{
		streamsAtScale = DYNAMIC_CAST(MeshCookedCollisionStreamsAtScale*)(mParams->meshCookedCollisionStreamsAtScale.buf[scaleIndex]);
	}
	else
	{
		streamsAtScale = DYNAMIC_CAST(MeshCookedCollisionStreamsAtScale*)(traits->createNvParameterized(MeshCookedCollisionStreamsAtScale::staticClassName()));
		mParams->meshCookedCollisionStreamsAtScale.buf[scaleIndex] = streamsAtScale;
	}

	if (mAsset != NULL && (int)mAsset->chunkConvexHulls.size() != streamsAtScale->meshCookedCollisionStreams.arraySizes[0])
	{
		NvParameterized::Handle streamsHandle(*streamsAtScale);
		streamsAtScale->getParameterHandle("meshCookedCollisionStreams", streamsHandle);
		streamsHandle.resizeArray((int32_t)mAsset->chunkConvexHulls.size());
		mConvexMeshContainer[(uint32_t)scaleIndex].resize(mAsset->chunkConvexHulls.size());
	}

	if ((int)hullIndex >= streamsAtScale->meshCookedCollisionStreams.arraySizes[0])
	{
		return NULL;
	}

	PxConvexMesh* convexMesh = NULL;

	MeshCookedCollisionStream* stream = DYNAMIC_CAST(MeshCookedCollisionStream*)(streamsAtScale->meshCookedCollisionStreams.buf[hullIndex]);
	if (stream == NULL)
	{
		if (mAsset == NULL)
		{
			return NULL;
		}

		stream = DYNAMIC_CAST(MeshCookedCollisionStream*)(traits->createNvParameterized(MeshCookedCollisionStream::staticClassName()));
		streamsAtScale->meshCookedCollisionStreams.buf[hullIndex] = stream;

		PX_PROFILE_ZONE("DestructibleCookChunkCollisionMeshes", GetInternalApexSDK()->getContextId());

		// Update the asset's stats with the number of cooked collision convex meshes
		if (mAsset != NULL)
		{
			++mAsset->mRuntimeCookedConvexCount;
		}

		const ConvexHullImpl& hullData = mAsset->chunkConvexHulls[hullIndex];

		if (hullData.getVertexCount() == 0)
		{
			return NULL;
		}

		Array<PxVec3> scaledPoints;
		scaledPoints.resize(hullData.getVertexCount());
		PxVec3 centroid(0.0f);
		for (uint32_t i = 0; i < scaledPoints.size(); ++i)
		{
			scaledPoints[i] = hullData.getVertex(i);	// Cook at unit scale first
			centroid += scaledPoints[i];
		}
		centroid *= 1.0f/(float)scaledPoints.size();
		for (uint32_t i = 0; i < scaledPoints.size(); ++i)
		{
			scaledPoints[i] -= centroid;
		}

		nvidia::PsMemoryBuffer memStream;
		memStream.setEndianMode(PxFileBuf::ENDIAN_NONE);
		PxStreamFromFileBuf nvs(memStream);
		physx::PxConvexMeshDesc meshDesc;
		meshDesc.points.count = scaledPoints.size();
		meshDesc.points.data = scaledPoints.begin();
		meshDesc.points.stride = sizeof(PxVec3);
		meshDesc.flags = physx::PxConvexFlag::eCOMPUTE_CONVEX;
		const float skinWidth = GetApexSDK()->getCookingInterface() != NULL ? GetApexSDK()->getCookingInterface()->getParams().skinWidth : 0.0f;
		if (skinWidth > 0.0f)
		{
			meshDesc.flags |= physx::PxConvexFlag::eINFLATE_CONVEX;
		}
		bool success = GetApexSDK()->getCookingInterface()->cookConvexMesh(meshDesc, nvs);

		// Now scale all the points, in case this array is used as-is (failure cases)
		for (uint32_t i = 0; i < scaledPoints.size(); ++i)
		{
			scaledPoints[i] += centroid;
			scaledPoints[i] = scaledPoints[i].multiply(scale);
		}

		if (success)
		{
			PxStreamFromFileBuf nvs(memStream);
			convexMesh = GetApexSDK()->getPhysXSDK()->createConvexMesh(nvs);

			// Examine the mass properties to make sure they're reasonable.
			if (convexMesh != NULL)
			{
				float mass;
				PxMat33 localInertia;
				PxVec3 localCenterOfMass;
				convexMesh->getMassInformation(mass, localInertia, localCenterOfMass);
				PxMat33 massFrame;
				const PxVec3 massLocalInertia = diagonalizeSymmetric(massFrame, localInertia);
				success = (mass > 0 && massLocalInertia.x > 0 && massLocalInertia.y > 0 && massLocalInertia.z > 0);
				if (success && massLocalInertia.maxElement() > 4000*massLocalInertia.minElement())
				{
					convexMesh->release();
					convexMesh = NULL;
					success = false;
				}
			}
			else
			{
				success = false;
			}

			if (success)
			{
				// Now scale the convex hull
				memStream.reset();
				memStream.setEndianMode(PxFileBuf::ENDIAN_NONE);
				PxStreamFromFileBuf nvs(memStream);

				const uint32_t numVerts = convexMesh->getNbVertices();
				const PxVec3* verts = convexMesh->getVertices();

				scaledPoints.resize(numVerts);
				for (uint32_t i = 0; i < numVerts; ++i)
				{
					scaledPoints[i] = (verts[i] + centroid).multiply(scale);
				}

				// Unfortunately, we must build our own triangle buffer from the polygon buffer
				uint32_t triangleCount = 0;
				for (uint32_t i = 0; i < convexMesh->getNbPolygons(); ++i)
				{
					physx::PxHullPolygon polygon;
					convexMesh->getPolygonData(i, polygon);
					triangleCount += polygon.mNbVerts - 2;
				}
				const uint8_t* indexBuffer = (const uint8_t*)convexMesh->getIndexBuffer();
				Array<uint32_t> indices;
				indices.reserve(triangleCount*3);
				for (uint32_t i = 0; i < convexMesh->getNbPolygons(); ++i)
				{
					physx::PxHullPolygon polygon;
					convexMesh->getPolygonData(i, polygon);
					for (uint16_t j = 1; j < polygon.mNbVerts-1; ++j)
					{
						indices.pushBack((uint32_t)indexBuffer[polygon.mIndexBase]);
						indices.pushBack((uint32_t)indexBuffer[polygon.mIndexBase+j]);
						indices.pushBack((uint32_t)indexBuffer[polygon.mIndexBase+j+1]);
					}
				}

				physx::PxConvexMeshDesc meshDesc;
				meshDesc.points.count = scaledPoints.size();
				meshDesc.points.data = scaledPoints.begin();
				meshDesc.points.stride = sizeof(PxVec3);
				meshDesc.flags = physx::PxConvexFlag::eCOMPUTE_CONVEX;
				success = GetApexSDK()->getCookingInterface()->cookConvexMesh(meshDesc, nvs);

				convexMesh->release();
				convexMesh = NULL;

				if (success)
				{
					convexMesh = GetApexSDK()->getPhysXSDK()->createConvexMesh(nvs);
				}

				if (convexMesh == NULL)
				{
					success = false;
				}
			}
		}

		if (!success)
		{
			convexMesh = NULL;
			memStream.reset();
			memStream.setEndianMode(PxFileBuf::ENDIAN_NONE);
			PxStreamFromFileBuf nvs(memStream);
			// Just form bbox
			PxBounds3 bounds;
			bounds.setEmpty();
			for (uint32_t i = 0; i < scaledPoints.size(); ++i)
			{
				bounds.include(scaledPoints[i]);
			}
			PX_ASSERT(!bounds.isEmpty());
			bounds.fattenFast(PxMax(0.00001f, bounds.getExtents().magnitude()*0.001f));
			scaledPoints.resize(8);
			for (uint32_t i = 0; i < 8; ++i)
			{
				scaledPoints[i] = PxVec3((i & 1) ? bounds.maximum.x : bounds.minimum.x,
				                                (i & 2) ? bounds.maximum.y : bounds.minimum.y,
				                                (i & 4) ? bounds.maximum.z : bounds.minimum.z);
			}
			meshDesc.points.data = scaledPoints.begin();
			meshDesc.points.count = 8;
			if (!GetApexSDK()->getCookingInterface()->cookConvexMesh(meshDesc, nvs))
			{
				memStream.reset();
			}
		}

		{
			NvParameterized::Handle bytesHandle(stream);
			stream->getParameterHandle("bytes", bytesHandle);
			stream->resizeArray(bytesHandle, (int32_t)memStream.getWriteBufferSize());
			stream->setParamU8Array(bytesHandle, memStream.getWriteBuffer(), (int32_t)memStream.getWriteBufferSize());
		}
	}

	if (convexMesh == NULL)
	{
		nvidia::PsMemoryBuffer memStream(stream->bytes.buf, (uint32_t)stream->bytes.arraySizes[0]);
		memStream.setEndianMode(PxFileBuf::ENDIAN_NONE);
		PxStreamFromFileBuf nvs(memStream);
		convexMesh = GetApexSDK()->getPhysXSDK()->createConvexMesh(nvs);
	}

	// These resizes should not be required, fix it and remove them
	if (mConvexMeshContainer.size() <= (uint32_t)scaleIndex)
	{
		APEX_DEBUG_WARNING("The asset's (%s) convex mesh container needed resizing, debug this", mAsset->getName());
		mConvexMeshContainer.resize((uint32_t)scaleIndex+1);
	}
	if (mConvexMeshContainer[(uint32_t)scaleIndex].size() <= (uint32_t)hullIndex)
	{
		APEX_DEBUG_WARNING("The asset's (%s) convex mesh container at scale index %d needed resizing, debug this", mAsset->getName(), scaleIndex);
		mConvexMeshContainer[(uint32_t)scaleIndex].resize(hullIndex+1);
	}
	
	mConvexMeshContainer[(uint32_t)scaleIndex][hullIndex] = convexMesh;

	return convexMesh;
}

MeshCookedCollisionStreamsAtScale* DestructibleAssetCollision::getCollisionAtScale(const PxVec3& scale)
{
	cookScale(scale);

	const int32_t scaleIndex = getScaleIndex(scale, kDefaultDestructibleAssetCollisionScaleTolerance);
	if (scaleIndex < 0)
	{
		return NULL;
	}

	return DYNAMIC_CAST(MeshCookedCollisionStreamsAtScale*)(mParams->meshCookedCollisionStreamsAtScale.buf[scaleIndex]);
}

physx::Array<PxConvexMesh*>* DestructibleAssetCollision::getConvexMeshesAtScale(const PxVec3& scale)
{
	cookScale(scale);

	const int32_t scaleIndex = getScaleIndex(scale, kDefaultDestructibleAssetCollisionScaleTolerance);
	if (scaleIndex < 0)
	{
		return NULL;
	}

	return &mConvexMeshContainer[(uint32_t)scaleIndex];
}

PxFileBuf& DestructibleAssetCollision::deserialize(PxFileBuf& stream, const char* assetName)
{
	// If there are any referenced meshes in ANY scales we're going to revoke this operation as not supported
	for (uint32_t i=0; i<mConvexMeshContainer.size(); i++)
	{
		if (mConvexMeshContainer.getReferenceCount(i) > 0)
		{
			APEX_DEBUG_INFO("Cannot deserialize the cooked collision data cache for asset <%s> scaleIdx <%d> because it is in use by actors", getAssetName(), i);
			return stream;
		}
	}

	mAsset = NULL;
	mConvexMeshContainer.reset();

	/*uint32_t version =*/
	stream.readDword();	// Eat version #, not used since this is the initial version

	ApexSimpleString name;
	name.deserialize(stream);
	NvParameterized::Handle handle(*mParams);
	mParams->getParameterHandle("assetName", handle);
	mParams->setParamString(handle, name.c_str());

	if (assetName != NULL)
		mParams->setParamString(handle, assetName);

	stream >> mParams->cookingPlatform;
	stream >> mParams->cookingVersionNum;

	NvParameterized::Traits* traits = GetInternalApexSDK()->getParameterizedTraits();

	int scaleCount = (int)stream.readDword();
	mParams->getParameterHandle("scales", handle);
	mParams->resizeArray(handle, scaleCount);
	for (int i = 0; i < scaleCount; ++i)
	{
		stream >> mParams->scales.buf[i];
	}

	int meshScaleCount = (int)stream.readDword();
	mParams->getParameterHandle("meshCookedCollisionStreamsAtScale", handle);
	mParams->resizeArray(handle, meshScaleCount);
	mConvexMeshContainer.resize((uint32_t)meshScaleCount);
	for (uint32_t i = 0; i < (uint32_t)meshScaleCount; ++i)
	{
		MeshCookedCollisionStreamsAtScale* streamsAtScale = DYNAMIC_CAST(MeshCookedCollisionStreamsAtScale*)(mParams->meshCookedCollisionStreamsAtScale.buf[i]);
		if (streamsAtScale == NULL)
		{
			streamsAtScale = DYNAMIC_CAST(MeshCookedCollisionStreamsAtScale*)(traits->createNvParameterized(MeshCookedCollisionStreamsAtScale::staticClassName()));
			mParams->meshCookedCollisionStreamsAtScale.buf[i] = streamsAtScale;
		}

		handle.setInterface(streamsAtScale);
		physx::Array<PxConvexMesh*>& meshSet = mConvexMeshContainer[i];

		uint32_t meshCount = stream.readDword();
		streamsAtScale->getParameterHandle("meshCookedCollisionStreams", handle);
		streamsAtScale->resizeArray(handle, (int32_t)meshCount);
		meshSet.resize(meshCount);
		for (uint32_t j = 0; j < meshCount; ++j)
		{
			MeshCookedCollisionStream* collisionStream = DYNAMIC_CAST(MeshCookedCollisionStream*)(streamsAtScale->meshCookedCollisionStreams.buf[j]);
			if (collisionStream == NULL)
			{
				collisionStream = DYNAMIC_CAST(MeshCookedCollisionStream*)(traits->createNvParameterized(MeshCookedCollisionStream::staticClassName()));
				streamsAtScale->meshCookedCollisionStreams.buf[j] = collisionStream;
			}

			handle.setInterface(collisionStream);

			int bufferSize = (int)stream.readDword();
			collisionStream->getParameterHandle("bytes", handle);
			collisionStream->resizeArray(handle, bufferSize);
			stream.read(collisionStream->bytes.buf, (uint32_t)bufferSize);

			nvidia::PsMemoryBuffer memStream(collisionStream->bytes.buf, (uint32_t)collisionStream->bytes.arraySizes[0]);
			memStream.setEndianMode(PxFileBuf::ENDIAN_NONE);
			PxStreamFromFileBuf nvs(memStream);
			meshSet[j] = GetApexSDK()->getPhysXSDK()->createConvexMesh(nvs);
		}
	}
	return stream;
}

PxFileBuf& DestructibleAssetCollision::serialize(PxFileBuf& stream) const
{
#ifndef WITHOUT_APEX_AUTHORING
	stream << (uint32_t)Version::Current;

	ApexSimpleString name(mParams->assetName);
	name.serialize(stream);

	stream << mParams->cookingPlatform;
	stream << mParams->cookingVersionNum;

	stream.storeDword((uint32_t)mParams->scales.arraySizes[0]);
	for (uint32_t i = 0; i < (uint32_t)mParams->scales.arraySizes[0]; ++i)
	{
		stream << mParams->scales.buf[i];
	}

	stream.storeDword((uint32_t)mParams->meshCookedCollisionStreamsAtScale.arraySizes[0]);
	for (uint32_t i = 0; i < (uint32_t)mParams->meshCookedCollisionStreamsAtScale.arraySizes[0]; ++i)
	{
		MeshCookedCollisionStreamsAtScale* streamsAtScale = DYNAMIC_CAST(MeshCookedCollisionStreamsAtScale*)(mParams->meshCookedCollisionStreamsAtScale.buf[i]);
		if (streamsAtScale == NULL)
		{
			stream.storeDword(0);
		}
		else
		{
			stream.storeDword((uint32_t)streamsAtScale->meshCookedCollisionStreams.arraySizes[0]);
			for (uint32_t j = 0; j < (uint32_t)streamsAtScale->meshCookedCollisionStreams.arraySizes[0]; ++j)
			{
				MeshCookedCollisionStream* collisionStream = DYNAMIC_CAST(MeshCookedCollisionStream*)(streamsAtScale->meshCookedCollisionStreams.buf[j]);
				if (collisionStream == NULL)
				{
					stream.storeDword(0);
				}
				else
				{
					stream.storeDword((uint32_t)collisionStream->bytes.arraySizes[0]);
					stream.write(collisionStream->bytes.buf, (uint32_t)collisionStream->bytes.arraySizes[0]);
				}
			}
		}
	}
#endif // #ifndef WITHOUT_APEX_AUTHORING
	return stream;
}

bool DestructibleAssetCollision::platformAndVersionMatch() const
{
	const PxCookingParams& cookingParams = GetInternalApexSDK()->getCookingInterface()->getParams();
	const uint32_t presentCookingVersionNum = GetInternalApexSDK()->getCookingVersion();

	return ((uint32_t) cookingParams.targetPlatform == mParams->cookingPlatform) &&
	       ((presentCookingVersionNum & 0xFFFF0000) == (mParams->cookingVersionNum & 0xFFFF0000));
}

void DestructibleAssetCollision::setPlatformAndVersion()
{
	mParams->cookingPlatform = GetInternalApexSDK()->getCookingInterface()->getParams().targetPlatform;
	mParams->cookingVersionNum = GetInternalApexSDK()->getCookingVersion();
}

uint32_t DestructibleAssetCollision::memorySize() const
{
	uint32_t size = 0;

	for (int i = 0; i < mParams->meshCookedCollisionStreamsAtScale.arraySizes[0]; ++i)
	{
		MeshCookedCollisionStreamsAtScale* streamsAtScale = DYNAMIC_CAST(MeshCookedCollisionStreamsAtScale*)(mParams->meshCookedCollisionStreamsAtScale.buf[i]);
		if (streamsAtScale == NULL)
		{
			continue;
		}
		for (int j = 0; j < streamsAtScale->meshCookedCollisionStreams.arraySizes[0]; ++j)
		{
			MeshCookedCollisionStream* stream = DYNAMIC_CAST(MeshCookedCollisionStream*)(streamsAtScale->meshCookedCollisionStreams.buf[j]);
			if (stream == NULL)
			{
				continue;
			}
			size += (uint32_t)stream->bytes.arraySizes[0];
		}
	}

	return size;
}

void DestructibleAssetCollision::clearUnreferencedSets()
{
	for (uint32_t i = 0; i < mConvexMeshContainer.size(); ++i)
	{
		if (mConvexMeshContainer.getReferenceCount(i) == 0)
		{
			MeshCookedCollisionStreamsAtScale* streamsAtScale = DYNAMIC_CAST(MeshCookedCollisionStreamsAtScale*)(mParams->meshCookedCollisionStreamsAtScale.buf[i]);
			if (streamsAtScale)
			{
				NvParameterized::Handle handle(*streamsAtScale);
				streamsAtScale->getParameterHandle("meshCookedCollisionStreams", handle);
				streamsAtScale->resizeArray(handle, 0);
			}

			// We need to NULL this pointer, otherwise we'll be accessing old data as a result of the reset below
			DestructibleAssetImpl* asset = mAsset;
			if (asset)
			{
				asset->mCollisionMeshes = NULL;
			}
		}
	}
	mConvexMeshContainer.reset(false);
}

// Spit out warnings to the error stream for any referenced sets
void DestructibleAssetCollision::reportReferencedSets()
{
	for (uint32_t i = 0; i < mConvexMeshContainer.size(); ++i)
	{
		if (mConvexMeshContainer.getReferenceCount(i))
		{
			APEX_DEBUG_WARNING("Clearing a referenced convex mesh container for asset: %s", mAsset);
		}
	}
}

bool DestructibleAssetCollision::incReferenceCount(int scaleIndex)
{
	if (scaleIndex < 0 || scaleIndex >= (int)mConvexMeshContainer.size())
	{
		return false;
	}

	mConvexMeshContainer.incReferenceCount((uint32_t)scaleIndex);

	return true;
}

bool DestructibleAssetCollision::decReferenceCount(int scaleIndex)
{
	if (scaleIndex < 0 || scaleIndex >= (int)mConvexMeshContainer.size())
	{
		return false;
	}

	return mConvexMeshContainer.decReferenceCount((uint32_t)scaleIndex);
}

// The source 'collisionSet' is not const because it's list of PxConvexMesh pointers
// in 'mConvexMeshContainer' needs to be cleared so they aren't released in 
// DestructibleAssetCollision::resize(0)
void DestructibleAssetCollision::merge(DestructibleAssetCollision& collisionSet)
{
	NvParameterized::Traits* traits = GetInternalApexSDK()->getParameterizedTraits();

	// Prepare the convexMesh container for the collisionSet's meshes
	if (mConvexMeshContainer.size() < collisionSet.mConvexMeshContainer.size())
	{
		mConvexMeshContainer.resize(collisionSet.mConvexMeshContainer.size());
	}

	// Loop through scales contained in collisionSet
	for (uint32_t i = 0; i < (uint32_t)collisionSet.mParams->scales.arraySizes[0]; ++i)
	{
		const PxVec3& scale = collisionSet.mParams->scales.buf[i];
		int scaleIndex = getScaleIndex(scale, kDefaultDestructibleAssetCollisionScaleTolerance);
		if (scaleIndex < 0)
		{
			// Scale not found, add it to this set
			addScale(scale);
			scaleIndex = getScaleIndex(scale, kDefaultDestructibleAssetCollisionScaleTolerance);
			if (scaleIndex < 0)
			{
				continue;	// Failed to add scale
			}
			if (mParams->meshCookedCollisionStreamsAtScale.buf[scaleIndex] == NULL)	// Create streams if we need them
			{
				mParams->meshCookedCollisionStreamsAtScale.buf[scaleIndex] = DYNAMIC_CAST(MeshCookedCollisionStreamsAtScale*)(traits->createNvParameterized(MeshCookedCollisionStreamsAtScale::staticClassName()));
			}
			mParams->meshCookedCollisionStreamsAtScale.buf[scaleIndex]->copy(*collisionSet.mParams->meshCookedCollisionStreamsAtScale.buf[i]);
		}
		else
		{
			MeshCookedCollisionStreamsAtScale* streamsAtScale = DYNAMIC_CAST(MeshCookedCollisionStreamsAtScale*)(mParams->meshCookedCollisionStreamsAtScale.buf[scaleIndex]);
			PX_ASSERT(streamsAtScale != NULL);
			if (streamsAtScale->meshCookedCollisionStreams.arraySizes[0] == 0)	// Only merge if this scale is empty; we won't stomp any existing data
			{
				mParams->meshCookedCollisionStreamsAtScale.buf[scaleIndex]->copy(*collisionSet.mParams->meshCookedCollisionStreamsAtScale.buf[i]);
			}

			// also copy the PxConvexMesh pointers (because the source collisionSet has them already at this point)
			physx::Array<PxConvexMesh*>& srcConvexMeshSet = collisionSet.mConvexMeshContainer[i];

			// make sure the destination list is present
			bool convexMeshSetResized = false;
			if (mConvexMeshContainer[i].size() < srcConvexMeshSet.size())
			{
				convexMeshSetResized = true;
				mConvexMeshContainer[i].resize(srcConvexMeshSet.size());
			}

			for (uint32_t j=0; j<srcConvexMeshSet.size(); j++)
			{
				// Only merge if we need PxConvexMesh pointers, otherwise just release these 
				// newly created PxConvexMesh after exiting this method
				if(mConvexMeshContainer[i][j] == NULL || convexMeshSetResized)
				{
					mConvexMeshContainer[i][j] = srcConvexMeshSet[j];
					// This prevents DestructibleAssetCollision::resize() from releasing the convex mesh
					srcConvexMeshSet[j] = NULL;
				}
			}
		}
	}
}

int32_t DestructibleAssetCollision::getScaleIndex(const PxVec3& scale, float tolerance) const
{
	for (int i = 0; i < mParams->scales.arraySizes[0]; ++i)
	{
		const PxVec3& error = scale - mParams->scales.buf[i];
		if (PxAbs(error.x) <= tolerance && PxAbs(error.y) <= tolerance && PxAbs(error.z) <= tolerance)
		{
			return i;
		}
	}

	return -1;
}

/** DestructibleAsset::ScatterMeshInstanceInfo **/

DestructibleAssetImpl::ScatterMeshInstanceInfo::~ScatterMeshInstanceInfo()
{
	if (m_actor != NULL)
	{
		m_actor->release();
		m_actor = NULL;
	}

	if (m_instanceBuffer != NULL)
	{
		UserRenderResourceManager* rrm = GetInternalApexSDK()->getUserRenderResourceManager();
		rrm->releaseInstanceBuffer(*m_instanceBuffer);
		m_instanceBuffer = NULL;
	}
}

}
} // end namespace nvidia