ObjFileImporter.cpp 30 KB

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