ColladaLoader.cpp 69 KB

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