ObjFileParser.cpp 28 KB

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