ObjFileImporter.cpp 28 KB

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