ObjFileImporter.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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. #include "ObjFileImporter.h"
  35. #include "ObjFileParser.h"
  36. #include "ObjFileData.h"
  37. #include "MaterialSystem.h"
  38. #include "../include/aiScene.h"
  39. #include "../include/aiAssert.h"
  40. #include "../include/DefaultLogger.h"
  41. #include "../include/IOStream.h"
  42. #include "../include/IOSystem.h"
  43. #include <boost/scoped_ptr.hpp>
  44. #include <boost/format.hpp>
  45. namespace Assimp
  46. {
  47. // ------------------------------------------------------------------------------------------------
  48. using namespace std;
  49. //! Obj-file-format extention
  50. const string ObjFileImporter::OBJ_EXT = "obj";
  51. // ------------------------------------------------------------------------------------------------
  52. // Default constructor
  53. ObjFileImporter::ObjFileImporter() :
  54. m_pRootObject(NULL),
  55. m_strAbsPath("\\")
  56. {
  57. }
  58. // ------------------------------------------------------------------------------------------------
  59. // Destructor
  60. ObjFileImporter::~ObjFileImporter()
  61. {
  62. // Release root object instance
  63. if (NULL != m_pRootObject)
  64. {
  65. delete m_pRootObject;
  66. m_pRootObject = NULL;
  67. }
  68. }
  69. // ------------------------------------------------------------------------------------------------
  70. // Returns true, fi file is an obj file
  71. bool ObjFileImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler) const
  72. {
  73. if (pFile.empty())
  74. return false;
  75. string::size_type pos = pFile.find_last_of(".");
  76. if (string::npos == pos)
  77. return false;
  78. const string ext = pFile.substr(pos+1, pFile.size() - pos - 1);
  79. if (ext == OBJ_EXT)
  80. return true;
  81. return false;
  82. }
  83. // ------------------------------------------------------------------------------------------------
  84. // Obj-file import implementation
  85. void ObjFileImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  86. {
  87. // Read file into memory
  88. const std::string mode = "rb";
  89. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, mode));
  90. if (NULL == file.get())
  91. throw new ImportErrorException( "Failed to open file " + pFile + ".");
  92. // Get the filesize and vaslidate it, throwing an exception when failes
  93. size_t fileSize = file->FileSize();
  94. if( fileSize < 16)
  95. throw new ImportErrorException( "OBJ-file is too small.");
  96. // Allocate buffer and read file into it
  97. m_Buffer.resize( fileSize );
  98. const size_t readsize = file->Read(&m_Buffer.front(), sizeof(char), fileSize);
  99. assert (readsize == fileSize);
  100. //
  101. std::string strDirectory("\\"), strModelName;
  102. std::string::size_type pos = pFile.find_last_of("\\");
  103. if (pos != std::string::npos)
  104. {
  105. strDirectory = pFile.substr(0, pos);
  106. strModelName = pFile.substr(pos+1, pFile.size() - pos - 1);
  107. }
  108. else
  109. {
  110. strModelName = pFile;
  111. }
  112. // parse the file into a temporary representation
  113. ObjFileParser parser(m_Buffer, strDirectory, strModelName);
  114. // And create the proper return structures out of it
  115. CreateDataFromImport(parser.GetModel(), pScene);
  116. }
  117. // ------------------------------------------------------------------------------------------------
  118. // Create the data from parsed obj-file
  119. void ObjFileImporter::CreateDataFromImport(const ObjFile::Model* pModel, aiScene* pScene)
  120. {
  121. if (0L == pModel)
  122. return;
  123. // Create the root node of the scene
  124. pScene->mRootNode = new aiNode();
  125. if (!pModel->m_ModelName.empty())
  126. {
  127. // Set the name of the scene
  128. pScene->mRootNode->mName.Set(pModel->m_ModelName);
  129. }
  130. else
  131. {
  132. // This is an error, so break down the application
  133. ai_assert (false);
  134. }
  135. // Create nodes for the whole scene
  136. std::vector<aiMesh*> MeshArray;
  137. for (size_t index = 0; index < pModel->m_Objects.size(); index++)
  138. {
  139. createNodes(pModel, pModel->m_Objects[ index ], pScene->mRootNode, pScene, MeshArray);
  140. }
  141. // Create mesh pointer buffer for this scene
  142. if (pScene->mNumMeshes > 0)
  143. {
  144. pScene->mMeshes = new aiMesh*[ MeshArray.size() ];
  145. for (size_t index =0; index < MeshArray.size(); index++)
  146. {
  147. pScene->mMeshes [ index ] = MeshArray[ index ];
  148. }
  149. }
  150. // Create all materials
  151. for (size_t index = 0; index < pModel->m_Objects.size(); index++)
  152. {
  153. createMaterial( pModel, pModel->m_Objects[ index ], pScene );
  154. }
  155. }
  156. // ------------------------------------------------------------------------------------------------
  157. // Creates all nodes of the model
  158. aiNode *ObjFileImporter::createNodes(const ObjFile::Model* pModel, const ObjFile::Object* pData,
  159. aiNode *pParent, aiScene* pScene,
  160. std::vector<aiMesh*> &MeshArray)
  161. {
  162. if (NULL == pData)
  163. return NULL;
  164. // Store older mesh size to be able to computate mesh offsets for new mesh instances
  165. size_t oldMeshSize = MeshArray.size();
  166. aiNode *pNode = new aiNode();
  167. if (pParent != NULL)
  168. this->appendChildToParentNode(pParent, pNode);
  169. aiMesh *pMesh = NULL;
  170. for (unsigned int meshIndex = 0; meshIndex < pModel->m_Meshes.size(); meshIndex++)
  171. {
  172. pMesh = new aiMesh();
  173. MeshArray.push_back( pMesh );
  174. createTopology( pModel, pData, meshIndex, pMesh );
  175. }
  176. // Create all nodes from the subobjects stored in the current object
  177. if (!pData->m_SubObjects.empty())
  178. {
  179. pNode->mNumChildren = (unsigned int)pData->m_SubObjects.size();
  180. pNode->mChildren = new aiNode*[pData->m_SubObjects.size()];
  181. pNode->mNumMeshes = 1;
  182. pNode->mMeshes = new unsigned int[1];
  183. // Loop over all child objects, TODO
  184. /*for (size_t index = 0; index < pData->m_SubObjects.size(); index++)
  185. {
  186. // Create all child nodes
  187. pNode->mChildren[ index ] = createNodes( pModel, pData, pNode, pScene, MeshArray );
  188. for (unsigned int meshIndex = 0; meshIndex < pData->m_SubObjects[ index ]->m_Meshes.size(); meshIndex++)
  189. {
  190. pMesh = new aiMesh();
  191. MeshArray.push_back( pMesh );
  192. createTopology( pModel, pData, meshIndex, pMesh );
  193. }
  194. // Create material of this object
  195. createMaterial(pModel, pData->m_SubObjects[ index ], pScene);
  196. }*/
  197. }
  198. // Set mesh instances into scene- and node-instances
  199. const size_t meshSizeDiff = MeshArray.size()- oldMeshSize;
  200. if ( meshSizeDiff > 0 )
  201. {
  202. pNode->mMeshes = new unsigned int[ meshSizeDiff ];
  203. pNode->mNumMeshes = (unsigned int)meshSizeDiff;
  204. size_t index = 0;
  205. for (size_t i = oldMeshSize; i < MeshArray.size(); i++)
  206. {
  207. pNode->mMeshes[ index ] = pScene->mNumMeshes;
  208. pScene->mNumMeshes++;
  209. index++;
  210. }
  211. }
  212. return pNode;
  213. }
  214. // ------------------------------------------------------------------------------------------------
  215. // Create topology data
  216. void ObjFileImporter::createTopology(const ObjFile::Model* pModel,
  217. const ObjFile::Object* pData,
  218. unsigned int uiMeshIndex,
  219. aiMesh* pMesh )
  220. {
  221. // Checking preconditions
  222. ai_assert( NULL != pModel );
  223. if (NULL == pData)
  224. return;
  225. // Create faces
  226. ObjFile::Mesh *pObjMesh = pModel->m_Meshes[ uiMeshIndex ];
  227. ai_assert( NULL != pObjMesh );
  228. pMesh->mNumFaces = static_cast<unsigned int>( pObjMesh->m_Faces.size() );
  229. if ( pMesh->mNumFaces > 0 )
  230. {
  231. pMesh->mFaces = new aiFace[ pMesh->mNumFaces ];
  232. pMesh->mMaterialIndex = pObjMesh->m_uiMaterialIndex;
  233. // Copy all data from all stored meshes
  234. for (size_t index = 0; index < pObjMesh->m_Faces.size(); index++)
  235. {
  236. aiFace *pFace = &pMesh->mFaces[ index ];
  237. const unsigned int uiNumIndices = (unsigned int) pObjMesh->m_Faces[ index ]->m_pVertices->size();
  238. pFace->mNumIndices = (unsigned int) uiNumIndices;
  239. if (pFace->mNumIndices > 0)
  240. {
  241. pFace->mIndices = new unsigned int[ uiNumIndices ];
  242. ObjFile::Face::IndexArray *pIndexArray = pObjMesh->m_Faces[ index ]->m_pVertices;
  243. ai_assert ( NULL != pIndexArray );
  244. for ( size_t a=0; a<pFace->mNumIndices; a++ )
  245. {
  246. pFace->mIndices[ a ] = pIndexArray->at( a );
  247. }
  248. }
  249. else
  250. {
  251. pFace->mIndices = NULL;
  252. }
  253. }
  254. }
  255. // Create mesh vertices
  256. createVertexArray(pModel, pData, uiMeshIndex, pMesh);
  257. }
  258. // ------------------------------------------------------------------------------------------------
  259. // Creates a vretex array
  260. void ObjFileImporter::createVertexArray(const ObjFile::Model* pModel,
  261. const ObjFile::Object* pCurrentObject,
  262. unsigned int uiMeshIndex,
  263. aiMesh* pMesh)
  264. {
  265. // Checking preconditions
  266. ai_assert( NULL != pCurrentObject );
  267. // Break, if no faces are stored in object
  268. if (pCurrentObject->m_Faces.empty())
  269. return;
  270. // Get current mesh
  271. ObjFile::Mesh *pObjMesh = pModel->m_Meshes[ uiMeshIndex ];
  272. if ( NULL == pObjMesh )
  273. return;
  274. // Copy vertices of this mesh instance
  275. pMesh->mNumVertices = (unsigned int) pObjMesh->m_uiNumIndices;
  276. pMesh->mVertices = new aiVector3D[ pMesh->mNumVertices ];
  277. // Allocate buffer for normal vectors
  278. if ( !pModel->m_Normals.empty() )
  279. pMesh->mNormals = new aiVector3D[ pMesh->mNumVertices ];
  280. // Allocate buffer for texture coordinates
  281. if ( !pModel->m_TextureCoord.empty() )
  282. {
  283. for ( size_t i=0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; i++ )
  284. {
  285. const unsigned int num_uv = pObjMesh->m_uiUVCoordinates[ i ];
  286. if ( num_uv > 0 )
  287. {
  288. pMesh->mNumUVComponents[ i ] = num_uv;
  289. pMesh->mTextureCoords[ i ] = new aiVector3D[ num_uv ];
  290. }
  291. }
  292. }
  293. // Copy vertices, normals and textures into aiMesh instance
  294. unsigned int newIndex = 0;
  295. for ( size_t index=0; index < pObjMesh->m_Faces.size(); index++ )
  296. {
  297. // Get destination face
  298. aiFace *pDestFace = &pMesh->mFaces[ index ];
  299. // Get source face
  300. ObjFile::Face *pSourceFace = pObjMesh->m_Faces[ index ];
  301. // Copy all index arrays
  302. for ( size_t vertexIndex = 0; vertexIndex < pSourceFace->m_pVertices->size(); vertexIndex++ )
  303. {
  304. unsigned int vertex = pSourceFace->m_pVertices->at( vertexIndex );
  305. assert ( vertex < pModel->m_Vertices.size() );
  306. pMesh->mVertices[ newIndex ] = *pModel->m_Vertices[ vertex ];
  307. // Copy all normals
  308. if ( !pSourceFace->m_pNormals->empty() )
  309. {
  310. const unsigned int normal = pSourceFace->m_pNormals->at( vertexIndex );
  311. ai_assert( normal < pModel->m_Normals.size() );
  312. pMesh->mNormals[ newIndex ] = *pModel->m_Normals[ normal ];
  313. }
  314. // Copy all texture coordinates
  315. if ( !pModel->m_TextureCoord.empty() )
  316. {
  317. if ( !pSourceFace->m_pTexturCoords->empty() )
  318. {
  319. const unsigned int tex = pSourceFace->m_pTexturCoords->at( vertexIndex );
  320. ai_assert( tex < pModel->m_TextureCoord.size() );
  321. for ( size_t i=0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; i++)
  322. {
  323. if ( pMesh->mNumUVComponents[ i ] > 0 )
  324. {
  325. aiVector2D coord2d = *pModel->m_TextureCoord[ tex ];
  326. pMesh->mTextureCoords[ i ][ newIndex ] = aiVector3D( coord2d.x, coord2d.y, 0.0 );
  327. }
  328. }
  329. }
  330. }
  331. ai_assert( pMesh->mNumVertices > newIndex );
  332. pDestFace->mIndices[ vertexIndex ] = newIndex;
  333. ++newIndex;
  334. }
  335. }
  336. }
  337. // ------------------------------------------------------------------------------------------------
  338. // Counts all stored meshes
  339. void ObjFileImporter::countObjects(const std::vector<ObjFile::Object*> &rObjects, int &iNumMeshes)
  340. {
  341. iNumMeshes = 0;
  342. if (rObjects.empty())
  343. return;
  344. iNumMeshes += (unsigned int)rObjects.size();
  345. for (std::vector<ObjFile::Object*>::const_iterator it = rObjects.begin();
  346. it != rObjects.end();
  347. ++it)
  348. {
  349. if (!(*it)->m_SubObjects.empty())
  350. {
  351. countObjects((*it)->m_SubObjects, iNumMeshes);
  352. }
  353. }
  354. }
  355. // ------------------------------------------------------------------------------------------------
  356. // Creates tha material
  357. void ObjFileImporter::createMaterial(const ObjFile::Model* pModel, const ObjFile::Object* pData,
  358. aiScene* pScene)
  359. {
  360. ai_assert (NULL != pScene);
  361. if (NULL == pData)
  362. return;
  363. const unsigned int numMaterials = (unsigned int) pModel->m_MaterialLib.size();
  364. pScene->mNumMaterials = 0;
  365. if ( pModel->m_MaterialLib.empty() )
  366. return;
  367. pScene->mMaterials = new aiMaterial*[ numMaterials ];
  368. for ( unsigned int matIndex = 0; matIndex < numMaterials; matIndex++ )
  369. {
  370. Assimp::MaterialHelper* mat = new Assimp::MaterialHelper();
  371. // Store material name
  372. std::map<std::string, ObjFile::Material*>::const_iterator it = pModel->m_MaterialMap.find( pModel->m_MaterialLib[ matIndex ] );
  373. // No material found, use the default material
  374. if ( pModel->m_MaterialMap.end() == it)
  375. continue;
  376. ObjFile::Material *pCurrentMaterial = (*it).second;
  377. mat->AddProperty( &pCurrentMaterial->MaterialName, AI_MATKEY_NAME );
  378. mat->AddProperty<int>( &pCurrentMaterial->illumination_model, 1, AI_MATKEY_SHADING_MODEL);
  379. // Adding material colors
  380. mat->AddProperty( &pCurrentMaterial->ambient, 1, AI_MATKEY_COLOR_AMBIENT );
  381. mat->AddProperty( &pCurrentMaterial->diffuse, 1, AI_MATKEY_COLOR_DIFFUSE );
  382. mat->AddProperty( &pCurrentMaterial->specular, 1, AI_MATKEY_COLOR_SPECULAR );
  383. mat->AddProperty( &pCurrentMaterial->shineness, 1, AI_MATKEY_SHININESS );
  384. // Adding textures
  385. if ( 0 != pCurrentMaterial->texture.length )
  386. mat->AddProperty( &pCurrentMaterial->texture, AI_MATKEY_TEXTURE_DIFFUSE(0));
  387. // Store material property info in material array in scene
  388. pScene->mMaterials[ pScene->mNumMaterials ] = mat;
  389. pScene->mNumMaterials++;
  390. }
  391. // Test number of created materials.
  392. ai_assert( pScene->mNumMaterials == numMaterials );
  393. }
  394. // ------------------------------------------------------------------------------------------------
  395. // Appends this node to the parent node
  396. void ObjFileImporter::appendChildToParentNode(aiNode *pParent, aiNode *pChild)
  397. {
  398. // Checking preconditions
  399. ai_assert (NULL != pParent);
  400. ai_assert (NULL != pChild);
  401. // Assign parent to child
  402. pChild->mParent = pParent;
  403. size_t sNumChildren = 0;
  404. // If already children was assigned to the parent node, store them in a
  405. std::vector<aiNode*> temp;
  406. if (pParent->mChildren != NULL)
  407. {
  408. sNumChildren = pParent->mNumChildren;
  409. ai_assert (0 != sNumChildren);
  410. for (size_t index = 0; index < pParent->mNumChildren; index++)
  411. {
  412. temp.push_back(pParent->mChildren [ index ] );
  413. }
  414. delete [] pParent->mChildren;
  415. }
  416. // Copy node instances into parent node
  417. pParent->mNumChildren++;
  418. pParent->mChildren = new aiNode*[ pParent->mNumChildren ];
  419. for (size_t index = 0; index < pParent->mNumChildren-1; index++)
  420. {
  421. pParent->mChildren[ index ] = temp [ index ];
  422. }
  423. pParent->mChildren[ pParent->mNumChildren-1 ] = pChild;
  424. }
  425. // ------------------------------------------------------------------------------------------------
  426. } // Namespace Assimp