ObjFileParser.cpp 28 KB

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