ColladaParser.cpp 118 KB

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