ObjFileParser.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  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. ObjFile::Face *face = new ObjFile::Face( type );
  346. /*std::vector<unsigned int> *pIndices = new std::vector<unsigned int>;
  347. std::vector<unsigned int> *pTexID = new std::vector<unsigned int>;
  348. std::vector<unsigned int> *pNormalID = new std::vector<unsigned int>;*/
  349. bool hasNormal = false;
  350. const int vSize = m_pModel->m_Vertices.size();
  351. const int vtSize = m_pModel->m_TextureCoord.size();
  352. const int vnSize = m_pModel->m_Normals.size();
  353. const bool vt = (!m_pModel->m_TextureCoord.empty());
  354. const bool vn = (!m_pModel->m_Normals.empty());
  355. int iStep = 0, iPos = 0;
  356. while (pPtr != pEnd) {
  357. iStep = 1;
  358. if ( IsLineEnd( *pPtr ) ) {
  359. break;
  360. }
  361. if (*pPtr=='/' ) {
  362. if (type == aiPrimitiveType_POINT) {
  363. DefaultLogger::get()->error("Obj: Separator unexpected in point statement");
  364. }
  365. if (iPos == 0) {
  366. //if there are no texture coordinates in the file, but normals
  367. if (!vt && vn) {
  368. iPos = 1;
  369. iStep++;
  370. }
  371. }
  372. iPos++;
  373. } else if( IsSpaceOrNewLine( *pPtr ) ) {
  374. iPos = 0;
  375. } else {
  376. //OBJ USES 1 Base ARRAYS!!!!
  377. const int iVal( ::atoi( pPtr ) );
  378. // increment iStep position based off of the sign and # of digits
  379. int tmp = iVal;
  380. if ( iVal < 0 ) {
  381. ++iStep;
  382. }
  383. while ( ( tmp = tmp / 10 ) != 0 ) {
  384. ++iStep;
  385. }
  386. if ( iVal > 0 )
  387. {
  388. // Store parsed index
  389. if ( 0 == iPos )
  390. {
  391. face->m_vertices.push_back( iVal - 1 );
  392. //pIndices->push_back( iVal-1 );
  393. }
  394. else if ( 1 == iPos )
  395. {
  396. face->m_texturCoords.push_back( iVal - 1 );
  397. //pTexID->push_back( iVal-1 );
  398. }
  399. else if ( 2 == iPos )
  400. {
  401. face->m_normals.push_back( iVal - 1 );
  402. //pNormalID->push_back( iVal-1 );
  403. hasNormal = true;
  404. }
  405. else
  406. {
  407. reportErrorTokenInFace();
  408. }
  409. }
  410. else if ( iVal < 0 )
  411. {
  412. // Store relatively index
  413. if ( 0 == iPos )
  414. {
  415. face->m_vertices.push_back( vSize + iVal );
  416. //pIndices->push_back( vSize + iVal );
  417. }
  418. else if ( 1 == iPos )
  419. {
  420. face->m_texturCoords.push_back( vtSize + iVal );
  421. //pTexID->push_back( vtSize + iVal );
  422. }
  423. else if ( 2 == iPos )
  424. {
  425. face->m_normals.push_back( vnSize + iVal );
  426. //pNormalID->push_back( vnSize + iVal );
  427. hasNormal = true;
  428. }
  429. else
  430. {
  431. reportErrorTokenInFace();
  432. }
  433. }
  434. }
  435. pPtr += iStep;
  436. }
  437. if ( face->m_vertices.empty() ) {
  438. DefaultLogger::get()->error("Obj: Ignoring empty face");
  439. // skip line and clean up
  440. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  441. /*delete pNormalID;
  442. delete pTexID;
  443. delete pIndices;*/
  444. return;
  445. }
  446. // Set active material, if one set
  447. if( NULL != m_pModel->m_pCurrentMaterial ) {
  448. face->m_pMaterial = m_pModel->m_pCurrentMaterial;
  449. } else {
  450. face->m_pMaterial = m_pModel->m_pDefaultMaterial;
  451. }
  452. // Create a default object, if nothing is there
  453. if( NULL == m_pModel->m_pCurrent ) {
  454. createObject( DefaultObjName );
  455. }
  456. // Assign face to mesh
  457. if ( NULL == m_pModel->m_pCurrentMesh ) {
  458. createMesh( DefaultObjName );
  459. }
  460. // Store the face
  461. m_pModel->m_pCurrentMesh->m_Faces.push_back( face );
  462. m_pModel->m_pCurrentMesh->m_uiNumIndices += (unsigned int) face->m_vertices.size();
  463. m_pModel->m_pCurrentMesh->m_uiUVCoordinates[ 0 ] += (unsigned int) face->m_texturCoords.size();
  464. if( !m_pModel->m_pCurrentMesh->m_hasNormals && hasNormal ) {
  465. m_pModel->m_pCurrentMesh->m_hasNormals = true;
  466. }
  467. // Skip the rest of the line
  468. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  469. }
  470. // -------------------------------------------------------------------
  471. // Get values for a new material description
  472. void ObjFileParser::getMaterialDesc()
  473. {
  474. // Get next data for material data
  475. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  476. if (m_DataIt == m_DataItEnd) {
  477. return;
  478. }
  479. char *pStart = &(*m_DataIt);
  480. while( m_DataIt != m_DataItEnd && !IsLineEnd( *m_DataIt ) ) {
  481. ++m_DataIt;
  482. }
  483. // In some cases we should ignore this 'usemtl' command, this variable helps us to do so
  484. bool skip = false;
  485. // Get name
  486. std::string strName(pStart, &(*m_DataIt));
  487. strName = trim_whitespaces(strName);
  488. if (strName.empty())
  489. skip = true;
  490. // If the current mesh has the same material, we simply ignore that 'usemtl' command
  491. // There is no need to create another object or even mesh here
  492. if (m_pModel->m_pCurrentMaterial && m_pModel->m_pCurrentMaterial->MaterialName == aiString(strName))
  493. skip = true;
  494. if (!skip)
  495. {
  496. // Search for material
  497. std::map<std::string, ObjFile::Material*>::iterator it = m_pModel->m_MaterialMap.find(strName);
  498. if (it == m_pModel->m_MaterialMap.end())
  499. {
  500. // Not found, use default material
  501. m_pModel->m_pCurrentMaterial = m_pModel->m_pDefaultMaterial;
  502. DefaultLogger::get()->error("OBJ: failed to locate material " + strName + ", skipping");
  503. strName = m_pModel->m_pDefaultMaterial->MaterialName.C_Str();
  504. }
  505. else
  506. {
  507. // Found, using detected material
  508. m_pModel->m_pCurrentMaterial = (*it).second;
  509. }
  510. if (needsNewMesh(strName))
  511. createMesh(strName);
  512. m_pModel->m_pCurrentMesh->m_uiMaterialIndex = getMaterialIndex(strName);
  513. }
  514. // Skip rest of line
  515. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  516. }
  517. // -------------------------------------------------------------------
  518. // Get a comment, values will be skipped
  519. void ObjFileParser::getComment()
  520. {
  521. while (m_DataIt != m_DataItEnd)
  522. {
  523. if ( '\n' == (*m_DataIt))
  524. {
  525. ++m_DataIt;
  526. break;
  527. }
  528. else
  529. {
  530. ++m_DataIt;
  531. }
  532. }
  533. }
  534. // -------------------------------------------------------------------
  535. // Get material library from file.
  536. void ObjFileParser::getMaterialLib()
  537. {
  538. // Translate tuple
  539. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  540. if( m_DataIt == m_DataItEnd ) {
  541. return;
  542. }
  543. char *pStart = &(*m_DataIt);
  544. while( m_DataIt != m_DataItEnd && !IsLineEnd( *m_DataIt ) ) {
  545. ++m_DataIt;
  546. }
  547. // Check for existence
  548. const std::string strMatName(pStart, &(*m_DataIt));
  549. std::string absName;
  550. // Check if directive is valid.
  551. if(!strMatName.length()) throw DeadlyImportError("File name of the material is absent.");
  552. if ( m_pIO->StackSize() > 0 ) {
  553. std::string path = m_pIO->CurrentDirectory();
  554. if ( '/' != *path.rbegin() ) {
  555. path += '/';
  556. }
  557. absName = path + strMatName;
  558. } else {
  559. absName = strMatName;
  560. }
  561. IOStream *pFile = m_pIO->Open( absName );
  562. if (!pFile ) {
  563. DefaultLogger::get()->error("OBJ: Unable to locate material file " + strMatName);
  564. std::string strMatFallbackName = m_originalObjFileName.substr(0, m_originalObjFileName.length() - 3) + "mtl";
  565. DefaultLogger::get()->info("OBJ: Opening fallback material file " + strMatFallbackName);
  566. pFile = m_pIO->Open(strMatFallbackName);
  567. if (!pFile) {
  568. DefaultLogger::get()->error("OBJ: Unable to locate fallback material file " + strMatName);
  569. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  570. return;
  571. }
  572. }
  573. // Import material library data from file.
  574. // Some exporters (e.g. Silo) will happily write out empty
  575. // material files if the model doesn't use any materials, so we
  576. // allow that.
  577. std::vector<char> buffer;
  578. BaseImporter::TextFileToBuffer( pFile, buffer, BaseImporter::ALLOW_EMPTY );
  579. m_pIO->Close( pFile );
  580. // Importing the material library
  581. ObjFileMtlImporter mtlImporter( buffer, strMatName, m_pModel );
  582. }
  583. // -------------------------------------------------------------------
  584. // Set a new material definition as the current material.
  585. void ObjFileParser::getNewMaterial()
  586. {
  587. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  588. m_DataIt = getNextWord<DataArrayIt>(m_DataIt, m_DataItEnd);
  589. if( m_DataIt == m_DataItEnd ) {
  590. return;
  591. }
  592. char *pStart = &(*m_DataIt);
  593. std::string strMat( pStart, *m_DataIt );
  594. while( m_DataIt != m_DataItEnd && IsSpaceOrNewLine( *m_DataIt ) ) {
  595. ++m_DataIt;
  596. }
  597. std::map<std::string, ObjFile::Material*>::iterator it = m_pModel->m_MaterialMap.find( strMat );
  598. if ( it == m_pModel->m_MaterialMap.end() )
  599. {
  600. // Show a warning, if material was not found
  601. DefaultLogger::get()->warn("OBJ: Unsupported material requested: " + strMat);
  602. m_pModel->m_pCurrentMaterial = m_pModel->m_pDefaultMaterial;
  603. }
  604. else
  605. {
  606. // Set new material
  607. if ( needsNewMesh( strMat ) )
  608. {
  609. createMesh( strMat );
  610. }
  611. m_pModel->m_pCurrentMesh->m_uiMaterialIndex = getMaterialIndex( strMat );
  612. }
  613. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  614. }
  615. // -------------------------------------------------------------------
  616. int ObjFileParser::getMaterialIndex( const std::string &strMaterialName )
  617. {
  618. int mat_index = -1;
  619. if( strMaterialName.empty() ) {
  620. return mat_index;
  621. }
  622. for (size_t index = 0; index < m_pModel->m_MaterialLib.size(); ++index)
  623. {
  624. if ( strMaterialName == m_pModel->m_MaterialLib[ index ])
  625. {
  626. mat_index = (int)index;
  627. break;
  628. }
  629. }
  630. return mat_index;
  631. }
  632. // -------------------------------------------------------------------
  633. // Getter for a group name.
  634. void ObjFileParser::getGroupName() {
  635. std::string groupName;
  636. // here we skip 'g ' from line
  637. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  638. m_DataIt = getName<DataArrayIt>(m_DataIt, m_DataItEnd, groupName);
  639. if( isEndOfBuffer( m_DataIt, m_DataItEnd ) ) {
  640. return;
  641. }
  642. // Change active group, if necessary
  643. if ( m_pModel->m_strActiveGroup != groupName ) {
  644. // Search for already existing entry
  645. ObjFile::Model::ConstGroupMapIt it = m_pModel->m_Groups.find(groupName);
  646. // We are mapping groups into the object structure
  647. createObject( groupName );
  648. // New group name, creating a new entry
  649. if (it == m_pModel->m_Groups.end())
  650. {
  651. std::vector<unsigned int> *pFaceIDArray = new std::vector<unsigned int>;
  652. m_pModel->m_Groups[ groupName ] = pFaceIDArray;
  653. m_pModel->m_pGroupFaceIDs = (pFaceIDArray);
  654. }
  655. else
  656. {
  657. m_pModel->m_pGroupFaceIDs = (*it).second;
  658. }
  659. m_pModel->m_strActiveGroup = groupName;
  660. }
  661. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  662. }
  663. // -------------------------------------------------------------------
  664. // Not supported
  665. void ObjFileParser::getGroupNumber()
  666. {
  667. // Not used
  668. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  669. }
  670. // -------------------------------------------------------------------
  671. // Not supported
  672. void ObjFileParser::getGroupNumberAndResolution()
  673. {
  674. // Not used
  675. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  676. }
  677. // -------------------------------------------------------------------
  678. // Stores values for a new object instance, name will be used to
  679. // identify it.
  680. void ObjFileParser::getObjectName()
  681. {
  682. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  683. if( m_DataIt == m_DataItEnd ) {
  684. return;
  685. }
  686. char *pStart = &(*m_DataIt);
  687. while( m_DataIt != m_DataItEnd && !IsSpaceOrNewLine( *m_DataIt ) ) {
  688. ++m_DataIt;
  689. }
  690. std::string strObjectName(pStart, &(*m_DataIt));
  691. if (!strObjectName.empty())
  692. {
  693. // Reset current object
  694. m_pModel->m_pCurrent = NULL;
  695. // Search for actual object
  696. for (std::vector<ObjFile::Object*>::const_iterator it = m_pModel->m_Objects.begin();
  697. it != m_pModel->m_Objects.end();
  698. ++it)
  699. {
  700. if ((*it)->m_strObjName == strObjectName)
  701. {
  702. m_pModel->m_pCurrent = *it;
  703. break;
  704. }
  705. }
  706. // Allocate a new object, if current one was not found before
  707. if( NULL == m_pModel->m_pCurrent ) {
  708. createObject( strObjectName );
  709. }
  710. }
  711. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  712. }
  713. // -------------------------------------------------------------------
  714. // Creates a new object instance
  715. void ObjFileParser::createObject(const std::string &objName)
  716. {
  717. ai_assert( NULL != m_pModel );
  718. m_pModel->m_pCurrent = new ObjFile::Object;
  719. m_pModel->m_pCurrent->m_strObjName = objName;
  720. m_pModel->m_Objects.push_back( m_pModel->m_pCurrent );
  721. createMesh( objName );
  722. if( m_pModel->m_pCurrentMaterial )
  723. {
  724. m_pModel->m_pCurrentMesh->m_uiMaterialIndex =
  725. getMaterialIndex( m_pModel->m_pCurrentMaterial->MaterialName.data );
  726. m_pModel->m_pCurrentMesh->m_pMaterial = m_pModel->m_pCurrentMaterial;
  727. }
  728. }
  729. // -------------------------------------------------------------------
  730. // Creates a new mesh
  731. void ObjFileParser::createMesh( const std::string &meshName )
  732. {
  733. ai_assert( NULL != m_pModel );
  734. m_pModel->m_pCurrentMesh = new ObjFile::Mesh( meshName );
  735. m_pModel->m_Meshes.push_back( m_pModel->m_pCurrentMesh );
  736. unsigned int meshId = m_pModel->m_Meshes.size()-1;
  737. if ( NULL != m_pModel->m_pCurrent )
  738. {
  739. m_pModel->m_pCurrent->m_Meshes.push_back( meshId );
  740. }
  741. else
  742. {
  743. DefaultLogger::get()->error("OBJ: No object detected to attach a new mesh instance.");
  744. }
  745. }
  746. // -------------------------------------------------------------------
  747. // Returns true, if a new mesh must be created.
  748. bool ObjFileParser::needsNewMesh( const std::string &materialName )
  749. {
  750. // If no mesh data yet
  751. if(m_pModel->m_pCurrentMesh == 0)
  752. {
  753. return true;
  754. }
  755. bool newMat = false;
  756. int matIdx = getMaterialIndex( materialName );
  757. int curMatIdx = m_pModel->m_pCurrentMesh->m_uiMaterialIndex;
  758. if ( curMatIdx != int(ObjFile::Mesh::NoMaterial)
  759. && curMatIdx != matIdx
  760. // no need create a new mesh if no faces in current
  761. // lets say 'usemtl' goes straight after 'g'
  762. && m_pModel->m_pCurrentMesh->m_Faces.size() > 0 )
  763. {
  764. // New material -> only one material per mesh, so we need to create a new
  765. // material
  766. newMat = true;
  767. }
  768. return newMat;
  769. }
  770. // -------------------------------------------------------------------
  771. // Shows an error in parsing process.
  772. void ObjFileParser::reportErrorTokenInFace()
  773. {
  774. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  775. DefaultLogger::get()->error("OBJ: Not supported token in face description detected");
  776. }
  777. // -------------------------------------------------------------------
  778. } // Namespace Assimp
  779. #endif // !! ASSIMP_BUILD_NO_OBJ_IMPORTER