ASELoader.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  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 Implementation of the ASE importer class */
  35. #include "ASELoader.h"
  36. #include "3DSSpatialSort.h"
  37. #include "MaterialSystem.h"
  38. #include "../include/IOStream.h"
  39. #include "../include/IOSystem.h"
  40. #include "../include/aiMesh.h"
  41. #include "../include/aiScene.h"
  42. #include "../include/aiAssert.h"
  43. #include "../include/DefaultLogger.h"
  44. #include <boost/scoped_ptr.hpp>
  45. using namespace Assimp;
  46. using namespace Assimp::ASE;
  47. #define LOGOUT_WARN(x) DefaultLogger::get()->warn(x);
  48. // ------------------------------------------------------------------------------------------------
  49. // Constructor to be privately used by Importer
  50. ASEImporter::ASEImporter()
  51. {
  52. }
  53. // ------------------------------------------------------------------------------------------------
  54. // Destructor, private as well
  55. ASEImporter::~ASEImporter()
  56. {
  57. }
  58. // ------------------------------------------------------------------------------------------------
  59. // Returns whether the class can handle the format of the given file.
  60. bool ASEImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler) const
  61. {
  62. // simple check of file extension is enough for the moment
  63. std::string::size_type pos = pFile.find_last_of('.');
  64. // no file extension - can't read
  65. if( pos == std::string::npos)
  66. return false;
  67. std::string extension = pFile.substr( pos);
  68. if (extension.length() < 4)return false;
  69. if (extension[0] != '.')return false;
  70. if (extension[1] != 'a' && extension[1] != 'A')return false;
  71. if (extension[2] != 's' && extension[2] != 'S')return false;
  72. // NOTE: Sometimes the extension .ASK is also used
  73. // however, often it only contains static animation skeletons
  74. // without the real animations.
  75. if (extension[3] != 'e' && extension[3] != 'E' &&
  76. extension[3] != 'k' && extension[3] != 'K')return false;
  77. return true;
  78. }
  79. // ------------------------------------------------------------------------------------------------
  80. // Imports the given file into the given scene structure.
  81. void ASEImporter::InternReadFile(
  82. const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  83. {
  84. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile));
  85. // Check whether we can read from the file
  86. if( file.get() == NULL)
  87. {
  88. throw new ImportErrorException( "Failed to open ASE file " + pFile + ".");
  89. }
  90. size_t fileSize = file->FileSize();
  91. std::string::size_type pos = pFile.find_last_of('.');
  92. std::string extension = pFile.substr( pos);
  93. if(extension[3] == 'k' || extension[3] == 'K')
  94. {
  95. this->mIsAsk = true;
  96. }
  97. else this->mIsAsk = false;
  98. // allocate storage and copy the contents of the file to a memory buffer
  99. // (terminate it with zero)
  100. this->mBuffer = new unsigned char[fileSize+1];
  101. file->Read( (void*)mBuffer, 1, fileSize);
  102. this->mBuffer[fileSize] = '\0';
  103. // construct an ASE parser and parse the file
  104. this->mParser = new ASE::Parser((const char*)this->mBuffer);
  105. this->mParser->Parse();
  106. // process all meshes
  107. for (std::vector<ASE::Mesh>::iterator
  108. i = this->mParser->m_vMeshes.begin();
  109. i != this->mParser->m_vMeshes.end();++i)
  110. {
  111. // transform all vertices into worldspace
  112. // world2obj transform is specified in the
  113. // transformation matrix of a scenegraph node
  114. this->TransformVertices(*i);
  115. // now we need to create proper meshes from the import
  116. // we need to split them by materials, build valid vertex/face lists ...
  117. this->BuildUniqueRepresentation(*i);
  118. // need to generate proper vertex normals if necessary
  119. this->GenerateNormals(*i);
  120. // convert all meshes to aiMesh objects
  121. this->ConvertMeshes(*i,pScene);
  122. }
  123. // buil final material indices (remove submaterials and make the final list)
  124. this->BuildMaterialIndices(pScene);
  125. // build the final node graph
  126. this->BuildNodes(pScene);
  127. // delete the ASE parser
  128. delete this->mParser;
  129. this->mParser = NULL;
  130. return;
  131. }
  132. // ------------------------------------------------------------------------------------------------
  133. void ASEImporter::BuildNodes(aiScene* pcScene)
  134. {
  135. ai_assert(NULL != pcScene);
  136. pcScene->mRootNode = new aiNode();
  137. pcScene->mRootNode->mNumMeshes = 0;
  138. pcScene->mRootNode->mMeshes = 0;
  139. ai_assert(4 <= AI_MAX_NUMBER_OF_COLOR_SETS);
  140. std::vector<std::pair<aiMatrix4x4,std::list<unsigned int> > > stack;
  141. stack.reserve(pcScene->mNumMeshes);
  142. for (unsigned int i = 0; i < pcScene->mNumMeshes;++i)
  143. {
  144. // get the transformation matrix of the node
  145. aiMatrix4x4* pmTransform = (aiMatrix4x4*)pcScene->mMeshes[i]->mColors[2];
  146. // search for an identical matrix in our list
  147. for (std::vector<std::pair<aiMatrix4x4,std::list<unsigned int> > >::iterator
  148. a = stack.begin();
  149. a != stack.end();++a)
  150. {
  151. if ((*a).first == *pmTransform)
  152. {
  153. (*a).second.push_back(i);
  154. pmTransform->a1 = std::numeric_limits<float>::quiet_NaN();
  155. break;
  156. }
  157. }
  158. if (is_not_qnan(pmTransform->a1))
  159. {
  160. // add a new entry ...
  161. stack.push_back(std::pair<aiMatrix4x4,std::list<unsigned int> >(
  162. *pmTransform,std::list<unsigned int>()));
  163. stack.back().second.push_back(i);
  164. }
  165. // delete the matrix
  166. delete pmTransform;
  167. pcScene->mMeshes[i]->mColors[2] = NULL;
  168. }
  169. // allocate enough space for the child nodes
  170. pcScene->mRootNode->mNumChildren = stack.size();
  171. pcScene->mRootNode->mChildren = new aiNode*[stack.size()];
  172. // now build all nodes
  173. for (std::vector<std::pair<aiMatrix4x4,std::list<unsigned int> > >::iterator
  174. a = stack.begin();
  175. a != stack.end();++a)
  176. {
  177. aiNode* pcNode = new aiNode();
  178. pcNode->mNumMeshes = (*a).second.size();
  179. pcNode->mMeshes = new unsigned int[pcNode->mNumMeshes];
  180. for (std::list<unsigned int>::const_iterator
  181. i = (*a).second.begin();
  182. i != (*a).second.end();++i)
  183. {
  184. *pcNode->mMeshes++ = *i;
  185. }
  186. pcNode->mMeshes -= pcNode->mNumMeshes;
  187. pcNode->mTransformation = (*a).first;
  188. *pcScene->mRootNode->mChildren++ = pcNode;
  189. }
  190. pcScene->mRootNode->mChildren -= stack.size();
  191. return;
  192. }
  193. // ------------------------------------------------------------------------------------------------
  194. void ASEImporter::TransformVertices(ASE::Mesh& mesh)
  195. {
  196. // the matrix data is stored in column-major format,
  197. // but we need row major
  198. mesh.mTransform.Transpose();
  199. aiMatrix4x4 m = mesh.mTransform;
  200. m.Inverse();
  201. for (std::vector<aiVector3D>::iterator
  202. i = mesh.mPositions.begin();
  203. i != mesh.mPositions.end();++i)
  204. {
  205. (*i) = m * (*i);
  206. }
  207. }
  208. // ------------------------------------------------------------------------------------------------
  209. void ASEImporter::BuildUniqueRepresentation(ASE::Mesh& mesh)
  210. {
  211. // allocate output storage
  212. std::vector<aiVector3D> mPositions;
  213. std::vector<aiVector3D> amTexCoords[AI_MAX_NUMBER_OF_TEXTURECOORDS];
  214. std::vector<aiColor4D> mVertexColors;
  215. std::vector<aiVector3D> mNormals;
  216. std::vector<BoneVertex> mBoneVertices;
  217. unsigned int iSize = mesh.mFaces.size() * 3;
  218. mPositions.resize(iSize);
  219. // optional texture coordinates
  220. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS;++i)
  221. {
  222. if (!mesh.amTexCoords[i].empty())
  223. {
  224. amTexCoords[i].resize(iSize);
  225. }
  226. }
  227. // optional vertex colors
  228. if (!mesh.mVertexColors.empty())
  229. {
  230. mVertexColors.resize(iSize);
  231. }
  232. // optional vertex normals (vertex normals can simply be copied)
  233. if (!mesh.mNormals.empty())
  234. {
  235. mNormals.resize(iSize);
  236. }
  237. // bone vertices. There is no need to change the bone list
  238. if (!mesh.mBoneVertices.empty())
  239. {
  240. mBoneVertices.resize(iSize);
  241. }
  242. // iterate through all faces in the mesh
  243. unsigned int iCurrent = 0;
  244. for (std::vector<ASE::Face>::iterator
  245. i = mesh.mFaces.begin();
  246. i != mesh.mFaces.end();++i)
  247. {
  248. for (unsigned int n = 0; n < 3;++n,++iCurrent)
  249. {
  250. mPositions[iCurrent] = mesh.mPositions[(*i).mIndices[n]];
  251. // add texture coordinates
  252. for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS;++c)
  253. {
  254. if (!mesh.amTexCoords[c].empty())
  255. {
  256. amTexCoords[c][iCurrent] = mesh.amTexCoords[c][(*i).amUVIndices[c][n]];
  257. }
  258. }
  259. // add vertex colors
  260. if (!mesh.mVertexColors.empty())
  261. {
  262. mVertexColors[iCurrent] = mesh.mVertexColors[(*i).mColorIndices[n]];
  263. }
  264. // add normal vectors
  265. if (!mesh.mNormals.empty())
  266. {
  267. mNormals[iCurrent] = mesh.mNormals[(*i).mIndices[n]];
  268. }
  269. // handle bone vertices
  270. if ((*i).mIndices[n] < mesh.mBoneVertices.size())
  271. {
  272. // (sometimes this will cause bone verts to be duplicated
  273. // however, I' quite sure Schrompf' JoinVerticesStep
  274. // will fix that again ...)
  275. mBoneVertices[iCurrent] = mesh.mBoneVertices[(*i).mIndices[n]];
  276. }
  277. // assign a new valid index to the face
  278. (*i).mIndices[n] = iCurrent;
  279. }
  280. }
  281. // replace the old arrays
  282. mesh.mNormals = mNormals;
  283. mesh.mPositions = mPositions;
  284. mesh.mVertexColors = mVertexColors;
  285. for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS;++c)
  286. mesh.amTexCoords[c] = amTexCoords[c];
  287. // now need to transform all vertices with the inverse of their
  288. // transformation matrix ...
  289. aiMatrix4x4 mInverse = mesh.mTransform;
  290. mInverse.Inverse();
  291. for (std::vector<aiVector3D>::iterator
  292. i = mesh.mPositions.begin();
  293. i != mesh.mPositions.end();++i)
  294. {
  295. (*i) = mInverse * (*i);
  296. }
  297. return;
  298. }
  299. // ------------------------------------------------------------------------------------------------
  300. void ASEImporter::ConvertMaterial(ASE::Material& mat)
  301. {
  302. // allocate the output material
  303. mat.pcInstance = new MaterialHelper();
  304. // At first add the base ambient color of the
  305. // scene to the material
  306. mat.mAmbient.r += this->mParser->m_clrAmbient.r;
  307. mat.mAmbient.g += this->mParser->m_clrAmbient.g;
  308. mat.mAmbient.b += this->mParser->m_clrAmbient.b;
  309. aiString name;
  310. name.Set( mat.mName);
  311. mat.pcInstance->AddProperty( &name, AI_MATKEY_NAME);
  312. // material colors
  313. mat.pcInstance->AddProperty( &mat.mAmbient, 1, AI_MATKEY_COLOR_AMBIENT);
  314. mat.pcInstance->AddProperty( &mat.mDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  315. mat.pcInstance->AddProperty( &mat.mSpecular, 1, AI_MATKEY_COLOR_SPECULAR);
  316. mat.pcInstance->AddProperty( &mat.mEmissive, 1, AI_MATKEY_COLOR_EMISSIVE);
  317. // shininess
  318. if (0.0f != mat.mSpecularExponent && 0.0f != mat.mShininessStrength)
  319. {
  320. mat.pcInstance->AddProperty( &mat.mSpecularExponent, 1, AI_MATKEY_SHININESS);
  321. mat.pcInstance->AddProperty( &mat.mShininessStrength, 1, AI_MATKEY_SHININESS_STRENGTH);
  322. }
  323. // if there is no shininess, we can disable phong lighting
  324. else if (Dot3DS::Dot3DSFile::Metal == mat.mShading ||
  325. Dot3DS::Dot3DSFile::Phong == mat.mShading)
  326. {
  327. mat.mShading = Dot3DS::Dot3DSFile::Gouraud;
  328. }
  329. // opacity
  330. mat.pcInstance->AddProperty<float>( &mat.mTransparency,1,AI_MATKEY_OPACITY);
  331. // shading mode
  332. aiShadingMode eShading = aiShadingMode_NoShading;
  333. switch (mat.mShading)
  334. {
  335. case Dot3DS::Dot3DSFile::Flat:
  336. eShading = aiShadingMode_Flat; break;
  337. case Dot3DS::Dot3DSFile::Phong :
  338. eShading = aiShadingMode_Phong; break;
  339. // I don't know what "Wire" shading should be,
  340. // assume it is simple lambertian diffuse (L dot N) shading
  341. case Dot3DS::Dot3DSFile::Wire:
  342. case Dot3DS::Dot3DSFile::Gouraud:
  343. eShading = aiShadingMode_Gouraud; break;
  344. case Dot3DS::Dot3DSFile::Metal :
  345. eShading = aiShadingMode_CookTorrance; break;
  346. }
  347. mat.pcInstance->AddProperty<int>( (int*)&eShading,1,AI_MATKEY_SHADING_MODEL);
  348. if (Dot3DS::Dot3DSFile::Wire == mat.mShading)
  349. {
  350. // set the wireframe flag
  351. unsigned int iWire = 1;
  352. mat.pcInstance->AddProperty<int>( (int*)&iWire,1,AI_MATKEY_ENABLE_WIREFRAME);
  353. }
  354. // texture, if there is one
  355. if( mat.sTexDiffuse.mMapName.length() > 0)
  356. {
  357. aiString tex;
  358. tex.Set( mat.sTexDiffuse.mMapName);
  359. mat.pcInstance->AddProperty( &tex, AI_MATKEY_TEXTURE_DIFFUSE(0));
  360. if (is_not_qnan(mat.sTexDiffuse.mTextureBlend))
  361. mat.pcInstance->AddProperty<float>( &mat.sTexDiffuse.mTextureBlend, 1,
  362. AI_MATKEY_TEXBLEND_DIFFUSE(0));
  363. }
  364. if( mat.sTexSpecular.mMapName.length() > 0)
  365. {
  366. aiString tex;
  367. tex.Set( mat.sTexSpecular.mMapName);
  368. mat.pcInstance->AddProperty( &tex, AI_MATKEY_TEXTURE_SPECULAR(0));
  369. if (is_not_qnan(mat.sTexSpecular.mTextureBlend))
  370. mat.pcInstance->AddProperty<float>( &mat.sTexSpecular.mTextureBlend, 1,
  371. AI_MATKEY_TEXBLEND_SPECULAR(0));
  372. }
  373. if( mat.sTexOpacity.mMapName.length() > 0)
  374. {
  375. aiString tex;
  376. tex.Set( mat.sTexOpacity.mMapName);
  377. mat.pcInstance->AddProperty( &tex, AI_MATKEY_TEXTURE_OPACITY(0));
  378. if (is_not_qnan(mat.sTexOpacity.mTextureBlend))
  379. mat.pcInstance->AddProperty<float>( &mat.sTexOpacity.mTextureBlend, 1,
  380. AI_MATKEY_TEXBLEND_OPACITY(0));
  381. }
  382. if( mat.sTexEmissive.mMapName.length() > 0)
  383. {
  384. aiString tex;
  385. tex.Set( mat.sTexEmissive.mMapName);
  386. mat.pcInstance->AddProperty( &tex, AI_MATKEY_TEXTURE_EMISSIVE(0));
  387. if (is_not_qnan(mat.sTexEmissive.mTextureBlend))
  388. mat.pcInstance->AddProperty<float>( &mat.sTexEmissive.mTextureBlend, 1,
  389. AI_MATKEY_TEXBLEND_EMISSIVE(0));
  390. }
  391. if( mat.sTexAmbient.mMapName.length() > 0)
  392. {
  393. aiString tex;
  394. tex.Set( mat.sTexAmbient.mMapName);
  395. mat.pcInstance->AddProperty( &tex, AI_MATKEY_TEXTURE_AMBIENT(0));
  396. if (is_not_qnan(mat.sTexAmbient.mTextureBlend))
  397. mat.pcInstance->AddProperty<float>( &mat.sTexAmbient.mTextureBlend, 1,
  398. AI_MATKEY_TEXBLEND_AMBIENT(0));
  399. }
  400. if( mat.sTexBump.mMapName.length() > 0)
  401. {
  402. aiString tex;
  403. tex.Set( mat.sTexBump.mMapName);
  404. mat.pcInstance->AddProperty( &tex, AI_MATKEY_TEXTURE_HEIGHT(0));
  405. if (is_not_qnan(mat.sTexBump.mTextureBlend))
  406. mat.pcInstance->AddProperty<float>( &mat.sTexBump.mTextureBlend, 1,
  407. AI_MATKEY_TEXBLEND_HEIGHT(0));
  408. }
  409. if( mat.sTexShininess.mMapName.length() > 0)
  410. {
  411. aiString tex;
  412. tex.Set( mat.sTexShininess.mMapName);
  413. mat.pcInstance->AddProperty( &tex, AI_MATKEY_TEXTURE_SHININESS(0));
  414. if (is_not_qnan(mat.sTexShininess.mTextureBlend))
  415. mat.pcInstance->AddProperty<float>( &mat.sTexBump.mTextureBlend, 1,
  416. AI_MATKEY_TEXBLEND_SHININESS(0));
  417. }
  418. // store the name of the material itself, too
  419. if( mat.mName.length() > 0)
  420. {
  421. aiString tex;
  422. tex.Set( mat.mName);
  423. mat.pcInstance->AddProperty( &tex, AI_MATKEY_NAME);
  424. }
  425. return;
  426. }
  427. // ------------------------------------------------------------------------------------------------
  428. void ASEImporter::ConvertMeshes(ASE::Mesh& mesh, aiScene* pcScene)
  429. {
  430. ai_assert(NULL != pcScene);
  431. // validate the material index of the mesh
  432. if (mesh.iMaterialIndex >= this->mParser->m_vMaterials.size())
  433. {
  434. mesh.iMaterialIndex = this->mParser->m_vMaterials.size()-1;
  435. LOGOUT_WARN("Material index is out of range");
  436. }
  437. // List of all output meshes
  438. std::vector<aiMesh*> avOutMeshes;
  439. // if the material the mesh is assigned to is consisting of submeshes
  440. // we'll need to split it ... Quak.
  441. if (!this->mParser->m_vMaterials[mesh.iMaterialIndex].avSubMaterials.empty())
  442. {
  443. std::vector<ASE::Material> vSubMaterials = this->mParser->
  444. m_vMaterials[mesh.iMaterialIndex].avSubMaterials;
  445. std::vector<unsigned int>* aiSplit = new std::vector<unsigned int>[
  446. vSubMaterials.size()];
  447. // build a list of all faces per submaterial
  448. unsigned int iNum = 0;
  449. for (unsigned int i = 0; i < mesh.mFaces.size();++i)
  450. {
  451. // check range
  452. if (mesh.mFaces[i].iMaterial >= vSubMaterials.size())
  453. {
  454. LOGOUT_WARN("Submaterial index is out of range");
  455. // use the last material instead
  456. aiSplit[vSubMaterials.size()-1].push_back(i);
  457. }
  458. else aiSplit[mesh.mFaces[i].iMaterial].push_back(i);
  459. }
  460. // now generate submeshes
  461. for (unsigned int p = 0; p < vSubMaterials.size();++p)
  462. {
  463. if (aiSplit[p].size() != 0)
  464. {
  465. aiMesh* p_pcOut = new aiMesh();
  466. // let the sub material index
  467. p_pcOut->mMaterialIndex = p;
  468. // we will need this material
  469. this->mParser->m_vMaterials[mesh.iMaterialIndex].avSubMaterials[p].bNeed = true;
  470. // store the real index here ... color channel 3
  471. p_pcOut->mColors[3] = (aiColor4D*)(uintptr_t)mesh.iMaterialIndex;
  472. // store the real transformation matrix in color channel 2
  473. p_pcOut->mColors[2] = (aiColor4D*) new aiMatrix4x4(mesh.mTransform);
  474. avOutMeshes.push_back(p_pcOut);
  475. // convert vertices
  476. p_pcOut->mNumVertices = aiSplit[p].size()*3;
  477. p_pcOut->mNumFaces = aiSplit[p].size();
  478. // receive output vertex weights
  479. std::vector<std::pair<unsigned int, float> >* avOutputBones;
  480. if (!mesh.mBones.empty())
  481. {
  482. avOutputBones = new std::vector<std::pair<unsigned int, float> >[mesh.mBones.size()];
  483. }
  484. // allocate enough storage for faces
  485. p_pcOut->mFaces = new aiFace[p_pcOut->mNumFaces];
  486. if (p_pcOut->mNumVertices != 0)
  487. {
  488. p_pcOut->mVertices = new aiVector3D[p_pcOut->mNumVertices];
  489. p_pcOut->mNormals = new aiVector3D[p_pcOut->mNumVertices];
  490. unsigned int iBase = 0;
  491. for (unsigned int q = 0; q < aiSplit[p].size();++q)
  492. {
  493. unsigned int iIndex = aiSplit[p][q];
  494. p_pcOut->mFaces[q].mIndices = new unsigned int[3];
  495. p_pcOut->mFaces[q].mNumIndices = 3;
  496. for (unsigned int t = 0; t < 3;++t)
  497. {
  498. const uint32_t iIndex2 = mesh.mFaces[iIndex].mIndices[t];
  499. p_pcOut->mVertices[iBase] = mesh.mPositions[iIndex2];
  500. p_pcOut->mNormals[iBase] = mesh.mNormals[iIndex2];
  501. // convert bones, if existing
  502. if (!mesh.mBones.empty())
  503. {
  504. // check whether there is a vertex weight that is using
  505. // this vertex index ...
  506. if (iIndex2 < mesh.mBoneVertices.size())
  507. {
  508. for (std::vector<std::pair<int,float> >::const_iterator
  509. blubb = mesh.mBoneVertices[iIndex2].mBoneWeights.begin();
  510. blubb != mesh.mBoneVertices[iIndex2].mBoneWeights.end();++blubb)
  511. {
  512. // NOTE: illegal cases have already been filtered out
  513. avOutputBones[(*blubb).first].push_back(std::pair<unsigned int, float>(
  514. iBase,(*blubb).second));
  515. }
  516. }
  517. }
  518. ++iBase;
  519. }
  520. p_pcOut->mFaces[q].mIndices[0] = iBase-2;
  521. p_pcOut->mFaces[q].mIndices[1] = iBase-1;
  522. p_pcOut->mFaces[q].mIndices[2] = iBase;
  523. }
  524. }
  525. // convert texture coordinates
  526. for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS;++c)
  527. {
  528. if (!mesh.amTexCoords[c].empty())
  529. {
  530. p_pcOut->mTextureCoords[c] = new aiVector3D[p_pcOut->mNumVertices];
  531. unsigned int iBase = 0;
  532. for (unsigned int q = 0; q < aiSplit[p].size();++q)
  533. {
  534. unsigned int iIndex = aiSplit[p][q];
  535. for (unsigned int t = 0; t < 3;++t)
  536. {
  537. p_pcOut->mTextureCoords[c][iBase++] = mesh.amTexCoords[c][mesh.mFaces[iIndex].mIndices[t]];
  538. }
  539. }
  540. // setup the number of valid vertex components
  541. p_pcOut->mNumUVComponents[c] = mesh.mNumUVComponents[c];
  542. }
  543. }
  544. // convert vertex colors (only one set supported)
  545. if (!mesh.mVertexColors.empty())
  546. {
  547. p_pcOut->mColors[0] = new aiColor4D[p_pcOut->mNumVertices];
  548. unsigned int iBase = 0;
  549. for (unsigned int q = 0; q < aiSplit[p].size();++q)
  550. {
  551. unsigned int iIndex = aiSplit[p][q];
  552. for (unsigned int t = 0; t < 3;++t)
  553. {
  554. p_pcOut->mColors[0][iBase++] = mesh.mVertexColors[mesh.mFaces[iIndex].mIndices[t]];
  555. }
  556. }
  557. }
  558. if (!mesh.mBones.empty())
  559. {
  560. p_pcOut->mNumBones = 0;
  561. for (unsigned int mrspock = 0; mrspock < mesh.mBones.size();++mrspock)
  562. if (!avOutputBones[mrspock].empty())p_pcOut->mNumBones++;
  563. p_pcOut->mBones = new aiBone* [ p_pcOut->mNumBones ];
  564. aiBone** pcBone = &p_pcOut->mBones[0];
  565. for (unsigned int mrspock = 0; mrspock < mesh.mBones.size();++mrspock)
  566. {
  567. if (!avOutputBones[mrspock].empty())
  568. {
  569. // we will need this bone. add it to the output mesh and
  570. // add all per-vertex weights
  571. *pcBone = new aiBone();
  572. (**pcBone).mName.Set(mesh.mBones[mrspock].mName);
  573. (**pcBone).mNumWeights = avOutputBones[mrspock].size();
  574. (**pcBone).mWeights = new aiVertexWeight[(**pcBone).mNumWeights];
  575. for (unsigned int captainkirk = 0; captainkirk < (**pcBone).mNumWeights;++captainkirk)
  576. {
  577. const std::pair<unsigned int,float>& ref = avOutputBones[mrspock][captainkirk];
  578. (**pcBone).mWeights[captainkirk].mVertexId = ref.first;
  579. (**pcBone).mWeights[captainkirk].mWeight = ref.second;
  580. }
  581. ++pcBone;
  582. }
  583. }
  584. // delete allocated storage
  585. delete[] avOutputBones;
  586. }
  587. }
  588. }
  589. // delete storage
  590. delete[] aiSplit;
  591. }
  592. else
  593. {
  594. // otherwise we can simply copy the data to one output mesh
  595. aiMesh* p_pcOut = new aiMesh();
  596. // set an empty sub material index
  597. p_pcOut->mMaterialIndex = ASE::Face::DEFAULT_MATINDEX;
  598. this->mParser->m_vMaterials[mesh.iMaterialIndex].bNeed = true;
  599. // store the real index here ... in color channel 3
  600. p_pcOut->mColors[3] = (aiColor4D*)(uintptr_t)mesh.iMaterialIndex;
  601. // store the transformation matrix in color channel 2
  602. p_pcOut->mColors[2] = (aiColor4D*) new aiMatrix4x4(mesh.mTransform);
  603. avOutMeshes.push_back(p_pcOut);
  604. // convert vertices
  605. p_pcOut->mNumVertices = mesh.mPositions.size();
  606. p_pcOut->mNumFaces = mesh.mFaces.size();
  607. // allocate enough storage for faces
  608. p_pcOut->mFaces = new aiFace[p_pcOut->mNumFaces];
  609. // copy vertices
  610. p_pcOut->mVertices = new aiVector3D[mesh.mPositions.size()];
  611. memcpy(p_pcOut->mVertices,&mesh.mPositions[0],
  612. mesh.mPositions.size() * sizeof(aiVector3D));
  613. // copy normals
  614. p_pcOut->mNormals = new aiVector3D[mesh.mNormals.size()];
  615. memcpy(p_pcOut->mNormals,&mesh.mNormals[0],
  616. mesh.mNormals.size() * sizeof(aiVector3D));
  617. // copy texture coordinates
  618. for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS;++c)
  619. {
  620. if (!mesh.amTexCoords[c].empty())
  621. {
  622. p_pcOut->mTextureCoords[c] = new aiVector3D[mesh.amTexCoords[c].size()];
  623. memcpy(p_pcOut->mTextureCoords[c],&mesh.amTexCoords[c][0],
  624. mesh.amTexCoords[c].size() * sizeof(aiVector3D));
  625. // setup the number of valid vertex components
  626. p_pcOut->mNumUVComponents[c] = mesh.mNumUVComponents[c];
  627. }
  628. }
  629. // copy vertex colors
  630. if (!mesh.mVertexColors.empty())
  631. {
  632. p_pcOut->mColors[0] = new aiColor4D[mesh.mVertexColors.size()];
  633. memcpy(p_pcOut->mColors[0],&mesh.mVertexColors[0],
  634. mesh.mVertexColors.size() * sizeof(aiColor4D));
  635. }
  636. // copy faces
  637. for (unsigned int iFace = 0; iFace < p_pcOut->mNumFaces;++iFace)
  638. {
  639. p_pcOut->mFaces[iFace].mNumIndices = 3;
  640. p_pcOut->mFaces[iFace].mIndices = new unsigned int[3];
  641. // copy indices
  642. p_pcOut->mFaces[iFace].mIndices[0] = mesh.mFaces[iFace].mIndices[0];
  643. p_pcOut->mFaces[iFace].mIndices[1] = mesh.mFaces[iFace].mIndices[1];
  644. p_pcOut->mFaces[iFace].mIndices[2] = mesh.mFaces[iFace].mIndices[2];
  645. }
  646. // copy vertex bones
  647. if (!mesh.mBones.empty() && !mesh.mBoneVertices.empty())
  648. {
  649. std::vector<aiVertexWeight>* avBonesOut = new
  650. std::vector<aiVertexWeight>[mesh.mBones.size()];
  651. // find all vertex weights for this bone
  652. unsigned int quak = 0;
  653. for (std::vector<BoneVertex>::const_iterator
  654. harrypotter = mesh.mBoneVertices.begin();
  655. harrypotter != mesh.mBoneVertices.end();++harrypotter,++quak)
  656. {
  657. for (std::vector<std::pair<int,float> >::const_iterator
  658. ronaldweasley = (*harrypotter).mBoneWeights.begin();
  659. ronaldweasley != (*harrypotter).mBoneWeights.end();++ronaldweasley)
  660. {
  661. aiVertexWeight weight;
  662. weight.mVertexId = quak;
  663. weight.mWeight = (*ronaldweasley).second;
  664. avBonesOut[(*ronaldweasley).first].push_back(weight);
  665. }
  666. }
  667. // now build a final bone list
  668. p_pcOut->mNumBones = 0;
  669. for (unsigned int jfkennedy = 0; jfkennedy < mesh.mBones.size();++jfkennedy)
  670. if (!avBonesOut[jfkennedy].empty())p_pcOut->mNumBones++;
  671. p_pcOut->mBones = new aiBone*[p_pcOut->mNumBones];
  672. aiBone** pcBone = &p_pcOut->mBones[0];
  673. for (unsigned int jfkennedy = 0; jfkennedy < mesh.mBones.size();++jfkennedy)
  674. {
  675. if (!avBonesOut[jfkennedy].empty())
  676. {
  677. *pcBone = new aiBone();
  678. (**pcBone).mName.Set(mesh.mBones[jfkennedy].mName);
  679. (**pcBone).mNumWeights = avBonesOut[jfkennedy].size();
  680. (**pcBone).mWeights = new aiVertexWeight[(**pcBone).mNumWeights];
  681. memcpy((**pcBone).mWeights,&avBonesOut[jfkennedy][0],
  682. sizeof(aiVertexWeight) * (**pcBone).mNumWeights);
  683. ++pcBone;
  684. }
  685. }
  686. }
  687. }
  688. // now build the output mesh list
  689. pcScene->mNumMeshes = avOutMeshes.size();
  690. pcScene->mMeshes = new aiMesh*[pcScene->mNumMeshes];
  691. for (unsigned int i = 0; i < pcScene->mNumMeshes;++i)
  692. pcScene->mMeshes[i] = avOutMeshes[i];
  693. return;
  694. }
  695. // ------------------------------------------------------------------------------------------------
  696. void ASEImporter::BuildMaterialIndices(aiScene* pcScene)
  697. {
  698. ai_assert(NULL != pcScene);
  699. // iterate through all materials and check whether we need them
  700. unsigned int iNum = 0;
  701. for (unsigned int iMat = 0; iMat < this->mParser->m_vMaterials.size();++iMat)
  702. {
  703. if (this->mParser->m_vMaterials[iMat].bNeed)
  704. {
  705. // convert it to the aiMaterial layout
  706. this->ConvertMaterial(this->mParser->m_vMaterials[iMat]);
  707. iNum++;
  708. }
  709. for (unsigned int iSubMat = 0; iSubMat < this->mParser->m_vMaterials[
  710. iMat].avSubMaterials.size();++iSubMat)
  711. {
  712. if (this->mParser->m_vMaterials[iMat].avSubMaterials[iSubMat].bNeed)
  713. {
  714. // convert it to the aiMaterial layout
  715. this->ConvertMaterial(this->mParser->m_vMaterials[iMat].avSubMaterials[iSubMat]);
  716. iNum++;
  717. }
  718. }
  719. }
  720. // allocate the output material array
  721. pcScene->mNumMaterials = iNum;
  722. pcScene->mMaterials = new aiMaterial*[pcScene->mNumMaterials];
  723. iNum = 0;
  724. for (unsigned int iMat = 0; iMat < this->mParser->m_vMaterials.size();++iMat)
  725. {
  726. if (this->mParser->m_vMaterials[iMat].bNeed)
  727. {
  728. ai_assert(NULL != this->mParser->m_vMaterials[iMat].pcInstance);
  729. pcScene->mMaterials[iNum] = this->mParser->m_vMaterials[iMat].pcInstance;
  730. // iterate through all meshes and search for one which is using
  731. // this top-level material index
  732. for (unsigned int iMesh = 0; iMesh < pcScene->mNumMeshes;++iMesh)
  733. {
  734. if (ASE::Face::DEFAULT_MATINDEX == pcScene->mMeshes[iMesh]->mMaterialIndex &&
  735. iMat == (uintptr_t)pcScene->mMeshes[iMesh]->mColors[3])
  736. {
  737. pcScene->mMeshes[iMesh]->mMaterialIndex = iNum;
  738. pcScene->mMeshes[iMesh]->mColors[3] = NULL;
  739. }
  740. }
  741. iNum++;
  742. }
  743. for (unsigned int iSubMat = 0; iSubMat < this->mParser->m_vMaterials[iMat].avSubMaterials.size();++iSubMat)
  744. {
  745. if (this->mParser->m_vMaterials[iMat].avSubMaterials[iSubMat].bNeed)
  746. {
  747. ai_assert(NULL != this->mParser->m_vMaterials[iMat].avSubMaterials[iSubMat].pcInstance);
  748. pcScene->mMaterials[iNum] = this->mParser->m_vMaterials[iMat].
  749. avSubMaterials[iSubMat].pcInstance;
  750. // iterate through all meshes and search for one which is using
  751. // this sub-level material index
  752. for (unsigned int iMesh = 0; iMesh < pcScene->mNumMeshes;++iMesh)
  753. {
  754. if (iSubMat == pcScene->mMeshes[iMesh]->mMaterialIndex &&
  755. iMat == (uintptr_t)pcScene->mMeshes[iMesh]->mColors[3])
  756. {
  757. pcScene->mMeshes[iMesh]->mMaterialIndex = iNum;
  758. pcScene->mMeshes[iMesh]->mColors[3] = NULL;
  759. }
  760. }
  761. iNum++;
  762. }
  763. }
  764. }
  765. // finished!
  766. return;
  767. }
  768. // ------------------------------------------------------------------------------------------------
  769. // Generate normal vectors basing on smoothing groups
  770. void ASEImporter::GenerateNormals(ASE::Mesh& mesh)
  771. {
  772. if (mesh.mNormals.empty())
  773. {
  774. // need to calculate normals ...
  775. // TODO: Find a way to merge this with the code in 3DSGenNormals.cpp
  776. mesh.mNormals.resize(mesh.mPositions.size(),aiVector3D());
  777. for( unsigned int a = 0; a < mesh.mFaces.size(); a++)
  778. {
  779. const ASE::Face& face = mesh.mFaces[a];
  780. // assume it is a triangle
  781. aiVector3D* pV1 = &mesh.mPositions[face.mIndices[0]];
  782. aiVector3D* pV2 = &mesh.mPositions[face.mIndices[1]];
  783. aiVector3D* pV3 = &mesh.mPositions[face.mIndices[2]];
  784. aiVector3D pDelta1 = *pV2 - *pV1;
  785. aiVector3D pDelta2 = *pV3 - *pV1;
  786. aiVector3D vNor = pDelta1 ^ pDelta2;
  787. mesh.mNormals[face.mIndices[0]] = vNor;
  788. mesh.mNormals[face.mIndices[1]] = vNor;
  789. mesh.mNormals[face.mIndices[2]] = vNor;
  790. }
  791. // calculate the position bounds so we have a reliable epsilon to
  792. // check position differences against
  793. // @Schrompf: This is the 7th time this snippet is repeated!
  794. aiVector3D minVec( 1e10f, 1e10f, 1e10f), maxVec( -1e10f, -1e10f, -1e10f);
  795. for( unsigned int a = 0; a < mesh.mPositions.size(); a++)
  796. {
  797. minVec.x = std::min( minVec.x, mesh.mPositions[a].x);
  798. minVec.y = std::min( minVec.y, mesh.mPositions[a].y);
  799. minVec.z = std::min( minVec.z, mesh.mPositions[a].z);
  800. maxVec.x = std::max( maxVec.x, mesh.mPositions[a].x);
  801. maxVec.y = std::max( maxVec.y, mesh.mPositions[a].y);
  802. maxVec.z = std::max( maxVec.z, mesh.mPositions[a].z);
  803. }
  804. const float posEpsilon = (maxVec - minVec).Length() * 1e-5f;
  805. std::vector<aiVector3D> avNormals;
  806. avNormals.resize(mesh.mNormals.size());
  807. // now generate the spatial sort tree
  808. D3DSSpatialSorter sSort;
  809. for( std::vector<ASE::Face>::iterator
  810. i = mesh.mFaces.begin();
  811. i != mesh.mFaces.end();++i){sSort.AddFace(&(*i),mesh.mPositions);}
  812. sSort.Prepare();
  813. for( std::vector<ASE::Face>::iterator
  814. i = mesh.mFaces.begin();
  815. i != mesh.mFaces.end();++i)
  816. {
  817. std::vector<unsigned int> poResult;
  818. for (unsigned int c = 0; c < 3;++c)
  819. {
  820. sSort.FindPositions(mesh.mPositions[(*i).mIndices[c]],(*i).iSmoothGroup,
  821. posEpsilon,poResult);
  822. aiVector3D vNormals;
  823. float fDiv = 0.0f;
  824. for (std::vector<unsigned int>::const_iterator
  825. a = poResult.begin();
  826. a != poResult.end();++a)
  827. {
  828. vNormals += mesh.mNormals[(*a)];
  829. fDiv += 1.0f;
  830. }
  831. vNormals.x /= fDiv;vNormals.y /= fDiv;vNormals.z /= fDiv;
  832. vNormals.Normalize();
  833. avNormals[(*i).mIndices[c]] = vNormals;
  834. poResult.clear();
  835. }
  836. }
  837. mesh.mNormals = avNormals;
  838. }
  839. return;
  840. }