ColladaParser.cpp 101 KB

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