ObjFileParser.cpp 28 KB

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