ColladaParser.cpp 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2020, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file ColladaParser.cpp
  35. * @brief Implementation of the Collada parser helper
  36. */
  37. #ifndef ASSIMP_BUILD_NO_COLLADA_IMPORTER
  38. #include "ColladaParser.h"
  39. #include <assimp/ParsingUtils.h>
  40. #include <assimp/StringUtils.h>
  41. #include <assimp/TinyFormatter.h>
  42. #include <assimp/ZipArchiveIOSystem.h>
  43. #include <assimp/commonMetaData.h>
  44. #include <assimp/fast_atof.h>
  45. #include <assimp/light.h>
  46. #include <assimp/DefaultLogger.hpp>
  47. #include <assimp/IOSystem.hpp>
  48. #include <stdarg.h>
  49. #include <memory>
  50. #include <sstream>
  51. using namespace Assimp;
  52. using namespace Assimp::Collada;
  53. using namespace Assimp::Formatter;
  54. // ------------------------------------------------------------------------------------------------
  55. // Constructor to be privately used by Importer
  56. ColladaParser::ColladaParser(IOSystem *pIOHandler, const std::string &pFile) :
  57. mFileName(pFile),
  58. mXmlParser(),
  59. mDataLibrary(),
  60. mAccessorLibrary(),
  61. mMeshLibrary(),
  62. mNodeLibrary(),
  63. mImageLibrary(),
  64. mEffectLibrary(),
  65. mMaterialLibrary(),
  66. mLightLibrary(),
  67. mCameraLibrary(),
  68. mControllerLibrary(),
  69. mRootNode(nullptr),
  70. mAnims(),
  71. mUnitSize(1.0f),
  72. mUpDirection(UP_Y),
  73. mFormat(FV_1_5_n) {
  74. if (nullptr == pIOHandler) {
  75. throw DeadlyImportError("IOSystem is nullptr.");
  76. }
  77. std::unique_ptr<IOStream> daefile;
  78. std::unique_ptr<ZipArchiveIOSystem> zip_archive;
  79. // Determine type
  80. std::string extension = BaseImporter::GetExtension(pFile);
  81. if (extension != "dae") {
  82. zip_archive.reset(new ZipArchiveIOSystem(pIOHandler, pFile));
  83. }
  84. if (zip_archive && zip_archive->isOpen()) {
  85. std::string dae_filename = ReadZaeManifest(*zip_archive);
  86. if (dae_filename.empty()) {
  87. throw DeadlyImportError("Invalid ZAE");
  88. }
  89. daefile.reset(zip_archive->Open(dae_filename.c_str()));
  90. if (daefile == nullptr) {
  91. throw DeadlyImportError("Invalid ZAE manifest: '", dae_filename, "' is missing");
  92. }
  93. } else {
  94. // attempt to open the file directly
  95. daefile.reset(pIOHandler->Open(pFile));
  96. if (daefile.get() == nullptr) {
  97. throw DeadlyImportError("Failed to open file '", pFile, "'.");
  98. }
  99. }
  100. // generate a XML reader for it
  101. if (!mXmlParser.parse(daefile.get())) {
  102. throw DeadlyImportError("Unable to read file, malformed XML");
  103. }
  104. // start reading
  105. XmlNode node = mXmlParser.getRootNode();
  106. XmlNode colladaNode = node.child("COLLADA");
  107. if (colladaNode.empty()) {
  108. return;
  109. }
  110. ReadContents(colladaNode);
  111. // read embedded textures
  112. if (zip_archive && zip_archive->isOpen()) {
  113. ReadEmbeddedTextures(*zip_archive);
  114. }
  115. }
  116. // ------------------------------------------------------------------------------------------------
  117. // Destructor, private as well
  118. ColladaParser::~ColladaParser() {
  119. for (NodeLibrary::iterator it = mNodeLibrary.begin(); it != mNodeLibrary.end(); ++it)
  120. delete it->second;
  121. for (MeshLibrary::iterator it = mMeshLibrary.begin(); it != mMeshLibrary.end(); ++it)
  122. delete it->second;
  123. }
  124. // ------------------------------------------------------------------------------------------------
  125. // Read a ZAE manifest and return the filename to attempt to open
  126. std::string ColladaParser::ReadZaeManifest(ZipArchiveIOSystem &zip_archive) {
  127. // Open the manifest
  128. std::unique_ptr<IOStream> manifestfile(zip_archive.Open("manifest.xml"));
  129. if (manifestfile == nullptr) {
  130. // No manifest, hope there is only one .DAE inside
  131. std::vector<std::string> file_list;
  132. zip_archive.getFileListExtension(file_list, "dae");
  133. if (file_list.empty()) {
  134. return std::string();
  135. }
  136. return file_list.front();
  137. }
  138. XmlParser manifestParser;
  139. if (!manifestParser.parse(manifestfile.get())) {
  140. return std::string();
  141. }
  142. XmlNode root = manifestParser.getRootNode();
  143. const std::string &name = root.name();
  144. if (name != "dae_root") {
  145. root = *manifestParser.findNode("dae_root");
  146. if (nullptr == root) {
  147. return std::string();
  148. }
  149. std::string v;
  150. XmlParser::getValueAsString(root, v);
  151. aiString ai_str(v);
  152. UriDecodePath(ai_str);
  153. return std::string(ai_str.C_Str());
  154. }
  155. return std::string();
  156. }
  157. // ------------------------------------------------------------------------------------------------
  158. // Convert a path read from a collada file to the usual representation
  159. void ColladaParser::UriDecodePath(aiString &ss) {
  160. // TODO: collada spec, p 22. Handle URI correctly.
  161. // For the moment we're just stripping the file:// away to make it work.
  162. // Windows doesn't seem to be able to find stuff like
  163. // 'file://..\LWO\LWO2\MappingModes\earthSpherical.jpg'
  164. if (0 == strncmp(ss.data, "file://", 7)) {
  165. ss.length -= 7;
  166. memmove(ss.data, ss.data + 7, ss.length);
  167. ss.data[ss.length] = '\0';
  168. }
  169. // Maxon Cinema Collada Export writes "file:///C:\andsoon" with three slashes...
  170. // I need to filter it without destroying linux paths starting with "/somewhere"
  171. #if defined(_MSC_VER)
  172. if (ss.data[0] == '/' && isalpha((unsigned char)ss.data[1]) && ss.data[2] == ':') {
  173. #else
  174. if (ss.data[0] == '/' && isalpha(ss.data[1]) && ss.data[2] == ':') {
  175. #endif
  176. --ss.length;
  177. ::memmove(ss.data, ss.data + 1, ss.length);
  178. ss.data[ss.length] = 0;
  179. }
  180. // find and convert all %xy special chars
  181. char *out = ss.data;
  182. for (const char *it = ss.data; it != ss.data + ss.length; /**/) {
  183. if (*it == '%' && (it + 3) < ss.data + ss.length) {
  184. // separate the number to avoid dragging in chars from behind into the parsing
  185. char mychar[3] = { it[1], it[2], 0 };
  186. size_t nbr = strtoul16(mychar);
  187. it += 3;
  188. *out++ = (char)(nbr & 0xFF);
  189. } else {
  190. *out++ = *it++;
  191. }
  192. }
  193. // adjust length and terminator of the shortened string
  194. *out = 0;
  195. ai_assert(out > ss.data);
  196. ss.length = static_cast<ai_uint32>(out - ss.data);
  197. }
  198. // ------------------------------------------------------------------------------------------------
  199. // Reads the contents of the file
  200. void ColladaParser::ReadContents(XmlNode &node) {
  201. const std::string name = node.name();
  202. if (name == "COLLADA") {
  203. std::string version;
  204. if (XmlParser::getStdStrAttribute(node, "version", version)) {
  205. aiString v;
  206. v.Set(version.c_str());
  207. mAssetMetaData.emplace(AI_METADATA_SOURCE_FORMAT_VERSION, v);
  208. if (!::strncmp(version.c_str(), "1.5", 3)) {
  209. mFormat = FV_1_5_n;
  210. ASSIMP_LOG_DEBUG("Collada schema version is 1.5.n");
  211. } else if (!::strncmp(version.c_str(), "1.4", 3)) {
  212. mFormat = FV_1_4_n;
  213. ASSIMP_LOG_DEBUG("Collada schema version is 1.4.n");
  214. } else if (!::strncmp(version.c_str(), "1.3", 3)) {
  215. mFormat = FV_1_3_n;
  216. ASSIMP_LOG_DEBUG("Collada schema version is 1.3.n");
  217. }
  218. }
  219. ReadStructure(node);
  220. }
  221. }
  222. // ------------------------------------------------------------------------------------------------
  223. // Reads the structure of the file
  224. void ColladaParser::ReadStructure(XmlNode &node) {
  225. for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  226. const std::string name = std::string(currentNode.name());
  227. ASSIMP_LOG_DEBUG("last name" + name);
  228. if (name == "asset")
  229. ReadAssetInfo(currentNode);
  230. else if (name == "library_animations")
  231. ReadAnimationLibrary(currentNode);
  232. else if (name == "library_animation_clips")
  233. ReadAnimationClipLibrary(currentNode);
  234. else if (name == "library_controllers")
  235. ReadControllerLibrary(currentNode);
  236. else if (name == "library_images")
  237. ReadImageLibrary(currentNode);
  238. else if (name == "library_materials")
  239. ReadMaterialLibrary(currentNode);
  240. else if (name == "library_effects")
  241. ReadEffectLibrary(currentNode);
  242. else if (name == "library_geometries")
  243. ReadGeometryLibrary(currentNode);
  244. else if (name == "library_visual_scenes")
  245. ReadSceneLibrary(currentNode);
  246. else if (name == "library_lights")
  247. ReadLightLibrary(currentNode);
  248. else if (name == "library_cameras")
  249. ReadCameraLibrary(currentNode);
  250. else if (name == "library_nodes")
  251. ReadSceneNode(currentNode, nullptr); /* some hacking to reuse this piece of code */
  252. else if (name == "scene")
  253. ReadScene(currentNode);
  254. }
  255. PostProcessRootAnimations();
  256. PostProcessControllers();
  257. }
  258. // ------------------------------------------------------------------------------------------------
  259. // Reads asset information such as coordinate system information and legal blah
  260. void ColladaParser::ReadAssetInfo(XmlNode &node) {
  261. if (node.empty()) {
  262. return;
  263. }
  264. for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  265. const std::string name = currentNode.name();
  266. if (name == "unit") {
  267. pugi::xml_attribute attr = currentNode.attribute("meter");
  268. mUnitSize = 1.f;
  269. if (attr) {
  270. mUnitSize = static_cast<ai_real>(attr.as_double());
  271. }
  272. } else if (name == "up_axis") {
  273. std::string v;
  274. XmlParser::getValueAsString(currentNode, v);
  275. if (v == "X_UP") {
  276. mUpDirection = UP_X;
  277. } else if (v == "Z_UP") {
  278. mUpDirection = UP_Z;
  279. } else {
  280. mUpDirection = UP_Y;
  281. }
  282. } else if (name == "contributor") {
  283. for (XmlNode currentChldNode : currentNode.children()) {
  284. ReadMetaDataItem(currentChldNode, mAssetMetaData);
  285. }
  286. } else {
  287. ReadMetaDataItem(currentNode, mAssetMetaData);
  288. }
  289. }
  290. }
  291. static bool FindCommonKey(const std::string &collada_key, const MetaKeyPairVector &key_renaming, size_t &found_index) {
  292. for (size_t i = 0; i < key_renaming.size(); ++i) {
  293. if (key_renaming[i].first == collada_key) {
  294. found_index = i;
  295. return true;
  296. }
  297. }
  298. found_index = std::numeric_limits<size_t>::max();
  299. return false;
  300. }
  301. // ------------------------------------------------------------------------------------------------
  302. // Reads a single string metadata item
  303. void ColladaParser::ReadMetaDataItem(XmlNode &node, StringMetaData &metadata) {
  304. const Collada::MetaKeyPairVector &key_renaming = GetColladaAssimpMetaKeysCamelCase();
  305. const std::string name = node.name();
  306. if (name.empty()) {
  307. return;
  308. }
  309. std::string v;
  310. if (XmlParser::getValueAsString(node, v)) {
  311. trim(v);
  312. aiString aistr;
  313. aistr.Set(v);
  314. std::string camel_key_str(name);
  315. ToCamelCase(camel_key_str);
  316. size_t found_index;
  317. if (FindCommonKey(camel_key_str, key_renaming, found_index)) {
  318. metadata.emplace(key_renaming[found_index].second, aistr);
  319. } else {
  320. metadata.emplace(camel_key_str, aistr);
  321. }
  322. }
  323. }
  324. // ------------------------------------------------------------------------------------------------
  325. // Reads the animation clips
  326. void ColladaParser::ReadAnimationClipLibrary(XmlNode &node) {
  327. if (node.empty()) {
  328. return;
  329. }
  330. std::string animName;
  331. pugi::xml_attribute nameAttr = node.attribute("name");
  332. if (nameAttr) {
  333. animName = nameAttr.as_string();
  334. } else {
  335. pugi::xml_attribute idAttr = node.attribute("id");
  336. if (idAttr) {
  337. animName = idAttr.as_string();
  338. } else {
  339. animName = std::string("animation_") + to_string(mAnimationClipLibrary.size());
  340. }
  341. }
  342. std::pair<std::string, std::vector<std::string>> clip;
  343. clip.first = animName;
  344. for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  345. const std::string currentName = currentNode.name();
  346. if (currentName == "instance_animation") {
  347. pugi::xml_attribute url = currentNode.attribute("url");
  348. if (url) {
  349. const std::string urlName = url.as_string();
  350. if (urlName[0] != '#') {
  351. throw DeadlyImportError("Unknown reference format");
  352. }
  353. clip.second.push_back(url.as_string());
  354. }
  355. }
  356. if (clip.second.size() > 0) {
  357. mAnimationClipLibrary.push_back(clip);
  358. }
  359. }
  360. }
  361. void ColladaParser::PostProcessControllers() {
  362. std::string meshId;
  363. for (ControllerLibrary::iterator it = mControllerLibrary.begin(); it != mControllerLibrary.end(); ++it) {
  364. meshId = it->second.mMeshId;
  365. if (meshId.empty()) {
  366. continue;
  367. }
  368. ControllerLibrary::iterator findItr = mControllerLibrary.find(meshId);
  369. while (findItr != mControllerLibrary.end()) {
  370. meshId = findItr->second.mMeshId;
  371. findItr = mControllerLibrary.find(meshId);
  372. }
  373. it->second.mMeshId = meshId;
  374. }
  375. }
  376. // ------------------------------------------------------------------------------------------------
  377. // Re-build animations from animation clip library, if present, otherwise combine single-channel animations
  378. void ColladaParser::PostProcessRootAnimations() {
  379. if (mAnimationClipLibrary.empty()) {
  380. mAnims.CombineSingleChannelAnimations();
  381. return;
  382. }
  383. Animation temp;
  384. for (AnimationClipLibrary::iterator it = mAnimationClipLibrary.begin(); it != mAnimationClipLibrary.end(); ++it) {
  385. std::string clipName = it->first;
  386. Animation *clip = new Animation();
  387. clip->mName = clipName;
  388. temp.mSubAnims.push_back(clip);
  389. for (std::vector<std::string>::iterator a = it->second.begin(); a != it->second.end(); ++a) {
  390. std::string animationID = *a;
  391. AnimationLibrary::iterator animation = mAnimationLibrary.find(animationID);
  392. if (animation != mAnimationLibrary.end()) {
  393. Animation *pSourceAnimation = animation->second;
  394. pSourceAnimation->CollectChannelsRecursively(clip->mChannels);
  395. }
  396. }
  397. }
  398. mAnims = temp;
  399. // Ensure no double deletes.
  400. temp.mSubAnims.clear();
  401. }
  402. // ------------------------------------------------------------------------------------------------
  403. // Reads the animation library
  404. void ColladaParser::ReadAnimationLibrary(XmlNode &node) {
  405. if (node.empty()) {
  406. return;
  407. }
  408. for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  409. const std::string currentName = currentNode.name();
  410. if (currentName == "animation") {
  411. ReadAnimation(currentNode, &mAnims);
  412. }
  413. }
  414. }
  415. // ------------------------------------------------------------------------------------------------
  416. // Reads an animation into the given parent structure
  417. void ColladaParser::ReadAnimation(XmlNode &node, Collada::Animation *pParent) {
  418. if (node.empty()) {
  419. return;
  420. }
  421. // an <animation> element may be a container for grouping sub-elements or an animation channel
  422. // this is the channel collection by ID, in case it has channels
  423. typedef std::map<std::string, AnimationChannel> ChannelMap;
  424. ChannelMap channels;
  425. // this is the anim container in case we're a container
  426. Animation *anim = nullptr;
  427. // optional name given as an attribute
  428. std::string animName;
  429. pugi::xml_attribute nameAttr = node.attribute("name");
  430. if (nameAttr) {
  431. animName = nameAttr.as_string();
  432. } else {
  433. animName = "animation";
  434. }
  435. std::string animID;
  436. pugi::xml_attribute idAttr = node.attribute("id");
  437. if (idAttr) {
  438. animID = idAttr.as_string();
  439. }
  440. for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  441. const std::string currentName = currentNode.name();
  442. if (currentName == "animation") {
  443. if (!anim) {
  444. anim = new Animation;
  445. anim->mName = animName;
  446. pParent->mSubAnims.push_back(anim);
  447. }
  448. // recurse into the sub-element
  449. ReadAnimation(currentNode, anim);
  450. } else if (currentName == "source") {
  451. ReadSource(currentNode);
  452. } else if (currentName == "sampler") {
  453. pugi::xml_attribute sampler_id = currentNode.attribute("id");
  454. if (sampler_id) {
  455. std::string id = sampler_id.as_string();
  456. ChannelMap::iterator newChannel = channels.insert(std::make_pair(id, AnimationChannel())).first;
  457. // have it read into a channel
  458. ReadAnimationSampler(currentNode, newChannel->second);
  459. } else if (currentName == "channel") {
  460. pugi::xml_attribute target = currentNode.attribute("target");
  461. pugi::xml_attribute source = currentNode.attribute("source");
  462. std::string source_name = source.as_string();
  463. if (source_name[0] == '#') {
  464. source_name = source_name.substr(1, source_name.size() - 1);
  465. }
  466. ChannelMap::iterator cit = channels.find(source_name);
  467. if (cit != channels.end()) {
  468. cit->second.mTarget = target.as_string();
  469. }
  470. }
  471. }
  472. }
  473. // it turned out to have channels - add them
  474. if (!channels.empty()) {
  475. if (nullptr == anim) {
  476. anim = new Animation;
  477. anim->mName = animName;
  478. pParent->mSubAnims.push_back(anim);
  479. }
  480. for (ChannelMap::const_iterator it = channels.begin(); it != channels.end(); ++it) {
  481. anim->mChannels.push_back(it->second);
  482. }
  483. if (idAttr) {
  484. mAnimationLibrary[animID] = anim;
  485. }
  486. }
  487. }
  488. // ------------------------------------------------------------------------------------------------
  489. // Reads an animation sampler into the given anim channel
  490. void ColladaParser::ReadAnimationSampler(XmlNode &node, Collada::AnimationChannel &pChannel) {
  491. for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  492. const std::string currentName = currentNode.name();
  493. if (currentName == "input") {
  494. if (XmlParser::hasAttribute(currentNode, "semantic")) {
  495. std::string semantic, sourceAttr;
  496. XmlParser::getStdStrAttribute(currentNode, "semantic", semantic);
  497. if (XmlParser::hasAttribute(currentNode, "source")) {
  498. XmlParser::getStdStrAttribute(currentNode, "source", sourceAttr);
  499. const char *source = sourceAttr.c_str();
  500. if (source[0] != '#') {
  501. throw DeadlyImportError("Unsupported URL format");
  502. }
  503. source++;
  504. if (semantic == "INPUT")
  505. pChannel.mSourceTimes = source;
  506. else if (semantic == "OUTPUT")
  507. pChannel.mSourceValues = source;
  508. else if (semantic == "IN_TANGENT")
  509. pChannel.mInTanValues = source;
  510. else if (semantic == "OUT_TANGENT")
  511. pChannel.mOutTanValues = source;
  512. else if (semantic == "INTERPOLATION")
  513. pChannel.mInterpolationValues = source;
  514. }
  515. }
  516. }
  517. }
  518. }
  519. // ------------------------------------------------------------------------------------------------
  520. // Reads the skeleton controller library
  521. void ColladaParser::ReadControllerLibrary(XmlNode &node) {
  522. if (node.empty()) {
  523. return;
  524. }
  525. for (XmlNode &currentNode : node.children()) {
  526. const std::string &currentName = currentNode.name();
  527. if (currentName != "controller") {
  528. continue;
  529. ;
  530. }
  531. std::string id = node.attribute("id").as_string();
  532. mControllerLibrary[id] = Controller();
  533. ReadController(node, mControllerLibrary[id]);
  534. }
  535. }
  536. // ------------------------------------------------------------------------------------------------
  537. // Reads a controller into the given mesh structure
  538. void ColladaParser::ReadController(XmlNode &node, Collada::Controller &pController) {
  539. // initial values
  540. pController.mType = Skin;
  541. pController.mMethod = Normalized;
  542. for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  543. const std::string &currentName = currentNode.name();
  544. if (currentName == "morph") {
  545. pController.mType = Morph;
  546. pController.mMeshId = currentNode.attribute("source").as_string();
  547. int methodIndex = currentNode.attribute("method").as_int();
  548. if (methodIndex > 0) {
  549. std::string method;
  550. XmlParser::getValueAsString(currentNode, method);
  551. if (method == "RELATIVE") {
  552. pController.mMethod = Relative;
  553. }
  554. }
  555. } else if (currentName == "skin") {
  556. pController.mMeshId = currentNode.attribute("source").as_string();
  557. } else if (currentName == "bind_shape_matrix") {
  558. std::string v;
  559. XmlParser::getValueAsString(currentNode, v);
  560. const char *content = v.c_str();
  561. for (unsigned int a = 0; a < 16; a++) {
  562. // read a number
  563. content = fast_atoreal_move<ai_real>(content, pController.mBindShapeMatrix[a]);
  564. // skip whitespace after it
  565. SkipSpacesAndLineEnd(&content);
  566. }
  567. } else if (currentName == "source") {
  568. ReadSource(currentNode);
  569. } else if (currentName == "joints") {
  570. ReadControllerJoints(currentNode, pController);
  571. } else if (currentName == "vertex_weights") {
  572. ReadControllerWeights(currentNode, pController);
  573. } else if (currentName == "targets") {
  574. for (XmlNode currentChildNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  575. const std::string &currentChildName = currentChildNode.name();
  576. if (currentChildName == "input") {
  577. const char *semantics = currentChildNode.attribute("semantic").as_string();
  578. const char *source = currentChildNode.attribute("source").as_string();
  579. if (strcmp(semantics, "MORPH_TARGET") == 0) {
  580. pController.mMorphTarget = source + 1;
  581. } else if (strcmp(semantics, "MORPH_WEIGHT") == 0) {
  582. pController.mMorphWeight = source + 1;
  583. }
  584. }
  585. }
  586. }
  587. }
  588. }
  589. // ------------------------------------------------------------------------------------------------
  590. // Reads the joint definitions for the given controller
  591. void ColladaParser::ReadControllerJoints(XmlNode &node, Collada::Controller &pController) {
  592. for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  593. const std::string currentName = currentNode.name();
  594. if (currentName == "input") {
  595. const char *attrSemantic = currentNode.attribute("semantic").as_string();
  596. const char *attrSource = currentNode.attribute("source").as_string();
  597. if (attrSource[0] != '#') {
  598. throw DeadlyImportError("Unsupported URL format in \"", attrSource, "\" in source attribute of <joints> data <input> element");
  599. }
  600. ++attrSource;
  601. // parse source URL to corresponding source
  602. if (strcmp(attrSemantic, "JOINT") == 0) {
  603. pController.mJointNameSource = attrSource;
  604. } else if (strcmp(attrSemantic, "INV_BIND_MATRIX") == 0) {
  605. pController.mJointOffsetMatrixSource = attrSource;
  606. } else {
  607. throw DeadlyImportError("Unknown semantic \"" , attrSemantic , "\" in <joints> data <input> element");
  608. }
  609. }
  610. }
  611. }
  612. // ------------------------------------------------------------------------------------------------
  613. // Reads the joint weights for the given controller
  614. void ColladaParser::ReadControllerWeights(XmlNode &node, Collada::Controller &pController) {
  615. // Read vertex count from attributes and resize the array accordingly
  616. int vertexCount=0;
  617. XmlParser::getIntAttribute(node, "count", vertexCount);
  618. for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  619. std::string currentName = currentNode.name();
  620. if (currentName == "input") {
  621. InputChannel channel;
  622. const char *attrSemantic = currentNode.attribute("semantic").as_string();
  623. const char *attrSource = currentNode.attribute("source").as_string();
  624. channel.mOffset = currentNode.attribute("offset").as_int();
  625. // local URLS always start with a '#'. We don't support global URLs
  626. if (attrSource[0] != '#') {
  627. throw DeadlyImportError( "Unsupported URL format in \"", attrSource, "\" in source attribute of <vertex_weights> data <input> element");
  628. }
  629. channel.mAccessor = attrSource + 1;
  630. // parse source URL to corresponding source
  631. if (strcmp(attrSemantic, "JOINT") == 0) {
  632. pController.mWeightInputJoints = channel;
  633. } else if (strcmp(attrSemantic, "WEIGHT") == 0) {
  634. pController.mWeightInputWeights = channel;
  635. } else {
  636. throw DeadlyImportError("Unknown semantic \"", attrSemantic, "\" in <vertex_weights> data <input> element");
  637. }
  638. } else if (currentName == "vcount" && vertexCount > 0) {
  639. const char *text = currentNode.value();
  640. size_t numWeights = 0;
  641. for (std::vector<size_t>::iterator it = pController.mWeightCounts.begin(); it != pController.mWeightCounts.end(); ++it) {
  642. if (*text == 0) {
  643. throw DeadlyImportError("Out of data while reading <vcount>");
  644. }
  645. *it = strtoul10(text, &text);
  646. numWeights += *it;
  647. SkipSpacesAndLineEnd(&text);
  648. }
  649. // reserve weight count
  650. pController.mWeights.resize(numWeights);
  651. } else if (currentName == "v" && vertexCount > 0) {
  652. // read JointIndex - WeightIndex pairs
  653. std::string stdText;
  654. XmlParser::getValueAsString(currentNode, stdText);
  655. const char *text = stdText.c_str();
  656. for (std::vector<std::pair<size_t, size_t>>::iterator it = pController.mWeights.begin(); it != pController.mWeights.end(); ++it) {
  657. if (text == 0) {
  658. throw DeadlyImportError("Out of data while reading <vertex_weights>");
  659. }
  660. it->first = strtoul10(text, &text);
  661. SkipSpacesAndLineEnd(&text);
  662. if (*text == 0) {
  663. throw DeadlyImportError("Out of data while reading <vertex_weights>");
  664. }
  665. it->second = strtoul10(text, &text);
  666. SkipSpacesAndLineEnd(&text);
  667. }
  668. }
  669. }
  670. }
  671. // ------------------------------------------------------------------------------------------------
  672. // Reads the image library contents
  673. void ColladaParser::ReadImageLibrary(XmlNode &node) {
  674. if (node.empty()) {
  675. return;
  676. }
  677. for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  678. const std::string name = currentNode.name();
  679. if (name == "image") {
  680. std::string id = currentNode.attribute("id").as_string();
  681. mImageLibrary[id] = Image();
  682. // read on from there
  683. ReadImage(currentNode, mImageLibrary[id]);
  684. }
  685. }
  686. }
  687. // ------------------------------------------------------------------------------------------------
  688. // Reads an image entry into the given image
  689. void ColladaParser::ReadImage(XmlNode &node, Collada::Image &pImage) {
  690. for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  691. const std::string currentName = currentNode.name();
  692. if (currentName == "image") {
  693. // Ignore
  694. continue;
  695. } else if (currentName == "init_from") {
  696. if (mFormat == FV_1_4_n) {
  697. // FIX: C4D exporter writes empty <init_from/> tags
  698. if (!currentNode.empty()) {
  699. // element content is filename - hopefully
  700. const char *sz = currentNode.text().as_string();
  701. if (sz) {
  702. aiString filepath(sz);
  703. UriDecodePath(filepath);
  704. pImage.mFileName = filepath.C_Str();
  705. }
  706. }
  707. if (!pImage.mFileName.length()) {
  708. pImage.mFileName = "unknown_texture";
  709. }
  710. } else if (mFormat == FV_1_5_n) {
  711. // make sure we skip over mip and array initializations, which
  712. // we don't support, but which could confuse the loader if
  713. // they're not skipped.
  714. //int v = currentNode.attribute("ref").as_int();
  715. /* if (v y) {
  716. ASSIMP_LOG_WARN("Collada: Ignoring texture array index");
  717. continue;
  718. }*/
  719. //v = currentNode.attribute("mip_index").as_int();
  720. /*if (attrib != -1 && v > 0) {
  721. ASSIMP_LOG_WARN("Collada: Ignoring MIP map layer");
  722. continue;
  723. }*/
  724. // TODO: correctly jump over cube and volume maps?
  725. }
  726. } else if (mFormat == FV_1_5_n) {
  727. std::string value;
  728. XmlNode refChild = currentNode.child("ref");
  729. XmlNode hexChild = currentNode.child("hex");
  730. if (refChild) {
  731. // element content is filename - hopefully
  732. if (XmlParser::getValueAsString(refChild, value)) {
  733. aiString filepath(value);
  734. UriDecodePath(filepath);
  735. pImage.mFileName = filepath.C_Str();
  736. }
  737. } else if (hexChild && !pImage.mFileName.length()) {
  738. // embedded image. get format
  739. pImage.mEmbeddedFormat = hexChild.attribute("format").as_string();
  740. if (pImage.mEmbeddedFormat.empty()) {
  741. ASSIMP_LOG_WARN("Collada: Unknown image file format");
  742. }
  743. XmlParser::getValueAsString(hexChild, value);
  744. const char *data = value.c_str();
  745. // hexadecimal-encoded binary octets. First of all, find the
  746. // required buffer size to reserve enough storage.
  747. const char *cur = data;
  748. while (!IsSpaceOrNewLine(*cur)) {
  749. ++cur;
  750. }
  751. const unsigned int size = (unsigned int)(cur - data) * 2;
  752. pImage.mImageData.resize(size);
  753. for (unsigned int i = 0; i < size; ++i) {
  754. pImage.mImageData[i] = HexOctetToDecimal(data + (i << 1));
  755. }
  756. }
  757. }
  758. }
  759. }
  760. // ------------------------------------------------------------------------------------------------
  761. // Reads the material library
  762. void ColladaParser::ReadMaterialLibrary(XmlNode &node) {
  763. if (node.empty()) {
  764. return;
  765. }
  766. std::map<std::string, int> names;
  767. for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  768. const std::string currentName = currentNode.name();
  769. std::string id = currentNode.attribute("id").as_string();
  770. std::string name = currentNode.attribute("name").as_string();
  771. mMaterialLibrary[id] = Material();
  772. if (!name.empty()) {
  773. std::map<std::string, int>::iterator it = names.find(name);
  774. if (it != names.end()) {
  775. std::ostringstream strStream;
  776. strStream << ++it->second;
  777. name.append(" " + strStream.str());
  778. } else {
  779. names[name] = 0;
  780. }
  781. mMaterialLibrary[id].mName = name;
  782. }
  783. ReadMaterial(currentNode, mMaterialLibrary[id]);
  784. }
  785. }
  786. // ------------------------------------------------------------------------------------------------
  787. // Reads the light library
  788. void ColladaParser::ReadLightLibrary(XmlNode &node) {
  789. if (node.empty()) {
  790. return;
  791. }
  792. for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  793. const std::string &currentName = currentNode.name();
  794. if (currentName == "light") {
  795. std::string id = currentNode.attribute("id").as_string();
  796. ReadLight(currentNode, mLightLibrary[id] = Light());
  797. }
  798. }
  799. }
  800. // ------------------------------------------------------------------------------------------------
  801. // Reads the camera library
  802. void ColladaParser::ReadCameraLibrary(XmlNode &node) {
  803. if (node.empty()) {
  804. return;
  805. }
  806. for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  807. const std::string &currentName = currentNode.name();
  808. if (currentName == "camera") {
  809. std::string id = currentNode.attribute("id").as_string();
  810. // create an entry and store it in the library under its ID
  811. Camera &cam = mCameraLibrary[id];
  812. std::string name = currentNode.attribute("name").as_string();
  813. if (!name.empty()) {
  814. cam.mName = name;
  815. }
  816. ReadCamera(currentNode, cam);
  817. }
  818. }
  819. }
  820. // ------------------------------------------------------------------------------------------------
  821. // Reads a material entry into the given material
  822. void ColladaParser::ReadMaterial(XmlNode &node, Collada::Material &pMaterial) {
  823. for (XmlNode currentNode : node.children()) {
  824. const std::string &currentName = currentNode.name();
  825. if (currentName == "instance_effect") {
  826. const char *url = currentNode.attribute("url").as_string();
  827. if (url[0] != '#') {
  828. throw DeadlyImportError("Unknown reference format");
  829. }
  830. pMaterial.mEffect = url + 1;
  831. }
  832. }
  833. }
  834. // ------------------------------------------------------------------------------------------------
  835. // Reads a light entry into the given light
  836. void ColladaParser::ReadLight(XmlNode &node, Collada::Light &pLight) {
  837. XmlNodeIterator xmlIt(node);
  838. xmlIt.collectChildrenPreOrder(node);
  839. XmlNode currentNode;
  840. while (xmlIt.getNext(currentNode)) {
  841. const std::string &currentName = currentNode.name();
  842. if (currentName == "spot") {
  843. pLight.mType = aiLightSource_SPOT;
  844. } else if (currentName == "ambient") {
  845. pLight.mType = aiLightSource_AMBIENT;
  846. } else if (currentName == "directional") {
  847. pLight.mType = aiLightSource_DIRECTIONAL;
  848. } else if (currentName == "point") {
  849. pLight.mType = aiLightSource_POINT;
  850. } else if (currentName == "color") {
  851. // text content contains 3 floats
  852. std::string v;
  853. XmlParser::getValueAsString(currentNode, v);
  854. const char *content = v.c_str();
  855. content = fast_atoreal_move<ai_real>(content, (ai_real &)pLight.mColor.r);
  856. SkipSpacesAndLineEnd(&content);
  857. content = fast_atoreal_move<ai_real>(content, (ai_real &)pLight.mColor.g);
  858. SkipSpacesAndLineEnd(&content);
  859. content = fast_atoreal_move<ai_real>(content, (ai_real &)pLight.mColor.b);
  860. SkipSpacesAndLineEnd(&content);
  861. } else if (currentName == "constant_attenuation") {
  862. XmlParser::getFloatAttribute(currentNode, "constant_attenuation", pLight.mAttConstant);
  863. } else if (currentName == "linear_attenuation") {
  864. XmlParser::getFloatAttribute(currentNode, "linear_attenuation", pLight.mAttLinear);
  865. } else if (currentName == "quadratic_attenuation") {
  866. XmlParser::getFloatAttribute(currentNode, "quadratic_attenuation", pLight.mAttQuadratic);
  867. } else if (currentName == "falloff_angle") {
  868. XmlParser::getFloatAttribute(currentNode, "falloff_angle", pLight.mFalloffAngle);
  869. } else if (currentName == "falloff_exponent") {
  870. XmlParser::getFloatAttribute(currentNode, "falloff_exponent", pLight.mFalloffExponent);
  871. }
  872. // FCOLLADA extensions
  873. // -------------------------------------------------------
  874. else if (currentName == "outer_cone") {
  875. XmlParser::getFloatAttribute(currentNode, "outer_cone", pLight.mOuterAngle);
  876. } else if (currentName == "penumbra_angle") { // ... and this one is even deprecated
  877. XmlParser::getFloatAttribute(currentNode, "penumbra_angle", pLight.mPenumbraAngle);
  878. } else if (currentName == "intensity") {
  879. XmlParser::getFloatAttribute(currentNode, "intensity", pLight.mIntensity);
  880. } else if (currentName == "falloff") {
  881. XmlParser::getFloatAttribute(currentNode, "falloff", pLight.mOuterAngle);
  882. } else if (currentName == "hotspot_beam") {
  883. XmlParser::getFloatAttribute(currentNode, "hotspot_beam", pLight.mFalloffAngle);
  884. }
  885. // OpenCOLLADA extensions
  886. // -------------------------------------------------------
  887. else if (currentName == "decay_falloff") {
  888. XmlParser::getFloatAttribute(currentNode, "decay_falloff", pLight.mOuterAngle);
  889. }
  890. }
  891. }
  892. // ------------------------------------------------------------------------------------------------
  893. // Reads a camera entry into the given light
  894. void ColladaParser::ReadCamera(XmlNode &node, Collada::Camera &camera) {
  895. XmlNodeIterator xmlIt(node);
  896. xmlIt.collectChildrenPreOrder(node);
  897. XmlNode currentNode;
  898. while (xmlIt.getNext(currentNode)) {
  899. const std::string &currentName = currentNode.name();
  900. if (currentName == "orthographic") {
  901. camera.mOrtho = true;
  902. } else if (currentName == "xfov" || currentName == "xmag") {
  903. XmlParser::getValueAsFloat(currentNode, camera.mHorFov);
  904. } else if (currentName == "yfov" || currentName == "ymag") {
  905. XmlParser::getValueAsFloat(currentNode, camera.mVerFov);
  906. } else if (currentName == "aspect_ratio") {
  907. XmlParser::getValueAsFloat(currentNode, camera.mAspect);
  908. } else if (currentName == "znear") {
  909. XmlParser::getValueAsFloat(currentNode, camera.mZNear);
  910. } else if (currentName == "zfar") {
  911. XmlParser::getValueAsFloat(currentNode, camera.mZFar);
  912. }
  913. }
  914. }
  915. // ------------------------------------------------------------------------------------------------
  916. // Reads the effect library
  917. void ColladaParser::ReadEffectLibrary(XmlNode &node) {
  918. if (node.empty()) {
  919. return;
  920. }
  921. for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  922. const std::string &currentName = currentNode.name();
  923. if (currentName == "effect") {
  924. // read ID. Do I have to repeat my ranting about "optional" attributes?
  925. std::string id;
  926. XmlParser::getStdStrAttribute(currentNode, "id", id);
  927. // create an entry and store it in the library under its ID
  928. mEffectLibrary[id] = Effect();
  929. // read on from there
  930. ReadEffect(currentNode, mEffectLibrary[id]);
  931. }
  932. }
  933. }
  934. // ------------------------------------------------------------------------------------------------
  935. // Reads an effect entry into the given effect
  936. void ColladaParser::ReadEffect(XmlNode &node, Collada::Effect &pEffect) {
  937. for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  938. const std::string &currentName = currentNode.name();
  939. if (currentName == "profile_COMMON") {
  940. ReadEffectProfileCommon(currentNode, pEffect);
  941. }
  942. }
  943. }
  944. // ------------------------------------------------------------------------------------------------
  945. // Reads an COMMON effect profile
  946. void ColladaParser::ReadEffectProfileCommon(XmlNode &node, Collada::Effect &pEffect) {
  947. XmlNodeIterator xmlIt(node);
  948. xmlIt.collectChildrenPreOrder(node);
  949. XmlNode currentNode;
  950. while (xmlIt.getNext(currentNode)) {
  951. const std::string &currentName = currentNode.name();
  952. if (currentName == "newparam") {
  953. // save ID
  954. std::string sid = currentNode.attribute("sid").as_string();
  955. pEffect.mParams[sid] = EffectParam();
  956. ReadEffectParam(currentNode, pEffect.mParams[sid]);
  957. } else if (currentName == "technique" || currentName == "extra") {
  958. // just syntactic sugar
  959. } else if (mFormat == FV_1_4_n && currentName == "image") {
  960. // read ID. Another entry which is "optional" by design but obligatory in reality
  961. std::string id = currentNode.attribute("id").as_string();
  962. // create an entry and store it in the library under its ID
  963. mImageLibrary[id] = Image();
  964. // read on from there
  965. ReadImage(currentNode, mImageLibrary[id]);
  966. } else if (currentName == "phong")
  967. pEffect.mShadeType = Shade_Phong;
  968. else if (currentName == "constant")
  969. pEffect.mShadeType = Shade_Constant;
  970. else if (currentName == "lambert")
  971. pEffect.mShadeType = Shade_Lambert;
  972. else if (currentName == "blinn")
  973. pEffect.mShadeType = Shade_Blinn;
  974. /* Color + texture properties */
  975. else if (currentName == "emission")
  976. ReadEffectColor(currentNode, pEffect.mEmissive, pEffect.mTexEmissive);
  977. else if (currentName == "ambient")
  978. ReadEffectColor(currentNode, pEffect.mAmbient, pEffect.mTexAmbient);
  979. else if (currentName == "diffuse")
  980. ReadEffectColor(currentNode, pEffect.mDiffuse, pEffect.mTexDiffuse);
  981. else if (currentName == "specular")
  982. ReadEffectColor(currentNode, pEffect.mSpecular, pEffect.mTexSpecular);
  983. else if (currentName == "reflective") {
  984. ReadEffectColor(currentNode, pEffect.mReflective, pEffect.mTexReflective);
  985. } else if (currentName == "transparent") {
  986. pEffect.mHasTransparency = true;
  987. const char *opaque = currentNode.attribute("opaque").as_string();
  988. //const char *opaque = mReader->getAttributeValueSafe("opaque");
  989. if (::strcmp(opaque, "RGB_ZERO") == 0 || ::strcmp(opaque, "RGB_ONE") == 0) {
  990. pEffect.mRGBTransparency = true;
  991. }
  992. // In RGB_ZERO mode, the transparency is interpreted in reverse, go figure...
  993. if (::strcmp(opaque, "RGB_ZERO") == 0 || ::strcmp(opaque, "A_ZERO") == 0) {
  994. pEffect.mInvertTransparency = true;
  995. }
  996. ReadEffectColor(currentNode, pEffect.mTransparent, pEffect.mTexTransparent);
  997. } else if (currentName == "shininess")
  998. ReadEffectFloat(currentNode, pEffect.mShininess);
  999. else if (currentName == "reflectivity")
  1000. ReadEffectFloat(currentNode, pEffect.mReflectivity);
  1001. /* Single scalar properties */
  1002. else if (currentName == "transparency")
  1003. ReadEffectFloat(currentNode, pEffect.mTransparency);
  1004. else if (currentName == "index_of_refraction")
  1005. ReadEffectFloat(currentNode, pEffect.mRefractIndex);
  1006. // GOOGLEEARTH/OKINO extensions
  1007. // -------------------------------------------------------
  1008. else if (currentName == "double_sided")
  1009. XmlParser::getBoolAttribute(currentNode, currentName.c_str(), pEffect.mDoubleSided);
  1010. // FCOLLADA extensions
  1011. // -------------------------------------------------------
  1012. else if (currentName == "bump") {
  1013. aiColor4D dummy;
  1014. ReadEffectColor(currentNode, dummy, pEffect.mTexBump);
  1015. }
  1016. // MAX3D extensions
  1017. // -------------------------------------------------------
  1018. else if (currentName == "wireframe") {
  1019. XmlParser::getBoolAttribute(currentNode, currentName.c_str(), pEffect.mWireframe);
  1020. } else if (currentName == "faceted") {
  1021. XmlParser::getBoolAttribute(currentNode, currentName.c_str(), pEffect.mFaceted);
  1022. }
  1023. }
  1024. }
  1025. // ------------------------------------------------------------------------------------------------
  1026. // Read texture wrapping + UV transform settings from a profile==Maya chunk
  1027. void ColladaParser::ReadSamplerProperties(XmlNode &node, Sampler &out) {
  1028. if (node.empty()) {
  1029. return;
  1030. }
  1031. XmlNodeIterator xmlIt(node);
  1032. xmlIt.collectChildrenPreOrder(node);
  1033. XmlNode currentNode;
  1034. while (xmlIt.getNext(currentNode)) {
  1035. const std::string &currentName = currentNode.name();
  1036. // MAYA extensions
  1037. // -------------------------------------------------------
  1038. if (currentName == "wrapU") {
  1039. XmlParser::getBoolAttribute(currentNode, currentName.c_str(), out.mWrapU);
  1040. } else if (currentName == "wrapV") {
  1041. XmlParser::getBoolAttribute(currentNode, currentName.c_str(), out.mWrapV);
  1042. } else if (currentName == "mirrorU") {
  1043. XmlParser::getBoolAttribute(currentNode, currentName.c_str(), out.mMirrorU);
  1044. } else if (currentName == "mirrorV") {
  1045. XmlParser::getBoolAttribute(currentNode, currentName.c_str(), out.mMirrorV);
  1046. } else if (currentName == "repeatU") {
  1047. XmlParser::getFloatAttribute(currentNode, currentName.c_str(), out.mTransform.mScaling.x);
  1048. } else if (currentName == "repeatV") {
  1049. XmlParser::getFloatAttribute(currentNode, currentName.c_str(), out.mTransform.mScaling.y);
  1050. } else if (currentName == "offsetU") {
  1051. XmlParser::getFloatAttribute(currentNode, currentName.c_str(), out.mTransform.mTranslation.x);
  1052. } else if (currentName == "offsetV") {
  1053. XmlParser::getFloatAttribute(currentNode, currentName.c_str(), out.mTransform.mTranslation.y);
  1054. } else if (currentName == "rotateUV") {
  1055. XmlParser::getFloatAttribute(currentNode, currentName.c_str(), out.mTransform.mRotation);
  1056. } else if (currentName == "blend_mode") {
  1057. std::string v;
  1058. XmlParser::getValueAsString(currentNode, v);
  1059. const char *sz = v.c_str();
  1060. // http://www.feelingsoftware.com/content/view/55/72/lang,en/
  1061. // NONE, OVER, IN, OUT, ADD, SUBTRACT, MULTIPLY, DIFFERENCE, LIGHTEN, DARKEN, SATURATE, DESATURATE and ILLUMINATE
  1062. if (0 == ASSIMP_strincmp(sz, "ADD", 3))
  1063. out.mOp = aiTextureOp_Add;
  1064. else if (0 == ASSIMP_strincmp(sz, "SUBTRACT", 8))
  1065. out.mOp = aiTextureOp_Subtract;
  1066. else if (0 == ASSIMP_strincmp(sz, "MULTIPLY", 8))
  1067. out.mOp = aiTextureOp_Multiply;
  1068. else {
  1069. ASSIMP_LOG_WARN("Collada: Unsupported MAYA texture blend mode");
  1070. }
  1071. }
  1072. // OKINO extensions
  1073. // -------------------------------------------------------
  1074. else if (currentName == "weighting") {
  1075. XmlParser::getFloatAttribute(currentNode, currentName.c_str(), out.mWeighting);
  1076. } else if (currentName == "mix_with_previous_layer") {
  1077. XmlParser::getFloatAttribute(currentNode, currentName.c_str(), out.mMixWithPrevious);
  1078. }
  1079. // MAX3D extensions
  1080. // -------------------------------------------------------
  1081. else if (currentName == "amount") {
  1082. XmlParser::getFloatAttribute(currentNode, currentName.c_str(), out.mWeighting);
  1083. }
  1084. }
  1085. }
  1086. // ------------------------------------------------------------------------------------------------
  1087. // Reads an effect entry containing a color or a texture defining that color
  1088. void ColladaParser::ReadEffectColor(XmlNode &node, aiColor4D &pColor, Sampler &pSampler) {
  1089. if (node.empty()) {
  1090. return;
  1091. }
  1092. XmlNodeIterator xmlIt(node);
  1093. xmlIt.collectChildrenPreOrder(node);
  1094. XmlNode currentNode;
  1095. while (xmlIt.getNext(currentNode)) {
  1096. const std::string &currentName = currentNode.name();
  1097. if (currentName == "color") {
  1098. // text content contains 4 floats
  1099. std::string v;
  1100. XmlParser::getValueAsString(currentNode, v);
  1101. const char *content = v.c_str();
  1102. content = fast_atoreal_move<ai_real>(content, (ai_real &)pColor.r);
  1103. SkipSpacesAndLineEnd(&content);
  1104. content = fast_atoreal_move<ai_real>(content, (ai_real &)pColor.g);
  1105. SkipSpacesAndLineEnd(&content);
  1106. content = fast_atoreal_move<ai_real>(content, (ai_real &)pColor.b);
  1107. SkipSpacesAndLineEnd(&content);
  1108. content = fast_atoreal_move<ai_real>(content, (ai_real &)pColor.a);
  1109. SkipSpacesAndLineEnd(&content);
  1110. } else if (currentName == "texture") {
  1111. // get name of source texture/sampler
  1112. XmlParser::getStdStrAttribute(currentNode, "texture", pSampler.mName);
  1113. // get name of UV source channel. Specification demands it to be there, but some exporters
  1114. // don't write it. It will be the default UV channel in case it's missing.
  1115. XmlParser::getStdStrAttribute(currentNode, "texcoord", pSampler.mUVChannel);
  1116. // as we've read texture, the color needs to be 1,1,1,1
  1117. pColor = aiColor4D(1.f, 1.f, 1.f, 1.f);
  1118. } else if (currentName == "technique") {
  1119. std::string profile;
  1120. XmlParser::getStdStrAttribute(currentNode, "profile", profile);
  1121. //const int _profile = GetAttribute("profile");
  1122. //const char *profile = mReader->getAttributeValue(_profile);
  1123. // Some extensions are quite useful ... ReadSamplerProperties processes
  1124. // several extensions in MAYA, OKINO and MAX3D profiles.
  1125. if (!::strcmp(profile.c_str(), "MAYA") || !::strcmp(profile.c_str(), "MAX3D") || !::strcmp(profile.c_str(), "OKINO")) {
  1126. // get more information on this sampler
  1127. ReadSamplerProperties(currentNode, pSampler);
  1128. }
  1129. }
  1130. }
  1131. }
  1132. // ------------------------------------------------------------------------------------------------
  1133. // Reads an effect entry containing a float
  1134. void ColladaParser::ReadEffectFloat(XmlNode &node, ai_real &pFloat) {
  1135. pFloat = 0.f;
  1136. XmlNode floatNode = node.child("float");
  1137. if (floatNode.empty()) {
  1138. return;
  1139. }
  1140. XmlParser::getValueAsFloat(floatNode, pFloat);
  1141. }
  1142. // ------------------------------------------------------------------------------------------------
  1143. // Reads an effect parameter specification of any kind
  1144. void ColladaParser::ReadEffectParam(XmlNode &node, Collada::EffectParam &pParam) {
  1145. if (node.empty()) {
  1146. return;
  1147. }
  1148. XmlNodeIterator xmlIt(node);
  1149. xmlIt.collectChildrenPreOrder(node);
  1150. XmlNode currentNode;
  1151. while (xmlIt.getNext(currentNode)) {
  1152. const std::string &currentName = currentNode.name();
  1153. if (currentName == "surface") {
  1154. // image ID given inside <init_from> tags
  1155. XmlNode initNode = currentNode.child("init_from");
  1156. if (initNode) {
  1157. std::string v;
  1158. XmlParser::getValueAsString(initNode, v);
  1159. pParam.mType = Param_Surface;
  1160. pParam.mReference = v.c_str();
  1161. }
  1162. } else if (currentName == "sampler2D" && (FV_1_4_n == mFormat || FV_1_3_n == mFormat)) {
  1163. // surface ID is given inside <source> tags
  1164. const char *content = currentNode.value();
  1165. pParam.mType = Param_Sampler;
  1166. pParam.mReference = content;
  1167. } else if (currentName == "sampler2D") {
  1168. // surface ID is given inside <instance_image> tags
  1169. std::string url;
  1170. XmlParser::getStdStrAttribute(currentNode, "url", url);
  1171. if (url[0] != '#') {
  1172. throw DeadlyImportError("Unsupported URL format in instance_image");
  1173. }
  1174. pParam.mType = Param_Sampler;
  1175. pParam.mReference = url.c_str() + 1;
  1176. }
  1177. }
  1178. }
  1179. // ------------------------------------------------------------------------------------------------
  1180. // Reads the geometry library contents
  1181. void ColladaParser::ReadGeometryLibrary(XmlNode &node) {
  1182. if (node.empty()) {
  1183. return;
  1184. }
  1185. for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  1186. const std::string &currentName = currentNode.name();
  1187. if (currentName == "geometry") {
  1188. // read ID. Another entry which is "optional" by design but obligatory in reality
  1189. std::string id;
  1190. XmlParser::getStdStrAttribute(currentNode, "id", id);
  1191. // create a mesh and store it in the library under its (resolved) ID
  1192. // Skip and warn if ID is not unique
  1193. if (mMeshLibrary.find(id) == mMeshLibrary.cend()) {
  1194. std::unique_ptr<Mesh> mesh(new Mesh(id));
  1195. XmlParser::getStdStrAttribute(currentNode, "name", mesh->mName);
  1196. // read on from there
  1197. ReadGeometry(currentNode, *mesh);
  1198. // Read successfully, add to library
  1199. mMeshLibrary.insert({ id, mesh.release() });
  1200. }
  1201. }
  1202. }
  1203. }
  1204. // ------------------------------------------------------------------------------------------------
  1205. // Reads a geometry from the geometry library.
  1206. void ColladaParser::ReadGeometry(XmlNode &node, Collada::Mesh &pMesh) {
  1207. if (node.empty()) {
  1208. return;
  1209. }
  1210. for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  1211. const std::string &currentName = currentNode.name();
  1212. if (currentName == "mesh") {
  1213. ReadMesh(currentNode, pMesh);
  1214. }
  1215. }
  1216. }
  1217. // ------------------------------------------------------------------------------------------------
  1218. // Reads a mesh from the geometry library
  1219. void ColladaParser::ReadMesh(XmlNode &node, Mesh &pMesh) {
  1220. if (node.empty()) {
  1221. return;
  1222. }
  1223. XmlNodeIterator xmlIt(node);
  1224. xmlIt.collectChildrenPreOrder(node);
  1225. XmlNode currentNode;
  1226. while (xmlIt.getNext(currentNode)) {
  1227. const std::string &currentName = currentNode.name();
  1228. if (currentName == "source") {
  1229. ReadSource(currentNode);
  1230. } else if (currentName == "vertices") {
  1231. ReadVertexData(currentNode, pMesh);
  1232. } else if (currentName == "triangles" || currentName == "lines" || currentName == "linestrips" || currentName == "polygons" || currentName == "polylist" || currentName == "trifans" || currentName == "tristrips") {
  1233. ReadIndexData(currentNode, pMesh);
  1234. }
  1235. }
  1236. }
  1237. // ------------------------------------------------------------------------------------------------
  1238. // Reads a source element
  1239. void ColladaParser::ReadSource(XmlNode &node) {
  1240. if (node.empty()) {
  1241. return;
  1242. }
  1243. std::string sourceID;
  1244. XmlParser::getStdStrAttribute(node, "id", sourceID);
  1245. XmlNodeIterator xmlIt(node);
  1246. xmlIt.collectChildrenPreOrder(node);
  1247. XmlNode currentNode;
  1248. while (xmlIt.getNext(currentNode)) {
  1249. const std::string &currentName = currentNode.name();
  1250. if (currentName == "float_array" || currentName == "IDREF_array" || currentName == "Name_array") {
  1251. ReadDataArray(currentNode);
  1252. } else if (currentName == "technique_common") {
  1253. XmlNode technique = currentNode.child("accessor");
  1254. if (!technique.empty()) {
  1255. ReadAccessor(technique, sourceID);
  1256. }
  1257. }
  1258. }
  1259. }
  1260. // ------------------------------------------------------------------------------------------------
  1261. // Reads a data array holding a number of floats, and stores it in the global library
  1262. void ColladaParser::ReadDataArray(XmlNode &node) {
  1263. std::string name = node.name();
  1264. bool isStringArray = (name == "IDREF_array" || name == "Name_array");
  1265. // read attributes
  1266. std::string id;
  1267. XmlParser::getStdStrAttribute(node, "id", id);
  1268. unsigned int count;
  1269. XmlParser::getUIntAttribute(node, "count", count);
  1270. std::string v;
  1271. XmlParser::getValueAsString(node, v);
  1272. trim(v);
  1273. const char *content = v.c_str();
  1274. // read values and store inside an array in the data library
  1275. mDataLibrary[id] = Data();
  1276. Data &data = mDataLibrary[id];
  1277. data.mIsStringArray = isStringArray;
  1278. // some exporters write empty data arrays, but we need to conserve them anyways because others might reference them
  1279. if (content) {
  1280. if (isStringArray) {
  1281. data.mStrings.reserve(count);
  1282. std::string s;
  1283. for (unsigned int a = 0; a < count; a++) {
  1284. if (*content == 0) {
  1285. throw DeadlyImportError("Expected more values while reading IDREF_array contents.");
  1286. }
  1287. s.clear();
  1288. while (!IsSpaceOrNewLine(*content))
  1289. s += *content++;
  1290. data.mStrings.push_back(s);
  1291. SkipSpacesAndLineEnd(&content);
  1292. }
  1293. } else {
  1294. data.mValues.reserve(count);
  1295. for (unsigned int a = 0; a < count; a++) {
  1296. if (*content == 0) {
  1297. throw DeadlyImportError("Expected more values while reading float_array contents.");
  1298. }
  1299. ai_real value;
  1300. // read a number
  1301. //SkipSpacesAndLineEnd(&content);
  1302. content = fast_atoreal_move<ai_real>(content, value);
  1303. data.mValues.push_back(value);
  1304. // skip whitespace after it
  1305. SkipSpacesAndLineEnd(&content);
  1306. }
  1307. }
  1308. }
  1309. }
  1310. // ------------------------------------------------------------------------------------------------
  1311. // Reads an accessor and stores it in the global library
  1312. void ColladaParser::ReadAccessor(XmlNode &node, const std::string &pID) {
  1313. // read accessor attributes
  1314. std::string source;
  1315. XmlParser::getStdStrAttribute(node, "source", source);
  1316. if (source[0] != '#') {
  1317. throw DeadlyImportError("Unknown reference format in url \"", source, "\" in source attribute of <accessor> element.");
  1318. }
  1319. int count = 0;
  1320. XmlParser::getIntAttribute(node, "count", count);
  1321. unsigned int offset = 0;
  1322. if (XmlParser::hasAttribute(node, "offset")) {
  1323. XmlParser::getUIntAttribute(node, "offset", offset);
  1324. }
  1325. unsigned int stride = 1;
  1326. if (XmlParser::hasAttribute(node, "stride")) {
  1327. XmlParser::getUIntAttribute(node, "stride", stride);
  1328. }
  1329. // store in the library under the given ID
  1330. mAccessorLibrary[pID] = Accessor();
  1331. Accessor &acc = mAccessorLibrary[pID];
  1332. acc.mCount = count;
  1333. acc.mOffset = offset;
  1334. acc.mStride = stride;
  1335. acc.mSource = source.c_str() + 1; // ignore the leading '#'
  1336. acc.mSize = 0; // gets incremented with every param
  1337. XmlNodeIterator xmlIt(node);
  1338. xmlIt.collectChildrenPreOrder(node);
  1339. XmlNode currentNode;
  1340. while (xmlIt.getNext(currentNode)) {
  1341. const std::string &currentName = currentNode.name();
  1342. if (currentName == "param") {
  1343. // read data param
  1344. std::string name;
  1345. if (XmlParser::hasAttribute(currentNode, "name")) {
  1346. XmlParser::getStdStrAttribute(currentNode, "name", name);
  1347. //name = mReader->getAttributeValue(attrName);
  1348. // analyse for common type components and store it's sub-offset in the corresponding field
  1349. /* Cartesian coordinates */
  1350. if (name == "X")
  1351. acc.mSubOffset[0] = acc.mParams.size();
  1352. else if (name == "Y")
  1353. acc.mSubOffset[1] = acc.mParams.size();
  1354. else if (name == "Z")
  1355. acc.mSubOffset[2] = acc.mParams.size();
  1356. /* RGBA colors */
  1357. else if (name == "R")
  1358. acc.mSubOffset[0] = acc.mParams.size();
  1359. else if (name == "G")
  1360. acc.mSubOffset[1] = acc.mParams.size();
  1361. else if (name == "B")
  1362. acc.mSubOffset[2] = acc.mParams.size();
  1363. else if (name == "A")
  1364. acc.mSubOffset[3] = acc.mParams.size();
  1365. /* UVWQ (STPQ) texture coordinates */
  1366. else if (name == "S")
  1367. acc.mSubOffset[0] = acc.mParams.size();
  1368. else if (name == "T")
  1369. acc.mSubOffset[1] = acc.mParams.size();
  1370. else if (name == "P")
  1371. acc.mSubOffset[2] = acc.mParams.size();
  1372. // else if( name == "Q") acc.mSubOffset[3] = acc.mParams.size();
  1373. /* 4D uv coordinates are not supported in Assimp */
  1374. /* Generic extra data, interpreted as UV data, too*/
  1375. else if (name == "U")
  1376. acc.mSubOffset[0] = acc.mParams.size();
  1377. else if (name == "V")
  1378. acc.mSubOffset[1] = acc.mParams.size();
  1379. //else
  1380. // DefaultLogger::get()->warn( format() << "Unknown accessor parameter \"" << name << "\". Ignoring data channel." );
  1381. }
  1382. if (XmlParser::hasAttribute(currentNode, "type")) {
  1383. // read data type
  1384. // TODO: (thom) I don't have a spec here at work. Check if there are other multi-value types
  1385. // which should be tested for here.
  1386. std::string type;
  1387. XmlParser::getStdStrAttribute(currentNode, "type", type);
  1388. if (type == "float4x4")
  1389. acc.mSize += 16;
  1390. else
  1391. acc.mSize += 1;
  1392. }
  1393. acc.mParams.push_back(name);
  1394. }
  1395. }
  1396. }
  1397. // ------------------------------------------------------------------------------------------------
  1398. // Reads input declarations of per-vertex mesh data into the given mesh
  1399. void ColladaParser::ReadVertexData(XmlNode &node, Mesh &pMesh) {
  1400. // extract the ID of the <vertices> element. Not that we care, but to catch strange referencing schemes we should warn about
  1401. XmlParser::getStdStrAttribute(node, "id", pMesh.mVertexID);
  1402. for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  1403. const std::string &currentName = currentNode.name();
  1404. if (currentName == "input") {
  1405. ReadInputChannel(currentNode, pMesh.mPerVertexData);
  1406. } else {
  1407. throw DeadlyImportError("Unexpected sub element <", currentName, "> in tag <vertices>");
  1408. }
  1409. }
  1410. }
  1411. // ------------------------------------------------------------------------------------------------
  1412. // Reads input declarations of per-index mesh data into the given mesh
  1413. void ColladaParser::ReadIndexData(XmlNode &node, Mesh &pMesh) {
  1414. std::vector<size_t> vcount;
  1415. std::vector<InputChannel> perIndexData;
  1416. unsigned int numPrimitives;
  1417. XmlParser::getUIntAttribute(node, "count", numPrimitives);
  1418. // read primitive count from the attribute
  1419. //int attrCount = GetAttribute("count");
  1420. //size_t numPrimitives = (size_t)mReader->getAttributeValueAsInt(attrCount);
  1421. // some mesh types (e.g. tristrips) don't specify primitive count upfront,
  1422. // so we need to sum up the actual number of primitives while we read the <p>-tags
  1423. size_t actualPrimitives = 0;
  1424. SubMesh subgroup;
  1425. if (XmlParser::hasAttribute(node, "material")) {
  1426. XmlParser::getStdStrAttribute(node, "material", subgroup.mMaterial);
  1427. }
  1428. // material subgroup
  1429. // int attrMaterial = TestAttribute("material");
  1430. //if (attrMaterial > -1)
  1431. // subgroup.mMaterial = mReader->getAttributeValue(attrMaterial);
  1432. // distinguish between polys and triangles
  1433. std::string elementName = node.name();
  1434. PrimitiveType primType = Prim_Invalid;
  1435. if (elementName == "lines")
  1436. primType = Prim_Lines;
  1437. else if (elementName == "linestrips")
  1438. primType = Prim_LineStrip;
  1439. else if (elementName == "polygons")
  1440. primType = Prim_Polygon;
  1441. else if (elementName == "polylist")
  1442. primType = Prim_Polylist;
  1443. else if (elementName == "triangles")
  1444. primType = Prim_Triangles;
  1445. else if (elementName == "trifans")
  1446. primType = Prim_TriFans;
  1447. else if (elementName == "tristrips")
  1448. primType = Prim_TriStrips;
  1449. ai_assert(primType != Prim_Invalid);
  1450. // also a number of <input> elements, but in addition a <p> primitive collection and probably index counts for all primitives
  1451. XmlNodeIterator xmlIt(node);
  1452. xmlIt.collectChildrenPreOrder(node);
  1453. XmlNode currentNode;
  1454. while (xmlIt.getNext(currentNode)) {
  1455. const std::string &currentName = currentNode.name();
  1456. if (currentName == "input") {
  1457. ReadInputChannel(currentNode, perIndexData);
  1458. } else if (currentName == "vcount") {
  1459. if (!currentNode.empty()) {
  1460. if (numPrimitives) // It is possible to define a mesh without any primitives
  1461. {
  1462. // case <polylist> - specifies the number of indices for each polygon
  1463. std::string v;
  1464. XmlParser::getValueAsString(currentNode, v);
  1465. const char *content = v.c_str();
  1466. vcount.reserve(numPrimitives);
  1467. for (unsigned int a = 0; a < numPrimitives; a++) {
  1468. if (*content == 0) {
  1469. throw DeadlyImportError("Expected more values while reading <vcount> contents.");
  1470. }
  1471. // read a number
  1472. vcount.push_back((size_t)strtoul10(content, &content));
  1473. // skip whitespace after it
  1474. SkipSpacesAndLineEnd(&content);
  1475. }
  1476. }
  1477. }
  1478. } else if (currentName == "p") {
  1479. if (!currentNode.empty()) {
  1480. // now here the actual fun starts - these are the indices to construct the mesh data from
  1481. actualPrimitives += ReadPrimitives(currentNode, pMesh, perIndexData, numPrimitives, vcount, primType);
  1482. }
  1483. } else if (currentName == "extra") {
  1484. // skip
  1485. } else if (currentName == "ph") {
  1486. // skip
  1487. } else {
  1488. throw DeadlyImportError("Unexpected sub element <", currentName, "> in tag <", elementName, ">");
  1489. }
  1490. }
  1491. #ifdef ASSIMP_BUILD_DEBUG
  1492. if (primType != Prim_TriFans && primType != Prim_TriStrips && primType != Prim_LineStrip &&
  1493. 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'.
  1494. ai_assert(actualPrimitives == numPrimitives);
  1495. }
  1496. #endif
  1497. // only when we're done reading all <p> tags (and thus know the final vertex count) can we commit the submesh
  1498. subgroup.mNumFaces = actualPrimitives;
  1499. pMesh.mSubMeshes.push_back(subgroup);
  1500. }
  1501. // ------------------------------------------------------------------------------------------------
  1502. // Reads a single input channel element and stores it in the given array, if valid
  1503. void ColladaParser::ReadInputChannel(XmlNode &node, std::vector<InputChannel> &poChannels) {
  1504. InputChannel channel;
  1505. // read semantic
  1506. std::string semantic;
  1507. XmlParser::getStdStrAttribute(node, "semantic", semantic);
  1508. channel.mType = GetTypeForSemantic(semantic);
  1509. // read source
  1510. std::string source;
  1511. XmlParser::getStdStrAttribute(node, "source", source);
  1512. if (source[0] != '#') {
  1513. throw DeadlyImportError("Unknown reference format in url \"", source, "\" in source attribute of <input> element.");
  1514. }
  1515. channel.mAccessor = source.c_str() + 1; // skipping the leading #, hopefully the remaining text is the accessor ID only
  1516. // read index offset, if per-index <input>
  1517. if (XmlParser::hasAttribute(node, "offset")) {
  1518. XmlParser::getUIntAttribute(node, "offset", (unsigned int &)channel.mOffset);
  1519. }
  1520. // read set if texture coordinates
  1521. if (channel.mType == IT_Texcoord || channel.mType == IT_Color) {
  1522. int attrSet = -1;
  1523. if (XmlParser::hasAttribute(node, "set")) {
  1524. XmlParser::getIntAttribute(node, "set", attrSet);
  1525. }
  1526. channel.mIndex = attrSet;
  1527. }
  1528. // store, if valid type
  1529. if (channel.mType != IT_Invalid)
  1530. poChannels.push_back(channel);
  1531. }
  1532. // ------------------------------------------------------------------------------------------------
  1533. // Reads a <p> primitive index list and assembles the mesh data into the given mesh
  1534. size_t ColladaParser::ReadPrimitives(XmlNode &node, Mesh &pMesh, std::vector<InputChannel> &pPerIndexChannels,
  1535. size_t pNumPrimitives, const std::vector<size_t> &pVCount, PrimitiveType pPrimType) {
  1536. // determine number of indices coming per vertex
  1537. // find the offset index for all per-vertex channels
  1538. size_t numOffsets = 1;
  1539. size_t perVertexOffset = SIZE_MAX; // invalid value
  1540. for (const InputChannel &channel : pPerIndexChannels) {
  1541. numOffsets = std::max(numOffsets, channel.mOffset + 1);
  1542. if (channel.mType == IT_Vertex)
  1543. perVertexOffset = channel.mOffset;
  1544. }
  1545. // determine the expected number of indices
  1546. size_t expectedPointCount = 0;
  1547. switch (pPrimType) {
  1548. case Prim_Polylist: {
  1549. for (size_t i : pVCount)
  1550. expectedPointCount += i;
  1551. break;
  1552. }
  1553. case Prim_Lines:
  1554. expectedPointCount = 2 * pNumPrimitives;
  1555. break;
  1556. case Prim_Triangles:
  1557. expectedPointCount = 3 * pNumPrimitives;
  1558. break;
  1559. default:
  1560. // other primitive types don't state the index count upfront... we need to guess
  1561. break;
  1562. }
  1563. // and read all indices into a temporary array
  1564. std::vector<size_t> indices;
  1565. if (expectedPointCount > 0)
  1566. indices.reserve(expectedPointCount * numOffsets);
  1567. if (pNumPrimitives > 0) // It is possible to not contain any indices
  1568. {
  1569. std::string v;
  1570. XmlParser::getValueAsString(node, v);
  1571. const char *content = v.c_str();
  1572. while (*content != 0) {
  1573. // read a value.
  1574. // Hack: (thom) Some exporters put negative indices sometimes. We just try to carry on anyways.
  1575. int value = std::max(0, strtol10(content, &content));
  1576. indices.push_back(size_t(value));
  1577. // skip whitespace after it
  1578. SkipSpacesAndLineEnd(&content);
  1579. }
  1580. }
  1581. // complain if the index count doesn't fit
  1582. if (expectedPointCount > 0 && indices.size() != expectedPointCount * numOffsets) {
  1583. if (pPrimType == Prim_Lines) {
  1584. // HACK: We just fix this number since SketchUp 15.3.331 writes the wrong 'count' for 'lines'
  1585. ReportWarning("Expected different index count in <p> element, %zu instead of %zu.", indices.size(), expectedPointCount * numOffsets);
  1586. pNumPrimitives = (indices.size() / numOffsets) / 2;
  1587. } else {
  1588. throw DeadlyImportError("Expected different index count in <p> element.");
  1589. }
  1590. } else if (expectedPointCount == 0 && (indices.size() % numOffsets) != 0) {
  1591. throw DeadlyImportError("Expected different index count in <p> element.");
  1592. }
  1593. // find the data for all sources
  1594. for (std::vector<InputChannel>::iterator it = pMesh.mPerVertexData.begin(); it != pMesh.mPerVertexData.end(); ++it) {
  1595. InputChannel &input = *it;
  1596. if (input.mResolved)
  1597. continue;
  1598. // find accessor
  1599. input.mResolved = &ResolveLibraryReference(mAccessorLibrary, input.mAccessor);
  1600. // resolve accessor's data pointer as well, if necessary
  1601. const Accessor *acc = input.mResolved;
  1602. if (!acc->mData)
  1603. acc->mData = &ResolveLibraryReference(mDataLibrary, acc->mSource);
  1604. }
  1605. // and the same for the per-index channels
  1606. for (std::vector<InputChannel>::iterator it = pPerIndexChannels.begin(); it != pPerIndexChannels.end(); ++it) {
  1607. InputChannel &input = *it;
  1608. if (input.mResolved)
  1609. continue;
  1610. // ignore vertex pointer, it doesn't refer to an accessor
  1611. if (input.mType == IT_Vertex) {
  1612. // warn if the vertex channel does not refer to the <vertices> element in the same mesh
  1613. if (input.mAccessor != pMesh.mVertexID) {
  1614. throw DeadlyImportError("Unsupported vertex referencing scheme.");
  1615. }
  1616. continue;
  1617. }
  1618. // find accessor
  1619. input.mResolved = &ResolveLibraryReference(mAccessorLibrary, input.mAccessor);
  1620. // resolve accessor's data pointer as well, if necessary
  1621. const Accessor *acc = input.mResolved;
  1622. if (!acc->mData)
  1623. acc->mData = &ResolveLibraryReference(mDataLibrary, acc->mSource);
  1624. }
  1625. // For continued primitives, the given count does not come all in one <p>, but only one primitive per <p>
  1626. size_t numPrimitives = pNumPrimitives;
  1627. if (pPrimType == Prim_TriFans || pPrimType == Prim_Polygon)
  1628. numPrimitives = 1;
  1629. // For continued primitives, the given count is actually the number of <p>'s inside the parent tag
  1630. if (pPrimType == Prim_TriStrips) {
  1631. size_t numberOfVertices = indices.size() / numOffsets;
  1632. numPrimitives = numberOfVertices - 2;
  1633. }
  1634. if (pPrimType == Prim_LineStrip) {
  1635. size_t numberOfVertices = indices.size() / numOffsets;
  1636. numPrimitives = numberOfVertices - 1;
  1637. }
  1638. pMesh.mFaceSize.reserve(numPrimitives);
  1639. pMesh.mFacePosIndices.reserve(indices.size() / numOffsets);
  1640. size_t polylistStartVertex = 0;
  1641. for (size_t currentPrimitive = 0; currentPrimitive < numPrimitives; currentPrimitive++) {
  1642. // determine number of points for this primitive
  1643. size_t numPoints = 0;
  1644. switch (pPrimType) {
  1645. case Prim_Lines:
  1646. numPoints = 2;
  1647. for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++)
  1648. CopyVertex(currentVertex, numOffsets, numPoints, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices);
  1649. break;
  1650. case Prim_LineStrip:
  1651. numPoints = 2;
  1652. for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++)
  1653. CopyVertex(currentVertex, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices);
  1654. break;
  1655. case Prim_Triangles:
  1656. numPoints = 3;
  1657. for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++)
  1658. CopyVertex(currentVertex, numOffsets, numPoints, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices);
  1659. break;
  1660. case Prim_TriStrips:
  1661. numPoints = 3;
  1662. ReadPrimTriStrips(numOffsets, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices);
  1663. break;
  1664. case Prim_Polylist:
  1665. numPoints = pVCount[currentPrimitive];
  1666. for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++)
  1667. CopyVertex(polylistStartVertex + currentVertex, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, 0, indices);
  1668. polylistStartVertex += numPoints;
  1669. break;
  1670. case Prim_TriFans:
  1671. case Prim_Polygon:
  1672. numPoints = indices.size() / numOffsets;
  1673. for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++)
  1674. CopyVertex(currentVertex, numOffsets, numPoints, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices);
  1675. break;
  1676. default:
  1677. // LineStrip is not supported due to expected index unmangling
  1678. throw DeadlyImportError("Unsupported primitive type.");
  1679. break;
  1680. }
  1681. // store the face size to later reconstruct the face from
  1682. pMesh.mFaceSize.push_back(numPoints);
  1683. }
  1684. // if I ever get my hands on that guy who invented this steaming pile of indirection...
  1685. return numPrimitives;
  1686. }
  1687. ///@note This function won't work correctly if both PerIndex and PerVertex channels have same channels.
  1688. ///For example if TEXCOORD present in both <vertices> and <polylist> tags this function will create wrong uv coordinates.
  1689. ///It's not clear from COLLADA documentation is this allowed or not. For now only exporter fixed to avoid such behavior
  1690. void ColladaParser::CopyVertex(size_t currentVertex, size_t numOffsets, size_t numPoints, size_t perVertexOffset, Mesh &pMesh,
  1691. std::vector<InputChannel> &pPerIndexChannels, size_t currentPrimitive, const std::vector<size_t> &indices) {
  1692. // calculate the base offset of the vertex whose attributes we ant to copy
  1693. size_t baseOffset = currentPrimitive * numOffsets * numPoints + currentVertex * numOffsets;
  1694. // don't overrun the boundaries of the index list
  1695. ai_assert((baseOffset + numOffsets - 1) < indices.size());
  1696. // extract per-vertex channels using the global per-vertex offset
  1697. for (std::vector<InputChannel>::iterator it = pMesh.mPerVertexData.begin(); it != pMesh.mPerVertexData.end(); ++it)
  1698. ExtractDataObjectFromChannel(*it, indices[baseOffset + perVertexOffset], pMesh);
  1699. // and extract per-index channels using there specified offset
  1700. for (std::vector<InputChannel>::iterator it = pPerIndexChannels.begin(); it != pPerIndexChannels.end(); ++it)
  1701. ExtractDataObjectFromChannel(*it, indices[baseOffset + it->mOffset], pMesh);
  1702. // store the vertex-data index for later assignment of bone vertex weights
  1703. pMesh.mFacePosIndices.push_back(indices[baseOffset + perVertexOffset]);
  1704. }
  1705. void ColladaParser::ReadPrimTriStrips(size_t numOffsets, size_t perVertexOffset, Mesh &pMesh, std::vector<InputChannel> &pPerIndexChannels,
  1706. size_t currentPrimitive, const std::vector<size_t> &indices) {
  1707. if (currentPrimitive % 2 != 0) {
  1708. //odd tristrip triangles need their indices mangled, to preserve winding direction
  1709. CopyVertex(1, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices);
  1710. CopyVertex(0, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices);
  1711. CopyVertex(2, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices);
  1712. } else { //for non tristrips or even tristrip triangles
  1713. CopyVertex(0, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices);
  1714. CopyVertex(1, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices);
  1715. CopyVertex(2, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices);
  1716. }
  1717. }
  1718. // ------------------------------------------------------------------------------------------------
  1719. // Extracts a single object from an input channel and stores it in the appropriate mesh data array
  1720. void ColladaParser::ExtractDataObjectFromChannel(const InputChannel &pInput, size_t pLocalIndex, Mesh &pMesh) {
  1721. // ignore vertex referrer - we handle them that separate
  1722. if (pInput.mType == IT_Vertex)
  1723. return;
  1724. const Accessor &acc = *pInput.mResolved;
  1725. if (pLocalIndex >= acc.mCount) {
  1726. throw DeadlyImportError("Invalid data index (", pLocalIndex, "/", acc.mCount, ") in primitive specification");
  1727. }
  1728. // get a pointer to the start of the data object referred to by the accessor and the local index
  1729. const ai_real *dataObject = &(acc.mData->mValues[0]) + acc.mOffset + pLocalIndex * acc.mStride;
  1730. // assemble according to the accessors component sub-offset list. We don't care, yet,
  1731. // what kind of object exactly we're extracting here
  1732. ai_real obj[4];
  1733. for (size_t c = 0; c < 4; ++c)
  1734. obj[c] = dataObject[acc.mSubOffset[c]];
  1735. // now we reinterpret it according to the type we're reading here
  1736. switch (pInput.mType) {
  1737. case IT_Position: // ignore all position streams except 0 - there can be only one position
  1738. if (pInput.mIndex == 0)
  1739. pMesh.mPositions.push_back(aiVector3D(obj[0], obj[1], obj[2]));
  1740. else
  1741. ASSIMP_LOG_ERROR("Collada: just one vertex position stream supported");
  1742. break;
  1743. case IT_Normal:
  1744. // pad to current vertex count if necessary
  1745. if (pMesh.mNormals.size() < pMesh.mPositions.size() - 1)
  1746. pMesh.mNormals.insert(pMesh.mNormals.end(), pMesh.mPositions.size() - pMesh.mNormals.size() - 1, aiVector3D(0, 1, 0));
  1747. // ignore all normal streams except 0 - there can be only one normal
  1748. if (pInput.mIndex == 0)
  1749. pMesh.mNormals.push_back(aiVector3D(obj[0], obj[1], obj[2]));
  1750. else
  1751. ASSIMP_LOG_ERROR("Collada: just one vertex normal stream supported");
  1752. break;
  1753. case IT_Tangent:
  1754. // pad to current vertex count if necessary
  1755. if (pMesh.mTangents.size() < pMesh.mPositions.size() - 1)
  1756. pMesh.mTangents.insert(pMesh.mTangents.end(), pMesh.mPositions.size() - pMesh.mTangents.size() - 1, aiVector3D(1, 0, 0));
  1757. // ignore all tangent streams except 0 - there can be only one tangent
  1758. if (pInput.mIndex == 0)
  1759. pMesh.mTangents.push_back(aiVector3D(obj[0], obj[1], obj[2]));
  1760. else
  1761. ASSIMP_LOG_ERROR("Collada: just one vertex tangent stream supported");
  1762. break;
  1763. case IT_Bitangent:
  1764. // pad to current vertex count if necessary
  1765. if (pMesh.mBitangents.size() < pMesh.mPositions.size() - 1)
  1766. pMesh.mBitangents.insert(pMesh.mBitangents.end(), pMesh.mPositions.size() - pMesh.mBitangents.size() - 1, aiVector3D(0, 0, 1));
  1767. // ignore all bitangent streams except 0 - there can be only one bitangent
  1768. if (pInput.mIndex == 0)
  1769. pMesh.mBitangents.push_back(aiVector3D(obj[0], obj[1], obj[2]));
  1770. else
  1771. ASSIMP_LOG_ERROR("Collada: just one vertex bitangent stream supported");
  1772. break;
  1773. case IT_Texcoord:
  1774. // up to 4 texture coord sets are fine, ignore the others
  1775. if (pInput.mIndex < AI_MAX_NUMBER_OF_TEXTURECOORDS) {
  1776. // pad to current vertex count if necessary
  1777. if (pMesh.mTexCoords[pInput.mIndex].size() < pMesh.mPositions.size() - 1)
  1778. pMesh.mTexCoords[pInput.mIndex].insert(pMesh.mTexCoords[pInput.mIndex].end(),
  1779. pMesh.mPositions.size() - pMesh.mTexCoords[pInput.mIndex].size() - 1, aiVector3D(0, 0, 0));
  1780. pMesh.mTexCoords[pInput.mIndex].push_back(aiVector3D(obj[0], obj[1], obj[2]));
  1781. if (0 != acc.mSubOffset[2] || 0 != acc.mSubOffset[3]) /* hack ... consider cleaner solution */
  1782. pMesh.mNumUVComponents[pInput.mIndex] = 3;
  1783. } else {
  1784. ASSIMP_LOG_ERROR("Collada: too many texture coordinate sets. Skipping.");
  1785. }
  1786. break;
  1787. case IT_Color:
  1788. // up to 4 color sets are fine, ignore the others
  1789. if (pInput.mIndex < AI_MAX_NUMBER_OF_COLOR_SETS) {
  1790. // pad to current vertex count if necessary
  1791. if (pMesh.mColors[pInput.mIndex].size() < pMesh.mPositions.size() - 1)
  1792. pMesh.mColors[pInput.mIndex].insert(pMesh.mColors[pInput.mIndex].end(),
  1793. pMesh.mPositions.size() - pMesh.mColors[pInput.mIndex].size() - 1, aiColor4D(0, 0, 0, 1));
  1794. aiColor4D result(0, 0, 0, 1);
  1795. for (size_t i = 0; i < pInput.mResolved->mSize; ++i) {
  1796. result[static_cast<unsigned int>(i)] = obj[pInput.mResolved->mSubOffset[i]];
  1797. }
  1798. pMesh.mColors[pInput.mIndex].push_back(result);
  1799. } else {
  1800. ASSIMP_LOG_ERROR("Collada: too many vertex color sets. Skipping.");
  1801. }
  1802. break;
  1803. default:
  1804. // IT_Invalid and IT_Vertex
  1805. ai_assert(false && "shouldn't ever get here");
  1806. }
  1807. }
  1808. // ------------------------------------------------------------------------------------------------
  1809. // Reads the library of node hierarchies and scene parts
  1810. void ColladaParser::ReadSceneLibrary(XmlNode &node) {
  1811. if (node.empty()) {
  1812. return;
  1813. }
  1814. for (XmlNode currentNode : node.children()) {
  1815. const std::string &currentName = currentNode.name();
  1816. if (currentName == "visual_scene") {
  1817. // read ID. Is optional according to the spec, but how on earth should a scene_instance refer to it then?
  1818. std::string id;
  1819. XmlParser::getStdStrAttribute(currentNode, "id", id);
  1820. // read name if given.
  1821. std::string attrName = "Scene";
  1822. if (XmlParser::hasAttribute(currentNode, "name")) {
  1823. XmlParser::getStdStrAttribute(currentNode, "name", attrName);
  1824. }
  1825. // create a node and store it in the library under its ID
  1826. Node *sceneNode = new Node;
  1827. sceneNode->mID = id;
  1828. sceneNode->mName = attrName;
  1829. mNodeLibrary[sceneNode->mID] = sceneNode;
  1830. ReadSceneNode(currentNode, sceneNode);
  1831. }
  1832. }
  1833. }
  1834. // ------------------------------------------------------------------------------------------------
  1835. // Reads a scene node's contents including children and stores it in the given node
  1836. void ColladaParser::ReadSceneNode(XmlNode &node, Node *pNode) {
  1837. // quit immediately on <bla/> elements
  1838. if (node.empty()) {
  1839. return;
  1840. }
  1841. for (XmlNode &currentNode : node.children()) {
  1842. const std::string &currentName = currentNode.name();
  1843. if (currentName == "node") {
  1844. Node *child = new Node;
  1845. if (XmlParser::hasAttribute(currentNode, "id")) {
  1846. XmlParser::getStdStrAttribute(currentNode, "id", child->mID);
  1847. }
  1848. if (XmlParser::hasAttribute(currentNode, "sid")) {
  1849. XmlParser::getStdStrAttribute(currentNode, "id", child->mSID);
  1850. }
  1851. if (XmlParser::hasAttribute(currentNode, "name")) {
  1852. XmlParser::getStdStrAttribute(currentNode, "name", child->mName);
  1853. }
  1854. if (pNode) {
  1855. pNode->mChildren.push_back(child);
  1856. child->mParent = pNode;
  1857. } else {
  1858. // no parent node given, probably called from <library_nodes> element.
  1859. // create new node in node library
  1860. mNodeLibrary[child->mID] = child;
  1861. }
  1862. // read on recursively from there
  1863. ReadSceneNode(currentNode, child);
  1864. continue;
  1865. } else if (!pNode) {
  1866. // For any further stuff we need a valid node to work on
  1867. continue;
  1868. }
  1869. if (currentName == "lookat") {
  1870. ReadNodeTransformation(currentNode, pNode, TF_LOOKAT);
  1871. } else if (currentName == "matrix") {
  1872. ReadNodeTransformation(currentNode, pNode, TF_MATRIX);
  1873. } else if (currentName == "rotate") {
  1874. ReadNodeTransformation(currentNode, pNode, TF_ROTATE);
  1875. } else if (currentName == "scale") {
  1876. ReadNodeTransformation(currentNode, pNode, TF_SCALE);
  1877. } else if (currentName == "skew") {
  1878. ReadNodeTransformation(currentNode, pNode, TF_SKEW);
  1879. } else if (currentName == "translate") {
  1880. ReadNodeTransformation(currentNode, pNode, TF_TRANSLATE);
  1881. } else if (currentName == "render" && pNode->mParent == nullptr && 0 == pNode->mPrimaryCamera.length()) {
  1882. // ... scene evaluation or, in other words, postprocessing pipeline,
  1883. // or, again in other words, a turing-complete description how to
  1884. // render a Collada scene. The only thing that is interesting for
  1885. // us is the primary camera.
  1886. if (XmlParser::hasAttribute(currentNode, "camera_node")) {
  1887. std::string s;
  1888. XmlParser::getStdStrAttribute(currentNode, "camera_node", s);
  1889. if (s[0] != '#') {
  1890. ASSIMP_LOG_ERROR("Collada: Unresolved reference format of camera");
  1891. } else {
  1892. pNode->mPrimaryCamera = s.c_str() + 1;
  1893. }
  1894. }
  1895. } else if (currentName == "instance_node") {
  1896. // find the node in the library
  1897. if (XmlParser::hasAttribute(currentNode, "url")) {
  1898. std::string s;
  1899. XmlParser::getStdStrAttribute(currentNode, "url", s);
  1900. if (s[0] != '#') {
  1901. ASSIMP_LOG_ERROR("Collada: Unresolved reference format of node");
  1902. } else {
  1903. pNode->mNodeInstances.push_back(NodeInstance());
  1904. pNode->mNodeInstances.back().mNode = s.c_str() + 1;
  1905. }
  1906. }
  1907. } else if (currentName == "instance_geometry" || currentName == "instance_controller") {
  1908. // Reference to a mesh or controller, with possible material associations
  1909. ReadNodeGeometry(currentNode, pNode);
  1910. } else if (currentName == "instance_light") {
  1911. // Reference to a light, name given in 'url' attribute
  1912. if (XmlParser::hasAttribute(currentNode, "url")) {
  1913. std::string url;
  1914. XmlParser::getStdStrAttribute(currentNode, "url", url);
  1915. if (url[0] != '#') {
  1916. throw DeadlyImportError("Unknown reference format in <instance_light> element");
  1917. }
  1918. pNode->mLights.push_back(LightInstance());
  1919. pNode->mLights.back().mLight = url.c_str() + 1;
  1920. }
  1921. } else if (currentName == "instance_camera") {
  1922. // Reference to a camera, name given in 'url' attribute
  1923. if (XmlParser::hasAttribute(currentNode, "url")) {
  1924. std::string url;
  1925. XmlParser::getStdStrAttribute(currentNode, "url", url);
  1926. if (url[0] != '#') {
  1927. throw DeadlyImportError("Unknown reference format in <instance_camera> element");
  1928. }
  1929. pNode->mCameras.push_back(CameraInstance());
  1930. pNode->mCameras.back().mCamera = url.c_str() + 1;
  1931. }
  1932. }
  1933. }
  1934. }
  1935. // ------------------------------------------------------------------------------------------------
  1936. // Reads a node transformation entry of the given type and adds it to the given node's transformation list.
  1937. void ColladaParser::ReadNodeTransformation(XmlNode &node, Node *pNode, TransformType pType) {
  1938. if (node.empty()) {
  1939. return;
  1940. }
  1941. std::string tagName = node.name();
  1942. Transform tf;
  1943. tf.mType = pType;
  1944. // read SID
  1945. if (XmlParser::hasAttribute(node, "sid")) {
  1946. XmlParser::getStdStrAttribute(node, "sid", tf.mID);
  1947. }
  1948. // how many parameters to read per transformation type
  1949. static const unsigned int sNumParameters[] = { 9, 4, 3, 3, 7, 16 };
  1950. std::string value;
  1951. XmlParser::getValueAsString(node, value);
  1952. const char *content = value.c_str();
  1953. // read as many parameters and store in the transformation
  1954. for (unsigned int a = 0; a < sNumParameters[pType]; a++) {
  1955. // read a number
  1956. content = fast_atoreal_move<ai_real>(content, tf.f[a]);
  1957. // skip whitespace after it
  1958. SkipSpacesAndLineEnd(&content);
  1959. }
  1960. // place the transformation at the queue of the node
  1961. pNode->mTransforms.push_back(tf);
  1962. }
  1963. // ------------------------------------------------------------------------------------------------
  1964. // Processes bind_vertex_input and bind elements
  1965. void ColladaParser::ReadMaterialVertexInputBinding(XmlNode &node, Collada::SemanticMappingTable &tbl) {
  1966. //XmlNodeIterator xmlIt(node);
  1967. //xmlIt.collectChildrenPreOrder(node);
  1968. //XmlNode currentNode;
  1969. std::string name = node.name();
  1970. for (XmlNode currentNode : node.children()) {
  1971. const std::string &currentName = currentNode.name();
  1972. if (currentName == "bind_vertex_input") {
  1973. Collada::InputSemanticMapEntry vn;
  1974. // effect semantic
  1975. if (XmlParser::hasAttribute(currentNode, "semantic")) {
  1976. std::string s;
  1977. XmlParser::getStdStrAttribute(currentNode, "semantic", s);
  1978. XmlParser::getUIntAttribute(currentNode, "input_semantic", (unsigned int &)vn.mType);
  1979. }
  1980. std::string s;
  1981. XmlParser::getStdStrAttribute(currentNode, "semantic", s);
  1982. // input semantic
  1983. XmlParser::getUIntAttribute(currentNode, "input_semantic", (unsigned int &)vn.mType);
  1984. // index of input set
  1985. if (XmlParser::hasAttribute(currentNode, "input_set")) {
  1986. XmlParser::getUIntAttribute(currentNode, "input_set", vn.mSet);
  1987. }
  1988. tbl.mMap[s] = vn;
  1989. } else if (currentName == "bind") {
  1990. ASSIMP_LOG_WARN("Collada: Found unsupported <bind> element");
  1991. }
  1992. }
  1993. }
  1994. void ColladaParser::ReadEmbeddedTextures(ZipArchiveIOSystem &zip_archive) {
  1995. // Attempt to load any undefined Collada::Image in ImageLibrary
  1996. for (ImageLibrary::iterator it = mImageLibrary.begin(); it != mImageLibrary.end(); ++it) {
  1997. Collada::Image &image = (*it).second;
  1998. if (image.mImageData.empty()) {
  1999. std::unique_ptr<IOStream> image_file(zip_archive.Open(image.mFileName.c_str()));
  2000. if (image_file) {
  2001. image.mImageData.resize(image_file->FileSize());
  2002. image_file->Read(image.mImageData.data(), image_file->FileSize(), 1);
  2003. image.mEmbeddedFormat = BaseImporter::GetExtension(image.mFileName);
  2004. if (image.mEmbeddedFormat == "jpeg") {
  2005. image.mEmbeddedFormat = "jpg";
  2006. }
  2007. }
  2008. }
  2009. }
  2010. }
  2011. // ------------------------------------------------------------------------------------------------
  2012. // Reads a mesh reference in a node and adds it to the node's mesh list
  2013. void ColladaParser::ReadNodeGeometry(XmlNode &node, Node *pNode) {
  2014. // referred mesh is given as an attribute of the <instance_geometry> element
  2015. std::string url;
  2016. XmlParser::getStdStrAttribute(node, "url", url);
  2017. if (url[0] != '#') {
  2018. throw DeadlyImportError("Unknown reference format");
  2019. }
  2020. Collada::MeshInstance instance;
  2021. instance.mMeshOrController = url.c_str() + 1; // skipping the leading #
  2022. for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  2023. const std::string &currentName = currentNode.name();
  2024. if (currentName == "bind_material") {
  2025. XmlNode techNode = currentNode.child("technique_common");
  2026. if (techNode) {
  2027. XmlNode instanceMatNode = techNode.child("instance_material");
  2028. // read ID of the geometry subgroup and the target material
  2029. std::string group;
  2030. XmlParser::getStdStrAttribute(instanceMatNode, "symbol", group);
  2031. XmlParser::getStdStrAttribute(instanceMatNode, "target", url);
  2032. const char *urlMat = url.c_str();
  2033. Collada::SemanticMappingTable s;
  2034. if (urlMat[0] == '#')
  2035. urlMat++;
  2036. s.mMatName = urlMat;
  2037. // store the association
  2038. instance.mMaterials[group] = s;
  2039. ReadMaterialVertexInputBinding(instanceMatNode, s);
  2040. }
  2041. }
  2042. }
  2043. // store it
  2044. pNode->mMeshes.push_back(instance);
  2045. }
  2046. // ------------------------------------------------------------------------------------------------
  2047. // Reads the collada scene
  2048. void ColladaParser::ReadScene(XmlNode &node) {
  2049. if (node.empty()) {
  2050. return;
  2051. }
  2052. for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
  2053. const std::string currentName = currentNode.name();
  2054. if (currentName == "instance_visual_scene") {
  2055. // should be the first and only occurrence
  2056. if (mRootNode) {
  2057. throw DeadlyImportError("Invalid scene containing multiple root nodes in <instance_visual_scene> element");
  2058. }
  2059. // read the url of the scene to instance. Should be of format "#some_name"
  2060. std::string url;
  2061. XmlParser::getStdStrAttribute(currentNode, "url", url);
  2062. if (url[0] != '#') {
  2063. throw DeadlyImportError("Unknown reference format in <instance_visual_scene> element");
  2064. }
  2065. // find the referred scene, skip the leading #
  2066. NodeLibrary::const_iterator sit = mNodeLibrary.find(url.c_str() + 1);
  2067. if (sit == mNodeLibrary.end()) {
  2068. throw DeadlyImportError("Unable to resolve visual_scene reference \"", std::string(url), "\" in <instance_visual_scene> element.");
  2069. }
  2070. mRootNode = sit->second;
  2071. }
  2072. }
  2073. }
  2074. void ColladaParser::ReportWarning(const char *msg, ...) {
  2075. ai_assert(nullptr != msg);
  2076. va_list args;
  2077. va_start(args, msg);
  2078. char szBuffer[3000];
  2079. const int iLen = vsprintf(szBuffer, msg, args);
  2080. ai_assert(iLen > 0);
  2081. va_end(args);
  2082. ASSIMP_LOG_WARN_F("Validation warning: ", std::string(szBuffer, iLen));
  2083. }
  2084. // ------------------------------------------------------------------------------------------------
  2085. // Calculates the resulting transformation from all the given transform steps
  2086. aiMatrix4x4 ColladaParser::CalculateResultTransform(const std::vector<Transform> &pTransforms) const {
  2087. aiMatrix4x4 res;
  2088. for (std::vector<Transform>::const_iterator it = pTransforms.begin(); it != pTransforms.end(); ++it) {
  2089. const Transform &tf = *it;
  2090. switch (tf.mType) {
  2091. case TF_LOOKAT: {
  2092. aiVector3D pos(tf.f[0], tf.f[1], tf.f[2]);
  2093. aiVector3D dstPos(tf.f[3], tf.f[4], tf.f[5]);
  2094. aiVector3D up = aiVector3D(tf.f[6], tf.f[7], tf.f[8]).Normalize();
  2095. aiVector3D dir = aiVector3D(dstPos - pos).Normalize();
  2096. aiVector3D right = (dir ^ up).Normalize();
  2097. res *= aiMatrix4x4(
  2098. right.x, up.x, -dir.x, pos.x,
  2099. right.y, up.y, -dir.y, pos.y,
  2100. right.z, up.z, -dir.z, pos.z,
  2101. 0, 0, 0, 1);
  2102. break;
  2103. }
  2104. case TF_ROTATE: {
  2105. aiMatrix4x4 rot;
  2106. ai_real angle = tf.f[3] * ai_real(AI_MATH_PI) / ai_real(180.0);
  2107. aiVector3D axis(tf.f[0], tf.f[1], tf.f[2]);
  2108. aiMatrix4x4::Rotation(angle, axis, rot);
  2109. res *= rot;
  2110. break;
  2111. }
  2112. case TF_TRANSLATE: {
  2113. aiMatrix4x4 trans;
  2114. aiMatrix4x4::Translation(aiVector3D(tf.f[0], tf.f[1], tf.f[2]), trans);
  2115. res *= trans;
  2116. break;
  2117. }
  2118. case TF_SCALE: {
  2119. 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,
  2120. 0.0f, 0.0f, 0.0f, 1.0f);
  2121. res *= scale;
  2122. break;
  2123. }
  2124. case TF_SKEW:
  2125. // TODO: (thom)
  2126. ai_assert(false);
  2127. break;
  2128. case TF_MATRIX: {
  2129. 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],
  2130. tf.f[8], tf.f[9], tf.f[10], tf.f[11], tf.f[12], tf.f[13], tf.f[14], tf.f[15]);
  2131. res *= mat;
  2132. break;
  2133. }
  2134. default:
  2135. ai_assert(false);
  2136. break;
  2137. }
  2138. }
  2139. return res;
  2140. }
  2141. // ------------------------------------------------------------------------------------------------
  2142. // Determines the input data type for the given semantic string
  2143. Collada::InputType ColladaParser::GetTypeForSemantic(const std::string &semantic) {
  2144. if (semantic.empty()) {
  2145. ASSIMP_LOG_WARN("Vertex input type is empty.");
  2146. return IT_Invalid;
  2147. }
  2148. if (semantic == "POSITION")
  2149. return IT_Position;
  2150. else if (semantic == "TEXCOORD")
  2151. return IT_Texcoord;
  2152. else if (semantic == "NORMAL")
  2153. return IT_Normal;
  2154. else if (semantic == "COLOR")
  2155. return IT_Color;
  2156. else if (semantic == "VERTEX")
  2157. return IT_Vertex;
  2158. else if (semantic == "BINORMAL" || semantic == "TEXBINORMAL")
  2159. return IT_Bitangent;
  2160. else if (semantic == "TANGENT" || semantic == "TEXTANGENT")
  2161. return IT_Tangent;
  2162. ASSIMP_LOG_WARN_F("Unknown vertex input type \"", semantic, "\". Ignoring.");
  2163. return IT_Invalid;
  2164. }
  2165. #endif // !! ASSIMP_BUILD_NO_DAE_IMPORTER