ObjFileImporter.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2016, assimp 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 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. #ifndef ASSIMP_BUILD_NO_OBJ_IMPORTER
  35. #include "DefaultIOSystem.h"
  36. #include "ObjFileImporter.h"
  37. #include "ObjFileParser.h"
  38. #include "ObjFileData.h"
  39. #include <boost/scoped_ptr.hpp>
  40. #include <assimp/Importer.hpp>
  41. #include <assimp/scene.h>
  42. #include <assimp/ai_assert.h>
  43. #include <assimp/DefaultLogger.hpp>
  44. static const aiImporterDesc desc = {
  45. "Wavefront Object Importer",
  46. "",
  47. "",
  48. "surfaces not supported",
  49. aiImporterFlags_SupportTextFlavour,
  50. 0,
  51. 0,
  52. 0,
  53. 0,
  54. "obj"
  55. };
  56. static const unsigned int ObjMinSize = 16;
  57. namespace Assimp {
  58. using namespace std;
  59. // ------------------------------------------------------------------------------------------------
  60. // Default constructor
  61. ObjFileImporter::ObjFileImporter() :
  62. m_Buffer(),
  63. m_pRootObject( NULL ),
  64. m_strAbsPath( "" )
  65. {
  66. DefaultIOSystem io;
  67. m_strAbsPath = io.getOsSeparator();
  68. }
  69. // ------------------------------------------------------------------------------------------------
  70. // Destructor.
  71. ObjFileImporter::~ObjFileImporter()
  72. {
  73. delete m_pRootObject;
  74. m_pRootObject = NULL;
  75. }
  76. // ------------------------------------------------------------------------------------------------
  77. // Returns true, if file is an obj file.
  78. bool ObjFileImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler , bool checkSig ) const
  79. {
  80. if(!checkSig) //Check File Extension
  81. {
  82. return SimpleExtensionCheck(pFile,"obj");
  83. }
  84. else //Check file Header
  85. {
  86. static const char *pTokens[] = { "mtllib", "usemtl", "v ", "vt ", "vn ", "o ", "g ", "s ", "f " };
  87. return BaseImporter::SearchFileHeaderForToken(pIOHandler, pFile, pTokens, 9 );
  88. }
  89. }
  90. // ------------------------------------------------------------------------------------------------
  91. const aiImporterDesc* ObjFileImporter::GetInfo () const
  92. {
  93. return &desc;
  94. }
  95. // ------------------------------------------------------------------------------------------------
  96. // Obj-file import implementation
  97. void ObjFileImporter::InternReadFile( const std::string &file, aiScene* pScene, IOSystem* pIOHandler) {
  98. // Read file into memory
  99. static const std::string mode = "rb";
  100. boost::scoped_ptr<IOStream> fileStream( pIOHandler->Open( file, mode));
  101. if( !fileStream.get() ) {
  102. throw DeadlyImportError( "Failed to open file " + file + "." );
  103. }
  104. // Get the file-size and validate it, throwing an exception when fails
  105. size_t fileSize = fileStream->FileSize();
  106. if( fileSize < ObjMinSize ) {
  107. throw DeadlyImportError( "OBJ-file is too small.");
  108. }
  109. // Allocate buffer and read file into it
  110. TextFileToBuffer( fileStream.get(),m_Buffer);
  111. // Get the model name
  112. std::string modelName, folderName;
  113. std::string::size_type pos = file.find_last_of( "\\/" );
  114. if ( pos != std::string::npos ) {
  115. modelName = file.substr(pos+1, file.size() - pos - 1);
  116. folderName = file.substr( 0, pos );
  117. if ( !folderName.empty() ) {
  118. pIOHandler->PushDirectory( folderName );
  119. }
  120. } else {
  121. modelName = file;
  122. }
  123. // This next stage takes ~ 1/3th of the total readFile task
  124. // so should amount for 1/3th of the progress
  125. // only update every 100KB or it'll be too slow
  126. unsigned int progress = 0;
  127. unsigned int progressCounter = 0;
  128. const unsigned int updateProgressEveryBytes = 100 * 1024;
  129. const unsigned int progressTotal = (3*m_Buffer.size()/updateProgressEveryBytes);
  130. // process all '\'
  131. std::vector<char> ::iterator iter = m_Buffer.begin();
  132. while (iter != m_Buffer.end())
  133. {
  134. if (*iter == '\\')
  135. {
  136. // remove '\'
  137. iter = m_Buffer.erase(iter);
  138. // remove next character
  139. while (*iter == '\r' || *iter == '\n')
  140. iter = m_Buffer.erase(iter);
  141. }
  142. else
  143. ++iter;
  144. if (++progressCounter >= updateProgressEveryBytes)
  145. {
  146. m_progress->UpdateFileRead(++progress, progressTotal);
  147. progressCounter = 0;
  148. }
  149. }
  150. // 1/3rd progress
  151. m_progress->UpdateFileRead(1, 3);
  152. // parse the file into a temporary representation
  153. ObjFileParser parser(m_Buffer, modelName, pIOHandler, m_progress, file);
  154. // And create the proper return structures out of it
  155. CreateDataFromImport(parser.GetModel(), pScene);
  156. // Clean up allocated storage for the next import
  157. m_Buffer.clear();
  158. // Pop directory stack
  159. if ( pIOHandler->StackSize() > 0 ) {
  160. pIOHandler->PopDirectory();
  161. }
  162. }
  163. // ------------------------------------------------------------------------------------------------
  164. // Create the data from parsed obj-file
  165. void ObjFileImporter::CreateDataFromImport(const ObjFile::Model* pModel, aiScene* pScene) {
  166. if( 0L == pModel ) {
  167. return;
  168. }
  169. // Create the root node of the scene
  170. pScene->mRootNode = new aiNode;
  171. if ( !pModel->m_ModelName.empty() )
  172. {
  173. // Set the name of the scene
  174. pScene->mRootNode->mName.Set(pModel->m_ModelName);
  175. }
  176. else
  177. {
  178. // This is a fatal error, so break down the application
  179. ai_assert(false);
  180. }
  181. // Create nodes for the whole scene
  182. std::vector<aiMesh*> MeshArray;
  183. for (size_t index = 0; index < pModel->m_Objects.size(); index++)
  184. {
  185. createNodes(pModel, pModel->m_Objects[ index ], pScene->mRootNode, pScene, MeshArray);
  186. }
  187. // Create mesh pointer buffer for this scene
  188. if (pScene->mNumMeshes > 0)
  189. {
  190. pScene->mMeshes = new aiMesh*[ MeshArray.size() ];
  191. for (size_t index =0; index < MeshArray.size(); index++)
  192. {
  193. pScene->mMeshes[ index ] = MeshArray[ index ];
  194. }
  195. }
  196. // Create all materials
  197. createMaterials( pModel, pScene );
  198. }
  199. // ------------------------------------------------------------------------------------------------
  200. // Creates all nodes of the model
  201. aiNode *ObjFileImporter::createNodes(const ObjFile::Model* pModel, const ObjFile::Object* pObject,
  202. aiNode *pParent, aiScene* pScene,
  203. std::vector<aiMesh*> &MeshArray )
  204. {
  205. ai_assert( NULL != pModel );
  206. if( NULL == pObject ) {
  207. return NULL;
  208. }
  209. // Store older mesh size to be able to computes mesh offsets for new mesh instances
  210. const size_t oldMeshSize = MeshArray.size();
  211. aiNode *pNode = new aiNode;
  212. pNode->mName = pObject->m_strObjName;
  213. // If we have a parent node, store it
  214. if( pParent != NULL ) {
  215. appendChildToParentNode( pParent, pNode );
  216. }
  217. for ( size_t i=0; i< pObject->m_Meshes.size(); i++ )
  218. {
  219. unsigned int meshId = pObject->m_Meshes[ i ];
  220. aiMesh *pMesh = createTopology( pModel, pObject, meshId );
  221. if( pMesh && pMesh->mNumFaces > 0 ) {
  222. MeshArray.push_back( pMesh );
  223. }
  224. }
  225. // Create all nodes from the sub-objects stored in the current object
  226. if ( !pObject->m_SubObjects.empty() )
  227. {
  228. size_t numChilds = pObject->m_SubObjects.size();
  229. pNode->mNumChildren = static_cast<unsigned int>( numChilds );
  230. pNode->mChildren = new aiNode*[ numChilds ];
  231. pNode->mNumMeshes = 1;
  232. pNode->mMeshes = new unsigned int[ 1 ];
  233. }
  234. // Set mesh instances into scene- and node-instances
  235. const size_t meshSizeDiff = MeshArray.size()- oldMeshSize;
  236. if ( meshSizeDiff > 0 )
  237. {
  238. pNode->mMeshes = new unsigned int[ meshSizeDiff ];
  239. pNode->mNumMeshes = static_cast<unsigned int>( meshSizeDiff );
  240. size_t index = 0;
  241. for (size_t i = oldMeshSize; i < MeshArray.size(); i++)
  242. {
  243. pNode->mMeshes[ index ] = pScene->mNumMeshes;
  244. pScene->mNumMeshes++;
  245. index++;
  246. }
  247. }
  248. return pNode;
  249. }
  250. // ------------------------------------------------------------------------------------------------
  251. // Create topology data
  252. aiMesh *ObjFileImporter::createTopology( const ObjFile::Model* pModel, const ObjFile::Object* pData,
  253. unsigned int meshIndex )
  254. {
  255. // Checking preconditions
  256. ai_assert( NULL != pModel );
  257. if( NULL == pData ) {
  258. return NULL;
  259. }
  260. // Create faces
  261. ObjFile::Mesh *pObjMesh = pModel->m_Meshes[ meshIndex ];
  262. if( !pObjMesh ) {
  263. return NULL;
  264. }
  265. if( pObjMesh->m_Faces.empty() ) {
  266. return NULL;
  267. }
  268. aiMesh* pMesh = new aiMesh;
  269. if( !pObjMesh->m_name.empty() ) {
  270. pMesh->mName.Set( pObjMesh->m_name );
  271. }
  272. for (size_t index = 0; index < pObjMesh->m_Faces.size(); index++)
  273. {
  274. ObjFile::Face *const inp = pObjMesh->m_Faces[ index ];
  275. ai_assert( NULL != inp );
  276. if (inp->m_PrimitiveType == aiPrimitiveType_LINE) {
  277. pMesh->mNumFaces += inp->m_pVertices->size() - 1;
  278. pMesh->mPrimitiveTypes |= aiPrimitiveType_LINE;
  279. } else if (inp->m_PrimitiveType == aiPrimitiveType_POINT) {
  280. pMesh->mNumFaces += inp->m_pVertices->size();
  281. pMesh->mPrimitiveTypes |= aiPrimitiveType_POINT;
  282. } else {
  283. ++pMesh->mNumFaces;
  284. if (inp->m_pVertices->size() > 3) {
  285. pMesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  286. } else {
  287. pMesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  288. }
  289. }
  290. }
  291. unsigned int uiIdxCount( 0u );
  292. if ( pMesh->mNumFaces > 0 ) {
  293. pMesh->mFaces = new aiFace[ pMesh->mNumFaces ];
  294. if ( pObjMesh->m_uiMaterialIndex != ObjFile::Mesh::NoMaterial ) {
  295. pMesh->mMaterialIndex = pObjMesh->m_uiMaterialIndex;
  296. }
  297. unsigned int outIndex( 0 );
  298. // Copy all data from all stored meshes
  299. for (size_t index = 0; index < pObjMesh->m_Faces.size(); index++) {
  300. ObjFile::Face* const inp = pObjMesh->m_Faces[ index ];
  301. if (inp->m_PrimitiveType == aiPrimitiveType_LINE) {
  302. for(size_t i = 0; i < inp->m_pVertices->size() - 1; ++i) {
  303. aiFace& f = pMesh->mFaces[ outIndex++ ];
  304. uiIdxCount += f.mNumIndices = 2;
  305. f.mIndices = new unsigned int[2];
  306. }
  307. continue;
  308. }
  309. else if (inp->m_PrimitiveType == aiPrimitiveType_POINT) {
  310. for(size_t i = 0; i < inp->m_pVertices->size(); ++i) {
  311. aiFace& f = pMesh->mFaces[ outIndex++ ];
  312. uiIdxCount += f.mNumIndices = 1;
  313. f.mIndices = new unsigned int[1];
  314. }
  315. continue;
  316. }
  317. aiFace *pFace = &pMesh->mFaces[ outIndex++ ];
  318. const unsigned int uiNumIndices = (unsigned int) pObjMesh->m_Faces[ index ]->m_pVertices->size();
  319. uiIdxCount += pFace->mNumIndices = (unsigned int) uiNumIndices;
  320. if (pFace->mNumIndices > 0) {
  321. pFace->mIndices = new unsigned int[ uiNumIndices ];
  322. }
  323. }
  324. }
  325. // Create mesh vertices
  326. createVertexArray(pModel, pData, meshIndex, pMesh, uiIdxCount);
  327. return pMesh;
  328. }
  329. // ------------------------------------------------------------------------------------------------
  330. // Creates a vertex array
  331. void ObjFileImporter::createVertexArray(const ObjFile::Model* pModel,
  332. const ObjFile::Object* pCurrentObject,
  333. unsigned int uiMeshIndex,
  334. aiMesh* pMesh,
  335. unsigned int numIndices)
  336. {
  337. // Checking preconditions
  338. ai_assert( NULL != pCurrentObject );
  339. // Break, if no faces are stored in object
  340. if ( pCurrentObject->m_Meshes.empty() )
  341. return;
  342. // Get current mesh
  343. ObjFile::Mesh *pObjMesh = pModel->m_Meshes[ uiMeshIndex ];
  344. if ( NULL == pObjMesh || pObjMesh->m_uiNumIndices < 1)
  345. return;
  346. // Copy vertices of this mesh instance
  347. pMesh->mNumVertices = numIndices;
  348. if (pMesh->mNumVertices == 0) {
  349. throw DeadlyImportError( "OBJ: no vertices" );
  350. } else if (pMesh->mNumVertices > AI_MAX_ALLOC(aiVector3D)) {
  351. throw DeadlyImportError( "OBJ: Too many vertices, would run out of memory" );
  352. }
  353. pMesh->mVertices = new aiVector3D[ pMesh->mNumVertices ];
  354. // Allocate buffer for normal vectors
  355. if ( !pModel->m_Normals.empty() && pObjMesh->m_hasNormals )
  356. pMesh->mNormals = new aiVector3D[ pMesh->mNumVertices ];
  357. // Allocate buffer for texture coordinates
  358. if ( !pModel->m_TextureCoord.empty() && pObjMesh->m_uiUVCoordinates[0] )
  359. {
  360. pMesh->mNumUVComponents[ 0 ] = 2;
  361. pMesh->mTextureCoords[ 0 ] = new aiVector3D[ pMesh->mNumVertices ];
  362. }
  363. // Copy vertices, normals and textures into aiMesh instance
  364. unsigned int newIndex = 0, outIndex = 0;
  365. for ( size_t index=0; index < pObjMesh->m_Faces.size(); index++ )
  366. {
  367. // Get source face
  368. ObjFile::Face *pSourceFace = pObjMesh->m_Faces[ index ];
  369. // Copy all index arrays
  370. for ( size_t vertexIndex = 0, outVertexIndex = 0; vertexIndex < pSourceFace->m_pVertices->size(); vertexIndex++ )
  371. {
  372. const unsigned int vertex = pSourceFace->m_pVertices->at( vertexIndex );
  373. if ( vertex >= pModel->m_Vertices.size() )
  374. throw DeadlyImportError( "OBJ: vertex index out of range" );
  375. pMesh->mVertices[ newIndex ] = pModel->m_Vertices[ vertex ];
  376. // Copy all normals
  377. if ( !pModel->m_Normals.empty() && vertexIndex < pSourceFace->m_pNormals->size())
  378. {
  379. const unsigned int normal = pSourceFace->m_pNormals->at( vertexIndex );
  380. if ( normal >= pModel->m_Normals.size() )
  381. throw DeadlyImportError("OBJ: vertex normal index out of range");
  382. pMesh->mNormals[ newIndex ] = pModel->m_Normals[ normal ];
  383. }
  384. // Copy all texture coordinates
  385. if ( !pModel->m_TextureCoord.empty() && vertexIndex < pSourceFace->m_pTexturCoords->size())
  386. {
  387. const unsigned int tex = pSourceFace->m_pTexturCoords->at( vertexIndex );
  388. ai_assert( tex < pModel->m_TextureCoord.size() );
  389. if ( tex >= pModel->m_TextureCoord.size() )
  390. throw DeadlyImportError("OBJ: texture coordinate index out of range");
  391. const aiVector3D &coord3d = pModel->m_TextureCoord[ tex ];
  392. pMesh->mTextureCoords[ 0 ][ newIndex ] = aiVector3D( coord3d.x, coord3d.y, coord3d.z );
  393. }
  394. if ( pMesh->mNumVertices <= newIndex ) {
  395. throw DeadlyImportError("OBJ: bad vertex index");
  396. }
  397. // Get destination face
  398. aiFace *pDestFace = &pMesh->mFaces[ outIndex ];
  399. const bool last = ( vertexIndex == pSourceFace->m_pVertices->size() - 1 );
  400. if (pSourceFace->m_PrimitiveType != aiPrimitiveType_LINE || !last)
  401. {
  402. pDestFace->mIndices[ outVertexIndex ] = newIndex;
  403. outVertexIndex++;
  404. }
  405. if (pSourceFace->m_PrimitiveType == aiPrimitiveType_POINT)
  406. {
  407. outIndex++;
  408. outVertexIndex = 0;
  409. }
  410. else if (pSourceFace->m_PrimitiveType == aiPrimitiveType_LINE)
  411. {
  412. outVertexIndex = 0;
  413. if(!last)
  414. outIndex++;
  415. if (vertexIndex) {
  416. if(!last) {
  417. pMesh->mVertices[ newIndex+1 ] = pMesh->mVertices[ newIndex ];
  418. if ( !pSourceFace->m_pNormals->empty() && !pModel->m_Normals.empty()) {
  419. pMesh->mNormals[ newIndex+1 ] = pMesh->mNormals[newIndex ];
  420. }
  421. if ( !pModel->m_TextureCoord.empty() ) {
  422. for ( size_t i=0; i < pMesh->GetNumUVChannels(); i++ ) {
  423. pMesh->mTextureCoords[ i ][ newIndex+1 ] = pMesh->mTextureCoords[ i ][ newIndex ];
  424. }
  425. }
  426. ++newIndex;
  427. }
  428. pDestFace[-1].mIndices[1] = newIndex;
  429. }
  430. }
  431. else if (last) {
  432. outIndex++;
  433. }
  434. ++newIndex;
  435. }
  436. }
  437. }
  438. // ------------------------------------------------------------------------------------------------
  439. // Counts all stored meshes
  440. void ObjFileImporter::countObjects(const std::vector<ObjFile::Object*> &rObjects, int &iNumMeshes)
  441. {
  442. iNumMeshes = 0;
  443. if ( rObjects.empty() )
  444. return;
  445. iNumMeshes += static_cast<unsigned int>( rObjects.size() );
  446. for (std::vector<ObjFile::Object*>::const_iterator it = rObjects.begin();
  447. it != rObjects.end();
  448. ++it)
  449. {
  450. if (!(*it)->m_SubObjects.empty())
  451. {
  452. countObjects((*it)->m_SubObjects, iNumMeshes);
  453. }
  454. }
  455. }
  456. // ------------------------------------------------------------------------------------------------
  457. // Add clamp mode property to material if necessary
  458. void ObjFileImporter::addTextureMappingModeProperty(aiMaterial* mat, aiTextureType type, int clampMode)
  459. {
  460. ai_assert( NULL != mat);
  461. mat->AddProperty<int>(&clampMode, 1, AI_MATKEY_MAPPINGMODE_U(type, 0));
  462. mat->AddProperty<int>(&clampMode, 1, AI_MATKEY_MAPPINGMODE_V(type, 0));
  463. }
  464. // ------------------------------------------------------------------------------------------------
  465. // Creates the material
  466. void ObjFileImporter::createMaterials(const ObjFile::Model* pModel, aiScene* pScene )
  467. {
  468. ai_assert( NULL != pScene );
  469. if ( NULL == pScene )
  470. return;
  471. const unsigned int numMaterials = (unsigned int) pModel->m_MaterialLib.size();
  472. pScene->mNumMaterials = 0;
  473. if ( pModel->m_MaterialLib.empty() ) {
  474. DefaultLogger::get()->debug("OBJ: no materials specified");
  475. return;
  476. }
  477. pScene->mMaterials = new aiMaterial*[ numMaterials ];
  478. for ( unsigned int matIndex = 0; matIndex < numMaterials; matIndex++ )
  479. {
  480. // Store material name
  481. std::map<std::string, ObjFile::Material*>::const_iterator it;
  482. it = pModel->m_MaterialMap.find( pModel->m_MaterialLib[ matIndex ] );
  483. // No material found, use the default material
  484. if ( pModel->m_MaterialMap.end() == it )
  485. continue;
  486. aiMaterial* mat = new aiMaterial;
  487. ObjFile::Material *pCurrentMaterial = (*it).second;
  488. mat->AddProperty( &pCurrentMaterial->MaterialName, AI_MATKEY_NAME );
  489. // convert illumination model
  490. int sm = 0;
  491. switch (pCurrentMaterial->illumination_model)
  492. {
  493. case 0:
  494. sm = aiShadingMode_NoShading;
  495. break;
  496. case 1:
  497. sm = aiShadingMode_Gouraud;
  498. break;
  499. case 2:
  500. sm = aiShadingMode_Phong;
  501. break;
  502. default:
  503. sm = aiShadingMode_Gouraud;
  504. DefaultLogger::get()->error("OBJ: unexpected illumination model (0-2 recognized)");
  505. }
  506. mat->AddProperty<int>( &sm, 1, AI_MATKEY_SHADING_MODEL);
  507. // multiplying the specular exponent with 2 seems to yield better results
  508. pCurrentMaterial->shineness *= 4.f;
  509. // Adding material colors
  510. mat->AddProperty( &pCurrentMaterial->ambient, 1, AI_MATKEY_COLOR_AMBIENT );
  511. mat->AddProperty( &pCurrentMaterial->diffuse, 1, AI_MATKEY_COLOR_DIFFUSE );
  512. mat->AddProperty( &pCurrentMaterial->specular, 1, AI_MATKEY_COLOR_SPECULAR );
  513. mat->AddProperty( &pCurrentMaterial->emissive, 1, AI_MATKEY_COLOR_EMISSIVE );
  514. mat->AddProperty( &pCurrentMaterial->shineness, 1, AI_MATKEY_SHININESS );
  515. mat->AddProperty( &pCurrentMaterial->alpha, 1, AI_MATKEY_OPACITY );
  516. // Adding refraction index
  517. mat->AddProperty( &pCurrentMaterial->ior, 1, AI_MATKEY_REFRACTI );
  518. // Adding textures
  519. if ( 0 != pCurrentMaterial->texture.length )
  520. {
  521. mat->AddProperty( &pCurrentMaterial->texture, AI_MATKEY_TEXTURE_DIFFUSE(0));
  522. if (pCurrentMaterial->clamp[ObjFile::Material::TextureDiffuseType])
  523. {
  524. addTextureMappingModeProperty(mat, aiTextureType_DIFFUSE);
  525. }
  526. }
  527. if ( 0 != pCurrentMaterial->textureAmbient.length )
  528. {
  529. mat->AddProperty( &pCurrentMaterial->textureAmbient, AI_MATKEY_TEXTURE_AMBIENT(0));
  530. if (pCurrentMaterial->clamp[ObjFile::Material::TextureAmbientType])
  531. {
  532. addTextureMappingModeProperty(mat, aiTextureType_AMBIENT);
  533. }
  534. }
  535. if ( 0 != pCurrentMaterial->textureEmissive.length )
  536. mat->AddProperty( &pCurrentMaterial->textureEmissive, AI_MATKEY_TEXTURE_EMISSIVE(0));
  537. if ( 0 != pCurrentMaterial->textureSpecular.length )
  538. {
  539. mat->AddProperty( &pCurrentMaterial->textureSpecular, AI_MATKEY_TEXTURE_SPECULAR(0));
  540. if (pCurrentMaterial->clamp[ObjFile::Material::TextureSpecularType])
  541. {
  542. addTextureMappingModeProperty(mat, aiTextureType_SPECULAR);
  543. }
  544. }
  545. if ( 0 != pCurrentMaterial->textureBump.length )
  546. {
  547. mat->AddProperty( &pCurrentMaterial->textureBump, AI_MATKEY_TEXTURE_HEIGHT(0));
  548. if (pCurrentMaterial->clamp[ObjFile::Material::TextureBumpType])
  549. {
  550. addTextureMappingModeProperty(mat, aiTextureType_HEIGHT);
  551. }
  552. }
  553. if ( 0 != pCurrentMaterial->textureNormal.length )
  554. {
  555. mat->AddProperty( &pCurrentMaterial->textureNormal, AI_MATKEY_TEXTURE_NORMALS(0));
  556. if (pCurrentMaterial->clamp[ObjFile::Material::TextureNormalType])
  557. {
  558. addTextureMappingModeProperty(mat, aiTextureType_NORMALS);
  559. }
  560. }
  561. if( 0 != pCurrentMaterial->textureReflection[0].length )
  562. {
  563. ObjFile::Material::TextureType type = 0 != pCurrentMaterial->textureReflection[1].length ?
  564. ObjFile::Material::TextureReflectionCubeTopType :
  565. ObjFile::Material::TextureReflectionSphereType;
  566. unsigned count = type == ObjFile::Material::TextureReflectionSphereType ? 1 : 6;
  567. for( unsigned i = 0; i < count; i++ )
  568. mat->AddProperty(&pCurrentMaterial->textureReflection[i], AI_MATKEY_TEXTURE_REFLECTION(i));
  569. if(pCurrentMaterial->clamp[type])
  570. //TODO addTextureMappingModeProperty should accept an index to handle clamp option for each
  571. //texture of a cubemap
  572. addTextureMappingModeProperty(mat, aiTextureType_REFLECTION);
  573. }
  574. if ( 0 != pCurrentMaterial->textureDisp.length )
  575. {
  576. mat->AddProperty( &pCurrentMaterial->textureDisp, AI_MATKEY_TEXTURE_DISPLACEMENT(0) );
  577. if (pCurrentMaterial->clamp[ObjFile::Material::TextureDispType])
  578. {
  579. addTextureMappingModeProperty(mat, aiTextureType_DISPLACEMENT);
  580. }
  581. }
  582. if ( 0 != pCurrentMaterial->textureOpacity.length )
  583. {
  584. mat->AddProperty( &pCurrentMaterial->textureOpacity, AI_MATKEY_TEXTURE_OPACITY(0));
  585. if (pCurrentMaterial->clamp[ObjFile::Material::TextureOpacityType])
  586. {
  587. addTextureMappingModeProperty(mat, aiTextureType_OPACITY);
  588. }
  589. }
  590. if ( 0 != pCurrentMaterial->textureSpecularity.length )
  591. {
  592. mat->AddProperty( &pCurrentMaterial->textureSpecularity, AI_MATKEY_TEXTURE_SHININESS(0));
  593. if (pCurrentMaterial->clamp[ObjFile::Material::TextureSpecularityType])
  594. {
  595. addTextureMappingModeProperty(mat, aiTextureType_SHININESS);
  596. }
  597. }
  598. // Store material property info in material array in scene
  599. pScene->mMaterials[ pScene->mNumMaterials ] = mat;
  600. pScene->mNumMaterials++;
  601. }
  602. // Test number of created materials.
  603. ai_assert( pScene->mNumMaterials == numMaterials );
  604. }
  605. // ------------------------------------------------------------------------------------------------
  606. // Appends this node to the parent node
  607. void ObjFileImporter::appendChildToParentNode(aiNode *pParent, aiNode *pChild)
  608. {
  609. // Checking preconditions
  610. ai_assert( NULL != pParent );
  611. ai_assert( NULL != pChild );
  612. // Assign parent to child
  613. pChild->mParent = pParent;
  614. // If already children was assigned to the parent node, store them in a
  615. std::vector<aiNode*> temp;
  616. if (pParent->mChildren != NULL)
  617. {
  618. ai_assert( 0 != pParent->mNumChildren );
  619. for (size_t index = 0; index < pParent->mNumChildren; index++)
  620. {
  621. temp.push_back(pParent->mChildren [ index ] );
  622. }
  623. delete [] pParent->mChildren;
  624. }
  625. // Copy node instances into parent node
  626. pParent->mNumChildren++;
  627. pParent->mChildren = new aiNode*[ pParent->mNumChildren ];
  628. for (size_t index = 0; index < pParent->mNumChildren-1; index++)
  629. {
  630. pParent->mChildren[ index ] = temp [ index ];
  631. }
  632. pParent->mChildren[ pParent->mNumChildren-1 ] = pChild;
  633. }
  634. // ------------------------------------------------------------------------------------------------
  635. } // Namespace Assimp
  636. #endif // !! ASSIMP_BUILD_NO_OBJ_IMPORTER