ObjFileImporter.cpp 17 KB

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