ColladaParser.cpp 99 KB

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