LWOLoader.cpp 60 KB

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