ObjFileImporter.cpp 17 KB

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