ObjFileParser.cpp 28 KB

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