ObjFileParser.cpp 30 KB

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