ColladaLoader.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (ASSIMP)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2008, ASSIMP Development 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 Development 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. #include "../include/aiAnim.h"
  37. #include "ColladaLoader.h"
  38. #include "ColladaParser.h"
  39. using namespace Assimp;
  40. // ------------------------------------------------------------------------------------------------
  41. // Constructor to be privately used by Importer
  42. ColladaLoader::ColladaLoader()
  43. {}
  44. // ------------------------------------------------------------------------------------------------
  45. // Destructor, private as well
  46. ColladaLoader::~ColladaLoader()
  47. {}
  48. // ------------------------------------------------------------------------------------------------
  49. // Returns whether the class can handle the format of the given file.
  50. bool ColladaLoader::CanRead( const std::string& pFile, IOSystem* pIOHandler) const
  51. {
  52. // check file extension
  53. std::string::size_type pos = pFile.find_last_of('.');
  54. // no file extension - can't read
  55. if( pos == std::string::npos)
  56. return false;
  57. std::string extension = pFile.substr( pos);
  58. for( std::string::iterator it = extension.begin(); it != extension.end(); ++it)
  59. *it = tolower( *it);
  60. if( extension == ".dae")
  61. return true;
  62. // XML - too generic, we need to open the file and search for typical keywords
  63. if( extension == ".xml") {
  64. /* If CanRead() is called in order to check whether we
  65. * support a specific file extension in general pIOHandler
  66. * might be NULL and it's our duty to return true here.
  67. */
  68. if (!pIOHandler)return true;
  69. const char* tokens[] = {"collada"};
  70. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  71. }
  72. return false;
  73. }
  74. // ------------------------------------------------------------------------------------------------
  75. // Imports the given file into the given scene structure.
  76. void ColladaLoader::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  77. {
  78. mFileName = pFile;
  79. // parse the input file
  80. ColladaParser parser( pFile);
  81. if( !parser.mRootNode)
  82. throw new ImportErrorException( "File came out empty. Something is wrong here.");
  83. // create the materials first, for the meshes to find
  84. BuildMaterials( parser, pScene);
  85. // build the node hierarchy from it
  86. pScene->mRootNode = BuildHierarchy( parser, parser.mRootNode);
  87. // Convert to Z_UP, if different orientation
  88. if( parser.mUpDirection == ColladaParser::UP_X)
  89. pScene->mRootNode->mTransformation *= aiMatrix4x4(
  90. 0, -1, 0, 0,
  91. 0, 0, -1, 0,
  92. 1, 0, 0, 0,
  93. 0, 0, 0, 1);
  94. else if( parser.mUpDirection == ColladaParser::UP_Y)
  95. pScene->mRootNode->mTransformation *= aiMatrix4x4(
  96. 1, 0, 0, 0,
  97. 0, 0, -1, 0,
  98. 0, 1, 0, 0,
  99. 0, 0, 0, 1);
  100. // store all meshes
  101. StoreSceneMeshes( pScene);
  102. }
  103. // ------------------------------------------------------------------------------------------------
  104. // Recursively constructs a scene node for the given parser node and returns it.
  105. aiNode* ColladaLoader::BuildHierarchy( const ColladaParser& pParser, const Collada::Node* pNode)
  106. {
  107. // create a node for it
  108. aiNode* node = new aiNode( pNode->mName);
  109. // calculate the transformation matrix for it
  110. node->mTransformation = pParser.CalculateResultTransform( pNode->mTransforms);
  111. // add children
  112. node->mNumChildren = pNode->mChildren.size();
  113. node->mChildren = new aiNode*[node->mNumChildren];
  114. for( unsigned int a = 0; a < pNode->mChildren.size(); a++)
  115. {
  116. node->mChildren[a] = BuildHierarchy( pParser, pNode->mChildren[a]);
  117. node->mChildren[a]->mParent = node;
  118. }
  119. // construct meshes
  120. BuildMeshesForNode( pParser, pNode, node);
  121. return node;
  122. }
  123. // ------------------------------------------------------------------------------------------------
  124. // Builds meshes for the given node and references them
  125. void ColladaLoader::BuildMeshesForNode( const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget)
  126. {
  127. // accumulated mesh references by this node
  128. std::vector<size_t> newMeshRefs;
  129. // for the moment we simply ignore all material tags and transfer the meshes one by one
  130. BOOST_FOREACH( const Collada::MeshInstance& mid, pNode->mMeshes)
  131. {
  132. // find the referred mesh
  133. ColladaParser::MeshLibrary::const_iterator srcMeshIt = pParser.mMeshLibrary.find( mid.mMesh);
  134. if( srcMeshIt == pParser.mMeshLibrary.end())
  135. {
  136. DefaultLogger::get()->warn( boost::str( boost::format( "Unable to find geometry for ID \"%s\". Skipping.") % mid.mMesh));
  137. continue;
  138. }
  139. const Collada::Mesh* srcMesh = srcMeshIt->second;
  140. // build a mesh for each of its subgroups
  141. size_t vertexStart = 0, faceStart = 0;
  142. for( size_t sm = 0; sm < srcMesh->mSubMeshes.size(); ++sm)
  143. {
  144. const Collada::SubMesh& submesh = srcMesh->mSubMeshes[sm];
  145. // find material assigned to this submesh
  146. std::map<std::string, std::string>::const_iterator meshMatIt = mid.mMaterials.find( submesh.mMaterial);
  147. std::string meshMaterial;
  148. if( meshMatIt != mid.mMaterials.end())
  149. meshMaterial = meshMatIt->second;
  150. else
  151. DefaultLogger::get()->warn( boost::str( boost::format( "No material specified for subgroup \"%s\" in geometry \"%s\".") % submesh.mMaterial % mid.mMesh));
  152. // built lookup index of the Mesh-Submesh-Material combination
  153. ColladaMeshIndex index( mid.mMesh, sm, meshMaterial);
  154. // if we already have the mesh at the library, just add its index to the node's array
  155. std::map<ColladaMeshIndex, size_t>::const_iterator dstMeshIt = mMeshIndexByID.find( index);
  156. if( dstMeshIt != mMeshIndexByID.end())
  157. {
  158. newMeshRefs.push_back( dstMeshIt->second);
  159. } else
  160. {
  161. // else we have to add the mesh to the collection and store its newly assigned index at the node
  162. aiMesh* dstMesh = new aiMesh;
  163. // count the vertices addressed by its faces
  164. size_t numVertices =
  165. std::accumulate( srcMesh->mFaceSize.begin() + faceStart, srcMesh->mFaceSize.begin() + faceStart + submesh.mNumFaces, 0);
  166. // copy positions
  167. dstMesh->mNumVertices = numVertices;
  168. dstMesh->mVertices = new aiVector3D[numVertices];
  169. std::copy( srcMesh->mPositions.begin() + vertexStart, srcMesh->mPositions.begin() + vertexStart + numVertices, dstMesh->mVertices);
  170. // normals, if given. HACK: (thom) Due to the fucking Collada spec we never know if we have the same
  171. // number of normals as there are positions. So we also ignore any vertex attribute if it has a different count
  172. if( srcMesh->mNormals.size() == srcMesh->mPositions.size())
  173. {
  174. dstMesh->mNormals = new aiVector3D[numVertices];
  175. std::copy( srcMesh->mNormals.begin() + vertexStart, srcMesh->mNormals.begin() + vertexStart + numVertices, dstMesh->mNormals);
  176. }
  177. // same for texturecoords, as many as we have
  178. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; a++)
  179. {
  180. if( srcMesh->mTexCoords[a].size() == srcMesh->mPositions.size())
  181. {
  182. dstMesh->mTextureCoords[a] = new aiVector3D[numVertices];
  183. for( size_t b = vertexStart; b < vertexStart + numVertices; ++b)
  184. dstMesh->mTextureCoords[a][b].Set( srcMesh->mTexCoords[a][b].x, srcMesh->mTexCoords[a][b].y, 0.0f);
  185. dstMesh->mNumUVComponents[a] = 2;
  186. }
  187. }
  188. // same for vertex colors, as many as we have
  189. for( size_t a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; a++)
  190. {
  191. if( srcMesh->mColors[a].size() == srcMesh->mPositions.size())
  192. {
  193. dstMesh->mColors[a] = new aiColor4D[numVertices];
  194. std::copy( srcMesh->mColors[a].begin() + vertexStart, srcMesh->mColors[a].begin() + vertexStart + numVertices, dstMesh->mColors[a]);
  195. }
  196. }
  197. // create faces. Due to the fact that each face uses unique vertices, we can simply count up on each vertex
  198. size_t vertex = 0;
  199. dstMesh->mNumFaces = submesh.mNumFaces;
  200. dstMesh->mFaces = new aiFace[dstMesh->mNumFaces];
  201. for( size_t a = 0; a < dstMesh->mNumFaces; ++a)
  202. {
  203. size_t s = srcMesh->mFaceSize[ faceStart + a];
  204. aiFace& face = dstMesh->mFaces[a];
  205. face.mNumIndices = s;
  206. face.mIndices = new unsigned int[s];
  207. for( size_t b = 0; b < s; ++b)
  208. face.mIndices[b] = vertex++;
  209. }
  210. // store the mesh, and store its new index in the node
  211. newMeshRefs.push_back( mMeshes.size());
  212. mMeshIndexByID[index] = mMeshes.size();
  213. mMeshes.push_back( dstMesh);
  214. vertexStart += numVertices; faceStart += submesh.mNumFaces;
  215. // assign the material index
  216. std::map<std::string, size_t>::const_iterator matIt = mMaterialIndexByName.find( meshMaterial);
  217. if( matIt != mMaterialIndexByName.end())
  218. dstMesh->mMaterialIndex = matIt->second;
  219. else
  220. dstMesh->mMaterialIndex = 0;
  221. }
  222. }
  223. }
  224. // now place all mesh references we gathered in the target node
  225. pTarget->mNumMeshes = newMeshRefs.size();
  226. if( newMeshRefs.size())
  227. {
  228. pTarget->mMeshes = new unsigned int[pTarget->mNumMeshes];
  229. std::copy( newMeshRefs.begin(), newMeshRefs.end(), pTarget->mMeshes);
  230. }
  231. }
  232. // ------------------------------------------------------------------------------------------------
  233. // Stores all meshes in the given scene
  234. void ColladaLoader::StoreSceneMeshes( aiScene* pScene)
  235. {
  236. pScene->mNumMeshes = mMeshes.size();
  237. if( mMeshes.size() > 0)
  238. {
  239. pScene->mMeshes = new aiMesh*[mMeshes.size()];
  240. std::copy( mMeshes.begin(), mMeshes.end(), pScene->mMeshes);
  241. }
  242. }
  243. // ------------------------------------------------------------------------------------------------
  244. // Constructs materials from the collada material definitions
  245. void ColladaLoader::BuildMaterials( const ColladaParser& pParser, aiScene* pScene)
  246. {
  247. std::vector<aiMaterial*> newMats;
  248. for( ColladaParser::MaterialLibrary::const_iterator matIt = pParser.mMaterialLibrary.begin(); matIt != pParser.mMaterialLibrary.end(); ++matIt)
  249. {
  250. const Collada::Material& material = matIt->second;
  251. // a material is only a reference to an effect
  252. ColladaParser::EffectLibrary::const_iterator effIt = pParser.mEffectLibrary.find( material.mEffect);
  253. if( effIt == pParser.mEffectLibrary.end())
  254. continue;
  255. const Collada::Effect& effect = effIt->second;
  256. // create material
  257. Assimp::MaterialHelper* mat = new Assimp::MaterialHelper;
  258. aiString name( matIt->first);
  259. mat->AddProperty( &name, AI_MATKEY_NAME);
  260. int shadeMode;
  261. switch( effect.mShadeType)
  262. {
  263. case Collada::Shade_Constant: shadeMode = aiShadingMode_NoShading; break;
  264. case Collada::Shade_Lambert: shadeMode = aiShadingMode_Gouraud; break;
  265. case Collada::Shade_Blinn: shadeMode = aiShadingMode_Blinn; break;
  266. default: shadeMode = aiShadingMode_Phong; break;
  267. }
  268. mat->AddProperty<int>( &shadeMode, 1, AI_MATKEY_SHADING_MODEL);
  269. mat->AddProperty( &effect.mAmbient, 1, AI_MATKEY_COLOR_AMBIENT);
  270. mat->AddProperty( &effect.mDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  271. mat->AddProperty( &effect.mSpecular, 1, AI_MATKEY_COLOR_SPECULAR);
  272. mat->AddProperty( &effect.mEmissive, 1, AI_MATKEY_COLOR_EMISSIVE);
  273. mat->AddProperty( &effect.mShininess, 1, AI_MATKEY_SHININESS);
  274. mat->AddProperty( &effect.mRefractIndex, 1, AI_MATKEY_REFRACTI);
  275. // add textures, if given
  276. if( !effect.mTexAmbient.empty())
  277. mat->AddProperty( &FindFilenameForEffectTexture( pParser, effect, effect.mTexAmbient), AI_MATKEY_TEXTURE_AMBIENT( 0));
  278. if( !effect.mTexDiffuse.empty())
  279. mat->AddProperty( &FindFilenameForEffectTexture( pParser, effect, effect.mTexDiffuse), AI_MATKEY_TEXTURE_DIFFUSE( 0));
  280. if( !effect.mTexEmissive.empty())
  281. mat->AddProperty( &FindFilenameForEffectTexture( pParser, effect, effect.mTexEmissive), AI_MATKEY_TEXTURE_EMISSIVE( 0));
  282. if( !effect.mTexSpecular.empty())
  283. mat->AddProperty( &FindFilenameForEffectTexture( pParser, effect, effect.mTexSpecular), AI_MATKEY_TEXTURE_SPECULAR( 0));
  284. // store the material
  285. mMaterialIndexByName[matIt->first] = newMats.size();
  286. newMats.push_back( mat);
  287. }
  288. // store a dummy material if none were given
  289. if( newMats.size() == 0)
  290. {
  291. Assimp::MaterialHelper* mat = new Assimp::MaterialHelper;
  292. aiString name( std::string( "dummy"));
  293. mat->AddProperty( &name, AI_MATKEY_NAME);
  294. int shadeMode = aiShadingMode_Phong;
  295. mat->AddProperty<int>( &shadeMode, 1, AI_MATKEY_SHADING_MODEL);
  296. 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);
  297. mat->AddProperty( &colAmbient, 1, AI_MATKEY_COLOR_AMBIENT);
  298. mat->AddProperty( &colDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  299. mat->AddProperty( &colSpecular, 1, AI_MATKEY_COLOR_SPECULAR);
  300. float specExp = 5.0f;
  301. mat->AddProperty( &specExp, 1, AI_MATKEY_SHININESS);
  302. }
  303. // store the materials in the scene
  304. pScene->mNumMaterials = newMats.size();
  305. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials];
  306. std::copy( newMats.begin(), newMats.end(), pScene->mMaterials);
  307. }
  308. // ------------------------------------------------------------------------------------------------
  309. // Resolves the texture name for the given effect texture entry
  310. const aiString& ColladaLoader::FindFilenameForEffectTexture( const ColladaParser& pParser, const Collada::Effect& pEffect, const std::string& pName)
  311. {
  312. // recurse through the param references until we end up at an image
  313. std::string name = pName;
  314. while( 1)
  315. {
  316. // the given string is a param entry. Find it
  317. Collada::Effect::ParamLibrary::const_iterator it = pEffect.mParams.find( name);
  318. // if not found, we're at the end of the recursion. The resulting string should be the image ID
  319. if( it == pEffect.mParams.end())
  320. break;
  321. // else recurse on
  322. name = it->second.mReference;
  323. }
  324. // find the image referred by this name in the image library of the scene
  325. ColladaParser::ImageLibrary::const_iterator imIt = pParser.mImageLibrary.find( name);
  326. if( imIt == pParser.mImageLibrary.end())
  327. throw new ImportErrorException( boost::str( boost::format( "Unable to resolve effect texture entry \"%s\", ended up at ID \"%s\".") % pName % name));
  328. static aiString result;
  329. result.Set( imIt->second.mFileName);
  330. return result;
  331. }