LWOLoader.cpp 25 KB

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