ColladaParser.cpp 130 KB

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