ColladaParser.cpp 100 KB

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