ObjFileParser.cpp 28 KB

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