ObjFileParser.cpp 28 KB

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