ObjFileImporter.cpp 31 KB

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