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
|
/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2025, assimp team
All rights reserved.
Redistribution and use of this software 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 the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"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.
---------------------------------------------------------------------------
*/
/** @file ColladaParser.cpp
* @brief Implementation of the Collada parser helper
*/
#ifndef ASSIMP_BUILD_NO_COLLADA_IMPORTER
#include "ColladaParser.h"
#include <assimp/ParsingUtils.h>
#include <assimp/StringUtils.h>
#include <assimp/ZipArchiveIOSystem.h>
#include <assimp/commonMetaData.h>
#include <assimp/fast_atof.h>
#include <assimp/light.h>
#include <assimp/DefaultLogger.hpp>
#include <assimp/IOSystem.hpp>
#include <memory>
#include <utility>
using namespace Assimp;
using namespace Assimp::Collada;
using namespace Assimp::Formatter;
// ------------------------------------------------------------------------------------------------
static void ReportWarning(const char *msg, ...) {
ai_assert(nullptr != msg);
va_list args;
va_start(args, msg);
char szBuffer[3000];
const int iLen = vsnprintf(szBuffer, sizeof(szBuffer), msg, args);
ai_assert(iLen > 0);
va_end(args);
ASSIMP_LOG_WARN("Validation warning: ", std::string(szBuffer, iLen));
}
// ------------------------------------------------------------------------------------------------
static bool FindCommonKey(const std::string &collada_key, const MetaKeyPairVector &key_renaming, size_t &found_index) {
for (size_t i = 0; i < key_renaming.size(); ++i) {
if (key_renaming[i].first == collada_key) {
found_index = i;
return true;
}
}
found_index = std::numeric_limits<size_t>::max();
return false;
}
// ------------------------------------------------------------------------------------------------
static void readUrlAttribute(XmlNode &node, std::string &url) {
url.clear();
if (!XmlParser::getStdStrAttribute(node, "url", url)) {
return;
}
if (url[0] != '#') {
throw DeadlyImportError("Unknown reference format");
}
url = url.c_str() + 1;
}
// ------------------------------------------------------------------------------------------------
// Reads a node transformation entry of the given type and adds it to the given node's transformation list.
static void ReadNodeTransformation(XmlNode &node, Node *pNode, TransformType pType) {
if (node.empty()) {
return;
}
std::string tagName = node.name();
Transform tf;
tf.mType = pType;
// read SID
if (XmlParser::hasAttribute(node, "sid")) {
XmlParser::getStdStrAttribute(node, "sid", tf.mID);
}
// how many parameters to read per transformation type
static constexpr unsigned int sNumParameters[] = { 9, 4, 3, 3, 7, 16 };
std::string value;
XmlParser::getValueAsString(node, value);
const char *content = value.c_str();
const char *end = value.c_str() + value.size();
// read as many parameters and store in the transformation
for (unsigned int a = 0; a < sNumParameters[pType]; a++) {
// skip whitespace before the number
SkipSpacesAndLineEnd(&content, end);
// read a number
content = fast_atoreal_move<ai_real>(content, tf.f[a]);
}
// place the transformation at the queue of the node
pNode->mTransforms.push_back(tf);
}
// ------------------------------------------------------------------------------------------------
// Reads a single string metadata item
static void ReadMetaDataItem(XmlNode &node, ColladaParser::StringMetaData &metadata) {
const MetaKeyPairVector &key_renaming = GetColladaAssimpMetaKeysCamelCase();
const std::string name = node.name();
if (name.empty()) {
return;
}
std::string v;
if (!XmlParser::getValueAsString(node, v)) {
return;
}
v = ai_trim(v);
aiString aistr;
aistr.Set(v);
std::string camel_key_str(name);
ToCamelCase(camel_key_str);
size_t found_index;
if (FindCommonKey(camel_key_str, key_renaming, found_index)) {
metadata.emplace(key_renaming[found_index].second, aistr);
} else {
metadata.emplace(camel_key_str, aistr);
}
}
// ------------------------------------------------------------------------------------------------
// Reads an animation sampler into the given anim channel
static void ReadAnimationSampler(const XmlNode &node, AnimationChannel &pChannel) {
for (XmlNode ¤tNode : node.children()) {
const std::string ¤tName = currentNode.name();
if (currentName == "input") {
if (XmlParser::hasAttribute(currentNode, "semantic")) {
std::string semantic, sourceAttr;
XmlParser::getStdStrAttribute(currentNode, "semantic", semantic);
if (XmlParser::hasAttribute(currentNode, "source")) {
XmlParser::getStdStrAttribute(currentNode, "source", sourceAttr);
const char *source = sourceAttr.c_str();
if (source[0] != '#') {
throw DeadlyImportError("Unsupported URL format");
}
source++;
if (semantic == "INPUT") {
pChannel.mSourceTimes = source;
} else if (semantic == "OUTPUT") {
pChannel.mSourceValues = source;
} else if (semantic == "IN_TANGENT") {
pChannel.mInTanValues = source;
} else if (semantic == "OUT_TANGENT") {
pChannel.mOutTanValues = source;
} else if (semantic == "INTERPOLATION") {
pChannel.mInterpolationValues = source;
}
}
}
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads the joint definitions for the given controller
static void ReadControllerJoints(const XmlNode &node, Controller &pController) {
for (XmlNode ¤tNode : node.children()) {
const std::string ¤tName = currentNode.name();
if (currentName == "input") {
const char *attrSemantic = currentNode.attribute("semantic").as_string();
const char *attrSource = currentNode.attribute("source").as_string();
if (attrSource[0] != '#') {
throw DeadlyImportError("Unsupported URL format in \"", attrSource, "\" in source attribute of <joints> data <input> element");
}
++attrSource;
// parse source URL to corresponding source
if (strcmp(attrSemantic, "JOINT") == 0) {
pController.mJointNameSource = attrSource;
} else if (strcmp(attrSemantic, "INV_BIND_MATRIX") == 0) {
pController.mJointOffsetMatrixSource = attrSource;
} else {
throw DeadlyImportError("Unknown semantic \"", attrSemantic, "\" in <joints> data <input> element");
}
}
}
}
// ------------------------------------------------------------------------------------------------
static void ReadControllerWeightsInput(const XmlNode ¤tNode, Controller &pController) {
InputChannel channel;
const char *attrSemantic = currentNode.attribute("semantic").as_string();
const char *attrSource = currentNode.attribute("source").as_string();
channel.mOffset = currentNode.attribute("offset").as_int();
// local URLS always start with a '#'. We don't support global URLs
if (attrSource[0] != '#') {
throw DeadlyImportError("Unsupported URL format in \"", attrSource, "\" in source attribute of <vertex_weights> data <input> element");
}
channel.mAccessor = attrSource + 1;
// parse source URL to corresponding source
if (strcmp(attrSemantic, "JOINT") == 0) {
pController.mWeightInputJoints = channel;
} else if (strcmp(attrSemantic, "WEIGHT") == 0) {
pController.mWeightInputWeights = channel;
} else {
throw DeadlyImportError("Unknown semantic \"", attrSemantic, "\" in <vertex_weights> data <input> element");
}
}
// ------------------------------------------------------------------------------------------------
static void ReadControllerWeightsVCount(const XmlNode ¤tNode, Controller &pController) {
const std::string stdText = currentNode.text().as_string();
const char *text = stdText.c_str();
const char *end = text + stdText.size();
size_t numWeights = 0;
for (auto it = pController.mWeightCounts.begin(); it != pController.mWeightCounts.end(); ++it) {
if (*text == 0) {
throw DeadlyImportError("Out of data while reading <vcount>");
}
*it = strtoul10(text, &text);
numWeights += *it;
SkipSpacesAndLineEnd(&text, end);
}
// reserve weight count
pController.mWeights.resize(numWeights);
}
// ------------------------------------------------------------------------------------------------
static void ReadControllerWeightsJoint2verts(XmlNode ¤tNode, Controller &pController) {
// read JointIndex - WeightIndex pairs
std::string stdText;
XmlParser::getValueAsString(currentNode, stdText);
const char *text = stdText.c_str();
const char *end = text + stdText.size();
for (auto it = pController.mWeights.begin(); it != pController.mWeights.end(); ++it) {
if (text == nullptr) {
throw DeadlyImportError("Out of data while reading <vertex_weights>");
}
SkipSpacesAndLineEnd(&text, end);
it->first = strtoul10(text, &text);
SkipSpacesAndLineEnd(&text, end);
if (*text == 0) {
throw DeadlyImportError("Out of data while reading <vertex_weights>");
}
it->second = strtoul10(text, &text);
SkipSpacesAndLineEnd(&text, end);
}
}
// ------------------------------------------------------------------------------------------------
// Reads the joint weights for the given controller
static void ReadControllerWeights(XmlNode &node, Controller &pController) {
// Read vertex count from attributes and resize the array accordingly
int vertexCount = 0;
XmlParser::getIntAttribute(node, "count", vertexCount);
pController.mWeightCounts.resize(vertexCount);
for (XmlNode ¤tNode : node.children()) {
const std::string ¤tName = currentNode.name();
if (currentName == "input") {
ReadControllerWeightsInput(currentNode, pController);
} else if (currentName == "vcount" && vertexCount > 0) {
ReadControllerWeightsVCount(currentNode, pController);
} else if (currentName == "v" && vertexCount > 0) {
ReadControllerWeightsJoint2verts(currentNode, pController);
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads a material entry into the given material
static void ReadMaterial(const XmlNode &node, Material &pMaterial) {
for (XmlNode ¤tNode : node.children()) {
const std::string ¤tName = currentNode.name();
if (currentName == "instance_effect") {
std::string url;
readUrlAttribute(currentNode, url);
pMaterial.mEffect = url;
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads a light entry into the given light
static void ReadLight(XmlNode &node, Light &pLight) {
XmlNodeIterator xmlIt(node, XmlNodeIterator::PreOrderMode);
XmlNode currentNode;
// TODO: Check the current technique and skip over unsupported extra techniques
while (xmlIt.getNext(currentNode)) {
const std::string ¤tName = currentNode.name();
if (currentName == "spot") {
pLight.mType = aiLightSource_SPOT;
} else if (currentName == "ambient") {
pLight.mType = aiLightSource_AMBIENT;
} else if (currentName == "directional") {
pLight.mType = aiLightSource_DIRECTIONAL;
} else if (currentName == "point") {
pLight.mType = aiLightSource_POINT;
} else if (currentName == "color") {
// text content contains 3 floats
std::string v;
XmlParser::getValueAsString(currentNode, v);
const char *content = v.c_str();
const char *end = content + v.size();
content = fast_atoreal_move<ai_real>(content, (ai_real &)pLight.mColor.r);
SkipSpacesAndLineEnd(&content, end);
content = fast_atoreal_move<ai_real>(content, (ai_real &)pLight.mColor.g);
SkipSpacesAndLineEnd(&content, end);
content = fast_atoreal_move<ai_real>(content, (ai_real &)pLight.mColor.b);
SkipSpacesAndLineEnd(&content, end);
} else if (currentName == "constant_attenuation") {
XmlParser::getValueAsReal(currentNode, pLight.mAttConstant);
} else if (currentName == "linear_attenuation") {
XmlParser::getValueAsReal(currentNode, pLight.mAttLinear);
} else if (currentName == "quadratic_attenuation") {
XmlParser::getValueAsReal(currentNode, pLight.mAttQuadratic);
} else if (currentName == "falloff_angle") {
XmlParser::getValueAsReal(currentNode, pLight.mFalloffAngle);
} else if (currentName == "falloff_exponent") {
XmlParser::getValueAsReal(currentNode, pLight.mFalloffExponent);
}
// FCOLLADA extensions
// -------------------------------------------------------
else if (currentName == "outer_cone") {
XmlParser::getValueAsReal(currentNode, pLight.mOuterAngle);
} else if (currentName == "penumbra_angle") { // this one is deprecated, now calculated using outer_cone
XmlParser::getValueAsReal(currentNode, pLight.mPenumbraAngle);
} else if (currentName == "intensity") {
XmlParser::getValueAsReal(currentNode, pLight.mIntensity);
} else if (currentName == "falloff") {
XmlParser::getValueAsReal(currentNode, pLight.mOuterAngle);
} else if (currentName == "hotspot_beam") {
XmlParser::getValueAsReal(currentNode, pLight.mFalloffAngle);
}
// OpenCOLLADA extensions
// -------------------------------------------------------
else if (currentName == "decay_falloff") {
XmlParser::getValueAsReal(currentNode, pLight.mOuterAngle);
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads a camera entry into the given light
static void ReadCamera(XmlNode &node, Camera &camera) {
XmlNodeIterator xmlIt(node, XmlNodeIterator::PreOrderMode);
XmlNode currentNode;
while (xmlIt.getNext(currentNode)) {
const std::string ¤tName = currentNode.name();
if (currentName == "orthographic") {
camera.mOrtho = true;
} else if (currentName == "xfov" || currentName == "xmag") {
XmlParser::getValueAsReal(currentNode, camera.mHorFov);
} else if (currentName == "yfov" || currentName == "ymag") {
XmlParser::getValueAsReal(currentNode, camera.mVerFov);
} else if (currentName == "aspect_ratio") {
XmlParser::getValueAsReal(currentNode, camera.mAspect);
} else if (currentName == "znear") {
XmlParser::getValueAsReal(currentNode, camera.mZNear);
} else if (currentName == "zfar") {
XmlParser::getValueAsReal(currentNode, camera.mZFar);
}
}
}
// ------------------------------------------------------------------------------------------------
// Constructor to be privately used by Importer
ColladaParser::ColladaParser(IOSystem *pIOHandler, const std::string &pFile) :
mFileName(pFile),
mRootNode(nullptr),
mUnitSize(1.0f),
mUpDirection(UP_Y),
mFormat(FV_1_5_n) {
if (nullptr == pIOHandler) {
throw DeadlyImportError("IOSystem is nullptr.");
}
std::unique_ptr<IOStream> daeFile;
std::unique_ptr<ZipArchiveIOSystem> zip_archive;
// Determine type
const std::string extension = BaseImporter::GetExtension(pFile);
if (extension != "dae") {
zip_archive = std::make_unique<ZipArchiveIOSystem>(pIOHandler, pFile);
}
if (zip_archive && zip_archive->isOpen()) {
std::string dae_filename = ReadZaeManifest(*zip_archive);
if (dae_filename.empty()) {
throw DeadlyImportError("Invalid ZAE");
}
daeFile.reset(zip_archive->Open(dae_filename.c_str()));
if (daeFile == nullptr) {
throw DeadlyImportError("Invalid ZAE manifest: '", dae_filename, "' is missing");
}
} else {
// attempt to open the file directly
daeFile.reset(pIOHandler->Open(pFile));
if (daeFile == nullptr) {
throw DeadlyImportError("Failed to open file '", pFile, "'.");
}
}
// generate a XML reader for it
if (!mXmlParser.parse(daeFile.get())) {
throw DeadlyImportError("Unable to read file, malformed XML");
}
// start reading
const XmlNode node = mXmlParser.getRootNode();
XmlNode colladaNode = node.child("COLLADA");
if (colladaNode.empty()) {
return;
}
// Read content and embedded textures
ReadContents(colladaNode);
if (zip_archive && zip_archive->isOpen()) {
ReadEmbeddedTextures(*zip_archive);
}
}
// ------------------------------------------------------------------------------------------------
// Destructor, private as well
ColladaParser::~ColladaParser() {
for (auto &it : mNodeLibrary) {
delete it.second;
}
for (auto &it : mMeshLibrary) {
delete it.second;
}
}
// ------------------------------------------------------------------------------------------------
// Read a ZAE manifest and return the filename to attempt to open
std::string ColladaParser::ReadZaeManifest(ZipArchiveIOSystem &zip_archive) {
// Open the manifest
std::unique_ptr<IOStream> manifestfile(zip_archive.Open("manifest.xml"));
if (manifestfile == nullptr) {
// No manifest, hope there is only one .DAE inside
std::vector<std::string> file_list;
zip_archive.getFileListExtension(file_list, "dae");
if (file_list.empty()) {
return {};
}
return file_list.front();
}
XmlParser manifestParser;
if (!manifestParser.parse(manifestfile.get())) {
return {};
}
XmlNode root = manifestParser.getRootNode();
const std::string &name = root.name();
if (name != "dae_root") {
root = *manifestParser.findNode("dae_root");
if (nullptr == root) {
return {};
}
std::string v;
XmlParser::getValueAsString(root, v);
aiString ai_str(v);
UriDecodePath(ai_str);
return std::string(ai_str.C_Str());
}
return {};
}
// ------------------------------------------------------------------------------------------------
// Convert a path read from a collada file to the usual representation
void ColladaParser::UriDecodePath(aiString &ss) {
// TODO: collada spec, p 22. Handle URI correctly.
// For the moment we're just stripping the file:// away to make it work.
// Windows doesn't seem to be able to find stuff like
// 'file://..\LWO\LWO2\MappingModes\earthSpherical.jpg'
if (0 == strncmp(ss.data, "file://", 7)) {
ss.length -= 7;
memmove(ss.data, ss.data + 7, ss.length);
ss.data[ss.length] = '\0';
}
// Maxon Cinema Collada Export writes "file:///C:\andsoon" with three slashes...
// I need to filter it without destroying linux paths starting with "/somewhere"
if (ss.data[0] == '/' && isalpha((unsigned char)ss.data[1]) && ss.data[2] == ':') {
--ss.length;
::memmove(ss.data, ss.data + 1, ss.length);
ss.data[ss.length] = 0;
}
// find and convert all %xy special chars
char *out = ss.data;
for (const char *it = ss.data; it != ss.data + ss.length; /**/) {
if (*it == '%' && (it + 3) < ss.data + ss.length) {
// separate the number to avoid dragging in chars from behind into the parsing
char mychar[3] = { it[1], it[2], 0 };
size_t nbr = strtoul16(mychar);
it += 3;
*out++ = static_cast<char>(nbr & 0xFF);
} else {
*out++ = *it++;
}
}
// adjust length and terminator of the shortened string
*out = 0;
ai_assert(out > ss.data);
ss.length = static_cast<ai_uint32>(out - ss.data);
}
// ------------------------------------------------------------------------------------------------
// Reads the contents of the file
void ColladaParser::ReadContents(XmlNode &node) {
if (const std::string name = node.name(); name == "COLLADA") {
std::string version;
if (XmlParser::getStdStrAttribute(node, "version", version)) {
aiString v;
v.Set(version);
mAssetMetaData.emplace(AI_METADATA_SOURCE_FORMAT_VERSION, v);
if (!::strncmp(version.c_str(), "1.5", 3)) {
mFormat = FV_1_5_n;
ASSIMP_LOG_DEBUG("Collada schema version is 1.5.n");
} else if (!::strncmp(version.c_str(), "1.4", 3)) {
mFormat = FV_1_4_n;
ASSIMP_LOG_DEBUG("Collada schema version is 1.4.n");
} else if (!::strncmp(version.c_str(), "1.3", 3)) {
mFormat = FV_1_3_n;
ASSIMP_LOG_DEBUG("Collada schema version is 1.3.n");
}
}
ReadStructure(node);
}
}
// ------------------------------------------------------------------------------------------------
// Reads the structure of the file
void ColladaParser::ReadStructure(XmlNode &node) {
for (XmlNode ¤tNode : node.children()) {
if (const std::string ¤tName = currentNode.name(); currentName == "asset") {
ReadAssetInfo(currentNode);
} else if (currentName == "library_animations") {
ReadAnimationLibrary(currentNode);
} else if (currentName == "library_animation_clips") {
ReadAnimationClipLibrary(currentNode);
} else if (currentName == "library_controllers") {
ReadControllerLibrary(currentNode);
} else if (currentName == "library_images") {
ReadImageLibrary(currentNode);
} else if (currentName == "library_materials") {
ReadMaterialLibrary(currentNode);
} else if (currentName == "library_effects") {
ReadEffectLibrary(currentNode);
} else if (currentName == "library_geometries") {
ReadGeometryLibrary(currentNode);
} else if (currentName == "library_visual_scenes") {
ReadSceneLibrary(currentNode);
} else if (currentName == "library_lights") {
ReadLightLibrary(currentNode);
} else if (currentName == "library_cameras") {
ReadCameraLibrary(currentNode);
} else if (currentName == "library_nodes") {
ReadSceneNode(currentNode, nullptr); /* some hacking to reuse this piece of code */
} else if (currentName == "scene") {
ReadScene(currentNode);
}
}
PostProcessRootAnimations();
PostProcessControllers();
}
// ------------------------------------------------------------------------------------------------
// Reads asset information such as coordinate system information and legal blah
void ColladaParser::ReadAssetInfo(XmlNode &node) {
if (node.empty()) {
return;
}
for (XmlNode ¤tNode : node.children()) {
if (const std::string ¤tName = currentNode.name(); currentName == "unit") {
mUnitSize = 1.f;
std::string tUnitSizeString;
if (XmlParser::getStdStrAttribute(currentNode, "meter", tUnitSizeString)) {
try {
fast_atoreal_move<ai_real>(tUnitSizeString.data(), mUnitSize);
} catch (const DeadlyImportError& die) {
std::string warning("Collada: Failed to parse meter parameter to real number. Exception:\n");
warning.append(die.what());
ASSIMP_LOG_WARN(warning.data());
}
}
} else if (currentName == "up_axis") {
std::string v;
if (!XmlParser::getValueAsString(currentNode, v)) {
continue;
}
if (v == "X_UP") {
mUpDirection = UP_X;
} else if (v == "Z_UP") {
mUpDirection = UP_Z;
} else {
mUpDirection = UP_Y;
}
} else if (currentName == "contributor") {
for (XmlNode currentChildNode : currentNode.children()) {
ReadMetaDataItem(currentChildNode, mAssetMetaData);
}
} else {
ReadMetaDataItem(currentNode, mAssetMetaData);
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads the animation clips
void ColladaParser::ReadAnimationClipLibrary(XmlNode &node) {
if (node.empty()) {
return;
}
std::string animName;
if (!XmlParser::getStdStrAttribute(node, "name", animName)) {
if (!XmlParser::getStdStrAttribute(node, "id", animName)) {
animName = std::string("animation_") + ai_to_string(mAnimationClipLibrary.size());
}
}
std::pair<std::string, std::vector<std::string>> clip;
clip.first = animName;
for (XmlNode ¤tNode : node.children()) {
const std::string ¤tName = currentNode.name();
if (currentName == "instance_animation") {
std::string url;
readUrlAttribute(currentNode, url);
clip.second.push_back(url);
}
if (clip.second.size() > 0) {
mAnimationClipLibrary.push_back(clip);
}
}
}
// ------------------------------------------------------------------------------------------------
// The controller post processing step
void ColladaParser::PostProcessControllers() {
for (auto &it : mControllerLibrary) {
std::string meshId = it.second.mMeshId;
if (meshId.empty()) {
continue;
}
auto findItr = mControllerLibrary.find(meshId);
while (findItr != mControllerLibrary.end()) {
meshId = findItr->second.mMeshId;
findItr = mControllerLibrary.find(meshId);
}
it.second.mMeshId = meshId;
}
}
// ------------------------------------------------------------------------------------------------
// Re-build animations from animation clip library, if present, otherwise combine single-channel animations
void ColladaParser::PostProcessRootAnimations() {
if (mAnimationClipLibrary.empty()) {
mAnims.CombineSingleChannelAnimations();
return;
}
Animation temp;
for (auto &it : mAnimationClipLibrary) {
std::string clipName = it.first;
auto *clip = new Animation();
clip->mName = clipName;
temp.mSubAnims.push_back(clip);
for (const std::string &animationID : it.second) {
auto animation = mAnimationLibrary.find(animationID);
if (animation != mAnimationLibrary.end()) {
Animation *pSourceAnimation = animation->second;
pSourceAnimation->CollectChannelsRecursively(clip->mChannels);
}
}
}
mAnims = temp;
// Ensure no double deletes.
temp.mSubAnims.clear();
}
// ------------------------------------------------------------------------------------------------
// Reads the animation library
void ColladaParser::ReadAnimationLibrary(XmlNode &node) {
if (node.empty()) {
return;
}
for (XmlNode ¤tNode : node.children()) {
const std::string ¤tName = currentNode.name();
if (currentName == "animation") {
ReadAnimation(currentNode, &mAnims);
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads an animation into the given parent structure
void ColladaParser::ReadAnimation(XmlNode &node, Collada::Animation *pParent) {
if (node.empty()) {
return;
}
// an <animation> element may be a container for grouping sub-elements or an animation channel
// this is the channel collection by ID, in case it has channels
using ChannelMap = std::map<std::string, AnimationChannel>;
ChannelMap channels;
// this is the anim container in case we're a container
Animation *anim = nullptr;
// optional name given as an attribute
std::string animName;
if (!XmlParser::getStdStrAttribute(node, "name", animName)) {
animName = "animation";
}
std::string animID;
pugi::xml_attribute idAttr = node.attribute("id");
if (idAttr) {
animID = idAttr.as_string();
}
for (XmlNode ¤tNode : node.children()) {
const std::string ¤tName = currentNode.name();
if (currentName == "animation") {
if (!anim) {
anim = new Animation;
anim->mName = animName;
pParent->mSubAnims.push_back(anim);
}
// recurse into the sub-element
ReadAnimation(currentNode, anim);
} else if (currentName == "source") {
ReadSource(currentNode);
} else if (currentName == "sampler") {
std::string id;
if (XmlParser::getStdStrAttribute(currentNode, "id", id)) {
// have it read into a channel
auto newChannel = channels.insert(std::make_pair(id, AnimationChannel())).first;
ReadAnimationSampler(currentNode, newChannel->second);
}
} else if (currentName == "channel") {
std::string source_name, target;
XmlParser::getStdStrAttribute(currentNode, "source", source_name);
XmlParser::getStdStrAttribute(currentNode, "target", target);
if (source_name[0] == '#') {
source_name = source_name.substr(1, source_name.size() - 1);
}
auto cit = channels.find(source_name);
if (cit != channels.end()) {
cit->second.mTarget = target;
}
}
}
// it turned out to have channels - add them
if (!channels.empty()) {
if (nullptr == anim) {
anim = new Animation;
anim->mName = animName;
pParent->mSubAnims.push_back(anim);
}
for (const auto &channel : channels) {
anim->mChannels.push_back(channel.second);
}
if (idAttr) {
mAnimationLibrary[animID] = anim;
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads the skeleton controller library
void ColladaParser::ReadControllerLibrary(XmlNode &node) {
if (node.empty()) {
return;
}
for (XmlNode ¤tNode : node.children()) {
const std::string ¤tName = currentNode.name();
if (currentName != "controller") {
continue;
}
if (std::string id; XmlParser::getStdStrAttribute(currentNode, "id", id)) {
mControllerLibrary[id] = Controller();
ReadController(currentNode, mControllerLibrary[id]);
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads a controller into the given mesh structure
void ColladaParser::ReadController(XmlNode &node, Collada::Controller &controller) {
// initial values
controller.mType = Skin;
controller.mMethod = Normalized;
XmlNodeIterator xmlIt(node, XmlNodeIterator::PreOrderMode);
XmlNode currentNode;
while (xmlIt.getNext(currentNode)) {
if (const std::string ¤tName = currentNode.name(); currentName == "morph") {
controller.mType = Morph;
std::string id = currentNode.attribute("source").as_string();
controller.mMeshId = id.substr(1, id.size() - 1);
if (const int methodIndex = currentNode.attribute("method").as_int(); methodIndex > 0) {
std::string method;
XmlParser::getValueAsString(currentNode, method);
if (method == "RELATIVE") {
controller.mMethod = Relative;
}
}
} else if (currentName == "skin") {
if (std::string id; XmlParser::getStdStrAttribute(currentNode, "source", id)) {
controller.mMeshId = id.substr(1, id.size() - 1);
}
} else if (currentName == "bind_shape_matrix") {
std::string v;
XmlParser::getValueAsString(currentNode, v);
const char *content = v.c_str();
const char *end = content + v.size();
for (auto & a : controller.mBindShapeMatrix) {
SkipSpacesAndLineEnd(&content, end);
// read a number
content = fast_atoreal_move<ai_real>(content, a);
// skip whitespace after it
SkipSpacesAndLineEnd(&content, end);
}
} else if (currentName == "source") {
ReadSource(currentNode);
} else if (currentName == "joints") {
ReadControllerJoints(currentNode, controller);
} else if (currentName == "vertex_weights") {
ReadControllerWeights(currentNode, controller);
} else if (currentName == "targets") {
for (XmlNode currentChildNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
const std::string ¤tChildName = currentChildNode.name();
if (currentChildName == "input") {
const char *semantics = currentChildNode.attribute("semantic").as_string();
const char *source = currentChildNode.attribute("source").as_string();
if (strcmp(semantics, "MORPH_TARGET") == 0) {
controller.mMorphTarget = source + 1;
} else if (strcmp(semantics, "MORPH_WEIGHT") == 0) {
controller.mMorphWeight = source + 1;
}
}
}
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads the image library contents
void ColladaParser::ReadImageLibrary(const XmlNode &node) {
for (XmlNode ¤tNode : node.children()) {
const std::string ¤tName = currentNode.name();
if (currentName == "image") {
if (std::basic_string<char> id; XmlParser::getStdStrAttribute(currentNode, "id", id)) {
mImageLibrary[id] = Image();
// read on from there
ReadImage(currentNode, mImageLibrary[id]);
}
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads an image entry into the given image
void ColladaParser::ReadImage(const XmlNode &node, Collada::Image &pImage) const {
for (XmlNode ¤tNode : node.children()) {
const std::string currentName = currentNode.name();
if (currentName == "image") {
// Ignore
continue;
} else if (currentName == "init_from") {
if (mFormat == FV_1_4_n) {
// FIX: C4D exporter writes empty <init_from/> tags
if (!currentNode.empty()) {
// element content is filename - hopefully
const char *sz = currentNode.text().as_string();
if (nullptr != sz) {
aiString filepath(sz);
UriDecodePath(filepath);
pImage.mFileName = filepath.C_Str();
}
}
if (!pImage.mFileName.length()) {
pImage.mFileName = "unknown_texture";
}
} else if (mFormat == FV_1_5_n) {
std::string value;
XmlNode refChild = currentNode.child("ref");
XmlNode hexChild = currentNode.child("hex");
if (refChild) {
// element content is filename - hopefully
if (XmlParser::getValueAsString(refChild, value)) {
aiString filepath(value);
UriDecodePath(filepath);
pImage.mFileName = filepath.C_Str();
}
} else if (hexChild && !pImage.mFileName.length()) {
// embedded image. get format
pImage.mEmbeddedFormat = hexChild.attribute("format").as_string();
if (pImage.mEmbeddedFormat.empty()) {
ASSIMP_LOG_WARN("Collada: Unknown image file format");
}
XmlParser::getValueAsString(hexChild, value);
const char *data = value.c_str();
// hexadecimal-encoded binary octets. First of all, find the
// required buffer size to reserve enough storage.
const char *cur = data;
while (!IsSpaceOrNewLine(*cur)) {
++cur;
}
const unsigned int size = (unsigned int)(cur - data) * 2;
pImage.mImageData.resize(size);
for (unsigned int i = 0; i < size; ++i) {
pImage.mImageData[i] = HexOctetToDecimal(data + (i << 1));
}
}
}
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads the material library
void ColladaParser::ReadMaterialLibrary(XmlNode &node) {
std::map<std::string, int> names;
for (const XmlNode ¤tNode : node.children()) {
std::string id = currentNode.attribute("id").as_string();
std::string name = currentNode.attribute("name").as_string();
mMaterialLibrary[id] = Material();
if (!name.empty()) {
auto it = names.find(name);
if (it != names.end()) {
std::ostringstream strStream;
strStream << ++it->second;
name.append(" " + strStream.str());
} else {
names[name] = 0;
}
mMaterialLibrary[id].mName = name;
}
ReadMaterial(currentNode, mMaterialLibrary[id]);
}
}
// ------------------------------------------------------------------------------------------------
// Reads the light library
void ColladaParser::ReadLightLibrary(XmlNode &node) {
for (XmlNode ¤tNode : node.children()) {
const std::string ¤tName = currentNode.name();
if (currentName == "light") {
std::string id;
if (XmlParser::getStdStrAttribute(currentNode, "id", id)) {
ReadLight(currentNode, mLightLibrary[id] = Light());
}
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads the camera library
void ColladaParser::ReadCameraLibrary(XmlNode &node) {
for (XmlNode ¤tNode : node.children()) {
const std::string ¤tName = currentNode.name();
if (currentName == "camera") {
std::string id;
if (!XmlParser::getStdStrAttribute(currentNode, "id", id)) {
continue;
}
// create an entry and store it in the library under its ID
Camera &cam = mCameraLibrary[id];
std::string name;
if (!XmlParser::getStdStrAttribute(currentNode, "name", name)) {
continue;
}
if (!name.empty()) {
cam.mName = name;
}
ReadCamera(currentNode, cam);
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads the effect library
void ColladaParser::ReadEffectLibrary(XmlNode &node) {
if (node.empty()) {
return;
}
for (XmlNode ¤tNode : node.children()) {
const std::string ¤tName = currentNode.name();
if (currentName == "effect") {
// read ID. Do I have to repeat my ranting about "optional" attributes?
std::string id;
XmlParser::getStdStrAttribute(currentNode, "id", id);
// create an entry and store it in the library under its ID
mEffectLibrary[id] = Effect();
// read on from there
ReadEffect(currentNode, mEffectLibrary[id]);
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads an effect entry into the given effect
void ColladaParser::ReadEffect(XmlNode &node, Collada::Effect &pEffect) {
for (XmlNode ¤tNode : node.children()) {
const std::string ¤tName = currentNode.name();
if (currentName == "profile_COMMON") {
ReadEffectProfileCommon(currentNode, pEffect);
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads an COMMON effect profile
void ColladaParser::ReadEffectProfileCommon(XmlNode &node, Collada::Effect &pEffect) {
XmlNodeIterator xmlIt(node, XmlNodeIterator::PreOrderMode);
XmlNode currentNode;
while (xmlIt.getNext(currentNode)) {
const std::string currentName = currentNode.name();
if (currentName == "newparam") {
// save ID
std::string sid = currentNode.attribute("sid").as_string();
pEffect.mParams[sid] = EffectParam();
ReadEffectParam(currentNode, pEffect.mParams[sid]);
} else if (currentName == "technique" || currentName == "extra") {
// just syntactic sugar
} else if (mFormat == FV_1_4_n && currentName == "image") {
// read ID. Another entry which is "optional" by design but obligatory in reality
std::string id = currentNode.attribute("id").as_string();
// create an entry and store it in the library under its ID
mImageLibrary[id] = Image();
// read on from there
ReadImage(currentNode, mImageLibrary[id]);
} else if (currentName == "phong")
pEffect.mShadeType = Shade_Phong;
else if (currentName == "constant")
pEffect.mShadeType = Shade_Constant;
else if (currentName == "lambert")
pEffect.mShadeType = Shade_Lambert;
else if (currentName == "blinn")
pEffect.mShadeType = Shade_Blinn;
/* Color + texture properties */
else if (currentName == "emission")
ReadEffectColor(currentNode, pEffect.mEmissive, pEffect.mTexEmissive);
else if (currentName == "ambient")
ReadEffectColor(currentNode, pEffect.mAmbient, pEffect.mTexAmbient);
else if (currentName == "diffuse")
ReadEffectColor(currentNode, pEffect.mDiffuse, pEffect.mTexDiffuse);
else if (currentName == "specular")
ReadEffectColor(currentNode, pEffect.mSpecular, pEffect.mTexSpecular);
else if (currentName == "reflective") {
ReadEffectColor(currentNode, pEffect.mReflective, pEffect.mTexReflective);
} else if (currentName == "transparent") {
pEffect.mHasTransparency = true;
const char *opaque = currentNode.attribute("opaque").as_string();
//const char *opaque = mReader->getAttributeValueSafe("opaque");
if (::strcmp(opaque, "RGB_ZERO") == 0 || ::strcmp(opaque, "RGB_ONE") == 0) {
pEffect.mRGBTransparency = true;
}
// In RGB_ZERO mode, the transparency is interpreted in reverse, go figure...
if (::strcmp(opaque, "RGB_ZERO") == 0 || ::strcmp(opaque, "A_ZERO") == 0) {
pEffect.mInvertTransparency = true;
}
ReadEffectColor(currentNode, pEffect.mTransparent, pEffect.mTexTransparent);
} else if (currentName == "shininess")
ReadEffectFloat(currentNode, pEffect.mShininess);
else if (currentName == "reflectivity")
ReadEffectFloat(currentNode, pEffect.mReflectivity);
/* Single scalar properties */
else if (currentName == "transparency")
ReadEffectFloat(currentNode, pEffect.mTransparency);
else if (currentName == "index_of_refraction")
ReadEffectFloat(currentNode, pEffect.mRefractIndex);
// GOOGLEEARTH/OKINO extensions
// -------------------------------------------------------
else if (currentName == "double_sided")
XmlParser::getValueAsBool(currentNode, pEffect.mDoubleSided);
// FCOLLADA extensions
// -------------------------------------------------------
else if (currentName == "bump") {
aiColor4D dummy;
ReadEffectColor(currentNode, dummy, pEffect.mTexBump);
}
// MAX3D extensions
// -------------------------------------------------------
else if (currentName == "wireframe") {
XmlParser::getValueAsBool(currentNode, pEffect.mWireframe);
} else if (currentName == "faceted") {
XmlParser::getValueAsBool(currentNode, pEffect.mFaceted);
}
}
}
// ------------------------------------------------------------------------------------------------
// Read texture wrapping + UV transform settings from a profile==Maya chunk
void ColladaParser::ReadSamplerProperties(XmlNode &node, Sampler &out) {
if (node.empty()) {
return;
}
XmlNodeIterator xmlIt(node, XmlNodeIterator::PreOrderMode);
XmlNode currentNode;
while (xmlIt.getNext(currentNode)) {
const std::string ¤tName = currentNode.name();
// MAYA extensions
// -------------------------------------------------------
if (currentName == "wrapU") {
XmlParser::getValueAsBool(currentNode, out.mWrapU);
} else if (currentName == "wrapV") {
XmlParser::getValueAsBool(currentNode, out.mWrapV);
} else if (currentName == "mirrorU") {
XmlParser::getValueAsBool(currentNode, out.mMirrorU);
} else if (currentName == "mirrorV") {
XmlParser::getValueAsBool(currentNode, out.mMirrorV);
} else if (currentName == "repeatU") {
XmlParser::getValueAsReal(currentNode, out.mTransform.mScaling.x);
} else if (currentName == "repeatV") {
XmlParser::getValueAsReal(currentNode, out.mTransform.mScaling.y);
} else if (currentName == "offsetU") {
XmlParser::getValueAsReal(currentNode, out.mTransform.mTranslation.x);
} else if (currentName == "offsetV") {
XmlParser::getValueAsReal(currentNode, out.mTransform.mTranslation.y);
} else if (currentName == "rotateUV") {
XmlParser::getValueAsReal(currentNode, out.mTransform.mRotation);
} else if (currentName == "blend_mode") {
std::string v;
XmlParser::getValueAsString(currentNode, v);
const char *sz = v.c_str();
// http://www.feelingsoftware.com/content/view/55/72/lang,en/
// NONE, OVER, IN, OUT, ADD, SUBTRACT, MULTIPLY, DIFFERENCE, LIGHTEN, DARKEN, SATURATE, DESATURATE and ILLUMINATE
if (0 == ASSIMP_strincmp(sz, "ADD", 3))
out.mOp = aiTextureOp_Add;
else if (0 == ASSIMP_strincmp(sz, "SUBTRACT", 8))
out.mOp = aiTextureOp_Subtract;
else if (0 == ASSIMP_strincmp(sz, "MULTIPLY", 8))
out.mOp = aiTextureOp_Multiply;
else {
ASSIMP_LOG_WARN("Collada: Unsupported MAYA texture blend mode");
}
}
// OKINO extensions
// -------------------------------------------------------
else if (currentName == "weighting") {
XmlParser::getValueAsReal(currentNode, out.mWeighting);
} else if (currentName == "mix_with_previous_layer") {
XmlParser::getValueAsReal(currentNode, out.mMixWithPrevious);
}
// MAX3D extensions
// -------------------------------------------------------
else if (currentName == "amount") {
XmlParser::getValueAsReal(currentNode, out.mWeighting);
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads an effect entry containing a color or a texture defining that color
void ColladaParser::ReadEffectColor(XmlNode &node, aiColor4D &pColor, Sampler &pSampler) {
if (node.empty()) {
return;
}
XmlNodeIterator xmlIt(node, XmlNodeIterator::PreOrderMode);
XmlNode currentNode;
while (xmlIt.getNext(currentNode)) {
const std::string ¤tName = currentNode.name();
if (currentName == "color") {
// text content contains 4 floats
std::string v;
XmlParser::getValueAsString(currentNode, v);
const char *content = v.c_str();
const char *end = v.c_str() + v.size() + 1;
content = fast_atoreal_move<ai_real>(content, (ai_real &)pColor.r);
SkipSpacesAndLineEnd(&content, end);
content = fast_atoreal_move<ai_real>(content, (ai_real &)pColor.g);
SkipSpacesAndLineEnd(&content, end);
content = fast_atoreal_move<ai_real>(content, (ai_real &)pColor.b);
SkipSpacesAndLineEnd(&content, end);
content = fast_atoreal_move<ai_real>(content, (ai_real &)pColor.a);
SkipSpacesAndLineEnd(&content, end);
} else if (currentName == "texture") {
// get name of source texture/sampler
XmlParser::getStdStrAttribute(currentNode, "texture", pSampler.mName);
// get name of UV source channel. Specification demands it to be there, but some exporters
// don't write it. It will be the default UV channel in case it's missing.
XmlParser::getStdStrAttribute(currentNode, "texcoord", pSampler.mUVChannel);
// as we've read texture, the color needs to be 1,1,1,1
pColor = aiColor4D(1.f, 1.f, 1.f, 1.f);
} else if (currentName == "technique") {
std::string profile;
XmlParser::getStdStrAttribute(currentNode, "profile", profile);
// Some extensions are quite useful ... ReadSamplerProperties processes
// several extensions in MAYA, OKINO and MAX3D profiles.
if (!::strcmp(profile.c_str(), "MAYA") || !::strcmp(profile.c_str(), "MAX3D") || !::strcmp(profile.c_str(), "OKINO")) {
// get more information on this sampler
ReadSamplerProperties(currentNode, pSampler);
}
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads an effect entry containing a float
void ColladaParser::ReadEffectFloat(XmlNode &node, ai_real &pReal) {
pReal = 0.f;
XmlNode floatNode = node.child("float");
if (floatNode.empty()) {
return;
}
XmlParser::getValueAsReal(floatNode, pReal);
}
// ------------------------------------------------------------------------------------------------
// Reads an effect parameter specification of any kind
void ColladaParser::ReadEffectParam(XmlNode &node, Collada::EffectParam &pParam) {
if (node.empty()) {
return;
}
for (XmlNode ¤tNode : node.children()) {
const std::string ¤tName = currentNode.name();
if (currentName == "surface") {
// image ID given inside <init_from> tags
XmlNode initNode = currentNode.child("init_from");
if (initNode) {
std::string v;
XmlParser::getValueAsString(initNode, v);
pParam.mType = Param_Surface;
pParam.mReference = v.c_str();
}
} else if (currentName == "sampler2D" && (FV_1_4_n == mFormat || FV_1_3_n == mFormat)) {
// surface ID is given inside <source> tags
XmlNode source = currentNode.child("source");
if (source) {
std::string v;
XmlParser::getValueAsString(source, v);
pParam.mType = Param_Sampler;
pParam.mReference = v.c_str();
}
} else if (currentName == "sampler2D") {
// surface ID is given inside <instance_image> tags
XmlNode instance_image = currentNode.child("instance_image");
if (instance_image) {
std::string url;
XmlParser::getStdStrAttribute(instance_image, "url", url);
if (url[0] != '#') {
throw DeadlyImportError("Unsupported URL format in instance_image");
}
pParam.mType = Param_Sampler;
pParam.mReference = url.c_str() + 1;
}
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads the geometry library contents
void ColladaParser::ReadGeometryLibrary(XmlNode &node) {
if (node.empty()) {
return;
}
for (XmlNode ¤tNode : node.children()) {
const std::string ¤tName = currentNode.name();
if (currentName == "geometry") {
// read ID. Another entry which is "optional" by design but obligatory in reality
std::string id;
XmlParser::getStdStrAttribute(currentNode, "id", id);
// create a mesh and store it in the library under its (resolved) ID
// Skip and warn if ID is not unique
if (mMeshLibrary.find(id) == mMeshLibrary.cend()) {
std::unique_ptr<Mesh> mesh(new Mesh(id));
XmlParser::getStdStrAttribute(currentNode, "name", mesh->mName);
// read on from there
ReadGeometry(currentNode, *mesh);
// Read successfully, add to library
mMeshLibrary.insert({ id, mesh.release() });
}
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads a geometry from the geometry library.
void ColladaParser::ReadGeometry(XmlNode &node, Collada::Mesh &pMesh) {
if (node.empty()) {
return;
}
for (XmlNode ¤tNode : node.children()) {
const std::string ¤tName = currentNode.name();
if (currentName == "mesh") {
ReadMesh(currentNode, pMesh);
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads a mesh from the geometry library
void ColladaParser::ReadMesh(XmlNode &node, Mesh &pMesh) {
if (node.empty()) {
return;
}
XmlNodeIterator xmlIt(node, XmlNodeIterator::PreOrderMode);
XmlNode currentNode;
while (xmlIt.getNext(currentNode)) {
const std::string ¤tName = currentNode.name();
if (currentName == "source") {
ReadSource(currentNode);
} else if (currentName == "vertices") {
ReadVertexData(currentNode, pMesh);
} else if (currentName == "triangles" || currentName == "lines" || currentName == "linestrips" ||
currentName == "polygons" || currentName == "polylist" || currentName == "trifans" ||
currentName == "tristrips") {
ReadIndexData(currentNode, pMesh);
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads a source element
void ColladaParser::ReadSource(XmlNode &node) {
if (node.empty()) {
return;
}
std::string sourceID;
XmlParser::getStdStrAttribute(node, "id", sourceID);
XmlNodeIterator xmlIt(node, XmlNodeIterator::PreOrderMode);
XmlNode currentNode;
while (xmlIt.getNext(currentNode)) {
const std::string ¤tName = currentNode.name();
if (currentName == "float_array" || currentName == "IDREF_array" || currentName == "Name_array") {
ReadDataArray(currentNode);
} else if (currentName == "technique_common") {
XmlNode technique = currentNode.child("accessor");
if (!technique.empty()) {
ReadAccessor(technique, sourceID);
}
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads a data array holding a number of floats, and stores it in the global library
void ColladaParser::ReadDataArray(XmlNode &node) {
std::string name = node.name();
bool isStringArray = (name == "IDREF_array" || name == "Name_array");
// read attributes
std::string id;
XmlParser::getStdStrAttribute(node, "id", id);
unsigned int count = 0;
XmlParser::getUIntAttribute(node, "count", count);
std::string v;
XmlParser::getValueAsString(node, v);
v = ai_trim(v);
const char *content = v.c_str();
const char *end = content + v.size();
// read values and store inside an array in the data library
mDataLibrary[id] = Data();
Data &data = mDataLibrary[id];
data.mIsStringArray = isStringArray;
// some exporters write empty data arrays, but we need to conserve them anyways because others might reference them
if (content) {
if (isStringArray) {
data.mStrings.reserve(count);
std::string s;
for (unsigned int a = 0; a < count; a++) {
if (*content == 0) {
throw DeadlyImportError("Expected more values while reading IDREF_array contents.");
}
s.clear();
while (!IsSpaceOrNewLine(*content)) {
s += *content;
content++;
}
data.mStrings.push_back(s);
SkipSpacesAndLineEnd(&content, end);
}
} else {
data.mValues.reserve(count);
for (unsigned int a = 0; a < count; a++) {
if (*content == 0) {
throw DeadlyImportError("Expected more values while reading float_array contents.");
}
// read a number
ai_real value;
content = fast_atoreal_move<ai_real>(content, value);
data.mValues.push_back(value);
// skip whitespace after it
SkipSpacesAndLineEnd(&content, end);
}
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads an accessor and stores it in the global library
void ColladaParser::ReadAccessor(XmlNode &node, const std::string &pID) {
// read accessor attributes
std::string source;
XmlParser::getStdStrAttribute(node, "source", source);
if (source[0] != '#') {
throw DeadlyImportError("Unknown reference format in url \"", source, "\" in source attribute of <accessor> element.");
}
int count = 0;
XmlParser::getIntAttribute(node, "count", count);
unsigned int offset = 0;
if (XmlParser::hasAttribute(node, "offset")) {
XmlParser::getUIntAttribute(node, "offset", offset);
}
unsigned int stride = 1;
if (XmlParser::hasAttribute(node, "stride")) {
XmlParser::getUIntAttribute(node, "stride", stride);
}
// store in the library under the given ID
mAccessorLibrary[pID] = Accessor();
Accessor &acc = mAccessorLibrary[pID];
acc.mCount = count;
acc.mOffset = offset;
acc.mStride = stride;
acc.mSource = source.c_str() + 1; // ignore the leading '#'
acc.mSize = 0; // gets incremented with every param
XmlNodeIterator xmlIt(node, XmlNodeIterator::PreOrderMode);
XmlNode currentNode;
while (xmlIt.getNext(currentNode)) {
const std::string ¤tName = currentNode.name();
if (currentName == "param") {
// read data param
std::string name;
if (XmlParser::hasAttribute(currentNode, "name")) {
XmlParser::getStdStrAttribute(currentNode, "name", name);
// analyse for common type components and store it's sub-offset in the corresponding field
// Cartesian coordinates
if (name == "X")
acc.mSubOffset[0] = acc.mParams.size();
else if (name == "Y")
acc.mSubOffset[1] = acc.mParams.size();
else if (name == "Z")
acc.mSubOffset[2] = acc.mParams.size();
/* RGBA colors */
else if (name == "R")
acc.mSubOffset[0] = acc.mParams.size();
else if (name == "G")
acc.mSubOffset[1] = acc.mParams.size();
else if (name == "B")
acc.mSubOffset[2] = acc.mParams.size();
else if (name == "A")
acc.mSubOffset[3] = acc.mParams.size();
/* UVWQ (STPQ) texture coordinates */
else if (name == "S")
acc.mSubOffset[0] = acc.mParams.size();
else if (name == "T")
acc.mSubOffset[1] = acc.mParams.size();
else if (name == "P")
acc.mSubOffset[2] = acc.mParams.size();
/* Generic extra data, interpreted as UV data, too*/
else if (name == "U")
acc.mSubOffset[0] = acc.mParams.size();
else if (name == "V")
acc.mSubOffset[1] = acc.mParams.size();
}
if (XmlParser::hasAttribute(currentNode, "type")) {
// read data type
// TODO: (thom) I don't have a spec here at work. Check if there are other multi-value types
// which should be tested for here.
std::string type;
XmlParser::getStdStrAttribute(currentNode, "type", type);
if (type == "float4x4")
acc.mSize += 16;
else
acc.mSize += 1;
}
acc.mParams.push_back(name);
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads input declarations of per-vertex mesh data into the given mesh
void ColladaParser::ReadVertexData(XmlNode &node, Mesh &pMesh) {
// extract the ID of the <vertices> element. Not that we care, but to catch strange referencing schemes we should warn about
XmlParser::getStdStrAttribute(node, "id", pMesh.mVertexID);
for (XmlNode ¤tNode : node.children()) {
const std::string ¤tName = currentNode.name();
if (currentName == "input") {
ReadInputChannel(currentNode, pMesh.mPerVertexData);
} else {
throw DeadlyImportError("Unexpected sub element <", currentName, "> in tag <vertices>");
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads input declarations of per-index mesh data into the given mesh
void ColladaParser::ReadIndexData(XmlNode &node, Mesh &pMesh) {
std::vector<size_t> vcount;
std::vector<InputChannel> perIndexData;
unsigned int numPrimitives = 0;
XmlParser::getUIntAttribute(node, "count", numPrimitives);
// read primitive count from the attribute
//int attrCount = GetAttribute("count");
//size_t numPrimitives = (size_t)mReader->getAttributeValueAsInt(attrCount);
// some mesh types (e.g. tristrips) don't specify primitive count upfront,
// so we need to sum up the actual number of primitives while we read the <p>-tags
size_t actualPrimitives = 0;
SubMesh subgroup;
if (XmlParser::hasAttribute(node, "material")) {
XmlParser::getStdStrAttribute(node, "material", subgroup.mMaterial);
}
// distinguish between polys and triangles
std::string elementName = node.name();
PrimitiveType primType = Prim_Invalid;
if (elementName == "lines")
primType = Prim_Lines;
else if (elementName == "linestrips")
primType = Prim_LineStrip;
else if (elementName == "polygons")
primType = Prim_Polygon;
else if (elementName == "polylist")
primType = Prim_Polylist;
else if (elementName == "triangles")
primType = Prim_Triangles;
else if (elementName == "trifans")
primType = Prim_TriFans;
else if (elementName == "tristrips")
primType = Prim_TriStrips;
ai_assert(primType != Prim_Invalid);
// also a number of <input> elements, but in addition a <p> primitive collection and probably index counts for all primitives
XmlNodeIterator xmlIt(node, XmlNodeIterator::PreOrderMode);
XmlNode currentNode;
while (xmlIt.getNext(currentNode)) {
const std::string ¤tName = currentNode.name();
if (currentName == "input") {
ReadInputChannel(currentNode, perIndexData);
} else if (currentName == "vcount") {
if (!currentNode.empty()) {
if (numPrimitives) // It is possible to define a mesh without any primitives
{
// case <polylist> - specifies the number of indices for each polygon
std::string v;
XmlParser::getValueAsString(currentNode, v);
const char *content = v.c_str();
const char *end = content + v.size();
vcount.reserve(numPrimitives);
SkipSpacesAndLineEnd(&content, end);
for (unsigned int a = 0; a < numPrimitives; a++) {
if (*content == 0) {
throw DeadlyImportError("Expected more values while reading <vcount> contents.");
}
// read a number
vcount.push_back((size_t)strtoul10(content, &content));
// skip whitespace after it
SkipSpacesAndLineEnd(&content, end);
}
}
}
} else if (currentName == "p") {
if (!currentNode.empty()) {
// now here the actual fun starts - these are the indices to construct the mesh data from
actualPrimitives += ReadPrimitives(currentNode, pMesh, perIndexData, numPrimitives, vcount, primType);
}
} else if (currentName == "extra") {
// skip
} else if (currentName == "ph") {
// skip
} else {
throw DeadlyImportError("Unexpected sub element <", currentName, "> in tag <", elementName, ">");
}
}
#ifdef ASSIMP_BUILD_DEBUG
if (primType != Prim_TriFans && primType != Prim_TriStrips && primType != Prim_LineStrip &&
primType != Prim_Lines) { // this is ONLY to workaround a bug in SketchUp 15.3.331 where it writes the wrong 'count' when it writes out the 'lines'.
ai_assert(actualPrimitives == numPrimitives);
}
#endif
// only when we're done reading all <p> tags (and thus know the final vertex count) can we commit the submesh
subgroup.mNumFaces = actualPrimitives;
pMesh.mSubMeshes.push_back(subgroup);
}
// ------------------------------------------------------------------------------------------------
// Reads a single input channel element and stores it in the given array, if valid
void ColladaParser::ReadInputChannel(XmlNode &node, std::vector<InputChannel> &poChannels) {
InputChannel channel;
// read semantic
std::string semantic;
XmlParser::getStdStrAttribute(node, "semantic", semantic);
channel.mType = GetTypeForSemantic(semantic);
// read source
std::string source;
XmlParser::getStdStrAttribute(node, "source", source);
if (source[0] != '#') {
throw DeadlyImportError("Unknown reference format in url \"", source, "\" in source attribute of <input> element.");
}
channel.mAccessor = source.c_str() + 1; // skipping the leading #, hopefully the remaining text is the accessor ID only
// read index offset, if per-index <input>
if (XmlParser::hasAttribute(node, "offset")) {
XmlParser::getUIntAttribute(node, "offset", (unsigned int &)channel.mOffset);
}
// read set if texture coordinates
if (channel.mType == IT_Texcoord || channel.mType == IT_Color) {
unsigned int attrSet = 0;
if (XmlParser::getUIntAttribute(node, "set", attrSet))
channel.mIndex = attrSet;
}
// store, if valid type
if (channel.mType != IT_Invalid)
poChannels.push_back(channel);
}
// ------------------------------------------------------------------------------------------------
// Reads a <p> primitive index list and assembles the mesh data into the given mesh
size_t ColladaParser::ReadPrimitives(XmlNode &node, Mesh &pMesh, std::vector<InputChannel> &pPerIndexChannels,
size_t pNumPrimitives, const std::vector<size_t> &pVCount, PrimitiveType pPrimType) {
// determine number of indices coming per vertex
// find the offset index for all per-vertex channels
size_t numOffsets = 1;
size_t perVertexOffset = SIZE_MAX; // invalid value
for (const InputChannel &channel : pPerIndexChannels) {
numOffsets = std::max(numOffsets, channel.mOffset + 1);
if (channel.mType == IT_Vertex)
perVertexOffset = channel.mOffset;
}
// determine the expected number of indices
size_t expectedPointCount = 0;
switch (pPrimType) {
case Prim_Polylist: {
for (size_t i : pVCount)
expectedPointCount += i;
break;
}
case Prim_Lines:
expectedPointCount = 2 * pNumPrimitives;
break;
case Prim_Triangles:
expectedPointCount = 3 * pNumPrimitives;
break;
default:
break;
}
// and read all indices into a temporary array
std::vector<size_t> indices;
if (expectedPointCount > 0) {
indices.reserve(expectedPointCount * numOffsets);
}
// It is possible to not contain any indices
if (pNumPrimitives > 0) {
std::string v;
XmlParser::getValueAsString(node, v);
const char *content = v.c_str();
const char *end = content + v.size();
SkipSpacesAndLineEnd(&content, end);
while (*content != 0) {
// read a value.
// Hack: (thom) Some exporters put negative indices sometimes. We just try to carry on anyways.
int value = std::max(0, strtol10(content, &content));
indices.push_back(size_t(value));
// skip whitespace after it
SkipSpacesAndLineEnd(&content, end);
}
}
// complain if the index count doesn't fit
if (expectedPointCount > 0 && indices.size() != expectedPointCount * numOffsets) {
if (pPrimType == Prim_Lines) {
// HACK: We just fix this number since SketchUp 15.3.331 writes the wrong 'count' for 'lines'
ReportWarning("Expected different index count in <p> element, %zu instead of %zu.", indices.size(), expectedPointCount * numOffsets);
pNumPrimitives = (indices.size() / numOffsets) / 2;
} else {
throw DeadlyImportError("Expected different index count in <p> element.");
}
} else if (expectedPointCount == 0 && (indices.size() % numOffsets) != 0) {
throw DeadlyImportError("Expected different index count in <p> element.");
}
// find the data for all sources
for (auto it = pMesh.mPerVertexData.begin(); it != pMesh.mPerVertexData.end(); ++it) {
InputChannel &input = *it;
if (input.mResolved) {
continue;
}
// find accessor
input.mResolved = &ResolveLibraryReference(mAccessorLibrary, input.mAccessor);
// resolve accessor's data pointer as well, if necessary
const Accessor *acc = input.mResolved;
if (!acc->mData) {
acc->mData = &ResolveLibraryReference(mDataLibrary, acc->mSource);
const size_t dataSize = acc->mOffset + acc->mCount * acc->mStride;
if (dataSize > acc->mData->mValues.size()) {
throw DeadlyImportError("Not enough data for accessor");
}
}
}
// and the same for the per-index channels
for (auto it = pPerIndexChannels.begin(); it != pPerIndexChannels.end(); ++it) {
InputChannel &input = *it;
if (input.mResolved) {
continue;
}
// ignore vertex pointer, it doesn't refer to an accessor
if (input.mType == IT_Vertex) {
// warn if the vertex channel does not refer to the <vertices> element in the same mesh
if (input.mAccessor != pMesh.mVertexID) {
throw DeadlyImportError("Unsupported vertex referencing scheme.");
}
continue;
}
// find accessor
input.mResolved = &ResolveLibraryReference(mAccessorLibrary, input.mAccessor);
// resolve accessor's data pointer as well, if necessary
const Accessor *acc = input.mResolved;
if (!acc->mData) {
acc->mData = &ResolveLibraryReference(mDataLibrary, acc->mSource);
const size_t dataSize = acc->mOffset + acc->mCount * acc->mStride;
if (dataSize > acc->mData->mValues.size()) {
throw DeadlyImportError("Not enough data for accessor");
}
}
}
// For continued primitives, the given count does not come all in one <p>, but only one primitive per <p>
size_t numPrimitives = pNumPrimitives;
if (pPrimType == Prim_TriFans || pPrimType == Prim_Polygon) {
numPrimitives = 1;
}
// For continued primitives, the given count is actually the number of <p>'s inside the parent tag
if (pPrimType == Prim_TriStrips) {
size_t numberOfVertices = indices.size() / numOffsets;
numPrimitives = numberOfVertices - 2;
}
if (pPrimType == Prim_LineStrip) {
size_t numberOfVertices = indices.size() / numOffsets;
numPrimitives = numberOfVertices - 1;
}
pMesh.mFaceSize.reserve(numPrimitives);
pMesh.mFacePosIndices.reserve(indices.size() / numOffsets);
size_t polylistStartVertex = 0;
for (size_t currentPrimitive = 0; currentPrimitive < numPrimitives; currentPrimitive++) {
// determine number of points for this primitive
size_t numPoints = 0;
switch (pPrimType) {
case Prim_Lines:
numPoints = 2;
for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++)
CopyVertex(currentVertex, numOffsets, numPoints, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices);
break;
case Prim_LineStrip:
numPoints = 2;
for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++)
CopyVertex(currentVertex, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices);
break;
case Prim_Triangles:
numPoints = 3;
for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++)
CopyVertex(currentVertex, numOffsets, numPoints, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices);
break;
case Prim_TriStrips:
numPoints = 3;
ReadPrimTriStrips(numOffsets, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices);
break;
case Prim_Polylist:
numPoints = pVCount[currentPrimitive];
for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++)
CopyVertex(polylistStartVertex + currentVertex, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, 0, indices);
polylistStartVertex += numPoints;
break;
case Prim_TriFans:
case Prim_Polygon:
numPoints = indices.size() / numOffsets;
for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++)
CopyVertex(currentVertex, numOffsets, numPoints, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices);
break;
default:
// LineStrip is not supported due to expected index unmangling
throw DeadlyImportError("Unsupported primitive type.");
}
// store the face size to later reconstruct the face from
pMesh.mFaceSize.push_back(numPoints);
}
// if I ever get my hands on that guy who invented this steaming pile of indirection...
return numPrimitives;
}
///@note This function won't work correctly if both PerIndex and PerVertex channels have same channels.
///For example if TEXCOORD present in both <vertices> and <polylist> tags this function will create wrong uv coordinates.
///It's not clear from COLLADA documentation whether this is allowed or not. For now only exporter fixed to avoid such behavior
void ColladaParser::CopyVertex(size_t currentVertex, size_t numOffsets, size_t numPoints, size_t perVertexOffset, Mesh &pMesh,
std::vector<InputChannel> &pPerIndexChannels, size_t currentPrimitive, const std::vector<size_t> &indices) {
// calculate the base offset of the vertex whose attributes we ant to copy
size_t baseOffset = currentPrimitive * numOffsets * numPoints + currentVertex * numOffsets;
// don't overrun the boundaries of the index list
ai_assert((baseOffset + numOffsets - 1) < indices.size());
// extract per-vertex channels using the global per-vertex offset
for (auto it = pMesh.mPerVertexData.begin(); it != pMesh.mPerVertexData.end(); ++it) {
ExtractDataObjectFromChannel(*it, indices[baseOffset + perVertexOffset], pMesh);
}
// and extract per-index channels using there specified offset
for (auto it = pPerIndexChannels.begin(); it != pPerIndexChannels.end(); ++it) {
ExtractDataObjectFromChannel(*it, indices[baseOffset + it->mOffset], pMesh);
}
// store the vertex-data index for later assignment of bone vertex weights
pMesh.mFacePosIndices.push_back(indices[baseOffset + perVertexOffset]);
}
void ColladaParser::ReadPrimTriStrips(size_t numOffsets, size_t perVertexOffset, Mesh &pMesh, std::vector<InputChannel> &pPerIndexChannels,
size_t currentPrimitive, const std::vector<size_t> &indices) {
if (currentPrimitive % 2 != 0) {
//odd tristrip triangles need their indices mangled, to preserve winding direction
CopyVertex(1, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices);
CopyVertex(0, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices);
CopyVertex(2, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices);
} else { //for non tristrips or even tristrip triangles
CopyVertex(0, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices);
CopyVertex(1, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices);
CopyVertex(2, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices);
}
}
// ------------------------------------------------------------------------------------------------
// Extracts a single object from an input channel and stores it in the appropriate mesh data array
void ColladaParser::ExtractDataObjectFromChannel(const InputChannel &pInput, size_t pLocalIndex, Mesh &pMesh) {
// ignore vertex referrer - we handle them that separate
if (pInput.mType == IT_Vertex) {
return;
}
const Accessor &acc = *pInput.mResolved;
if (pLocalIndex >= acc.mCount) {
throw DeadlyImportError("Invalid data index (", pLocalIndex, "/", acc.mCount, ") in primitive specification");
}
// get a pointer to the start of the data object referred to by the accessor and the local index
const ai_real *dataObject = &(acc.mData->mValues[0]) + acc.mOffset + pLocalIndex * acc.mStride;
// assemble according to the accessors component sub-offset list. We don't care, yet,
// what kind of object exactly we're extracting here
ai_real obj[4];
for (size_t c = 0; c < 4; ++c) {
obj[c] = dataObject[acc.mSubOffset[c]];
}
// now we reinterpret it according to the type we're reading here
switch (pInput.mType) {
case IT_Position: // ignore all position streams except 0 - there can be only one position
if (pInput.mIndex == 0) {
pMesh.mPositions.emplace_back(obj[0], obj[1], obj[2]);
} else {
ASSIMP_LOG_ERROR("Collada: just one vertex position stream supported");
}
break;
case IT_Normal:
// pad to current vertex count if necessary
if (pMesh.mNormals.size() < pMesh.mPositions.size() - 1)
pMesh.mNormals.insert(pMesh.mNormals.end(), pMesh.mPositions.size() - pMesh.mNormals.size() - 1, aiVector3D(0, 1, 0));
// ignore all normal streams except 0 - there can be only one normal
if (pInput.mIndex == 0) {
pMesh.mNormals.emplace_back(obj[0], obj[1], obj[2]);
} else {
ASSIMP_LOG_ERROR("Collada: just one vertex normal stream supported");
}
break;
case IT_Tangent:
// pad to current vertex count if necessary
if (pMesh.mTangents.size() < pMesh.mPositions.size() - 1)
pMesh.mTangents.insert(pMesh.mTangents.end(), pMesh.mPositions.size() - pMesh.mTangents.size() - 1, aiVector3D(1, 0, 0));
// ignore all tangent streams except 0 - there can be only one tangent
if (pInput.mIndex == 0) {
pMesh.mTangents.emplace_back(obj[0], obj[1], obj[2]);
} else {
ASSIMP_LOG_ERROR("Collada: just one vertex tangent stream supported");
}
break;
case IT_Bitangent:
// pad to current vertex count if necessary
if (pMesh.mBitangents.size() < pMesh.mPositions.size() - 1) {
pMesh.mBitangents.insert(pMesh.mBitangents.end(), pMesh.mPositions.size() - pMesh.mBitangents.size() - 1, aiVector3D(0, 0, 1));
}
// ignore all bitangent streams except 0 - there can be only one bitangent
if (pInput.mIndex == 0) {
pMesh.mBitangents.emplace_back(obj[0], obj[1], obj[2]);
} else {
ASSIMP_LOG_ERROR("Collada: just one vertex bitangent stream supported");
}
break;
case IT_Texcoord:
// up to 4 texture coord sets are fine, ignore the others
if (pInput.mIndex < AI_MAX_NUMBER_OF_TEXTURECOORDS) {
// pad to current vertex count if necessary
if (pMesh.mTexCoords[pInput.mIndex].size() < pMesh.mPositions.size() - 1)
pMesh.mTexCoords[pInput.mIndex].insert(pMesh.mTexCoords[pInput.mIndex].end(),
pMesh.mPositions.size() - pMesh.mTexCoords[pInput.mIndex].size() - 1, aiVector3D(0, 0, 0));
pMesh.mTexCoords[pInput.mIndex].emplace_back(obj[0], obj[1], obj[2]);
if (0 != acc.mSubOffset[2] || 0 != acc.mSubOffset[3]) {
pMesh.mNumUVComponents[pInput.mIndex] = 3;
}
} else {
ASSIMP_LOG_ERROR("Collada: too many texture coordinate sets. Skipping.");
}
break;
case IT_Color:
// up to 4 color sets are fine, ignore the others
if (pInput.mIndex < AI_MAX_NUMBER_OF_COLOR_SETS) {
// pad to current vertex count if necessary
if (pMesh.mColors[pInput.mIndex].size() < pMesh.mPositions.size() - 1)
pMesh.mColors[pInput.mIndex].insert(pMesh.mColors[pInput.mIndex].end(),
pMesh.mPositions.size() - pMesh.mColors[pInput.mIndex].size() - 1, aiColor4D(0, 0, 0, 1));
aiColor4D result(0, 0, 0, 1);
for (size_t i = 0; i < pInput.mResolved->mSize; ++i) {
result[static_cast<unsigned int>(i)] = obj[pInput.mResolved->mSubOffset[i]];
}
pMesh.mColors[pInput.mIndex].push_back(result);
} else {
ASSIMP_LOG_ERROR("Collada: too many vertex color sets. Skipping.");
}
break;
default:
// IT_Invalid and IT_Vertex
ai_assert(false && "shouldn't ever get here");
}
}
// ------------------------------------------------------------------------------------------------
// Reads the library of node hierarchies and scene parts
void ColladaParser::ReadSceneLibrary(XmlNode &node) {
if (node.empty()) {
return;
}
for (XmlNode ¤tNode : node.children()) {
const std::string ¤tName = currentNode.name();
if (currentName == "visual_scene") {
// read ID. Is optional according to the spec, but how on earth should a scene_instance refer to it then?
std::string id;
XmlParser::getStdStrAttribute(currentNode, "id", id);
// read name if given.
std::string attrName = "Scene";
if (XmlParser::hasAttribute(currentNode, "name")) {
XmlParser::getStdStrAttribute(currentNode, "name", attrName);
}
// create a node and store it in the library under its ID
Node *sceneNode = new Node;
sceneNode->mID = id;
sceneNode->mName = attrName;
mNodeLibrary[sceneNode->mID] = sceneNode;
ReadSceneNode(currentNode, sceneNode);
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads a scene node's contents including children and stores it in the given node
void ColladaParser::ReadSceneNode(XmlNode &node, Node *pNode) {
// quit immediately on <bla/> elements
if (node.empty()) {
return;
}
for (XmlNode ¤tNode : node.children()) {
const std::string ¤tName = currentNode.name();
if (currentName == "node") {
Node *child = new Node;
if (XmlParser::hasAttribute(currentNode, "id")) {
XmlParser::getStdStrAttribute(currentNode, "id", child->mID);
}
if (XmlParser::hasAttribute(currentNode, "sid")) {
XmlParser::getStdStrAttribute(currentNode, "sid", child->mSID);
}
if (XmlParser::hasAttribute(currentNode, "name")) {
XmlParser::getStdStrAttribute(currentNode, "name", child->mName);
}
if (pNode) {
pNode->mChildren.push_back(child);
child->mParent = pNode;
} else {
// no parent node given, probably called from <library_nodes> element.
// create new node in node library
mNodeLibrary[child->mID] = child;
}
// read on recursively from there
ReadSceneNode(currentNode, child);
continue;
} else if (!pNode) {
// For any further stuff we need a valid node to work on
continue;
}
if (currentName == "lookat") {
ReadNodeTransformation(currentNode, pNode, TF_LOOKAT);
} else if (currentName == "matrix") {
ReadNodeTransformation(currentNode, pNode, TF_MATRIX);
} else if (currentName == "rotate") {
ReadNodeTransformation(currentNode, pNode, TF_ROTATE);
} else if (currentName == "scale") {
ReadNodeTransformation(currentNode, pNode, TF_SCALE);
} else if (currentName == "skew") {
ReadNodeTransformation(currentNode, pNode, TF_SKEW);
} else if (currentName == "translate") {
ReadNodeTransformation(currentNode, pNode, TF_TRANSLATE);
} else if (currentName == "render" && pNode->mParent == nullptr && 0 == pNode->mPrimaryCamera.length()) {
// ... scene evaluation or, in other words, postprocessing pipeline,
// or, again in other words, a turing-complete description how to
// render a Collada scene. The only thing that is interesting for
// us is the primary camera.
if (XmlParser::hasAttribute(currentNode, "camera_node")) {
std::string s;
XmlParser::getStdStrAttribute(currentNode, "camera_node", s);
if (s[0] != '#') {
ASSIMP_LOG_ERROR("Collada: Unresolved reference format of camera");
} else {
pNode->mPrimaryCamera = s.c_str() + 1;
}
}
} else if (currentName == "instance_node") {
// find the node in the library
if (XmlParser::hasAttribute(currentNode, "url")) {
std::string s;
XmlParser::getStdStrAttribute(currentNode, "url", s);
if (s[0] != '#') {
ASSIMP_LOG_ERROR("Collada: Unresolved reference format of node");
} else {
pNode->mNodeInstances.emplace_back();
pNode->mNodeInstances.back().mNode = s.c_str() + 1;
}
}
} else if (currentName == "instance_geometry" || currentName == "instance_controller") {
// Reference to a mesh or controller, with possible material associations
ReadNodeGeometry(currentNode, pNode);
} else if (currentName == "instance_light") {
// Reference to a light, name given in 'url' attribute
if (XmlParser::hasAttribute(currentNode, "url")) {
std::string url;
XmlParser::getStdStrAttribute(currentNode, "url", url);
if (url[0] != '#') {
throw DeadlyImportError("Unknown reference format in <instance_light> element");
}
pNode->mLights.emplace_back();
pNode->mLights.back().mLight = url.c_str() + 1;
}
} else if (currentName == "instance_camera") {
// Reference to a camera, name given in 'url' attribute
if (XmlParser::hasAttribute(currentNode, "url")) {
std::string url;
XmlParser::getStdStrAttribute(currentNode, "url", url);
if (url[0] != '#') {
throw DeadlyImportError("Unknown reference format in <instance_camera> element");
}
pNode->mCameras.emplace_back();
pNode->mCameras.back().mCamera = url.c_str() + 1;
}
}
}
}
// ------------------------------------------------------------------------------------------------
// Processes bind_vertex_input and bind elements
void ColladaParser::ReadMaterialVertexInputBinding(XmlNode &node, Collada::SemanticMappingTable &tbl) {
std::string name = node.name();
for (XmlNode ¤tNode : node.children()) {
const std::string ¤tName = currentNode.name();
if (currentName == "bind_vertex_input") {
Collada::InputSemanticMapEntry vn;
// effect semantic
if (XmlParser::hasAttribute(currentNode, "semantic")) {
std::string s;
XmlParser::getStdStrAttribute(currentNode, "semantic", s);
XmlParser::getUIntAttribute(currentNode, "input_semantic", (unsigned int &)vn.mType);
}
std::string s;
XmlParser::getStdStrAttribute(currentNode, "semantic", s);
// input semantic
XmlParser::getUIntAttribute(currentNode, "input_semantic", (unsigned int &)vn.mType);
// index of input set
if (XmlParser::hasAttribute(currentNode, "input_set")) {
XmlParser::getUIntAttribute(currentNode, "input_set", vn.mSet);
}
tbl.mMap[s] = vn;
} else if (currentName == "bind") {
ASSIMP_LOG_WARN("Collada: Found unsupported <bind> element");
}
}
}
void ColladaParser::ReadEmbeddedTextures(ZipArchiveIOSystem &zip_archive) {
// Attempt to load any undefined Collada::Image in ImageLibrary
for (auto &it : mImageLibrary) {
if (Image &image = it.second; image.mImageData.empty()) {
std::unique_ptr<IOStream> image_file(zip_archive.Open(image.mFileName.c_str()));
if (image_file) {
image.mImageData.resize(image_file->FileSize());
image_file->Read(image.mImageData.data(), image_file->FileSize(), 1);
image.mEmbeddedFormat = BaseImporter::GetExtension(image.mFileName);
if (image.mEmbeddedFormat == "jpeg") {
image.mEmbeddedFormat = "jpg";
}
}
}
}
}
// ------------------------------------------------------------------------------------------------
// Reads a mesh reference in a node and adds it to the node's mesh list
void ColladaParser::ReadNodeGeometry(XmlNode &node, Node *pNode) {
// referred mesh is given as an attribute of the <instance_geometry> element
std::string url;
XmlParser::getStdStrAttribute(node, "url", url);
if (url[0] != '#') {
throw DeadlyImportError("Unknown reference format");
}
Collada::MeshInstance instance;
instance.mMeshOrController = url.c_str() + 1; // skipping the leading #
for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
const std::string ¤tName = currentNode.name();
if (currentName == "bind_material") {
XmlNode techNode = currentNode.child("technique_common");
if (techNode) {
for (XmlNode instanceMatNode = techNode.child("instance_material"); instanceMatNode; instanceMatNode = instanceMatNode.next_sibling())
{
const std::string &instance_name = instanceMatNode.name();
if (instance_name == "instance_material")
{
// read ID of the geometry subgroup and the target material
std::string group;
XmlParser::getStdStrAttribute(instanceMatNode, "symbol", group);
XmlParser::getStdStrAttribute(instanceMatNode, "target", url);
const char *urlMat = url.c_str();
Collada::SemanticMappingTable s;
if (urlMat[0] == '#')
urlMat++;
s.mMatName = urlMat;
ReadMaterialVertexInputBinding(instanceMatNode, s);
// store the association
instance.mMaterials[group] = s;
}
}
}
}
}
// store it
pNode->mMeshes.push_back(instance);
}
// ------------------------------------------------------------------------------------------------
// Reads the collada scene
void ColladaParser::ReadScene(XmlNode &node) {
if (node.empty()) {
return;
}
for (XmlNode ¤tNode : node.children()) {
const std::string ¤tName = currentNode.name();
if (currentName == "instance_visual_scene") {
// should be the first and only occurrence
if (mRootNode) {
throw DeadlyImportError("Invalid scene containing multiple root nodes in <instance_visual_scene> element");
}
// read the url of the scene to instance. Should be of format "#some_name"
std::string url;
XmlParser::getStdStrAttribute(currentNode, "url", url);
if (url[0] != '#') {
throw DeadlyImportError("Unknown reference format in <instance_visual_scene> element");
}
// find the referred scene, skip the leading #
auto sit = mNodeLibrary.find(url.c_str() + 1);
if (sit == mNodeLibrary.end()) {
throw DeadlyImportError("Unable to resolve visual_scene reference \"", std::string(std::move(url)), "\" in <instance_visual_scene> element.");
}
mRootNode = sit->second;
}
}
}
// ------------------------------------------------------------------------------------------------
// Calculates the resulting transformation from all the given transform steps
aiMatrix4x4 ColladaParser::CalculateResultTransform(const std::vector<Transform> &pTransforms) const {
aiMatrix4x4 res;
for (std::vector<Transform>::const_iterator it = pTransforms.begin(); it != pTransforms.end(); ++it) {
const Transform &tf = *it;
switch (tf.mType) {
case TF_LOOKAT: {
aiVector3D pos(tf.f[0], tf.f[1], tf.f[2]);
aiVector3D dstPos(tf.f[3], tf.f[4], tf.f[5]);
aiVector3D up = aiVector3D(tf.f[6], tf.f[7], tf.f[8]).Normalize();
aiVector3D dir = aiVector3D(dstPos - pos).Normalize();
aiVector3D right = (dir ^ up).Normalize();
res *= aiMatrix4x4(
right.x, up.x, -dir.x, pos.x,
right.y, up.y, -dir.y, pos.y,
right.z, up.z, -dir.z, pos.z,
0, 0, 0, 1);
break;
}
case TF_ROTATE: {
aiMatrix4x4 rot;
ai_real angle = tf.f[3] * ai_real(AI_MATH_PI) / ai_real(180.0);
aiVector3D axis(tf.f[0], tf.f[1], tf.f[2]);
aiMatrix4x4::Rotation(angle, axis, rot);
res *= rot;
break;
}
case TF_TRANSLATE: {
aiMatrix4x4 trans;
aiMatrix4x4::Translation(aiVector3D(tf.f[0], tf.f[1], tf.f[2]), trans);
res *= trans;
break;
}
case TF_SCALE: {
aiMatrix4x4 scale(tf.f[0], 0.0f, 0.0f, 0.0f, 0.0f, tf.f[1], 0.0f, 0.0f, 0.0f, 0.0f, tf.f[2], 0.0f,
0.0f, 0.0f, 0.0f, 1.0f);
res *= scale;
break;
}
case TF_SKEW:
// TODO: (thom)
ai_assert(false);
break;
case TF_MATRIX: {
aiMatrix4x4 mat(tf.f[0], tf.f[1], tf.f[2], tf.f[3], tf.f[4], tf.f[5], tf.f[6], tf.f[7],
tf.f[8], tf.f[9], tf.f[10], tf.f[11], tf.f[12], tf.f[13], tf.f[14], tf.f[15]);
res *= mat;
break;
}
default:
ai_assert(false);
break;
}
}
return res;
}
// ------------------------------------------------------------------------------------------------
// Determines the input data type for the given semantic string
InputType ColladaParser::GetTypeForSemantic(const std::string &semantic) {
if (semantic.empty()) {
ASSIMP_LOG_WARN("Vertex input type is empty.");
return IT_Invalid;
}
if (semantic == "POSITION")
return IT_Position;
else if (semantic == "TEXCOORD")
return IT_Texcoord;
else if (semantic == "NORMAL")
return IT_Normal;
else if (semantic == "COLOR")
return IT_Color;
else if (semantic == "VERTEX")
return IT_Vertex;
else if (semantic == "BINORMAL" || semantic == "TEXBINORMAL")
return IT_Bitangent;
else if (semantic == "TANGENT" || semantic == "TEXTANGENT")
return IT_Tangent;
ASSIMP_LOG_WARN("Unknown vertex input type \"", semantic, "\". Ignoring.");
return IT_Invalid;
}
#endif // !! ASSIMP_BUILD_NO_DAE_IMPORTER
|