2
0

ObjFileParser.cpp 29 KB

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