ObjFileImporter.cpp 27 KB

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