ColladaParser.cpp 86 KB

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