ColladaParser.cpp 126 KB

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