ColladaLoader.cpp 16 KB

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