LWOLoader.cpp 45 KB

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