LWOLoader.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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. /** @file Implementation of the LWO importer class */
  35. // internal headers
  36. #include "LWOLoader.h"
  37. #include "MaterialSystem.h"
  38. #include "ByteSwap.h"
  39. // public assimp headers
  40. #include "../include/IOStream.h"
  41. #include "../include/IOSystem.h"
  42. #include "../include/aiMesh.h"
  43. #include "../include/aiScene.h"
  44. #include "../include/aiAssert.h"
  45. #include "../include/DefaultLogger.h"
  46. // boost headers
  47. #include <boost/scoped_ptr.hpp>
  48. using namespace Assimp;
  49. // ------------------------------------------------------------------------------------------------
  50. // Constructor to be privately used by Importer
  51. LWOImporter::LWOImporter()
  52. {
  53. }
  54. // ------------------------------------------------------------------------------------------------
  55. // Destructor, private as well
  56. LWOImporter::~LWOImporter()
  57. {
  58. }
  59. // ------------------------------------------------------------------------------------------------
  60. // Returns whether the class can handle the format of the given file.
  61. bool LWOImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler) const
  62. {
  63. // simple check of file extension is enough for the moment
  64. std::string::size_type pos = pFile.find_last_of('.');
  65. // no file extension - can't read
  66. if( pos == std::string::npos)return false;
  67. std::string extension = pFile.substr( pos);
  68. if (extension.length() < 4)return false;
  69. if (extension[0] != '.')return false;
  70. if (extension[1] != 'l' && extension[1] != 'L')return false;
  71. if (extension[2] != 'w' && extension[2] != 'W')return false;
  72. if (extension[3] != 'o' && extension[3] != 'O')return false;
  73. return true;
  74. }
  75. // ------------------------------------------------------------------------------------------------
  76. // Imports the given file into the given scene structure.
  77. void LWOImporter::InternReadFile( const std::string& pFile,
  78. aiScene* pScene,
  79. IOSystem* pIOHandler)
  80. {
  81. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  82. // Check whether we can read from the file
  83. if( file.get() == NULL)
  84. throw new ImportErrorException( "Failed to open LWO file " + pFile + ".");
  85. if((this->fileSize = (unsigned int)file->FileSize()) < 12)
  86. throw new ImportErrorException("LWO: The file is too small to contain the IFF header");
  87. // allocate storage and copy the contents of the file to a memory buffer
  88. std::vector< uint8_t > mBuffer(fileSize);
  89. file->Read( &mBuffer[0], 1, fileSize);
  90. this->pScene = pScene;
  91. // determine the type of the file
  92. uint32_t fileType;
  93. const char* sz = IFF::ReadHeader(&mBuffer[0],fileType);
  94. if (sz)throw new ImportErrorException(sz);
  95. mFileBuffer = &mBuffer[0] + 12;
  96. fileSize -= 12;
  97. // create temporary storage on the stack but store points to
  98. // it in the class instance. Therefoe everything will be destructed
  99. // properly if an exception is thrown.
  100. PointList _mTempPoints;
  101. mTempPoints = &_mTempPoints;
  102. FaceList _mFaces;
  103. mFaces = &_mFaces;
  104. TagList _mTags;
  105. mTags = &_mTags;
  106. TagMappingTable _mMapping;
  107. mMapping = &_mMapping;
  108. SurfaceList _mSurfaces;
  109. mSurfaces = &_mSurfaces;
  110. // old lightwave file format (prior to v6)
  111. if (AI_LWO_FOURCC_LWOB == fileType)this->LoadLWOBFile();
  112. // new lightwave format
  113. else if (AI_LWO_FOURCC_LWO2 == fileType)this->LoadLWO2File();
  114. // we don't know this format
  115. else
  116. {
  117. char szBuff[5];
  118. szBuff[0] = (char)(fileType >> 24u);
  119. szBuff[1] = (char)(fileType >> 16u);
  120. szBuff[2] = (char)(fileType >> 8u);
  121. szBuff[3] = (char)(fileType);
  122. throw new ImportErrorException(std::string("Unknown LWO sub format: ") + szBuff);
  123. }
  124. ResolveTags();
  125. // now sort all faces by the surfaces assigned to them
  126. typedef std::vector<unsigned int> SortedRep;
  127. std::vector<SortedRep> pSorted(mSurfaces->size()+1);
  128. unsigned int i = 0;
  129. unsigned int iDefaultSurface = 0xffffffff;
  130. for (FaceList::iterator it = mFaces->begin(), end = mFaces->end();
  131. it != end;++it,++i)
  132. {
  133. unsigned int idx = (*it).surfaceIndex;
  134. if (idx >= mTags->size())
  135. {
  136. DefaultLogger::get()->warn("LWO: Invalid face surface index");
  137. idx = mTags->size()-1;
  138. }
  139. if(0xffffffff == (idx = _mMapping[idx]))
  140. {
  141. if (0xffffffff == iDefaultSurface)
  142. {
  143. iDefaultSurface = mSurfaces->size();
  144. mSurfaces->push_back(LWO::Surface());
  145. LWO::Surface& surf = mSurfaces->back();
  146. surf.mColor.r = surf.mColor.g = surf.mColor.b = 0.6f;
  147. }
  148. idx = iDefaultSurface;
  149. }
  150. pSorted[idx].push_back(i);
  151. }
  152. if (0xffffffff == iDefaultSurface)pSorted.erase(pSorted.end()-1);
  153. // now generate output meshes
  154. for (unsigned int p = 0; p < mSurfaces->size();++p)
  155. if (!pSorted[p].empty())pScene->mNumMeshes++;
  156. if (!(pScene->mNumMaterials = pScene->mNumMeshes))
  157. throw new ImportErrorException("LWO: There are no meshes");
  158. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  159. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials];
  160. for (unsigned int p = 0,i = 0;i < mSurfaces->size();++i)
  161. {
  162. SortedRep& sorted = pSorted[i];
  163. if (sorted.empty())continue;
  164. // generate the mesh
  165. aiMesh* mesh = pScene->mMeshes[p] = new aiMesh();
  166. mesh->mNumFaces = sorted.size();
  167. for (SortedRep::const_iterator it = sorted.begin(), end = sorted.end();
  168. it != end;++it)
  169. {
  170. mesh->mNumVertices += _mFaces[*it].mNumIndices;
  171. }
  172. aiVector3D* pv = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  173. aiFace* pf = mesh->mFaces = new aiFace[mesh->mNumFaces];
  174. mesh->mMaterialIndex = p;
  175. // now convert all faces
  176. unsigned int vert = 0;
  177. for (SortedRep::const_iterator it = sorted.begin(), end = sorted.end();
  178. it != end;++it)
  179. {
  180. LWO::Face& face = _mFaces[*it];
  181. // copy all vertices
  182. for (unsigned int q = 0; q < face.mNumIndices;++q)
  183. {
  184. *pv++ = _mTempPoints[face.mIndices[q]];
  185. face.mIndices[q] = vert++;
  186. }
  187. pf->mIndices = face.mIndices;
  188. pf->mNumIndices = face.mNumIndices;
  189. face.mIndices = NULL; // make sure it won't be deleted
  190. pf++;
  191. }
  192. // generate the corresponding material
  193. MaterialHelper* pcMat = new MaterialHelper();
  194. pScene->mMaterials[p] = pcMat;
  195. //ConvertMaterial(mSurfaces[i],pcMat);
  196. ++p;
  197. }
  198. }
  199. // ------------------------------------------------------------------------------------------------
  200. void LWOImporter::CountVertsAndFaces(unsigned int& verts, unsigned int& faces,
  201. LE_NCONST uint8_t*& cursor, const uint8_t* const end, unsigned int max)
  202. {
  203. while (cursor < end && max--)
  204. {
  205. uint16_t numIndices = *((uint16_t*)cursor);cursor+=2;
  206. verts += numIndices;faces++;
  207. cursor += numIndices*2;
  208. int16_t surface = *((uint16_t*)cursor);cursor+=2;
  209. if (surface < 0)
  210. {
  211. // there are detail polygons
  212. numIndices = *((uint16_t*)cursor);cursor+=2;
  213. CountVertsAndFaces(verts,faces,cursor,end,numIndices);
  214. }
  215. }
  216. }
  217. // ------------------------------------------------------------------------------------------------
  218. void LWOImporter::CopyFaceIndices(LWOImporter::FaceList::iterator& it,
  219. LE_NCONST uint8_t*& cursor,
  220. const uint8_t* const end,
  221. unsigned int max)
  222. {
  223. while (cursor < end && max--)
  224. {
  225. LWO::Face& face = *it;++it;
  226. if(face.mNumIndices = *((uint16_t*)cursor))
  227. {
  228. if (cursor + face.mNumIndices*2 + 4 >= end)break;
  229. face.mIndices = new unsigned int[face.mNumIndices];
  230. for (unsigned int i = 0; i < face.mNumIndices;++i)
  231. {
  232. face.mIndices[i] = *((uint16_t*)(cursor+=2));
  233. if (face.mIndices[i] >= mTempPoints->size())
  234. {
  235. face.mIndices[i] = mTempPoints->size()-1;
  236. DefaultLogger::get()->warn("LWO: Face index is out of range");
  237. }
  238. }
  239. }
  240. else DefaultLogger::get()->warn("LWO: Face has 0 indices");
  241. cursor+=2;
  242. int16_t surface = *((uint16_t*)cursor);cursor+=2;
  243. if (surface < 0)
  244. {
  245. surface = -surface;
  246. // there are detail polygons
  247. uint16_t numPolygons = *((uint16_t*)cursor);cursor+=2;
  248. if (cursor < end)CopyFaceIndices(it,cursor,end,numPolygons);
  249. }
  250. face.surfaceIndex = surface-1;
  251. }
  252. }
  253. // ------------------------------------------------------------------------------------------------
  254. void LWOImporter::ResolveTags()
  255. {
  256. mMapping->resize(mTags->size(),0xffffffff);
  257. for (unsigned int a = 0; a < mTags->size();++a)
  258. {
  259. for (unsigned int i = 0; i < mSurfaces->size();++i)
  260. {
  261. if ((*mTags)[a] == (*mSurfaces)[i].mName)
  262. {
  263. (*mMapping)[a] = i;
  264. break;
  265. }
  266. }
  267. }
  268. }
  269. // ------------------------------------------------------------------------------------------------
  270. void LWOImporter::ParseString(std::string& out,unsigned int max)
  271. {
  272. unsigned int iCursor = 0;
  273. const char* in = (const char*)mFileBuffer,*sz = in;
  274. while (*in)
  275. {
  276. if (++iCursor > max)
  277. {
  278. DefaultLogger::get()->warn("LWOB: Invalid file, texture name (TIMG) is too long");
  279. break;
  280. }
  281. ++in;
  282. }
  283. unsigned int len = unsigned int (in-sz);
  284. out = std::string(sz,len);
  285. }
  286. // ------------------------------------------------------------------------------------------------
  287. void LWOImporter::AdjustTexturePath(std::string& out)
  288. {
  289. if (::strstr(out.c_str(), "(sequence)"))
  290. {
  291. // remove the (sequence) and append 000
  292. DefaultLogger::get()->info("LWO: Sequence of animated texture found. It will be ignored");
  293. out = out.substr(0,out.length()-10) + "000";
  294. }
  295. }
  296. // ------------------------------------------------------------------------------------------------
  297. #define AI_LWO_VALIDATE_CHUNK_LENGTH(name,size) \
  298. if (head->length < size) \
  299. { \
  300. DefaultLogger::get()->warn("LWO: "#name" chunk is too small"); \
  301. break; \
  302. } \
  303. // ------------------------------------------------------------------------------------------------
  304. void LWOImporter::LoadLWOTags(unsigned int size)
  305. {
  306. const char* szCur = (const char*)mFileBuffer, *szLast = szCur;
  307. const char* const szEnd = szLast+size;
  308. while (szCur < szEnd)
  309. {
  310. if (!(*szCur++))
  311. {
  312. const unsigned int len = unsigned int(szCur-szLast);
  313. mTags->push_back(std::string(szLast,len));
  314. szCur += len & 1;
  315. szLast = szCur;
  316. }
  317. }
  318. }
  319. // ------------------------------------------------------------------------------------------------
  320. void LWOImporter::LoadLWOBSurface(unsigned int size)
  321. {
  322. uint32_t iCursor = 0;
  323. mSurfaces->push_back( LWO::Surface () );
  324. LWO::Surface& surf = mSurfaces->back();
  325. LWO::Texture* pTex = NULL;
  326. // at first we'll need to read the name of the surface
  327. const uint8_t* sz = mFileBuffer;
  328. while (*mFileBuffer)
  329. {
  330. if (++iCursor > size)throw new ImportErrorException("LWOB: Invalid file, surface name is too long");
  331. ++mFileBuffer;
  332. }
  333. unsigned int len = unsigned int (mFileBuffer-sz);
  334. surf.mName = std::string((const char*)sz,len);
  335. mFileBuffer += 1-(len & 1); // skip one byte if the length of the string is odd
  336. while (true)
  337. {
  338. if ((iCursor += sizeof(IFF::ChunkHeader)) > size)break;
  339. LE_NCONST IFF::ChunkHeader* head = (LE_NCONST IFF::ChunkHeader*)mFileBuffer;
  340. AI_LSWAP4(head->length);
  341. AI_LSWAP4(head->type);
  342. if ((iCursor += head->length) > size)
  343. {
  344. throw new ImportErrorException("LWOB: Invalid file, the size attribute of "
  345. "a surface sub chunk points behind the end of the file");
  346. }
  347. mFileBuffer += sizeof(IFF::ChunkHeader);
  348. LE_NCONST uint8_t* next = mFileBuffer+head->length;
  349. switch (head->type)
  350. {
  351. // diffuse color
  352. case AI_LWO_COLR:
  353. {
  354. AI_LWO_VALIDATE_CHUNK_LENGTH(COLR,3);
  355. surf.mColor.r = *mFileBuffer++ / 255.0f;
  356. surf.mColor.g = *mFileBuffer++ / 255.0f;
  357. surf.mColor.b = *mFileBuffer / 255.0f;
  358. break;
  359. }
  360. // diffuse strength ... hopefully
  361. case AI_LWO_DIFF:
  362. {
  363. AI_LWO_VALIDATE_CHUNK_LENGTH(DIFF,2);
  364. AI_LSWAP2(mFileBuffer);
  365. surf.mDiffuseValue = *((int16_t*)mFileBuffer) / 255.0f;
  366. break;
  367. }
  368. // specular strength ... hopefully
  369. case AI_LWO_SPEC:
  370. {
  371. AI_LWO_VALIDATE_CHUNK_LENGTH(SPEC,2);
  372. AI_LSWAP2(mFileBuffer);
  373. surf.mSpecularValue = *((int16_t*)mFileBuffer) / 255.0f;
  374. break;
  375. }
  376. // transparency
  377. case AI_LWO_TRAN:
  378. {
  379. AI_LWO_VALIDATE_CHUNK_LENGTH(TRAN,2);
  380. AI_LSWAP2(mFileBuffer);
  381. surf.mTransparency = *((int16_t*)mFileBuffer) / 255.0f;
  382. break;
  383. }
  384. // glossiness
  385. case AI_LWO_GLOS:
  386. {
  387. AI_LWO_VALIDATE_CHUNK_LENGTH(GLOS,2);
  388. AI_LSWAP2(mFileBuffer);
  389. surf.mGlossiness = float(*((int16_t*)mFileBuffer));
  390. break;
  391. }
  392. // color texture
  393. case AI_LWO_CTEX:
  394. {
  395. pTex = &surf.mColorTexture;
  396. break;
  397. }
  398. // diffuse texture
  399. case AI_LWO_DTEX:
  400. {
  401. pTex = &surf.mDiffuseTexture;
  402. break;
  403. }
  404. // specular texture
  405. case AI_LWO_STEX:
  406. {
  407. pTex = &surf.mSpecularTexture;
  408. break;
  409. }
  410. // bump texture
  411. case AI_LWO_BTEX:
  412. {
  413. pTex = &surf.mBumpTexture;
  414. break;
  415. }
  416. // transparency texture
  417. case AI_LWO_TTEX:
  418. {
  419. pTex = &surf.mTransparencyTexture;
  420. break;
  421. }
  422. // texture path
  423. case AI_LWO_TIMG:
  424. {
  425. if (pTex)
  426. {
  427. ParseString(pTex->mFileName,head->length);
  428. AdjustTexturePath(pTex->mFileName);
  429. mFileBuffer += pTex->mFileName.length();
  430. }
  431. else DefaultLogger::get()->warn("LWOB: TIMG tag was encuntered although "
  432. "there was no xTEX tag before");
  433. break;
  434. }
  435. // texture strength
  436. case AI_LWO_TVAL:
  437. {
  438. AI_LWO_VALIDATE_CHUNK_LENGTH(TVAL,1);
  439. if (pTex)pTex->mStrength = *mFileBuffer / 255.0f;
  440. else DefaultLogger::get()->warn("LWOB: TVAL tag was encuntered "
  441. "although there was no xTEX tag before");
  442. break;
  443. }
  444. }
  445. mFileBuffer = next;
  446. }
  447. }
  448. // ------------------------------------------------------------------------------------------------
  449. void LWOImporter::LoadLWOBFile()
  450. {
  451. uint32_t iCursor = 0;
  452. while (true)
  453. {
  454. if ((iCursor += sizeof(IFF::ChunkHeader)) > this->fileSize)break;
  455. LE_NCONST IFF::ChunkHeader* head = (LE_NCONST IFF::ChunkHeader*)mFileBuffer;
  456. AI_LSWAP4(head->length);
  457. AI_LSWAP4(head->type);
  458. if ((iCursor += head->length) > this->fileSize)
  459. {
  460. //throw new ImportErrorException("LWOB: Invalid file, the size attribute of "
  461. // "a chunk points behind the end of the file");
  462. break;
  463. }
  464. mFileBuffer += sizeof(IFF::ChunkHeader);
  465. LE_NCONST uint8_t* next = mFileBuffer+head->length;
  466. switch (head->type)
  467. {
  468. // vertex list
  469. case AI_LWO_PNTS:
  470. {
  471. mTempPoints->resize( head->length / 12 );
  472. #ifndef AI_BUILD_BIG_ENDIAN
  473. for (unsigned int i = 0; i < head->length>>2;++i)
  474. ByteSwap::Swap4( mFileBuffer + (i << 2));
  475. #endif
  476. ::memcpy(&(*mTempPoints)[0],mFileBuffer,head->length);
  477. break;
  478. }
  479. // face list
  480. case AI_LWO_POLS:
  481. {
  482. // first find out how many faces and vertices we'll finally need
  483. const uint8_t* const end = mFileBuffer + head->length;
  484. LE_NCONST uint8_t* cursor = mFileBuffer;
  485. #ifndef AI_BUILD_BIG_ENDIAN
  486. while (cursor < end)ByteSwap::Swap2(cursor++);
  487. cursor = mFileBuffer;
  488. #endif
  489. unsigned int iNumFaces = 0,iNumVertices = 0;
  490. CountVertsAndFaces(iNumVertices,iNumFaces,cursor,end);
  491. // allocate the output array and copy face indices
  492. if (iNumFaces)
  493. {
  494. cursor = mFileBuffer;
  495. this->mTempPoints->resize(iNumVertices);
  496. this->mFaces->resize(iNumFaces);
  497. FaceList::iterator it = this->mFaces->begin();
  498. CopyFaceIndices(it,cursor,end);
  499. }
  500. break;
  501. }
  502. // list of tags
  503. case AI_LWO_SRFS:
  504. {
  505. LoadLWOTags(head->length);
  506. break;
  507. }
  508. // surface chunk
  509. case AI_LWO_SURF:
  510. {
  511. LoadLWOBSurface(head->length);
  512. break;
  513. }
  514. }
  515. mFileBuffer = next;
  516. }
  517. }
  518. // ------------------------------------------------------------------------------------------------
  519. void LWOImporter::LoadLWO2File()
  520. {
  521. }