ObjFileParser.cpp 17 KB

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