ObjFileParser.cpp 28 KB

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