LWOLoader.cpp 53 KB

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