ObjFileParser.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (ASSIMP)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2008, ASSIMP Development 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 Development 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. #include "AssimpPCH.h"
  35. #ifndef ASSIMP_BUILD_NO_OBJ_IMPORTER
  36. #include "ObjFileParser.h"
  37. #include "ObjFileMtlImporter.h"
  38. #include "ObjTools.h"
  39. #include "ObjFileData.h"
  40. #include "fast_atof.h"
  41. #include "../include/aiTypes.h"
  42. #include "DefaultIOSystem.h"
  43. namespace Assimp {
  44. // -------------------------------------------------------------------
  45. const std::string ObjFileParser::DEFAULT_MATERIAL = AI_DEFAULT_MATERIAL_NAME;
  46. // fix: changed that to our standard default name
  47. // -------------------------------------------------------------------
  48. // Constructor with loaded data and directories.
  49. ObjFileParser::ObjFileParser(std::vector<char> &Data,const std::string &strModelName, IOSystem *io ) :
  50. m_DataIt(Data.begin()),
  51. m_DataItEnd(Data.end()),
  52. m_pModel(NULL),
  53. m_uiLine(0),
  54. m_pIO( io )
  55. {
  56. // Create the model instance to store all the data
  57. m_pModel = new ObjFile::Model();
  58. m_pModel->m_ModelName = strModelName;
  59. m_pModel->m_pDefaultMaterial = new ObjFile::Material();
  60. m_pModel->m_pDefaultMaterial->MaterialName.Set( DEFAULT_MATERIAL );
  61. m_pModel->m_MaterialLib.push_back( DEFAULT_MATERIAL );
  62. m_pModel->m_MaterialMap[ DEFAULT_MATERIAL ] = m_pModel->m_pDefaultMaterial;
  63. // Start parsing the file
  64. parseFile();
  65. }
  66. // -------------------------------------------------------------------
  67. ObjFileParser::~ObjFileParser()
  68. {
  69. delete m_pModel->m_pDefaultMaterial;
  70. m_pModel->m_pDefaultMaterial = NULL;
  71. delete m_pModel;
  72. m_pModel = NULL;
  73. }
  74. // -------------------------------------------------------------------
  75. ObjFile::Model *ObjFileParser::GetModel() const
  76. {
  77. return m_pModel;
  78. }
  79. // -------------------------------------------------------------------
  80. void ObjFileParser::parseFile()
  81. {
  82. if (m_DataIt == m_DataItEnd)
  83. return;
  84. while (m_DataIt != m_DataItEnd)
  85. {
  86. switch (*m_DataIt)
  87. {
  88. case 'v': // Parse a vertex texture coordinate
  89. {
  90. ++m_DataIt;
  91. if (*m_DataIt == ' ')
  92. {
  93. // Read in vertex definition
  94. getVector3(m_pModel->m_Vertices);
  95. }
  96. else if (*m_DataIt == 't')
  97. {
  98. // Read in texture coordinate (2D)
  99. ++m_DataIt;
  100. getVector2(m_pModel->m_TextureCoord);
  101. }
  102. else if (*m_DataIt == 'n')
  103. {
  104. // Read in normal vector definition
  105. ++m_DataIt;
  106. getVector3( m_pModel->m_Normals );
  107. }
  108. }
  109. break;
  110. case 'f': // Parse a face
  111. {
  112. getFace();
  113. }
  114. break;
  115. case '#': // Parse a comment
  116. {
  117. getComment();
  118. }
  119. break;
  120. case 'u': // Parse a material desc. setter
  121. {
  122. getMaterialDesc();
  123. }
  124. break;
  125. case 'm': // Parse a material library
  126. {
  127. getMaterialLib();
  128. }
  129. break;
  130. case 'g': // Parse group name
  131. {
  132. getGroupName();
  133. }
  134. break;
  135. case 's': // Parse group number
  136. {
  137. getGroupNumber();
  138. }
  139. break;
  140. case 'o': // Parse object name
  141. {
  142. getObjectName();
  143. }
  144. break;
  145. default:
  146. {
  147. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  148. }
  149. break;
  150. }
  151. }
  152. }
  153. // -------------------------------------------------------------------
  154. // Copy the next word in a temporary buffer
  155. void ObjFileParser::copyNextWord(char *pBuffer, size_t length)
  156. {
  157. size_t index = 0;
  158. m_DataIt = getNextWord<DataArrayIt>(m_DataIt, m_DataItEnd);
  159. while ( !isSeparator(*m_DataIt) && m_DataIt != m_DataItEnd )
  160. {
  161. pBuffer[index] = *m_DataIt;
  162. index++;
  163. if (index == length-1)
  164. break;
  165. ++m_DataIt;
  166. }
  167. pBuffer[index] = '\0';
  168. }
  169. // -------------------------------------------------------------------
  170. // Copy the next line into a temporary buffer
  171. void ObjFileParser::copyNextLine(char *pBuffer, size_t length)
  172. {
  173. size_t index = 0;
  174. while (m_DataIt != m_DataItEnd)
  175. {
  176. // (Aramis) removed assertion (index<length-1) in favour of an explicit check
  177. if (*m_DataIt == '\n' || *m_DataIt == '\r' || index == length-1)
  178. break;
  179. pBuffer[ index ] = *m_DataIt;
  180. ++index;
  181. ++m_DataIt;
  182. }
  183. pBuffer[ index ] = '\0';
  184. }
  185. // -------------------------------------------------------------------
  186. // Get values for a new 3D vector instance
  187. void ObjFileParser::getVector3(std::vector<aiVector3D> &point3d_array)
  188. {
  189. float x, y, z;
  190. copyNextWord(m_buffer, BUFFERSIZE);
  191. x = (float) fast_atof(m_buffer);
  192. copyNextWord(m_buffer, BUFFERSIZE);
  193. y = (float) fast_atof(m_buffer);
  194. copyNextWord(m_buffer, BUFFERSIZE);
  195. z = (float) fast_atof(m_buffer);
  196. point3d_array.push_back( aiVector3D( x, y, z ) );
  197. //skipLine();
  198. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  199. }
  200. // -------------------------------------------------------------------
  201. // Get values for a new 2D vector instance
  202. void ObjFileParser::getVector2( std::vector<aiVector2D> &point2d_array )
  203. {
  204. float x, y;
  205. copyNextWord(m_buffer, BUFFERSIZE);
  206. x = (float) fast_atof(m_buffer);
  207. copyNextWord(m_buffer, BUFFERSIZE);
  208. y = (float) fast_atof(m_buffer);
  209. point2d_array.push_back(aiVector2D(x, y));
  210. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  211. }
  212. // -------------------------------------------------------------------
  213. // Get values for a new face instance
  214. void ObjFileParser::getFace()
  215. {
  216. copyNextLine(m_buffer, BUFFERSIZE);
  217. if (m_DataIt == m_DataItEnd)
  218. return;
  219. char *pPtr = m_buffer;
  220. char *pEnd = &pPtr[BUFFERSIZE];
  221. pPtr = getNextToken<char*>(pPtr, pEnd);
  222. if (pPtr == '\0')
  223. return;
  224. std::vector<unsigned int> *pIndices = new std::vector<unsigned int>;
  225. std::vector<unsigned int> *pTexID = new std::vector<unsigned int>;
  226. std::vector<unsigned int> *pNormalID = new std::vector<unsigned int>;
  227. bool hasNormal = false;
  228. bool vt = (!m_pModel->m_TextureCoord.empty());
  229. bool vn = (!m_pModel->m_Normals.empty());
  230. int iStep = 0, iPos = 0;
  231. while (pPtr != pEnd)
  232. {
  233. iStep = 1;
  234. if (*pPtr == '\0')
  235. break;
  236. if (*pPtr=='\r')
  237. break;
  238. if (*pPtr=='/' )
  239. {
  240. if (iPos == 0)
  241. {
  242. //if there are no texturecoordinates in the obj file but normals
  243. if (!vt && vn) {
  244. iPos = 1;
  245. iStep++;
  246. }
  247. }
  248. iPos++;
  249. }
  250. else if ( isSeparator(*pPtr) )
  251. {
  252. iPos = 0;
  253. }
  254. else
  255. {
  256. //OBJ USES 1 Base ARRAYS!!!!
  257. const int iVal = atoi( pPtr );
  258. int tmp = iVal;
  259. while ( ( tmp = tmp / 10 )!=0 )
  260. ++iStep;
  261. if ( iVal > 0 )
  262. {
  263. // Store parsed index
  264. if ( 0 == iPos )
  265. {
  266. pIndices->push_back( iVal-1 );
  267. }
  268. else if ( 1 == iPos )
  269. {
  270. pTexID->push_back( iVal-1 );
  271. }
  272. else if ( 2 == iPos )
  273. {
  274. pNormalID->push_back( iVal-1 );
  275. hasNormal = true;
  276. }
  277. else
  278. {
  279. reportErrorTokenInFace();
  280. }
  281. }
  282. }
  283. for ( int i=0; i<iStep; i++ )
  284. ++pPtr;
  285. }
  286. ObjFile::Face *face = new ObjFile::Face(pIndices, pNormalID, pTexID);
  287. // Set active material, if one set
  288. if (NULL != m_pModel->m_pCurrentMaterial)
  289. face->m_pMaterial = m_pModel->m_pCurrentMaterial;
  290. else
  291. face->m_pMaterial = m_pModel->m_pDefaultMaterial;
  292. // Create a default object, if nothing there
  293. if ( NULL == m_pModel->m_pCurrent )
  294. createObject("defaultobject");
  295. // Store the new instance
  296. m_pModel->m_pCurrent->m_Faces.push_back(face);
  297. // Assign face to mesh
  298. if ( NULL == m_pModel->m_pCurrentMesh )
  299. {
  300. m_pModel->m_pCurrentMesh = new ObjFile::Mesh();
  301. m_pModel->m_Meshes.push_back( m_pModel->m_pCurrentMesh );
  302. }
  303. // Store the face
  304. m_pModel->m_pCurrentMesh->m_Faces.push_back( face );
  305. m_pModel->m_pCurrentMesh->m_uiNumIndices += (unsigned int)face->m_pVertices->size();
  306. m_pModel->m_pCurrentMesh->m_uiUVCoordinates[ 0 ] += (unsigned int)face->m_pTexturCoords[0].size();
  307. if(!m_pModel->m_pCurrentMesh->m_hasNormals && hasNormal) {
  308. m_pModel->m_pCurrentMesh->m_hasNormals = true;
  309. }
  310. // Skip the rest of the line
  311. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  312. }
  313. // -------------------------------------------------------------------
  314. // Get values for a new material description
  315. void ObjFileParser::getMaterialDesc()
  316. {
  317. // Get next data for material data
  318. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  319. if (m_DataIt == m_DataItEnd)
  320. return;
  321. char *pStart = &(*m_DataIt);
  322. while ( !isSeparator(*m_DataIt) && m_DataIt != m_DataItEnd )
  323. ++m_DataIt;
  324. // Get name
  325. std::string strName(pStart, &(*m_DataIt));
  326. if ( strName.empty())
  327. return;
  328. // Search for material
  329. std::map<std::string, ObjFile::Material*>::iterator it = m_pModel->m_MaterialMap.find( strName );
  330. if ( it == m_pModel->m_MaterialMap.end() )
  331. {
  332. // Not found, use default material
  333. m_pModel->m_pCurrentMaterial = m_pModel->m_pDefaultMaterial;
  334. }
  335. else
  336. {
  337. // Found, using detected material
  338. m_pModel->m_pCurrentMaterial = (*it).second;
  339. m_pModel->m_pCurrentMesh->m_uiMaterialIndex = getMaterialIndex( strName );
  340. }
  341. // Skip rest of line
  342. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  343. }
  344. // -------------------------------------------------------------------
  345. // Get a comment, values will be skipped
  346. void ObjFileParser::getComment()
  347. {
  348. bool running = true;
  349. while (running)
  350. {
  351. if ( '\n' == (*m_DataIt) || m_DataIt == m_DataItEnd )
  352. {
  353. ++m_DataIt;
  354. break;
  355. }
  356. else
  357. {
  358. ++m_DataIt;
  359. }
  360. }
  361. }
  362. // -------------------------------------------------------------------
  363. // Get material library from file.
  364. void ObjFileParser::getMaterialLib()
  365. {
  366. // Translate tuple
  367. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  368. if (m_DataIt == m_DataItEnd)
  369. return;
  370. char *pStart = &(*m_DataIt);
  371. while (!isNewLine(*m_DataIt))
  372. m_DataIt++;
  373. // Check for existence
  374. const std::string strMatName(pStart, &(*m_DataIt));
  375. IOStream *pFile = m_pIO->Open(strMatName);
  376. if (!pFile )
  377. {
  378. DefaultLogger::get()->error("OBJ: Unable to locate material file " + strMatName);
  379. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  380. return;
  381. }
  382. // Import material library data from file
  383. std::vector<char> buffer;
  384. BaseImporter::TextFileToBuffer(pFile,buffer);
  385. m_pIO->Close( pFile );
  386. // Importing the material library
  387. ObjFileMtlImporter mtlImporter( buffer, strMatName, m_pModel );
  388. }
  389. // -------------------------------------------------------------------
  390. // Set a new material definition as the current material.
  391. void ObjFileParser::getNewMaterial()
  392. {
  393. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  394. m_DataIt = getNextWord<DataArrayIt>(m_DataIt, m_DataItEnd);
  395. if ( m_DataIt == m_DataItEnd )
  396. return;
  397. char *pStart = &(*m_DataIt);
  398. std::string strMat(pStart, *m_DataIt);
  399. while ( isSeparator( *m_DataIt ) )
  400. m_DataIt++;
  401. std::map<std::string, ObjFile::Material*>::iterator it = m_pModel->m_MaterialMap.find( strMat );
  402. if (it == m_pModel->m_MaterialMap.end())
  403. {
  404. // Show a warning, if material was not found
  405. DefaultLogger::get()->warn("OBJ: Unsupported material requested: " + strMat);
  406. m_pModel->m_pCurrentMaterial = m_pModel->m_pDefaultMaterial;
  407. }
  408. else
  409. {
  410. // Set new material
  411. m_pModel->m_pCurrentMaterial = (*it).second;
  412. m_pModel->m_pCurrentMesh->m_uiMaterialIndex = getMaterialIndex( strMat );
  413. }
  414. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  415. }
  416. // -------------------------------------------------------------------
  417. int ObjFileParser::getMaterialIndex( const std::string &strMaterialName )
  418. {
  419. int mat_index = -1;
  420. if ( strMaterialName.empty() )
  421. return mat_index;
  422. for (size_t index = 0; index < m_pModel->m_MaterialLib.size(); ++index)
  423. {
  424. if ( strMaterialName == m_pModel->m_MaterialLib[ index ])
  425. {
  426. mat_index = (int)index;
  427. break;
  428. }
  429. }
  430. return mat_index;
  431. }
  432. // -------------------------------------------------------------------
  433. // Getter for a group name.
  434. void ObjFileParser::getGroupName()
  435. {
  436. // Get next word from data buffer
  437. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  438. m_DataIt = getNextWord<DataArrayIt>(m_DataIt, m_DataItEnd);
  439. if ( isEndOfBuffer( m_DataIt, m_DataItEnd ) )
  440. return;
  441. // Store groupname in group library
  442. char *pStart = &(*m_DataIt);
  443. while ( !isSeparator(*m_DataIt) )
  444. m_DataIt++;
  445. std::string strGroupName(pStart, &(*m_DataIt));
  446. // Change active group, if necessary
  447. if (m_pModel->m_strActiveGroup != strGroupName)
  448. {
  449. // Search for already existing entry
  450. ObjFile::Model::ConstGroupMapIt it = m_pModel->m_Groups.find(&strGroupName);
  451. // We are mapping groups into the object structure
  452. /// TODO: Is this the right way to do it????
  453. createObject( strGroupName );
  454. // New group name, creating a new entry
  455. if (it == m_pModel->m_Groups.end())
  456. {
  457. std::vector<unsigned int> *pFaceIDArray = new std::vector<unsigned int>;
  458. m_pModel->m_Groups[ &strGroupName ] = pFaceIDArray;
  459. m_pModel->m_pGroupFaceIDs = (pFaceIDArray);
  460. }
  461. else
  462. {
  463. m_pModel->m_pGroupFaceIDs = (*it).second;
  464. }
  465. m_pModel->m_strActiveGroup = strGroupName;
  466. }
  467. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  468. }
  469. // -------------------------------------------------------------------
  470. // Not supported
  471. void ObjFileParser::getGroupNumber()
  472. {
  473. // Not used
  474. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  475. }
  476. // -------------------------------------------------------------------
  477. // Stores values for a new object instance, name will be used to
  478. // identify it.
  479. void ObjFileParser::getObjectName()
  480. {
  481. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  482. if (m_DataIt == m_DataItEnd)
  483. return;
  484. char *pStart = &(*m_DataIt);
  485. while (!isSeparator(*m_DataIt))
  486. m_DataIt++;
  487. std::string strObjectName(pStart, &(*m_DataIt));
  488. if (!strObjectName.empty())
  489. {
  490. // Reset current object
  491. m_pModel->m_pCurrent = NULL;
  492. // Search for actual object
  493. for (std::vector<ObjFile::Object*>::const_iterator it = m_pModel->m_Objects.begin();
  494. it != m_pModel->m_Objects.end();
  495. ++it)
  496. {
  497. if ((*it)->m_strObjName == strObjectName)
  498. {
  499. m_pModel->m_pCurrent = *it;
  500. break;
  501. }
  502. }
  503. // Allocate a new object, if current one wasn´t found before
  504. if ( NULL == m_pModel->m_pCurrent )
  505. createObject(strObjectName);
  506. }
  507. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  508. }
  509. // -------------------------------------------------------------------
  510. // Creates a new object instance
  511. void ObjFileParser::createObject(const std::string &strObjectName)
  512. {
  513. ai_assert (NULL != m_pModel);
  514. ai_assert (!strObjectName.empty());
  515. m_pModel->m_pCurrent = new ObjFile::Object();
  516. m_pModel->m_pCurrent->m_strObjName = strObjectName;
  517. m_pModel->m_Objects.push_back( m_pModel->m_pCurrent );
  518. m_pModel->m_pCurrentMesh = new ObjFile::Mesh();
  519. m_pModel->m_Meshes.push_back( m_pModel->m_pCurrentMesh );
  520. if( m_pModel->m_pCurrentMaterial )
  521. {
  522. m_pModel->m_pCurrentMesh->m_uiMaterialIndex =
  523. getMaterialIndex( m_pModel->m_pCurrentMaterial->MaterialName.data );
  524. m_pModel->m_pCurrentMesh->m_pMaterial = m_pModel->m_pCurrentMaterial;
  525. }
  526. }
  527. // -------------------------------------------------------------------
  528. // Shows an error in parsing process.
  529. void ObjFileParser::reportErrorTokenInFace()
  530. {
  531. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  532. DefaultLogger::get()->error("OBJ: Not supported token in face description detected");
  533. }
  534. // -------------------------------------------------------------------
  535. } // Namespace Assimp
  536. #endif // !! ASSIMP_BUILD_NO_OBJ_IMPORTER