LWOLoader.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  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. #include "AssimpPCH.h"
  36. // internal headers
  37. #include "LWOLoader.h"
  38. #include "MaterialSystem.h"
  39. #include "StringComparison.h"
  40. #include "SGSpatialSort.h"
  41. #include "ByteSwap.h"
  42. #include "ProcessHelper.h"
  43. using namespace Assimp;
  44. // ------------------------------------------------------------------------------------------------
  45. // Constructor to be privately used by Importer
  46. LWOImporter::LWOImporter()
  47. {
  48. }
  49. // ------------------------------------------------------------------------------------------------
  50. // Destructor, private as well
  51. LWOImporter::~LWOImporter()
  52. {
  53. }
  54. // ------------------------------------------------------------------------------------------------
  55. // Returns whether the class can handle the format of the given file.
  56. bool LWOImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler) const
  57. {
  58. // simple check of file extension is enough for the moment
  59. std::string::size_type pos = pFile.find_last_of('.');
  60. // no file extension - can't read
  61. if( pos == std::string::npos)return false;
  62. std::string extension = pFile.substr( pos);
  63. if (extension.length() < 4)return false;
  64. if (extension[0] != '.')return false;
  65. if (extension[1] != 'l' && extension[1] != 'L')return false;
  66. if (extension[2] != 'w' && extension[2] != 'W')return false;
  67. if (extension[3] != 'o' && extension[3] != 'O')return false;
  68. return true;
  69. }
  70. // ------------------------------------------------------------------------------------------------
  71. // Setup configuration properties
  72. void LWOImporter::SetupProperties(const Importer* pImp)
  73. {
  74. configSpeedFlag = ( 0 != pImp->GetPropertyInteger(AI_CONFIG_FAVOUR_SPEED,0) ? true : false);
  75. configLayerIndex = pImp->GetPropertyInteger (AI_CONFIG_IMPORT_LWO_ONE_LAYER_ONLY,0xffffffff);
  76. configLayerName = pImp->GetPropertyString (AI_CONFIG_IMPORT_LWO_ONE_LAYER_ONLY,"");
  77. }
  78. // ------------------------------------------------------------------------------------------------
  79. // Imports the given file into the given scene structure.
  80. void LWOImporter::InternReadFile( const std::string& pFile,
  81. aiScene* pScene,
  82. IOSystem* pIOHandler)
  83. {
  84. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  85. // Check whether we can read from the file
  86. if( file.get() == NULL)
  87. throw new ImportErrorException( "Failed to open LWO file " + pFile + ".");
  88. if((this->fileSize = (unsigned int)file->FileSize()) < 12)
  89. throw new ImportErrorException("LWO: The file is too small to contain the IFF header");
  90. // allocate storage and copy the contents of the file to a memory buffer
  91. std::vector< uint8_t > mBuffer(fileSize);
  92. file->Read( &mBuffer[0], 1, fileSize);
  93. this->pScene = pScene;
  94. // determine the type of the file
  95. uint32_t fileType;
  96. const char* sz = IFF::ReadHeader(&mBuffer[0],fileType);
  97. if (sz)throw new ImportErrorException(sz);
  98. mFileBuffer = &mBuffer[0] + 12;
  99. fileSize -= 12;
  100. // create temporary storage on the stack but store pointers to it in the class
  101. // instance. Therefore everything will be destructed properly if an exception
  102. // is thrown and we needn't take care of that.
  103. LayerList _mLayers;
  104. mLayers = &_mLayers;
  105. TagList _mTags;
  106. mTags = &_mTags;
  107. TagMappingTable _mMapping;
  108. mMapping = &_mMapping;
  109. SurfaceList _mSurfaces;
  110. mSurfaces = &_mSurfaces;
  111. // allocate a default layer
  112. mLayers->push_back(Layer());
  113. mCurLayer = &mLayers->back();
  114. mCurLayer->mName = "<LWODefault>";
  115. // old lightwave file format (prior to v6)
  116. if (AI_LWO_FOURCC_LWOB == fileType)
  117. {
  118. DefaultLogger::get()->info("LWO file format: LWOB (<= LightWave 5.5)");
  119. mIsLWO2 = false;
  120. this->LoadLWOBFile();
  121. }
  122. // new lightwave format
  123. else if (AI_LWO_FOURCC_LWO2 == fileType)
  124. {
  125. DefaultLogger::get()->info("LWO file format: LWO2 (>= LightWave 6)");
  126. mIsLWO2 = true;
  127. this->LoadLWO2File();
  128. }
  129. // we don't know this format
  130. else
  131. {
  132. char szBuff[5];
  133. szBuff[0] = (char)(fileType >> 24u);
  134. szBuff[1] = (char)(fileType >> 16u);
  135. szBuff[2] = (char)(fileType >> 8u);
  136. szBuff[3] = (char)(fileType);
  137. throw new ImportErrorException(std::string("Unknown LWO sub format: ") + szBuff);
  138. }
  139. // now, as we have loaded all data, we can resolve cross-referenced tags and clips
  140. ResolveTags();
  141. ResolveClips();
  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::iterator lit = mLayers->begin(), lend = mLayers->end();
  149. lit != lend;++lit)
  150. {
  151. 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::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. // count the number of vertices
  198. SortedRep::const_iterator it = sorted.begin(), end = sorted.end();
  199. for (;it != end;++it)
  200. {
  201. mesh->mNumVertices += layer.mFaces[*it].mNumIndices;
  202. }
  203. aiVector3D* pv = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  204. aiFace* pf = mesh->mFaces = new aiFace[mesh->mNumFaces];
  205. mesh->mMaterialIndex = i;
  206. // find out which vertex color channels and which texture coordinate
  207. // channels are really required by the material attached to this mesh
  208. unsigned int vUVChannelIndices[AI_MAX_NUMBER_OF_TEXTURECOORDS];
  209. unsigned int vVColorIndices[AI_MAX_NUMBER_OF_COLOR_SETS];
  210. #if _DEBUG
  211. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_TEXTURECOORDS;++mui )
  212. vUVChannelIndices[mui] = 0xffffffff;
  213. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_COLOR_SETS;++mui )
  214. vVColorIndices[mui] = 0xffffffff;
  215. #endif
  216. FindUVChannels(_mSurfaces[i],layer,vUVChannelIndices);
  217. FindVCChannels(_mSurfaces[i],layer,vVColorIndices);
  218. // allocate storage for UV and CV channels
  219. aiVector3D* pvUV[AI_MAX_NUMBER_OF_TEXTURECOORDS];
  220. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_TEXTURECOORDS;++mui )
  221. {
  222. if (0xffffffff == vUVChannelIndices[mui])break;
  223. pvUV[mui] = mesh->mTextureCoords[mui] = new aiVector3D[mesh->mNumVertices];
  224. // LightWave doesn't support more than 2 UV components
  225. mesh->mNumUVComponents[0] = 2;
  226. }
  227. aiColor4D* pvVC[AI_MAX_NUMBER_OF_COLOR_SETS];
  228. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_COLOR_SETS;++mui)
  229. {
  230. if (0xffffffff == vVColorIndices[mui])break;
  231. pvVC[mui] = mesh->mColors[mui] = new aiColor4D[mesh->mNumVertices];
  232. }
  233. // we would not need this extra array, but the code is much cleaner if we use it
  234. // FIX: we can use the referrer ID array here. invalidate its contents
  235. // before we resize it to avoid a unnecessary memcpy
  236. std::vector<unsigned int>& smoothingGroups = layer.mPointReferrers;
  237. smoothingGroups.erase (smoothingGroups.begin(),smoothingGroups.end());
  238. smoothingGroups.resize(mesh->mNumFaces,0);
  239. // now convert all faces
  240. unsigned int vert = 0;
  241. std::vector<unsigned int>::iterator outIt = smoothingGroups.begin();
  242. for (it = sorted.begin(); it != end;++it,++outIt)
  243. {
  244. const LWO::Face& face = layer.mFaces[*it];
  245. *outIt = face.smoothGroup;
  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] + layer.mPivot;
  251. pv->z *= -1.0f; // DX to OGL
  252. pv++;
  253. // process UV coordinates
  254. for (unsigned int w = 0; w < AI_MAX_NUMBER_OF_TEXTURECOORDS;++w)
  255. {
  256. if (0xffffffff == vUVChannelIndices[w])break;
  257. aiVector3D*& pp = pvUV[w];
  258. const aiVector2D& src = ((aiVector2D*)&layer.mUVChannels[vUVChannelIndices[w]].rawData[0])[idx];
  259. pp->x = src.x;
  260. pp->y = src.y; // DX to OGL
  261. pp++;
  262. }
  263. // process vertex colors
  264. for (unsigned int w = 0; w < AI_MAX_NUMBER_OF_COLOR_SETS;++w)
  265. {
  266. if (0xffffffff == vVColorIndices[w])break;
  267. *(pvVC[w])++ = ((aiColor4D*)&layer.mVColorChannels[vVColorIndices[w]].rawData[0])[idx];
  268. }
  269. #if 0
  270. // process vertex weights - not yet supported
  271. for (unsigned int w = 0; w < layer.mWeightChannels.size();++w)
  272. {
  273. }
  274. #endif
  275. face.mIndices[q] = vert + (face.mNumIndices-q-1);
  276. }
  277. vert += face.mNumIndices;
  278. pf->mIndices = face.mIndices;
  279. pf->mNumIndices = face.mNumIndices;
  280. unsigned int** p = (unsigned int**)&face.mIndices;*p = NULL; // make sure it won't be deleted
  281. pf++;
  282. }
  283. // compute normal vectors for the mesh - we can't use our GenSmoothNormal-Step here
  284. // since it wouldn't handle smoothing groups correctly
  285. ComputeNormals(mesh,smoothingGroups,_mSurfaces[i]);
  286. ++p;
  287. }
  288. }
  289. // generate nodes to render the mesh. Store the parent index
  290. // in the mParent member of the nodes
  291. aiNode* pcNode = new aiNode();
  292. apcNodes.push_back(pcNode);
  293. pcNode->mName.Set(layer.mName);
  294. pcNode->mParent = (aiNode*)(uintptr_t)(layer.mParent);
  295. pcNode->mNumMeshes = (unsigned int)apcMeshes.size() - meshStart;
  296. pcNode->mMeshes = new unsigned int[pcNode->mNumMeshes];
  297. for (unsigned int p = 0; p < pcNode->mNumMeshes;++p)
  298. pcNode->mMeshes[p] = p + meshStart;
  299. }
  300. // the RemoveRedundantMaterials step will clean this up later
  301. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials = (unsigned int)mSurfaces->size()];
  302. for (unsigned int mat = 0; mat < pScene->mNumMaterials;++mat)
  303. {
  304. MaterialHelper* pcMat = new MaterialHelper();
  305. pScene->mMaterials[mat] = pcMat;
  306. ConvertMaterial((*mSurfaces)[mat],pcMat);
  307. }
  308. // copy the meshes to the output structure
  309. if (apcMeshes.size()) // shouldn't occur, just to be sure we don't crash
  310. {
  311. pScene->mMeshes = new aiMesh*[ pScene->mNumMeshes = (unsigned int)apcMeshes.size() ];
  312. ::memcpy(pScene->mMeshes,&apcMeshes[0],pScene->mNumMeshes*sizeof(void*));
  313. }
  314. // generate the final node graph
  315. GenerateNodeGraph(apcNodes);
  316. }
  317. // ------------------------------------------------------------------------------------------------
  318. void LWOImporter::ComputeNormals(aiMesh* mesh, const std::vector<unsigned int>& smoothingGroups,
  319. const LWO::Surface& surface)
  320. {
  321. // allocate output storage
  322. mesh->mNormals = new aiVector3D[mesh->mNumVertices];
  323. // First generate per-face normals
  324. aiVector3D* out;
  325. std::vector<aiVector3D> faceNormals;
  326. if (!surface.mMaximumSmoothAngle)
  327. out = mesh->mNormals;
  328. else
  329. {
  330. faceNormals.resize(mesh->mNumVertices);
  331. out = &faceNormals[0];
  332. }
  333. aiFace* begin = mesh->mFaces, *const end = mesh->mFaces+mesh->mNumFaces;
  334. for (; begin != end; ++begin)
  335. {
  336. aiFace& face = *begin;
  337. // LWO doc: "the normal is defined as the cross product of the first and last edges"
  338. aiVector3D* pV1 = mesh->mVertices + face.mIndices[0];
  339. aiVector3D* pV2 = mesh->mVertices + face.mIndices[1];
  340. aiVector3D* pV3 = mesh->mVertices + face.mIndices[face.mNumIndices-1];
  341. aiVector3D vNor = ((*pV2 - *pV1) ^ (*pV3 - *pV1)).Normalize();
  342. for (unsigned int i = 0; i < face.mNumIndices;++i)
  343. out[face.mIndices[i]] = vNor;
  344. }
  345. if (!surface.mMaximumSmoothAngle)return;
  346. const float posEpsilon = ComputePositionEpsilon(mesh);
  347. // now generate the spatial sort tree
  348. SGSpatialSort sSort;
  349. std::vector<unsigned int>::const_iterator it = smoothingGroups.begin();
  350. for( begin = mesh->mFaces; begin != end; ++begin, ++it)
  351. {
  352. aiFace& face = *begin;
  353. for (unsigned int i = 0; i < face.mNumIndices;++i)
  354. {
  355. register unsigned int tt = face.mIndices[i];
  356. sSort.Add(mesh->mVertices[tt],tt,*it);
  357. }
  358. }
  359. // sort everything - this takes O(nlogn) time
  360. sSort.Prepare();
  361. std::vector<unsigned int> poResult;
  362. poResult.reserve(20);
  363. // generate vertex normals. We have O(logn) for the binary lookup, which we need
  364. // for n elements, thus the EXPECTED complexity is O(nlogn)
  365. if (surface.mMaximumSmoothAngle < 3.f && !configSpeedFlag)
  366. {
  367. const float fLimit = cos(surface.mMaximumSmoothAngle);
  368. for( begin = mesh->mFaces, it = smoothingGroups.begin(); begin != end; ++begin, ++it)
  369. {
  370. register unsigned int sg = *it;
  371. aiFace& face = *begin;
  372. unsigned int* beginIdx = face.mIndices, *const endIdx = face.mIndices+face.mNumIndices;
  373. for (; beginIdx != endIdx; ++beginIdx)
  374. {
  375. register unsigned int idx = *beginIdx;
  376. sSort.FindPositions(mesh->mVertices[idx],sg,posEpsilon,poResult,true);
  377. std::vector<unsigned int>::const_iterator a, end = poResult.end();
  378. aiVector3D vNormals;
  379. for (a = poResult.begin();a != end;++a)
  380. {
  381. const aiVector3D& v = faceNormals[*a];
  382. if (v * faceNormals[idx] < fLimit)continue;
  383. vNormals += v;
  384. }
  385. vNormals.Normalize();
  386. mesh->mNormals[idx] = vNormals;
  387. }
  388. }
  389. }
  390. else // faster code path in case there is no smooth angle
  391. {
  392. std::vector<bool> vertexDone(mesh->mNumVertices,false);
  393. for( begin = mesh->mFaces, it = smoothingGroups.begin(); begin != end; ++begin, ++it)
  394. {
  395. register unsigned int sg = *it;
  396. aiFace& face = *begin;
  397. unsigned int* beginIdx = face.mIndices, *const endIdx = face.mIndices+face.mNumIndices;
  398. for (; beginIdx != endIdx; ++beginIdx)
  399. {
  400. register unsigned int idx = *beginIdx;
  401. if (vertexDone[idx])continue;
  402. sSort.FindPositions(mesh->mVertices[idx],sg,posEpsilon,poResult,true);
  403. std::vector<unsigned int>::const_iterator a, end = poResult.end();
  404. aiVector3D vNormals;
  405. for (a = poResult.begin();a != end;++a)
  406. {
  407. const aiVector3D& v = faceNormals[*a];
  408. vNormals += v;
  409. }
  410. vNormals.Normalize();
  411. for (a = poResult.begin();a != end;++a)
  412. {
  413. mesh->mNormals[*a] = vNormals;
  414. vertexDone[*a] = true;
  415. }
  416. }
  417. }
  418. }
  419. }
  420. // ------------------------------------------------------------------------------------------------
  421. void LWOImporter::AddChildren(aiNode* node, uintptr_t parent, std::vector<aiNode*>& apcNodes)
  422. {
  423. for (uintptr_t i = 0; i < (uintptr_t)apcNodes.size();++i)
  424. {
  425. if (i == parent)continue;
  426. if (apcNodes[i] && (uintptr_t)apcNodes[i]->mParent == parent)++node->mNumChildren;
  427. }
  428. if (node->mNumChildren)
  429. {
  430. node->mChildren = new aiNode* [ node->mNumChildren ];
  431. for (uintptr_t i = 0, p = 0; i < (uintptr_t)apcNodes.size();++i)
  432. {
  433. if (i == parent)continue;
  434. if (apcNodes[i] && parent == (uintptr_t)(apcNodes[i]->mParent))
  435. {
  436. node->mChildren[p++] = apcNodes[i];
  437. apcNodes[i]->mParent = node;
  438. // recursively add more children
  439. AddChildren(apcNodes[i],i,apcNodes);
  440. apcNodes[i] = NULL;
  441. }
  442. }
  443. }
  444. }
  445. // ------------------------------------------------------------------------------------------------
  446. void LWOImporter::GenerateNodeGraph(std::vector<aiNode*>& apcNodes)
  447. {
  448. // now generate the final nodegraph - generate a root node
  449. pScene->mRootNode = new aiNode();
  450. pScene->mRootNode->mName.Set("<LWORoot>");
  451. AddChildren(pScene->mRootNode,0,apcNodes);
  452. unsigned int extra = 0;
  453. for (unsigned int i = 0; i < apcNodes.size();++i)
  454. if (apcNodes[i] && apcNodes[i]->mNumMeshes)++extra;
  455. if (extra)
  456. {
  457. // we need to add extra nodes to the root
  458. const unsigned int newSize = extra + pScene->mRootNode->mNumChildren;
  459. aiNode** const apcNewNodes = new aiNode*[newSize];
  460. if((extra = pScene->mRootNode->mNumChildren))
  461. ::memcpy(apcNewNodes,pScene->mRootNode->mChildren,extra*sizeof(void*));
  462. aiNode** cc = apcNewNodes+extra;
  463. for (unsigned int i = 0; i < apcNodes.size();++i)
  464. {
  465. if (apcNodes[i] && apcNodes[i]->mNumMeshes)
  466. {
  467. *cc++ = apcNodes[i];
  468. apcNodes[i]->mParent = pScene->mRootNode;
  469. // recursively add more children
  470. AddChildren(apcNodes[i],i,apcNodes);
  471. apcNodes[i] = NULL;
  472. }
  473. }
  474. delete[] pScene->mRootNode->mChildren;
  475. pScene->mRootNode->mChildren = apcNewNodes;
  476. pScene->mRootNode->mNumChildren = newSize;
  477. }
  478. if (!pScene->mRootNode->mNumChildren)throw new ImportErrorException("LWO: Unable to build a valid node graph");
  479. // remove a single root node
  480. // TODO: implement directly in the above loop, no need to deallocate here
  481. if (1 == pScene->mRootNode->mNumChildren)
  482. {
  483. aiNode* pc = pScene->mRootNode->mChildren[0];
  484. pc->mParent = pScene->mRootNode->mChildren[0] = NULL;
  485. delete pScene->mRootNode;
  486. pScene->mRootNode = pc;
  487. }
  488. }
  489. // ------------------------------------------------------------------------------------------------
  490. void LWOImporter::ResolveTags()
  491. {
  492. // --- this function is used for both LWO2 and LWOB
  493. mMapping->resize(mTags->size(),0xffffffff);
  494. for (unsigned int a = 0; a < mTags->size();++a)
  495. {
  496. for (unsigned int i = 0; i < mSurfaces->size();++i)
  497. {
  498. const std::string& c = (*mTags)[a];
  499. const std::string& d = (*mSurfaces)[i].mName;
  500. if (!ASSIMP_stricmp(c,d))
  501. {
  502. (*mMapping)[a] = i;
  503. break;
  504. }
  505. }
  506. }
  507. }
  508. // ------------------------------------------------------------------------------------------------
  509. void LWOImporter::ResolveClips()
  510. {
  511. for( unsigned int i = 0; i < mClips.size();++i)
  512. {
  513. Clip& clip = mClips[i];
  514. if (Clip::REF == clip.type)
  515. {
  516. if (clip.clipRef >= mClips.size())
  517. {
  518. DefaultLogger::get()->error("LWO2: Clip referrer index is out of range");
  519. clip.clipRef = 0;
  520. }
  521. Clip& dest = mClips[clip.clipRef];
  522. if (Clip::REF == dest.type)
  523. {
  524. DefaultLogger::get()->error("LWO2: Clip references another clip reference");
  525. clip.type = Clip::UNSUPPORTED;
  526. }
  527. else
  528. {
  529. clip.path = dest.path;
  530. clip.type = dest.type;
  531. }
  532. }
  533. }
  534. }
  535. // ------------------------------------------------------------------------------------------------
  536. void LWOImporter::AdjustTexturePath(std::string& out)
  537. {
  538. // --- this function is used for both LWO2 and LWOB
  539. if (!mIsLWO2 && ::strstr(out.c_str(), "(sequence)"))
  540. {
  541. // remove the (sequence) and append 000
  542. DefaultLogger::get()->info("LWOB: Sequence of animated texture found. It will be ignored");
  543. out = out.substr(0,out.length()-10) + "000";
  544. }
  545. // format: drive:path/file - we need to insert a slash after the drive
  546. std::string::size_type n = out.find_first_of(':');
  547. if (std::string::npos != n)
  548. {
  549. out.insert(n+1,"/");
  550. }
  551. }
  552. // ------------------------------------------------------------------------------------------------
  553. void LWOImporter::LoadLWOTags(unsigned int size)
  554. {
  555. // --- this function is used for both LWO2 and LWOB
  556. const char* szCur = (const char*)mFileBuffer, *szLast = szCur;
  557. const char* const szEnd = szLast+size;
  558. while (szCur < szEnd)
  559. {
  560. if (!(*szCur))
  561. {
  562. const unsigned int len = (unsigned int)(szCur-szLast);
  563. mTags->push_back(std::string(szLast,len));
  564. szCur += len & 1;
  565. szLast = szCur;
  566. }
  567. szCur++;
  568. }
  569. }
  570. // ------------------------------------------------------------------------------------------------
  571. void LWOImporter::LoadLWOPoints(unsigned int length)
  572. {
  573. // --- this function is used for both LWO2 and LWOB but for
  574. // LWO2 we need to allocate 25% more storage - it could be we'll
  575. // need to duplicate some points later.
  576. register unsigned int regularSize = (unsigned int)mCurLayer->mTempPoints.size() + length / 12;
  577. if (mIsLWO2)
  578. {
  579. mCurLayer->mTempPoints.reserve ( regularSize + (regularSize>>2u) );
  580. mCurLayer->mTempPoints.resize ( regularSize );
  581. // initialize all point referrers with the default values
  582. mCurLayer->mPointReferrers.reserve ( regularSize + (regularSize>>2u) );
  583. mCurLayer->mPointReferrers.resize ( regularSize, 0xffffffff );
  584. }
  585. else mCurLayer->mTempPoints.resize( regularSize );
  586. // perform endianess conversions
  587. #ifndef AI_BUILD_BIG_ENDIAN
  588. for (unsigned int i = 0; i < length>>2;++i)
  589. ByteSwap::Swap4( mFileBuffer + (i << 2));
  590. #endif
  591. ::memcpy(&mCurLayer->mTempPoints[0],mFileBuffer,length);
  592. }
  593. // ------------------------------------------------------------------------------------------------
  594. void LWOImporter::LoadLWO2Polygons(unsigned int length)
  595. {
  596. LE_NCONST uint16_t* const end = (LE_NCONST uint16_t*)(mFileBuffer+length);
  597. uint32_t type = GetU4();
  598. if (type != AI_LWO_FACE)
  599. {
  600. DefaultLogger::get()->warn("LWO2: Only POLS.FACE chunks are supported.");
  601. return;
  602. }
  603. // first find out how many faces and vertices we'll finally need
  604. uint16_t* cursor = (uint16_t*)mFileBuffer;
  605. unsigned int iNumFaces = 0,iNumVertices = 0;
  606. CountVertsAndFacesLWO2(iNumVertices,iNumFaces,cursor,end);
  607. // allocate the output array and copy face indices
  608. if (iNumFaces)
  609. {
  610. cursor = (uint16_t*)mFileBuffer;
  611. mCurLayer->mFaces.resize(iNumFaces);
  612. FaceList::iterator it = mCurLayer->mFaces.begin();
  613. CopyFaceIndicesLWO2(it,cursor,end);
  614. }
  615. }
  616. // ------------------------------------------------------------------------------------------------
  617. void LWOImporter::CountVertsAndFacesLWO2(unsigned int& verts, unsigned int& faces,
  618. uint16_t*& cursor, const uint16_t* const end, unsigned int max)
  619. {
  620. while (cursor < end && max--)
  621. {
  622. AI_LSWAP2P(cursor);
  623. uint16_t numIndices = *cursor++;
  624. numIndices &= 0x03FF;
  625. verts += numIndices;++faces;
  626. for(uint16_t i = 0; i < numIndices; i++)
  627. ReadVSizedIntLWO2((uint8_t*&)cursor);
  628. }
  629. }
  630. // ------------------------------------------------------------------------------------------------
  631. void LWOImporter::CopyFaceIndicesLWO2(FaceList::iterator& it,
  632. uint16_t*& cursor,
  633. const uint16_t* const end)
  634. {
  635. while (cursor < end)
  636. {
  637. LWO::Face& face = *it;++it;
  638. if((face.mNumIndices = (*cursor++) & 0x03FF)) // swapping has already been done
  639. {
  640. face.mIndices = new unsigned int[face.mNumIndices];
  641. for(unsigned int i = 0; i < face.mNumIndices; i++)
  642. {
  643. face.mIndices[i] = ReadVSizedIntLWO2((uint8_t*&)cursor) + mCurLayer->mPointIDXOfs;
  644. if(face.mIndices[i] > mCurLayer->mTempPoints.size())
  645. {
  646. DefaultLogger::get()->warn("LWO2: face index is out of range");
  647. face.mIndices[i] = (unsigned int)mCurLayer->mTempPoints.size()-1;
  648. }
  649. }
  650. }
  651. else DefaultLogger::get()->warn("LWO2: face has 0 indices");
  652. }
  653. }
  654. // ------------------------------------------------------------------------------------------------
  655. void LWOImporter::LoadLWO2PolygonTags(unsigned int length)
  656. {
  657. LE_NCONST uint8_t* const end = mFileBuffer+length;
  658. AI_LWO_VALIDATE_CHUNK_LENGTH(length,PTAG,4);
  659. uint32_t type = GetU4();
  660. if (type != AI_LWO_SURF && type != AI_LWO_SMGP)
  661. return;
  662. while (mFileBuffer < end)
  663. {
  664. unsigned int i = ReadVSizedIntLWO2(mFileBuffer) + mCurLayer->mFaceIDXOfs;
  665. unsigned int j = GetU2();
  666. if (i >= mCurLayer->mFaces.size())
  667. {
  668. DefaultLogger::get()->warn("LWO2: face index in PTAG is out of range");
  669. continue;
  670. }
  671. switch (type)
  672. {
  673. case AI_LWO_SURF:
  674. mCurLayer->mFaces[i].surfaceIndex = j;
  675. break;
  676. case AI_LWO_SMGP:
  677. mCurLayer->mFaces[i].smoothGroup = j;
  678. break;
  679. };
  680. }
  681. }
  682. // ------------------------------------------------------------------------------------------------
  683. template <class T>
  684. VMapEntry* FindEntry(std::vector< T >& list,const std::string& name, bool perPoly)
  685. {
  686. for (typename std::vector< T >::iterator it = list.begin(), end = list.end();
  687. it != end; ++it)
  688. {
  689. if ((*it).name == name)
  690. {
  691. if (!perPoly)
  692. {
  693. DefaultLogger::get()->warn("LWO2: Found two VMAP sections with equal names");
  694. }
  695. return &(*it);
  696. }
  697. }
  698. list.push_back( T() );
  699. VMapEntry* p = &list.back();
  700. p->name = name;
  701. return p;
  702. }
  703. // ------------------------------------------------------------------------------------------------
  704. template <class T>
  705. void CreateNewEntry(std::vector< T >& list, unsigned int srcIdx)
  706. {
  707. for (typename std::vector< T >::iterator
  708. it = list.begin(), end = list.end();
  709. it != end;++it)
  710. {
  711. T& chan = *it;
  712. chan.abAssigned[srcIdx] = true;
  713. chan.abAssigned.resize(chan.abAssigned.size()+1,false);
  714. for (unsigned int a = 0; a < chan.dims;++a)
  715. chan.rawData.push_back(chan.rawData[srcIdx*chan.dims+a]);
  716. }
  717. }
  718. // ------------------------------------------------------------------------------------------------
  719. void LWOImporter::DoRecursiveVMAPAssignment(VMapEntry* base, unsigned int numRead,
  720. unsigned int idx, float* data)
  721. {
  722. ai_assert(NULL != data);
  723. LWO::ReferrerList& refList = mCurLayer->mPointReferrers;
  724. unsigned int i;
  725. base->abAssigned[idx] = true;
  726. for (i = 0; i < numRead;++i)
  727. base->rawData[idx*base->dims+i]= data[i];
  728. if (0xffffffff != (i = refList[idx]))
  729. DoRecursiveVMAPAssignment(base,numRead,i,data);
  730. }
  731. // ------------------------------------------------------------------------------------------------
  732. void AddToSingleLinkedList(ReferrerList& refList, unsigned int srcIdx, unsigned int destIdx)
  733. {
  734. if(0xffffffff == refList[srcIdx])
  735. {
  736. refList[srcIdx] = destIdx;
  737. return;
  738. }
  739. AddToSingleLinkedList(refList,refList[srcIdx],destIdx);
  740. }
  741. // ------------------------------------------------------------------------------------------------
  742. void LWOImporter::LoadLWO2VertexMap(unsigned int length, bool perPoly)
  743. {
  744. LE_NCONST uint8_t* const end = mFileBuffer+length;
  745. AI_LWO_VALIDATE_CHUNK_LENGTH(length,VMAP,6);
  746. unsigned int type = GetU4();
  747. unsigned int dims = GetU2();
  748. VMapEntry* base;
  749. // read the name of the vertex map
  750. std::string name;
  751. GetS0(name,length);
  752. switch (type)
  753. {
  754. case AI_LWO_TXUV:
  755. if (dims != 2)
  756. {
  757. DefaultLogger::get()->warn("LWO2: Found UV channel with != 2 components");
  758. }
  759. base = FindEntry(mCurLayer->mUVChannels,name,perPoly);
  760. break;
  761. case AI_LWO_WGHT:
  762. if (dims != 1)
  763. {
  764. DefaultLogger::get()->warn("LWO2: found vertex weight map with != 1 components");
  765. }
  766. base = FindEntry(mCurLayer->mWeightChannels,name,perPoly);
  767. break;
  768. case AI_LWO_RGB:
  769. case AI_LWO_RGBA:
  770. if (dims != 3 && dims != 4)
  771. {
  772. DefaultLogger::get()->warn("LWO2: found vertex color map with != 3&4 components");
  773. }
  774. base = FindEntry(mCurLayer->mVColorChannels,name,perPoly);
  775. break;
  776. default: return;
  777. };
  778. base->Allocate((unsigned int)mCurLayer->mTempPoints.size());
  779. // now read all entries in the map
  780. type = std::min(dims,base->dims);
  781. const unsigned int diff = (dims - type)<<2;
  782. LWO::FaceList& list = mCurLayer->mFaces;
  783. LWO::PointList& pointList = mCurLayer->mTempPoints;
  784. LWO::ReferrerList& refList = mCurLayer->mPointReferrers;
  785. float temp[4];
  786. const unsigned int numPoints = (unsigned int)pointList.size();
  787. const unsigned int numFaces = (unsigned int)list.size();
  788. while (mFileBuffer < end)
  789. {
  790. unsigned int idx = ReadVSizedIntLWO2(mFileBuffer) + mCurLayer->mPointIDXOfs;
  791. if (idx >= numPoints)
  792. {
  793. DefaultLogger::get()->warn("LWO2: vertex index in vmap/vmad is out of range");
  794. mFileBuffer += base->dims*4;continue;
  795. }
  796. if (perPoly)
  797. {
  798. unsigned int polyIdx = ReadVSizedIntLWO2(mFileBuffer) + mCurLayer->mFaceIDXOfs;
  799. if (base->abAssigned[idx])
  800. {
  801. // we have already a VMAP entry for this vertex - thus
  802. // we need to duplicate the corresponding polygon.
  803. if (polyIdx >= numFaces)
  804. {
  805. DefaultLogger::get()->warn("LWO2: VMAD polygon index is out of range");
  806. mFileBuffer += base->dims*4;continue;
  807. }
  808. LWO::Face& src = list[polyIdx];
  809. refList.resize(refList.size()+src.mNumIndices, 0xffffffff);
  810. // generate new vertex positions
  811. for (unsigned int i = 0; i < src.mNumIndices;++i)
  812. {
  813. register unsigned int srcIdx = src.mIndices[i];
  814. if (idx == srcIdx)
  815. {
  816. idx = (unsigned int)pointList.size();
  817. }
  818. src.mIndices[i] = (unsigned int)pointList.size();
  819. // store the index of the new vertex in the old vertex
  820. // so we get a single linked list we can traverse in
  821. // only one direction
  822. AddToSingleLinkedList(refList,srcIdx,src.mIndices[i]);
  823. pointList.push_back(pointList[srcIdx]);
  824. CreateNewEntry(mCurLayer->mVColorChannels, srcIdx );
  825. CreateNewEntry(mCurLayer->mUVChannels, srcIdx );
  826. CreateNewEntry(mCurLayer->mWeightChannels, srcIdx );
  827. }
  828. }
  829. }
  830. for (unsigned int l = 0; l < type;++l)
  831. temp[l] = GetF4();
  832. DoRecursiveVMAPAssignment(base,type,idx, temp);
  833. mFileBuffer += diff;
  834. }
  835. }
  836. // ------------------------------------------------------------------------------------------------
  837. void LWOImporter::LoadLWO2Clip(unsigned int length)
  838. {
  839. AI_LWO_VALIDATE_CHUNK_LENGTH(length,CLIP,10);
  840. mClips.push_back(LWO::Clip());
  841. LWO::Clip& clip = mClips.back();
  842. // first - get the index of the clip
  843. clip.idx = GetU4();
  844. IFF::SubChunkHeader* const head = IFF::LoadSubChunk(mFileBuffer);
  845. switch (head->type)
  846. {
  847. case AI_LWO_STIL:
  848. GetS0(clip.path,head->length);
  849. clip.type = Clip::STILL;
  850. break;
  851. case AI_LWO_ISEQ:
  852. {
  853. uint8_t digits = GetU1(); mFileBuffer++;
  854. int16_t offset = GetU2(); mFileBuffer+=4;
  855. int16_t start = GetU2(); mFileBuffer+=4;
  856. std::string s;std::stringstream ss;
  857. GetS0(s,head->length);
  858. head->length -= (unsigned int)s.length()+1;
  859. ss << s;
  860. ss << std::setw(digits) << offset + start;
  861. GetS0(s,head->length);
  862. ss << s;
  863. clip.path = ss.str();
  864. clip.type = Clip::SEQ;
  865. }
  866. break;
  867. case AI_LWO_STCC:
  868. DefaultLogger::get()->warn("LWO2: Color shifted images are not supported");
  869. break;
  870. case AI_LWO_ANIM:
  871. DefaultLogger::get()->warn("LWO2: Animated textures are not supported");
  872. break;
  873. case AI_LWO_XREF:
  874. clip.type = Clip::REF;
  875. clip.clipRef = GetU4();
  876. break;
  877. default:
  878. DefaultLogger::get()->warn("LWO2: Encountered unknown CLIP subchunk");
  879. }
  880. }
  881. // ------------------------------------------------------------------------------------------------
  882. void LWOImporter::LoadLWO2File()
  883. {
  884. LE_NCONST uint8_t* const end = mFileBuffer + fileSize;
  885. while (true)
  886. {
  887. if (mFileBuffer + sizeof(IFF::ChunkHeader) > end)break;
  888. IFF::ChunkHeader* const head = IFF::LoadChunk(mFileBuffer);
  889. if (mFileBuffer + head->length > end)
  890. {
  891. throw new ImportErrorException("LWO2: Chunk length points behind the file");
  892. break;
  893. }
  894. uint8_t* const next = mFileBuffer+head->length;
  895. unsigned int iUnnamed = 0;
  896. switch (head->type)
  897. {
  898. // new layer
  899. case AI_LWO_LAYR:
  900. {
  901. // add a new layer to the list ....
  902. mLayers->push_back ( LWO::Layer() );
  903. LWO::Layer& layer = mLayers->back();
  904. mCurLayer = &layer;
  905. AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,LAYR,16);
  906. // and parse its properties, e.g. the pivot point
  907. mFileBuffer += 2;
  908. mCurLayer->mPivot.x = GetF4();
  909. mCurLayer->mPivot.y = GetF4();
  910. mCurLayer->mPivot.z = GetF4();
  911. mFileBuffer += 2;
  912. GetS0(layer.mName,head->length-16);
  913. // if the name is empty, generate a default name
  914. if (layer.mName.empty())
  915. {
  916. char buffer[128]; // should be sufficiently large
  917. ::sprintf(buffer,"Layer_%i", iUnnamed++);
  918. layer.mName = buffer;
  919. }
  920. if (mFileBuffer + 2 <= next)
  921. layer.mParent = GetU2();
  922. break;
  923. }
  924. // vertex list
  925. case AI_LWO_PNTS:
  926. {
  927. unsigned int old = (unsigned int)mCurLayer->mTempPoints.size();
  928. LoadLWOPoints(head->length);
  929. mCurLayer->mPointIDXOfs = old;
  930. break;
  931. }
  932. // vertex tags
  933. case AI_LWO_VMAD:
  934. if (mCurLayer->mFaces.empty())
  935. {
  936. DefaultLogger::get()->warn("LWO2: Unexpected VMAD chunk");
  937. break;
  938. }
  939. // --- intentionally no break here
  940. case AI_LWO_VMAP:
  941. {
  942. if (mCurLayer->mTempPoints.empty())
  943. DefaultLogger::get()->warn("LWO2: Unexpected VMAP chunk");
  944. else LoadLWO2VertexMap(head->length,head->type == AI_LWO_VMAD);
  945. break;
  946. }
  947. // face list
  948. case AI_LWO_POLS:
  949. {
  950. unsigned int old = (unsigned int)mCurLayer->mFaces.size();
  951. LoadLWO2Polygons(head->length);
  952. mCurLayer->mFaceIDXOfs = old;
  953. break;
  954. }
  955. // polygon tags
  956. case AI_LWO_PTAG:
  957. {
  958. if (mCurLayer->mFaces.empty())
  959. DefaultLogger::get()->warn("LWO2: Unexpected PTAG");
  960. else LoadLWO2PolygonTags(head->length);
  961. break;
  962. }
  963. // list of tags
  964. case AI_LWO_TAGS:
  965. {
  966. if (!mTags->empty())
  967. DefaultLogger::get()->warn("LWO2: SRFS chunk encountered twice");
  968. else LoadLWOTags(head->length);
  969. break;
  970. }
  971. // surface chunk
  972. case AI_LWO_SURF:
  973. {
  974. LoadLWO2Surface(head->length);
  975. break;
  976. }
  977. // clip chunk
  978. case AI_LWO_CLIP:
  979. {
  980. LoadLWO2Clip(head->length);
  981. break;
  982. }
  983. }
  984. mFileBuffer = next;
  985. }
  986. }