ObjFileParser.cpp 27 KB

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