LWOLoader.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  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. // -- no configuration options at the moment
  81. }
  82. // ------------------------------------------------------------------------------------------------
  83. // Imports the given file into the given scene structure.
  84. void LWOImporter::InternReadFile( const std::string& pFile,
  85. aiScene* pScene,
  86. IOSystem* pIOHandler)
  87. {
  88. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  89. // Check whether we can read from the file
  90. if( file.get() == NULL)
  91. throw new ImportErrorException( "Failed to open LWO file " + pFile + ".");
  92. if((this->fileSize = (unsigned int)file->FileSize()) < 12)
  93. throw new ImportErrorException("LWO: The file is too small to contain the IFF header");
  94. // allocate storage and copy the contents of the file to a memory buffer
  95. std::vector< uint8_t > mBuffer(fileSize);
  96. file->Read( &mBuffer[0], 1, fileSize);
  97. this->pScene = pScene;
  98. // determine the type of the file
  99. uint32_t fileType;
  100. const char* sz = IFF::ReadHeader(&mBuffer[0],fileType);
  101. if (sz)throw new ImportErrorException(sz);
  102. mFileBuffer = &mBuffer[0] + 12;
  103. fileSize -= 12;
  104. // create temporary storage on the stack but store pointers to it in the class
  105. // instance. Therefore everything will be destructed properly if an exception
  106. // is thrown and we needn't take care of that.
  107. LayerList _mLayers;
  108. mLayers = &_mLayers;
  109. TagList _mTags;
  110. mTags = &_mTags;
  111. TagMappingTable _mMapping;
  112. mMapping = &_mMapping;
  113. SurfaceList _mSurfaces;
  114. mSurfaces = &_mSurfaces;
  115. // allocate a default layer
  116. mLayers->push_back(Layer());
  117. mCurLayer = &mLayers->back();
  118. mCurLayer->mName = "<LWODefault>";
  119. // old lightwave file format (prior to v6)
  120. if (AI_LWO_FOURCC_LWOB == fileType)
  121. {
  122. mIsLWO2 = false;
  123. this->LoadLWOBFile();
  124. }
  125. // new lightwave format
  126. else if (AI_LWO_FOURCC_LWO2 == fileType)
  127. {
  128. mIsLWO2 = true;
  129. this->LoadLWO2File();
  130. }
  131. // we don't know this format
  132. else
  133. {
  134. char szBuff[5];
  135. szBuff[0] = (char)(fileType >> 24u);
  136. szBuff[1] = (char)(fileType >> 16u);
  137. szBuff[2] = (char)(fileType >> 8u);
  138. szBuff[3] = (char)(fileType);
  139. throw new ImportErrorException(std::string("Unknown LWO sub format: ") + szBuff);
  140. }
  141. ResolveTags();
  142. // now process all layers and build meshes and nodes
  143. std::vector<aiMesh*> apcMeshes;
  144. std::vector<aiNode*> apcNodes;
  145. apcNodes.reserve(mLayers->size());
  146. apcMeshes.reserve(mLayers->size()*std::min(((unsigned int)mSurfaces->size()/2u), 1u));
  147. // the RemoveRedundantMaterials step will clean this up later
  148. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials = (unsigned int)mSurfaces->size()];
  149. for (unsigned int mat = 0; mat < pScene->mNumMaterials;++mat)
  150. {
  151. MaterialHelper* pcMat = new MaterialHelper();
  152. pScene->mMaterials[mat] = pcMat;
  153. ConvertMaterial((*mSurfaces)[mat],pcMat);
  154. }
  155. unsigned int iDefaultSurface = 0xffffffff; // index of the default surface
  156. for (LayerList::const_iterator lit = mLayers->begin(), lend = mLayers->end();
  157. lit != lend;++lit)
  158. {
  159. const LWO::Layer& layer = *lit;
  160. // I don't know whether there could be dummy layers, but it would be possible
  161. const unsigned int meshStart = (unsigned int)apcMeshes.size();
  162. if (!layer.mFaces.empty() && !layer.mTempPoints.empty())
  163. {
  164. // now sort all faces by the surfaces assigned to them
  165. typedef std::vector<unsigned int> SortedRep;
  166. std::vector<SortedRep> pSorted(mSurfaces->size()+1);
  167. unsigned int i = 0;
  168. for (FaceList::const_iterator it = layer.mFaces.begin(), end = layer.mFaces.end();
  169. it != end;++it,++i)
  170. {
  171. unsigned int idx = (*it).surfaceIndex;
  172. if (idx >= mTags->size())
  173. {
  174. DefaultLogger::get()->warn("LWO: Invalid face surface index");
  175. idx = (unsigned int)mTags->size()-1;
  176. }
  177. if(0xffffffff == (idx = _mMapping[idx]))
  178. {
  179. if (0xffffffff == iDefaultSurface)
  180. {
  181. iDefaultSurface = (unsigned int)mSurfaces->size();
  182. mSurfaces->push_back(LWO::Surface());
  183. LWO::Surface& surf = mSurfaces->back();
  184. surf.mColor.r = surf.mColor.g = surf.mColor.b = 0.6f;
  185. }
  186. idx = iDefaultSurface;
  187. }
  188. pSorted[idx].push_back(i);
  189. }
  190. if (0xffffffff == iDefaultSurface)pSorted.erase(pSorted.end()-1);
  191. // now generate output meshes
  192. for (unsigned int p = 0; p < mSurfaces->size();++p)
  193. if (!pSorted[p].empty())pScene->mNumMeshes++;
  194. if (!pScene->mNumMeshes)
  195. throw new ImportErrorException("LWO: There are no meshes");
  196. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  197. for (unsigned int p = 0,i = 0;i < mSurfaces->size();++i)
  198. {
  199. SortedRep& sorted = pSorted[i];
  200. if (sorted.empty())continue;
  201. // generate the mesh
  202. aiMesh* mesh = new aiMesh();
  203. apcMeshes.push_back(mesh);
  204. mesh->mNumFaces = (unsigned int)sorted.size();
  205. for (SortedRep::const_iterator it = sorted.begin(), end = sorted.end();
  206. it != end;++it)
  207. {
  208. mesh->mNumVertices += layer.mFaces[*it].mNumIndices;
  209. }
  210. aiVector3D* pv = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  211. aiFace* pf = mesh->mFaces = new aiFace[mesh->mNumFaces];
  212. mesh->mMaterialIndex = i;
  213. // find out which vertex color channels and which texture coordinate
  214. // channels are really required by the material attached to this mesh
  215. unsigned int vUVChannelIndices[AI_MAX_NUMBER_OF_TEXTURECOORDS];
  216. unsigned int vVColorIndices[AI_MAX_NUMBER_OF_COLOR_SETS];
  217. #if _DEBUG
  218. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_TEXTURECOORDS;++mui )
  219. vUVChannelIndices[mui] = 0xffffffff;
  220. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_COLOR_SETS;++mui )
  221. vVColorIndices[mui] = 0xffffffff;
  222. #endif
  223. FindUVChannels(_mSurfaces[i],layer,vUVChannelIndices);
  224. FindVCChannels(_mSurfaces[i],layer,vVColorIndices);
  225. // allocate storage for UV and CV channels
  226. aiVector3D* pvUV[AI_MAX_NUMBER_OF_TEXTURECOORDS];
  227. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_TEXTURECOORDS;++mui )
  228. {
  229. if (0xffffffff == vUVChannelIndices[mui])break;
  230. pvUV[mui] = mesh->mTextureCoords[mui] = new aiVector3D[mesh->mNumVertices];
  231. // LightWave doesn't support more than 2 UV components
  232. mesh->mNumUVComponents[0] = 2;
  233. }
  234. aiColor4D* pvVC[AI_MAX_NUMBER_OF_COLOR_SETS];
  235. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_COLOR_SETS;++mui)
  236. {
  237. if (0xffffffff == vVColorIndices[mui])break;
  238. pvVC[mui] = mesh->mColors[mui] = new aiColor4D[mesh->mNumVertices];
  239. }
  240. // now convert all faces
  241. unsigned int vert = 0;
  242. for (SortedRep::const_iterator it = sorted.begin(), end = sorted.end();
  243. it != end;++it)
  244. {
  245. const LWO::Face& face = layer.mFaces[*it];
  246. // copy all vertices
  247. for (unsigned int q = 0; q < face.mNumIndices;++q)
  248. {
  249. register unsigned int idx = face.mIndices[q];
  250. *pv++ = layer.mTempPoints[idx];
  251. // process UV coordinates
  252. for (unsigned int w = 0; w < AI_MAX_NUMBER_OF_TEXTURECOORDS;++w)
  253. {
  254. if (0xffffffff == vUVChannelIndices[w])break;
  255. *(pvUV[w])++ = layer.mUVChannels[vUVChannelIndices[w]].data[idx];
  256. }
  257. // process vertex colors
  258. for (unsigned int w = 0; w < AI_MAX_NUMBER_OF_COLOR_SETS;++w)
  259. {
  260. if (0xffffffff == vVColorIndices[w])break;
  261. *(pvVC[w])++ = layer.mVColorChannels[vVColorIndices[w]].data[idx];
  262. }
  263. #if 0
  264. // process vertex weights - not yet supported
  265. for (unsigned int w = 0; w < layer.mWeightChannels.size();++w)
  266. {
  267. }
  268. #endif
  269. face.mIndices[q] = vert++;
  270. }
  271. pf->mIndices = face.mIndices;
  272. pf->mNumIndices = face.mNumIndices;
  273. const_cast<unsigned int*>(face.mIndices) = NULL; // make sure it won't be deleted
  274. pf++;
  275. }
  276. ++p;
  277. }
  278. }
  279. // generate nodes to render the mesh. Store the parent index
  280. // in the mParent member of the nodes
  281. aiNode* pcNode = new aiNode();
  282. apcNodes.push_back(pcNode);
  283. pcNode->mName.Set(layer.mName);
  284. pcNode->mParent = reinterpret_cast<aiNode*>(layer.mParent);
  285. pcNode->mNumMeshes = (unsigned int)apcMeshes.size() - meshStart;
  286. pcNode->mMeshes = new unsigned int[pcNode->mNumMeshes];
  287. for (unsigned int p = 0; p < pcNode->mNumMeshes;++p)
  288. pcNode->mMeshes[p] = p + meshStart;
  289. }
  290. // generate the final node graph
  291. GenerateNodeGraph(apcNodes);
  292. // copy the meshes to the output structure
  293. if (apcMeshes.size()) // shouldn't occur, just to be sure we don't crash
  294. {
  295. pScene->mMeshes = new aiMesh*[ pScene->mNumMeshes = (unsigned int)apcMeshes.size() ];
  296. ::memcpy(pScene->mMeshes,&apcMeshes[0],pScene->mNumMeshes*sizeof(void*));
  297. }
  298. }
  299. // ------------------------------------------------------------------------------------------------
  300. void LWOImporter::GenerateNodeGraph(std::vector<aiNode*>& apcNodes)
  301. {
  302. // now generate the final nodegraph
  303. uint16_t curIndex = 0;
  304. while (curIndex < (uint16_t)apcNodes.size())
  305. {
  306. aiNode* node;
  307. uint16_t iCurParent = curIndex-1;
  308. node = curIndex ? apcNodes[iCurParent] : new aiNode("<dummy_root>");
  309. unsigned int numChilds = 0;
  310. for (unsigned int i = 0; i < apcNodes.size();++i)
  311. {
  312. if (i == iCurParent)continue;
  313. if ( reinterpret_cast<uint16_t>(apcNodes[i]->mParent) == iCurParent)++numChilds;
  314. }
  315. if (numChilds)
  316. {
  317. if (!pScene->mRootNode)
  318. {
  319. pScene->mRootNode = node;
  320. }
  321. node->mChildren = new aiNode* [ node->mNumChildren = numChilds ];
  322. for (unsigned int i = 0, p = 0; i < apcNodes.size();++i)
  323. {
  324. if (i == iCurParent)continue;
  325. uint16_t parent = reinterpret_cast<uint16_t>(apcNodes[i]->mParent);
  326. if (parent == iCurParent)
  327. {
  328. node->mChildren[p++] = apcNodes[i];
  329. apcNodes[i]->mParent = node;
  330. apcNodes[i] = NULL;
  331. }
  332. }
  333. }
  334. else if (!curIndex)delete node;
  335. ++curIndex;
  336. }
  337. // remove a single root node
  338. // TODO: implement directly in the above loop, no need to deallocate here
  339. if (1 == pScene->mRootNode->mNumChildren)
  340. {
  341. aiNode* pc = pScene->mRootNode->mChildren[0];
  342. pc->mParent = pScene->mRootNode->mChildren[0] = NULL;
  343. delete pScene->mRootNode;
  344. pScene->mRootNode = pc;
  345. }
  346. // add unreferenced nodes to a dummy root
  347. unsigned int m = 0;
  348. for (std::vector<aiNode*>::iterator it = apcNodes.begin(), end = apcNodes.end();
  349. it != end;++it)
  350. {
  351. aiNode* p = *it;
  352. if (p)++m;
  353. }
  354. if (m)
  355. {
  356. aiNode* pc = new aiNode();
  357. pc->mName.Set("<dummy_root>");
  358. aiNode** cc = pc->mChildren = new aiNode*[ pc->mNumChildren = m+1 ];
  359. for (std::vector<aiNode*>::iterator it = apcNodes.begin(), end = apcNodes.end();
  360. it != end;++it)
  361. {
  362. aiNode* p = *it;
  363. if (p)*cc++ = p;
  364. }
  365. if (pScene->mRootNode)
  366. {
  367. *cc = pScene->mRootNode;
  368. pScene->mRootNode->mParent = pc;
  369. }
  370. else --pc->mNumChildren;
  371. pScene->mRootNode = pc;
  372. }
  373. if (!pScene->mRootNode)throw new ImportErrorException("LWO: Unable to build a valid node graph");
  374. }
  375. // ------------------------------------------------------------------------------------------------
  376. void LWOImporter::ResolveTags()
  377. {
  378. // --- this function is used for both LWO2 and LWOB
  379. mMapping->resize(mTags->size(),0xffffffff);
  380. for (unsigned int a = 0; a < mTags->size();++a)
  381. {
  382. for (unsigned int i = 0; i < mSurfaces->size();++i)
  383. {
  384. const std::string& c = (*mTags)[a];
  385. const std::string& d = (*mSurfaces)[i].mName;
  386. if (!ASSIMP_stricmp(c,d))
  387. {
  388. (*mMapping)[a] = i;
  389. break;
  390. }
  391. }
  392. }
  393. }
  394. // ------------------------------------------------------------------------------------------------
  395. void LWOImporter::ParseString(std::string& out,unsigned int max)
  396. {
  397. // --- this function is used for both LWO2 and LWOB
  398. unsigned int iCursor = 0;
  399. const char* in = (const char*)mFileBuffer,*sz = in;
  400. while (*in)
  401. {
  402. if (++iCursor > max)
  403. {
  404. DefaultLogger::get()->warn("LWOB: Invalid file, string is is too long");
  405. break;
  406. }
  407. ++in;
  408. }
  409. unsigned int len = (unsigned int) (in-sz);
  410. out = std::string(sz,len);
  411. }
  412. // ------------------------------------------------------------------------------------------------
  413. void LWOImporter::AdjustTexturePath(std::string& out)
  414. {
  415. // --- this function is used for both LWO2 and LWOB
  416. if (::strstr(out.c_str(), "(sequence)"))
  417. {
  418. // remove the (sequence) and append 000
  419. DefaultLogger::get()->info("LWO: Sequence of animated texture found. It will be ignored");
  420. out = out.substr(0,out.length()-10) + "000";
  421. }
  422. }
  423. // ------------------------------------------------------------------------------------------------
  424. int LWOImporter::ReadVSizedIntLWO2(uint8_t*& inout)
  425. {
  426. int i;
  427. int c = *inout;inout++;
  428. if(c != 0xFF)
  429. {
  430. i = c << 8;
  431. c = *inout;inout++;
  432. i |= c;
  433. }
  434. else
  435. {
  436. c = *inout;inout++;
  437. i = c << 16;
  438. c = *inout;inout++;
  439. i |= c << 8;
  440. c = *inout;inout++;
  441. i |= c;
  442. }
  443. return i;
  444. }
  445. // ------------------------------------------------------------------------------------------------
  446. void LWOImporter::LoadLWOTags(unsigned int size)
  447. {
  448. // --- this function is used for both LWO2 and LWOB
  449. const char* szCur = (const char*)mFileBuffer, *szLast = szCur;
  450. const char* const szEnd = szLast+size;
  451. while (szCur < szEnd)
  452. {
  453. if (!(*szCur))
  454. {
  455. const unsigned int len = (unsigned int)(szCur-szLast);
  456. mTags->push_back(std::string(szLast,len));
  457. szCur += len & 1;
  458. szLast = szCur;
  459. }
  460. szCur++;
  461. }
  462. }
  463. // ------------------------------------------------------------------------------------------------
  464. void LWOImporter::LoadLWOPoints(unsigned int length)
  465. {
  466. // --- this function is used for both LWO2 and LWOB
  467. mCurLayer->mTempPoints.resize( length / 12 );
  468. // perform endianess conversions
  469. #ifndef AI_BUILD_BIG_ENDIAN
  470. for (unsigned int i = 0; i < length>>2;++i)
  471. ByteSwap::Swap4( mFileBuffer + (i << 2));
  472. #endif
  473. ::memcpy(&mCurLayer->mTempPoints[0],mFileBuffer,length);
  474. }
  475. // ------------------------------------------------------------------------------------------------
  476. void LWOImporter::LoadLWOPolygons(unsigned int length)
  477. {
  478. // --- this function is used for both LWO2 and LWOB
  479. if (mIsLWO2)
  480. {
  481. uint32_t type = *((LE_NCONST uint32_t*)mFileBuffer);mFileBuffer += 4;
  482. if (type != AI_LWO_FACE)
  483. {
  484. DefaultLogger::get()->warn("LWO2: Only POLS.FACE chunsk are supported.");
  485. return;
  486. }
  487. }
  488. // first find out how many faces and vertices we'll finally need
  489. LE_NCONST uint16_t* const end = (LE_NCONST uint16_t*)(mFileBuffer+length);
  490. LE_NCONST uint16_t* cursor = (LE_NCONST uint16_t*)mFileBuffer;
  491. // perform endianess conversions
  492. #ifndef AI_BUILD_BIG_ENDIAN
  493. while (cursor < end)ByteSwap::Swap2(cursor++);
  494. cursor = (LE_NCONST uint16_t*)mFileBuffer;
  495. #endif
  496. unsigned int iNumFaces = 0,iNumVertices = 0;
  497. if (mIsLWO2)CountVertsAndFacesLWO2(iNumVertices,iNumFaces,cursor,end);
  498. else CountVertsAndFacesLWOB(iNumVertices,iNumFaces,cursor,end);
  499. // allocate the output array and copy face indices
  500. if (iNumFaces)
  501. {
  502. cursor = (LE_NCONST uint16_t*)mFileBuffer;
  503. mCurLayer->mFaces.resize(iNumFaces);
  504. FaceList::iterator it = mCurLayer->mFaces.begin();
  505. if (mIsLWO2)CopyFaceIndicesLWO2(it,cursor,end);
  506. else CopyFaceIndicesLWOB(it,cursor,end);
  507. }
  508. }
  509. // ------------------------------------------------------------------------------------------------
  510. void LWOImporter::CountVertsAndFacesLWO2(unsigned int& verts, unsigned int& faces,
  511. LE_NCONST uint16_t*& cursor, const uint16_t* const end, unsigned int max)
  512. {
  513. while (cursor < end && max--)
  514. {
  515. uint16_t numIndices = *cursor++;
  516. numIndices &= 0x03FF;
  517. verts += numIndices;++faces;
  518. for(uint16_t i = 0; i < numIndices; i++)
  519. ReadVSizedIntLWO2((uint8_t*&)cursor);
  520. }
  521. }
  522. // ------------------------------------------------------------------------------------------------
  523. void LWOImporter::CopyFaceIndicesLWO2(FaceList::iterator& it,
  524. LE_NCONST uint16_t*& cursor,
  525. const uint16_t* const end,
  526. unsigned int max)
  527. {
  528. while (cursor < end && max--)
  529. {
  530. LWO::Face& face = *it;++it;
  531. if(face.mNumIndices = (*cursor++) & 0x03FF)
  532. {
  533. face.mIndices = new unsigned int[face.mNumIndices];
  534. for(unsigned int i = 0; i < face.mNumIndices; i++)
  535. {
  536. face.mIndices[i] = ReadVSizedIntLWO2((uint8_t*&)cursor) + mCurLayer->mPointIDXOfs;
  537. if(face.mIndices[i] > mCurLayer->mTempPoints.size())
  538. {
  539. DefaultLogger::get()->warn("LWO2: face index is out of range");
  540. face.mIndices[i] = (unsigned int)mCurLayer->mTempPoints.size()-1;
  541. }
  542. }
  543. }
  544. else DefaultLogger::get()->warn("LWO2: face has 0 indices");
  545. }
  546. }
  547. // ------------------------------------------------------------------------------------------------
  548. void LWOImporter::LoadLWO2PolygonTags(unsigned int length)
  549. {
  550. uint32_t type = *((LE_NCONST uint32_t*)mFileBuffer);mFileBuffer+=4;
  551. AI_LSWAP4(type);
  552. if (type != AI_LWO_SURF && type != AI_LWO_SMGP)
  553. return;
  554. LE_NCONST uint8_t* const end = mFileBuffer+length;
  555. while (mFileBuffer < end)
  556. {
  557. unsigned int i = ReadVSizedIntLWO2(mFileBuffer) + mCurLayer->mFaceIDXOfs;
  558. unsigned int j = ReadVSizedIntLWO2(mFileBuffer);
  559. if (i > mCurLayer->mFaces.size())
  560. {
  561. DefaultLogger::get()->warn("LWO2: face index in ptag list is out of range");
  562. continue;
  563. }
  564. switch (type)
  565. {
  566. case AI_LWO_SURF:
  567. mCurLayer->mFaces[i].surfaceIndex = j;
  568. break;
  569. case AI_LWO_SMGP:
  570. mCurLayer->mFaces[i].smoothGroup = j;
  571. break;
  572. };
  573. }
  574. }
  575. // ------------------------------------------------------------------------------------------------
  576. void LWOImporter::LoadLWO2VertexMap(unsigned int length, bool perPoly)
  577. {
  578. unsigned int type = *((LE_NCONST uint32_t*)mFileBuffer);mFileBuffer+=4;
  579. unsigned int dims = *((LE_NCONST uint16_t*)mFileBuffer);mFileBuffer+=2;
  580. VMapEntry* base;
  581. switch (type)
  582. {
  583. case AI_LWO_TXUV:
  584. if (dims != 2)
  585. {
  586. DefaultLogger::get()->warn("LWO2: Found UV channel with != 2 components");
  587. }
  588. mCurLayer->mUVChannels.push_back(UVChannel((unsigned int)mCurLayer->mTempPoints.size()));
  589. base = &mCurLayer->mUVChannels.back();
  590. case AI_LWO_WGHT:
  591. if (dims != 1)
  592. {
  593. DefaultLogger::get()->warn("LWO2: found vertex weight map with != 1 components");
  594. }
  595. mCurLayer->mWeightChannels.push_back(WeightChannel((unsigned int)mCurLayer->mTempPoints.size()));
  596. base = &mCurLayer->mWeightChannels.back();
  597. case AI_LWO_RGB:
  598. case AI_LWO_RGBA:
  599. if (dims != 3 && dims != 4)
  600. {
  601. DefaultLogger::get()->warn("LWO2: found vertex color map with != 3&4 components");
  602. }
  603. mCurLayer->mVColorChannels.push_back(VColorChannel((unsigned int)mCurLayer->mTempPoints.size()));
  604. base = &mCurLayer->mVColorChannels.back();
  605. default: return;
  606. };
  607. // read the name of the vertex map
  608. ParseString(base->name,length);
  609. // now read all entries in the map
  610. type = std::min(dims,base->dims);
  611. const unsigned int diff = (dims - type)<<2;
  612. LE_NCONST uint8_t* const end = mFileBuffer+length;
  613. while (mFileBuffer < end)
  614. {
  615. unsigned int idx = ReadVSizedIntLWO2(mFileBuffer) + mCurLayer->mPointIDXOfs;
  616. if (idx > mCurLayer->mTempPoints.size())
  617. {
  618. DefaultLogger::get()->warn("LWO2: vertex index in vmap/vmad is out of range");
  619. continue;
  620. }
  621. for (unsigned int i = 0; i < type;++i)
  622. {
  623. base->rawData[idx*dims+i]= *((float*)mFileBuffer);
  624. mFileBuffer += 4;
  625. }
  626. mFileBuffer += diff;
  627. }
  628. }
  629. // ------------------------------------------------------------------------------------------------
  630. void LWOImporter::LoadLWO2File()
  631. {
  632. LE_NCONST uint8_t* const end = mFileBuffer + fileSize;
  633. while (true)
  634. {
  635. if (mFileBuffer + sizeof(IFF::ChunkHeader) > end)break;
  636. LE_NCONST IFF::ChunkHeader* const head = (LE_NCONST IFF::ChunkHeader*)mFileBuffer;
  637. AI_LSWAP4(head->length);
  638. AI_LSWAP4(head->type);
  639. mFileBuffer += sizeof(IFF::ChunkHeader);
  640. if (mFileBuffer + head->length > end)
  641. {
  642. throw new ImportErrorException("LWOB: Invalid file, the size attribute of "
  643. "a chunk points behind the end of the file");
  644. break;
  645. }
  646. LE_NCONST uint8_t* const next = mFileBuffer+head->length;
  647. unsigned int iUnnamed = 0;
  648. switch (head->type)
  649. {
  650. // new layer
  651. case AI_LWO_LAYR:
  652. {
  653. // add a new layer to the list ....
  654. mLayers->push_back ( LWO::Layer() );
  655. LWO::Layer& layer = mLayers->back();
  656. mCurLayer = &layer;
  657. AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,LAYR,16);
  658. // and parse its properties
  659. mFileBuffer += 16;
  660. ParseString(layer.mName,head->length-16);
  661. // if the name is empty, generate a default name
  662. if (layer.mName.empty())
  663. {
  664. char buffer[128]; // should be sufficiently large
  665. ::sprintf(buffer,"Layer_%i", iUnnamed++);
  666. layer.mName = buffer;
  667. }
  668. if (mFileBuffer + 2 <= next)
  669. layer.mParent = *((uint16_t*)mFileBuffer);
  670. break;
  671. }
  672. // vertex list
  673. case AI_LWO_PNTS:
  674. {
  675. unsigned int old = (unsigned int)mCurLayer->mTempPoints.size();
  676. LoadLWOPoints(head->length);
  677. mCurLayer->mPointIDXOfs = old;
  678. break;
  679. }
  680. // vertex tags
  681. //case AI_LWO_VMAD:
  682. case AI_LWO_VMAP:
  683. {
  684. if (mCurLayer->mTempPoints.empty())
  685. DefaultLogger::get()->warn("LWO2: Unexpected VMAD/VMAP chunk");
  686. else LoadLWO2VertexMap(head->length,head->type == AI_LWO_VMAD);
  687. break;
  688. }
  689. // face list
  690. case AI_LWO_POLS:
  691. {
  692. unsigned int old = (unsigned int)mCurLayer->mFaces.size();
  693. LoadLWOPolygons(head->length);
  694. mCurLayer->mFaceIDXOfs = old;
  695. break;
  696. }
  697. // polygon tags
  698. case AI_LWO_PTAG:
  699. {
  700. if (mCurLayer->mFaces.empty())
  701. DefaultLogger::get()->warn("LWO2: Unexpected PTAG");
  702. else LoadLWO2PolygonTags(head->length);
  703. break;
  704. }
  705. // list of tags
  706. case AI_LWO_SRFS:
  707. {
  708. if (!mTags->empty())
  709. DefaultLogger::get()->warn("LWO2: SRFS chunk encountered twice");
  710. else LoadLWOTags(head->length);
  711. break;
  712. }
  713. // surface chunk
  714. case AI_LWO_SURF:
  715. {
  716. if (!mSurfaces->empty())
  717. DefaultLogger::get()->warn("LWO2: SURF chunk encountered twice");
  718. else LoadLWO2Surface(head->length);
  719. break;
  720. }
  721. }
  722. mFileBuffer = next;
  723. }
  724. }