ColladaParser.cpp 100 KB

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