ColladaParser.cpp 121 KB

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