ObjFileImporter.cpp 29 KB

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