ObjFileImporter.cpp 17 KB

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