ColladaParser.cpp 123 KB

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