ColladaParser.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538
  1. /** Implementation of the Collada parser helper*/
  2. /*
  3. ---------------------------------------------------------------------------
  4. Open Asset Import Library (ASSIMP)
  5. ---------------------------------------------------------------------------
  6. Copyright (c) 2006-2008, ASSIMP Development Team
  7. All rights reserved.
  8. Redistribution and use of this software in source and binary forms,
  9. with or without modification, are permitted provided that the following
  10. conditions are met:
  11. * Redistributions of source code must retain the above
  12. copyright notice, this list of conditions and the
  13. following disclaimer.
  14. * Redistributions in binary form must reproduce the above
  15. copyright notice, this list of conditions and the
  16. following disclaimer in the documentation and/or other
  17. materials provided with the distribution.
  18. * Neither the name of the ASSIMP team, nor the names of its
  19. contributors may be used to endorse or promote products
  20. derived from this software without specific prior
  21. written permission of the ASSIMP Development Team.
  22. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  23. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  24. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  25. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  26. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  27. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  28. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  29. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  30. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  31. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  32. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  33. ---------------------------------------------------------------------------
  34. */
  35. #include "AssimpPCH.h"
  36. #ifndef ASSIMP_BUILD_NO_DAE_IMPORTER
  37. #include "ColladaParser.h"
  38. #include "fast_atof.h"
  39. #include "ParsingUtils.h"
  40. using namespace Assimp;
  41. using namespace Assimp::Collada;
  42. // ------------------------------------------------------------------------------------------------
  43. // Constructor to be privately used by Importer
  44. ColladaParser::ColladaParser( const std::string& pFile)
  45. : mFileName( pFile)
  46. {
  47. mRootNode = NULL;
  48. mUnitSize = 1.0f;
  49. mUpDirection = UP_Z;
  50. // generate a XML reader for it
  51. mReader = irr::io::createIrrXMLReader( pFile.c_str());
  52. if( !mReader)
  53. ThrowException( "Unable to open file.");
  54. // start reading
  55. ReadContents();
  56. }
  57. // ------------------------------------------------------------------------------------------------
  58. // Destructor, private as well
  59. ColladaParser::~ColladaParser()
  60. {
  61. delete mReader;
  62. for( NodeLibrary::iterator it = mNodeLibrary.begin(); it != mNodeLibrary.end(); ++it)
  63. delete it->second;
  64. for( MeshLibrary::iterator it = mMeshLibrary.begin(); it != mMeshLibrary.end(); ++it)
  65. delete it->second;
  66. }
  67. // ------------------------------------------------------------------------------------------------
  68. // Reads the contents of the file
  69. void ColladaParser::ReadContents()
  70. {
  71. while( mReader->read())
  72. {
  73. // handle the root element "COLLADA"
  74. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  75. {
  76. if( IsElement( "COLLADA"))
  77. {
  78. ReadStructure();
  79. } else
  80. {
  81. DefaultLogger::get()->debug( boost::str( boost::format( "Ignoring global element \"%s\".") % mReader->getNodeName()));
  82. SkipElement();
  83. }
  84. } else
  85. {
  86. // skip everything else silently
  87. }
  88. }
  89. }
  90. // ------------------------------------------------------------------------------------------------
  91. // Reads the structure of the file
  92. void ColladaParser::ReadStructure()
  93. {
  94. while( mReader->read())
  95. {
  96. // beginning of elements
  97. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  98. {
  99. if( IsElement( "asset"))
  100. ReadAssetInfo();
  101. else if( IsElement( "library_images"))
  102. ReadImageLibrary();
  103. else if( IsElement( "library_materials"))
  104. ReadMaterialLibrary();
  105. else if( IsElement( "library_effects"))
  106. ReadEffectLibrary();
  107. else if( IsElement( "library_geometries"))
  108. ReadGeometryLibrary();
  109. else if( IsElement( "library_visual_scenes"))
  110. ReadSceneLibrary();
  111. else if( IsElement( "scene"))
  112. ReadScene();
  113. else
  114. SkipElement();
  115. }
  116. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  117. {
  118. break;
  119. }
  120. }
  121. }
  122. // ------------------------------------------------------------------------------------------------
  123. // Reads asset informations such as coordinate system informations and legal blah
  124. void ColladaParser::ReadAssetInfo()
  125. {
  126. while( mReader->read())
  127. {
  128. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  129. {
  130. if( IsElement( "unit"))
  131. {
  132. // read unit data from the element's attributes
  133. int attrIndex = GetAttribute( "meter");
  134. mUnitSize = mReader->getAttributeValueAsFloat( attrIndex);
  135. // consume the trailing stuff
  136. if( !mReader->isEmptyElement())
  137. SkipElement();
  138. }
  139. else if( IsElement( "up_axis"))
  140. {
  141. // read content, strip whitespace, compare
  142. const char* content = GetTextContent();
  143. if( strncmp( content, "X_UP", 4) == 0)
  144. mUpDirection = UP_X;
  145. else if( strncmp( content, "Y_UP", 4) == 0)
  146. mUpDirection = UP_Y;
  147. else
  148. mUpDirection = UP_Z;
  149. // check element end
  150. TestClosing( "up_axis");
  151. } else
  152. {
  153. SkipElement();
  154. }
  155. }
  156. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  157. {
  158. if( strcmp( mReader->getNodeName(), "asset") != 0)
  159. ThrowException( "Expected end of \"asset\" element.");
  160. break;
  161. }
  162. }
  163. }
  164. // ------------------------------------------------------------------------------------------------
  165. // Reads the image library contents
  166. void ColladaParser::ReadImageLibrary()
  167. {
  168. while( mReader->read())
  169. {
  170. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  171. {
  172. if( IsElement( "image"))
  173. {
  174. // read ID. Another entry which is "optional" by design but obligatory in reality
  175. int attrID = GetAttribute( "id");
  176. std::string id = mReader->getAttributeValue( attrID);
  177. // create an entry and store it in the library under its ID
  178. mImageLibrary[id] = Image();
  179. // read on from there
  180. ReadImage( mImageLibrary[id]);
  181. } else
  182. {
  183. // ignore the rest
  184. SkipElement();
  185. }
  186. }
  187. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  188. {
  189. if( strcmp( mReader->getNodeName(), "library_images") != 0)
  190. ThrowException( "Expected end of \"library_images\" element.");
  191. break;
  192. }
  193. }
  194. }
  195. // ------------------------------------------------------------------------------------------------
  196. // Reads an image entry into the given image
  197. void ColladaParser::ReadImage( Collada::Image& pImage)
  198. {
  199. while( mReader->read())
  200. {
  201. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  202. {
  203. if( IsElement( "init_from"))
  204. {
  205. // element content is filename - hopefully
  206. const char* content = GetTextContent();
  207. pImage.mFileName = content;
  208. TestClosing( "init_from");
  209. } else
  210. {
  211. // ignore the rest
  212. SkipElement();
  213. }
  214. }
  215. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  216. {
  217. if( strcmp( mReader->getNodeName(), "image") != 0)
  218. ThrowException( "Expected end of \"image\" element.");
  219. break;
  220. }
  221. }
  222. }
  223. // ------------------------------------------------------------------------------------------------
  224. // Reads the material library
  225. void ColladaParser::ReadMaterialLibrary()
  226. {
  227. while( mReader->read())
  228. {
  229. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  230. {
  231. if( IsElement( "material"))
  232. {
  233. // read ID. By now you propably know my opinion about this "specification"
  234. int attrID = GetAttribute( "id");
  235. std::string id = mReader->getAttributeValue( attrID);
  236. // create an entry and store it in the library under its ID
  237. mMaterialLibrary[id] = Material();
  238. // read on from there
  239. ReadMaterial( mMaterialLibrary[id]);
  240. } else
  241. {
  242. // ignore the rest
  243. SkipElement();
  244. }
  245. }
  246. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  247. {
  248. if( strcmp( mReader->getNodeName(), "library_materials") != 0)
  249. ThrowException( "Expected end of \"library_materials\" element.");
  250. break;
  251. }
  252. }
  253. }
  254. // ------------------------------------------------------------------------------------------------
  255. // Reads a material entry into the given material
  256. void ColladaParser::ReadMaterial( Collada::Material& pMaterial)
  257. {
  258. while( mReader->read())
  259. {
  260. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  261. {
  262. if( IsElement( "instance_effect"))
  263. {
  264. // referred effect by URL
  265. int attrUrl = GetAttribute( "url");
  266. const char* url = mReader->getAttributeValue( attrUrl);
  267. if( url[0] != '#')
  268. ThrowException( "Unknown reference format");
  269. pMaterial.mEffect = url+1;
  270. SkipElement();
  271. } else
  272. {
  273. // ignore the rest
  274. SkipElement();
  275. }
  276. }
  277. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  278. {
  279. if( strcmp( mReader->getNodeName(), "material") != 0)
  280. ThrowException( "Expected end of \"image\" element.");
  281. break;
  282. }
  283. }
  284. }
  285. // ------------------------------------------------------------------------------------------------
  286. // Reads the effect library
  287. void ColladaParser::ReadEffectLibrary()
  288. {
  289. while( mReader->read())
  290. {
  291. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  292. {
  293. if( IsElement( "effect"))
  294. {
  295. // read ID. Do I have to repeat my ranting about "optional" attributes?
  296. int attrID = GetAttribute( "id");
  297. std::string id = mReader->getAttributeValue( attrID);
  298. // create an entry and store it in the library under its ID
  299. mEffectLibrary[id] = Effect();
  300. // read on from there
  301. ReadEffect( mEffectLibrary[id]);
  302. } else
  303. {
  304. // ignore the rest
  305. SkipElement();
  306. }
  307. }
  308. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  309. {
  310. if( strcmp( mReader->getNodeName(), "library_effects") != 0)
  311. ThrowException( "Expected end of \"library_effects\" element.");
  312. break;
  313. }
  314. }
  315. }
  316. // ------------------------------------------------------------------------------------------------
  317. // Reads an effect entry into the given effect
  318. void ColladaParser::ReadEffect( Collada::Effect& pEffect)
  319. {
  320. // for the moment we don't support any other type of effect.
  321. // TODO: (thom) Rewrite this so that it ignores the whole effect instead of bailing out
  322. TestOpening( "profile_COMMON");
  323. while( mReader->read())
  324. {
  325. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  326. {
  327. if( IsElement( "newparam"))
  328. {
  329. // save ID
  330. int attrSID = GetAttribute( "sid");
  331. std::string sid = mReader->getAttributeValue( attrSID);
  332. pEffect.mParams[sid] = EffectParam();
  333. ReadEffectParam( pEffect.mParams[sid]);
  334. }
  335. else if( IsElement( "technique"))
  336. {
  337. // just syntactic sugar
  338. }
  339. else if( IsElement( "phong"))
  340. pEffect.mShadeType = Shade_Phong;
  341. else if( IsElement( "constant"))
  342. pEffect.mShadeType = Shade_Constant;
  343. else if( IsElement( "lambert"))
  344. pEffect.mShadeType = Shade_Lambert;
  345. else if( IsElement( "blinn"))
  346. pEffect.mShadeType = Shade_Blinn;
  347. else if( IsElement( "emission"))
  348. ReadEffectColor( pEffect.mEmissive, pEffect.mTexEmissive);
  349. else if( IsElement( "ambient"))
  350. ReadEffectColor( pEffect.mAmbient, pEffect.mTexAmbient);
  351. else if( IsElement( "diffuse"))
  352. ReadEffectColor( pEffect.mDiffuse, pEffect.mTexDiffuse);
  353. else if( IsElement( "specular"))
  354. ReadEffectColor( pEffect.mSpecular, pEffect.mTexSpecular);
  355. else if( IsElement( "reflective")){
  356. std::string buf;
  357. ReadEffectColor( pEffect.mReflective, buf);
  358. }
  359. else if( IsElement( "transparent")){
  360. std::string buf;
  361. ReadEffectColor( pEffect.mRefractive,buf);
  362. }
  363. else if( IsElement( "shininess"))
  364. ReadEffectFloat( pEffect.mShininess);
  365. else if( IsElement( "reflectivity"))
  366. ReadEffectFloat( pEffect.mReflectivity);
  367. else if( IsElement( "transparency"))
  368. ReadEffectFloat( pEffect.mRefractivity);
  369. else if( IsElement( "index_of_refraction"))
  370. ReadEffectFloat( pEffect.mRefractIndex);
  371. else
  372. {
  373. // ignore the rest
  374. SkipElement();
  375. }
  376. }
  377. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  378. {
  379. if( strcmp( mReader->getNodeName(), "effect") == 0)
  380. break;
  381. }
  382. }
  383. }
  384. // ------------------------------------------------------------------------------------------------
  385. // Reads an effect entry containing a color or a texture defining that color
  386. void ColladaParser::ReadEffectColor( aiColor4D& pColor, std::string& pSampler)
  387. {
  388. while( mReader->read())
  389. {
  390. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  391. {
  392. if( IsElement( "color"))
  393. {
  394. // text content contains 4 floats
  395. const char* content = GetTextContent();
  396. float fBuf;
  397. content = fast_atof_move( content, fBuf);
  398. pColor.r = fBuf;
  399. SkipSpacesAndLineEnd( &content);
  400. content = fast_atof_move( content, fBuf);
  401. pColor.g = fBuf;
  402. SkipSpacesAndLineEnd( &content);
  403. content = fast_atof_move( content, fBuf);
  404. pColor.b = fBuf;
  405. SkipSpacesAndLineEnd( &content);
  406. content = fast_atof_move( content, fBuf);
  407. pColor.a = fBuf;
  408. SkipSpacesAndLineEnd( &content);
  409. TestClosing( "color");
  410. }
  411. else if( IsElement( "texture"))
  412. {
  413. int attrTex = GetAttribute( "texture");
  414. pSampler = mReader->getAttributeValue( attrTex);
  415. SkipElement();
  416. } else
  417. {
  418. // ignore the rest
  419. SkipElement();
  420. }
  421. }
  422. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  423. {
  424. break;
  425. }
  426. }
  427. }
  428. // ------------------------------------------------------------------------------------------------
  429. // Reads an effect entry containing a float
  430. void ColladaParser::ReadEffectFloat( float& pFloat)
  431. {
  432. while( mReader->read())
  433. {
  434. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  435. {
  436. if( IsElement( "float"))
  437. {
  438. // text content contains a single floats
  439. const char* content = GetTextContent();
  440. content = fast_atof_move( content, pFloat);
  441. SkipSpacesAndLineEnd( &content);
  442. TestClosing( "float");
  443. } else
  444. {
  445. // ignore the rest
  446. SkipElement();
  447. }
  448. }
  449. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  450. {
  451. break;
  452. }
  453. }
  454. }
  455. // ------------------------------------------------------------------------------------------------
  456. // Reads an effect parameter specification of any kind
  457. void ColladaParser::ReadEffectParam( Collada::EffectParam& pParam)
  458. {
  459. while( mReader->read())
  460. {
  461. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  462. {
  463. if( IsElement( "surface"))
  464. {
  465. // image ID given inside <init_from> tags
  466. TestOpening( "init_from");
  467. const char* content = GetTextContent();
  468. pParam.mType = Param_Surface;
  469. pParam.mReference = content;
  470. TestClosing( "init_from");
  471. // don't care for remaining stuff
  472. SkipElement( "surface");
  473. }
  474. else if( IsElement( "sampler2D"))
  475. {
  476. // surface ID is given inside <source> tags
  477. TestOpening( "source");
  478. const char* content = GetTextContent();
  479. pParam.mType = Param_Sampler;
  480. pParam.mReference = content;
  481. TestClosing( "source");
  482. // don't care for remaining stuff
  483. SkipElement( "sampler2D");
  484. } else
  485. {
  486. // ignore unknown element
  487. SkipElement();
  488. }
  489. }
  490. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  491. {
  492. break;
  493. }
  494. }
  495. }
  496. // ------------------------------------------------------------------------------------------------
  497. // Reads the geometry library contents
  498. void ColladaParser::ReadGeometryLibrary()
  499. {
  500. while( mReader->read())
  501. {
  502. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  503. {
  504. if( IsElement( "geometry"))
  505. {
  506. // read ID. Another entry which is "optional" by design but obligatory in reality
  507. int indexID = GetAttribute( "id");
  508. std::string id = mReader->getAttributeValue( indexID);
  509. // TODO: (thom) support SIDs
  510. assert( TestAttribute( "sid") == -1);
  511. // create a mesh and store it in the library under its ID
  512. Mesh* mesh = new Mesh;
  513. mMeshLibrary[id] = mesh;
  514. // read on from there
  515. ReadGeometry( mesh);
  516. } else
  517. {
  518. // ignore the rest
  519. SkipElement();
  520. }
  521. }
  522. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  523. {
  524. if( strcmp( mReader->getNodeName(), "library_geometries") != 0)
  525. ThrowException( "Expected end of \"library_geometries\" element.");
  526. break;
  527. }
  528. }
  529. }
  530. // ------------------------------------------------------------------------------------------------
  531. // Reads a geometry from the geometry library.
  532. void ColladaParser::ReadGeometry( Collada::Mesh* pMesh)
  533. {
  534. while( mReader->read())
  535. {
  536. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  537. {
  538. if( IsElement( "mesh"))
  539. {
  540. // read on from there
  541. ReadMesh( pMesh);
  542. } else
  543. {
  544. // ignore the rest
  545. SkipElement();
  546. }
  547. }
  548. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  549. {
  550. if( strcmp( mReader->getNodeName(), "geometry") != 0)
  551. ThrowException( "Expected end of \"geometry\" element.");
  552. break;
  553. }
  554. }
  555. }
  556. // ------------------------------------------------------------------------------------------------
  557. // Reads a mesh from the geometry library
  558. void ColladaParser::ReadMesh( Mesh* pMesh)
  559. {
  560. // I'm doing a dirty state parsing here because I don't want to open another submethod for it.
  561. // There's a <source> tag defining the name for the accessor inside, and possible a <float_array>
  562. // with it's own ID. This string contains the current source's ID if parsing is inside a <source> element.
  563. std::string presentSourceID;
  564. while( mReader->read())
  565. {
  566. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  567. {
  568. if( IsElement( "source"))
  569. {
  570. // beginning of a source element - store ID for the inner elements
  571. int attrID = GetAttribute( "id");
  572. presentSourceID = mReader->getAttributeValue( attrID);
  573. }
  574. else if( IsElement( "float_array"))
  575. {
  576. ReadFloatArray();
  577. }
  578. else if( IsElement( "technique_common"))
  579. {
  580. // I don't fucking care for your profiles bullshit
  581. }
  582. else if( IsElement( "accessor"))
  583. {
  584. ReadAccessor( presentSourceID);
  585. }
  586. else if( IsElement( "vertices"))
  587. {
  588. // read per-vertex mesh data
  589. ReadVertexData( pMesh);
  590. }
  591. else if( IsElement( "triangles") || IsElement( "lines") || IsElement( "linestrips")
  592. || IsElement( "polygons") || IsElement( "polylist") || IsElement( "trifans") || IsElement( "tristrips"))
  593. {
  594. // read per-index mesh data and faces setup
  595. ReadIndexData( pMesh);
  596. } else
  597. {
  598. // ignore the rest
  599. SkipElement();
  600. }
  601. }
  602. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  603. {
  604. if( strcmp( mReader->getNodeName(), "source") == 0)
  605. {
  606. // end of <source> - reset present source ID
  607. presentSourceID.clear();
  608. }
  609. else if( strcmp( mReader->getNodeName(), "technique_common") == 0)
  610. {
  611. // end of another meaningless element - read over it
  612. }
  613. else if( strcmp( mReader->getNodeName(), "mesh") == 0)
  614. {
  615. // end of <mesh> element - we're done here
  616. break;
  617. } else
  618. {
  619. // everything else should be punished
  620. ThrowException( "Expected end of \"mesh\" element.");
  621. }
  622. }
  623. }
  624. }
  625. // ------------------------------------------------------------------------------------------------
  626. // Reads a data array holding a number of floats, and stores it in the global library
  627. void ColladaParser::ReadFloatArray()
  628. {
  629. // read attributes
  630. int indexID = GetAttribute( "id");
  631. std::string id = mReader->getAttributeValue( indexID);
  632. int indexCount = GetAttribute( "count");
  633. unsigned int count = (unsigned int) mReader->getAttributeValueAsInt( indexCount);
  634. const char* content = GetTextContent();
  635. // read values and store inside an array in the data library
  636. mDataLibrary[id] = Data();
  637. Data& data = mDataLibrary[id];
  638. data.mValues.reserve( count);
  639. for( unsigned int a = 0; a < count; a++)
  640. {
  641. if( *content == 0)
  642. ThrowException( "Expected more values while reading float_array contents.");
  643. float value;
  644. // read a number
  645. content = fast_atof_move( content, value);
  646. data.mValues.push_back( value);
  647. // skip whitespace after it
  648. SkipSpacesAndLineEnd( &content);
  649. }
  650. // test for closing tag
  651. TestClosing( "float_array");
  652. }
  653. // ------------------------------------------------------------------------------------------------
  654. // Reads an accessor and stores it in the global library
  655. void ColladaParser::ReadAccessor( const std::string& pID)
  656. {
  657. // read accessor attributes
  658. int attrSource = GetAttribute( "source");
  659. const char* source = mReader->getAttributeValue( attrSource);
  660. if( source[0] != '#')
  661. ThrowException( boost::str( boost::format( "Unknown reference format in url \"%s\".") % source));
  662. int attrCount = GetAttribute( "count");
  663. unsigned int count = (unsigned int) mReader->getAttributeValueAsInt( attrCount);
  664. int attrOffset = TestAttribute( "offset");
  665. unsigned int offset = 0;
  666. if( attrOffset > -1)
  667. offset = (unsigned int) mReader->getAttributeValueAsInt( attrOffset);
  668. int attrStride = TestAttribute( "stride");
  669. unsigned int stride = 1;
  670. if( attrStride > -1)
  671. stride = (unsigned int) mReader->getAttributeValueAsInt( attrStride);
  672. // store in the library under the given ID
  673. mAccessorLibrary[pID] = Accessor();
  674. Accessor& acc = mAccessorLibrary[pID];
  675. acc.mCount = count;
  676. acc.mOffset = offset;
  677. acc.mStride = stride;
  678. acc.mSource = source+1; // ignore the leading '#'
  679. // and read the components
  680. while( mReader->read())
  681. {
  682. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  683. {
  684. if( IsElement( "param"))
  685. {
  686. // read data param
  687. int attrName = TestAttribute( "name");
  688. std::string name;
  689. if( attrName > -1)
  690. {
  691. name = mReader->getAttributeValue( attrName);
  692. // analyse for common type components and store it's sub-offset in the corresponding field
  693. if( name == "X") acc.mSubOffset[0] = acc.mParams.size();
  694. else if( name == "Y") acc.mSubOffset[1] = acc.mParams.size();
  695. else if( name == "Z") acc.mSubOffset[2] = acc.mParams.size();
  696. else if( name == "R") acc.mSubOffset[0] = acc.mParams.size();
  697. else if( name == "G") acc.mSubOffset[1] = acc.mParams.size();
  698. else if( name == "B") acc.mSubOffset[2] = acc.mParams.size();
  699. else if( name == "A") acc.mSubOffset[3] = acc.mParams.size();
  700. else if( name == "S") acc.mSubOffset[0] = acc.mParams.size();
  701. else if( name == "T") acc.mSubOffset[1] = acc.mParams.size();
  702. else
  703. DefaultLogger::get()->warn( boost::str( boost::format( "Unknown accessor parameter \"%s\". Ignoring data channel.") % name));
  704. }
  705. acc.mParams.push_back( name);
  706. // skip remaining stuff of this element, if any
  707. SkipElement();
  708. } else
  709. {
  710. ThrowException( "Unexpected sub element in tag \"accessor\".");
  711. }
  712. }
  713. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  714. {
  715. if( strcmp( mReader->getNodeName(), "accessor") != 0)
  716. ThrowException( "Expected end of \"accessor\" element.");
  717. break;
  718. }
  719. }
  720. }
  721. // ------------------------------------------------------------------------------------------------
  722. // Reads input declarations of per-vertex mesh data into the given mesh
  723. void ColladaParser::ReadVertexData( Mesh* pMesh)
  724. {
  725. // extract the ID of the <vertices> element. Not that we care, but to catch strange referencing schemes we should warn about
  726. int attrID= GetAttribute( "id");
  727. pMesh->mVertexID = mReader->getAttributeValue( attrID);
  728. // a number of <input> elements
  729. while( mReader->read())
  730. {
  731. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  732. {
  733. if( IsElement( "input"))
  734. {
  735. ReadInputChannel( pMesh->mPerVertexData);
  736. } else
  737. {
  738. ThrowException( "Unexpected sub element in tag \"vertices\".");
  739. }
  740. }
  741. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  742. {
  743. if( strcmp( mReader->getNodeName(), "vertices") != 0)
  744. ThrowException( "Expected end of \"vertices\" element.");
  745. break;
  746. }
  747. }
  748. }
  749. // ------------------------------------------------------------------------------------------------
  750. // Reads input declarations of per-index mesh data into the given mesh
  751. void ColladaParser::ReadIndexData( Mesh* pMesh)
  752. {
  753. std::vector<size_t> vcount;
  754. std::vector<InputChannel> perIndexData;
  755. // read primitive count from the attribute
  756. int attrCount = GetAttribute( "count");
  757. size_t numPrimitives = (size_t) mReader->getAttributeValueAsInt( attrCount);
  758. // material subgroup
  759. int attrMaterial = TestAttribute( "material");
  760. SubMesh subgroup;
  761. if( attrMaterial > -1)
  762. subgroup.mMaterial = mReader->getAttributeValue( attrMaterial);
  763. subgroup.mNumFaces = numPrimitives;
  764. pMesh->mSubMeshes.push_back( subgroup);
  765. // distinguish between polys and triangles
  766. std::string elementName = mReader->getNodeName();
  767. PrimitiveType primType = Prim_Invalid;
  768. if( IsElement( "lines"))
  769. primType = Prim_Lines;
  770. else if( IsElement( "linestrips"))
  771. primType = Prim_LineStrip;
  772. else if( IsElement( "polygons"))
  773. primType = Prim_Polygon;
  774. else if( IsElement( "polylist"))
  775. primType = Prim_Polylist;
  776. else if( IsElement( "triangles"))
  777. primType = Prim_Triangles;
  778. else if( IsElement( "trifans"))
  779. primType = Prim_TriFans;
  780. else if( IsElement( "tristrips"))
  781. primType = Prim_TriStrips;
  782. assert( primType != Prim_Invalid);
  783. // also a number of <input> elements, but in addition a <p> primitive collection and propably index counts for all primitives
  784. while( mReader->read())
  785. {
  786. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  787. {
  788. if( IsElement( "input"))
  789. {
  790. ReadInputChannel( perIndexData);
  791. }
  792. else if( IsElement( "vcount"))
  793. {
  794. if( !mReader->isEmptyElement())
  795. {
  796. // case <polylist> - specifies the number of indices for each polygon
  797. const char* content = GetTextContent();
  798. vcount.reserve( numPrimitives);
  799. for( unsigned int a = 0; a < numPrimitives; a++)
  800. {
  801. if( *content == 0)
  802. ThrowException( "Expected more values while reading vcount contents.");
  803. // read a number
  804. vcount.push_back( (size_t) strtol10( content, &content));
  805. // skip whitespace after it
  806. SkipSpacesAndLineEnd( &content);
  807. }
  808. TestClosing( "vcount");
  809. }
  810. }
  811. else if( IsElement( "p"))
  812. {
  813. if( !mReader->isEmptyElement())
  814. {
  815. // now here the actual fun starts - these are the indices to construct the mesh data from
  816. ReadPrimitives( pMesh, perIndexData, numPrimitives, vcount, primType);
  817. }
  818. } else
  819. {
  820. ThrowException( "Unexpected sub element in tag \"vertices\".");
  821. }
  822. }
  823. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  824. {
  825. if( mReader->getNodeName() != elementName)
  826. ThrowException( boost::str( boost::format( "Expected end of \"%s\" element.") % elementName));
  827. break;
  828. }
  829. }
  830. }
  831. // ------------------------------------------------------------------------------------------------
  832. // Reads a single input channel element and stores it in the given array, if valid
  833. void ColladaParser::ReadInputChannel( std::vector<InputChannel>& poChannels)
  834. {
  835. InputChannel channel;
  836. // read semantic
  837. int attrSemantic = GetAttribute( "semantic");
  838. std::string semantic = mReader->getAttributeValue( attrSemantic);
  839. channel.mType = GetTypeForSemantic( semantic);
  840. // read source
  841. int attrSource = GetAttribute( "source");
  842. const char* source = mReader->getAttributeValue( attrSource);
  843. if( source[0] != '#')
  844. ThrowException( boost::str( boost::format( "Unknown reference format in url \"%s\".") % source));
  845. channel.mAccessor = source+1; // skipping the leading #, hopefully the remaining text is the accessor ID only
  846. // read index offset, if per-index <input>
  847. int attrOffset = TestAttribute( "offset");
  848. if( attrOffset > -1)
  849. channel.mOffset = mReader->getAttributeValueAsInt( attrOffset);
  850. // store, if valid type
  851. if( channel.mType != IT_Invalid)
  852. poChannels.push_back( channel);
  853. // skip remaining stuff of this element, if any
  854. SkipElement();
  855. }
  856. // ------------------------------------------------------------------------------------------------
  857. // Reads a <p> primitive index list and assembles the mesh data into the given mesh
  858. void ColladaParser::ReadPrimitives( Mesh* pMesh, std::vector<InputChannel>& pPerIndexChannels,
  859. size_t pNumPrimitives, const std::vector<size_t>& pVCount, PrimitiveType pPrimType)
  860. {
  861. // determine number of indices coming per vertex
  862. // find the offset index for all per-vertex channels
  863. size_t numOffsets = 1;
  864. size_t perVertexOffset = -1; // invalid value
  865. BOOST_FOREACH( const InputChannel& channel, pPerIndexChannels)
  866. {
  867. numOffsets = std::max( numOffsets, channel.mOffset+1);
  868. if( channel.mType == IT_Vertex)
  869. perVertexOffset = channel.mOffset;
  870. }
  871. // determine the expected number of indices
  872. size_t expectedPointCount = 0;
  873. switch( pPrimType)
  874. {
  875. case Prim_Polylist:
  876. {
  877. BOOST_FOREACH( size_t i, pVCount)
  878. expectedPointCount += i;
  879. break;
  880. }
  881. case Prim_Lines:
  882. expectedPointCount = 2 * pNumPrimitives;
  883. break;
  884. case Prim_Triangles:
  885. expectedPointCount = 3 * pNumPrimitives;
  886. break;
  887. default:
  888. // other primitive types don't state the index count upfront... we need to guess
  889. break;
  890. }
  891. // and read all indices into a temporary array
  892. std::vector<size_t> indices;
  893. if( expectedPointCount > 0)
  894. indices.reserve( expectedPointCount * numOffsets);
  895. const char* content = GetTextContent();
  896. while( *content != 0)
  897. {
  898. // read a value
  899. unsigned int value = strtol10( content, &content);
  900. indices.push_back( size_t( value));
  901. // skip whitespace after it
  902. SkipSpacesAndLineEnd( &content);
  903. }
  904. // complain if the index count doesn't fit
  905. if( expectedPointCount > 0 && indices.size() != expectedPointCount * numOffsets)
  906. ThrowException( "Expected different index count in <p> element.");
  907. else if( expectedPointCount == 0 && (indices.size() % numOffsets) != 0)
  908. ThrowException( "Expected different index count in <p> element.");
  909. // find the data for all sources
  910. BOOST_FOREACH( InputChannel& input, pMesh->mPerVertexData)
  911. {
  912. if( input.mResolved)
  913. continue;
  914. // find accessor
  915. input.mResolved = &ResolveLibraryReference( mAccessorLibrary, input.mAccessor);
  916. // resolve accessor's data pointer as well, if neccessary
  917. const Accessor* acc = input.mResolved;
  918. if( !acc->mData)
  919. acc->mData = &ResolveLibraryReference( mDataLibrary, acc->mSource);
  920. }
  921. // and the same for the per-index channels
  922. BOOST_FOREACH( InputChannel& input, pPerIndexChannels)
  923. {
  924. if( input.mResolved)
  925. continue;
  926. // ignore vertex pointer, it doesn't refer to an accessor
  927. if( input.mType == IT_Vertex)
  928. {
  929. // warn if the vertex channel does not refer to the <vertices> element in the same mesh
  930. if( input.mAccessor != pMesh->mVertexID)
  931. ThrowException( "Unsupported vertex referencing scheme. I fucking hate Collada.");
  932. continue;
  933. }
  934. // find accessor
  935. input.mResolved = &ResolveLibraryReference( mAccessorLibrary, input.mAccessor);
  936. // resolve accessor's data pointer as well, if neccessary
  937. const Accessor* acc = input.mResolved;
  938. if( !acc->mData)
  939. acc->mData = &ResolveLibraryReference( mDataLibrary, acc->mSource);
  940. }
  941. // now assemble vertex data according to those indices
  942. std::vector<size_t>::const_iterator idx = indices.begin();
  943. // For continued primitives, the given count does not come all in one <p>, but only one primitive per <p>
  944. size_t numPrimitives = pNumPrimitives;
  945. if( pPrimType == Prim_TriFans || pPrimType == Prim_Polygon)
  946. numPrimitives = 1;
  947. for( size_t a = 0; a < numPrimitives; a++)
  948. {
  949. // determine number of points for this primitive
  950. size_t numPoints = 0;
  951. switch( pPrimType)
  952. {
  953. case Prim_Lines: numPoints = 2; break;
  954. case Prim_Triangles: numPoints = 3; break;
  955. case Prim_Polylist: numPoints = pVCount[a]; break;
  956. case Prim_TriFans:
  957. case Prim_Polygon: numPoints = indices.size() / numOffsets; break;
  958. default:
  959. // LineStrip and TriStrip not supported due to expected index unmangling
  960. ThrowException( "Unsupported primitive type.");
  961. break;
  962. }
  963. // store the face size to later reconstruct the face from
  964. pMesh->mFaceSize.push_back( numPoints);
  965. // gather that number of vertices
  966. for( size_t b = 0; b < numPoints; b++)
  967. {
  968. // read all indices for this vertex. Yes, in a hacky static array
  969. assert( numOffsets < 20);
  970. static size_t vindex[20];
  971. for( size_t offsets = 0; offsets < numOffsets; ++offsets)
  972. vindex[offsets] = *idx++;
  973. // extract per-vertex channels using the global per-vertex offset
  974. BOOST_FOREACH( const InputChannel& input, pMesh->mPerVertexData)
  975. ExtractDataObjectFromChannel( input, vindex[perVertexOffset], pMesh);
  976. // and extract per-index channels using there specified offset
  977. BOOST_FOREACH( const InputChannel& input, pPerIndexChannels)
  978. ExtractDataObjectFromChannel( input, vindex[input.mOffset], pMesh);
  979. }
  980. }
  981. // if I ever get my hands on that guy who invented this steaming pile of indirection...
  982. TestClosing( "p");
  983. }
  984. // ------------------------------------------------------------------------------------------------
  985. // Extracts a single object from an input channel and stores it in the appropriate mesh data array
  986. void ColladaParser::ExtractDataObjectFromChannel( const InputChannel& pInput, size_t pLocalIndex, Mesh* pMesh)
  987. {
  988. // ignore vertex referrer - we handle them that separate
  989. if( pInput.mType == IT_Vertex)
  990. return;
  991. const Accessor& acc = *pInput.mResolved;
  992. if( pLocalIndex >= acc.mCount)
  993. ThrowException( boost::str( boost::format( "Invalid data index (%d/%d) in primitive specification") % pLocalIndex % acc.mCount));
  994. // get a pointer to the start of the data object referred to by the accessor and the local index
  995. const float* dataObject = &(acc.mData->mValues[0]) + acc.mOffset + pLocalIndex* acc.mStride;
  996. // assemble according to the accessors component sub-offset list. We don't care, yet, what kind of object exactly we're extracting here
  997. float obj[4];
  998. for( size_t c = 0; c < 4; ++c)
  999. obj[c] = dataObject[acc.mSubOffset[c]];
  1000. // now we reinterpret it according to the type we're reading here
  1001. switch( pInput.mType)
  1002. {
  1003. case IT_Position: // ignore all position streams except 0 - there can be only one position
  1004. if( pInput.mIndex == 0)
  1005. pMesh->mPositions.push_back( aiVector3D( obj[0], obj[1], obj[2]));
  1006. break;
  1007. case IT_Normal: // ignore all normal streams except 0 - there can be only one normal
  1008. if( pInput.mIndex == 0)
  1009. pMesh->mNormals.push_back( aiVector3D( obj[0], obj[1], obj[2]));
  1010. break;
  1011. case IT_Texcoord: // up to 4 texture coord sets are fine, ignore the others
  1012. if( pInput.mIndex < AI_MAX_NUMBER_OF_TEXTURECOORDS)
  1013. pMesh->mTexCoords[pInput.mIndex].push_back( aiVector2D( obj[0], obj[1]));
  1014. break;
  1015. case IT_Color: // up to 4 color sets are fine, ignore the others
  1016. if( pInput.mIndex < AI_MAX_NUMBER_OF_COLOR_SETS)
  1017. pMesh->mColors[pInput.mIndex].push_back( aiColor4D( obj[0], obj[1], obj[2], obj[3]));
  1018. break;
  1019. }
  1020. }
  1021. // ------------------------------------------------------------------------------------------------
  1022. // Reads the library of node hierarchies and scene parts
  1023. void ColladaParser::ReadSceneLibrary()
  1024. {
  1025. while( mReader->read())
  1026. {
  1027. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1028. {
  1029. // a visual scene - generate root node under its ID and let ReadNode() do the recursive work
  1030. if( IsElement( "visual_scene"))
  1031. {
  1032. // read ID. Is optional according to the spec, but how on earth should a scene_instance refer to it then?
  1033. int indexID = GetAttribute( "id");
  1034. const char* attrID = mReader->getAttributeValue( indexID);
  1035. // read name if given.
  1036. int indexName = TestAttribute( "name");
  1037. const char* attrName = "unnamed";
  1038. if( indexName > -1)
  1039. attrName = mReader->getAttributeValue( indexName);
  1040. // TODO: (thom) support SIDs
  1041. assert( TestAttribute( "sid") == -1);
  1042. // create a node and store it in the library under its ID
  1043. Node* node = new Node;
  1044. node->mID = attrID;
  1045. node->mName = attrName;
  1046. mNodeLibrary[node->mID] = node;
  1047. ReadSceneNode( node);
  1048. } else
  1049. {
  1050. // ignore the rest
  1051. SkipElement();
  1052. }
  1053. }
  1054. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1055. {
  1056. if( strcmp( mReader->getNodeName(), "library_visual_scenes") != 0)
  1057. ThrowException( "Expected end of \"library_visual_scenes\" element.");
  1058. break;
  1059. }
  1060. }
  1061. }
  1062. // ------------------------------------------------------------------------------------------------
  1063. // Reads a scene node's contents including children and stores it in the given node
  1064. void ColladaParser::ReadSceneNode( Node* pNode)
  1065. {
  1066. // quit immediately on <bla/> elements
  1067. if( mReader->isEmptyElement())
  1068. return;
  1069. while( mReader->read())
  1070. {
  1071. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1072. {
  1073. if( IsElement( "lookat"))
  1074. ReadNodeTransformation( pNode, TF_LOOKAT);
  1075. else if( IsElement( "matrix"))
  1076. ReadNodeTransformation( pNode, TF_MATRIX);
  1077. else if( IsElement( "rotate"))
  1078. ReadNodeTransformation( pNode, TF_ROTATE);
  1079. else if( IsElement( "scale"))
  1080. ReadNodeTransformation( pNode, TF_SCALE);
  1081. else if( IsElement( "skew"))
  1082. ReadNodeTransformation( pNode, TF_SKEW);
  1083. else if( IsElement( "translate"))
  1084. ReadNodeTransformation( pNode, TF_TRANSLATE);
  1085. else if( IsElement( "node"))
  1086. {
  1087. Node* child = new Node;
  1088. int attrID = TestAttribute( "id");
  1089. if( attrID > -1)
  1090. child->mID = mReader->getAttributeValue( attrID);
  1091. int attrName = TestAttribute( "name");
  1092. if( attrName > -1)
  1093. child->mName = mReader->getAttributeValue( attrName);
  1094. // TODO: (thom) support SIDs
  1095. // assert( TestAttribute( "sid") == -1);
  1096. pNode->mChildren.push_back( child);
  1097. child->mParent = pNode;
  1098. // read on recursively from there
  1099. ReadSceneNode( child);
  1100. } else if( IsElement( "instance_node"))
  1101. {
  1102. // test for it, in case we need to implement it
  1103. assert( false);
  1104. SkipElement();
  1105. } else if( IsElement( "instance_geometry"))
  1106. {
  1107. // Reference to a mesh, we possible material associations
  1108. ReadNodeGeometry( pNode);
  1109. } else
  1110. {
  1111. // skip everything else for the moment
  1112. SkipElement();
  1113. }
  1114. }
  1115. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1116. {
  1117. break;
  1118. }
  1119. }
  1120. }
  1121. // ------------------------------------------------------------------------------------------------
  1122. // Reads a node transformation entry of the given type and adds it to the given node's transformation list.
  1123. void ColladaParser::ReadNodeTransformation( Node* pNode, TransformType pType)
  1124. {
  1125. std::string tagName = mReader->getNodeName();
  1126. // how many parameters to read per transformation type
  1127. static const unsigned int sNumParameters[] = { 9, 4, 3, 3, 7, 16 };
  1128. const char* content = GetTextContent();
  1129. // read as many parameters and store in the transformation
  1130. Transform tf;
  1131. tf.mType = pType;
  1132. for( unsigned int a = 0; a < sNumParameters[pType]; a++)
  1133. {
  1134. // read a number
  1135. content = fast_atof_move( content, tf.f[a]);
  1136. // skip whitespace after it
  1137. SkipSpacesAndLineEnd( &content);
  1138. }
  1139. // place the transformation at the queue of the node
  1140. pNode->mTransforms.push_back( tf);
  1141. // and consum the closing tag
  1142. TestClosing( tagName.c_str());
  1143. }
  1144. // ------------------------------------------------------------------------------------------------
  1145. // Reads a mesh reference in a node and adds it to the node's mesh list
  1146. void ColladaParser::ReadNodeGeometry( Node* pNode)
  1147. {
  1148. // referred mesh is given as an attribute of the <instance_geometry> element
  1149. int attrUrl = GetAttribute( "url");
  1150. const char* url = mReader->getAttributeValue( attrUrl);
  1151. if( url[0] != '#')
  1152. ThrowException( "Unknown reference format");
  1153. Collada::MeshInstance instance;
  1154. instance.mMesh = url+1; // skipping the leading #
  1155. if( !mReader->isEmptyElement())
  1156. {
  1157. // read material associations. Ignore additional elements inbetween
  1158. while( mReader->read())
  1159. {
  1160. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1161. {
  1162. if( IsElement( "instance_material"))
  1163. {
  1164. // read ID of the geometry subgroup and the target material
  1165. int attrGroup = GetAttribute( "symbol");
  1166. std::string group = mReader->getAttributeValue( attrGroup);
  1167. int attrMaterial = GetAttribute( "target");
  1168. const char* urlMat = mReader->getAttributeValue( attrMaterial);
  1169. if( urlMat[0] != '#')
  1170. ThrowException( "Unknown reference format");
  1171. std::string mat = urlMat+1;
  1172. // store the association
  1173. instance.mMaterials[group] = mat;
  1174. }
  1175. }
  1176. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1177. {
  1178. if( strcmp( mReader->getNodeName(), "instance_geometry") == 0)
  1179. break;
  1180. }
  1181. }
  1182. }
  1183. // store it
  1184. pNode->mMeshes.push_back( instance);
  1185. }
  1186. // ------------------------------------------------------------------------------------------------
  1187. // Reads the collada scene
  1188. void ColladaParser::ReadScene()
  1189. {
  1190. while( mReader->read())
  1191. {
  1192. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1193. {
  1194. if( IsElement( "instance_visual_scene"))
  1195. {
  1196. // should be the first and only occurence
  1197. if( mRootNode)
  1198. ThrowException( "Invalid scene containing multiple root nodes");
  1199. // read the url of the scene to instance. Should be of format "#some_name"
  1200. int urlIndex = GetAttribute( "url");
  1201. const char* url = mReader->getAttributeValue( urlIndex);
  1202. if( url[0] != '#')
  1203. ThrowException( "Unknown reference format");
  1204. // find the referred scene, skip the leading #
  1205. NodeLibrary::const_iterator sit = mNodeLibrary.find( url+1);
  1206. if( sit == mNodeLibrary.end())
  1207. ThrowException( boost::str( boost::format( "Unable to resolve visual_scene reference \"%s\".") % url));
  1208. mRootNode = sit->second;
  1209. } else
  1210. {
  1211. SkipElement();
  1212. }
  1213. }
  1214. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1215. {
  1216. break;
  1217. }
  1218. }
  1219. }
  1220. // ------------------------------------------------------------------------------------------------
  1221. // Aborts the file reading with an exception
  1222. void ColladaParser::ThrowException( const std::string& pError) const
  1223. {
  1224. throw new ImportErrorException( boost::str( boost::format( "%s - %s") % mFileName % pError));
  1225. }
  1226. // ------------------------------------------------------------------------------------------------
  1227. // Skips all data until the end node of the current element
  1228. void ColladaParser::SkipElement()
  1229. {
  1230. // nothing to skip if it's an <element />
  1231. if( mReader->isEmptyElement())
  1232. return;
  1233. // reroute
  1234. SkipElement( mReader->getNodeName());
  1235. }
  1236. // ------------------------------------------------------------------------------------------------
  1237. // Skips all data until the end node of the given element
  1238. void ColladaParser::SkipElement( const char* pElement)
  1239. {
  1240. // copy the current node's name because it'a pointer to the reader's internal buffer,
  1241. // which is going to change with the upcoming parsing
  1242. std::string element = pElement;
  1243. while( mReader->read())
  1244. {
  1245. if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1246. if( mReader->getNodeName() == element)
  1247. break;
  1248. }
  1249. }
  1250. // ------------------------------------------------------------------------------------------------
  1251. // Tests for an opening element of the given name, throws an exception if not found
  1252. void ColladaParser::TestOpening( const char* pName)
  1253. {
  1254. // read element start
  1255. if( !mReader->read())
  1256. ThrowException( boost::str( boost::format( "Unexpected end of file while beginning of \"%s\" element.") % pName));
  1257. // whitespace in front is ok, just read again if found
  1258. if( mReader->getNodeType() == irr::io::EXN_TEXT)
  1259. if( !mReader->read())
  1260. ThrowException( boost::str( boost::format( "Unexpected end of file while reading beginning of \"%s\" element.") % pName));
  1261. if( mReader->getNodeType() != irr::io::EXN_ELEMENT || strcmp( mReader->getNodeName(), pName) != 0)
  1262. ThrowException( boost::str( boost::format( "Expected start of \"%s\" element.") % pName));
  1263. }
  1264. // ------------------------------------------------------------------------------------------------
  1265. // Tests for the closing tag of the given element, throws an exception if not found
  1266. void ColladaParser::TestClosing( const char* pName)
  1267. {
  1268. // read closing tag
  1269. if( !mReader->read())
  1270. ThrowException( boost::str( boost::format( "Unexpected end of file while reading end of \"%s\" element.") % pName));
  1271. // whitespace in front is ok, just read again if found
  1272. if( mReader->getNodeType() == irr::io::EXN_TEXT)
  1273. if( !mReader->read())
  1274. ThrowException( boost::str( boost::format( "Unexpected end of file while reading end of \"%s\" element.") % pName));
  1275. if( mReader->getNodeType() != irr::io::EXN_ELEMENT_END || strcmp( mReader->getNodeName(), pName) != 0)
  1276. ThrowException( boost::str( boost::format( "Expected end of \"%s\" element.") % pName));
  1277. }
  1278. // ------------------------------------------------------------------------------------------------
  1279. // Returns the index of the named attribute or -1 if not found. Does not throw, therefore useful for optional attributes
  1280. int ColladaParser::GetAttribute( const char* pAttr) const
  1281. {
  1282. int index = TestAttribute( pAttr);
  1283. if( index != -1)
  1284. return index;
  1285. // attribute not found -> throw an exception
  1286. ThrowException( boost::str( boost::format( "Expected attribute \"%s\" at element \"%s\".") % pAttr % mReader->getNodeName()));
  1287. return -1;
  1288. }
  1289. // ------------------------------------------------------------------------------------------------
  1290. // Tests the present element for the presence of one attribute, returns its index or throws an exception if not found
  1291. int ColladaParser::TestAttribute( const char* pAttr) const
  1292. {
  1293. for( int a = 0; a < mReader->getAttributeCount(); a++)
  1294. if( strcmp( mReader->getAttributeName( a), pAttr) == 0)
  1295. return a;
  1296. return -1;
  1297. }
  1298. // ------------------------------------------------------------------------------------------------
  1299. // Reads the text contents of an element, throws an exception if not given. Skips leading whitespace.
  1300. const char* ColladaParser::GetTextContent()
  1301. {
  1302. // present node should be the beginning of an element
  1303. if( mReader->getNodeType() != irr::io::EXN_ELEMENT || mReader->isEmptyElement())
  1304. ThrowException( "Expected opening element");
  1305. // read contents of the element
  1306. if( !mReader->read())
  1307. ThrowException( "Unexpected end of file while reading asset up_axis element.");
  1308. if( mReader->getNodeType() != irr::io::EXN_TEXT)
  1309. ThrowException( "Invalid contents in element \"up_axis\".");
  1310. // skip leading whitespace
  1311. const char* text = mReader->getNodeData();
  1312. SkipSpacesAndLineEnd( &text);
  1313. return text;
  1314. }
  1315. // ------------------------------------------------------------------------------------------------
  1316. // Calculates the resulting transformation fromm all the given transform steps
  1317. aiMatrix4x4 ColladaParser::CalculateResultTransform( const std::vector<Transform>& pTransforms) const
  1318. {
  1319. aiMatrix4x4 res;
  1320. for( std::vector<Transform>::const_iterator it = pTransforms.begin(); it != pTransforms.end(); ++it)
  1321. {
  1322. const Transform& tf = *it;
  1323. switch( tf.mType)
  1324. {
  1325. case TF_LOOKAT:
  1326. // TODO: (thom)
  1327. assert( false);
  1328. break;
  1329. case TF_ROTATE:
  1330. {
  1331. aiMatrix4x4 rot;
  1332. float angle = tf.f[3] * float( AI_MATH_PI) / 180.0f;
  1333. aiVector3D axis( tf.f[0], tf.f[1], tf.f[2]);
  1334. aiMatrix4x4::Rotation( angle, axis, rot);
  1335. res *= rot;
  1336. break;
  1337. }
  1338. case TF_TRANSLATE:
  1339. {
  1340. aiMatrix4x4 trans;
  1341. aiMatrix4x4::Translation( aiVector3D( tf.f[0], tf.f[1], tf.f[2]), trans);
  1342. res *= trans;
  1343. break;
  1344. }
  1345. case TF_SCALE:
  1346. {
  1347. 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,
  1348. 0.0f, 0.0f, 0.0f, 1.0f);
  1349. res *= scale;
  1350. break;
  1351. }
  1352. case TF_SKEW:
  1353. // TODO: (thom)
  1354. assert( false);
  1355. break;
  1356. case TF_MATRIX:
  1357. {
  1358. 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],
  1359. tf.f[8], tf.f[9], tf.f[10], tf.f[11], tf.f[12], tf.f[13], tf.f[14], tf.f[15]);
  1360. res *= mat;
  1361. break;
  1362. }
  1363. default:
  1364. assert( false);
  1365. break;
  1366. }
  1367. }
  1368. return res;
  1369. }
  1370. // ------------------------------------------------------------------------------------------------
  1371. // Determines the input data type for the given semantic string
  1372. Collada::InputType ColladaParser::GetTypeForSemantic( const std::string& pSemantic)
  1373. {
  1374. if( pSemantic == "POSITION")
  1375. return IT_Position;
  1376. else if( pSemantic == "TEXCOORD")
  1377. return IT_Texcoord;
  1378. else if( pSemantic == "NORMAL")
  1379. return IT_Normal;
  1380. else if( pSemantic == "COLOR")
  1381. return IT_Color;
  1382. else if( pSemantic == "VERTEX")
  1383. return IT_Vertex;
  1384. DefaultLogger::get()->warn( boost::str( boost::format( "Unknown vertex input type \"%s\". Ignoring.") % pSemantic));
  1385. return IT_Invalid;
  1386. }
  1387. #endif // !! ASSIMP_BUILD_NO_DAE_IMPORTER