ObjFileParser.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2025, 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 "ObjFileParser.h"
  36. #include "ObjFileData.h"
  37. #include "ObjFileMtlImporter.h"
  38. #include "ObjTools.h"
  39. #include <assimp/BaseImporter.h>
  40. #include <assimp/DefaultIOSystem.h>
  41. #include <assimp/ParsingUtils.h>
  42. #include <assimp/DefaultLogger.hpp>
  43. #include <assimp/Importer.hpp>
  44. #include <cstdlib>
  45. #include <memory>
  46. #include <utility>
  47. namespace Assimp {
  48. constexpr const char ObjFileParser::DEFAULT_MATERIAL[];
  49. ObjFileParser::ObjFileParser() :
  50. m_DataIt(),
  51. m_DataItEnd(),
  52. m_pModel(nullptr),
  53. m_uiLine(0),
  54. m_buffer(),
  55. mEnd(&m_buffer[Buffersize]),
  56. m_pIO(nullptr),
  57. m_progress(nullptr),
  58. m_originalObjFileName() {
  59. std::fill_n(m_buffer, Buffersize, '\0');
  60. }
  61. ObjFileParser::ObjFileParser(IOStreamBuffer<char> &streamBuffer, const std::string &modelName,
  62. IOSystem *io, ProgressHandler *progress,
  63. const std::string &originalObjFileName) :
  64. m_DataIt(),
  65. m_DataItEnd(),
  66. m_pModel(nullptr),
  67. m_uiLine(0),
  68. m_buffer(),
  69. m_pIO(io),
  70. m_progress(progress),
  71. m_originalObjFileName(originalObjFileName) {
  72. std::fill_n(m_buffer, Buffersize, '\0');
  73. // Create the model instance to store all the data
  74. m_pModel.reset(new ObjFile::Model());
  75. m_pModel->mModelName = modelName;
  76. // create default material and store it
  77. m_pModel->mDefaultMaterial = new ObjFile::Material;
  78. m_pModel->mDefaultMaterial->MaterialName.Set(DEFAULT_MATERIAL);
  79. m_pModel->mMaterialLib.emplace_back(DEFAULT_MATERIAL);
  80. m_pModel->mMaterialMap[DEFAULT_MATERIAL] = m_pModel->mDefaultMaterial;
  81. // Start parsing the file
  82. parseFile(streamBuffer);
  83. }
  84. void ObjFileParser::setBuffer(std::vector<char> &buffer) {
  85. m_DataIt = buffer.begin();
  86. m_DataItEnd = buffer.end();
  87. }
  88. ObjFile::Model *ObjFileParser::GetModel() const {
  89. return m_pModel.get();
  90. }
  91. void ObjFileParser::parseFile(IOStreamBuffer<char> &streamBuffer) {
  92. // only update every 100KB or it'll be too slow
  93. //const unsigned int updateProgressEveryBytes = 100 * 1024;
  94. const unsigned int bytesToProcess = static_cast<unsigned int>(streamBuffer.size());
  95. const unsigned int progressTotal = bytesToProcess;
  96. unsigned int processed = 0u;
  97. size_t lastFilePos = 0u;
  98. bool insideCstype = false;
  99. std::vector<char> buffer;
  100. while (streamBuffer.getNextDataLine(buffer, '\\')) {
  101. m_DataIt = buffer.begin();
  102. m_DataItEnd = buffer.end();
  103. mEnd = &buffer[buffer.size() - 1] + 1;
  104. // Handle progress reporting
  105. const size_t filePos(streamBuffer.getFilePos());
  106. if (lastFilePos < filePos) {
  107. processed = static_cast<unsigned int>(filePos);
  108. lastFilePos = filePos;
  109. m_progress->UpdateFileRead(processed, progressTotal);
  110. }
  111. // handle c-stype section end (http://paulbourke.net/dataformats/obj/)
  112. if (insideCstype) {
  113. switch (*m_DataIt) {
  114. case 'e': {
  115. std::string name;
  116. getNameNoSpace(m_DataIt, m_DataItEnd, name);
  117. insideCstype = name != "end";
  118. } break;
  119. }
  120. goto pf_skip_line;
  121. }
  122. // parse line
  123. switch (*m_DataIt) {
  124. case 'v': // Parse a vertex texture coordinate
  125. {
  126. ++m_DataIt;
  127. if (*m_DataIt == ' ' || *m_DataIt == '\t') {
  128. size_t numComponents = getNumComponentsInDataDefinition();
  129. if (numComponents == 3) {
  130. // read in vertex definition
  131. getVector3(m_pModel->mVertices);
  132. } else if (numComponents == 4) {
  133. // read in vertex definition (homogeneous coords)
  134. getHomogeneousVector3(m_pModel->mVertices);
  135. } else if (numComponents == 6) {
  136. // fill previous omitted vertex-colors by default
  137. if (m_pModel->mVertexColors.size() < m_pModel->mVertices.size()) {
  138. m_pModel->mVertexColors.resize(m_pModel->mVertices.size(), aiVector3D(0, 0, 0));
  139. }
  140. // read vertex and vertex-color
  141. getTwoVectors3(m_pModel->mVertices, m_pModel->mVertexColors);
  142. }
  143. // append omitted vertex-colors as default for the end if any vertex-color exists
  144. if (!m_pModel->mVertexColors.empty() && m_pModel->mVertexColors.size() < m_pModel->mVertices.size()) {
  145. m_pModel->mVertexColors.resize(m_pModel->mVertices.size(), aiVector3D(0, 0, 0));
  146. }
  147. } else if (*m_DataIt == 't') {
  148. // read in texture coordinate ( 2D or 3D )
  149. ++m_DataIt;
  150. size_t dim = getTexCoordVector(m_pModel->mTextureCoord);
  151. m_pModel->mTextureCoordDim = std::max(m_pModel->mTextureCoordDim, (unsigned int)dim);
  152. } else if (*m_DataIt == 'n') {
  153. // Read in normal vector definition
  154. ++m_DataIt;
  155. getVector3(m_pModel->mNormals);
  156. }
  157. } break;
  158. case 'p': // Parse a face, line or point statement
  159. case 'l':
  160. case 'f': {
  161. getFace(*m_DataIt == 'f' ? aiPrimitiveType_POLYGON : (*m_DataIt == 'l' ? aiPrimitiveType_LINE : aiPrimitiveType_POINT));
  162. } break;
  163. case '#': // Parse a comment
  164. {
  165. getComment();
  166. } break;
  167. case 'u': // Parse a material desc. setter
  168. {
  169. std::string name;
  170. getNameNoSpace(m_DataIt, m_DataItEnd, name);
  171. size_t nextSpace = name.find(' ');
  172. if (nextSpace != std::string::npos)
  173. name = name.substr(0, nextSpace);
  174. if (name == "usemtl") {
  175. getMaterialDesc();
  176. }
  177. } break;
  178. case 'm': // Parse a material library or merging group ('mg')
  179. {
  180. std::string name;
  181. getNameNoSpace(m_DataIt, m_DataItEnd, name);
  182. size_t nextSpace = name.find(' ');
  183. if (nextSpace != std::string::npos)
  184. name = name.substr(0, nextSpace);
  185. if (name == "mg")
  186. getGroupNumberAndResolution();
  187. else if (name == "mtllib")
  188. getMaterialLib();
  189. else
  190. goto pf_skip_line;
  191. } break;
  192. case 'g': // Parse group name
  193. {
  194. getGroupName();
  195. } break;
  196. case 's': // Parse group number
  197. {
  198. getGroupNumber();
  199. } break;
  200. case 'o': // Parse object name
  201. {
  202. getObjectName();
  203. } break;
  204. case 'c': // handle cstype section start
  205. {
  206. std::string name;
  207. getNameNoSpace(m_DataIt, m_DataItEnd, name);
  208. insideCstype = name == "cstype";
  209. goto pf_skip_line;
  210. }
  211. default: {
  212. pf_skip_line:
  213. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  214. } break;
  215. }
  216. }
  217. }
  218. void ObjFileParser::copyNextWord(char *pBuffer, size_t length) {
  219. size_t index = 0;
  220. m_DataIt = getNextWord<DataArrayIt>(m_DataIt, m_DataItEnd);
  221. if (*m_DataIt == '\\') {
  222. ++m_DataIt;
  223. ++m_DataIt;
  224. m_DataIt = getNextWord<DataArrayIt>(m_DataIt, m_DataItEnd);
  225. }
  226. while (m_DataIt != m_DataItEnd && !IsSpaceOrNewLine(*m_DataIt)) {
  227. pBuffer[index] = *m_DataIt;
  228. index++;
  229. if (index == length - 1) {
  230. break;
  231. }
  232. ++m_DataIt;
  233. }
  234. ai_assert(index < length);
  235. pBuffer[index] = '\0';
  236. }
  237. static bool isDataDefinitionEnd(const char *tmp) {
  238. if (*tmp == '\\') {
  239. tmp++;
  240. if (IsLineEnd(*tmp)) {
  241. return true;
  242. }
  243. }
  244. return false;
  245. }
  246. static bool isNanOrInf(const char *in) {
  247. // Look for "nan" or "inf", case insensitive
  248. return ((in[0] == 'N' || in[0] == 'n') && ASSIMP_strincmp(in, "nan", 3) == 0) ||
  249. ((in[0] == 'I' || in[0] == 'i') && ASSIMP_strincmp(in, "inf", 3) == 0);
  250. }
  251. size_t ObjFileParser::getNumComponentsInDataDefinition() {
  252. size_t numComponents(0);
  253. const char *tmp(&m_DataIt[0]);
  254. bool end_of_definition = false;
  255. while (!end_of_definition) {
  256. if (isDataDefinitionEnd(tmp)) {
  257. tmp += 2;
  258. } else if (IsLineEnd(*tmp)) {
  259. end_of_definition = true;
  260. }
  261. if (!SkipSpaces(&tmp, mEnd) || *tmp == '#') {
  262. break;
  263. }
  264. const bool isNum(IsNumeric(*tmp) || isNanOrInf(tmp));
  265. SkipToken(tmp, mEnd);
  266. if (isNum) {
  267. ++numComponents;
  268. }
  269. if (!SkipSpaces(&tmp, mEnd) || *tmp == '#') {
  270. break;
  271. }
  272. }
  273. return numComponents;
  274. }
  275. size_t ObjFileParser::getTexCoordVector(std::vector<aiVector3D> &point3d_array) {
  276. size_t numComponents = getNumComponentsInDataDefinition();
  277. ai_real x, y, z;
  278. if (2 == numComponents) {
  279. copyNextWord(m_buffer, Buffersize);
  280. x = (ai_real)fast_atof(m_buffer);
  281. copyNextWord(m_buffer, Buffersize);
  282. y = (ai_real)fast_atof(m_buffer);
  283. z = 0.0;
  284. } else if (3 == numComponents) {
  285. copyNextWord(m_buffer, Buffersize);
  286. x = (ai_real)fast_atof(m_buffer);
  287. copyNextWord(m_buffer, Buffersize);
  288. y = (ai_real)fast_atof(m_buffer);
  289. copyNextWord(m_buffer, Buffersize);
  290. z = (ai_real)fast_atof(m_buffer);
  291. } else {
  292. throw DeadlyImportError("OBJ: Invalid number of components");
  293. }
  294. // Coerce nan and inf to 0 as is the OBJ default value
  295. if (!std::isfinite(x))
  296. x = 0;
  297. if (!std::isfinite(y))
  298. y = 0;
  299. if (!std::isfinite(z))
  300. z = 0;
  301. point3d_array.emplace_back(x, y, z);
  302. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  303. return numComponents;
  304. }
  305. void ObjFileParser::getVector3(std::vector<aiVector3D> &point3d_array) {
  306. ai_real x, y, z;
  307. copyNextWord(m_buffer, Buffersize);
  308. x = (ai_real)fast_atof(m_buffer);
  309. copyNextWord(m_buffer, Buffersize);
  310. y = (ai_real)fast_atof(m_buffer);
  311. copyNextWord(m_buffer, Buffersize);
  312. z = (ai_real)fast_atof(m_buffer);
  313. point3d_array.emplace_back(x, y, z);
  314. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  315. }
  316. void ObjFileParser::getHomogeneousVector3(std::vector<aiVector3D> &point3d_array) {
  317. ai_real x, y, z, w;
  318. copyNextWord(m_buffer, Buffersize);
  319. x = (ai_real)fast_atof(m_buffer);
  320. copyNextWord(m_buffer, Buffersize);
  321. y = (ai_real)fast_atof(m_buffer);
  322. copyNextWord(m_buffer, Buffersize);
  323. z = (ai_real)fast_atof(m_buffer);
  324. copyNextWord(m_buffer, Buffersize);
  325. w = (ai_real)fast_atof(m_buffer);
  326. if (w == 0)
  327. throw DeadlyImportError("OBJ: Invalid component in homogeneous vector (Division by zero)");
  328. point3d_array.emplace_back(x / w, y / w, z / w);
  329. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  330. }
  331. void ObjFileParser::getTwoVectors3(std::vector<aiVector3D> &point3d_array_a, std::vector<aiVector3D> &point3d_array_b) {
  332. ai_real x, y, z;
  333. copyNextWord(m_buffer, Buffersize);
  334. x = (ai_real)fast_atof(m_buffer);
  335. copyNextWord(m_buffer, Buffersize);
  336. y = (ai_real)fast_atof(m_buffer);
  337. copyNextWord(m_buffer, Buffersize);
  338. z = (ai_real)fast_atof(m_buffer);
  339. point3d_array_a.emplace_back(x, y, z);
  340. copyNextWord(m_buffer, Buffersize);
  341. x = (ai_real)fast_atof(m_buffer);
  342. copyNextWord(m_buffer, Buffersize);
  343. y = (ai_real)fast_atof(m_buffer);
  344. copyNextWord(m_buffer, Buffersize);
  345. z = (ai_real)fast_atof(m_buffer);
  346. point3d_array_b.emplace_back(x, y, z);
  347. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  348. }
  349. void ObjFileParser::getVector2(std::vector<aiVector2D> &point2d_array) {
  350. ai_real x, y;
  351. copyNextWord(m_buffer, Buffersize);
  352. x = (ai_real)fast_atof(m_buffer);
  353. copyNextWord(m_buffer, Buffersize);
  354. y = (ai_real)fast_atof(m_buffer);
  355. point2d_array.emplace_back(x, y);
  356. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  357. }
  358. static constexpr char DefaultObjName[] = "defaultobject";
  359. void ObjFileParser::getFace(aiPrimitiveType type) {
  360. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  361. if (m_DataIt == m_DataItEnd || *m_DataIt == '\0') {
  362. return;
  363. }
  364. ObjFile::Face *face = new ObjFile::Face(type);
  365. bool hasNormal = false;
  366. const int vSize = static_cast<unsigned int>(m_pModel->mVertices.size());
  367. const int vtSize = static_cast<unsigned int>(m_pModel->mTextureCoord.size());
  368. const int vnSize = static_cast<unsigned int>(m_pModel->mNormals.size());
  369. const bool vt = (!m_pModel->mTextureCoord.empty());
  370. const bool vn = (!m_pModel->mNormals.empty());
  371. int iPos = 0;
  372. while (m_DataIt < m_DataItEnd) {
  373. int iStep = 1;
  374. if (IsLineEnd(*m_DataIt) || *m_DataIt == '#') {
  375. break;
  376. }
  377. if (*m_DataIt == '/') {
  378. if (type == aiPrimitiveType_POINT) {
  379. ASSIMP_LOG_ERROR("Obj: Separator unexpected in point statement");
  380. }
  381. iPos++;
  382. } else if (IsSpaceOrNewLine(*m_DataIt)) {
  383. iPos = 0;
  384. } else {
  385. //OBJ USES 1 Base ARRAYS!!!!
  386. int iVal;
  387. auto end = m_DataIt;
  388. // find either the buffer end or the '\0'
  389. while (end < m_DataItEnd && *end != '\0')
  390. ++end;
  391. // avoid temporary string allocation if there is a zero
  392. if (end != m_DataItEnd) {
  393. iVal = ::atoi(&(*m_DataIt));
  394. } else {
  395. // otherwise make a zero terminated copy, which is safe to pass to atoi
  396. std::string number(&(*m_DataIt), m_DataItEnd - m_DataIt);
  397. iVal = ::atoi(number.c_str());
  398. }
  399. // increment iStep position based off of the sign and # of digits
  400. int tmp = iVal;
  401. if (iVal < 0) {
  402. ++iStep;
  403. }
  404. while ((tmp = tmp / 10) != 0) {
  405. ++iStep;
  406. }
  407. if (iPos == 1 && !vt && vn) {
  408. iPos = 2; // skip texture coords for normals if there are no tex coords
  409. }
  410. if (iVal > 0) {
  411. // Store parsed index
  412. if (0 == iPos) {
  413. face->m_vertices.push_back(iVal - 1);
  414. } else if (1 == iPos) {
  415. face->m_texturCoords.push_back(iVal - 1);
  416. } else if (2 == iPos) {
  417. face->m_normals.push_back(iVal - 1);
  418. hasNormal = true;
  419. } else {
  420. reportErrorTokenInFace();
  421. }
  422. } else if (iVal < 0) {
  423. // Store relatively index
  424. if (0 == iPos) {
  425. face->m_vertices.push_back(vSize + iVal);
  426. } else if (1 == iPos) {
  427. face->m_texturCoords.push_back(vtSize + iVal);
  428. } else if (2 == iPos) {
  429. face->m_normals.push_back(vnSize + iVal);
  430. hasNormal = true;
  431. } else {
  432. reportErrorTokenInFace();
  433. }
  434. } else {
  435. //On error, std::atoi will return 0 which is not a valid value
  436. delete face;
  437. throw DeadlyImportError("OBJ: Invalid face index.");
  438. }
  439. }
  440. m_DataIt += iStep;
  441. }
  442. if (face->m_vertices.empty()) {
  443. ASSIMP_LOG_ERROR("Obj: Ignoring empty face");
  444. // skip line and clean up
  445. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  446. delete face;
  447. return;
  448. }
  449. // Set active material, if one set
  450. if (nullptr != m_pModel->mCurrentMaterial) {
  451. face->m_pMaterial = m_pModel->mCurrentMaterial;
  452. } else {
  453. face->m_pMaterial = m_pModel->mDefaultMaterial;
  454. }
  455. // Create a default object, if nothing is there
  456. if (nullptr == m_pModel->mCurrentObject) {
  457. createObject(DefaultObjName);
  458. }
  459. // Assign face to mesh
  460. if (nullptr == m_pModel->mCurrentMesh) {
  461. createMesh(DefaultObjName);
  462. }
  463. // Store the face
  464. m_pModel->mCurrentMesh->m_Faces.emplace_back(face);
  465. m_pModel->mCurrentMesh->m_uiNumIndices += static_cast<unsigned int>(face->m_vertices.size());
  466. m_pModel->mCurrentMesh->m_uiUVCoordinates[0] += static_cast<unsigned int>(face->m_texturCoords.size());
  467. if (!m_pModel->mCurrentMesh->m_hasNormals && hasNormal) {
  468. m_pModel->mCurrentMesh->m_hasNormals = true;
  469. }
  470. // Skip the rest of the line
  471. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  472. }
  473. void ObjFileParser::getMaterialDesc() {
  474. // Get next data for material data
  475. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  476. if (m_DataIt == m_DataItEnd) {
  477. return;
  478. }
  479. char *pStart = &(*m_DataIt);
  480. while (m_DataIt != m_DataItEnd && !IsLineEnd(*m_DataIt)) {
  481. ++m_DataIt;
  482. }
  483. // In some cases we should ignore this 'usemtl' command, this variable helps us to do so
  484. bool skip = false;
  485. // Get name
  486. std::string strName(pStart, &(*m_DataIt));
  487. strName = ai_trim(strName);
  488. if (strName.empty()) {
  489. skip = true;
  490. }
  491. // If the current mesh has the same material, we will ignore that 'usemtl' command
  492. // There is no need to create another object or even mesh here
  493. if (!skip) {
  494. if (m_pModel->mCurrentMaterial && m_pModel->mCurrentMaterial->MaterialName == aiString(strName)) {
  495. skip = true;
  496. }
  497. }
  498. if (!skip) {
  499. // Search for material
  500. std::map<std::string, ObjFile::Material *>::iterator it = m_pModel->mMaterialMap.find(strName);
  501. if (it == m_pModel->mMaterialMap.end()) {
  502. // Not found, so we don't know anything about the material except for its name.
  503. // This may be the case if the material library is missing. We don't want to lose all
  504. // materials if that happens, so create a new named material instead of discarding it
  505. // completely.
  506. ASSIMP_LOG_ERROR("OBJ: failed to locate material ", strName, ", creating new material");
  507. m_pModel->mCurrentMaterial = new ObjFile::Material();
  508. m_pModel->mCurrentMaterial->MaterialName.Set(strName);
  509. m_pModel->mMaterialLib.push_back(strName);
  510. m_pModel->mMaterialMap[strName] = m_pModel->mCurrentMaterial;
  511. } else {
  512. // Found, using detected material
  513. m_pModel->mCurrentMaterial = (*it).second;
  514. }
  515. if (needsNewMesh(strName)) {
  516. auto newMeshName = m_pModel->mActiveGroup.empty() ? strName : m_pModel->mActiveGroup;
  517. createMesh(newMeshName);
  518. }
  519. m_pModel->mCurrentMesh->m_uiMaterialIndex = getMaterialIndex(strName);
  520. }
  521. // Skip rest of line
  522. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  523. }
  524. // -------------------------------------------------------------------
  525. // Get a comment, values will be skipped
  526. void ObjFileParser::getComment() {
  527. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  528. }
  529. // -------------------------------------------------------------------
  530. // Get material library from file.
  531. void ObjFileParser::getMaterialLib() {
  532. // Translate tuple
  533. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  534. if (m_DataIt == m_DataItEnd) {
  535. return;
  536. }
  537. char *pStart = &(*m_DataIt);
  538. while (m_DataIt != m_DataItEnd && !IsLineEnd(*m_DataIt)) {
  539. ++m_DataIt;
  540. }
  541. // Check for existence
  542. const std::string strMatName(pStart, &(*m_DataIt));
  543. std::string absName;
  544. // Check if directive is valid.
  545. if (0 == strMatName.length()) {
  546. ASSIMP_LOG_WARN("OBJ: no name for material library specified.");
  547. return;
  548. }
  549. if (m_pIO->StackSize() > 0) {
  550. std::string path = m_pIO->CurrentDirectory();
  551. if ('/' != *path.rbegin()) {
  552. path += '/';
  553. }
  554. absName += path;
  555. absName += strMatName;
  556. } else {
  557. absName = strMatName;
  558. }
  559. std::unique_ptr<IOStream> pFile(m_pIO->Open(absName));
  560. if (nullptr == pFile) {
  561. ASSIMP_LOG_ERROR("OBJ: Unable to locate material file ", strMatName);
  562. std::string strMatFallbackName = m_originalObjFileName.substr(0, m_originalObjFileName.length() - 3) + "mtl";
  563. ASSIMP_LOG_INFO("OBJ: Opening fallback material file ", strMatFallbackName);
  564. pFile.reset(m_pIO->Open(strMatFallbackName));
  565. if (!pFile) {
  566. ASSIMP_LOG_ERROR("OBJ: Unable to locate fallback material file ", strMatFallbackName);
  567. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  568. return;
  569. }
  570. }
  571. // Import material library data from file.
  572. // Some exporters (e.g. Silo) will happily write out empty
  573. // material files if the model doesn't use any materials, so we
  574. // allow that.
  575. std::vector<char> buffer;
  576. BaseImporter::TextFileToBuffer(pFile.get(), buffer, BaseImporter::ALLOW_EMPTY);
  577. //m_pIO->Close(pFile);
  578. // Importing the material library
  579. ObjFileMtlImporter mtlImporter(buffer, strMatName, m_pModel.get());
  580. }
  581. // -------------------------------------------------------------------
  582. // Set a new material definition as the current material.
  583. void ObjFileParser::getNewMaterial() {
  584. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  585. m_DataIt = getNextWord<DataArrayIt>(m_DataIt, m_DataItEnd);
  586. if (m_DataIt == m_DataItEnd) {
  587. return;
  588. }
  589. char *pStart = &(*m_DataIt);
  590. std::string strMat(pStart, *m_DataIt);
  591. while (m_DataIt != m_DataItEnd && IsSpaceOrNewLine(*m_DataIt)) {
  592. ++m_DataIt;
  593. }
  594. std::map<std::string, ObjFile::Material *>::iterator it = m_pModel->mMaterialMap.find(strMat);
  595. if (it == m_pModel->mMaterialMap.end()) {
  596. // Show a warning, if material was not found
  597. ASSIMP_LOG_WARN("OBJ: Unsupported material requested: ", strMat);
  598. m_pModel->mCurrentMaterial = m_pModel->mDefaultMaterial;
  599. } else {
  600. // Set new material
  601. if (needsNewMesh(strMat)) {
  602. createMesh(strMat);
  603. }
  604. m_pModel->mCurrentMesh->m_uiMaterialIndex = getMaterialIndex(strMat);
  605. }
  606. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  607. }
  608. // -------------------------------------------------------------------
  609. int ObjFileParser::getMaterialIndex(const std::string &strMaterialName) {
  610. int mat_index = -1;
  611. if (strMaterialName.empty()) {
  612. return mat_index;
  613. }
  614. for (size_t index = 0; index < m_pModel->mMaterialLib.size(); ++index) {
  615. if (strMaterialName == m_pModel->mMaterialLib[index]) {
  616. mat_index = (int)index;
  617. break;
  618. }
  619. }
  620. return mat_index;
  621. }
  622. // -------------------------------------------------------------------
  623. // Getter for a group name.
  624. void ObjFileParser::getGroupName() {
  625. std::string groupName;
  626. // here we skip 'g ' from line
  627. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  628. m_DataIt = getName<DataArrayIt>(m_DataIt, m_DataItEnd, groupName);
  629. if (isEndOfBuffer(m_DataIt, m_DataItEnd)) {
  630. return;
  631. }
  632. // Change active group, if necessary
  633. if (m_pModel->mActiveGroup != groupName) {
  634. // Search for already existing entry
  635. ObjFile::Model::ConstGroupMapIt it = m_pModel->mGroups.find(groupName);
  636. // We are mapping groups into the object structure
  637. createObject(groupName);
  638. // New group name, creating a new entry
  639. if (it == m_pModel->mGroups.end()) {
  640. std::vector<unsigned int> *pFaceIDArray = new std::vector<unsigned int>;
  641. m_pModel->mGroups[groupName] = pFaceIDArray;
  642. m_pModel->mGroupFaceIDs = (pFaceIDArray);
  643. } else {
  644. m_pModel->mGroupFaceIDs = (*it).second;
  645. }
  646. m_pModel->mActiveGroup = groupName;
  647. }
  648. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  649. }
  650. // -------------------------------------------------------------------
  651. // Not supported
  652. void ObjFileParser::getGroupNumber() {
  653. // Not used
  654. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  655. }
  656. // -------------------------------------------------------------------
  657. // Not supported
  658. void ObjFileParser::getGroupNumberAndResolution() {
  659. // Not used
  660. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  661. }
  662. // -------------------------------------------------------------------
  663. // Stores values for a new object instance, name will be used to
  664. // identify it.
  665. void ObjFileParser::getObjectName() {
  666. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  667. if (m_DataIt == m_DataItEnd) {
  668. return;
  669. }
  670. char *pStart = &(*m_DataIt);
  671. while (m_DataIt != m_DataItEnd && !IsSpaceOrNewLine(*m_DataIt)) {
  672. ++m_DataIt;
  673. }
  674. std::string strObjectName(pStart, &(*m_DataIt));
  675. if (!strObjectName.empty()) {
  676. // Reset current object
  677. m_pModel->mCurrentObject = nullptr;
  678. // Search for actual object
  679. for (std::vector<ObjFile::Object *>::const_iterator it = m_pModel->mObjects.begin();
  680. it != m_pModel->mObjects.end();
  681. ++it) {
  682. if ((*it)->m_strObjName == strObjectName) {
  683. m_pModel->mCurrentObject = *it;
  684. break;
  685. }
  686. }
  687. // Allocate a new object, if current one was not found before
  688. if (nullptr == m_pModel->mCurrentObject) {
  689. createObject(strObjectName);
  690. }
  691. }
  692. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  693. }
  694. // -------------------------------------------------------------------
  695. // Creates a new object instance
  696. void ObjFileParser::createObject(const std::string &objName) {
  697. ai_assert(nullptr != m_pModel);
  698. m_pModel->mCurrentObject = new ObjFile::Object;
  699. m_pModel->mCurrentObject->m_strObjName = objName;
  700. m_pModel->mObjects.push_back(m_pModel->mCurrentObject);
  701. createMesh(objName);
  702. if (m_pModel->mCurrentMaterial) {
  703. m_pModel->mCurrentMesh->m_uiMaterialIndex =
  704. getMaterialIndex(m_pModel->mCurrentMaterial->MaterialName.data);
  705. m_pModel->mCurrentMesh->m_pMaterial = m_pModel->mCurrentMaterial;
  706. }
  707. }
  708. // -------------------------------------------------------------------
  709. // Creates a new mesh
  710. void ObjFileParser::createMesh(const std::string &meshName) {
  711. ai_assert(nullptr != m_pModel);
  712. m_pModel->mCurrentMesh = new ObjFile::Mesh(meshName);
  713. m_pModel->mMeshes.push_back(m_pModel->mCurrentMesh);
  714. unsigned int meshId = static_cast<unsigned int>(m_pModel->mMeshes.size() - 1);
  715. if (nullptr != m_pModel->mCurrentObject) {
  716. m_pModel->mCurrentObject->m_Meshes.push_back(meshId);
  717. } else {
  718. ASSIMP_LOG_ERROR("OBJ: No object detected to attach a new mesh instance.");
  719. }
  720. }
  721. // -------------------------------------------------------------------
  722. // Returns true, if a new mesh must be created.
  723. bool ObjFileParser::needsNewMesh(const std::string &materialName) {
  724. // If no mesh data yet
  725. if (m_pModel->mCurrentMesh == nullptr) {
  726. return true;
  727. }
  728. bool newMat = false;
  729. int matIdx = getMaterialIndex(materialName);
  730. int curMatIdx = m_pModel->mCurrentMesh->m_uiMaterialIndex;
  731. if (curMatIdx != int(ObjFile::Mesh::NoMaterial) && curMatIdx != matIdx
  732. // no need create a new mesh if no faces in current
  733. // lets say 'usemtl' goes straight after 'g'
  734. && !m_pModel->mCurrentMesh->m_Faces.empty()) {
  735. // New material -> only one material per mesh, so we need to create a new
  736. // material
  737. newMat = true;
  738. }
  739. return newMat;
  740. }
  741. // -------------------------------------------------------------------
  742. // Shows an error in parsing process.
  743. void ObjFileParser::reportErrorTokenInFace() {
  744. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  745. ASSIMP_LOG_ERROR("OBJ: Not supported token in face description detected");
  746. }
  747. // -------------------------------------------------------------------
  748. } // Namespace Assimp
  749. #endif // !! ASSIMP_BUILD_NO_OBJ_IMPORTER