ColladaParser.cpp 130 KB

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