ObjFileParser.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2020, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. #ifndef ASSIMP_BUILD_NO_OBJ_IMPORTER
  35. #include "ObjFileParser.h"
  36. #include "ObjFileData.h"
  37. #include "ObjFileMtlImporter.h"
  38. #include "ObjTools.h"
  39. #include <assimp/BaseImporter.h>
  40. #include <assimp/DefaultIOSystem.h>
  41. #include <assimp/ParsingUtils.h>
  42. #include <assimp/DefaultLogger.hpp>
  43. #include <assimp/Importer.hpp>
  44. #include <cstdlib>
  45. #include <memory>
  46. #include <utility>
  47. namespace Assimp {
  48. constexpr const char ObjFileParser::DEFAULT_MATERIAL[];
  49. ObjFileParser::ObjFileParser() :
  50. m_DataIt(),
  51. m_DataItEnd(),
  52. m_pModel(nullptr),
  53. m_uiLine(0),
  54. m_buffer(),
  55. m_pIO(nullptr),
  56. m_progress(nullptr),
  57. m_originalObjFileName() {
  58. std::fill_n(m_buffer, Buffersize, '\0');
  59. }
  60. ObjFileParser::ObjFileParser(IOStreamBuffer<char> &streamBuffer, const std::string &modelName,
  61. IOSystem *io, ProgressHandler *progress,
  62. const std::string &originalObjFileName) :
  63. m_DataIt(),
  64. m_DataItEnd(),
  65. m_pModel(nullptr),
  66. m_uiLine(0),
  67. m_buffer(),
  68. m_pIO(io),
  69. m_progress(progress),
  70. m_originalObjFileName(originalObjFileName) {
  71. std::fill_n(m_buffer, Buffersize, '\0');
  72. // Create the model instance to store all the data
  73. m_pModel.reset(new ObjFile::Model());
  74. m_pModel->m_ModelName = modelName;
  75. // create default material and store it
  76. m_pModel->m_pDefaultMaterial = new ObjFile::Material;
  77. m_pModel->m_pDefaultMaterial->MaterialName.Set(DEFAULT_MATERIAL);
  78. m_pModel->m_MaterialLib.push_back(DEFAULT_MATERIAL);
  79. m_pModel->m_MaterialMap[DEFAULT_MATERIAL] = m_pModel->m_pDefaultMaterial;
  80. // Start parsing the file
  81. parseFile(streamBuffer);
  82. }
  83. ObjFileParser::~ObjFileParser() {
  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. unsigned int progressCounter = 0;
  96. const unsigned int bytesToProcess = static_cast<unsigned int>(streamBuffer.size());
  97. const unsigned int progressTotal = bytesToProcess;
  98. unsigned int processed = 0;
  99. size_t lastFilePos(0);
  100. bool insideCstype = false;
  101. std::vector<char> buffer;
  102. while (streamBuffer.getNextDataLine(buffer, '\\')) {
  103. m_DataIt = buffer.begin();
  104. m_DataItEnd = buffer.end();
  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. progressCounter++;
  111. m_progress->UpdateFileRead(processed, progressTotal);
  112. }
  113. // handle cstype section end (http://paulbourke.net/dataformats/obj/)
  114. if (insideCstype) {
  115. switch (*m_DataIt) {
  116. case 'e': {
  117. std::string name;
  118. getNameNoSpace(m_DataIt, m_DataItEnd, name);
  119. insideCstype = name != "end";
  120. } break;
  121. }
  122. goto pf_skip_line;
  123. }
  124. // parse line
  125. switch (*m_DataIt) {
  126. case 'v': // Parse a vertex texture coordinate
  127. {
  128. ++m_DataIt;
  129. if (*m_DataIt == ' ' || *m_DataIt == '\t') {
  130. size_t numComponents = getNumComponentsInDataDefinition();
  131. if (numComponents == 3) {
  132. // read in vertex definition
  133. getVector3(m_pModel->m_Vertices);
  134. } else if (numComponents == 4) {
  135. // read in vertex definition (homogeneous coords)
  136. getHomogeneousVector3(m_pModel->m_Vertices);
  137. } else if (numComponents == 6) {
  138. // read vertex and vertex-color
  139. getTwoVectors3(m_pModel->m_Vertices, m_pModel->m_VertexColors);
  140. }
  141. } else if (*m_DataIt == 't') {
  142. // read in texture coordinate ( 2D or 3D )
  143. ++m_DataIt;
  144. size_t dim = getTexCoordVector(m_pModel->m_TextureCoord);
  145. m_pModel->m_TextureCoordDim = std::max(m_pModel->m_TextureCoordDim, (unsigned int)dim);
  146. } else if (*m_DataIt == 'n') {
  147. // Read in normal vector definition
  148. ++m_DataIt;
  149. getVector3(m_pModel->m_Normals);
  150. }
  151. } break;
  152. case 'p': // Parse a face, line or point statement
  153. case 'l':
  154. case 'f': {
  155. getFace(*m_DataIt == 'f' ? aiPrimitiveType_POLYGON : (*m_DataIt == 'l' ? aiPrimitiveType_LINE : aiPrimitiveType_POINT));
  156. } break;
  157. case '#': // Parse a comment
  158. {
  159. getComment();
  160. } break;
  161. case 'u': // Parse a material desc. setter
  162. {
  163. std::string name;
  164. getNameNoSpace(m_DataIt, m_DataItEnd, name);
  165. size_t nextSpace = name.find(' ');
  166. if (nextSpace != std::string::npos)
  167. name = name.substr(0, nextSpace);
  168. if (name == "usemtl") {
  169. getMaterialDesc();
  170. }
  171. } break;
  172. case 'm': // Parse a material library or merging group ('mg')
  173. {
  174. std::string name;
  175. getNameNoSpace(m_DataIt, m_DataItEnd, name);
  176. size_t nextSpace = name.find(' ');
  177. if (nextSpace != std::string::npos)
  178. name = name.substr(0, nextSpace);
  179. if (name == "mg")
  180. getGroupNumberAndResolution();
  181. else if (name == "mtllib")
  182. getMaterialLib();
  183. else
  184. goto pf_skip_line;
  185. } break;
  186. case 'g': // Parse group name
  187. {
  188. getGroupName();
  189. } break;
  190. case 's': // Parse group number
  191. {
  192. getGroupNumber();
  193. } break;
  194. case 'o': // Parse object name
  195. {
  196. getObjectName();
  197. } break;
  198. case 'c': // handle cstype section start
  199. {
  200. std::string name;
  201. getNameNoSpace(m_DataIt, m_DataItEnd, name);
  202. insideCstype = name == "cstype";
  203. goto pf_skip_line;
  204. } break;
  205. default: {
  206. pf_skip_line:
  207. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  208. } break;
  209. }
  210. }
  211. }
  212. void ObjFileParser::copyNextWord(char *pBuffer, size_t length) {
  213. size_t index = 0;
  214. m_DataIt = getNextWord<DataArrayIt>(m_DataIt, m_DataItEnd);
  215. if (*m_DataIt == '\\') {
  216. ++m_DataIt;
  217. ++m_DataIt;
  218. m_DataIt = getNextWord<DataArrayIt>(m_DataIt, m_DataItEnd);
  219. }
  220. while (m_DataIt != m_DataItEnd && !IsSpaceOrNewLine(*m_DataIt)) {
  221. pBuffer[index] = *m_DataIt;
  222. index++;
  223. if (index == length - 1) {
  224. break;
  225. }
  226. ++m_DataIt;
  227. }
  228. ai_assert(index < length);
  229. pBuffer[index] = '\0';
  230. }
  231. static bool isDataDefinitionEnd(const char *tmp) {
  232. if (*tmp == '\\') {
  233. tmp++;
  234. if (IsLineEnd(*tmp)) {
  235. return true;
  236. }
  237. }
  238. return false;
  239. }
  240. static bool isNanOrInf(const char *in) {
  241. // Look for "nan" or "inf", case insensitive
  242. return ((in[0] == 'N' || in[0] == 'n') && ASSIMP_strincmp(in, "nan", 3) == 0) ||
  243. ((in[0] == 'I' || in[0] == 'i') && ASSIMP_strincmp(in, "inf", 3) == 0);
  244. }
  245. size_t ObjFileParser::getNumComponentsInDataDefinition() {
  246. size_t numComponents(0);
  247. const char *tmp(&m_DataIt[0]);
  248. bool end_of_definition = false;
  249. while (!end_of_definition) {
  250. if (isDataDefinitionEnd(tmp)) {
  251. tmp += 2;
  252. } else if (IsLineEnd(*tmp)) {
  253. end_of_definition = true;
  254. }
  255. if (!SkipSpaces(&tmp)) {
  256. break;
  257. }
  258. const bool isNum(IsNumeric(*tmp) || isNanOrInf(tmp));
  259. SkipToken(tmp);
  260. if (isNum) {
  261. ++numComponents;
  262. }
  263. if (!SkipSpaces(&tmp)) {
  264. break;
  265. }
  266. }
  267. return numComponents;
  268. }
  269. size_t ObjFileParser::getTexCoordVector(std::vector<aiVector3D> &point3d_array) {
  270. size_t numComponents = getNumComponentsInDataDefinition();
  271. ai_real x, y, z;
  272. if (2 == numComponents) {
  273. copyNextWord(m_buffer, Buffersize);
  274. x = (ai_real)fast_atof(m_buffer);
  275. copyNextWord(m_buffer, Buffersize);
  276. y = (ai_real)fast_atof(m_buffer);
  277. z = 0.0;
  278. } else if (3 == numComponents) {
  279. copyNextWord(m_buffer, Buffersize);
  280. x = (ai_real)fast_atof(m_buffer);
  281. copyNextWord(m_buffer, Buffersize);
  282. y = (ai_real)fast_atof(m_buffer);
  283. copyNextWord(m_buffer, Buffersize);
  284. z = (ai_real)fast_atof(m_buffer);
  285. } else {
  286. throw DeadlyImportError("OBJ: Invalid number of components");
  287. }
  288. // Coerce nan and inf to 0 as is the OBJ default value
  289. if (!std::isfinite(x))
  290. x = 0;
  291. if (!std::isfinite(y))
  292. y = 0;
  293. if (!std::isfinite(z))
  294. z = 0;
  295. point3d_array.emplace_back(x, y, z);
  296. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  297. return numComponents;
  298. }
  299. void ObjFileParser::getVector3(std::vector<aiVector3D> &point3d_array) {
  300. ai_real x, y, z;
  301. copyNextWord(m_buffer, Buffersize);
  302. x = (ai_real)fast_atof(m_buffer);
  303. copyNextWord(m_buffer, Buffersize);
  304. y = (ai_real)fast_atof(m_buffer);
  305. copyNextWord(m_buffer, Buffersize);
  306. z = (ai_real)fast_atof(m_buffer);
  307. point3d_array.emplace_back(x, y, z);
  308. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  309. }
  310. void ObjFileParser::getHomogeneousVector3(std::vector<aiVector3D> &point3d_array) {
  311. ai_real x, y, z, w;
  312. copyNextWord(m_buffer, Buffersize);
  313. x = (ai_real)fast_atof(m_buffer);
  314. copyNextWord(m_buffer, Buffersize);
  315. y = (ai_real)fast_atof(m_buffer);
  316. copyNextWord(m_buffer, Buffersize);
  317. z = (ai_real)fast_atof(m_buffer);
  318. copyNextWord(m_buffer, Buffersize);
  319. w = (ai_real)fast_atof(m_buffer);
  320. if (w == 0)
  321. throw DeadlyImportError("OBJ: Invalid component in homogeneous vector (Division by zero)");
  322. point3d_array.emplace_back(x / w, y / w, z / w);
  323. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  324. }
  325. void ObjFileParser::getTwoVectors3(std::vector<aiVector3D> &point3d_array_a, std::vector<aiVector3D> &point3d_array_b) {
  326. ai_real x, y, z;
  327. copyNextWord(m_buffer, Buffersize);
  328. x = (ai_real)fast_atof(m_buffer);
  329. copyNextWord(m_buffer, Buffersize);
  330. y = (ai_real)fast_atof(m_buffer);
  331. copyNextWord(m_buffer, Buffersize);
  332. z = (ai_real)fast_atof(m_buffer);
  333. point3d_array_a.emplace_back(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_b.emplace_back(x, y, z);
  341. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  342. }
  343. void ObjFileParser::getVector2(std::vector<aiVector2D> &point2d_array) {
  344. ai_real x, y;
  345. copyNextWord(m_buffer, Buffersize);
  346. x = (ai_real)fast_atof(m_buffer);
  347. copyNextWord(m_buffer, Buffersize);
  348. y = (ai_real)fast_atof(m_buffer);
  349. point2d_array.emplace_back(x, y);
  350. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  351. }
  352. static const std::string DefaultObjName = "defaultobject";
  353. void ObjFileParser::getFace(aiPrimitiveType type) {
  354. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  355. if (m_DataIt == m_DataItEnd || *m_DataIt == '\0') {
  356. return;
  357. }
  358. ObjFile::Face *face = new ObjFile::Face(type);
  359. bool hasNormal = false;
  360. const int vSize = static_cast<unsigned int>(m_pModel->m_Vertices.size());
  361. const int vtSize = static_cast<unsigned int>(m_pModel->m_TextureCoord.size());
  362. const int vnSize = static_cast<unsigned int>(m_pModel->m_Normals.size());
  363. const bool vt = (!m_pModel->m_TextureCoord.empty());
  364. const bool vn = (!m_pModel->m_Normals.empty());
  365. int iPos = 0;
  366. while (m_DataIt != m_DataItEnd) {
  367. int iStep = 1;
  368. if (IsLineEnd(*m_DataIt)) {
  369. break;
  370. }
  371. if (*m_DataIt == '/') {
  372. if (type == aiPrimitiveType_POINT) {
  373. ASSIMP_LOG_ERROR("Obj: Separator unexpected in point statement");
  374. }
  375. iPos++;
  376. } else if (IsSpaceOrNewLine(*m_DataIt)) {
  377. iPos = 0;
  378. } else {
  379. //OBJ USES 1 Base ARRAYS!!!!
  380. const int iVal(::atoi(&(*m_DataIt)));
  381. // increment iStep position based off of the sign and # of digits
  382. int tmp = iVal;
  383. if (iVal < 0) {
  384. ++iStep;
  385. }
  386. while ((tmp = tmp / 10) != 0) {
  387. ++iStep;
  388. }
  389. if (iPos == 1 && !vt && vn)
  390. iPos = 2; // skip texture coords for normals if there are no tex coords
  391. if (iVal > 0) {
  392. // Store parsed index
  393. if (0 == iPos) {
  394. face->m_vertices.push_back(iVal - 1);
  395. } else if (1 == iPos) {
  396. face->m_texturCoords.push_back(iVal - 1);
  397. } else if (2 == iPos) {
  398. face->m_normals.push_back(iVal - 1);
  399. hasNormal = true;
  400. } else {
  401. reportErrorTokenInFace();
  402. }
  403. } else if (iVal < 0) {
  404. // Store relatively index
  405. if (0 == iPos) {
  406. face->m_vertices.push_back(vSize + iVal);
  407. } else if (1 == iPos) {
  408. face->m_texturCoords.push_back(vtSize + iVal);
  409. } else if (2 == iPos) {
  410. face->m_normals.push_back(vnSize + iVal);
  411. hasNormal = true;
  412. } else {
  413. reportErrorTokenInFace();
  414. }
  415. } else {
  416. //On error, std::atoi will return 0 which is not a valid value
  417. delete face;
  418. throw DeadlyImportError("OBJ: Invalid face indice");
  419. }
  420. }
  421. m_DataIt += iStep;
  422. }
  423. if (face->m_vertices.empty()) {
  424. ASSIMP_LOG_ERROR("Obj: Ignoring empty face");
  425. // skip line and clean up
  426. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  427. delete face;
  428. return;
  429. }
  430. // Set active material, if one set
  431. if (nullptr != m_pModel->m_pCurrentMaterial) {
  432. face->m_pMaterial = m_pModel->m_pCurrentMaterial;
  433. } else {
  434. face->m_pMaterial = m_pModel->m_pDefaultMaterial;
  435. }
  436. // Create a default object, if nothing is there
  437. if (nullptr == m_pModel->m_pCurrent) {
  438. createObject(DefaultObjName);
  439. }
  440. // Assign face to mesh
  441. if (nullptr == m_pModel->m_pCurrentMesh) {
  442. createMesh(DefaultObjName);
  443. }
  444. // Store the face
  445. m_pModel->m_pCurrentMesh->m_Faces.push_back(face);
  446. m_pModel->m_pCurrentMesh->m_uiNumIndices += (unsigned int)face->m_vertices.size();
  447. m_pModel->m_pCurrentMesh->m_uiUVCoordinates[0] += (unsigned int)face->m_texturCoords.size();
  448. if (!m_pModel->m_pCurrentMesh->m_hasNormals && hasNormal) {
  449. m_pModel->m_pCurrentMesh->m_hasNormals = true;
  450. }
  451. // Skip the rest of the line
  452. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  453. }
  454. void ObjFileParser::getMaterialDesc() {
  455. // Get next data for material data
  456. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  457. if (m_DataIt == m_DataItEnd) {
  458. return;
  459. }
  460. char *pStart = &(*m_DataIt);
  461. while (m_DataIt != m_DataItEnd && !IsLineEnd(*m_DataIt)) {
  462. ++m_DataIt;
  463. }
  464. // In some cases we should ignore this 'usemtl' command, this variable helps us to do so
  465. bool skip = false;
  466. // Get name
  467. std::string strName(pStart, &(*m_DataIt));
  468. strName = trim_whitespaces(strName);
  469. if (strName.empty())
  470. skip = true;
  471. // If the current mesh has the same material, we simply ignore that 'usemtl' command
  472. // There is no need to create another object or even mesh here
  473. if (m_pModel->m_pCurrentMaterial && m_pModel->m_pCurrentMaterial->MaterialName == aiString(strName)) {
  474. skip = true;
  475. }
  476. if (!skip) {
  477. // Search for material
  478. std::map<std::string, ObjFile::Material *>::iterator it = m_pModel->m_MaterialMap.find(strName);
  479. if (it == m_pModel->m_MaterialMap.end()) {
  480. // Not found, so we don't know anything about the material except for its name.
  481. // This may be the case if the material library is missing. We don't want to lose all
  482. // materials if that happens, so create a new named material instead of discarding it
  483. // completely.
  484. ASSIMP_LOG_ERROR("OBJ: failed to locate material ", strName, ", creating new material");
  485. m_pModel->m_pCurrentMaterial = new ObjFile::Material();
  486. m_pModel->m_pCurrentMaterial->MaterialName.Set(strName);
  487. m_pModel->m_MaterialLib.push_back(strName);
  488. m_pModel->m_MaterialMap[strName] = m_pModel->m_pCurrentMaterial;
  489. } else {
  490. // Found, using detected material
  491. m_pModel->m_pCurrentMaterial = (*it).second;
  492. }
  493. if (needsNewMesh(strName)) {
  494. createMesh(strName);
  495. }
  496. m_pModel->m_pCurrentMesh->m_uiMaterialIndex = getMaterialIndex(strName);
  497. }
  498. // Skip rest of line
  499. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  500. }
  501. // -------------------------------------------------------------------
  502. // Get a comment, values will be skipped
  503. void ObjFileParser::getComment() {
  504. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  505. }
  506. // -------------------------------------------------------------------
  507. // Get material library from file.
  508. void ObjFileParser::getMaterialLib() {
  509. // Translate tuple
  510. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  511. if (m_DataIt == m_DataItEnd) {
  512. return;
  513. }
  514. char *pStart = &(*m_DataIt);
  515. while (m_DataIt != m_DataItEnd && !IsLineEnd(*m_DataIt)) {
  516. ++m_DataIt;
  517. }
  518. // Check for existence
  519. const std::string strMatName(pStart, &(*m_DataIt));
  520. std::string absName;
  521. // Check if directive is valid.
  522. if (0 == strMatName.length()) {
  523. ASSIMP_LOG_WARN("OBJ: no name for material library specified.");
  524. return;
  525. }
  526. if (m_pIO->StackSize() > 0) {
  527. std::string path = m_pIO->CurrentDirectory();
  528. if ('/' != *path.rbegin()) {
  529. path += '/';
  530. }
  531. absName += path;
  532. absName += strMatName;
  533. } else {
  534. absName = strMatName;
  535. }
  536. IOStream *pFile = m_pIO->Open(absName);
  537. if (nullptr == pFile) {
  538. ASSIMP_LOG_ERROR("OBJ: Unable to locate material file ", strMatName);
  539. std::string strMatFallbackName = m_originalObjFileName.substr(0, m_originalObjFileName.length() - 3) + "mtl";
  540. ASSIMP_LOG_INFO("OBJ: Opening fallback material file ", strMatFallbackName);
  541. pFile = m_pIO->Open(strMatFallbackName);
  542. if (!pFile) {
  543. ASSIMP_LOG_ERROR("OBJ: Unable to locate fallback material file ", strMatFallbackName);
  544. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  545. return;
  546. }
  547. }
  548. // Import material library data from file.
  549. // Some exporters (e.g. Silo) will happily write out empty
  550. // material files if the model doesn't use any materials, so we
  551. // allow that.
  552. std::vector<char> buffer;
  553. BaseImporter::TextFileToBuffer(pFile, buffer, BaseImporter::ALLOW_EMPTY);
  554. m_pIO->Close(pFile);
  555. // Importing the material library
  556. ObjFileMtlImporter mtlImporter(buffer, strMatName, m_pModel.get());
  557. }
  558. // -------------------------------------------------------------------
  559. // Set a new material definition as the current material.
  560. void ObjFileParser::getNewMaterial() {
  561. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  562. m_DataIt = getNextWord<DataArrayIt>(m_DataIt, m_DataItEnd);
  563. if (m_DataIt == m_DataItEnd) {
  564. return;
  565. }
  566. char *pStart = &(*m_DataIt);
  567. std::string strMat(pStart, *m_DataIt);
  568. while (m_DataIt != m_DataItEnd && IsSpaceOrNewLine(*m_DataIt)) {
  569. ++m_DataIt;
  570. }
  571. std::map<std::string, ObjFile::Material *>::iterator it = m_pModel->m_MaterialMap.find(strMat);
  572. if (it == m_pModel->m_MaterialMap.end()) {
  573. // Show a warning, if material was not found
  574. ASSIMP_LOG_WARN("OBJ: Unsupported material requested: ", strMat);
  575. m_pModel->m_pCurrentMaterial = m_pModel->m_pDefaultMaterial;
  576. } else {
  577. // Set new material
  578. if (needsNewMesh(strMat)) {
  579. createMesh(strMat);
  580. }
  581. m_pModel->m_pCurrentMesh->m_uiMaterialIndex = getMaterialIndex(strMat);
  582. }
  583. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  584. }
  585. // -------------------------------------------------------------------
  586. int ObjFileParser::getMaterialIndex(const std::string &strMaterialName) {
  587. int mat_index = -1;
  588. if (strMaterialName.empty()) {
  589. return mat_index;
  590. }
  591. for (size_t index = 0; index < m_pModel->m_MaterialLib.size(); ++index) {
  592. if (strMaterialName == m_pModel->m_MaterialLib[index]) {
  593. mat_index = (int)index;
  594. break;
  595. }
  596. }
  597. return mat_index;
  598. }
  599. // -------------------------------------------------------------------
  600. // Getter for a group name.
  601. void ObjFileParser::getGroupName() {
  602. std::string groupName;
  603. // here we skip 'g ' from line
  604. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  605. m_DataIt = getName<DataArrayIt>(m_DataIt, m_DataItEnd, groupName);
  606. if (isEndOfBuffer(m_DataIt, m_DataItEnd)) {
  607. return;
  608. }
  609. // Change active group, if necessary
  610. if (m_pModel->m_strActiveGroup != groupName) {
  611. // Search for already existing entry
  612. ObjFile::Model::ConstGroupMapIt it = m_pModel->m_Groups.find(groupName);
  613. // We are mapping groups into the object structure
  614. createObject(groupName);
  615. // New group name, creating a new entry
  616. if (it == m_pModel->m_Groups.end()) {
  617. std::vector<unsigned int> *pFaceIDArray = new std::vector<unsigned int>;
  618. m_pModel->m_Groups[groupName] = pFaceIDArray;
  619. m_pModel->m_pGroupFaceIDs = (pFaceIDArray);
  620. } else {
  621. m_pModel->m_pGroupFaceIDs = (*it).second;
  622. }
  623. m_pModel->m_strActiveGroup = groupName;
  624. }
  625. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  626. }
  627. // -------------------------------------------------------------------
  628. // Not supported
  629. void ObjFileParser::getGroupNumber() {
  630. // Not used
  631. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  632. }
  633. // -------------------------------------------------------------------
  634. // Not supported
  635. void ObjFileParser::getGroupNumberAndResolution() {
  636. // Not used
  637. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  638. }
  639. // -------------------------------------------------------------------
  640. // Stores values for a new object instance, name will be used to
  641. // identify it.
  642. void ObjFileParser::getObjectName() {
  643. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  644. if (m_DataIt == m_DataItEnd) {
  645. return;
  646. }
  647. char *pStart = &(*m_DataIt);
  648. while (m_DataIt != m_DataItEnd && !IsSpaceOrNewLine(*m_DataIt)) {
  649. ++m_DataIt;
  650. }
  651. std::string strObjectName(pStart, &(*m_DataIt));
  652. if (!strObjectName.empty()) {
  653. // Reset current object
  654. m_pModel->m_pCurrent = nullptr;
  655. // Search for actual object
  656. for (std::vector<ObjFile::Object *>::const_iterator it = m_pModel->m_Objects.begin();
  657. it != m_pModel->m_Objects.end();
  658. ++it) {
  659. if ((*it)->m_strObjName == strObjectName) {
  660. m_pModel->m_pCurrent = *it;
  661. break;
  662. }
  663. }
  664. // Allocate a new object, if current one was not found before
  665. if (nullptr == m_pModel->m_pCurrent) {
  666. createObject(strObjectName);
  667. }
  668. }
  669. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  670. }
  671. // -------------------------------------------------------------------
  672. // Creates a new object instance
  673. void ObjFileParser::createObject(const std::string &objName) {
  674. ai_assert(nullptr != m_pModel);
  675. m_pModel->m_pCurrent = new ObjFile::Object;
  676. m_pModel->m_pCurrent->m_strObjName = objName;
  677. m_pModel->m_Objects.push_back(m_pModel->m_pCurrent);
  678. createMesh(objName);
  679. if (m_pModel->m_pCurrentMaterial) {
  680. m_pModel->m_pCurrentMesh->m_uiMaterialIndex =
  681. getMaterialIndex(m_pModel->m_pCurrentMaterial->MaterialName.data);
  682. m_pModel->m_pCurrentMesh->m_pMaterial = m_pModel->m_pCurrentMaterial;
  683. }
  684. }
  685. // -------------------------------------------------------------------
  686. // Creates a new mesh
  687. void ObjFileParser::createMesh(const std::string &meshName) {
  688. ai_assert(nullptr != m_pModel);
  689. m_pModel->m_pCurrentMesh = new ObjFile::Mesh(meshName);
  690. m_pModel->m_Meshes.push_back(m_pModel->m_pCurrentMesh);
  691. unsigned int meshId = static_cast<unsigned int>(m_pModel->m_Meshes.size() - 1);
  692. if (nullptr != m_pModel->m_pCurrent) {
  693. m_pModel->m_pCurrent->m_Meshes.push_back(meshId);
  694. } else {
  695. ASSIMP_LOG_ERROR("OBJ: No object detected to attach a new mesh instance.");
  696. }
  697. }
  698. // -------------------------------------------------------------------
  699. // Returns true, if a new mesh must be created.
  700. bool ObjFileParser::needsNewMesh(const std::string &materialName) {
  701. // If no mesh data yet
  702. if (m_pModel->m_pCurrentMesh == nullptr) {
  703. return true;
  704. }
  705. bool newMat = false;
  706. int matIdx = getMaterialIndex(materialName);
  707. int curMatIdx = m_pModel->m_pCurrentMesh->m_uiMaterialIndex;
  708. if (curMatIdx != int(ObjFile::Mesh::NoMaterial) && curMatIdx != matIdx
  709. // no need create a new mesh if no faces in current
  710. // lets say 'usemtl' goes straight after 'g'
  711. && !m_pModel->m_pCurrentMesh->m_Faces.empty()) {
  712. // New material -> only one material per mesh, so we need to create a new
  713. // material
  714. newMat = true;
  715. }
  716. return newMat;
  717. }
  718. // -------------------------------------------------------------------
  719. // Shows an error in parsing process.
  720. void ObjFileParser::reportErrorTokenInFace() {
  721. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  722. ASSIMP_LOG_ERROR("OBJ: Not supported token in face description detected");
  723. }
  724. // -------------------------------------------------------------------
  725. } // Namespace Assimp
  726. #endif // !! ASSIMP_BUILD_NO_OBJ_IMPORTER