LWOLoader.cpp 44 KB

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