2
0

ObjFileParser.cpp 28 KB

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