ObjFileImporter.cpp 16 KB

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