ColladaLoader.cpp 62 KB

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