ObjFileParser.cpp 29 KB

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