ObjFileImporter.cpp 31 KB

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