ColladaParser.cpp 101 KB

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