ColladaLoader.cpp 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2012, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file Implementation of the Collada loader */
  35. #include "AssimpPCH.h"
  36. #ifndef ASSIMP_BUILD_NO_COLLADA_IMPORTER
  37. #include "../include/assimp/anim.h"
  38. #include "ColladaLoader.h"
  39. #include "ColladaParser.h"
  40. #include "fast_atof.h"
  41. #include "ParsingUtils.h"
  42. #include "SkeletonMeshBuilder.h"
  43. #include "time.h"
  44. using namespace Assimp;
  45. static const aiImporterDesc desc = {
  46. "Collada Importer",
  47. "",
  48. "",
  49. "http://collada.org",
  50. aiImporterFlags_SupportTextFlavour,
  51. 1,
  52. 3,
  53. 1,
  54. 5,
  55. "dae"
  56. };
  57. // ------------------------------------------------------------------------------------------------
  58. // Constructor to be privately used by Importer
  59. ColladaLoader::ColladaLoader()
  60. : noSkeletonMesh()
  61. {}
  62. // ------------------------------------------------------------------------------------------------
  63. // Destructor, private as well
  64. ColladaLoader::~ColladaLoader()
  65. {}
  66. // ------------------------------------------------------------------------------------------------
  67. // Returns whether the class can handle the format of the given file.
  68. bool ColladaLoader::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  69. {
  70. // check file extension
  71. std::string extension = GetExtension(pFile);
  72. if( extension == "dae")
  73. return true;
  74. // XML - too generic, we need to open the file and search for typical keywords
  75. if( extension == "xml" || !extension.length() || checkSig) {
  76. /* If CanRead() is called in order to check whether we
  77. * support a specific file extension in general pIOHandler
  78. * might be NULL and it's our duty to return true here.
  79. */
  80. if (!pIOHandler)return true;
  81. const char* tokens[] = {"collada"};
  82. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  83. }
  84. return false;
  85. }
  86. // ------------------------------------------------------------------------------------------------
  87. void ColladaLoader::SetupProperties(const Importer* pImp)
  88. {
  89. noSkeletonMesh = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_NO_SKELETON_MESHES,0) != 0;
  90. }
  91. // ------------------------------------------------------------------------------------------------
  92. // Get file extension list
  93. const aiImporterDesc* ColladaLoader::GetInfo () const
  94. {
  95. return &desc;
  96. }
  97. // ------------------------------------------------------------------------------------------------
  98. // Imports the given file into the given scene structure.
  99. void ColladaLoader::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  100. {
  101. mFileName = pFile;
  102. // clean all member arrays - just for safety, it should work even if we did not
  103. mMeshIndexByID.clear();
  104. mMaterialIndexByName.clear();
  105. mMeshes.clear();
  106. newMats.clear();
  107. mLights.clear();
  108. mCameras.clear();
  109. mTextures.clear();
  110. // parse the input file
  111. ColladaParser parser( pIOHandler, pFile);
  112. if( !parser.mRootNode)
  113. throw DeadlyImportError( "Collada: File came out empty. Something is wrong here.");
  114. // reserve some storage to avoid unnecessary reallocs
  115. newMats.reserve(parser.mMaterialLibrary.size()*2);
  116. mMeshes.reserve(parser.mMeshLibrary.size()*2);
  117. mCameras.reserve(parser.mCameraLibrary.size());
  118. mLights.reserve(parser.mLightLibrary.size());
  119. // create the materials first, for the meshes to find
  120. BuildMaterials( parser, pScene);
  121. // build the node hierarchy from it
  122. pScene->mRootNode = BuildHierarchy( parser, parser.mRootNode);
  123. // ... then fill the materials with the now adjusted settings
  124. FillMaterials(parser, pScene);
  125. // Convert to Y_UP, if different orientation
  126. if( parser.mUpDirection == ColladaParser::UP_X)
  127. pScene->mRootNode->mTransformation *= aiMatrix4x4(
  128. 0, -1, 0, 0,
  129. 1, 0, 0, 0,
  130. 0, 0, 1, 0,
  131. 0, 0, 0, 1);
  132. else if( parser.mUpDirection == ColladaParser::UP_Z)
  133. pScene->mRootNode->mTransformation *= aiMatrix4x4(
  134. 1, 0, 0, 0,
  135. 0, 0, 1, 0,
  136. 0, -1, 0, 0,
  137. 0, 0, 0, 1);
  138. // store all meshes
  139. StoreSceneMeshes( pScene);
  140. // store all materials
  141. StoreSceneMaterials( pScene);
  142. // store all lights
  143. StoreSceneLights( pScene);
  144. // store all cameras
  145. StoreSceneCameras( pScene);
  146. // store all animations
  147. StoreAnimations( pScene, parser);
  148. // If no meshes have been loaded, it's probably just an animated skeleton.
  149. if (!pScene->mNumMeshes) {
  150. if (!noSkeletonMesh) {
  151. SkeletonMeshBuilder hero(pScene);
  152. }
  153. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  154. }
  155. }
  156. // ------------------------------------------------------------------------------------------------
  157. // Recursively constructs a scene node for the given parser node and returns it.
  158. aiNode* ColladaLoader::BuildHierarchy( const ColladaParser& pParser, const Collada::Node* pNode)
  159. {
  160. // create a node for it
  161. aiNode* node = new aiNode();
  162. // find a name for the new node. It's more complicated than you might think
  163. node->mName.Set( FindNameForNode( pNode));
  164. // calculate the transformation matrix for it
  165. node->mTransformation = pParser.CalculateResultTransform( pNode->mTransforms);
  166. // now resolve node instances
  167. std::vector<const Collada::Node*> instances;
  168. ResolveNodeInstances(pParser,pNode,instances);
  169. // add children. first the *real* ones
  170. node->mNumChildren = pNode->mChildren.size()+instances.size();
  171. node->mChildren = new aiNode*[node->mNumChildren];
  172. for( size_t a = 0; a < pNode->mChildren.size(); a++)
  173. {
  174. node->mChildren[a] = BuildHierarchy( pParser, pNode->mChildren[a]);
  175. node->mChildren[a]->mParent = node;
  176. }
  177. // ... and finally the resolved node instances
  178. for( size_t a = 0; a < instances.size(); a++)
  179. {
  180. node->mChildren[pNode->mChildren.size() + a] = BuildHierarchy( pParser, instances[a]);
  181. node->mChildren[pNode->mChildren.size() + a]->mParent = node;
  182. }
  183. // construct meshes
  184. BuildMeshesForNode( pParser, pNode, node);
  185. // construct cameras
  186. BuildCamerasForNode(pParser, pNode, node);
  187. // construct lights
  188. BuildLightsForNode(pParser, pNode, node);
  189. return node;
  190. }
  191. // ------------------------------------------------------------------------------------------------
  192. // Resolve node instances
  193. void ColladaLoader::ResolveNodeInstances( const ColladaParser& pParser, const Collada::Node* pNode,
  194. std::vector<const Collada::Node*>& resolved)
  195. {
  196. // reserve enough storage
  197. resolved.reserve(pNode->mNodeInstances.size());
  198. // ... and iterate through all nodes to be instanced as children of pNode
  199. for (std::vector<Collada::NodeInstance>::const_iterator it = pNode->mNodeInstances.begin(),
  200. end = pNode->mNodeInstances.end(); it != end; ++it)
  201. {
  202. // find the corresponding node in the library
  203. const ColladaParser::NodeLibrary::const_iterator itt = pParser.mNodeLibrary.find((*it).mNode);
  204. const Collada::Node* nd = itt == pParser.mNodeLibrary.end() ? NULL : (*itt).second;
  205. // FIX for http://sourceforge.net/tracker/?func=detail&aid=3054873&group_id=226462&atid=1067632
  206. // need to check for both name and ID to catch all. To avoid breaking valid files,
  207. // the workaround is only enabled when the first attempt to resolve the node has failed.
  208. if (!nd) {
  209. nd = FindNode(pParser.mRootNode,(*it).mNode);
  210. }
  211. if (!nd)
  212. DefaultLogger::get()->error("Collada: Unable to resolve reference to instanced node " + (*it).mNode);
  213. else {
  214. // attach this node to the list of children
  215. resolved.push_back(nd);
  216. }
  217. }
  218. }
  219. // ------------------------------------------------------------------------------------------------
  220. // Resolve UV channels
  221. void ColladaLoader::ApplyVertexToEffectSemanticMapping(Collada::Sampler& sampler,
  222. const Collada::SemanticMappingTable& table)
  223. {
  224. std::map<std::string, Collada::InputSemanticMapEntry>::const_iterator it = table.mMap.find(sampler.mUVChannel);
  225. if (it != table.mMap.end()) {
  226. if (it->second.mType != Collada::IT_Texcoord)
  227. DefaultLogger::get()->error("Collada: Unexpected effect input mapping");
  228. sampler.mUVId = it->second.mSet;
  229. }
  230. }
  231. // ------------------------------------------------------------------------------------------------
  232. // Builds lights for the given node and references them
  233. void ColladaLoader::BuildLightsForNode( const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget)
  234. {
  235. BOOST_FOREACH( const Collada::LightInstance& lid, pNode->mLights)
  236. {
  237. // find the referred light
  238. ColladaParser::LightLibrary::const_iterator srcLightIt = pParser.mLightLibrary.find( lid.mLight);
  239. if( srcLightIt == pParser.mLightLibrary.end())
  240. {
  241. DefaultLogger::get()->warn("Collada: Unable to find light for ID \"" + lid.mLight + "\". Skipping.");
  242. continue;
  243. }
  244. const Collada::Light* srcLight = &srcLightIt->second;
  245. if (srcLight->mType == aiLightSource_AMBIENT) {
  246. DefaultLogger::get()->error("Collada: Skipping ambient light for the moment");
  247. continue;
  248. }
  249. // now fill our ai data structure
  250. aiLight* out = new aiLight();
  251. out->mName = pTarget->mName;
  252. out->mType = (aiLightSourceType)srcLight->mType;
  253. // collada lights point in -Z by default, rest is specified in node transform
  254. out->mDirection = aiVector3D(0.f,0.f,-1.f);
  255. out->mAttenuationConstant = srcLight->mAttConstant;
  256. out->mAttenuationLinear = srcLight->mAttLinear;
  257. out->mAttenuationQuadratic = srcLight->mAttQuadratic;
  258. // collada doesn't differenciate between these color types
  259. out->mColorDiffuse = out->mColorSpecular = out->mColorAmbient = srcLight->mColor*srcLight->mIntensity;
  260. // convert falloff angle and falloff exponent in our representation, if given
  261. if (out->mType == aiLightSource_SPOT) {
  262. out->mAngleInnerCone = AI_DEG_TO_RAD( srcLight->mFalloffAngle );
  263. // ... some extension magic. FUCKING COLLADA.
  264. if (srcLight->mOuterAngle == 10e10f)
  265. {
  266. // ... some deprecation magic. FUCKING FCOLLADA.
  267. if (srcLight->mPenumbraAngle == 10e10f)
  268. {
  269. // Need to rely on falloff_exponent. I don't know how to interpret it, so I need to guess ....
  270. // epsilon chosen to be 0.1
  271. out->mAngleOuterCone = AI_DEG_TO_RAD (acos(pow(0.1f,1.f/srcLight->mFalloffExponent))+
  272. srcLight->mFalloffAngle);
  273. }
  274. else {
  275. out->mAngleOuterCone = out->mAngleInnerCone + AI_DEG_TO_RAD( srcLight->mPenumbraAngle );
  276. if (out->mAngleOuterCone < out->mAngleInnerCone)
  277. std::swap(out->mAngleInnerCone,out->mAngleOuterCone);
  278. }
  279. }
  280. else out->mAngleOuterCone = AI_DEG_TO_RAD( srcLight->mOuterAngle );
  281. }
  282. // add to light list
  283. mLights.push_back(out);
  284. }
  285. }
  286. // ------------------------------------------------------------------------------------------------
  287. // Builds cameras for the given node and references them
  288. void ColladaLoader::BuildCamerasForNode( const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget)
  289. {
  290. BOOST_FOREACH( const Collada::CameraInstance& cid, pNode->mCameras)
  291. {
  292. // find the referred light
  293. ColladaParser::CameraLibrary::const_iterator srcCameraIt = pParser.mCameraLibrary.find( cid.mCamera);
  294. if( srcCameraIt == pParser.mCameraLibrary.end())
  295. {
  296. DefaultLogger::get()->warn("Collada: Unable to find camera for ID \"" + cid.mCamera + "\". Skipping.");
  297. continue;
  298. }
  299. const Collada::Camera* srcCamera = &srcCameraIt->second;
  300. // orthographic cameras not yet supported in Assimp
  301. if (srcCamera->mOrtho) {
  302. DefaultLogger::get()->warn("Collada: Orthographic cameras are not supported.");
  303. }
  304. // now fill our ai data structure
  305. aiCamera* out = new aiCamera();
  306. out->mName = pTarget->mName;
  307. // collada cameras point in -Z by default, rest is specified in node transform
  308. out->mLookAt = aiVector3D(0.f,0.f,-1.f);
  309. // near/far z is already ok
  310. out->mClipPlaneFar = srcCamera->mZFar;
  311. out->mClipPlaneNear = srcCamera->mZNear;
  312. // ... but for the rest some values are optional
  313. // and we need to compute the others in any combination. FUCKING COLLADA.
  314. if (srcCamera->mAspect != 10e10f)
  315. out->mAspect = srcCamera->mAspect;
  316. if (srcCamera->mHorFov != 10e10f) {
  317. out->mHorizontalFOV = srcCamera->mHorFov;
  318. if (srcCamera->mVerFov != 10e10f && srcCamera->mAspect == 10e10f) {
  319. out->mAspect = tan(AI_DEG_TO_RAD(srcCamera->mHorFov)) /
  320. tan(AI_DEG_TO_RAD(srcCamera->mVerFov));
  321. }
  322. }
  323. else if (srcCamera->mAspect != 10e10f && srcCamera->mVerFov != 10e10f) {
  324. out->mHorizontalFOV = 2.0f * AI_RAD_TO_DEG(atan(srcCamera->mAspect *
  325. tan(AI_DEG_TO_RAD(srcCamera->mVerFov) * 0.5f)));
  326. }
  327. // Collada uses degrees, we use radians
  328. out->mHorizontalFOV = AI_DEG_TO_RAD(out->mHorizontalFOV);
  329. // add to camera list
  330. mCameras.push_back(out);
  331. }
  332. }
  333. // ------------------------------------------------------------------------------------------------
  334. // Builds meshes for the given node and references them
  335. void ColladaLoader::BuildMeshesForNode( const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget)
  336. {
  337. // accumulated mesh references by this node
  338. std::vector<size_t> newMeshRefs;
  339. newMeshRefs.reserve(pNode->mMeshes.size());
  340. // add a mesh for each subgroup in each collada mesh
  341. BOOST_FOREACH( const Collada::MeshInstance& mid, pNode->mMeshes)
  342. {
  343. const Collada::Mesh* srcMesh = NULL;
  344. const Collada::Controller* srcController = NULL;
  345. // find the referred mesh
  346. ColladaParser::MeshLibrary::const_iterator srcMeshIt = pParser.mMeshLibrary.find( mid.mMeshOrController);
  347. if( srcMeshIt == pParser.mMeshLibrary.end())
  348. {
  349. // if not found in the mesh-library, it might also be a controller referring to a mesh
  350. ColladaParser::ControllerLibrary::const_iterator srcContrIt = pParser.mControllerLibrary.find( mid.mMeshOrController);
  351. if( srcContrIt != pParser.mControllerLibrary.end())
  352. {
  353. srcController = &srcContrIt->second;
  354. srcMeshIt = pParser.mMeshLibrary.find( srcController->mMeshId);
  355. if( srcMeshIt != pParser.mMeshLibrary.end())
  356. srcMesh = srcMeshIt->second;
  357. }
  358. if( !srcMesh)
  359. {
  360. DefaultLogger::get()->warn( boost::str( boost::format( "Collada: Unable to find geometry for ID \"%s\". Skipping.") % mid.mMeshOrController));
  361. continue;
  362. }
  363. } else
  364. {
  365. // ID found in the mesh library -> direct reference to an unskinned mesh
  366. srcMesh = srcMeshIt->second;
  367. }
  368. // build a mesh for each of its subgroups
  369. size_t vertexStart = 0, faceStart = 0;
  370. for( size_t sm = 0; sm < srcMesh->mSubMeshes.size(); ++sm)
  371. {
  372. const Collada::SubMesh& submesh = srcMesh->mSubMeshes[sm];
  373. if( submesh.mNumFaces == 0)
  374. continue;
  375. // find material assigned to this submesh
  376. std::string meshMaterial;
  377. std::map<std::string, Collada::SemanticMappingTable >::const_iterator meshMatIt = mid.mMaterials.find( submesh.mMaterial);
  378. const Collada::SemanticMappingTable* table = NULL;
  379. if( meshMatIt != mid.mMaterials.end())
  380. {
  381. table = &meshMatIt->second;
  382. meshMaterial = table->mMatName;
  383. }
  384. else
  385. {
  386. DefaultLogger::get()->warn( boost::str( boost::format( "Collada: No material specified for subgroup \"%s\" in geometry \"%s\".") % submesh.mMaterial % mid.mMeshOrController));
  387. if( !mid.mMaterials.empty() )
  388. meshMaterial = mid.mMaterials.begin()->second.mMatName;
  389. }
  390. // OK ... here the *real* fun starts ... we have the vertex-input-to-effect-semantic-table
  391. // given. The only mapping stuff which we do actually support is the UV channel.
  392. std::map<std::string, size_t>::const_iterator matIt = mMaterialIndexByName.find( meshMaterial);
  393. unsigned int matIdx;
  394. if( matIt != mMaterialIndexByName.end())
  395. matIdx = matIt->second;
  396. else
  397. matIdx = 0;
  398. if (table && !table->mMap.empty() ) {
  399. std::pair<Collada::Effect*, aiMaterial*>& mat = newMats[matIdx];
  400. // Iterate through all texture channels assigned to the effect and
  401. // check whether we have mapping information for it.
  402. ApplyVertexToEffectSemanticMapping(mat.first->mTexDiffuse, *table);
  403. ApplyVertexToEffectSemanticMapping(mat.first->mTexAmbient, *table);
  404. ApplyVertexToEffectSemanticMapping(mat.first->mTexSpecular, *table);
  405. ApplyVertexToEffectSemanticMapping(mat.first->mTexEmissive, *table);
  406. ApplyVertexToEffectSemanticMapping(mat.first->mTexTransparent,*table);
  407. ApplyVertexToEffectSemanticMapping(mat.first->mTexBump, *table);
  408. }
  409. // built lookup index of the Mesh-Submesh-Material combination
  410. ColladaMeshIndex index( mid.mMeshOrController, sm, meshMaterial);
  411. // if we already have the mesh at the library, just add its index to the node's array
  412. std::map<ColladaMeshIndex, size_t>::const_iterator dstMeshIt = mMeshIndexByID.find( index);
  413. if( dstMeshIt != mMeshIndexByID.end()) {
  414. newMeshRefs.push_back( dstMeshIt->second);
  415. }
  416. else
  417. {
  418. // else we have to add the mesh to the collection and store its newly assigned index at the node
  419. aiMesh* dstMesh = CreateMesh( pParser, srcMesh, submesh, srcController, vertexStart, faceStart);
  420. // store the mesh, and store its new index in the node
  421. newMeshRefs.push_back( mMeshes.size());
  422. mMeshIndexByID[index] = mMeshes.size();
  423. mMeshes.push_back( dstMesh);
  424. vertexStart += dstMesh->mNumVertices; faceStart += submesh.mNumFaces;
  425. // assign the material index
  426. dstMesh->mMaterialIndex = matIdx;
  427. dstMesh->mName = mid.mMeshOrController;
  428. }
  429. }
  430. }
  431. // now place all mesh references we gathered in the target node
  432. pTarget->mNumMeshes = newMeshRefs.size();
  433. if( newMeshRefs.size())
  434. {
  435. pTarget->mMeshes = new unsigned int[pTarget->mNumMeshes];
  436. std::copy( newMeshRefs.begin(), newMeshRefs.end(), pTarget->mMeshes);
  437. }
  438. }
  439. // ------------------------------------------------------------------------------------------------
  440. // Creates a mesh for the given ColladaMesh face subset and returns the newly created mesh
  441. aiMesh* ColladaLoader::CreateMesh( const ColladaParser& pParser, const Collada::Mesh* pSrcMesh, const Collada::SubMesh& pSubMesh,
  442. const Collada::Controller* pSrcController, size_t pStartVertex, size_t pStartFace)
  443. {
  444. aiMesh* dstMesh = new aiMesh;
  445. // count the vertices addressed by its faces
  446. const size_t numVertices = std::accumulate( pSrcMesh->mFaceSize.begin() + pStartFace,
  447. pSrcMesh->mFaceSize.begin() + pStartFace + pSubMesh.mNumFaces, 0);
  448. // copy positions
  449. dstMesh->mNumVertices = numVertices;
  450. dstMesh->mVertices = new aiVector3D[numVertices];
  451. std::copy( pSrcMesh->mPositions.begin() + pStartVertex, pSrcMesh->mPositions.begin() +
  452. pStartVertex + numVertices, dstMesh->mVertices);
  453. // normals, if given. HACK: (thom) Due to the fucking Collada spec we never
  454. // know if we have the same number of normals as there are positions. So we
  455. // also ignore any vertex attribute if it has a different count
  456. if( pSrcMesh->mNormals.size() >= pStartVertex + numVertices)
  457. {
  458. dstMesh->mNormals = new aiVector3D[numVertices];
  459. std::copy( pSrcMesh->mNormals.begin() + pStartVertex, pSrcMesh->mNormals.begin() +
  460. pStartVertex + numVertices, dstMesh->mNormals);
  461. }
  462. // tangents, if given.
  463. if( pSrcMesh->mTangents.size() >= pStartVertex + numVertices)
  464. {
  465. dstMesh->mTangents = new aiVector3D[numVertices];
  466. std::copy( pSrcMesh->mTangents.begin() + pStartVertex, pSrcMesh->mTangents.begin() +
  467. pStartVertex + numVertices, dstMesh->mTangents);
  468. }
  469. // bitangents, if given.
  470. if( pSrcMesh->mBitangents.size() >= pStartVertex + numVertices)
  471. {
  472. dstMesh->mBitangents = new aiVector3D[numVertices];
  473. std::copy( pSrcMesh->mBitangents.begin() + pStartVertex, pSrcMesh->mBitangents.begin() +
  474. pStartVertex + numVertices, dstMesh->mBitangents);
  475. }
  476. // same for texturecoords, as many as we have
  477. // empty slots are not allowed, need to pack and adjust UV indexes accordingly
  478. for( size_t a = 0, real = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; a++)
  479. {
  480. if( pSrcMesh->mTexCoords[a].size() >= pStartVertex + numVertices)
  481. {
  482. dstMesh->mTextureCoords[real] = new aiVector3D[numVertices];
  483. for( size_t b = 0; b < numVertices; ++b)
  484. dstMesh->mTextureCoords[real][b] = pSrcMesh->mTexCoords[a][pStartVertex+b];
  485. dstMesh->mNumUVComponents[real] = pSrcMesh->mNumUVComponents[a];
  486. ++real;
  487. }
  488. }
  489. // same for vertex colors, as many as we have. again the same packing to avoid empty slots
  490. for( size_t a = 0, real = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; a++)
  491. {
  492. if( pSrcMesh->mColors[a].size() >= pStartVertex + numVertices)
  493. {
  494. dstMesh->mColors[real] = new aiColor4D[numVertices];
  495. std::copy( pSrcMesh->mColors[a].begin() + pStartVertex, pSrcMesh->mColors[a].begin() + pStartVertex + numVertices,dstMesh->mColors[real]);
  496. ++real;
  497. }
  498. }
  499. // create faces. Due to the fact that each face uses unique vertices, we can simply count up on each vertex
  500. size_t vertex = 0;
  501. dstMesh->mNumFaces = pSubMesh.mNumFaces;
  502. dstMesh->mFaces = new aiFace[dstMesh->mNumFaces];
  503. for( size_t a = 0; a < dstMesh->mNumFaces; ++a)
  504. {
  505. size_t s = pSrcMesh->mFaceSize[ pStartFace + a];
  506. aiFace& face = dstMesh->mFaces[a];
  507. face.mNumIndices = s;
  508. face.mIndices = new unsigned int[s];
  509. for( size_t b = 0; b < s; ++b)
  510. face.mIndices[b] = vertex++;
  511. }
  512. // create bones if given
  513. if( pSrcController)
  514. {
  515. // refuse if the vertex count does not match
  516. // if( pSrcController->mWeightCounts.size() != dstMesh->mNumVertices)
  517. // throw DeadlyImportError( "Joint Controller vertex count does not match mesh vertex count");
  518. // resolve references - joint names
  519. const Collada::Accessor& jointNamesAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mJointNameSource);
  520. const Collada::Data& jointNames = pParser.ResolveLibraryReference( pParser.mDataLibrary, jointNamesAcc.mSource);
  521. // joint offset matrices
  522. const Collada::Accessor& jointMatrixAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mJointOffsetMatrixSource);
  523. const Collada::Data& jointMatrices = pParser.ResolveLibraryReference( pParser.mDataLibrary, jointMatrixAcc.mSource);
  524. // joint vertex_weight name list - should refer to the same list as the joint names above. If not, report and reconsider
  525. const Collada::Accessor& weightNamesAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mWeightInputJoints.mAccessor);
  526. if( &weightNamesAcc != &jointNamesAcc)
  527. throw DeadlyImportError( "Temporary implementational lazyness. If you read this, please report to the author.");
  528. // vertex weights
  529. const Collada::Accessor& weightsAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mWeightInputWeights.mAccessor);
  530. const Collada::Data& weights = pParser.ResolveLibraryReference( pParser.mDataLibrary, weightsAcc.mSource);
  531. if( !jointNames.mIsStringArray || jointMatrices.mIsStringArray || weights.mIsStringArray)
  532. throw DeadlyImportError( "Data type mismatch while resolving mesh joints");
  533. // sanity check: we rely on the vertex weights always coming as pairs of BoneIndex-WeightIndex
  534. if( pSrcController->mWeightInputJoints.mOffset != 0 || pSrcController->mWeightInputWeights.mOffset != 1)
  535. throw DeadlyImportError( "Unsupported vertex_weight adresssing scheme. Fucking collada spec.");
  536. // create containers to collect the weights for each bone
  537. size_t numBones = jointNames.mStrings.size();
  538. std::vector<std::vector<aiVertexWeight> > dstBones( numBones);
  539. // build a temporary array of pointers to the start of each vertex's weights
  540. typedef std::vector< std::pair<size_t, size_t> > IndexPairVector;
  541. std::vector<IndexPairVector::const_iterator> weightStartPerVertex;
  542. weightStartPerVertex.resize(pSrcController->mWeightCounts.size(),pSrcController->mWeights.end());
  543. IndexPairVector::const_iterator pit = pSrcController->mWeights.begin();
  544. for( size_t a = 0; a < pSrcController->mWeightCounts.size(); ++a)
  545. {
  546. weightStartPerVertex[a] = pit;
  547. pit += pSrcController->mWeightCounts[a];
  548. }
  549. // now for each vertex put the corresponding vertex weights into each bone's weight collection
  550. for( size_t a = pStartVertex; a < pStartVertex + numVertices; ++a)
  551. {
  552. // which position index was responsible for this vertex? that's also the index by which
  553. // the controller assigns the vertex weights
  554. size_t orgIndex = pSrcMesh->mFacePosIndices[a];
  555. // find the vertex weights for this vertex
  556. IndexPairVector::const_iterator iit = weightStartPerVertex[orgIndex];
  557. size_t pairCount = pSrcController->mWeightCounts[orgIndex];
  558. for( size_t b = 0; b < pairCount; ++b, ++iit)
  559. {
  560. size_t jointIndex = iit->first;
  561. size_t vertexIndex = iit->second;
  562. float weight = ReadFloat( weightsAcc, weights, vertexIndex, 0);
  563. // one day I gonna kill that XSI Collada exporter
  564. if( weight > 0.0f)
  565. {
  566. aiVertexWeight w;
  567. w.mVertexId = a - pStartVertex;
  568. w.mWeight = weight;
  569. dstBones[jointIndex].push_back( w);
  570. }
  571. }
  572. }
  573. // count the number of bones which influence vertices of the current submesh
  574. size_t numRemainingBones = 0;
  575. for( std::vector<std::vector<aiVertexWeight> >::const_iterator it = dstBones.begin(); it != dstBones.end(); ++it)
  576. if( it->size() > 0)
  577. numRemainingBones++;
  578. // create bone array and copy bone weights one by one
  579. dstMesh->mNumBones = numRemainingBones;
  580. dstMesh->mBones = new aiBone*[numRemainingBones];
  581. size_t boneCount = 0;
  582. for( size_t a = 0; a < numBones; ++a)
  583. {
  584. // omit bones without weights
  585. if( dstBones[a].size() == 0)
  586. continue;
  587. // create bone with its weights
  588. aiBone* bone = new aiBone;
  589. bone->mName = ReadString( jointNamesAcc, jointNames, a);
  590. bone->mOffsetMatrix.a1 = ReadFloat( jointMatrixAcc, jointMatrices, a, 0);
  591. bone->mOffsetMatrix.a2 = ReadFloat( jointMatrixAcc, jointMatrices, a, 1);
  592. bone->mOffsetMatrix.a3 = ReadFloat( jointMatrixAcc, jointMatrices, a, 2);
  593. bone->mOffsetMatrix.a4 = ReadFloat( jointMatrixAcc, jointMatrices, a, 3);
  594. bone->mOffsetMatrix.b1 = ReadFloat( jointMatrixAcc, jointMatrices, a, 4);
  595. bone->mOffsetMatrix.b2 = ReadFloat( jointMatrixAcc, jointMatrices, a, 5);
  596. bone->mOffsetMatrix.b3 = ReadFloat( jointMatrixAcc, jointMatrices, a, 6);
  597. bone->mOffsetMatrix.b4 = ReadFloat( jointMatrixAcc, jointMatrices, a, 7);
  598. bone->mOffsetMatrix.c1 = ReadFloat( jointMatrixAcc, jointMatrices, a, 8);
  599. bone->mOffsetMatrix.c2 = ReadFloat( jointMatrixAcc, jointMatrices, a, 9);
  600. bone->mOffsetMatrix.c3 = ReadFloat( jointMatrixAcc, jointMatrices, a, 10);
  601. bone->mOffsetMatrix.c4 = ReadFloat( jointMatrixAcc, jointMatrices, a, 11);
  602. bone->mNumWeights = dstBones[a].size();
  603. bone->mWeights = new aiVertexWeight[bone->mNumWeights];
  604. std::copy( dstBones[a].begin(), dstBones[a].end(), bone->mWeights);
  605. // apply bind shape matrix to offset matrix
  606. aiMatrix4x4 bindShapeMatrix;
  607. bindShapeMatrix.a1 = pSrcController->mBindShapeMatrix[0];
  608. bindShapeMatrix.a2 = pSrcController->mBindShapeMatrix[1];
  609. bindShapeMatrix.a3 = pSrcController->mBindShapeMatrix[2];
  610. bindShapeMatrix.a4 = pSrcController->mBindShapeMatrix[3];
  611. bindShapeMatrix.b1 = pSrcController->mBindShapeMatrix[4];
  612. bindShapeMatrix.b2 = pSrcController->mBindShapeMatrix[5];
  613. bindShapeMatrix.b3 = pSrcController->mBindShapeMatrix[6];
  614. bindShapeMatrix.b4 = pSrcController->mBindShapeMatrix[7];
  615. bindShapeMatrix.c1 = pSrcController->mBindShapeMatrix[8];
  616. bindShapeMatrix.c2 = pSrcController->mBindShapeMatrix[9];
  617. bindShapeMatrix.c3 = pSrcController->mBindShapeMatrix[10];
  618. bindShapeMatrix.c4 = pSrcController->mBindShapeMatrix[11];
  619. bindShapeMatrix.d1 = pSrcController->mBindShapeMatrix[12];
  620. bindShapeMatrix.d2 = pSrcController->mBindShapeMatrix[13];
  621. bindShapeMatrix.d3 = pSrcController->mBindShapeMatrix[14];
  622. bindShapeMatrix.d4 = pSrcController->mBindShapeMatrix[15];
  623. bone->mOffsetMatrix *= bindShapeMatrix;
  624. // HACK: (thom) Some exporters address the bone nodes by SID, others address them by ID or even name.
  625. // Therefore I added a little name replacement here: I search for the bone's node by either name, ID or SID,
  626. // and replace the bone's name by the node's name so that the user can use the standard
  627. // find-by-name method to associate nodes with bones.
  628. const Collada::Node* bnode = FindNode( pParser.mRootNode, bone->mName.data);
  629. if( !bnode)
  630. bnode = FindNodeBySID( pParser.mRootNode, bone->mName.data);
  631. // assign the name that we would have assigned for the source node
  632. if( bnode)
  633. bone->mName.Set( FindNameForNode( bnode));
  634. else
  635. DefaultLogger::get()->warn( boost::str( boost::format( "ColladaLoader::CreateMesh(): could not find corresponding node for joint \"%s\".") % bone->mName.data));
  636. // and insert bone
  637. dstMesh->mBones[boneCount++] = bone;
  638. }
  639. }
  640. return dstMesh;
  641. }
  642. // ------------------------------------------------------------------------------------------------
  643. // Stores all meshes in the given scene
  644. void ColladaLoader::StoreSceneMeshes( aiScene* pScene)
  645. {
  646. pScene->mNumMeshes = mMeshes.size();
  647. if( mMeshes.size() > 0)
  648. {
  649. pScene->mMeshes = new aiMesh*[mMeshes.size()];
  650. std::copy( mMeshes.begin(), mMeshes.end(), pScene->mMeshes);
  651. mMeshes.clear();
  652. }
  653. }
  654. // ------------------------------------------------------------------------------------------------
  655. // Stores all cameras in the given scene
  656. void ColladaLoader::StoreSceneCameras( aiScene* pScene)
  657. {
  658. pScene->mNumCameras = mCameras.size();
  659. if( mCameras.size() > 0)
  660. {
  661. pScene->mCameras = new aiCamera*[mCameras.size()];
  662. std::copy( mCameras.begin(), mCameras.end(), pScene->mCameras);
  663. mCameras.clear();
  664. }
  665. }
  666. // ------------------------------------------------------------------------------------------------
  667. // Stores all lights in the given scene
  668. void ColladaLoader::StoreSceneLights( aiScene* pScene)
  669. {
  670. pScene->mNumLights = mLights.size();
  671. if( mLights.size() > 0)
  672. {
  673. pScene->mLights = new aiLight*[mLights.size()];
  674. std::copy( mLights.begin(), mLights.end(), pScene->mLights);
  675. mLights.clear();
  676. }
  677. }
  678. // ------------------------------------------------------------------------------------------------
  679. // Stores all textures in the given scene
  680. void ColladaLoader::StoreSceneTextures( aiScene* pScene)
  681. {
  682. pScene->mNumTextures = mTextures.size();
  683. if( mTextures.size() > 0)
  684. {
  685. pScene->mTextures = new aiTexture*[mTextures.size()];
  686. std::copy( mTextures.begin(), mTextures.end(), pScene->mTextures);
  687. mTextures.clear();
  688. }
  689. }
  690. // ------------------------------------------------------------------------------------------------
  691. // Stores all materials in the given scene
  692. void ColladaLoader::StoreSceneMaterials( aiScene* pScene)
  693. {
  694. pScene->mNumMaterials = newMats.size();
  695. if (newMats.size() > 0) {
  696. pScene->mMaterials = new aiMaterial*[newMats.size()];
  697. for (unsigned int i = 0; i < newMats.size();++i)
  698. pScene->mMaterials[i] = newMats[i].second;
  699. newMats.clear();
  700. }
  701. }
  702. // ------------------------------------------------------------------------------------------------
  703. // Stores all animations
  704. void ColladaLoader::StoreAnimations( aiScene* pScene, const ColladaParser& pParser)
  705. {
  706. // recursivly collect all animations from the collada scene
  707. StoreAnimations( pScene, pParser, &pParser.mAnims, "");
  708. // catch special case: many animations with the same length, each affecting only a single node.
  709. // we need to unite all those single-node-anims to a proper combined animation
  710. for( size_t a = 0; a < mAnims.size(); ++a)
  711. {
  712. aiAnimation* templateAnim = mAnims[a];
  713. if( templateAnim->mNumChannels == 1)
  714. {
  715. // search for other single-channel-anims with the same duration
  716. std::vector<size_t> collectedAnimIndices;
  717. for( size_t b = a+1; b < mAnims.size(); ++b)
  718. {
  719. aiAnimation* other = mAnims[b];
  720. if( other->mNumChannels == 1 && other->mDuration == templateAnim->mDuration && other->mTicksPerSecond == templateAnim->mTicksPerSecond )
  721. collectedAnimIndices.push_back( b);
  722. }
  723. // if there are other animations which fit the template anim, combine all channels into a single anim
  724. if( !collectedAnimIndices.empty() )
  725. {
  726. aiAnimation* combinedAnim = new aiAnimation();
  727. combinedAnim->mName = aiString( std::string( "combinedAnim_") + char( '0' + a));
  728. combinedAnim->mDuration = templateAnim->mDuration;
  729. combinedAnim->mTicksPerSecond = templateAnim->mTicksPerSecond;
  730. combinedAnim->mNumChannels = collectedAnimIndices.size() + 1;
  731. combinedAnim->mChannels = new aiNodeAnim*[combinedAnim->mNumChannels];
  732. // add the template anim as first channel by moving its aiNodeAnim to the combined animation
  733. combinedAnim->mChannels[0] = templateAnim->mChannels[0];
  734. templateAnim->mChannels[0] = NULL;
  735. delete templateAnim;
  736. // combined animation replaces template animation in the anim array
  737. mAnims[a] = combinedAnim;
  738. // move the memory of all other anims to the combined anim and erase them from the source anims
  739. for( size_t b = 0; b < collectedAnimIndices.size(); ++b)
  740. {
  741. aiAnimation* srcAnimation = mAnims[collectedAnimIndices[b]];
  742. combinedAnim->mChannels[1 + b] = srcAnimation->mChannels[0];
  743. srcAnimation->mChannels[0] = NULL;
  744. delete srcAnimation;
  745. }
  746. // in a second go, delete all the single-channel-anims that we've stripped from their channels
  747. // back to front to preserve indices - you know, removing an element from a vector moves all elements behind the removed one
  748. while( !collectedAnimIndices.empty() )
  749. {
  750. mAnims.erase( mAnims.begin() + collectedAnimIndices.back());
  751. collectedAnimIndices.pop_back();
  752. }
  753. }
  754. }
  755. }
  756. // now store all anims in the scene
  757. if( !mAnims.empty())
  758. {
  759. pScene->mNumAnimations = mAnims.size();
  760. pScene->mAnimations = new aiAnimation*[mAnims.size()];
  761. std::copy( mAnims.begin(), mAnims.end(), pScene->mAnimations);
  762. }
  763. }
  764. // ------------------------------------------------------------------------------------------------
  765. // Constructs the animations for the given source anim
  766. void ColladaLoader::StoreAnimations( aiScene* pScene, const ColladaParser& pParser, const Collada::Animation* pSrcAnim, const std::string pPrefix)
  767. {
  768. std::string animName = pPrefix.empty() ? pSrcAnim->mName : pPrefix + "_" + pSrcAnim->mName;
  769. // create nested animations, if given
  770. for( std::vector<Collada::Animation*>::const_iterator it = pSrcAnim->mSubAnims.begin(); it != pSrcAnim->mSubAnims.end(); ++it)
  771. StoreAnimations( pScene, pParser, *it, animName);
  772. // create animation channels, if any
  773. if( !pSrcAnim->mChannels.empty())
  774. CreateAnimation( pScene, pParser, pSrcAnim, animName);
  775. }
  776. // ------------------------------------------------------------------------------------------------
  777. // Constructs the animation for the given source anim
  778. void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pParser, const Collada::Animation* pSrcAnim, const std::string& pName)
  779. {
  780. // collect a list of animatable nodes
  781. std::vector<const aiNode*> nodes;
  782. CollectNodes( pScene->mRootNode, nodes);
  783. std::vector<aiNodeAnim*> anims;
  784. for( std::vector<const aiNode*>::const_iterator nit = nodes.begin(); nit != nodes.end(); ++nit)
  785. {
  786. // find all the collada anim channels which refer to the current node
  787. std::vector<Collada::ChannelEntry> entries;
  788. std::string nodeName = (*nit)->mName.data;
  789. // find the collada node corresponding to the aiNode
  790. const Collada::Node* srcNode = FindNode( pParser.mRootNode, nodeName);
  791. // ai_assert( srcNode != NULL);
  792. if( !srcNode)
  793. continue;
  794. // now check all channels if they affect the current node
  795. for( std::vector<Collada::AnimationChannel>::const_iterator cit = pSrcAnim->mChannels.begin();
  796. cit != pSrcAnim->mChannels.end(); ++cit)
  797. {
  798. const Collada::AnimationChannel& srcChannel = *cit;
  799. Collada::ChannelEntry entry;
  800. // we expect the animation target to be of type "nodeName/transformID.subElement". Ignore all others
  801. // find the slash that separates the node name - there should be only one
  802. std::string::size_type slashPos = srcChannel.mTarget.find( '/');
  803. if( slashPos == std::string::npos)
  804. continue;
  805. if( srcChannel.mTarget.find( '/', slashPos+1) != std::string::npos)
  806. continue;
  807. std::string targetID = srcChannel.mTarget.substr( 0, slashPos);
  808. if( targetID != srcNode->mID)
  809. continue;
  810. // find the dot that separates the transformID - there should be only one or zero
  811. std::string::size_type dotPos = srcChannel.mTarget.find( '.');
  812. if( dotPos != std::string::npos)
  813. {
  814. if( srcChannel.mTarget.find( '.', dotPos+1) != std::string::npos)
  815. continue;
  816. entry.mTransformId = srcChannel.mTarget.substr( slashPos+1, dotPos - slashPos - 1);
  817. std::string subElement = srcChannel.mTarget.substr( dotPos+1);
  818. if( subElement == "ANGLE")
  819. entry.mSubElement = 3; // last number in an Axis-Angle-Transform is the angle
  820. else if( subElement == "X")
  821. entry.mSubElement = 0;
  822. else if( subElement == "Y")
  823. entry.mSubElement = 1;
  824. else if( subElement == "Z")
  825. entry.mSubElement = 2;
  826. else
  827. DefaultLogger::get()->warn( boost::str( boost::format( "Unknown anim subelement \"%s\". Ignoring") % subElement));
  828. } else
  829. {
  830. // no subelement following, transformId is remaining string
  831. entry.mTransformId = srcChannel.mTarget.substr( slashPos+1);
  832. }
  833. // determine which transform step is affected by this channel
  834. entry.mTransformIndex = SIZE_MAX;
  835. for( size_t a = 0; a < srcNode->mTransforms.size(); ++a)
  836. if( srcNode->mTransforms[a].mID == entry.mTransformId)
  837. entry.mTransformIndex = a;
  838. if( entry.mTransformIndex == SIZE_MAX) {
  839. continue;
  840. }
  841. entry.mChannel = &(*cit);
  842. entries.push_back( entry);
  843. }
  844. // if there's no channel affecting the current node, we skip it
  845. if( entries.empty())
  846. continue;
  847. // resolve the data pointers for all anim channels. Find the minimum time while we're at it
  848. float startTime = 1e20f, endTime = -1e20f;
  849. for( std::vector<Collada::ChannelEntry>::iterator it = entries.begin(); it != entries.end(); ++it)
  850. {
  851. Collada::ChannelEntry& e = *it;
  852. e.mTimeAccessor = &pParser.ResolveLibraryReference( pParser.mAccessorLibrary, e.mChannel->mSourceTimes);
  853. e.mTimeData = &pParser.ResolveLibraryReference( pParser.mDataLibrary, e.mTimeAccessor->mSource);
  854. e.mValueAccessor = &pParser.ResolveLibraryReference( pParser.mAccessorLibrary, e.mChannel->mSourceValues);
  855. e.mValueData = &pParser.ResolveLibraryReference( pParser.mDataLibrary, e.mValueAccessor->mSource);
  856. // time count and value count must match
  857. if( e.mTimeAccessor->mCount != e.mValueAccessor->mCount)
  858. throw DeadlyImportError( boost::str( boost::format( "Time count / value count mismatch in animation channel \"%s\".") % e.mChannel->mTarget));
  859. if( e.mTimeAccessor->mCount > 0 )
  860. {
  861. // find bounding times
  862. startTime = std::min( startTime, ReadFloat( *e.mTimeAccessor, *e.mTimeData, 0, 0));
  863. endTime = std::max( endTime, ReadFloat( *e.mTimeAccessor, *e.mTimeData, e.mTimeAccessor->mCount-1, 0));
  864. }
  865. }
  866. std::vector<aiMatrix4x4> resultTrafos;
  867. if( !entries.empty() && entries.front().mTimeAccessor->mCount > 0 )
  868. {
  869. // create a local transformation chain of the node's transforms
  870. std::vector<Collada::Transform> transforms = srcNode->mTransforms;
  871. // now for every unique point in time, find or interpolate the key values for that time
  872. // and apply them to the transform chain. Then the node's present transformation can be calculated.
  873. float time = startTime;
  874. while( 1)
  875. {
  876. for( std::vector<Collada::ChannelEntry>::iterator it = entries.begin(); it != entries.end(); ++it)
  877. {
  878. Collada::ChannelEntry& e = *it;
  879. // find the keyframe behind the current point in time
  880. size_t pos = 0;
  881. float postTime = 0.f;
  882. while( 1)
  883. {
  884. if( pos >= e.mTimeAccessor->mCount)
  885. break;
  886. postTime = ReadFloat( *e.mTimeAccessor, *e.mTimeData, pos, 0);
  887. if( postTime >= time)
  888. break;
  889. ++pos;
  890. }
  891. pos = std::min( pos, e.mTimeAccessor->mCount-1);
  892. // read values from there
  893. float temp[16];
  894. for( size_t c = 0; c < e.mValueAccessor->mSize; ++c)
  895. temp[c] = ReadFloat( *e.mValueAccessor, *e.mValueData, pos, c);
  896. // if not exactly at the key time, interpolate with previous value set
  897. if( postTime > time && pos > 0)
  898. {
  899. float preTime = ReadFloat( *e.mTimeAccessor, *e.mTimeData, pos-1, 0);
  900. float factor = (time - postTime) / (preTime - postTime);
  901. for( size_t c = 0; c < e.mValueAccessor->mSize; ++c)
  902. {
  903. float v = ReadFloat( *e.mValueAccessor, *e.mValueData, pos-1, c);
  904. temp[c] += (v - temp[c]) * factor;
  905. }
  906. }
  907. // Apply values to current transformation
  908. std::copy( temp, temp + e.mValueAccessor->mSize, transforms[e.mTransformIndex].f + e.mSubElement);
  909. }
  910. // Calculate resulting transformation
  911. aiMatrix4x4 mat = pParser.CalculateResultTransform( transforms);
  912. // out of lazyness: we store the time in matrix.d4
  913. mat.d4 = time;
  914. resultTrafos.push_back( mat);
  915. // find next point in time to evaluate. That's the closest frame larger than the current in any channel
  916. float nextTime = 1e20f;
  917. for( std::vector<Collada::ChannelEntry>::iterator it = entries.begin(); it != entries.end(); ++it)
  918. {
  919. Collada::ChannelEntry& e = *it;
  920. // find the next time value larger than the current
  921. size_t pos = 0;
  922. while( pos < e.mTimeAccessor->mCount)
  923. {
  924. float t = ReadFloat( *e.mTimeAccessor, *e.mTimeData, pos, 0);
  925. if( t > time)
  926. {
  927. nextTime = std::min( nextTime, t);
  928. break;
  929. }
  930. ++pos;
  931. }
  932. }
  933. // no more keys on any channel after the current time -> we're done
  934. if( nextTime > 1e19)
  935. break;
  936. // else construct next keyframe at this following time point
  937. time = nextTime;
  938. }
  939. }
  940. // there should be some keyframes, but we aren't that fixated on valid input data
  941. // ai_assert( resultTrafos.size() > 0);
  942. // build an animation channel for the given node out of these trafo keys
  943. if( !resultTrafos.empty() )
  944. {
  945. aiNodeAnim* dstAnim = new aiNodeAnim;
  946. dstAnim->mNodeName = nodeName;
  947. dstAnim->mNumPositionKeys = resultTrafos.size();
  948. dstAnim->mNumRotationKeys= resultTrafos.size();
  949. dstAnim->mNumScalingKeys = resultTrafos.size();
  950. dstAnim->mPositionKeys = new aiVectorKey[resultTrafos.size()];
  951. dstAnim->mRotationKeys = new aiQuatKey[resultTrafos.size()];
  952. dstAnim->mScalingKeys = new aiVectorKey[resultTrafos.size()];
  953. for( size_t a = 0; a < resultTrafos.size(); ++a)
  954. {
  955. aiMatrix4x4 mat = resultTrafos[a];
  956. double time = double( mat.d4); // remember? time is stored in mat.d4
  957. mat.d4 = 1.0f;
  958. dstAnim->mPositionKeys[a].mTime = time;
  959. dstAnim->mRotationKeys[a].mTime = time;
  960. dstAnim->mScalingKeys[a].mTime = time;
  961. mat.Decompose( dstAnim->mScalingKeys[a].mValue, dstAnim->mRotationKeys[a].mValue, dstAnim->mPositionKeys[a].mValue);
  962. }
  963. anims.push_back( dstAnim);
  964. } else
  965. {
  966. DefaultLogger::get()->warn( "Collada loader: found empty animation channel, ignored. Please check your exporter.");
  967. }
  968. }
  969. if( !anims.empty())
  970. {
  971. aiAnimation* anim = new aiAnimation;
  972. anim->mName.Set( pName);
  973. anim->mNumChannels = anims.size();
  974. anim->mChannels = new aiNodeAnim*[anims.size()];
  975. std::copy( anims.begin(), anims.end(), anim->mChannels);
  976. anim->mDuration = 0.0f;
  977. for( size_t a = 0; a < anims.size(); ++a)
  978. {
  979. anim->mDuration = std::max( anim->mDuration, anims[a]->mPositionKeys[anims[a]->mNumPositionKeys-1].mTime);
  980. anim->mDuration = std::max( anim->mDuration, anims[a]->mRotationKeys[anims[a]->mNumRotationKeys-1].mTime);
  981. anim->mDuration = std::max( anim->mDuration, anims[a]->mScalingKeys[anims[a]->mNumScalingKeys-1].mTime);
  982. }
  983. anim->mTicksPerSecond = 1;
  984. mAnims.push_back( anim);
  985. }
  986. }
  987. // ------------------------------------------------------------------------------------------------
  988. // Add a texture to a material structure
  989. void ColladaLoader::AddTexture ( aiMaterial& mat, const ColladaParser& pParser,
  990. const Collada::Effect& effect,
  991. const Collada::Sampler& sampler,
  992. aiTextureType type, unsigned int idx)
  993. {
  994. // first of all, basic file name
  995. const aiString name = FindFilenameForEffectTexture( pParser, effect, sampler.mName );
  996. mat.AddProperty( &name, _AI_MATKEY_TEXTURE_BASE, type, idx );
  997. // mapping mode
  998. int map = aiTextureMapMode_Clamp;
  999. if (sampler.mWrapU)
  1000. map = aiTextureMapMode_Wrap;
  1001. if (sampler.mWrapU && sampler.mMirrorU)
  1002. map = aiTextureMapMode_Mirror;
  1003. mat.AddProperty( &map, 1, _AI_MATKEY_MAPPINGMODE_U_BASE, type, idx);
  1004. map = aiTextureMapMode_Clamp;
  1005. if (sampler.mWrapV)
  1006. map = aiTextureMapMode_Wrap;
  1007. if (sampler.mWrapV && sampler.mMirrorV)
  1008. map = aiTextureMapMode_Mirror;
  1009. mat.AddProperty( &map, 1, _AI_MATKEY_MAPPINGMODE_V_BASE, type, idx);
  1010. // UV transformation
  1011. mat.AddProperty(&sampler.mTransform, 1,
  1012. _AI_MATKEY_UVTRANSFORM_BASE, type, idx);
  1013. // Blend mode
  1014. mat.AddProperty((int*)&sampler.mOp , 1,
  1015. _AI_MATKEY_TEXBLEND_BASE, type, idx);
  1016. // Blend factor
  1017. mat.AddProperty((float*)&sampler.mWeighting , 1,
  1018. _AI_MATKEY_TEXBLEND_BASE, type, idx);
  1019. // UV source index ... if we didn't resolve the mapping, it is actually just
  1020. // a guess but it works in most cases. We search for the frst occurence of a
  1021. // number in the channel name. We assume it is the zero-based index into the
  1022. // UV channel array of all corresponding meshes. It could also be one-based
  1023. // for some exporters, but we won't care of it unless someone complains about.
  1024. if (sampler.mUVId != UINT_MAX)
  1025. map = sampler.mUVId;
  1026. else {
  1027. map = -1;
  1028. for (std::string::const_iterator it = sampler.mUVChannel.begin();it != sampler.mUVChannel.end(); ++it){
  1029. if (IsNumeric(*it)) {
  1030. map = strtoul10(&(*it));
  1031. break;
  1032. }
  1033. }
  1034. if (-1 == map) {
  1035. DefaultLogger::get()->warn("Collada: unable to determine UV channel for texture");
  1036. map = 0;
  1037. }
  1038. }
  1039. mat.AddProperty(&map,1,_AI_MATKEY_UVWSRC_BASE,type,idx);
  1040. }
  1041. // ------------------------------------------------------------------------------------------------
  1042. // Fills materials from the collada material definitions
  1043. void ColladaLoader::FillMaterials( const ColladaParser& pParser, aiScene* /*pScene*/)
  1044. {
  1045. for (std::vector<std::pair<Collada::Effect*, aiMaterial*> >::iterator it = newMats.begin(),
  1046. end = newMats.end(); it != end; ++it)
  1047. {
  1048. aiMaterial& mat = (aiMaterial&)*it->second;
  1049. Collada::Effect& effect = *it->first;
  1050. // resolve shading mode
  1051. int shadeMode;
  1052. if (effect.mFaceted) /* fixme */
  1053. shadeMode = aiShadingMode_Flat;
  1054. else {
  1055. switch( effect.mShadeType)
  1056. {
  1057. case Collada::Shade_Constant:
  1058. shadeMode = aiShadingMode_NoShading;
  1059. break;
  1060. case Collada::Shade_Lambert:
  1061. shadeMode = aiShadingMode_Gouraud;
  1062. break;
  1063. case Collada::Shade_Blinn:
  1064. shadeMode = aiShadingMode_Blinn;
  1065. break;
  1066. case Collada::Shade_Phong:
  1067. shadeMode = aiShadingMode_Phong;
  1068. break;
  1069. default:
  1070. DefaultLogger::get()->warn("Collada: Unrecognized shading mode, using gouraud shading");
  1071. shadeMode = aiShadingMode_Gouraud;
  1072. break;
  1073. }
  1074. }
  1075. mat.AddProperty<int>( &shadeMode, 1, AI_MATKEY_SHADING_MODEL);
  1076. // double-sided?
  1077. shadeMode = effect.mDoubleSided;
  1078. mat.AddProperty<int>( &shadeMode, 1, AI_MATKEY_TWOSIDED);
  1079. // wireframe?
  1080. shadeMode = effect.mWireframe;
  1081. mat.AddProperty<int>( &shadeMode, 1, AI_MATKEY_ENABLE_WIREFRAME);
  1082. // add material colors
  1083. mat.AddProperty( &effect.mAmbient, 1,AI_MATKEY_COLOR_AMBIENT);
  1084. mat.AddProperty( &effect.mDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  1085. mat.AddProperty( &effect.mSpecular, 1,AI_MATKEY_COLOR_SPECULAR);
  1086. mat.AddProperty( &effect.mEmissive, 1, AI_MATKEY_COLOR_EMISSIVE);
  1087. mat.AddProperty( &effect.mTransparent, 1, AI_MATKEY_COLOR_TRANSPARENT);
  1088. mat.AddProperty( &effect.mReflective, 1, AI_MATKEY_COLOR_REFLECTIVE);
  1089. // scalar properties
  1090. mat.AddProperty( &effect.mShininess, 1, AI_MATKEY_SHININESS);
  1091. mat.AddProperty( &effect.mReflectivity, 1, AI_MATKEY_REFLECTIVITY);
  1092. mat.AddProperty( &effect.mRefractIndex, 1, AI_MATKEY_REFRACTI);
  1093. // transparency, a very hard one. seemingly not all files are following the
  1094. // specification here .. but we can trick.
  1095. if (effect.mTransparency >= 0.f && effect.mTransparency < 1.f) {
  1096. effect.mTransparency = 1.f- effect.mTransparency;
  1097. mat.AddProperty( &effect.mTransparency, 1, AI_MATKEY_OPACITY );
  1098. mat.AddProperty( &effect.mTransparent, 1, AI_MATKEY_COLOR_TRANSPARENT );
  1099. }
  1100. // add textures, if given
  1101. if( !effect.mTexAmbient.mName.empty())
  1102. /* It is merely a lightmap */
  1103. AddTexture( mat, pParser, effect, effect.mTexAmbient, aiTextureType_LIGHTMAP);
  1104. if( !effect.mTexEmissive.mName.empty())
  1105. AddTexture( mat, pParser, effect, effect.mTexEmissive, aiTextureType_EMISSIVE);
  1106. if( !effect.mTexSpecular.mName.empty())
  1107. AddTexture( mat, pParser, effect, effect.mTexSpecular, aiTextureType_SPECULAR);
  1108. if( !effect.mTexDiffuse.mName.empty())
  1109. AddTexture( mat, pParser, effect, effect.mTexDiffuse, aiTextureType_DIFFUSE);
  1110. if( !effect.mTexBump.mName.empty())
  1111. AddTexture( mat, pParser, effect, effect.mTexBump, aiTextureType_NORMALS);
  1112. if( !effect.mTexTransparent.mName.empty())
  1113. AddTexture( mat, pParser, effect, effect.mTexTransparent, aiTextureType_OPACITY);
  1114. if( !effect.mTexReflective.mName.empty())
  1115. AddTexture( mat, pParser, effect, effect.mTexReflective, aiTextureType_REFLECTION);
  1116. }
  1117. }
  1118. // ------------------------------------------------------------------------------------------------
  1119. // Constructs materials from the collada material definitions
  1120. void ColladaLoader::BuildMaterials( ColladaParser& pParser, aiScene* /*pScene*/)
  1121. {
  1122. newMats.reserve(pParser.mMaterialLibrary.size());
  1123. for( ColladaParser::MaterialLibrary::const_iterator matIt = pParser.mMaterialLibrary.begin(); matIt != pParser.mMaterialLibrary.end(); ++matIt)
  1124. {
  1125. const Collada::Material& material = matIt->second;
  1126. // a material is only a reference to an effect
  1127. ColladaParser::EffectLibrary::iterator effIt = pParser.mEffectLibrary.find( material.mEffect);
  1128. if( effIt == pParser.mEffectLibrary.end())
  1129. continue;
  1130. Collada::Effect& effect = effIt->second;
  1131. // create material
  1132. aiMaterial* mat = new aiMaterial;
  1133. aiString name( matIt->first);
  1134. mat->AddProperty(&name,AI_MATKEY_NAME);
  1135. // store the material
  1136. mMaterialIndexByName[matIt->first] = newMats.size();
  1137. newMats.push_back( std::pair<Collada::Effect*, aiMaterial*>( &effect,mat) );
  1138. }
  1139. // ScenePreprocessor generates a default material automatically if none is there.
  1140. // All further code here in this loader works well without a valid material so
  1141. // we can safely let it to ScenePreprocessor.
  1142. #if 0
  1143. if( newMats.size() == 0)
  1144. {
  1145. aiMaterial* mat = new aiMaterial;
  1146. aiString name( AI_DEFAULT_MATERIAL_NAME );
  1147. mat->AddProperty( &name, AI_MATKEY_NAME);
  1148. const int shadeMode = aiShadingMode_Phong;
  1149. mat->AddProperty<int>( &shadeMode, 1, AI_MATKEY_SHADING_MODEL);
  1150. aiColor4D colAmbient( 0.2f, 0.2f, 0.2f, 1.0f), colDiffuse( 0.8f, 0.8f, 0.8f, 1.0f), colSpecular( 0.5f, 0.5f, 0.5f, 0.5f);
  1151. mat->AddProperty( &colAmbient, 1, AI_MATKEY_COLOR_AMBIENT);
  1152. mat->AddProperty( &colDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  1153. mat->AddProperty( &colSpecular, 1, AI_MATKEY_COLOR_SPECULAR);
  1154. const float specExp = 5.0f;
  1155. mat->AddProperty( &specExp, 1, AI_MATKEY_SHININESS);
  1156. }
  1157. #endif
  1158. }
  1159. // ------------------------------------------------------------------------------------------------
  1160. // Resolves the texture name for the given effect texture entry
  1161. aiString ColladaLoader::FindFilenameForEffectTexture( const ColladaParser& pParser,
  1162. const Collada::Effect& pEffect, const std::string& pName)
  1163. {
  1164. // recurse through the param references until we end up at an image
  1165. std::string name = pName;
  1166. while( 1)
  1167. {
  1168. // the given string is a param entry. Find it
  1169. Collada::Effect::ParamLibrary::const_iterator it = pEffect.mParams.find( name);
  1170. // if not found, we're at the end of the recursion. The resulting string should be the image ID
  1171. if( it == pEffect.mParams.end())
  1172. break;
  1173. // else recurse on
  1174. name = it->second.mReference;
  1175. }
  1176. // find the image referred by this name in the image library of the scene
  1177. ColladaParser::ImageLibrary::const_iterator imIt = pParser.mImageLibrary.find( name);
  1178. if( imIt == pParser.mImageLibrary.end())
  1179. {
  1180. throw DeadlyImportError( boost::str( boost::format(
  1181. "Collada: Unable to resolve effect texture entry \"%s\", ended up at ID \"%s\".") % pName % name));
  1182. }
  1183. aiString result;
  1184. // if this is an embedded texture image setup an aiTexture for it
  1185. if (imIt->second.mFileName.empty())
  1186. {
  1187. if (imIt->second.mImageData.empty()) {
  1188. throw DeadlyImportError("Collada: Invalid texture, no data or file reference given");
  1189. }
  1190. aiTexture* tex = new aiTexture();
  1191. // setup format hint
  1192. if (imIt->second.mEmbeddedFormat.length() > 3) {
  1193. DefaultLogger::get()->warn("Collada: texture format hint is too long, truncating to 3 characters");
  1194. }
  1195. strncpy(tex->achFormatHint,imIt->second.mEmbeddedFormat.c_str(),3);
  1196. // and copy texture data
  1197. tex->mHeight = 0;
  1198. tex->mWidth = imIt->second.mImageData.size();
  1199. tex->pcData = (aiTexel*)new char[tex->mWidth];
  1200. memcpy(tex->pcData,&imIt->second.mImageData[0],tex->mWidth);
  1201. // setup texture reference string
  1202. result.data[0] = '*';
  1203. result.length = 1 + ASSIMP_itoa10(result.data+1,MAXLEN-1,mTextures.size());
  1204. // and add this texture to the list
  1205. mTextures.push_back(tex);
  1206. }
  1207. else
  1208. {
  1209. result.Set( imIt->second.mFileName );
  1210. ConvertPath(result);
  1211. }
  1212. return result;
  1213. }
  1214. // ------------------------------------------------------------------------------------------------
  1215. // Convert a path read from a collada file to the usual representation
  1216. void ColladaLoader::ConvertPath (aiString& ss)
  1217. {
  1218. // TODO: collada spec, p 22. Handle URI correctly.
  1219. // For the moment we're just stripping the file:// away to make it work.
  1220. // Windoes doesn't seem to be able to find stuff like
  1221. // 'file://..\LWO\LWO2\MappingModes\earthSpherical.jpg'
  1222. if (0 == strncmp(ss.data,"file://",7))
  1223. {
  1224. ss.length -= 7;
  1225. memmove(ss.data,ss.data+7,ss.length);
  1226. ss.data[ss.length] = '\0';
  1227. }
  1228. // Maxon Cinema Collada Export writes "file:///C:\andsoon" with three slashes...
  1229. // I need to filter it without destroying linux paths starting with "/somewhere"
  1230. if( ss.data[0] == '/' && isalpha( ss.data[1]) && ss.data[2] == ':' )
  1231. {
  1232. ss.length--;
  1233. memmove( ss.data, ss.data+1, ss.length);
  1234. ss.data[ss.length] = 0;
  1235. }
  1236. // find and convert all %xyz special chars
  1237. char* out = ss.data;
  1238. for( const char* it = ss.data; it != ss.data + ss.length; /**/ )
  1239. {
  1240. if( *it == '%' )
  1241. {
  1242. size_t nbr = strtoul16( ++it, &it);
  1243. *out++ = (char)(nbr & 0xFF);
  1244. } else
  1245. {
  1246. *out++ = *it++;
  1247. }
  1248. }
  1249. // adjust length and terminator of the shortened string
  1250. *out = 0;
  1251. ss.length = (ptrdiff_t) (out - ss.data);
  1252. }
  1253. // ------------------------------------------------------------------------------------------------
  1254. // Reads a float value from an accessor and its data array.
  1255. float ColladaLoader::ReadFloat( const Collada::Accessor& pAccessor, const Collada::Data& pData, size_t pIndex, size_t pOffset) const
  1256. {
  1257. // FIXME: (thom) Test for data type here in every access? For the moment, I leave this to the caller
  1258. size_t pos = pAccessor.mStride * pIndex + pAccessor.mOffset + pOffset;
  1259. ai_assert( pos < pData.mValues.size());
  1260. return pData.mValues[pos];
  1261. }
  1262. // ------------------------------------------------------------------------------------------------
  1263. // Reads a string value from an accessor and its data array.
  1264. const std::string& ColladaLoader::ReadString( const Collada::Accessor& pAccessor, const Collada::Data& pData, size_t pIndex) const
  1265. {
  1266. size_t pos = pAccessor.mStride * pIndex + pAccessor.mOffset;
  1267. ai_assert( pos < pData.mStrings.size());
  1268. return pData.mStrings[pos];
  1269. }
  1270. // ------------------------------------------------------------------------------------------------
  1271. // Collects all nodes into the given array
  1272. void ColladaLoader::CollectNodes( const aiNode* pNode, std::vector<const aiNode*>& poNodes) const
  1273. {
  1274. poNodes.push_back( pNode);
  1275. for( size_t a = 0; a < pNode->mNumChildren; ++a)
  1276. CollectNodes( pNode->mChildren[a], poNodes);
  1277. }
  1278. // ------------------------------------------------------------------------------------------------
  1279. // Finds a node in the collada scene by the given name
  1280. const Collada::Node* ColladaLoader::FindNode( const Collada::Node* pNode, const std::string& pName) const
  1281. {
  1282. if( pNode->mName == pName || pNode->mID == pName)
  1283. return pNode;
  1284. for( size_t a = 0; a < pNode->mChildren.size(); ++a)
  1285. {
  1286. const Collada::Node* node = FindNode( pNode->mChildren[a], pName);
  1287. if( node)
  1288. return node;
  1289. }
  1290. return NULL;
  1291. }
  1292. // ------------------------------------------------------------------------------------------------
  1293. // Finds a node in the collada scene by the given SID
  1294. const Collada::Node* ColladaLoader::FindNodeBySID( const Collada::Node* pNode, const std::string& pSID) const
  1295. {
  1296. if( pNode->mSID == pSID)
  1297. return pNode;
  1298. for( size_t a = 0; a < pNode->mChildren.size(); ++a)
  1299. {
  1300. const Collada::Node* node = FindNodeBySID( pNode->mChildren[a], pSID);
  1301. if( node)
  1302. return node;
  1303. }
  1304. return NULL;
  1305. }
  1306. // ------------------------------------------------------------------------------------------------
  1307. // Finds a proper name for a node derived from the collada-node's properties
  1308. std::string ColladaLoader::FindNameForNode( const Collada::Node* pNode) const
  1309. {
  1310. // now setup the name of the node. We take the name if not empty, otherwise the collada ID
  1311. // FIX: Workaround for XSI calling the instanced visual scene 'untitled' by default.
  1312. if (!pNode->mName.empty() && pNode->mName != "untitled")
  1313. return pNode->mName;
  1314. else if (!pNode->mID.empty())
  1315. return pNode->mID;
  1316. else if (!pNode->mSID.empty())
  1317. return pNode->mSID;
  1318. else
  1319. {
  1320. // No need to worry. Unnamed nodes are no problem at all, except
  1321. // if cameras or lights need to be assigned to them.
  1322. return boost::str( boost::format( "$ColladaAutoName$_%d") % clock());
  1323. }
  1324. }
  1325. #endif // !! ASSIMP_BUILD_NO_DAE_IMPORTER