LWOLoader.cpp 53 KB

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