ObjFileParser.cpp 28 KB

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