ColladaParser.cpp 127 KB

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