LWOLoader.cpp 52 KB

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