ObjFileParser.cpp 28 KB

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