ColladaParser.cpp 48 KB

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