LWOLoader.cpp 53 KB

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