ColladaParser.cpp 101 KB

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