ObjFileImporter.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2023, 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 <assimp/ObjMaterial.h>
  46. #include <memory>
  47. static const aiImporterDesc desc = {
  48. "Wavefront Object Importer",
  49. "",
  50. "",
  51. "surfaces not supported",
  52. aiImporterFlags_SupportTextFlavour,
  53. 0,
  54. 0,
  55. 0,
  56. 0,
  57. "obj"
  58. };
  59. static const unsigned int ObjMinSize = 16;
  60. namespace Assimp {
  61. using namespace std;
  62. // ------------------------------------------------------------------------------------------------
  63. // Default constructor
  64. ObjFileImporter::ObjFileImporter() :
  65. m_Buffer(),
  66. m_pRootObject(nullptr),
  67. m_strAbsPath(std::string(1, DefaultIOSystem().getOsSeparator())) {}
  68. // ------------------------------------------------------------------------------------------------
  69. // Destructor.
  70. ObjFileImporter::~ObjFileImporter() {
  71. delete m_pRootObject;
  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) {
  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->mModelName.empty()) {
  137. // Set the name of the scene
  138. pScene->mRootNode->mName.Set(pModel->mModelName);
  139. } else {
  140. // This is a fatal error, so break down the application
  141. ai_assert(false);
  142. }
  143. if (!pModel->mObjects.empty()) {
  144. unsigned int meshCount = 0;
  145. unsigned int childCount = 0;
  146. for (auto object : pModel->mObjects) {
  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->mObjects.size(); ++index) {
  158. createNodes(pModel, pModel->mObjects[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->mVertices.empty()) {
  172. return;
  173. }
  174. std::unique_ptr<aiMesh> mesh(new aiMesh);
  175. mesh->mPrimitiveTypes = aiPrimitiveType_POINT;
  176. unsigned int n = (unsigned int)pModel->mVertices.size();
  177. mesh->mNumVertices = n;
  178. mesh->mVertices = new aiVector3D[n];
  179. memcpy(mesh->mVertices, pModel->mVertices.data(), n * sizeof(aiVector3D));
  180. if (!pModel->mNormals.empty()) {
  181. mesh->mNormals = new aiVector3D[n];
  182. if (pModel->mNormals.size() < n) {
  183. throw DeadlyImportError("OBJ: vertex normal index out of range");
  184. }
  185. memcpy(mesh->mNormals, pModel->mNormals.data(), n * sizeof(aiVector3D));
  186. }
  187. if (!pModel->mVertexColors.empty()) {
  188. mesh->mColors[0] = new aiColor4D[mesh->mNumVertices];
  189. for (unsigned int i = 0; i < n; ++i) {
  190. if (i < pModel->mVertexColors.size()) {
  191. const aiVector3D &color = pModel->mVertexColors[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 != nullptr) {
  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->mMeshes[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. const ObjFile::Face *inp = pObjMesh->m_Faces[index];
  277. if (inp->mPrimitiveType == aiPrimitiveType_LINE) {
  278. pMesh->mNumFaces += static_cast<unsigned int>(inp->m_vertices.size() - 1);
  279. pMesh->mPrimitiveTypes |= aiPrimitiveType_LINE;
  280. } else if (inp->mPrimitiveType == aiPrimitiveType_POINT) {
  281. pMesh->mNumFaces += static_cast<unsigned int>(inp->m_vertices.size());
  282. pMesh->mPrimitiveTypes |= aiPrimitiveType_POINT;
  283. } else {
  284. ++pMesh->mNumFaces;
  285. if (inp->m_vertices.size() > 3) {
  286. pMesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  287. } else {
  288. pMesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  289. }
  290. }
  291. }
  292. unsigned int uiIdxCount(0u);
  293. if (pMesh->mNumFaces > 0) {
  294. pMesh->mFaces = new aiFace[pMesh->mNumFaces];
  295. if (pObjMesh->m_uiMaterialIndex != ObjFile::Mesh::NoMaterial) {
  296. pMesh->mMaterialIndex = pObjMesh->m_uiMaterialIndex;
  297. }
  298. unsigned int outIndex(0);
  299. // Copy all data from all stored meshes
  300. for (auto &face : pObjMesh->m_Faces) {
  301. const ObjFile::Face *inp = face;
  302. if (inp->mPrimitiveType == aiPrimitiveType_LINE) {
  303. for (size_t i = 0; i < inp->m_vertices.size() - 1; ++i) {
  304. aiFace &f = pMesh->mFaces[outIndex++];
  305. uiIdxCount += f.mNumIndices = 2;
  306. f.mIndices = new unsigned int[2];
  307. }
  308. continue;
  309. } else if (inp->mPrimitiveType == aiPrimitiveType_POINT) {
  310. for (size_t i = 0; i < inp->m_vertices.size(); ++i) {
  311. aiFace &f = pMesh->mFaces[outIndex++];
  312. uiIdxCount += f.mNumIndices = 1;
  313. f.mIndices = new unsigned int[1];
  314. }
  315. continue;
  316. }
  317. aiFace *pFace = &pMesh->mFaces[outIndex++];
  318. const unsigned int uiNumIndices = (unsigned int)face->m_vertices.size();
  319. uiIdxCount += pFace->mNumIndices = (unsigned int)uiNumIndices;
  320. if (pFace->mNumIndices > 0) {
  321. pFace->mIndices = new unsigned int[uiNumIndices];
  322. }
  323. }
  324. }
  325. // Create mesh vertices
  326. createVertexArray(pModel, pData, meshIndex, pMesh.get(), uiIdxCount);
  327. return pMesh.release();
  328. }
  329. // ------------------------------------------------------------------------------------------------
  330. // Creates a vertex array
  331. void ObjFileImporter::createVertexArray(const ObjFile::Model *pModel,
  332. const ObjFile::Object *pCurrentObject,
  333. unsigned int uiMeshIndex,
  334. aiMesh *pMesh,
  335. unsigned int numIndices) {
  336. // Checking preconditions
  337. ai_assert(nullptr != pCurrentObject);
  338. // Break, if no faces are stored in object
  339. if (pCurrentObject->m_Meshes.empty())
  340. return;
  341. // Get current mesh
  342. ObjFile::Mesh *pObjMesh = pModel->mMeshes[uiMeshIndex];
  343. if (nullptr == pObjMesh || pObjMesh->m_uiNumIndices < 1) {
  344. return;
  345. }
  346. // Copy vertices of this mesh instance
  347. pMesh->mNumVertices = numIndices;
  348. if (pMesh->mNumVertices == 0) {
  349. throw DeadlyImportError("OBJ: no vertices");
  350. } else if (pMesh->mNumVertices > AI_MAX_VERTICES) {
  351. throw DeadlyImportError("OBJ: Too many vertices");
  352. }
  353. pMesh->mVertices = new aiVector3D[pMesh->mNumVertices];
  354. // Allocate buffer for normal vectors
  355. if (!pModel->mNormals.empty() && pObjMesh->m_hasNormals)
  356. pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
  357. // Allocate buffer for vertex-color vectors
  358. if (!pModel->mVertexColors.empty())
  359. pMesh->mColors[0] = new aiColor4D[pMesh->mNumVertices];
  360. // Allocate buffer for texture coordinates
  361. if (!pModel->mTextureCoord.empty() && pObjMesh->m_uiUVCoordinates[0]) {
  362. pMesh->mNumUVComponents[0] = pModel->mTextureCoordDim;
  363. pMesh->mTextureCoords[0] = new aiVector3D[pMesh->mNumVertices];
  364. }
  365. // Copy vertices, normals and textures into aiMesh instance
  366. bool normalsok = true, uvok = true;
  367. unsigned int newIndex = 0, outIndex = 0;
  368. for (auto sourceFace : pObjMesh->m_Faces) {
  369. // Copy all index arrays
  370. for (size_t vertexIndex = 0, outVertexIndex = 0; vertexIndex < sourceFace->m_vertices.size(); vertexIndex++) {
  371. const unsigned int vertex = sourceFace->m_vertices.at(vertexIndex);
  372. if (vertex >= pModel->mVertices.size()) {
  373. throw DeadlyImportError("OBJ: vertex index out of range");
  374. }
  375. if (pMesh->mNumVertices <= newIndex) {
  376. throw DeadlyImportError("OBJ: bad vertex index");
  377. }
  378. pMesh->mVertices[newIndex] = pModel->mVertices[vertex];
  379. // Copy all normals
  380. if (normalsok && !pModel->mNormals.empty() && vertexIndex < sourceFace->m_normals.size()) {
  381. const unsigned int normal = sourceFace->m_normals.at(vertexIndex);
  382. if (normal >= pModel->mNormals.size()) {
  383. normalsok = false;
  384. } else {
  385. pMesh->mNormals[newIndex] = pModel->mNormals[normal];
  386. }
  387. }
  388. // Copy all vertex colors
  389. if (vertex < pModel->mVertexColors.size()) {
  390. const aiVector3D &color = pModel->mVertexColors[vertex];
  391. pMesh->mColors[0][newIndex] = aiColor4D(color.x, color.y, color.z, 1.0);
  392. }
  393. // Copy all texture coordinates
  394. if (uvok && !pModel->mTextureCoord.empty() && vertexIndex < sourceFace->m_texturCoords.size()) {
  395. const unsigned int tex = sourceFace->m_texturCoords.at(vertexIndex);
  396. if (tex >= pModel->mTextureCoord.size()) {
  397. uvok = false;
  398. } else {
  399. const aiVector3D &coord3d = pModel->mTextureCoord[tex];
  400. pMesh->mTextureCoords[0][newIndex] = aiVector3D(coord3d.x, coord3d.y, coord3d.z);
  401. }
  402. }
  403. // Get destination face
  404. aiFace *pDestFace = &pMesh->mFaces[outIndex];
  405. const bool last = (vertexIndex == sourceFace->m_vertices.size() - 1);
  406. if (sourceFace->mPrimitiveType != aiPrimitiveType_LINE || !last) {
  407. pDestFace->mIndices[outVertexIndex] = newIndex;
  408. outVertexIndex++;
  409. }
  410. if (sourceFace->mPrimitiveType == aiPrimitiveType_POINT) {
  411. outIndex++;
  412. outVertexIndex = 0;
  413. } else if (sourceFace->mPrimitiveType == aiPrimitiveType_LINE) {
  414. outVertexIndex = 0;
  415. if (!last)
  416. outIndex++;
  417. if (vertexIndex) {
  418. if (!last) {
  419. if (pMesh->mNumVertices <= newIndex + 1) {
  420. throw DeadlyImportError("OBJ: bad vertex index");
  421. }
  422. pMesh->mVertices[newIndex + 1] = pMesh->mVertices[newIndex];
  423. if (!sourceFace->m_normals.empty() && !pModel->mNormals.empty()) {
  424. pMesh->mNormals[newIndex + 1] = pMesh->mNormals[newIndex];
  425. }
  426. if (!pModel->mTextureCoord.empty()) {
  427. for (size_t i = 0; i < pMesh->GetNumUVChannels(); i++) {
  428. pMesh->mTextureCoords[i][newIndex + 1] = pMesh->mTextureCoords[i][newIndex];
  429. }
  430. }
  431. ++newIndex;
  432. }
  433. pDestFace[-1].mIndices[1] = newIndex;
  434. }
  435. } else if (last) {
  436. outIndex++;
  437. }
  438. ++newIndex;
  439. }
  440. }
  441. if (!normalsok) {
  442. delete[] pMesh->mNormals;
  443. pMesh->mNormals = nullptr;
  444. }
  445. if (!uvok) {
  446. delete[] pMesh->mTextureCoords[0];
  447. pMesh->mTextureCoords[0] = nullptr;
  448. }
  449. }
  450. // ------------------------------------------------------------------------------------------------
  451. // Counts all stored meshes
  452. void ObjFileImporter::countObjects(const std::vector<ObjFile::Object *> &rObjects, int &iNumMeshes) {
  453. iNumMeshes = 0;
  454. if (rObjects.empty())
  455. return;
  456. iNumMeshes += static_cast<unsigned int>(rObjects.size());
  457. for (auto object : rObjects) {
  458. if (!object->m_SubObjects.empty()) {
  459. countObjects(object->m_SubObjects, iNumMeshes);
  460. }
  461. }
  462. }
  463. // ------------------------------------------------------------------------------------------------
  464. // Add clamp mode property to material if necessary
  465. void ObjFileImporter::addTextureMappingModeProperty(aiMaterial *mat, aiTextureType type, int clampMode, int index) {
  466. if (nullptr == mat) {
  467. return;
  468. }
  469. mat->AddProperty<int>(&clampMode, 1, AI_MATKEY_MAPPINGMODE_U(type, index));
  470. mat->AddProperty<int>(&clampMode, 1, AI_MATKEY_MAPPINGMODE_V(type, index));
  471. }
  472. // ------------------------------------------------------------------------------------------------
  473. // Creates the material
  474. void ObjFileImporter::createMaterials(const ObjFile::Model *pModel, aiScene *pScene) {
  475. if (nullptr == pScene) {
  476. return;
  477. }
  478. const unsigned int numMaterials = (unsigned int)pModel->mMaterialLib.size();
  479. pScene->mNumMaterials = 0;
  480. if (pModel->mMaterialLib.empty()) {
  481. ASSIMP_LOG_DEBUG("OBJ: no materials specified");
  482. return;
  483. }
  484. pScene->mMaterials = new aiMaterial *[numMaterials];
  485. for (unsigned int matIndex = 0; matIndex < numMaterials; matIndex++) {
  486. // Store material name
  487. std::map<std::string, ObjFile::Material *>::const_iterator it;
  488. it = pModel->mMaterialMap.find(pModel->mMaterialLib[matIndex]);
  489. // No material found, use the default material
  490. if (pModel->mMaterialMap.end() == it)
  491. continue;
  492. aiMaterial *mat = new aiMaterial;
  493. ObjFile::Material *pCurrentMaterial = (*it).second;
  494. mat->AddProperty(&pCurrentMaterial->MaterialName, AI_MATKEY_NAME);
  495. // convert illumination model
  496. int sm = 0;
  497. switch (pCurrentMaterial->illumination_model) {
  498. case 0:
  499. sm = aiShadingMode_NoShading;
  500. break;
  501. case 1:
  502. sm = aiShadingMode_Gouraud;
  503. break;
  504. case 2:
  505. sm = aiShadingMode_Phong;
  506. break;
  507. default:
  508. sm = aiShadingMode_Gouraud;
  509. ASSIMP_LOG_ERROR("OBJ: unexpected illumination model (0-2 recognized)");
  510. }
  511. mat->AddProperty<int>(&sm, 1, AI_MATKEY_SHADING_MODEL);
  512. // Preserve the original illum value
  513. mat->AddProperty<int>(&pCurrentMaterial->illumination_model, 1, AI_MATKEY_OBJ_ILLUM);
  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. if (pCurrentMaterial->roughness)
  523. mat->AddProperty(&pCurrentMaterial->roughness.Get(), 1, AI_MATKEY_ROUGHNESS_FACTOR);
  524. if (pCurrentMaterial->metallic)
  525. mat->AddProperty(&pCurrentMaterial->metallic.Get(), 1, AI_MATKEY_METALLIC_FACTOR);
  526. if (pCurrentMaterial->sheen)
  527. mat->AddProperty(&pCurrentMaterial->sheen.Get(), 1, AI_MATKEY_SHEEN_COLOR_FACTOR);
  528. if (pCurrentMaterial->clearcoat_thickness)
  529. mat->AddProperty(&pCurrentMaterial->clearcoat_thickness.Get(), 1, AI_MATKEY_CLEARCOAT_FACTOR);
  530. if (pCurrentMaterial->clearcoat_roughness)
  531. mat->AddProperty(&pCurrentMaterial->clearcoat_roughness.Get(), 1, AI_MATKEY_CLEARCOAT_ROUGHNESS_FACTOR);
  532. mat->AddProperty(&pCurrentMaterial->anisotropy, 1, AI_MATKEY_ANISOTROPY_FACTOR);
  533. // Adding refraction index
  534. mat->AddProperty(&pCurrentMaterial->ior, 1, AI_MATKEY_REFRACTI);
  535. // Adding textures
  536. const int uvwIndex = 0;
  537. if (0 != pCurrentMaterial->texture.length) {
  538. mat->AddProperty(&pCurrentMaterial->texture, AI_MATKEY_TEXTURE_DIFFUSE(0));
  539. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_DIFFUSE(0));
  540. if (pCurrentMaterial->clamp[ObjFile::Material::TextureDiffuseType]) {
  541. addTextureMappingModeProperty(mat, aiTextureType_DIFFUSE);
  542. }
  543. }
  544. if (0 != pCurrentMaterial->textureAmbient.length) {
  545. mat->AddProperty(&pCurrentMaterial->textureAmbient, AI_MATKEY_TEXTURE_AMBIENT(0));
  546. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_AMBIENT(0));
  547. if (pCurrentMaterial->clamp[ObjFile::Material::TextureAmbientType]) {
  548. addTextureMappingModeProperty(mat, aiTextureType_AMBIENT);
  549. }
  550. }
  551. if (0 != pCurrentMaterial->textureEmissive.length) {
  552. mat->AddProperty(&pCurrentMaterial->textureEmissive, AI_MATKEY_TEXTURE_EMISSIVE(0));
  553. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_EMISSIVE(0));
  554. }
  555. if (0 != pCurrentMaterial->textureSpecular.length) {
  556. mat->AddProperty(&pCurrentMaterial->textureSpecular, AI_MATKEY_TEXTURE_SPECULAR(0));
  557. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_SPECULAR(0));
  558. if (pCurrentMaterial->clamp[ObjFile::Material::TextureSpecularType]) {
  559. addTextureMappingModeProperty(mat, aiTextureType_SPECULAR);
  560. }
  561. }
  562. if (0 != pCurrentMaterial->textureBump.length) {
  563. mat->AddProperty(&pCurrentMaterial->textureBump, AI_MATKEY_TEXTURE_HEIGHT(0));
  564. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_HEIGHT(0));
  565. if (pCurrentMaterial->bump_multiplier != 1.0) {
  566. mat->AddProperty(&pCurrentMaterial->bump_multiplier, 1, AI_MATKEY_OBJ_BUMPMULT_HEIGHT(0));
  567. }
  568. if (pCurrentMaterial->clamp[ObjFile::Material::TextureBumpType]) {
  569. addTextureMappingModeProperty(mat, aiTextureType_HEIGHT);
  570. }
  571. }
  572. if (0 != pCurrentMaterial->textureNormal.length) {
  573. mat->AddProperty(&pCurrentMaterial->textureNormal, AI_MATKEY_TEXTURE_NORMALS(0));
  574. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_NORMALS(0));
  575. if (pCurrentMaterial->bump_multiplier != 1.0) {
  576. mat->AddProperty(&pCurrentMaterial->bump_multiplier, 1, AI_MATKEY_OBJ_BUMPMULT_NORMALS(0));
  577. }
  578. if (pCurrentMaterial->clamp[ObjFile::Material::TextureNormalType]) {
  579. addTextureMappingModeProperty(mat, aiTextureType_NORMALS);
  580. }
  581. }
  582. if (0 != pCurrentMaterial->textureReflection[0].length) {
  583. ObjFile::Material::TextureType type = 0 != pCurrentMaterial->textureReflection[1].length ?
  584. ObjFile::Material::TextureReflectionCubeTopType :
  585. ObjFile::Material::TextureReflectionSphereType;
  586. unsigned count = type == ObjFile::Material::TextureReflectionSphereType ? 1 : 6;
  587. for (unsigned i = 0; i < count; i++) {
  588. mat->AddProperty(&pCurrentMaterial->textureReflection[i], AI_MATKEY_TEXTURE_REFLECTION(i));
  589. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_REFLECTION(i));
  590. if (pCurrentMaterial->clamp[type])
  591. addTextureMappingModeProperty(mat, aiTextureType_REFLECTION, 1, i);
  592. }
  593. }
  594. if (0 != pCurrentMaterial->textureDisp.length) {
  595. mat->AddProperty(&pCurrentMaterial->textureDisp, AI_MATKEY_TEXTURE_DISPLACEMENT(0));
  596. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_DISPLACEMENT(0));
  597. if (pCurrentMaterial->clamp[ObjFile::Material::TextureDispType]) {
  598. addTextureMappingModeProperty(mat, aiTextureType_DISPLACEMENT);
  599. }
  600. }
  601. if (0 != pCurrentMaterial->textureOpacity.length) {
  602. mat->AddProperty(&pCurrentMaterial->textureOpacity, AI_MATKEY_TEXTURE_OPACITY(0));
  603. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_OPACITY(0));
  604. if (pCurrentMaterial->clamp[ObjFile::Material::TextureOpacityType]) {
  605. addTextureMappingModeProperty(mat, aiTextureType_OPACITY);
  606. }
  607. }
  608. if (0 != pCurrentMaterial->textureSpecularity.length) {
  609. mat->AddProperty(&pCurrentMaterial->textureSpecularity, AI_MATKEY_TEXTURE_SHININESS(0));
  610. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_SHININESS(0));
  611. if (pCurrentMaterial->clamp[ObjFile::Material::TextureSpecularityType]) {
  612. addTextureMappingModeProperty(mat, aiTextureType_SHININESS);
  613. }
  614. }
  615. if (0 != pCurrentMaterial->textureRoughness.length) {
  616. mat->AddProperty(&pCurrentMaterial->textureRoughness, _AI_MATKEY_TEXTURE_BASE, aiTextureType_DIFFUSE_ROUGHNESS, 0);
  617. mat->AddProperty(&uvwIndex, 1, _AI_MATKEY_UVWSRC_BASE, aiTextureType_DIFFUSE_ROUGHNESS, 0 );
  618. if (pCurrentMaterial->clamp[ObjFile::Material::TextureRoughnessType]) {
  619. addTextureMappingModeProperty(mat, aiTextureType_DIFFUSE_ROUGHNESS);
  620. }
  621. }
  622. if (0 != pCurrentMaterial->textureMetallic.length) {
  623. mat->AddProperty(&pCurrentMaterial->textureMetallic, _AI_MATKEY_TEXTURE_BASE, aiTextureType_METALNESS, 0);
  624. mat->AddProperty(&uvwIndex, 1, _AI_MATKEY_UVWSRC_BASE, aiTextureType_METALNESS, 0 );
  625. if (pCurrentMaterial->clamp[ObjFile::Material::TextureMetallicType]) {
  626. addTextureMappingModeProperty(mat, aiTextureType_METALNESS);
  627. }
  628. }
  629. if (0 != pCurrentMaterial->textureSheen.length) {
  630. mat->AddProperty(&pCurrentMaterial->textureSheen, _AI_MATKEY_TEXTURE_BASE, aiTextureType_SHEEN, 0);
  631. mat->AddProperty(&uvwIndex, 1, _AI_MATKEY_UVWSRC_BASE, aiTextureType_SHEEN, 0 );
  632. if (pCurrentMaterial->clamp[ObjFile::Material::TextureSheenType]) {
  633. addTextureMappingModeProperty(mat, aiTextureType_SHEEN);
  634. }
  635. }
  636. if (0 != pCurrentMaterial->textureRMA.length) {
  637. // NOTE: glTF importer places Rough/Metal/AO texture in Unknown so doing the same here for consistency.
  638. mat->AddProperty(&pCurrentMaterial->textureRMA, _AI_MATKEY_TEXTURE_BASE, aiTextureType_UNKNOWN, 0);
  639. mat->AddProperty(&uvwIndex, 1, _AI_MATKEY_UVWSRC_BASE, aiTextureType_UNKNOWN, 0 );
  640. if (pCurrentMaterial->clamp[ObjFile::Material::TextureRMAType]) {
  641. addTextureMappingModeProperty(mat, aiTextureType_UNKNOWN);
  642. }
  643. }
  644. // Store material property info in material array in scene
  645. pScene->mMaterials[pScene->mNumMaterials] = mat;
  646. pScene->mNumMaterials++;
  647. }
  648. // Test number of created materials.
  649. ai_assert(pScene->mNumMaterials == numMaterials);
  650. }
  651. // ------------------------------------------------------------------------------------------------
  652. // Appends this node to the parent node
  653. void ObjFileImporter::appendChildToParentNode(aiNode *pParent, aiNode *pChild) {
  654. // Checking preconditions
  655. ai_assert(nullptr != pParent);
  656. ai_assert(nullptr != pChild);
  657. // Assign parent to child
  658. pChild->mParent = pParent;
  659. // Copy node instances into parent node
  660. pParent->mNumChildren++;
  661. pParent->mChildren[pParent->mNumChildren - 1] = pChild;
  662. }
  663. // ------------------------------------------------------------------------------------------------
  664. } // Namespace Assimp
  665. #endif // !! ASSIMP_BUILD_NO_OBJ_IMPORTER