ColladaLoader.cpp 59 KB

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