2
0

ColladaLoader.cpp 62 KB

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