LWOLoader.cpp 44 KB

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