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
|
/**
* @file lldaeloader.cpp
* @brief LLDAELoader class implementation
*
* $LicenseInfo:firstyear=2013&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2013, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#if LL_MSVC
#pragma warning (disable : 4263)
#pragma warning (disable : 4264)
#endif
#include "dae.h"
#include "dom/domAsset.h"
#include "dom/domBind_material.h"
#include "dom/domCOLLADA.h"
#include "dom/domConstants.h"
#include "dom/domController.h"
#include "dom/domEffect.h"
#include "dom/domGeometry.h"
#include "dom/domInstance_geometry.h"
#include "dom/domInstance_material.h"
#include "dom/domInstance_node.h"
#include "dom/domInstance_effect.h"
#include "dom/domMaterial.h"
#include "dom/domMatrix.h"
#include "dom/domNode.h"
#include "dom/domProfile_COMMON.h"
#include "dom/domRotate.h"
#include "dom/domScale.h"
#include "dom/domTranslate.h"
#include "dom/domVisual_scene.h"
#if LL_MSVC
#pragma warning (default : 4263)
#pragma warning (default : 4264)
#endif
#include <boost/lexical_cast.hpp>
#include "lldaeloader.h"
#include "llsdserialize.h"
#include "lljoint.h"
#include "glh/glh_linear.h"
#include "llmatrix4a.h"
#include <boost/regex.hpp>
#include <boost/algorithm/string/replace.hpp>
std::string colladaVersion[VERSIONTYPE_COUNT+1] =
{
"1.4.0",
"1.4.1",
"Unsupported"
};
static const std::string lod_suffix[LLModel::NUM_LODS] =
{
"_LOD0",
"_LOD1",
"_LOD2",
"",
"_PHYS",
};
const U32 LIMIT_MATERIALS_OUTPUT = 12;
bool get_dom_sources(const domInputLocalOffset_Array& inputs, S32& pos_offset, S32& tc_offset, S32& norm_offset, S32 &idx_stride,
domSource* &pos_source, domSource* &tc_source, domSource* &norm_source)
{
idx_stride = 0;
for (U32 j = 0; j < inputs.getCount(); ++j)
{
idx_stride = llmax((S32) inputs[j]->getOffset(), idx_stride);
if (strcmp(COMMON_PROFILE_INPUT_VERTEX, inputs[j]->getSemantic()) == 0)
{ //found vertex array
const domURIFragmentType& uri = inputs[j]->getSource();
daeElementRef elem = uri.getElement();
domVertices* vertices = (domVertices*) elem.cast();
if ( !vertices )
{
return false;
}
domInputLocal_Array& v_inp = vertices->getInput_array();
for (U32 k = 0; k < v_inp.getCount(); ++k)
{
if (strcmp(COMMON_PROFILE_INPUT_POSITION, v_inp[k]->getSemantic()) == 0)
{
pos_offset = inputs[j]->getOffset();
const domURIFragmentType& uri = v_inp[k]->getSource();
daeElementRef elem = uri.getElement();
pos_source = (domSource*) elem.cast();
}
if (strcmp(COMMON_PROFILE_INPUT_NORMAL, v_inp[k]->getSemantic()) == 0)
{
norm_offset = inputs[j]->getOffset();
const domURIFragmentType& uri = v_inp[k]->getSource();
daeElementRef elem = uri.getElement();
norm_source = (domSource*) elem.cast();
}
}
}
if (strcmp(COMMON_PROFILE_INPUT_NORMAL, inputs[j]->getSemantic()) == 0)
{
//found normal array for this triangle list
norm_offset = inputs[j]->getOffset();
const domURIFragmentType& uri = inputs[j]->getSource();
daeElementRef elem = uri.getElement();
norm_source = (domSource*) elem.cast();
}
else if (strcmp(COMMON_PROFILE_INPUT_TEXCOORD, inputs[j]->getSemantic()) == 0)
{ //found texCoords
tc_offset = inputs[j]->getOffset();
const domURIFragmentType& uri = inputs[j]->getSource();
daeElementRef elem = uri.getElement();
tc_source = (domSource*) elem.cast();
}
}
idx_stride += 1;
return true;
}
LLModel::EModelStatus load_face_from_dom_triangles(std::vector<LLVolumeFace>& face_list, std::vector<std::string>& materials, domTrianglesRef& tri)
{
LLVolumeFace face;
std::vector<LLVolumeFace::VertexData> verts;
std::vector<U16> indices;
const domInputLocalOffset_Array& inputs = tri->getInput_array();
S32 pos_offset = -1;
S32 tc_offset = -1;
S32 norm_offset = -1;
domSource* pos_source = NULL;
domSource* tc_source = NULL;
domSource* norm_source = NULL;
S32 idx_stride = 0;
if ( !get_dom_sources(inputs, pos_offset, tc_offset, norm_offset, idx_stride, pos_source, tc_source, norm_source))
{
return LLModel::BAD_ELEMENT;
}
if (!pos_source || !pos_source->getFloat_array())
{
LL_WARNS() << "Unable to process mesh without position data; invalid model; invalid model." << LL_ENDL;
return LLModel::BAD_ELEMENT;
}
domPRef p = tri->getP();
domListOfUInts& idx = p->getValue();
domListOfFloats dummy ;
domListOfFloats& v = pos_source ? pos_source->getFloat_array()->getValue() : dummy ;
domListOfFloats& tc = tc_source ? tc_source->getFloat_array()->getValue() : dummy ;
domListOfFloats& n = norm_source ? norm_source->getFloat_array()->getValue() : dummy ;
if (pos_source)
{
if(v.getCount() == 0)
{
return LLModel::BAD_ELEMENT;
}
face.mExtents[0].set(v[0], v[1], v[2]);
face.mExtents[1].set(v[0], v[1], v[2]);
}
LLVolumeFace::VertexMapData::PointMap point_map;
for (U32 i = 0; i < idx.getCount(); i += idx_stride)
{
LLVolumeFace::VertexData cv;
if (pos_source)
{
cv.setPosition(LLVector4a(v[idx[i+pos_offset]*3+0],
v[idx[i+pos_offset]*3+1],
v[idx[i+pos_offset]*3+2]));
}
if (tc_source)
{
cv.mTexCoord.setVec(tc[idx[i+tc_offset]*2+0],
tc[idx[i+tc_offset]*2+1]);
}
if (norm_source)
{
cv.setNormal(LLVector4a(n[idx[i+norm_offset]*3+0],
n[idx[i+norm_offset]*3+1],
n[idx[i+norm_offset]*3+2]));
}
BOOL found = FALSE;
LLVolumeFace::VertexMapData::PointMap::iterator point_iter;
point_iter = point_map.find(LLVector3(cv.getPosition().getF32ptr()));
if (point_iter != point_map.end())
{
for (U32 j = 0; j < point_iter->second.size(); ++j)
{
// We have a matching loc
//
if ((point_iter->second)[j] == cv)
{
U16 shared_index = (point_iter->second)[j].mIndex;
// Don't share verts within the same tri, degenerate
//
U32 indx_size = indices.size();
U32 verts_new_tri = indx_size % 3;
if ((verts_new_tri < 1 || indices[indx_size - 1] != shared_index)
&& (verts_new_tri < 2 || indices[indx_size - 2] != shared_index))
{
found = true;
indices.push_back(shared_index);
}
break;
}
}
}
if (!found)
{
update_min_max(face.mExtents[0], face.mExtents[1], cv.getPosition());
verts.push_back(cv);
if (verts.size() >= 65535)
{
//llerrs << "Attempted to write model exceeding 16-bit index buffer limitation." << LL_ENDL;
return LLModel::VERTEX_NUMBER_OVERFLOW ;
}
U16 index = (U16) (verts.size()-1);
indices.push_back(index);
LLVolumeFace::VertexMapData d;
d.setPosition(cv.getPosition());
d.mTexCoord = cv.mTexCoord;
d.setNormal(cv.getNormal());
d.mIndex = index;
if (point_iter != point_map.end())
{
point_iter->second.push_back(d);
}
else
{
point_map[LLVector3(d.getPosition().getF32ptr())].push_back(d);
}
}
if (indices.size()%3 == 0 && verts.size() >= 65532)
{
std::string material;
if (tri->getMaterial())
{
material = std::string(tri->getMaterial());
}
materials.push_back(material);
face_list.push_back(face);
face_list.rbegin()->fillFromLegacyData(verts, indices);
LLVolumeFace& new_face = *face_list.rbegin();
if (!norm_source)
{
//ll_aligned_free_16(new_face.mNormals);
new_face.mNormals = NULL;
}
if (!tc_source)
{
//ll_aligned_free_16(new_face.mTexCoords);
new_face.mTexCoords = NULL;
}
face = LLVolumeFace();
point_map.clear();
}
}
if (!verts.empty())
{
std::string material;
if (tri->getMaterial())
{
material = std::string(tri->getMaterial());
}
materials.push_back(material);
face_list.push_back(face);
face_list.rbegin()->fillFromLegacyData(verts, indices);
LLVolumeFace& new_face = *face_list.rbegin();
if (!norm_source)
{
//ll_aligned_free_16(new_face.mNormals);
new_face.mNormals = NULL;
}
if (!tc_source)
{
//ll_aligned_free_16(new_face.mTexCoords);
new_face.mTexCoords = NULL;
}
}
return LLModel::NO_ERRORS ;
}
LLModel::EModelStatus load_face_from_dom_polylist(std::vector<LLVolumeFace>& face_list, std::vector<std::string>& materials, domPolylistRef& poly)
{
domPRef p = poly->getP();
domListOfUInts& idx = p->getValue();
if (idx.getCount() == 0)
{
return LLModel::NO_ERRORS ;
}
const domInputLocalOffset_Array& inputs = poly->getInput_array();
domListOfUInts& vcount = poly->getVcount()->getValue();
S32 pos_offset = -1;
S32 tc_offset = -1;
S32 norm_offset = -1;
domSource* pos_source = NULL;
domSource* tc_source = NULL;
domSource* norm_source = NULL;
S32 idx_stride = 0;
if (!get_dom_sources(inputs, pos_offset, tc_offset, norm_offset, idx_stride, pos_source, tc_source, norm_source))
{
return LLModel::BAD_ELEMENT;
}
LLVolumeFace face;
std::vector<U16> indices;
std::vector<LLVolumeFace::VertexData> verts;
domListOfFloats v;
domListOfFloats tc;
domListOfFloats n;
if (pos_source)
{
v = pos_source->getFloat_array()->getValue();
face.mExtents[0].set(v[0], v[1], v[2]);
face.mExtents[1].set(v[0], v[1], v[2]);
}
if (tc_source)
{
tc = tc_source->getFloat_array()->getValue();
}
if (norm_source)
{
n = norm_source->getFloat_array()->getValue();
}
LLVolumeFace::VertexMapData::PointMap point_map;
U32 cur_idx = 0;
for (U32 i = 0; i < vcount.getCount(); ++i)
{ //for each polygon
U32 first_index = 0;
U32 last_index = 0;
for (U32 j = 0; j < vcount[i]; ++j)
{ //for each vertex
LLVolumeFace::VertexData cv;
if (pos_source)
{
cv.getPosition().set(v[idx[cur_idx+pos_offset]*3+0],
v[idx[cur_idx+pos_offset]*3+1],
v[idx[cur_idx+pos_offset]*3+2]);
if (!cv.getPosition().isFinite3())
{
LL_WARNS() << "Found NaN while loading position data from DAE-Model, invalid model." << LL_ENDL;
return LLModel::BAD_ELEMENT;
}
}
if (tc_source)
{
cv.mTexCoord.setVec(tc[idx[cur_idx+tc_offset]*2+0],
tc[idx[cur_idx+tc_offset]*2+1]);
}
if (norm_source)
{
cv.getNormal().set(n[idx[cur_idx+norm_offset]*3+0],
n[idx[cur_idx+norm_offset]*3+1],
n[idx[cur_idx+norm_offset]*3+2]);
if (!cv.getNormal().isFinite3())
{
LL_WARNS() << "Found NaN while loading normals from DAE-Model, invalid model." << LL_ENDL;
return LLModel::BAD_ELEMENT;
}
}
cur_idx += idx_stride;
BOOL found = FALSE;
LLVolumeFace::VertexMapData::PointMap::iterator point_iter;
LLVector3 pos3(cv.getPosition().getF32ptr());
point_iter = point_map.find(pos3);
if (point_iter != point_map.end())
{
for (U32 k = 0; k < point_iter->second.size(); ++k)
{
if ((point_iter->second)[k] == cv)
{
found = TRUE;
U32 index = (point_iter->second)[k].mIndex;
if (j == 0)
{
first_index = index;
}
else if (j == 1)
{
last_index = index;
}
else
{
// if these are the same, we have a very, very skinny triangle (coincident verts on one or more edges)
//
llassert((first_index != last_index) && (last_index != index) && (first_index != index));
indices.push_back(first_index);
indices.push_back(last_index);
indices.push_back(index);
last_index = index;
}
break;
}
}
}
if (!found)
{
update_min_max(face.mExtents[0], face.mExtents[1], cv.getPosition());
verts.push_back(cv);
if (verts.size() >= 65535)
{
//llerrs << "Attempted to write model exceeding 16-bit index buffer limitation." << LL_ENDL;
return LLModel::VERTEX_NUMBER_OVERFLOW ;
}
U16 index = (U16) (verts.size()-1);
if (j == 0)
{
first_index = index;
}
else if (j == 1)
{
last_index = index;
}
else
{
// detect very skinny degenerate triangles with collapsed edges
//
llassert((first_index != last_index) && (last_index != index) && (first_index != index));
indices.push_back(first_index);
indices.push_back(last_index);
indices.push_back(index);
last_index = index;
}
LLVolumeFace::VertexMapData d;
d.setPosition(cv.getPosition());
d.mTexCoord = cv.mTexCoord;
d.setNormal(cv.getNormal());
d.mIndex = index;
if (point_iter != point_map.end())
{
point_iter->second.push_back(d);
}
else
{
point_map[pos3].push_back(d);
}
}
if (indices.size()%3 == 0 && indices.size() >= 65532)
{
std::string material;
if (poly->getMaterial())
{
material = std::string(poly->getMaterial());
}
materials.push_back(material);
face_list.push_back(face);
face_list.rbegin()->fillFromLegacyData(verts, indices);
LLVolumeFace& new_face = *face_list.rbegin();
if (!norm_source)
{
//ll_aligned_free_16(new_face.mNormals);
new_face.mNormals = NULL;
}
if (!tc_source)
{
//ll_aligned_free_16(new_face.mTexCoords);
new_face.mTexCoords = NULL;
}
face = LLVolumeFace();
verts.clear();
indices.clear();
point_map.clear();
}
}
}
if (!verts.empty())
{
std::string material;
if (poly->getMaterial())
{
material = std::string(poly->getMaterial());
}
materials.push_back(material);
face_list.push_back(face);
face_list.rbegin()->fillFromLegacyData(verts, indices);
LLVolumeFace& new_face = *face_list.rbegin();
if (!norm_source)
{
//ll_aligned_free_16(new_face.mNormals);
new_face.mNormals = NULL;
}
if (!tc_source)
{
//ll_aligned_free_16(new_face.mTexCoords);
new_face.mTexCoords = NULL;
}
}
return LLModel::NO_ERRORS ;
}
LLModel::EModelStatus load_face_from_dom_polygons(std::vector<LLVolumeFace>& face_list, std::vector<std::string>& materials, domPolygonsRef& poly)
{
LLVolumeFace face;
std::vector<U16> indices;
std::vector<LLVolumeFace::VertexData> verts;
const domInputLocalOffset_Array& inputs = poly->getInput_array();
S32 v_offset = -1;
S32 n_offset = -1;
S32 t_offset = -1;
domListOfFloats* v = NULL;
domListOfFloats* n = NULL;
domListOfFloats* t = NULL;
U32 stride = 0;
for (U32 i = 0; i < inputs.getCount(); ++i)
{
stride = llmax((U32) inputs[i]->getOffset()+1, stride);
if (strcmp(COMMON_PROFILE_INPUT_VERTEX, inputs[i]->getSemantic()) == 0)
{ //found vertex array
v_offset = inputs[i]->getOffset();
const domURIFragmentType& uri = inputs[i]->getSource();
daeElementRef elem = uri.getElement();
domVertices* vertices = (domVertices*) elem.cast();
if (!vertices)
{
return LLModel::BAD_ELEMENT;
}
domInputLocal_Array& v_inp = vertices->getInput_array();
for (U32 k = 0; k < v_inp.getCount(); ++k)
{
if (strcmp(COMMON_PROFILE_INPUT_POSITION, v_inp[k]->getSemantic()) == 0)
{
const domURIFragmentType& uri = v_inp[k]->getSource();
daeElementRef elem = uri.getElement();
domSource* src = (domSource*) elem.cast();
if (!src)
{
return LLModel::BAD_ELEMENT;
}
v = &(src->getFloat_array()->getValue());
}
}
}
else if (strcmp(COMMON_PROFILE_INPUT_NORMAL, inputs[i]->getSemantic()) == 0)
{
n_offset = inputs[i]->getOffset();
//found normal array for this triangle list
const domURIFragmentType& uri = inputs[i]->getSource();
daeElementRef elem = uri.getElement();
domSource* src = (domSource*) elem.cast();
if (!src)
{
return LLModel::BAD_ELEMENT;
}
n = &(src->getFloat_array()->getValue());
}
else if (strcmp(COMMON_PROFILE_INPUT_TEXCOORD, inputs[i]->getSemantic()) == 0 && inputs[i]->getSet() == 0)
{ //found texCoords
t_offset = inputs[i]->getOffset();
const domURIFragmentType& uri = inputs[i]->getSource();
daeElementRef elem = uri.getElement();
domSource* src = (domSource*) elem.cast();
if (!src)
{
return LLModel::BAD_ELEMENT;
}
t = &(src->getFloat_array()->getValue());
}
}
domP_Array& ps = poly->getP_array();
//make a triangle list in <verts>
for (U32 i = 0; i < ps.getCount(); ++i)
{ //for each polygon
domListOfUInts& idx = ps[i]->getValue();
for (U32 j = 0; j < idx.getCount()/stride; ++j)
{ //for each vertex
if (j > 2)
{
U32 size = verts.size();
LLVolumeFace::VertexData v0 = verts[size-3];
LLVolumeFace::VertexData v1 = verts[size-1];
verts.push_back(v0);
verts.push_back(v1);
}
LLVolumeFace::VertexData vert;
if (v)
{
U32 v_idx = idx[j*stride+v_offset]*3;
v_idx = llclamp(v_idx, (U32) 0, (U32) v->getCount());
vert.getPosition().set(v->get(v_idx),
v->get(v_idx+1),
v->get(v_idx+2));
}
//bounds check n and t lookups because some FBX to DAE converters
//use negative indices and empty arrays to indicate data does not exist
//for a particular channel
if (n && n->getCount() > 0)
{
U32 n_idx = idx[j*stride+n_offset]*3;
n_idx = llclamp(n_idx, (U32) 0, (U32) n->getCount());
vert.getNormal().set(n->get(n_idx),
n->get(n_idx+1),
n->get(n_idx+2));
}
else
{
vert.getNormal().clear();
}
if (t && t->getCount() > 0)
{
U32 t_idx = idx[j*stride+t_offset]*2;
t_idx = llclamp(t_idx, (U32) 0, (U32) t->getCount());
vert.mTexCoord.setVec(t->get(t_idx),
t->get(t_idx+1));
}
else
{
vert.mTexCoord.clear();
}
verts.push_back(vert);
}
}
if (verts.empty())
{
return LLModel::NO_ERRORS;
}
face.mExtents[0] = verts[0].getPosition();
face.mExtents[1] = verts[0].getPosition();
//create a map of unique vertices to indices
std::map<LLVolumeFace::VertexData, U32> vert_idx;
U32 cur_idx = 0;
for (U32 i = 0; i < verts.size(); ++i)
{
std::map<LLVolumeFace::VertexData, U32>::iterator iter = vert_idx.find(verts[i]);
if (iter == vert_idx.end())
{
vert_idx[verts[i]] = cur_idx++;
}
}
//build vertex array from map
std::vector<LLVolumeFace::VertexData> new_verts;
new_verts.resize(vert_idx.size());
for (std::map<LLVolumeFace::VertexData, U32>::iterator iter = vert_idx.begin(); iter != vert_idx.end(); ++iter)
{
new_verts[iter->second] = iter->first;
update_min_max(face.mExtents[0], face.mExtents[1], iter->first.getPosition());
}
//build index array from map
indices.resize(verts.size());
for (U32 i = 0; i < verts.size(); ++i)
{
indices[i] = vert_idx[verts[i]];
llassert(!i || (indices[i-1] != indices[i]));
}
// DEBUG just build an expanded triangle list
/*for (U32 i = 0; i < verts.size(); ++i)
{
indices.push_back((U16) i);
update_min_max(face.mExtents[0], face.mExtents[1], verts[i].getPosition());
}*/
if (!new_verts.empty())
{
std::string material;
if (poly->getMaterial())
{
material = std::string(poly->getMaterial());
}
materials.push_back(material);
face_list.push_back(face);
face_list.rbegin()->fillFromLegacyData(new_verts, indices);
LLVolumeFace& new_face = *face_list.rbegin();
if (!n)
{
//ll_aligned_free_16(new_face.mNormals);
new_face.mNormals = NULL;
}
if (!t)
{
//ll_aligned_free_16(new_face.mTexCoords);
new_face.mTexCoords = NULL;
}
}
return LLModel::NO_ERRORS ;
}
//-----------------------------------------------------------------------------
// LLDAELoader
//-----------------------------------------------------------------------------
LLDAELoader::LLDAELoader(
std::string filename,
S32 lod,
load_callback_t load_cb,
joint_lookup_func_t joint_lookup_func,
texture_load_func_t texture_load_func,
state_callback_t state_cb,
void* opaque_userdata,
JointTransformMap& jointTransformMap,
JointNameSet& jointsFromNodes,
std::map<std::string, std::string>& jointAliasMap,
U32 maxJointsPerMesh,
U32 modelLimit,
bool preprocess)
: LLModelLoader(
filename,
lod,
load_cb,
joint_lookup_func,
texture_load_func,
state_cb,
opaque_userdata,
jointTransformMap,
jointsFromNodes,
jointAliasMap,
maxJointsPerMesh),
mGeneratedModelLimit(modelLimit),
mPreprocessDAE(preprocess)
{
}
LLDAELoader::~LLDAELoader()
{
}
struct ModelSort
{
bool operator()(const LLPointer< LLModel >& lhs, const LLPointer< LLModel >& rhs)
{
if (lhs->mSubmodelID < rhs->mSubmodelID)
{
return true;
}
return LLStringUtil::compareInsensitive(lhs->mLabel, rhs->mLabel) < 0;
}
};
bool LLDAELoader::OpenFile(const std::string& filename)
{
//no suitable slm exists, load from the .dae file
DAE dae;
domCOLLADA* dom;
if (mPreprocessDAE)
{
dom = dae.openFromMemory(filename, preprocessDAE(filename).c_str());
}
else
{
LL_INFOS() << "Skipping dae preprocessing" << LL_ENDL;
dom = dae.open(filename);
}
if (!dom)
{
LL_INFOS() <<" Error with dae - traditionally indicates a corrupt file."<<LL_ENDL;
setLoadState( ERROR_PARSING );
return false;
}
//Dom version
daeString domVersion = dae.getDomVersion();
std::string sldom(domVersion);
LL_INFOS()<<"Collada Importer Version: "<<sldom<<LL_ENDL;
//Dae version
domVersionType docVersion = dom->getVersion();
//0=1.4
//1=1.4.1
//2=Currently unsupported, however may work
if (docVersion > 1 )
{
docVersion = VERSIONTYPE_COUNT;
}
LL_INFOS()<<"Dae version "<<colladaVersion[docVersion]<<LL_ENDL;
daeDatabase* db = dae.getDatabase();
daeInt count = db->getElementCount(NULL, COLLADA_TYPE_MESH);
daeDocument* doc = dae.getDoc(filename);
if (!doc)
{
LL_WARNS() << "can't find internal doc" << LL_ENDL;
return false;
}
daeElement* root = doc->getDomRoot();
if (!root)
{
LL_WARNS() << "document has no root" << LL_ENDL;
return false;
}
//Verify some basic properties of the dae
//1. Basic validity check on controller
U32 controllerCount = (int) db->getElementCount( NULL, "controller" );
bool result = false;
for ( int i=0; i<controllerCount; ++i )
{
domController* pController = NULL;
db->getElement( (daeElement**) &pController, i , NULL, "controller" );
result = verifyController( pController );
if (!result)
{
LL_INFOS() << "Could not verify controller" << LL_ENDL;
setLoadState( ERROR_PARSING );
return true;
}
}
//get unit scale
mTransform.setIdentity();
domAsset::domUnit* unit = daeSafeCast<domAsset::domUnit>(root->getDescendant(daeElement::matchType(domAsset::domUnit::ID())));
if (unit)
{
F32 meter = unit->getMeter();
mTransform.mMatrix[0][0] = meter;
mTransform.mMatrix[1][1] = meter;
mTransform.mMatrix[2][2] = meter;
}
//get up axis rotation
LLMatrix4 rotation;
domUpAxisType up = UPAXISTYPE_Y_UP; // default is Y_UP
domAsset::domUp_axis* up_axis =
daeSafeCast<domAsset::domUp_axis>(root->getDescendant(daeElement::matchType(domAsset::domUp_axis::ID())));
if (up_axis)
{
up = up_axis->getValue();
}
if (up == UPAXISTYPE_X_UP)
{
rotation.initRotation(0.0f, 90.0f * DEG_TO_RAD, 0.0f);
}
else if (up == UPAXISTYPE_Y_UP)
{
rotation.initRotation(90.0f * DEG_TO_RAD, 0.0f, 0.0f);
}
rotation *= mTransform;
mTransform = rotation;
mTransform.condition();
U32 submodel_limit = count > 0 ? mGeneratedModelLimit/count : 0;
for (daeInt idx = 0; idx < count; ++idx)
{ //build map of domEntities to LLModel
domMesh* mesh = NULL;
db->getElement((daeElement**) &mesh, idx, NULL, COLLADA_TYPE_MESH);
if (mesh)
{
std::vector<LLModel*> models;
loadModelsFromDomMesh(mesh, models, submodel_limit);
std::vector<LLModel*>::iterator i;
i = models.begin();
while (i != models.end())
{
LLModel* mdl = *i;
if(mdl->getStatus() != LLModel::NO_ERRORS)
{
setLoadState(ERROR_MODEL + mdl->getStatus()) ;
return false; //abort
}
if (mdl && validate_model(mdl))
{
mModelList.push_back(mdl);
mModelsMap[mesh].push_back(mdl);
}
i++;
}
}
}
std::sort(mModelList.begin(), mModelList.end(), ModelSort());
model_list::iterator model_iter = mModelList.begin();
while (model_iter != mModelList.end())
{
LLModel* mdl = *model_iter;
U32 material_count = mdl->mMaterialList.size();
LL_INFOS() << "Importing " << mdl->mLabel << " model with " << material_count << " material references" << LL_ENDL;
std::vector<std::string>::iterator mat_iter = mdl->mMaterialList.begin();
std::vector<std::string>::iterator end_iter = material_count > LIMIT_MATERIALS_OUTPUT
? mat_iter + LIMIT_MATERIALS_OUTPUT
: mdl->mMaterialList.end();
while (mat_iter != end_iter)
{
LL_INFOS() << mdl->mLabel << " references " << (*mat_iter) << LL_ENDL;
mat_iter++;
}
model_iter++;
}
count = db->getElementCount(NULL, COLLADA_TYPE_SKIN);
for (daeInt idx = 0; idx < count; ++idx)
{ //add skinned meshes as instances
domSkin* skin = NULL;
db->getElement((daeElement**) &skin, idx, NULL, COLLADA_TYPE_SKIN);
if (skin)
{
domGeometry* geom = daeSafeCast<domGeometry>(skin->getSource().getElement());
if (geom)
{
domMesh* mesh = geom->getMesh();
if (mesh)
{
std::vector< LLPointer< LLModel > >::iterator i = mModelsMap[mesh].begin();
while (i != mModelsMap[mesh].end())
{
LLPointer<LLModel> mdl = *i;
LLDAELoader::processDomModel(mdl, &dae, root, mesh, skin);
i++;
}
}
}
}
}
LL_INFOS()<< "Collada skins processed: " << count <<LL_ENDL;
daeElement* scene = root->getDescendant("visual_scene");
if (!scene)
{
LL_WARNS() << "document has no visual_scene" << LL_ENDL;
setLoadState( ERROR_PARSING );
return true;
}
setLoadState( DONE );
bool badElement = false;
processElement( scene, badElement, &dae );
if ( badElement )
{
LL_INFOS()<<"Scene could not be parsed"<<LL_ENDL;
setLoadState( ERROR_PARSING );
}
return true;
}
std::string LLDAELoader::preprocessDAE(std::string filename)
{
// Open a DAE file for some preprocessing (like removing space characters in IDs), see MAINT-5678
std::ifstream inFile;
inFile.open(filename.c_str(), std::ios_base::in);
std::stringstream strStream;
strStream << inFile.rdbuf();
std::string buffer = strStream.str();
LL_INFOS() << "Preprocessing dae file to remove spaces from the names, ids, etc." << LL_ENDL;
try
{
boost::regex re("\"[\\w\\.@#$-]*(\\s[\\w\\.@#$-]*)+\"");
boost::sregex_iterator next(buffer.begin(), buffer.end(), re);
boost::sregex_iterator end;
while (next != end)
{
boost::smatch match = *next;
std::string s = match.str();
LL_INFOS() << s << " found" << LL_ENDL;
boost::replace_all(s, " ", "_");
LL_INFOS() << "Replacing with " << s << LL_ENDL;
boost::replace_all(buffer, match.str(), s);
next++;
}
}
catch (boost::regex_error &)
{
LL_INFOS() << "Regex error" << LL_ENDL;
}
return buffer;
}
void LLDAELoader::processDomModel(LLModel* model, DAE* dae, daeElement* root, domMesh* mesh, domSkin* skin)
{
llassert(model && dae && mesh && skin);
if (model)
{
LLVector3 mesh_scale_vector;
LLVector3 mesh_translation_vector;
model->getNormalizedScaleTranslation(mesh_scale_vector, mesh_translation_vector);
LLMatrix4 normalized_transformation;
normalized_transformation.setTranslation(mesh_translation_vector);
LLMatrix4 mesh_scale;
mesh_scale.initScale(mesh_scale_vector);
mesh_scale *= normalized_transformation;
normalized_transformation = mesh_scale;
glh::matrix4f inv_mat((F32*) normalized_transformation.mMatrix);
inv_mat = inv_mat.inverse();
LLMatrix4 inverse_normalized_transformation(inv_mat.m);
domSkin::domBind_shape_matrix* bind_mat = skin->getBind_shape_matrix();
if (bind_mat)
{ //get bind shape matrix
domFloat4x4& dom_value = bind_mat->getValue();
LLMeshSkinInfo& skin_info = model->mSkinInfo;
for (int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
skin_info.mBindShapeMatrix.mMatrix[i][j] = dom_value[i + j*4];
}
}
LLMatrix4 trans = normalized_transformation;
trans *= skin_info.mBindShapeMatrix;
skin_info.mBindShapeMatrix = trans;
}
//Some collada setup for accessing the skeleton
U32 skeleton_count = dae->getDatabase()->getElementCount( NULL, "skeleton" );
std::vector<domInstance_controller::domSkeleton*> skeletons;
for (S32 i=0; i<skeleton_count; i++)
{
daeElement* pElement = 0;
dae->getDatabase()->getElement( &pElement, i, 0, "skeleton" );
//Try to get at the skeletal instance controller
domInstance_controller::domSkeleton* pSkeleton = daeSafeCast<domInstance_controller::domSkeleton>( pElement );
daeElement* pSkeletonRootNode = NULL;
if (pSkeleton)
{
pSkeletonRootNode = pSkeleton->getValue().getElement();
}
if (pSkeleton && pSkeletonRootNode)
{
skeletons.push_back(pSkeleton);
}
}
bool missingSkeletonOrScene = false;
//If no skeleton, do a breadth-first search to get at specific joints
if ( skeletons.size() == 0 )
{
daeElement* pScene = root->getDescendant("visual_scene");
if ( !pScene )
{
LL_WARNS()<<"No visual scene - unable to parse bone offsets "<<LL_ENDL;
missingSkeletonOrScene = true;
}
else
{
//Get the children at this level
daeTArray< daeSmartRef<daeElement> > children = pScene->getChildren();
S32 childCount = children.getCount();
//Process any children that are joints
//Not all children are joints, some code be ambient lights, cameras, geometry etc..
for (S32 i = 0; i < childCount; ++i)
{
domNode* pNode = daeSafeCast<domNode>(children[i]);
if ( isNodeAJoint( pNode ) )
{
processJointNode( pNode, mJointList );
}
}
}
}
else
//Has one or more skeletons
for (std::vector<domInstance_controller::domSkeleton*>::iterator skel_it = skeletons.begin();
skel_it != skeletons.end(); ++skel_it)
{
domInstance_controller::domSkeleton* pSkeleton = *skel_it;
//Get the root node of the skeleton
daeElement* pSkeletonRootNode = pSkeleton->getValue().getElement();
if ( pSkeletonRootNode )
{
//Once we have the root node - start acccessing it's joint components
const int jointCnt = mJointMap.size();
JointMap :: const_iterator jointIt = mJointMap.begin();
//Loop over all the possible joints within the .dae - using the allowed joint list in the ctor.
for ( int i=0; i<jointCnt; ++i, ++jointIt )
{
//Build a joint for the resolver to work with
char str[64]={0};
sprintf(str,"./%s",(*jointIt).first.c_str() );
//LL_WARNS()<<"Joint "<< str <<LL_ENDL;
//Setup the resolver
daeSIDResolver resolver( pSkeletonRootNode, str );
//Look for the joint
domNode* pJoint = daeSafeCast<domNode>( resolver.getElement() );
if ( pJoint )
{
//Pull out the translate id and store it in the jointTranslations map
daeSIDResolver jointResolverA( pJoint, "./translate" );
domTranslate* pTranslateA = daeSafeCast<domTranslate>( jointResolverA.getElement() );
daeSIDResolver jointResolverB( pJoint, "./location" );
domTranslate* pTranslateB = daeSafeCast<domTranslate>( jointResolverB.getElement() );
LLMatrix4 workingTransform;
//Translation via SID
if ( pTranslateA )
{
extractTranslation( pTranslateA, workingTransform );
}
else
{
if ( pTranslateB )
{
extractTranslation( pTranslateB, workingTransform );
}
else
{
//Translation via child from element
daeElement* pTranslateElement = getChildFromElement( pJoint, "translate" );
if ( pTranslateElement && pTranslateElement->typeID() != domTranslate::ID() )
{
LL_WARNS()<< "The found element is not a translate node" <<LL_ENDL;
missingSkeletonOrScene = true;
}
else
if ( pTranslateElement )
{
extractTranslationViaElement( pTranslateElement, workingTransform );
}
else
{
extractTranslationViaSID( pJoint, workingTransform );
}
}
}
//Store the joint transform w/respect to its name.
mJointList[(*jointIt).second.c_str()] = workingTransform;
}
}
//If anything failed in regards to extracting the skeleton, joints or translation id,
//mention it
if ( missingSkeletonOrScene )
{
LL_WARNS()<< "Partial jointmap found in asset - did you mean to just have a partial map?" << LL_ENDL;
}
}//got skeleton?
}
domSkin::domJoints* joints = skin->getJoints();
domInputLocal_Array& joint_input = joints->getInput_array();
for (size_t i = 0; i < joint_input.getCount(); ++i)
{
domInputLocal* input = joint_input.get(i);
xsNMTOKEN semantic = input->getSemantic();
if (strcmp(semantic, COMMON_PROFILE_INPUT_JOINT) == 0)
{ //found joint source, fill model->mJointMap and model->mSkinInfo.mJointNames
daeElement* elem = input->getSource().getElement();
domSource* source = daeSafeCast<domSource>(elem);
if (source)
{
domName_array* names_source = source->getName_array();
if (names_source)
{
domListOfNames &names = names_source->getValue();
for (size_t j = 0; j < names.getCount(); ++j)
{
std::string name(names.get(j));
if (mJointMap.find(name) != mJointMap.end())
{
name = mJointMap[name];
}
model->mSkinInfo.mJointNames.push_back(name);
}
}
else
{
domIDREF_array* names_source = source->getIDREF_array();
if (names_source)
{
xsIDREFS& names = names_source->getValue();
for (size_t j = 0; j < names.getCount(); ++j)
{
std::string name(names.get(j).getID());
if (mJointMap.find(name) != mJointMap.end())
{
name = mJointMap[name];
}
model->mSkinInfo.mJointNames.push_back(name);
}
}
}
}
}
else if (strcmp(semantic, COMMON_PROFILE_INPUT_INV_BIND_MATRIX) == 0)
{ //found inv_bind_matrix array, fill model->mInvBindMatrix
domSource* source = daeSafeCast<domSource>(input->getSource().getElement());
if (source)
{
domFloat_array* t = source->getFloat_array();
if (t)
{
domListOfFloats& transform = t->getValue();
S32 count = transform.getCount()/16;
for (S32 k = 0; k < count; ++k)
{
LLMatrix4 mat;
for (int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
mat.mMatrix[i][j] = transform[k*16 + i + j*4];
}
}
model->mSkinInfo.mInvBindMatrix.push_back(mat);
}
}
}
}
}
//Now that we've parsed the joint array, let's determine if we have a full rig
//(which means we have all the joint sthat are required for an avatar versus
//a skinned asset attached to a node in a file that contains an entire skeleton,
//but does not use the skeleton).
buildJointToNodeMappingFromScene( root );
critiqueRigForUploadApplicability( model->mSkinInfo.mJointNames );
if ( !missingSkeletonOrScene )
{
//Set the joint translations on the avatar
JointMap :: const_iterator masterJointIt = mJointMap.begin();
JointMap :: const_iterator masterJointItEnd = mJointMap.end();
for (;masterJointIt!=masterJointItEnd;++masterJointIt )
{
std::string lookingForJoint = (*masterJointIt).first.c_str();
if ( mJointList.find( lookingForJoint ) != mJointList.end() )
{
//LL_INFOS()<<"joint "<<lookingForJoint.c_str()<<LL_ENDL;
LLMatrix4 jointTransform = mJointList[lookingForJoint];
LLJoint* pJoint = mJointLookupFunc(lookingForJoint,mOpaqueData);
if ( pJoint )
{
// FIXME: mesh_id is used to determine which
// mesh gets to set the joint offset, in the
// event of a conflict. Since we don't know
// the mesh id yet, we can't guarantee that
// joint offsets will be applied with the same
// priority as in the uploaded model. If the
// file contains multiple meshes with
// conflicting joint offsets, preview may be
// incorrect.
LLUUID fake_mesh_id;
fake_mesh_id.generate();
pJoint->addAttachmentPosOverride( jointTransform.getTranslation(), fake_mesh_id, "");
}
else
{
//Most likely an error in the asset.
LL_WARNS()<<"Tried to apply joint position from .dae, but it did not exist in the avatar rig." << LL_ENDL;
}
}
}
} //missingSkeletonOrScene
//We need to construct the alternate bind matrix (which contains the new joint positions)
//in the same order as they were stored in the joint buffer. The joints associated
//with the skeleton are not stored in the same order as they are in the exported joint buffer.
//This remaps the skeletal joints to be in the same order as the joints stored in the model.
std::vector<std::string> :: const_iterator jointIt = model->mSkinInfo.mJointNames.begin();
const int jointCnt = model->mSkinInfo.mJointNames.size();
for ( int i=0; i<jointCnt; ++i, ++jointIt )
{
std::string lookingForJoint = (*jointIt).c_str();
//Look for the joint xform that we extracted from the skeleton, using the jointIt as the key
//and store it in the alternate bind matrix
if ( mJointMap.find( lookingForJoint ) != mJointMap.end() )
{
LLMatrix4 newInverse = model->mSkinInfo.mInvBindMatrix[i];
newInverse.setTranslation( mJointList[lookingForJoint].getTranslation() );
model->mSkinInfo.mAlternateBindMatrix.push_back( newInverse );
}
else
{
LL_DEBUGS("Mesh")<<"Possibly misnamed/missing joint [" <<lookingForJoint.c_str()<<"] "<<LL_ENDL;
}
}
//grab raw position array
domVertices* verts = mesh->getVertices();
if (verts)
{
domInputLocal_Array& inputs = verts->getInput_array();
for (size_t i = 0; i < inputs.getCount() && model->mPosition.empty(); ++i)
{
if (strcmp(inputs[i]->getSemantic(), COMMON_PROFILE_INPUT_POSITION) == 0)
{
domSource* pos_source = daeSafeCast<domSource>(inputs[i]->getSource().getElement());
if (pos_source)
{
domFloat_array* pos_array = pos_source->getFloat_array();
if (pos_array)
{
domListOfFloats& pos = pos_array->getValue();
for (size_t j = 0; j < pos.getCount(); j += 3)
{
if (pos.getCount() <= j+2)
{
LL_ERRS() << "Invalid position array size." << LL_ENDL;
}
LLVector3 v(pos[j], pos[j+1], pos[j+2]);
//transform from COLLADA space to volume space
v = v * inverse_normalized_transformation;
model->mPosition.push_back(v);
}
}
}
}
}
}
//grab skin weights array
domSkin::domVertex_weights* weights = skin->getVertex_weights();
if (weights)
{
domInputLocalOffset_Array& inputs = weights->getInput_array();
domFloat_array* vertex_weights = NULL;
for (size_t i = 0; i < inputs.getCount(); ++i)
{
if (strcmp(inputs[i]->getSemantic(), COMMON_PROFILE_INPUT_WEIGHT) == 0)
{
domSource* weight_source = daeSafeCast<domSource>(inputs[i]->getSource().getElement());
if (weight_source)
{
vertex_weights = weight_source->getFloat_array();
}
}
}
if (vertex_weights)
{
domListOfFloats& w = vertex_weights->getValue();
domListOfUInts& vcount = weights->getVcount()->getValue();
domListOfInts& v = weights->getV()->getValue();
U32 c_idx = 0;
for (size_t vc_idx = 0; vc_idx < vcount.getCount(); ++vc_idx)
{ //for each vertex
daeUInt count = vcount[vc_idx];
//create list of weights that influence this vertex
LLModel::weight_list weight_list;
for (daeUInt i = 0; i < count; ++i)
{ //for each weight
daeInt joint_idx = v[c_idx++];
daeInt weight_idx = v[c_idx++];
if (joint_idx == -1)
{
//ignore bindings to bind_shape_matrix
continue;
}
F32 weight_value = w[weight_idx];
weight_list.push_back(LLModel::JointWeight(joint_idx, weight_value));
}
//sort by joint weight
std::sort(weight_list.begin(), weight_list.end(), LLModel::CompareWeightGreater());
std::vector<LLModel::JointWeight> wght;
F32 total = 0.f;
for (U32 i = 0; i < llmin((U32) 4, (U32) weight_list.size()); ++i)
{ //take up to 4 most significant weights
if (weight_list[i].mWeight > 0.f)
{
wght.push_back( weight_list[i] );
total += weight_list[i].mWeight;
}
}
F32 scale = 1.f/total;
if (scale != 1.f)
{ //normalize weights
for (U32 i = 0; i < wght.size(); ++i)
{
wght[i].mWeight *= scale;
}
}
model->mSkinWeights[model->mPosition[vc_idx]] = wght;
}
}
}
//add instance to scene for this model
LLMatrix4 transformation;
transformation.initScale(mesh_scale_vector);
transformation.setTranslation(mesh_translation_vector);
transformation *= mTransform;
std::map<std::string, LLImportMaterial> materials;
for (U32 i = 0; i < model->mMaterialList.size(); ++i)
{
materials[model->mMaterialList[i]] = LLImportMaterial();
}
mScene[transformation].push_back(LLModelInstance(model, model->mLabel, transformation, materials));
stretch_extents(model, transformation, mExtents[0], mExtents[1], mFirstTransform);
}
}
//-----------------------------------------------------------------------------
// buildJointToNodeMappingFromScene()
//-----------------------------------------------------------------------------
void LLDAELoader::buildJointToNodeMappingFromScene( daeElement* pRoot )
{
daeElement* pScene = pRoot->getDescendant("visual_scene");
if ( pScene )
{
daeTArray< daeSmartRef<daeElement> > children = pScene->getChildren();
S32 childCount = children.getCount();
for (S32 i = 0; i < childCount; ++i)
{
domNode* pNode = daeSafeCast<domNode>(children[i]);
processJointToNodeMapping( pNode );
}
}
}
//-----------------------------------------------------------------------------
// processJointToNodeMapping()
//-----------------------------------------------------------------------------
void LLDAELoader::processJointToNodeMapping( domNode* pNode )
{
if ( isNodeAJoint( pNode ) )
{
//1.Store the parent
std::string nodeName = pNode->getName();
if ( !nodeName.empty() )
{
mJointsFromNode.push_front( pNode->getName() );
}
//2. Handle the kiddo's
processChildJoints( pNode );
}
else
{
//Determine if the're any children wrt to this failed node.
//This occurs when an armature is exported and ends up being what essentially amounts to
//as the root for the visual_scene
if ( pNode )
{
processChildJoints( pNode );
}
else
{
LL_INFOS()<<"Node is NULL"<<LL_ENDL;
}
}
}
//-----------------------------------------------------------------------------
// processChildJoint()
//-----------------------------------------------------------------------------
void LLDAELoader::processChildJoints( domNode* pParentNode )
{
daeTArray< daeSmartRef<daeElement> > childOfChild = pParentNode->getChildren();
S32 childOfChildCount = childOfChild.getCount();
for (S32 i = 0; i < childOfChildCount; ++i)
{
domNode* pChildNode = daeSafeCast<domNode>( childOfChild[i] );
if ( pChildNode )
{
processJointToNodeMapping( pChildNode );
}
}
}
//-----------------------------------------------------------------------------
// isNodeAJoint()
//-----------------------------------------------------------------------------
bool LLDAELoader::isNodeAJoint( domNode* pNode )
{
if ( !pNode || !pNode->getName() )
{
LL_INFOS()<<"Created node is NULL or invalid"<<LL_ENDL;
return false;
}
return LLModelLoader::isNodeAJoint(pNode->getName());
}
//-----------------------------------------------------------------------------
// verifyCount
//-----------------------------------------------------------------------------
bool LLDAELoader::verifyCount( int expected, int result )
{
if ( expected != result )
{
LL_INFOS()<< "Error: (expected/got)"<<expected<<"/"<<result<<"verts"<<LL_ENDL;
return false;
}
return true;
}
//-----------------------------------------------------------------------------
// verifyController
//-----------------------------------------------------------------------------
bool LLDAELoader::verifyController( domController* pController )
{
bool result = true;
domSkin* pSkin = pController->getSkin();
if ( pSkin )
{
xsAnyURI & uri = pSkin->getSource();
domElement* pElement = uri.getElement();
if ( !pElement )
{
LL_INFOS()<<"Can't resolve skin source"<<LL_ENDL;
return false;
}
daeString type_str = pElement->getTypeName();
if ( stricmp(type_str, "geometry") == 0 )
{
//Skin is reference directly by geometry and get the vertex count from skin
domSkin::domVertex_weights* pVertexWeights = pSkin->getVertex_weights();
U32 vertexWeightsCount = pVertexWeights->getCount();
domGeometry* pGeometry = (domGeometry*) (domElement*) uri.getElement();
domMesh* pMesh = pGeometry->getMesh();
if ( pMesh )
{
//Get vertex count from geometry
domVertices* pVertices = pMesh->getVertices();
if ( !pVertices )
{
LL_INFOS()<<"No vertices!"<<LL_ENDL;
return false;
}
if ( pVertices )
{
xsAnyURI src = pVertices->getInput_array()[0]->getSource();
domSource* pSource = (domSource*) (domElement*) src.getElement();
U32 verticesCount = pSource->getTechnique_common()->getAccessor()->getCount();
result = verifyCount( verticesCount, vertexWeightsCount );
if ( !result )
{
return result;
}
}
}
U32 vcountCount = (U32) pVertexWeights->getVcount()->getValue().getCount();
result = verifyCount( vcountCount, vertexWeightsCount );
if ( !result )
{
return result;
}
domInputLocalOffset_Array& inputs = pVertexWeights->getInput_array();
U32 sum = 0;
for (size_t i=0; i<vcountCount; i++)
{
sum += pVertexWeights->getVcount()->getValue()[i];
}
result = verifyCount( sum * inputs.getCount(), (domInt) pVertexWeights->getV()->getValue().getCount() );
}
}
return result;
}
//-----------------------------------------------------------------------------
// extractTranslation()
//-----------------------------------------------------------------------------
void LLDAELoader::extractTranslation( domTranslate* pTranslate, LLMatrix4& transform )
{
domFloat3 jointTrans = pTranslate->getValue();
LLVector3 singleJointTranslation( jointTrans[0], jointTrans[1], jointTrans[2] );
transform.setTranslation( singleJointTranslation );
}
//-----------------------------------------------------------------------------
// extractTranslationViaElement()
//-----------------------------------------------------------------------------
void LLDAELoader::extractTranslationViaElement( daeElement* pTranslateElement, LLMatrix4& transform )
{
if ( pTranslateElement )
{
domTranslate* pTranslateChild = dynamic_cast<domTranslate*>( pTranslateElement );
domFloat3 translateChild = pTranslateChild->getValue();
LLVector3 singleJointTranslation( translateChild[0], translateChild[1], translateChild[2] );
transform.setTranslation( singleJointTranslation );
}
}
//-----------------------------------------------------------------------------
// extractTranslationViaSID()
//-----------------------------------------------------------------------------
void LLDAELoader::extractTranslationViaSID( daeElement* pElement, LLMatrix4& transform )
{
if ( pElement )
{
daeSIDResolver resolver( pElement, "./transform" );
domMatrix* pMatrix = daeSafeCast<domMatrix>( resolver.getElement() );
//We are only extracting out the translational component atm
LLMatrix4 workingTransform;
if ( pMatrix )
{
domFloat4x4 domArray = pMatrix->getValue();
for ( int i = 0; i < 4; i++ )
{
for( int j = 0; j < 4; j++ )
{
workingTransform.mMatrix[i][j] = domArray[i + j*4];
}
}
LLVector3 trans = workingTransform.getTranslation();
transform.setTranslation( trans );
}
}
else
{
LL_WARNS()<<"Element is nonexistent - empty/unsupported node."<<LL_ENDL;
}
}
//-----------------------------------------------------------------------------
// processJointNode()
//-----------------------------------------------------------------------------
void LLDAELoader::processJointNode( domNode* pNode, JointTransformMap& jointTransforms )
{
if (pNode->getName() == NULL)
{
LL_WARNS() << "nameless node, can't process" << LL_ENDL;
return;
}
//LL_WARNS()<<"ProcessJointNode# Node:" <<pNode->getName()<<LL_ENDL;
//1. handle the incoming node - extract out translation via SID or element
LLMatrix4 workingTransform;
//Pull out the translate id and store it in the jointTranslations map
daeSIDResolver jointResolverA( pNode, "./translate" );
domTranslate* pTranslateA = daeSafeCast<domTranslate>( jointResolverA.getElement() );
daeSIDResolver jointResolverB( pNode, "./location" );
domTranslate* pTranslateB = daeSafeCast<domTranslate>( jointResolverB.getElement() );
//Translation via SID was successful
if ( pTranslateA )
{
extractTranslation( pTranslateA, workingTransform );
}
else
if ( pTranslateB )
{
extractTranslation( pTranslateB, workingTransform );
}
else
{
//Translation via child from element
daeElement* pTranslateElement = getChildFromElement( pNode, "translate" );
if ( !pTranslateElement || pTranslateElement->typeID() != domTranslate::ID() )
{
//LL_WARNS()<< "The found element is not a translate node" <<LL_ENDL;
daeSIDResolver jointResolver( pNode, "./matrix" );
domMatrix* pMatrix = daeSafeCast<domMatrix>( jointResolver.getElement() );
if ( pMatrix )
{
//LL_INFOS()<<"A matrix SID was however found!"<<LL_ENDL;
domFloat4x4 domArray = pMatrix->getValue();
for ( int i = 0; i < 4; i++ )
{
for( int j = 0; j < 4; j++ )
{
workingTransform.mMatrix[i][j] = domArray[i + j*4];
}
}
}
else
{
LL_WARNS()<< "The found element is not translate or matrix node - most likely a corrupt export!" <<LL_ENDL;
}
}
else
{
extractTranslationViaElement( pTranslateElement, workingTransform );
}
}
//Store the working transform relative to the nodes name.
jointTransforms[ pNode->getName() ] = workingTransform;
//2. handle the nodes children
//Gather and handle the incoming nodes children
daeTArray< daeSmartRef<daeElement> > childOfChild = pNode->getChildren();
S32 childOfChildCount = childOfChild.getCount();
for (S32 i = 0; i < childOfChildCount; ++i)
{
domNode* pChildNode = daeSafeCast<domNode>( childOfChild[i] );
if ( pChildNode )
{
processJointNode( pChildNode, jointTransforms );
}
}
}
//-----------------------------------------------------------------------------
// getChildFromElement()
//-----------------------------------------------------------------------------
daeElement* LLDAELoader::getChildFromElement( daeElement* pElement, std::string const & name )
{
daeElement* pChildOfElement = pElement->getChild( name.c_str() );
if ( pChildOfElement )
{
return pChildOfElement;
}
LL_DEBUGS("Mesh")<< "Could not find a child [" << name << "] for the element: \"" << pElement->getAttribute("id") << "\"" << LL_ENDL;
return NULL;
}
void LLDAELoader::processElement( daeElement* element, bool& badElement, DAE* dae )
{
LLMatrix4 saved_transform;
bool pushed_mat = false;
domNode* node = daeSafeCast<domNode>(element);
if (node)
{
pushed_mat = true;
saved_transform = mTransform;
}
domTranslate* translate = daeSafeCast<domTranslate>(element);
if (translate)
{
domFloat3 dom_value = translate->getValue();
LLMatrix4 translation;
translation.setTranslation(LLVector3(dom_value[0], dom_value[1], dom_value[2]));
translation *= mTransform;
mTransform = translation;
mTransform.condition();
}
domRotate* rotate = daeSafeCast<domRotate>(element);
if (rotate)
{
domFloat4 dom_value = rotate->getValue();
LLMatrix4 rotation;
rotation.initRotTrans(dom_value[3] * DEG_TO_RAD, LLVector3(dom_value[0], dom_value[1], dom_value[2]), LLVector3(0, 0, 0));
rotation *= mTransform;
mTransform = rotation;
mTransform.condition();
}
domScale* scale = daeSafeCast<domScale>(element);
if (scale)
{
domFloat3 dom_value = scale->getValue();
LLVector3 scale_vector = LLVector3(dom_value[0], dom_value[1], dom_value[2]);
scale_vector.abs(); // Set all values positive, since we don't currently support mirrored meshes
LLMatrix4 scaling;
scaling.initScale(scale_vector);
scaling *= mTransform;
mTransform = scaling;
mTransform.condition();
}
domMatrix* matrix = daeSafeCast<domMatrix>(element);
if (matrix)
{
domFloat4x4 dom_value = matrix->getValue();
LLMatrix4 matrix_transform;
for (int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
matrix_transform.mMatrix[i][j] = dom_value[i + j*4];
}
}
matrix_transform *= mTransform;
mTransform = matrix_transform;
mTransform.condition();
}
domInstance_geometry* instance_geo = daeSafeCast<domInstance_geometry>(element);
if (instance_geo)
{
domGeometry* geo = daeSafeCast<domGeometry>(instance_geo->getUrl().getElement());
if (geo)
{
domMesh* mesh = daeSafeCast<domMesh>(geo->getDescendant(daeElement::matchType(domMesh::ID())));
if (mesh)
{
std::vector< LLPointer< LLModel > >::iterator i = mModelsMap[mesh].begin();
while (i != mModelsMap[mesh].end())
{
LLModel* model = *i;
LLMatrix4 transformation = mTransform;
if (mTransform.determinant() < 0)
{ //negative scales are not supported
LL_INFOS() << "Negative scale detected, unsupported transform. domInstance_geometry: " << getElementLabel(instance_geo) << LL_ENDL;
badElement = true;
}
LLModelLoader::material_map materials = getMaterials(model, instance_geo, dae);
// adjust the transformation to compensate for mesh normalization
LLVector3 mesh_scale_vector;
LLVector3 mesh_translation_vector;
model->getNormalizedScaleTranslation(mesh_scale_vector, mesh_translation_vector);
LLMatrix4 mesh_translation;
mesh_translation.setTranslation(mesh_translation_vector);
mesh_translation *= transformation;
transformation = mesh_translation;
LLMatrix4 mesh_scale;
mesh_scale.initScale(mesh_scale_vector);
mesh_scale *= transformation;
transformation = mesh_scale;
if (transformation.determinant() < 0)
{ //negative scales are not supported
LL_INFOS() << "Negative scale detected, unsupported post-normalization transform. domInstance_geometry: " << getElementLabel(instance_geo) << LL_ENDL;
badElement = true;
}
std::string label;
if (model->mLabel.empty())
{
label = getLodlessLabel(instance_geo);
llassert(!label.empty());
if (model->mSubmodelID)
{
label += (char)((int)'a' + model->mSubmodelID);
}
model->mLabel = label + lod_suffix[mLod];
}
else
{
// Don't change model's name if possible, it will play havoc with scenes that already use said model.
size_t ext_pos = getSuffixPosition(model->mLabel);
if (ext_pos != -1)
{
label = model->mLabel.substr(0, ext_pos);
}
else
{
label = model->mLabel;
}
}
mScene[transformation].push_back(LLModelInstance(model, label, transformation, materials));
stretch_extents(model, transformation, mExtents[0], mExtents[1], mFirstTransform);
i++;
}
}
}
else
{
LL_INFOS()<<"Unable to resolve geometry URL."<<LL_ENDL;
badElement = true;
}
}
domInstance_node* instance_node = daeSafeCast<domInstance_node>(element);
if (instance_node)
{
daeElement* instance = instance_node->getUrl().getElement();
if (instance)
{
processElement(instance,badElement, dae);
}
}
//process children
daeTArray< daeSmartRef<daeElement> > children = element->getChildren();
int childCount = children.getCount();
for (S32 i = 0; i < childCount; i++)
{
processElement(children[i],badElement, dae);
}
if (pushed_mat)
{ //this element was a node, restore transform before processiing siblings
mTransform = saved_transform;
}
}
std::map<std::string, LLImportMaterial> LLDAELoader::getMaterials(LLModel* model, domInstance_geometry* instance_geo, DAE* dae)
{
std::map<std::string, LLImportMaterial> materials;
for (int i = 0; i < model->mMaterialList.size(); i++)
{
LLImportMaterial import_material;
domInstance_material* instance_mat = NULL;
domBind_material::domTechnique_common* technique =
daeSafeCast<domBind_material::domTechnique_common>(instance_geo->getDescendant(daeElement::matchType(domBind_material::domTechnique_common::ID())));
if (technique)
{
daeTArray< daeSmartRef<domInstance_material> > inst_materials = technique->getChildrenByType<domInstance_material>();
for (int j = 0; j < inst_materials.getCount(); j++)
{
std::string symbol(inst_materials[j]->getSymbol());
if (symbol == model->mMaterialList[i]) // found the binding
{
instance_mat = inst_materials[j];
break;
}
}
}
if (instance_mat)
{
domMaterial* material = daeSafeCast<domMaterial>(instance_mat->getTarget().getElement());
if (material)
{
domInstance_effect* instance_effect =
daeSafeCast<domInstance_effect>(material->getDescendant(daeElement::matchType(domInstance_effect::ID())));
if (instance_effect)
{
domEffect* effect = daeSafeCast<domEffect>(instance_effect->getUrl().getElement());
if (effect)
{
domProfile_COMMON* profile =
daeSafeCast<domProfile_COMMON>(effect->getDescendant(daeElement::matchType(domProfile_COMMON::ID())));
if (profile)
{
import_material = profileToMaterial(profile, dae);
}
}
}
}
}
import_material.mBinding = model->mMaterialList[i];
materials[model->mMaterialList[i]] = import_material;
}
return materials;
}
LLImportMaterial LLDAELoader::profileToMaterial(domProfile_COMMON* material, DAE* dae)
{
LLImportMaterial mat;
mat.mFullbright = FALSE;
daeElement* diffuse = material->getDescendant("diffuse");
if (diffuse)
{
domCommon_color_or_texture_type_complexType::domTexture* texture =
daeSafeCast<domCommon_color_or_texture_type_complexType::domTexture>(diffuse->getDescendant("texture"));
if (texture)
{
domCommon_newparam_type_Array newparams = material->getNewparam_array();
if (newparams.getCount())
{
for (S32 i = 0; i < newparams.getCount(); i++)
{
domFx_surface_common* surface = newparams[i]->getSurface();
if (surface)
{
domFx_surface_init_common* init = surface->getFx_surface_init_common();
if (init)
{
domFx_surface_init_from_common_Array init_from = init->getInit_from_array();
if (init_from.getCount() > i)
{
domImage* image = daeSafeCast<domImage>(init_from[i]->getValue().getElement());
if (image)
{
// we only support init_from now - embedded data will come later
domImage::domInit_from* init = image->getInit_from();
if (init)
{
mat.mDiffuseMapFilename = cdom::uriToNativePath(init->getValue().str());
mat.mDiffuseMapLabel = getElementLabel(material);
}
}
}
}
}
}
}
else if (texture->getTexture())
{
domImage* image = NULL;
dae->getDatabase()->getElement((daeElement**) &image, 0, texture->getTexture(), COLLADA_TYPE_IMAGE);
if (image)
{
// we only support init_from now - embedded data will come later
domImage::domInit_from* init = image->getInit_from();
if (init)
{
std::string image_path_value = cdom::uriToNativePath(init->getValue().str());
#if LL_WINDOWS
// Work-around DOM tendency to resort to UNC names which are only confusing for downstream...
//
std::string::iterator i = image_path_value.begin();
while (*i == '\\')
i++;
mat.mDiffuseMapFilename.assign(i, image_path_value.end());
#else
mat.mDiffuseMapFilename = image_path_value;
#endif
mat.mDiffuseMapLabel = getElementLabel(material);
}
}
}
}
domCommon_color_or_texture_type_complexType::domColor* color =
daeSafeCast<domCommon_color_or_texture_type_complexType::domColor>(diffuse->getDescendant("color"));
if (color)
{
domFx_color_common domfx_color = color->getValue();
LLColor4 value = LLColor4(domfx_color[0], domfx_color[1], domfx_color[2], domfx_color[3]);
mat.mDiffuseColor = value;
}
}
daeElement* emission = material->getDescendant("emission");
if (emission)
{
LLColor4 emission_color = getDaeColor(emission);
if (((emission_color[0] + emission_color[1] + emission_color[2]) / 3.0) > 0.25)
{
mat.mFullbright = TRUE;
}
}
return mat;
}
// try to get a decent label for this element
std::string LLDAELoader::getElementLabel(daeElement *element)
{
// if we have a name attribute, use it
std::string name = element->getAttribute("name");
if (name.length())
{
return name;
}
// if we have an ID attribute, use it
if (element->getID())
{
return std::string(element->getID());
}
// if we have a parent, use it
daeElement* parent = element->getParent();
std::string index_string;
if (parent)
{
// retrieve index to distinguish items inside same parent
size_t ind = 0;
parent->getChildren().find(element, ind);
index_string = "_" + boost::lexical_cast<std::string>(ind);
// if parent has a name or ID, use it
std::string name = parent->getAttribute("name");
if (!name.length())
{
name = std::string(parent->getID());
}
if (name.length())
{
// make sure that index won't mix up with pre-named lod extensions
size_t ext_pos = getSuffixPosition(name);
if (ext_pos == -1)
{
return name + index_string;
}
else
{
return name.insert(ext_pos, index_string);
}
}
}
// try to use our type
daeString element_name = element->getElementName();
if (element_name)
{
return std::string(element_name) + index_string;
}
// if all else fails, use "object"
return std::string("object") + index_string;
}
// static
size_t LLDAELoader::getSuffixPosition(std::string label)
{
if ((label.find("_LOD") != -1) || (label.find("_PHYS") != -1))
{
return label.rfind('_');
}
return -1;
}
// static
std::string LLDAELoader::getLodlessLabel(daeElement *element)
{
std::string label = getElementLabel(element);
size_t ext_pos = getSuffixPosition(label);
if (ext_pos != -1)
{
return label.substr(0, ext_pos);
}
return label;
}
LLColor4 LLDAELoader::getDaeColor(daeElement* element)
{
LLColor4 value;
domCommon_color_or_texture_type_complexType::domColor* color =
daeSafeCast<domCommon_color_or_texture_type_complexType::domColor>(element->getDescendant("color"));
if (color)
{
domFx_color_common domfx_color = color->getValue();
value = LLColor4(domfx_color[0], domfx_color[1], domfx_color[2], domfx_color[3]);
}
return value;
}
bool LLDAELoader::addVolumeFacesFromDomMesh(LLModel* pModel,domMesh* mesh)
{
LLModel::EModelStatus status = LLModel::NO_ERRORS;
domTriangles_Array& tris = mesh->getTriangles_array();
for (U32 i = 0; i < tris.getCount(); ++i)
{
domTrianglesRef& tri = tris.get(i);
status = load_face_from_dom_triangles(pModel->getVolumeFaces(), pModel->getMaterialList(), tri);
pModel->mStatus = status;
if(status != LLModel::NO_ERRORS)
{
pModel->ClearFacesAndMaterials();
return false;
}
}
domPolylist_Array& polys = mesh->getPolylist_array();
for (U32 i = 0; i < polys.getCount(); ++i)
{
domPolylistRef& poly = polys.get(i);
status = load_face_from_dom_polylist(pModel->getVolumeFaces(), pModel->getMaterialList(), poly);
if(status != LLModel::NO_ERRORS)
{
pModel->ClearFacesAndMaterials();
return false;
}
}
domPolygons_Array& polygons = mesh->getPolygons_array();
for (U32 i = 0; i < polygons.getCount(); ++i)
{
domPolygonsRef& poly = polygons.get(i);
status = load_face_from_dom_polygons(pModel->getVolumeFaces(), pModel->getMaterialList(), poly);
if(status != LLModel::NO_ERRORS)
{
pModel->ClearFacesAndMaterials();
return false;
}
}
return (status == LLModel::NO_ERRORS);
}
//static
LLModel* LLDAELoader::loadModelFromDomMesh(domMesh *mesh)
{
LLVolumeParams volume_params;
volume_params.setType(LL_PCODE_PROFILE_SQUARE, LL_PCODE_PATH_LINE);
LLModel* ret = new LLModel(volume_params, 0.f);
createVolumeFacesFromDomMesh(ret, mesh);
if (ret->mLabel.empty())
{
ret->mLabel = getElementLabel(mesh);
}
return ret;
}
//static diff version supports creating multiple models when material counts spill
// over the 8 face server-side limit
//
bool LLDAELoader::loadModelsFromDomMesh(domMesh* mesh, std::vector<LLModel*>& models_out, U32 submodel_limit)
{
LLVolumeParams volume_params;
volume_params.setType(LL_PCODE_PROFILE_SQUARE, LL_PCODE_PATH_LINE);
models_out.clear();
LLModel* ret = new LLModel(volume_params, 0.f);
std::string model_name = getLodlessLabel(mesh);
ret->mLabel = model_name + lod_suffix[mLod];
llassert(!ret->mLabel.empty());
// Like a monkey, ready to be shot into space
//
ret->ClearFacesAndMaterials();
// Get the whole set of volume faces
//
addVolumeFacesFromDomMesh(ret, mesh);
U32 volume_faces = ret->getNumVolumeFaces();
// Side-steps all manner of issues when splitting models
// and matching lower LOD materials to base models
//
ret->sortVolumeFacesByMaterialName();
bool normalized = false;
int submodelID = 0;
// remove all faces that definitely won't fit into one model and submodel limit
U32 face_limit = (submodel_limit + 1) * LL_SCULPT_MESH_MAX_FACES;
if (face_limit < volume_faces)
{
ret->setNumVolumeFaces(face_limit);
}
LLVolume::face_list_t remainder;
do
{
// Insure we do this once with the whole gang and not per-model
//
if (!normalized && !mNoNormalize)
{
normalized = true;
ret->normalizeVolumeFaces();
}
ret->trimVolumeFacesToSize(LL_SCULPT_MESH_MAX_FACES, &remainder);
if (!mNoOptimize)
{
ret->optimizeVolumeFaces();
}
volume_faces = remainder.size();
models_out.push_back(ret);
// If we have left-over volume faces, create another model
// to absorb them...
//
if (volume_faces)
{
LLModel* next = new LLModel(volume_params, 0.f);
next->mSubmodelID = ++submodelID;
next->mLabel = model_name + (char)((int)'a' + next->mSubmodelID) + lod_suffix[mLod];
next->getVolumeFaces() = remainder;
next->mNormalizedScale = ret->mNormalizedScale;
next->mNormalizedTranslation = ret->mNormalizedTranslation;
if ( ret->mMaterialList.size() > LL_SCULPT_MESH_MAX_FACES)
{
next->mMaterialList.assign(ret->mMaterialList.begin() + LL_SCULPT_MESH_MAX_FACES, ret->mMaterialList.end());
}
ret = next;
}
remainder.clear();
} while (volume_faces);
return true;
}
bool LLDAELoader::createVolumeFacesFromDomMesh(LLModel* pModel, domMesh* mesh)
{
if (mesh)
{
pModel->ClearFacesAndMaterials();
addVolumeFacesFromDomMesh(pModel, mesh);
if (pModel->getNumVolumeFaces() > 0)
{
pModel->normalizeVolumeFaces();
pModel->optimizeVolumeFaces();
if (pModel->getNumVolumeFaces() > 0)
{
return true;
}
}
}
else
{
LL_WARNS() << "no mesh found" << LL_ENDL;
}
return false;
}
|