2
0

ObjFileParser.cpp 16 KB

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