LWOLoader.cpp 16 KB

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