ColladaParser.cpp 94 KB

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