ObjFileImporter.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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. if(!checkSig) //Check File Extension
  67. {
  68. return SimpleExtensionCheck(pFile,"obj");
  69. }
  70. else //Check file Header
  71. {
  72. const char* tokens[] = {"mtllib","usemtl","vt ","vn ","o "};
  73. return BaseImporter::SearchFileHeaderForToken(pIOHandler, pFile, tokens, 5);
  74. }
  75. }
  76. // ------------------------------------------------------------------------------------------------
  77. // Obj-file import implementation
  78. void ObjFileImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  79. {
  80. DefaultIOSystem io;
  81. // Read file into memory
  82. const std::string mode = "rb";
  83. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, mode));
  84. if (NULL == file.get())
  85. throw new ImportErrorException( "Failed to open file " + pFile + ".");
  86. // Get the filesize and vaslidate it, throwing an exception when failes
  87. size_t fileSize = file->FileSize();
  88. if( fileSize < 16)
  89. throw new ImportErrorException( "OBJ-file is too small.");
  90. // Allocate buffer and read file into it
  91. TextFileToBuffer(file.get(),m_Buffer);
  92. //
  93. std::string strModelName;
  94. std::string::size_type pos = pFile.find_last_of( "\\/" );
  95. if ( pos != std::string::npos ) {
  96. strModelName = pFile.substr(pos+1, pFile.size() - pos - 1);
  97. }
  98. else
  99. {
  100. strModelName = pFile;
  101. }
  102. // parse the file into a temporary representation
  103. ObjFileParser parser(m_Buffer, strModelName, pIOHandler);
  104. // And create the proper return structures out of it
  105. CreateDataFromImport(parser.GetModel(), pScene);
  106. // Clean up allocated storage for the next import
  107. m_Buffer.clear();
  108. }
  109. // ------------------------------------------------------------------------------------------------
  110. // Create the data from parsed obj-file
  111. void ObjFileImporter::CreateDataFromImport(const ObjFile::Model* pModel, aiScene* pScene)
  112. {
  113. if (0L == pModel)
  114. return;
  115. // Create the root node of the scene
  116. pScene->mRootNode = new aiNode();
  117. if (!pModel->m_ModelName.empty())
  118. {
  119. // Set the name of the scene
  120. pScene->mRootNode->mName.Set(pModel->m_ModelName);
  121. }
  122. else
  123. {
  124. // This is an error, so break down the application
  125. ai_assert (false);
  126. }
  127. // Create nodes for the whole scene
  128. std::vector<aiMesh*> MeshArray;
  129. for (size_t index = 0; index < pModel->m_Objects.size(); index++)
  130. {
  131. createNodes(pModel, pModel->m_Objects[ index ], index, pScene->mRootNode, pScene, MeshArray);
  132. }
  133. // Create mesh pointer buffer for this scene
  134. if (pScene->mNumMeshes > 0)
  135. {
  136. pScene->mMeshes = new aiMesh*[ MeshArray.size() ];
  137. for (size_t index =0; index < MeshArray.size(); index++)
  138. {
  139. pScene->mMeshes [ index ] = MeshArray[ index ];
  140. }
  141. }
  142. // Create all materials
  143. for (size_t index = 0; index < pModel->m_Objects.size(); index++)
  144. {
  145. createMaterial( pModel, pModel->m_Objects[ index ], pScene );
  146. }
  147. }
  148. // ------------------------------------------------------------------------------------------------
  149. // Creates all nodes of the model
  150. aiNode *ObjFileImporter::createNodes(const ObjFile::Model* pModel, const ObjFile::Object* pData,
  151. unsigned int uiMeshIndex,
  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. createTopology( pModel, pData, uiMeshIndex, pMesh );
  167. if (pMesh->mNumVertices > 0) {
  168. MeshArray.push_back( pMesh );
  169. }
  170. }
  171. // Create all nodes from the subobjects stored in the current object
  172. if (!pData->m_SubObjects.empty())
  173. {
  174. pNode->mNumChildren = (unsigned int)pData->m_SubObjects.size();
  175. pNode->mChildren = new aiNode*[pData->m_SubObjects.size()];
  176. pNode->mNumMeshes = 1;
  177. pNode->mMeshes = new unsigned int[1];
  178. // Loop over all child objects, TODO
  179. /*for (size_t index = 0; index < pData->m_SubObjects.size(); index++)
  180. {
  181. // Create all child nodes
  182. pNode->mChildren[ index ] = createNodes( pModel, pData, pNode, pScene, MeshArray );
  183. for (unsigned int meshIndex = 0; meshIndex < pData->m_SubObjects[ index ]->m_Meshes.size(); meshIndex++)
  184. {
  185. pMesh = new aiMesh();
  186. MeshArray.push_back( pMesh );
  187. createTopology( pModel, pData, meshIndex, pMesh );
  188. }
  189. // Create material of this object
  190. createMaterial(pModel, pData->m_SubObjects[ index ], pScene);
  191. }*/
  192. }
  193. // Set mesh instances into scene- and node-instances
  194. const size_t meshSizeDiff = MeshArray.size()- oldMeshSize;
  195. if ( meshSizeDiff > 0 )
  196. {
  197. pNode->mMeshes = new unsigned int[ meshSizeDiff ];
  198. pNode->mNumMeshes = (unsigned int)meshSizeDiff;
  199. size_t index = 0;
  200. for (size_t i = oldMeshSize; i < MeshArray.size(); i++)
  201. {
  202. pNode->mMeshes[ index ] = pScene->mNumMeshes;
  203. pScene->mNumMeshes++;
  204. index++;
  205. }
  206. }
  207. return pNode;
  208. }
  209. // ------------------------------------------------------------------------------------------------
  210. // Create topology data
  211. void ObjFileImporter::createTopology(const ObjFile::Model* pModel,
  212. const ObjFile::Object* pData,
  213. unsigned int uiMeshIndex,
  214. aiMesh* pMesh )
  215. {
  216. // Checking preconditions
  217. ai_assert( NULL != pModel );
  218. if (NULL == pData)
  219. return;
  220. // Create faces
  221. ObjFile::Mesh *pObjMesh = pModel->m_Meshes[ uiMeshIndex ];
  222. ai_assert( NULL != pObjMesh );
  223. pMesh->mNumFaces = static_cast<unsigned int>( pObjMesh->m_Faces.size() );
  224. if ( pMesh->mNumFaces > 0 )
  225. {
  226. pMesh->mFaces = new aiFace[ pMesh->mNumFaces ];
  227. pMesh->mMaterialIndex = pObjMesh->m_uiMaterialIndex;
  228. // Copy all data from all stored meshes
  229. for (size_t index = 0; index < pObjMesh->m_Faces.size(); index++)
  230. {
  231. aiFace *pFace = &pMesh->mFaces[ index ];
  232. const unsigned int uiNumIndices = (unsigned int) pObjMesh->m_Faces[ index ]->m_pVertices->size();
  233. pFace->mNumIndices = (unsigned int) uiNumIndices;
  234. if (pFace->mNumIndices > 0)
  235. {
  236. pFace->mIndices = new unsigned int[ uiNumIndices ];
  237. ObjFile::Face::IndexArray *pIndexArray = pObjMesh->m_Faces[ index ]->m_pVertices;
  238. ai_assert ( NULL != pIndexArray );
  239. for ( size_t a=0; a<pFace->mNumIndices; a++ )
  240. {
  241. pFace->mIndices[ a ] = pIndexArray->at( a );
  242. }
  243. }
  244. else
  245. {
  246. pFace->mIndices = NULL;
  247. }
  248. }
  249. }
  250. // Create mesh vertices
  251. createVertexArray(pModel, pData, uiMeshIndex, pMesh);
  252. }
  253. // ------------------------------------------------------------------------------------------------
  254. // Creates a vretex array
  255. void ObjFileImporter::createVertexArray(const ObjFile::Model* pModel,
  256. const ObjFile::Object* pCurrentObject,
  257. unsigned int uiMeshIndex,
  258. aiMesh* pMesh)
  259. {
  260. // Checking preconditions
  261. ai_assert( NULL != pCurrentObject );
  262. // Break, if no faces are stored in object
  263. if (pCurrentObject->m_Faces.empty())
  264. return;
  265. // Get current mesh
  266. ObjFile::Mesh *pObjMesh = pModel->m_Meshes[ uiMeshIndex ];
  267. if ( NULL == pObjMesh || pObjMesh->m_uiNumIndices < 1)
  268. return;
  269. // Copy vertices of this mesh instance
  270. pMesh->mNumVertices = (unsigned int) pObjMesh->m_uiNumIndices;
  271. pMesh->mVertices = new aiVector3D[ pMesh->mNumVertices ];
  272. // Allocate buffer for normal vectors
  273. if ( !pModel->m_Normals.empty() && pObjMesh->m_hasNormals )
  274. pMesh->mNormals = new aiVector3D[ pMesh->mNumVertices ];
  275. // Allocate buffer for texture coordinates
  276. if ( !pModel->m_TextureCoord.empty() && pObjMesh->m_uiUVCoordinates[0] )
  277. {
  278. pMesh->mNumUVComponents[ 0 ] = 2;
  279. pMesh->mTextureCoords[ 0 ] = new aiVector3D[ pMesh->mNumVertices ];
  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 the 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. {
  370. case 0:
  371. sm = aiShadingMode_NoShading;
  372. break;
  373. case 1:
  374. sm = aiShadingMode_Gouraud;
  375. break;
  376. case 2:
  377. sm = aiShadingMode_Phong;
  378. break;
  379. default:
  380. sm = aiShadingMode_Gouraud;
  381. DefaultLogger::get()->error("OBJ/MTL: Unexpected illumination model (0-2 recognized)");
  382. }
  383. mat->AddProperty<int>( &sm, 1, AI_MATKEY_SHADING_MODEL);
  384. // multiplying the specular exponent with 2 seems to yield better results
  385. pCurrentMaterial->shineness *= 4.f;
  386. // Adding material colors
  387. mat->AddProperty( &pCurrentMaterial->ambient, 1, AI_MATKEY_COLOR_AMBIENT );
  388. mat->AddProperty( &pCurrentMaterial->diffuse, 1, AI_MATKEY_COLOR_DIFFUSE );
  389. mat->AddProperty( &pCurrentMaterial->specular, 1, AI_MATKEY_COLOR_SPECULAR );
  390. mat->AddProperty( &pCurrentMaterial->shineness, 1, AI_MATKEY_SHININESS );
  391. mat->AddProperty( &pCurrentMaterial->alpha, 1, AI_MATKEY_OPACITY );
  392. // Adding refraction index
  393. mat->AddProperty( &pCurrentMaterial->ior, 1, AI_MATKEY_REFRACTI );
  394. // Adding textures
  395. if ( 0 != pCurrentMaterial->texture.length )
  396. mat->AddProperty( &pCurrentMaterial->texture, AI_MATKEY_TEXTURE_DIFFUSE(0));
  397. if ( 0 != pCurrentMaterial->textureAmbient.length )
  398. mat->AddProperty( &pCurrentMaterial->textureAmbient, AI_MATKEY_TEXTURE_AMBIENT(0));
  399. if ( 0 != pCurrentMaterial->textureSpecular.length )
  400. mat->AddProperty( &pCurrentMaterial->textureSpecular, AI_MATKEY_TEXTURE_SPECULAR(0));
  401. if ( 0 != pCurrentMaterial->textureBump.length )
  402. mat->AddProperty( &pCurrentMaterial->textureBump, AI_MATKEY_TEXTURE_HEIGHT(0));
  403. if ( 0 != pCurrentMaterial->textureOpacity.length )
  404. mat->AddProperty( &pCurrentMaterial->textureOpacity, AI_MATKEY_TEXTURE_OPACITY(0));
  405. if ( 0 != pCurrentMaterial->textureSpecularity.length )
  406. mat->AddProperty( &pCurrentMaterial->textureSpecularity, AI_MATKEY_TEXTURE_SHININESS(0));
  407. // Store material property info in material array in scene
  408. pScene->mMaterials[ pScene->mNumMaterials ] = mat;
  409. pScene->mNumMaterials++;
  410. }
  411. // Test number of created materials.
  412. ai_assert( pScene->mNumMaterials == numMaterials );
  413. }
  414. // ------------------------------------------------------------------------------------------------
  415. // Appends this node to the parent node
  416. void ObjFileImporter::appendChildToParentNode(aiNode *pParent, aiNode *pChild)
  417. {
  418. // Checking preconditions
  419. ai_assert (NULL != pParent);
  420. ai_assert (NULL != pChild);
  421. // Assign parent to child
  422. pChild->mParent = pParent;
  423. size_t sNumChildren = 0;
  424. // If already children was assigned to the parent node, store them in a
  425. std::vector<aiNode*> temp;
  426. if (pParent->mChildren != NULL)
  427. {
  428. sNumChildren = pParent->mNumChildren;
  429. ai_assert (0 != sNumChildren);
  430. for (size_t index = 0; index < pParent->mNumChildren; index++)
  431. {
  432. temp.push_back(pParent->mChildren [ index ] );
  433. }
  434. delete [] pParent->mChildren;
  435. }
  436. // Copy node instances into parent node
  437. pParent->mNumChildren++;
  438. pParent->mChildren = new aiNode*[ pParent->mNumChildren ];
  439. for (size_t index = 0; index < pParent->mNumChildren-1; index++)
  440. {
  441. pParent->mChildren[ index ] = temp [ index ];
  442. }
  443. pParent->mChildren[ pParent->mNumChildren-1 ] = pChild;
  444. }
  445. // ------------------------------------------------------------------------------------------------
  446. } // Namespace Assimp
  447. #endif // !! ASSIMP_BUILD_NO_OBJ_IMPORTER