LWOLoader.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362
  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 LWOLoader.cpp
  35. * @brief Implementation of the LWO importer class
  36. */
  37. #include "AssimpPCH.h"
  38. #ifndef ASSIMP_BUILD_NO_LWO_IMPORTER
  39. // internal headers
  40. #include "LWOLoader.h"
  41. #include "MaterialSystem.h"
  42. #include "StringComparison.h"
  43. #include "SGSpatialSort.h"
  44. #include "ByteSwap.h"
  45. #include "ProcessHelper.h"
  46. #include "ConvertToLHProcess.h"
  47. using namespace Assimp;
  48. // ------------------------------------------------------------------------------------------------
  49. // Constructor to be privately used by Importer
  50. LWOImporter::LWOImporter()
  51. {}
  52. // ------------------------------------------------------------------------------------------------
  53. // Destructor, private as well
  54. LWOImporter::~LWOImporter()
  55. {}
  56. // ------------------------------------------------------------------------------------------------
  57. // Returns whether the class can handle the format of the given file.
  58. bool LWOImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  59. {
  60. const std::string extension = GetExtension(pFile);
  61. if (extension == "lwo" || extension == "lxo")
  62. return true;
  63. // if check for extension is not enough, check for the magic tokens
  64. if (!extension.length() || checkSig) {
  65. uint32_t tokens[3];
  66. tokens[0] = AI_LWO_FOURCC_LWOB;
  67. tokens[1] = AI_LWO_FOURCC_LWO2;
  68. tokens[2] = AI_LWO_FOURCC_LXOB;
  69. return CheckMagicToken(pIOHandler,pFile,tokens,3,8);
  70. }
  71. return false;
  72. }
  73. // ------------------------------------------------------------------------------------------------
  74. // Setup configuration properties
  75. void LWOImporter::SetupProperties(const Importer* pImp)
  76. {
  77. configSpeedFlag = ( 0 != pImp->GetPropertyInteger(AI_CONFIG_FAVOUR_SPEED,0) ? true : false);
  78. configLayerIndex = pImp->GetPropertyInteger (AI_CONFIG_IMPORT_LWO_ONE_LAYER_ONLY,0xffffffff);
  79. configLayerName = pImp->GetPropertyString (AI_CONFIG_IMPORT_LWO_ONE_LAYER_ONLY,"");
  80. }
  81. // ------------------------------------------------------------------------------------------------
  82. // Imports the given file into the given scene structure.
  83. void LWOImporter::InternReadFile( const std::string& pFile,
  84. aiScene* pScene,
  85. IOSystem* pIOHandler)
  86. {
  87. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  88. // Check whether we can read from the file
  89. if( file.get() == NULL)
  90. throw new ImportErrorException( "Failed to open LWO file " + pFile + ".");
  91. if((this->fileSize = (unsigned int)file->FileSize()) < 12)
  92. throw new ImportErrorException("LWO: The file is too small to contain the IFF header");
  93. // Allocate storage and copy the contents of the file to a memory buffer
  94. std::vector< uint8_t > mBuffer(fileSize);
  95. file->Read( &mBuffer[0], 1, fileSize);
  96. this->pScene = pScene;
  97. // Determine the type of the file
  98. uint32_t fileType;
  99. const char* sz = IFF::ReadHeader(&mBuffer[0],fileType);
  100. if (sz)throw new ImportErrorException(sz);
  101. mFileBuffer = &mBuffer[0] + 12;
  102. fileSize -= 12;
  103. // Initialize some members with their default values
  104. hasNamedLayer = false;
  105. // Create temporary storage on the stack but store pointers to it in the class
  106. // instance. Therefore everything will be destructed properly if an exception
  107. // is thrown and we needn't take care of that.
  108. LayerList _mLayers;
  109. SurfaceList _mSurfaces;
  110. TagList _mTags;
  111. TagMappingTable _mMapping;
  112. mLayers = &_mLayers;
  113. mTags = &_mTags;
  114. mMapping = &_mMapping;
  115. mSurfaces = &_mSurfaces;
  116. // Allocate a default layer (layer indices are 1-based from now)
  117. mLayers->push_back(Layer());
  118. mCurLayer = &mLayers->back();
  119. mCurLayer->mName = "<LWODefault>";
  120. // old lightwave file format (prior to v6)
  121. if (AI_LWO_FOURCC_LWOB == fileType) {
  122. DefaultLogger::get()->info("LWO file format: LWOB (<= LightWave 5.5)");
  123. mIsLWO2 = false;
  124. LoadLWOBFile();
  125. }
  126. // New lightwave format
  127. else if (AI_LWO_FOURCC_LWO2 == fileType) {
  128. DefaultLogger::get()->info("LWO file format: LWO2 (>= LightWave 6)");
  129. }
  130. // MODO file format
  131. else if (AI_LWO_FOURCC_LXOB == fileType) {
  132. DefaultLogger::get()->info("LWO file format: LXOB (Modo)");
  133. }
  134. // we don't know this format
  135. else
  136. {
  137. char szBuff[5];
  138. szBuff[0] = (char)(fileType >> 24u);
  139. szBuff[1] = (char)(fileType >> 16u);
  140. szBuff[2] = (char)(fileType >> 8u);
  141. szBuff[3] = (char)(fileType);
  142. throw new ImportErrorException(std::string("Unknown LWO sub format: ") + szBuff);
  143. }
  144. if (AI_LWO_FOURCC_LWOB != fileType) {
  145. mIsLWO2 = true;
  146. LoadLWO2File();
  147. // The newer lightwave format allows the user to configure the
  148. // loader that just one layer is used. If this is the case
  149. // we need to check now whether the requested layer has been found.
  150. if (0xffffffff != configLayerIndex && configLayerIndex > mLayers->size())
  151. throw new ImportErrorException("LWO2: The requested layer was not found");
  152. if (configLayerName.length() && !hasNamedLayer) {
  153. throw new ImportErrorException("LWO2: Unable to find the requested layer: "
  154. + configLayerName);
  155. }
  156. }
  157. // now, as we have loaded all data, we can resolve cross-referenced tags and clips
  158. ResolveTags();
  159. ResolveClips();
  160. // now process all layers and build meshes and nodes
  161. std::vector<aiMesh*> apcMeshes;
  162. std::vector<aiNode*> apcNodes;
  163. apcNodes. reserve(mLayers->size());
  164. apcMeshes.reserve(mLayers->size()*std::min(((unsigned int)mSurfaces->size()/2u), 1u));
  165. unsigned int iDefaultSurface = 0xffffffff; // index of the default surface
  166. for (LayerList::iterator lit = mLayers->begin(), lend = mLayers->end();lit != lend;++lit) {
  167. LWO::Layer& layer = *lit;
  168. if (layer.skip)
  169. continue;
  170. // I don't know whether there could be dummy layers, but it would be possible
  171. const unsigned int meshStart = (unsigned int)apcMeshes.size();
  172. if (!layer.mFaces.empty() && !layer.mTempPoints.empty()) {
  173. // now sort all faces by the surfaces assigned to them
  174. std::vector<SortedRep> pSorted(mSurfaces->size()+1);
  175. unsigned int i = 0;
  176. for (FaceList::iterator it = layer.mFaces.begin(), end = layer.mFaces.end();it != end;++it,++i) {
  177. // Check whether we support this face's type
  178. if ((*it).type != AI_LWO_FACE && (*it).type != AI_LWO_PTCH) {
  179. continue;
  180. }
  181. unsigned int idx = (*it).surfaceIndex;
  182. if (idx >= mTags->size())
  183. {
  184. DefaultLogger::get()->warn("LWO: Invalid face surface index");
  185. idx = 0xffffffff;
  186. }
  187. if(0xffffffff == idx || 0xffffffff == (idx = _mMapping[idx])) {
  188. if (0xffffffff == iDefaultSurface) {
  189. iDefaultSurface = (unsigned int)mSurfaces->size();
  190. mSurfaces->push_back(LWO::Surface());
  191. LWO::Surface& surf = mSurfaces->back();
  192. surf.mColor.r = surf.mColor.g = surf.mColor.b = 0.6f;
  193. surf.mName = "LWODefaultSurface";
  194. }
  195. idx = iDefaultSurface;
  196. }
  197. pSorted[idx].push_back(i);
  198. }
  199. if (0xffffffff == iDefaultSurface) {
  200. pSorted.erase(pSorted.end()-1);
  201. }
  202. for (unsigned int p = 0,i = 0;i < mSurfaces->size();++i) {
  203. SortedRep& sorted = pSorted[i];
  204. if (sorted.empty())
  205. continue;
  206. // generate the mesh
  207. aiMesh* mesh = new aiMesh();
  208. apcMeshes.push_back(mesh);
  209. mesh->mNumFaces = (unsigned int)sorted.size();
  210. // count the number of vertices
  211. SortedRep::const_iterator it = sorted.begin(), end = sorted.end();
  212. for (;it != end;++it) {
  213. mesh->mNumVertices += layer.mFaces[*it].mNumIndices;
  214. }
  215. aiVector3D *nrm = NULL, * pv = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  216. aiFace* pf = mesh->mFaces = new aiFace[mesh->mNumFaces];
  217. mesh->mMaterialIndex = i;
  218. // find out which vertex color channels and which texture coordinate
  219. // channels are really required by the material attached to this mesh
  220. unsigned int vUVChannelIndices[AI_MAX_NUMBER_OF_TEXTURECOORDS];
  221. unsigned int vVColorIndices[AI_MAX_NUMBER_OF_COLOR_SETS];
  222. #if _DEBUG
  223. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_TEXTURECOORDS;++mui )
  224. vUVChannelIndices[mui] = 0xffffffff;
  225. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_COLOR_SETS;++mui )
  226. vVColorIndices[mui] = 0xffffffff;
  227. #endif
  228. FindUVChannels(_mSurfaces[i],sorted,layer,vUVChannelIndices);
  229. FindVCChannels(_mSurfaces[i],sorted,layer,vVColorIndices);
  230. // allocate storage for UV and CV channels
  231. aiVector3D* pvUV[AI_MAX_NUMBER_OF_TEXTURECOORDS];
  232. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_TEXTURECOORDS;++mui ) {
  233. if (0xffffffff == vUVChannelIndices[mui])
  234. break;
  235. pvUV[mui] = mesh->mTextureCoords[mui] = new aiVector3D[mesh->mNumVertices];
  236. // LightWave doesn't support more than 2 UV components (?)
  237. mesh->mNumUVComponents[0] = 2;
  238. }
  239. if (layer.mNormals.name.length())
  240. nrm = mesh->mNormals = new aiVector3D[mesh->mNumVertices];
  241. aiColor4D* pvVC[AI_MAX_NUMBER_OF_COLOR_SETS];
  242. for (unsigned int mui = 0; mui < AI_MAX_NUMBER_OF_COLOR_SETS;++mui) {
  243. if (0xffffffff == vVColorIndices[mui])break;
  244. pvVC[mui] = mesh->mColors[mui] = new aiColor4D[mesh->mNumVertices];
  245. }
  246. // we would not need this extra array, but the code is much cleaner if we use it
  247. std::vector<unsigned int>& smoothingGroups = layer.mPointReferrers;
  248. smoothingGroups.erase (smoothingGroups.begin(),smoothingGroups.end());
  249. smoothingGroups.resize(mesh->mNumFaces,0);
  250. // now convert all faces
  251. unsigned int vert = 0;
  252. std::vector<unsigned int>::iterator outIt = smoothingGroups.begin();
  253. for (it = sorted.begin(); it != end;++it,++outIt) {
  254. const LWO::Face& face = layer.mFaces[*it];
  255. *outIt = face.smoothGroup;
  256. // copy all vertices
  257. for (unsigned int q = 0; q < face.mNumIndices;++q,++vert) {
  258. register unsigned int idx = face.mIndices[q];
  259. *pv++ = layer.mTempPoints[idx] /*- layer.mPivot*/;
  260. // process UV coordinates
  261. for (unsigned int w = 0; w < AI_MAX_NUMBER_OF_TEXTURECOORDS;++w) {
  262. if (0xffffffff == vUVChannelIndices[w])
  263. break;
  264. aiVector3D*& pp = pvUV[w];
  265. const aiVector2D& src = ((aiVector2D*)&layer.mUVChannels[vUVChannelIndices[w]].rawData[0])[idx];
  266. pp->x = src.x;
  267. pp->y = src.y;
  268. pp++;
  269. }
  270. // process normals (MODO extension)
  271. if (nrm) {
  272. *nrm = ((aiVector3D*)&layer.mNormals.rawData[0])[idx];
  273. nrm->z *= -1.f;
  274. ++nrm;
  275. }
  276. // process vertex colors
  277. for (unsigned int w = 0; w < AI_MAX_NUMBER_OF_COLOR_SETS;++w) {
  278. if (0xffffffff == vVColorIndices[w])
  279. break;
  280. *pvVC[w] = ((aiColor4D*)&layer.mVColorChannels[vVColorIndices[w]].rawData[0])[idx];
  281. // If a RGB color map is explicitly requested delete the
  282. // alpha channel - it could theoretically be != 1.
  283. if(_mSurfaces[i].mVCMapType == AI_LWO_RGB)
  284. pvVC[w]->a = 1.f;
  285. pvVC[w]++;
  286. }
  287. #if 0
  288. // process vertex weights - not yet supported
  289. for (unsigned int w = 0; w < layer.mWeightChannels.size();++w)
  290. {
  291. }
  292. #endif
  293. face.mIndices[q] = vert;
  294. }
  295. pf->mIndices = face.mIndices;
  296. pf->mNumIndices = face.mNumIndices;
  297. unsigned int** p = (unsigned int**)&face.mIndices;*p = NULL; // HACK: make sure it won't be deleted
  298. pf++;
  299. }
  300. if (!mesh->mNormals) {
  301. // Compute normal vectors for the mesh - we can't use our GenSmoothNormal-
  302. // Step here since it wouldn't handle smoothing groups correctly for LWO.
  303. // So we use a separate implementation.
  304. ComputeNormals(mesh,smoothingGroups,_mSurfaces[i]);
  305. }
  306. else DefaultLogger::get()->debug("LWO2: No need to compute normals, they're already there");
  307. ++p;
  308. }
  309. }
  310. // Generate nodes to render the mesh. Store the source layer in the mParent member of the nodes
  311. unsigned int num = apcMeshes.size() - meshStart;
  312. if (layer.mName != "<LWODefault>" || num > 0) {
  313. aiNode* pcNode = new aiNode();
  314. apcNodes.push_back(pcNode);
  315. pcNode->mName.Set(layer.mName);
  316. pcNode->mParent = (aiNode*)&layer;
  317. pcNode->mNumMeshes = num;
  318. if (pcNode->mNumMeshes) {
  319. pcNode->mMeshes = new unsigned int[pcNode->mNumMeshes];
  320. for (unsigned int p = 0; p < pcNode->mNumMeshes;++p)
  321. pcNode->mMeshes[p] = p + meshStart;
  322. }
  323. }
  324. }
  325. if (apcNodes.empty() || apcMeshes.empty())
  326. throw new ImportErrorException("LWO: No meshes loaded");
  327. // The RemoveRedundantMaterials step will clean this up later
  328. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials = (unsigned int)mSurfaces->size()];
  329. for (unsigned int mat = 0; mat < pScene->mNumMaterials;++mat) {
  330. MaterialHelper* pcMat = new MaterialHelper();
  331. pScene->mMaterials[mat] = pcMat;
  332. ConvertMaterial((*mSurfaces)[mat],pcMat);
  333. }
  334. // copy the meshes to the output structure
  335. pScene->mMeshes = new aiMesh*[ pScene->mNumMeshes = (unsigned int)apcMeshes.size() ];
  336. ::memcpy(pScene->mMeshes,&apcMeshes[0],pScene->mNumMeshes*sizeof(void*));
  337. // generate the final node graph
  338. GenerateNodeGraph(apcNodes);
  339. }
  340. // ------------------------------------------------------------------------------------------------
  341. void LWOImporter::ComputeNormals(aiMesh* mesh, const std::vector<unsigned int>& smoothingGroups,
  342. const LWO::Surface& surface)
  343. {
  344. // Allocate output storage
  345. mesh->mNormals = new aiVector3D[mesh->mNumVertices];
  346. // First generate per-face normals
  347. aiVector3D* out;
  348. std::vector<aiVector3D> faceNormals;
  349. // ... in some cases that's already enough
  350. if (!surface.mMaximumSmoothAngle)
  351. out = mesh->mNormals;
  352. else {
  353. faceNormals.resize(mesh->mNumVertices);
  354. out = &faceNormals[0];
  355. }
  356. aiFace* begin = mesh->mFaces, *const end = mesh->mFaces+mesh->mNumFaces;
  357. for (; begin != end; ++begin) {
  358. aiFace& face = *begin;
  359. // LWO doc: "the normal is defined as the cross product of the first and last edges"
  360. aiVector3D* pV1 = mesh->mVertices + face.mIndices[0];
  361. aiVector3D* pV2 = mesh->mVertices + face.mIndices[1];
  362. aiVector3D* pV3 = mesh->mVertices + face.mIndices[face.mNumIndices-1];
  363. aiVector3D vNor = ((*pV2 - *pV1) ^(*pV3 - *pV1)).Normalize();
  364. for (unsigned int i = 0; i < face.mNumIndices;++i)
  365. out[face.mIndices[i]] = vNor;
  366. }
  367. if (!surface.mMaximumSmoothAngle)return;
  368. const float posEpsilon = ComputePositionEpsilon(mesh);
  369. // Now generate the spatial sort tree
  370. SGSpatialSort sSort;
  371. std::vector<unsigned int>::const_iterator it = smoothingGroups.begin();
  372. for( begin = mesh->mFaces; begin != end; ++begin, ++it)
  373. {
  374. aiFace& face = *begin;
  375. for (unsigned int i = 0; i < face.mNumIndices;++i)
  376. {
  377. register unsigned int tt = face.mIndices[i];
  378. sSort.Add(mesh->mVertices[tt],tt,*it);
  379. }
  380. }
  381. // Sort everything - this takes O(nlogn) time
  382. sSort.Prepare();
  383. std::vector<unsigned int> poResult;
  384. poResult.reserve(20);
  385. // Generate vertex normals. We have O(logn) for the binary lookup, which we need
  386. // for n elements, thus the EXPECTED complexity is O(nlogn)
  387. if (surface.mMaximumSmoothAngle < 3.f && !configSpeedFlag) {
  388. const float fLimit = cos(surface.mMaximumSmoothAngle);
  389. for( begin = mesh->mFaces, it = smoothingGroups.begin(); begin != end; ++begin, ++it) {
  390. const aiFace& face = *begin;
  391. unsigned int* beginIdx = face.mIndices, *const endIdx = face.mIndices+face.mNumIndices;
  392. for (; beginIdx != endIdx; ++beginIdx)
  393. {
  394. register unsigned int idx = *beginIdx;
  395. sSort.FindPositions(mesh->mVertices[idx],*it,posEpsilon,poResult,true);
  396. std::vector<unsigned int>::const_iterator a, end = poResult.end();
  397. aiVector3D vNormals;
  398. for (a = poResult.begin();a != end;++a) {
  399. const aiVector3D& v = faceNormals[*a];
  400. if (v * faceNormals[idx] < fLimit)
  401. continue;
  402. vNormals += v;
  403. }
  404. mesh->mNormals[idx] = vNormals.Normalize();
  405. }
  406. }
  407. }
  408. // faster code path in case there is no smooth angle
  409. else {
  410. std::vector<bool> vertexDone(mesh->mNumVertices,false);
  411. for( begin = mesh->mFaces, it = smoothingGroups.begin(); begin != end; ++begin, ++it) {
  412. const aiFace& face = *begin;
  413. unsigned int* beginIdx = face.mIndices, *const endIdx = face.mIndices+face.mNumIndices;
  414. for (; beginIdx != endIdx; ++beginIdx)
  415. {
  416. register unsigned int idx = *beginIdx;
  417. if (vertexDone[idx])
  418. continue;
  419. sSort.FindPositions(mesh->mVertices[idx],*it,posEpsilon,poResult,true);
  420. std::vector<unsigned int>::const_iterator a, end = poResult.end();
  421. aiVector3D vNormals;
  422. for (a = poResult.begin();a != end;++a) {
  423. const aiVector3D& v = faceNormals[*a];
  424. vNormals += v;
  425. }
  426. vNormals.Normalize();
  427. for (a = poResult.begin();a != end;++a) {
  428. mesh->mNormals[*a] = vNormals;
  429. vertexDone[*a] = true;
  430. }
  431. }
  432. }
  433. }
  434. }
  435. // ------------------------------------------------------------------------------------------------
  436. void LWOImporter::AddChildren(aiNode* node, uint16_t parent, std::vector<aiNode*>& apcNodes)
  437. {
  438. for (std::vector<aiNode*>::iterator it = apcNodes.begin(); it != apcNodes.end(); ++it) {
  439. if (*it) {
  440. LWO::Layer* layer = (LWO::Layer*)(*it)->mParent;
  441. if (layer->mParent == parent && layer->mIndex != parent)
  442. ++node->mNumChildren;
  443. }
  444. }
  445. if (node->mNumChildren) {
  446. unsigned int p = 0;
  447. node->mChildren = new aiNode* [ node->mNumChildren ];
  448. for (std::vector<aiNode*>::iterator it = apcNodes.begin(); it != apcNodes.end(); ++it) {
  449. if (*it) {
  450. LWO::Layer* layer = (LWO::Layer*)(*it)->mParent;
  451. if (layer->mParent == parent && layer->mIndex != parent) {
  452. aiNode* nd = node->mChildren[p++] = *it;
  453. nd->mParent = node;
  454. // fixme: ignore pivot points for the moment
  455. //nd->mTransformation.a4 = layer->mPivot.x;
  456. //nd->mTransformation.b4 = layer->mPivot.y;
  457. //nd->mTransformation.c4 = layer->mPivot.z;
  458. // recursively add more children
  459. (*it) = NULL;
  460. AddChildren(nd,layer->mIndex,apcNodes);
  461. }
  462. }
  463. }
  464. }
  465. }
  466. // ------------------------------------------------------------------------------------------------
  467. void LWOImporter::GenerateNodeGraph(std::vector<aiNode*>& apcNodes)
  468. {
  469. // now generate the final nodegraph - generate a root node and attach children
  470. aiNode* root = pScene->mRootNode = new aiNode();
  471. root->mName.Set("<LWORoot>");
  472. AddChildren(root,0,apcNodes);
  473. // check whether we added all layers with meshes assigned to the output graph.
  474. // if not, add them to the root node
  475. unsigned int extra = 0;
  476. for (std::vector<aiNode*>::iterator it = apcNodes.begin(); it != apcNodes.end(); ++it) {
  477. if ((*it) && (*it)->mNumMeshes)
  478. ++extra;
  479. }
  480. if (extra) {
  481. const unsigned int newSize = extra + pScene->mRootNode->mNumChildren;
  482. aiNode** const apcNewNodes = new aiNode*[newSize];
  483. if((extra = root->mNumChildren))
  484. ::memcpy(apcNewNodes,root->mChildren,extra*sizeof(void*));
  485. aiNode** cc = apcNewNodes+extra;
  486. for (std::vector<aiNode*>::iterator it = apcNodes.begin(); it != apcNodes.end(); ++it) {
  487. if ((*it) && (*it)->mNumMeshes) {
  488. aiNode* nd = *cc++ = *it;
  489. nd->mParent = pScene->mRootNode;
  490. // recursively add more children
  491. (*it) = NULL;
  492. AddChildren(nd,((LWO::Layer*)nd->mParent)->mIndex,apcNodes);
  493. }
  494. }
  495. delete[] root->mChildren;
  496. root->mChildren = apcNewNodes;
  497. root->mNumChildren = newSize;
  498. }
  499. if (!pScene->mRootNode->mNumChildren)
  500. throw new ImportErrorException("LWO: Unable to build a valid node graph");
  501. // Remove a single root node with no meshes assigned to it ...
  502. if (1 == pScene->mRootNode->mNumChildren) {
  503. aiNode* pc = pScene->mRootNode->mChildren[0];
  504. pc->mParent = pScene->mRootNode->mChildren[0] = NULL;
  505. delete pScene->mRootNode;
  506. pScene->mRootNode = pc;
  507. }
  508. // convert the whole stuff to RH with CCW winding
  509. MakeLeftHandedProcess maker;
  510. maker.Execute(pScene);
  511. FlipWindingOrderProcess flipper;
  512. flipper.Execute(pScene);
  513. }
  514. // ------------------------------------------------------------------------------------------------
  515. void LWOImporter::ResolveTags()
  516. {
  517. // --- this function is used for both LWO2 and LWOB
  518. mMapping->resize(mTags->size(),0xffffffff);
  519. for (unsigned int a = 0; a < mTags->size();++a)
  520. {
  521. const std::string& c = (*mTags)[a];
  522. for (unsigned int i = 0; i < mSurfaces->size();++i)
  523. {
  524. const std::string& d = (*mSurfaces)[i].mName;
  525. if (!ASSIMP_stricmp(c,d))
  526. {
  527. (*mMapping)[a] = i;
  528. break;
  529. }
  530. }
  531. }
  532. }
  533. // ------------------------------------------------------------------------------------------------
  534. void LWOImporter::ResolveClips()
  535. {
  536. for( unsigned int i = 0; i < mClips.size();++i)
  537. {
  538. Clip& clip = mClips[i];
  539. if (Clip::REF == clip.type)
  540. {
  541. if (clip.clipRef >= mClips.size())
  542. {
  543. DefaultLogger::get()->error("LWO2: Clip referrer index is out of range");
  544. clip.clipRef = 0;
  545. }
  546. Clip& dest = mClips[clip.clipRef];
  547. if (Clip::REF == dest.type)
  548. {
  549. DefaultLogger::get()->error("LWO2: Clip references another clip reference");
  550. clip.type = Clip::UNSUPPORTED;
  551. }
  552. else
  553. {
  554. clip.path = dest.path;
  555. clip.type = dest.type;
  556. }
  557. }
  558. }
  559. }
  560. // ------------------------------------------------------------------------------------------------
  561. void LWOImporter::AdjustTexturePath(std::string& out)
  562. {
  563. // --- this function is used for both LWO2 and LWOB
  564. if (!mIsLWO2 && ::strstr(out.c_str(), "(sequence)"))
  565. {
  566. // remove the (sequence) and append 000
  567. DefaultLogger::get()->info("LWOB: Sequence of animated texture found. It will be ignored");
  568. out = out.substr(0,out.length()-10) + "000";
  569. }
  570. // format: drive:path/file - we need to insert a slash after the drive
  571. std::string::size_type n = out.find_first_of(':');
  572. if (std::string::npos != n)
  573. {
  574. out.insert(n+1,"/");
  575. }
  576. }
  577. // ------------------------------------------------------------------------------------------------
  578. void LWOImporter::LoadLWOTags(unsigned int size)
  579. {
  580. // --- this function is used for both LWO2 and LWOB
  581. const char* szCur = (const char*)mFileBuffer, *szLast = szCur;
  582. const char* const szEnd = szLast+size;
  583. while (szCur < szEnd)
  584. {
  585. if (!(*szCur))
  586. {
  587. const size_t len = (size_t)(szCur-szLast);
  588. // FIX: skip empty-sized tags
  589. if (len)
  590. mTags->push_back(std::string(szLast,len));
  591. szCur += (len&0x1 ? 1 : 2);
  592. szLast = szCur;
  593. }
  594. szCur++;
  595. }
  596. }
  597. // ------------------------------------------------------------------------------------------------
  598. void LWOImporter::LoadLWOPoints(unsigned int length)
  599. {
  600. // --- this function is used for both LWO2 and LWOB but for
  601. // LWO2 we need to allocate 25% more storage - it could be we'll
  602. // need to duplicate some points later.
  603. register unsigned int regularSize = (unsigned int)mCurLayer->mTempPoints.size() + length / 12;
  604. if (mIsLWO2)
  605. {
  606. mCurLayer->mTempPoints.reserve ( regularSize + (regularSize>>2u) );
  607. mCurLayer->mTempPoints.resize ( regularSize );
  608. // initialize all point referrers with the default values
  609. mCurLayer->mPointReferrers.reserve ( regularSize + (regularSize>>2u) );
  610. mCurLayer->mPointReferrers.resize ( regularSize, 0xffffffff );
  611. }
  612. else mCurLayer->mTempPoints.resize( regularSize );
  613. // perform endianess conversions
  614. #ifndef AI_BUILD_BIG_ENDIAN
  615. for (unsigned int i = 0; i < length>>2;++i)
  616. ByteSwap::Swap4( mFileBuffer + (i << 2));
  617. #endif
  618. ::memcpy(&mCurLayer->mTempPoints[0],mFileBuffer,length);
  619. }
  620. // ------------------------------------------------------------------------------------------------
  621. void LWOImporter::LoadLWO2Polygons(unsigned int length)
  622. {
  623. LE_NCONST uint16_t* const end = (LE_NCONST uint16_t*)(mFileBuffer+length);
  624. const uint32_t type = GetU4();
  625. // Determine the type of the polygons
  626. switch (type)
  627. {
  628. // read unsupported stuff too (although we wont process it)
  629. case AI_LWO_BONE:
  630. DefaultLogger::get()->warn("LWO2: Encountered unsupported primitive chunk (BONE)");
  631. break;
  632. case AI_LWO_MBAL:
  633. DefaultLogger::get()->warn("LWO2: Encountered unsupported primitive chunk (METABALL)");
  634. break;
  635. case AI_LWO_CURV:
  636. DefaultLogger::get()->warn("LWO2: Encountered unsupported primitive chunk (SPLINE)");;
  637. break;
  638. // These are ok with no restrictions
  639. case AI_LWO_PTCH:
  640. case AI_LWO_FACE:
  641. break;
  642. default:
  643. // hm!? wtf is this? ok ...
  644. DefaultLogger::get()->error("LWO2: Encountered unknown polygon type");
  645. break;
  646. }
  647. // first find out how many faces and vertices we'll finally need
  648. uint16_t* cursor= (uint16_t*)mFileBuffer;
  649. unsigned int iNumFaces = 0,iNumVertices = 0;
  650. CountVertsAndFacesLWO2(iNumVertices,iNumFaces,cursor,end);
  651. // allocate the output array and copy face indices
  652. if (iNumFaces) {
  653. cursor = (uint16_t*)mFileBuffer;
  654. mCurLayer->mFaces.resize(iNumFaces,LWO::Face(type));
  655. FaceList::iterator it = mCurLayer->mFaces.begin();
  656. CopyFaceIndicesLWO2(it,cursor,end);
  657. }
  658. }
  659. // ------------------------------------------------------------------------------------------------
  660. void LWOImporter::CountVertsAndFacesLWO2(unsigned int& verts, unsigned int& faces,
  661. uint16_t*& cursor, const uint16_t* const end, unsigned int max)
  662. {
  663. while (cursor < end && max--)
  664. {
  665. AI_LSWAP2P(cursor);
  666. uint16_t numIndices = *cursor++;
  667. numIndices &= 0x03FF;
  668. verts += numIndices;++faces;
  669. for(uint16_t i = 0; i < numIndices; i++)
  670. ReadVSizedIntLWO2((uint8_t*&)cursor);
  671. }
  672. }
  673. // ------------------------------------------------------------------------------------------------
  674. void LWOImporter::CopyFaceIndicesLWO2(FaceList::iterator& it,
  675. uint16_t*& cursor,
  676. const uint16_t* const end)
  677. {
  678. while (cursor < end)
  679. {
  680. LWO::Face& face = *it;++it;
  681. if((face.mNumIndices = (*cursor++) & 0x03FF)) // swapping has already been done
  682. {
  683. face.mIndices = new unsigned int[face.mNumIndices];
  684. for(unsigned int i = 0; i < face.mNumIndices; i++)
  685. {
  686. face.mIndices[i] = ReadVSizedIntLWO2((uint8_t*&)cursor) + mCurLayer->mPointIDXOfs;
  687. if(face.mIndices[i] > mCurLayer->mTempPoints.size())
  688. {
  689. DefaultLogger::get()->warn("LWO2: face index is out of range");
  690. face.mIndices[i] = (unsigned int)mCurLayer->mTempPoints.size()-1;
  691. }
  692. }
  693. }
  694. else throw new ImportErrorException("LWO2: face has 0 indices");
  695. }
  696. }
  697. // ------------------------------------------------------------------------------------------------
  698. void LWOImporter::LoadLWO2PolygonTags(unsigned int length)
  699. {
  700. LE_NCONST uint8_t* const end = mFileBuffer+length;
  701. AI_LWO_VALIDATE_CHUNK_LENGTH(length,PTAG,4);
  702. uint32_t type = GetU4();
  703. if (type != AI_LWO_SURF && type != AI_LWO_SMGP)
  704. return;
  705. while (mFileBuffer < end)
  706. {
  707. unsigned int i = ReadVSizedIntLWO2(mFileBuffer) + mCurLayer->mFaceIDXOfs;
  708. unsigned int j = GetU2();
  709. if (i >= mCurLayer->mFaces.size())
  710. {
  711. DefaultLogger::get()->warn("LWO2: face index in PTAG is out of range");
  712. continue;
  713. }
  714. switch (type)
  715. {
  716. case AI_LWO_SURF:
  717. mCurLayer->mFaces[i].surfaceIndex = j;
  718. break;
  719. case AI_LWO_SMGP:
  720. mCurLayer->mFaces[i].smoothGroup = j;
  721. break;
  722. };
  723. }
  724. }
  725. // ------------------------------------------------------------------------------------------------
  726. template <class T>
  727. VMapEntry* FindEntry(std::vector< T >& list,const std::string& name, bool perPoly)
  728. {
  729. for (typename std::vector< T >::iterator it = list.begin(), end = list.end();it != end; ++it) {
  730. if ((*it).name == name)
  731. {
  732. if (!perPoly)
  733. {
  734. DefaultLogger::get()->warn("LWO2: Found two VMAP sections with equal names");
  735. }
  736. return &(*it);
  737. }
  738. }
  739. list.push_back( T() );
  740. VMapEntry* p = &list.back();
  741. p->name = name;
  742. return p;
  743. }
  744. // ------------------------------------------------------------------------------------------------
  745. template <class T>
  746. inline void CreateNewEntry(T& chan, unsigned int srcIdx)
  747. {
  748. if (!chan.name.length())return;
  749. chan.abAssigned[srcIdx] = true;
  750. chan.abAssigned.resize(chan.abAssigned.size()+1,false);
  751. for (unsigned int a = 0; a < chan.dims;++a)
  752. chan.rawData.push_back(chan.rawData[srcIdx*chan.dims+a]);
  753. }
  754. // ------------------------------------------------------------------------------------------------
  755. template <class T>
  756. inline void CreateNewEntry(std::vector< T >& list, unsigned int srcIdx)
  757. {
  758. for (typename std::vector< T >::iterator it = list.begin(), end = list.end();it != end;++it) {
  759. CreateNewEntry( *it, srcIdx );
  760. }
  761. }
  762. // ------------------------------------------------------------------------------------------------
  763. inline void LWOImporter::DoRecursiveVMAPAssignment(VMapEntry* base, unsigned int numRead,
  764. unsigned int idx, float* data)
  765. {
  766. ai_assert(NULL != data);
  767. LWO::ReferrerList& refList = mCurLayer->mPointReferrers;
  768. unsigned int i;
  769. base->abAssigned[idx] = true;
  770. for (i = 0; i < numRead;++i)
  771. base->rawData[idx*base->dims+i]= data[i];
  772. if (0xffffffff != (i = refList[idx]))
  773. DoRecursiveVMAPAssignment(base,numRead,i,data);
  774. }
  775. // ------------------------------------------------------------------------------------------------
  776. inline void AddToSingleLinkedList(ReferrerList& refList, unsigned int srcIdx, unsigned int destIdx)
  777. {
  778. if(0xffffffff == refList[srcIdx]) {
  779. refList[srcIdx] = destIdx;
  780. return;
  781. }
  782. AddToSingleLinkedList(refList,refList[srcIdx],destIdx);
  783. }
  784. // ------------------------------------------------------------------------------------------------
  785. // Load LWO2 vertex map
  786. void LWOImporter::LoadLWO2VertexMap(unsigned int length, bool perPoly)
  787. {
  788. LE_NCONST uint8_t* const end = mFileBuffer+length;
  789. AI_LWO_VALIDATE_CHUNK_LENGTH(length,VMAP,6);
  790. unsigned int type = GetU4();
  791. unsigned int dims = GetU2();
  792. VMapEntry* base;
  793. // read the name of the vertex map
  794. std::string name;
  795. GetS0(name,length);
  796. switch (type)
  797. {
  798. case AI_LWO_TXUV:
  799. if (dims != 2) {
  800. DefaultLogger::get()->warn("LWO2: Found UV channel with != 2 components");
  801. return;
  802. }
  803. base = FindEntry(mCurLayer->mUVChannels,name,perPoly);
  804. break;
  805. case AI_LWO_WGHT:
  806. if (dims != 1) {
  807. DefaultLogger::get()->warn("LWO2: found vertex weight map with != 1 components");
  808. return;
  809. }
  810. base = FindEntry(mCurLayer->mWeightChannels,name,perPoly);
  811. break;
  812. case AI_LWO_RGB:
  813. case AI_LWO_RGBA:
  814. if (dims != 3 && dims != 4) {
  815. DefaultLogger::get()->warn("LWO2: found vertex color map with != 3&4 components");
  816. return;
  817. }
  818. base = FindEntry(mCurLayer->mVColorChannels,name,perPoly);
  819. break;
  820. case AI_LWO_MODO_NORM:
  821. /* This is a non-standard extension chunk used by Luxology's MODO.
  822. * It stores per-vertex normals. This VMAP exists just once, has
  823. * 3 dimensions and is btw extremely beautiful.
  824. */
  825. if (name != "vert_normals" || dims != 3 || mCurLayer->mNormals.name.length())
  826. return;
  827. DefaultLogger::get()->info("Non-standard extension: MODO VMAP.NORM.vert_normals");
  828. mCurLayer->mNormals.name = name;
  829. base = & mCurLayer->mNormals;
  830. break;
  831. default:
  832. return;
  833. };
  834. base->Allocate((unsigned int)mCurLayer->mTempPoints.size());
  835. // now read all entries in the map
  836. type = std::min(dims,base->dims);
  837. const unsigned int diff = (dims - type)<<2;
  838. LWO::FaceList& list = mCurLayer->mFaces;
  839. LWO::PointList& pointList = mCurLayer->mTempPoints;
  840. LWO::ReferrerList& refList = mCurLayer->mPointReferrers;
  841. float temp[4];
  842. const unsigned int numPoints = (unsigned int)pointList.size();
  843. const unsigned int numFaces = (unsigned int)list.size();
  844. while (mFileBuffer < end)
  845. {
  846. unsigned int idx = ReadVSizedIntLWO2(mFileBuffer) + mCurLayer->mPointIDXOfs;
  847. if (idx >= numPoints) {
  848. DefaultLogger::get()->warn("LWO2: vertex index in vmap/vmad is out of range");
  849. mFileBuffer += base->dims*4;continue;
  850. }
  851. if (perPoly) {
  852. unsigned int polyIdx = ReadVSizedIntLWO2(mFileBuffer) + mCurLayer->mFaceIDXOfs;
  853. if (base->abAssigned[idx]) {
  854. // we have already a VMAP entry for this vertex - thus
  855. // we need to duplicate the corresponding polygon.
  856. if (polyIdx >= numFaces) {
  857. DefaultLogger::get()->warn("LWO2: VMAD polygon index is out of range");
  858. mFileBuffer += base->dims*4;
  859. continue;
  860. }
  861. LWO::Face& src = list[polyIdx];
  862. // generate a new unique vertex for the corresponding index - but only
  863. // if we can find the index in the face
  864. for (unsigned int i = 0; i < src.mNumIndices;++i) {
  865. register unsigned int srcIdx = src.mIndices[i];
  866. if (idx != srcIdx)
  867. continue;
  868. refList.resize(refList.size()+1, 0xffffffff);
  869. idx = (unsigned int)pointList.size();
  870. src.mIndices[i] = (unsigned int)pointList.size();
  871. // store the index of the new vertex in the old vertex
  872. // so we get a single linked list we can traverse in
  873. // only one direction
  874. AddToSingleLinkedList(refList,srcIdx,src.mIndices[i]);
  875. pointList.push_back(pointList[srcIdx]);
  876. CreateNewEntry(mCurLayer->mVColorChannels, srcIdx );
  877. CreateNewEntry(mCurLayer->mUVChannels, srcIdx );
  878. CreateNewEntry(mCurLayer->mWeightChannels, srcIdx );
  879. CreateNewEntry(mCurLayer->mNormals, srcIdx );
  880. }
  881. }
  882. }
  883. for (unsigned int l = 0; l < type;++l)
  884. temp[l] = GetF4();
  885. DoRecursiveVMAPAssignment(base,type,idx, temp);
  886. mFileBuffer += diff;
  887. }
  888. }
  889. // ------------------------------------------------------------------------------------------------
  890. // Load LWO2 clip
  891. void LWOImporter::LoadLWO2Clip(unsigned int length)
  892. {
  893. AI_LWO_VALIDATE_CHUNK_LENGTH(length,CLIP,10);
  894. mClips.push_back(LWO::Clip());
  895. LWO::Clip& clip = mClips.back();
  896. // first - get the index of the clip
  897. clip.idx = GetU4();
  898. IFF::SubChunkHeader* const head = IFF::LoadSubChunk(mFileBuffer);
  899. switch (head->type)
  900. {
  901. case AI_LWO_STIL:
  902. AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,STIL,1);
  903. // "Normal" texture
  904. GetS0(clip.path,head->length);
  905. clip.type = Clip::STILL;
  906. break;
  907. case AI_LWO_ISEQ:
  908. AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,ISEQ,16);
  909. // Image sequence. We'll later take the first.
  910. {
  911. uint8_t digits = GetU1(); mFileBuffer++;
  912. int16_t offset = GetU2(); mFileBuffer+=4;
  913. int16_t start = GetU2(); mFileBuffer+=4;
  914. std::string s;std::stringstream ss;
  915. GetS0(s,head->length);
  916. head->length -= (unsigned int)s.length()+1;
  917. ss << s;
  918. ss << std::setw(digits) << offset + start;
  919. GetS0(s,head->length);
  920. ss << s;
  921. clip.path = ss.str();
  922. clip.type = Clip::SEQ;
  923. }
  924. break;
  925. case AI_LWO_STCC:
  926. DefaultLogger::get()->warn("LWO2: Color shifted images are not supported");
  927. break;
  928. case AI_LWO_ANIM:
  929. DefaultLogger::get()->warn("LWO2: Animated textures are not supported");
  930. break;
  931. case AI_LWO_XREF:
  932. AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,XREF,4);
  933. // Just a cross-reference to another CLIp
  934. clip.type = Clip::REF;
  935. clip.clipRef = GetU4();
  936. break;
  937. case AI_LWO_NEGA:
  938. AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,NEGA,2);
  939. clip.negate = (0 != GetU2());
  940. break;
  941. default:
  942. DefaultLogger::get()->warn("LWO2: Encountered unknown CLIP subchunk");
  943. }
  944. }
  945. // ------------------------------------------------------------------------------------------------
  946. // Load envelope description
  947. void LWOImporter::LoadLWO2Envelope(unsigned int length)
  948. {
  949. LE_NCONST uint8_t* const end = mFileBuffer + length;
  950. AI_LWO_VALIDATE_CHUNK_LENGTH(length,ENVL,4);
  951. mEnvelopes.push_back(LWO::Envelope());
  952. LWO::Envelope& envelope = mEnvelopes.back();
  953. // Get the index of the envelope
  954. envelope.index = ReadVSizedIntLWO2(mFileBuffer);
  955. // ... and read all subchunks
  956. while (true)
  957. {
  958. if (mFileBuffer + 6 >= end)break;
  959. LE_NCONST IFF::SubChunkHeader* const head = IFF::LoadSubChunk(mFileBuffer);
  960. if (mFileBuffer + head->length > end)
  961. throw new ImportErrorException("LWO2: Invalid envelope chunk length");
  962. uint8_t* const next = mFileBuffer+head->length;
  963. switch (head->type)
  964. {
  965. // Type & representation of the envelope
  966. case AI_LWO_TYPE:
  967. AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,TYPE,2);
  968. mFileBuffer++; // skip user format
  969. // Determine type of envelope
  970. envelope.type = (LWO::EnvelopeType)*mFileBuffer;
  971. ++mFileBuffer;
  972. break;
  973. // precondition
  974. case AI_LWO_PRE:
  975. AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,PRE,2);
  976. envelope.pre = (LWO::PrePostBehaviour)GetU2();
  977. break;
  978. // postcondition
  979. case AI_LWO_POST:
  980. AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,POST,2);
  981. envelope.post = (LWO::PrePostBehaviour)GetU2();
  982. break;
  983. // keyframe
  984. case AI_LWO_KEY:
  985. {
  986. AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,KEY,8);
  987. envelope.keys.push_back(LWO::Key());
  988. LWO::Key& key = envelope.keys.back();
  989. key.time = GetF4();
  990. key.value = GetF4();
  991. break;
  992. }
  993. // interval interpolation
  994. case AI_LWO_SPAN:
  995. {
  996. AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,SPAN,4);
  997. if (envelope.keys.size()<2)
  998. DefaultLogger::get()->warn("LWO2: Unexpected SPAN chunk");
  999. else {
  1000. LWO::Key& key = envelope.keys.back();
  1001. switch (GetU4())
  1002. {
  1003. case AI_LWO_STEP:
  1004. key.inter = LWO::IT_STEP;break;
  1005. case AI_LWO_LINE:
  1006. key.inter = LWO::IT_LINE;break;
  1007. case AI_LWO_TCB:
  1008. key.inter = LWO::IT_TCB;break;
  1009. case AI_LWO_HERM:
  1010. key.inter = LWO::IT_HERM;break;
  1011. case AI_LWO_BEZI:
  1012. key.inter = LWO::IT_BEZI;break;
  1013. case AI_LWO_BEZ2:
  1014. key.inter = LWO::IT_BEZ2;break;
  1015. default:
  1016. DefaultLogger::get()->warn("LWO2: Unknown interval interpolation mode");
  1017. };
  1018. // todo ... read params
  1019. }
  1020. break;
  1021. }
  1022. default:
  1023. DefaultLogger::get()->warn("LWO2: Encountered unknown ENVL subchunk");
  1024. }
  1025. // regardless how much we did actually read, go to the next chunk
  1026. mFileBuffer = next;
  1027. }
  1028. }
  1029. // ------------------------------------------------------------------------------------------------
  1030. // Load file - master function
  1031. void LWOImporter::LoadLWO2File()
  1032. {
  1033. bool skip = false;
  1034. LE_NCONST uint8_t* const end = mFileBuffer + fileSize;
  1035. while (true)
  1036. {
  1037. if (mFileBuffer + sizeof(IFF::ChunkHeader) > end)break;
  1038. IFF::ChunkHeader* const head = IFF::LoadChunk(mFileBuffer);
  1039. if (mFileBuffer + head->length > end)
  1040. {
  1041. throw new ImportErrorException("LWO2: Chunk length points behind the file");
  1042. break;
  1043. }
  1044. uint8_t* const next = mFileBuffer+head->length;
  1045. unsigned int iUnnamed = 0;
  1046. switch (head->type)
  1047. {
  1048. // new layer
  1049. case AI_LWO_LAYR:
  1050. {
  1051. // add a new layer to the list ....
  1052. mLayers->push_back ( LWO::Layer() );
  1053. LWO::Layer& layer = mLayers->back();
  1054. mCurLayer = &layer;
  1055. AI_LWO_VALIDATE_CHUNK_LENGTH(head->length,LAYR,16);
  1056. // Continue loading this layer or ignore it? Check the layer index property
  1057. // NOTE: The first layer is the default layer, so the layer index is one-based now
  1058. if (0xffffffff != configLayerIndex && configLayerIndex != mLayers->size()-1) {
  1059. skip = true;
  1060. }
  1061. else skip = false;
  1062. // layer index. that's just for internal parenting, from the scope of a LWS file
  1063. // all layers are numbered in the oder in which they appear in the file
  1064. layer.mIndex = GetU2();
  1065. // pivot point
  1066. mFileBuffer += 2; /* unknown */
  1067. mCurLayer->mPivot.x = GetF4();
  1068. mCurLayer->mPivot.y = GetF4();
  1069. mCurLayer->mPivot.z = GetF4();
  1070. GetS0(layer.mName,head->length-16);
  1071. // if the name is empty, generate a default name
  1072. if (layer.mName.empty()) {
  1073. char buffer[128]; // should be sufficiently large
  1074. ::sprintf(buffer,"Layer_%i", iUnnamed++);
  1075. layer.mName = buffer;
  1076. }
  1077. // load this layer or ignore it? Check the layer name property
  1078. if (configLayerName.length() && configLayerName != layer.mName) {
  1079. skip = true;
  1080. }
  1081. else hasNamedLayer = true;
  1082. // optional: parent of this layer
  1083. if (mFileBuffer + 2 <= next)
  1084. layer.mParent = GetU2();
  1085. break;
  1086. }
  1087. // vertex list
  1088. case AI_LWO_PNTS:
  1089. {
  1090. if (skip)
  1091. break;
  1092. unsigned int old = (unsigned int)mCurLayer->mTempPoints.size();
  1093. LoadLWOPoints(head->length);
  1094. mCurLayer->mPointIDXOfs = old;
  1095. break;
  1096. }
  1097. // vertex tags
  1098. case AI_LWO_VMAD:
  1099. if (mCurLayer->mFaces.empty())
  1100. {
  1101. DefaultLogger::get()->warn("LWO2: Unexpected VMAD chunk");
  1102. break;
  1103. }
  1104. // --- intentionally no break here
  1105. case AI_LWO_VMAP:
  1106. {
  1107. if (skip)
  1108. break;
  1109. if (mCurLayer->mTempPoints.empty())
  1110. DefaultLogger::get()->warn("LWO2: Unexpected VMAP chunk");
  1111. else LoadLWO2VertexMap(head->length,head->type == AI_LWO_VMAD);
  1112. break;
  1113. }
  1114. // face list
  1115. case AI_LWO_POLS:
  1116. {
  1117. if (skip)
  1118. break;
  1119. unsigned int old = (unsigned int)mCurLayer->mFaces.size();
  1120. LoadLWO2Polygons(head->length);
  1121. mCurLayer->mFaceIDXOfs = old;
  1122. break;
  1123. }
  1124. // polygon tags
  1125. case AI_LWO_PTAG:
  1126. {
  1127. if (skip)
  1128. break;
  1129. if (mCurLayer->mFaces.empty())
  1130. DefaultLogger::get()->warn("LWO2: Unexpected PTAG");
  1131. else LoadLWO2PolygonTags(head->length);
  1132. break;
  1133. }
  1134. // list of tags
  1135. case AI_LWO_TAGS:
  1136. {
  1137. if (!mTags->empty())
  1138. DefaultLogger::get()->warn("LWO2: SRFS chunk encountered twice");
  1139. else LoadLWOTags(head->length);
  1140. break;
  1141. }
  1142. // surface chunk
  1143. case AI_LWO_SURF:
  1144. {
  1145. LoadLWO2Surface(head->length);
  1146. break;
  1147. }
  1148. // clip chunk
  1149. case AI_LWO_CLIP:
  1150. {
  1151. LoadLWO2Clip(head->length);
  1152. break;
  1153. }
  1154. // envelope chunk
  1155. case AI_LWO_ENVL:
  1156. {
  1157. LoadLWO2Envelope(head->length);
  1158. break;
  1159. }
  1160. }
  1161. mFileBuffer = next;
  1162. }
  1163. }
  1164. #endif // !! ASSIMP_BUILD_NO_LWO_IMPORTER