ASELoader.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2015, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file ASELoader.cpp
  35. * @brief Implementation of the ASE importer class
  36. */
  37. #ifndef ASSIMP_BUILD_NO_ASE_IMPORTER
  38. // internal headers
  39. #include "ASELoader.h"
  40. #include "StringComparison.h"
  41. #include "SkeletonMeshBuilder.h"
  42. #include "TargetAnimation.h"
  43. #include "../include/assimp/Importer.hpp"
  44. #include <boost/scoped_ptr.hpp>
  45. #include "../include/assimp/IOSystem.hpp"
  46. #include "../include/assimp/DefaultLogger.hpp"
  47. #include "../include/assimp/scene.h"
  48. // utilities
  49. #include "fast_atof.h"
  50. using namespace Assimp;
  51. using namespace Assimp::ASE;
  52. static const aiImporterDesc desc = {
  53. "ASE Importer",
  54. "",
  55. "",
  56. "Similar to 3DS but text-encoded",
  57. aiImporterFlags_SupportTextFlavour,
  58. 0,
  59. 0,
  60. 0,
  61. 0,
  62. "ase ask"
  63. };
  64. // ------------------------------------------------------------------------------------------------
  65. // Constructor to be privately used by Importer
  66. ASEImporter::ASEImporter()
  67. : noSkeletonMesh()
  68. {}
  69. // ------------------------------------------------------------------------------------------------
  70. // Destructor, private as well
  71. ASEImporter::~ASEImporter()
  72. {}
  73. // ------------------------------------------------------------------------------------------------
  74. // Returns whether the class can handle the format of the given file.
  75. bool ASEImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool cs) const
  76. {
  77. // check file extension
  78. const std::string extension = GetExtension(pFile);
  79. if( extension == "ase" || extension == "ask")
  80. return true;
  81. if ((!extension.length() || cs) && pIOHandler) {
  82. const char* tokens[] = {"*3dsmax_asciiexport"};
  83. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  84. }
  85. return false;
  86. }
  87. // ------------------------------------------------------------------------------------------------
  88. // Loader meta information
  89. const aiImporterDesc* ASEImporter::GetInfo () const
  90. {
  91. return &desc;
  92. }
  93. // ------------------------------------------------------------------------------------------------
  94. // Setup configuration options
  95. void ASEImporter::SetupProperties(const Importer* pImp)
  96. {
  97. configRecomputeNormals = (pImp->GetPropertyInteger(
  98. AI_CONFIG_IMPORT_ASE_RECONSTRUCT_NORMALS,1) ? true : false);
  99. noSkeletonMesh = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_NO_SKELETON_MESHES,0) != 0;
  100. }
  101. // ------------------------------------------------------------------------------------------------
  102. // Imports the given file into the given scene structure.
  103. void ASEImporter::InternReadFile( const std::string& pFile,
  104. aiScene* pScene, IOSystem* pIOHandler)
  105. {
  106. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  107. // Check whether we can read from the file
  108. if( file.get() == NULL) {
  109. throw DeadlyImportError( "Failed to open ASE file " + pFile + ".");
  110. }
  111. // Allocate storage and copy the contents of the file to a memory buffer
  112. std::vector<char> mBuffer2;
  113. TextFileToBuffer(file.get(),mBuffer2);
  114. this->mBuffer = &mBuffer2[0];
  115. this->pcScene = pScene;
  116. // ------------------------------------------------------------------
  117. // Guess the file format by looking at the extension
  118. // ASC is considered to be the older format 110,
  119. // ASE is the actual version 200 (that is currently written by max)
  120. // ------------------------------------------------------------------
  121. unsigned int defaultFormat;
  122. std::string::size_type s = pFile.length()-1;
  123. switch (pFile.c_str()[s]) {
  124. case 'C':
  125. case 'c':
  126. defaultFormat = AI_ASE_OLD_FILE_FORMAT;
  127. break;
  128. default:
  129. defaultFormat = AI_ASE_NEW_FILE_FORMAT;
  130. };
  131. // Construct an ASE parser and parse the file
  132. ASE::Parser parser(mBuffer,defaultFormat);
  133. mParser = &parser;
  134. mParser->Parse();
  135. //------------------------------------------------------------------
  136. // Check whether we god at least one mesh. If we did - generate
  137. // materials and copy meshes.
  138. // ------------------------------------------------------------------
  139. if ( !mParser->m_vMeshes.empty()) {
  140. // If absolutely no material has been loaded from the file
  141. // we need to generate a default material
  142. GenerateDefaultMaterial();
  143. // process all meshes
  144. bool tookNormals = false;
  145. std::vector<aiMesh*> avOutMeshes;
  146. avOutMeshes.reserve(mParser->m_vMeshes.size()*2);
  147. for (std::vector<ASE::Mesh>::iterator i = mParser->m_vMeshes.begin();i != mParser->m_vMeshes.end();++i) {
  148. if ((*i).bSkip) {
  149. continue;
  150. }
  151. BuildUniqueRepresentation(*i);
  152. // Need to generate proper vertex normals if necessary
  153. if(GenerateNormals(*i)) {
  154. tookNormals = true;
  155. }
  156. // Convert all meshes to aiMesh objects
  157. ConvertMeshes(*i,avOutMeshes);
  158. }
  159. if (tookNormals) {
  160. DefaultLogger::get()->debug("ASE: Taking normals from the file. Use "
  161. "the AI_CONFIG_IMPORT_ASE_RECONSTRUCT_NORMALS setting if you "
  162. "experience problems");
  163. }
  164. // Now build the output mesh list. Remove dummies
  165. pScene->mNumMeshes = (unsigned int)avOutMeshes.size();
  166. aiMesh** pp = pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  167. for (std::vector<aiMesh*>::const_iterator i = avOutMeshes.begin();i != avOutMeshes.end();++i) {
  168. if (!(*i)->mNumFaces) {
  169. continue;
  170. }
  171. *pp++ = *i;
  172. }
  173. pScene->mNumMeshes = (unsigned int)(pp - pScene->mMeshes);
  174. // Build final material indices (remove submaterials and setup
  175. // the final list)
  176. BuildMaterialIndices();
  177. }
  178. // ------------------------------------------------------------------
  179. // Copy all scene graph nodes - lights, cameras, dummies and meshes
  180. // into one huge list.
  181. //------------------------------------------------------------------
  182. std::vector<BaseNode*> nodes;
  183. nodes.reserve(mParser->m_vMeshes.size() +mParser->m_vLights.size()
  184. + mParser->m_vCameras.size() + mParser->m_vDummies.size());
  185. // Lights
  186. for (std::vector<ASE::Light>::iterator it = mParser->m_vLights.begin(),
  187. end = mParser->m_vLights.end();it != end; ++it)nodes.push_back(&(*it));
  188. // Cameras
  189. for (std::vector<ASE::Camera>::iterator it = mParser->m_vCameras.begin(),
  190. end = mParser->m_vCameras.end();it != end; ++it)nodes.push_back(&(*it));
  191. // Meshes
  192. for (std::vector<ASE::Mesh>::iterator it = mParser->m_vMeshes.begin(),
  193. end = mParser->m_vMeshes.end();it != end; ++it)nodes.push_back(&(*it));
  194. // Dummies
  195. for (std::vector<ASE::Dummy>::iterator it = mParser->m_vDummies.begin(),
  196. end = mParser->m_vDummies.end();it != end; ++it)nodes.push_back(&(*it));
  197. // build the final node graph
  198. BuildNodes(nodes);
  199. // build output animations
  200. BuildAnimations(nodes);
  201. // build output cameras
  202. BuildCameras();
  203. // build output lights
  204. BuildLights();
  205. // ------------------------------------------------------------------
  206. // If we have no meshes use the SkeletonMeshBuilder helper class
  207. // to build a mesh for the animation skeleton
  208. // FIXME: very strange results
  209. // ------------------------------------------------------------------
  210. if (!pScene->mNumMeshes) {
  211. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  212. if (!noSkeletonMesh) {
  213. SkeletonMeshBuilder skeleton(pScene);
  214. }
  215. }
  216. }
  217. // ------------------------------------------------------------------------------------------------
  218. void ASEImporter::GenerateDefaultMaterial()
  219. {
  220. ai_assert(NULL != mParser);
  221. bool bHas = false;
  222. for (std::vector<ASE::Mesh>::iterator i = mParser->m_vMeshes.begin();i != mParser->m_vMeshes.end();++i) {
  223. if ((*i).bSkip)continue;
  224. if (ASE::Face::DEFAULT_MATINDEX == (*i).iMaterialIndex) {
  225. (*i).iMaterialIndex = (unsigned int)mParser->m_vMaterials.size();
  226. bHas = true;
  227. }
  228. }
  229. if (bHas || mParser->m_vMaterials.empty()) {
  230. // add a simple material without submaterials to the parser's list
  231. mParser->m_vMaterials.push_back ( ASE::Material() );
  232. ASE::Material& mat = mParser->m_vMaterials.back();
  233. mat.mDiffuse = aiColor3D(0.6f,0.6f,0.6f);
  234. mat.mSpecular = aiColor3D(1.0f,1.0f,1.0f);
  235. mat.mAmbient = aiColor3D(0.05f,0.05f,0.05f);
  236. mat.mShading = Discreet3DS::Gouraud;
  237. mat.mName = AI_DEFAULT_MATERIAL_NAME;
  238. }
  239. }
  240. // ------------------------------------------------------------------------------------------------
  241. void ASEImporter::BuildAnimations(const std::vector<BaseNode*>& nodes)
  242. {
  243. // check whether we have at least one mesh which has animations
  244. std::vector<ASE::BaseNode*>::const_iterator i = nodes.begin();
  245. unsigned int iNum = 0;
  246. for (;i != nodes.end();++i) {
  247. // TODO: Implement Bezier & TCB support
  248. if ((*i)->mAnim.mPositionType != ASE::Animation::TRACK) {
  249. DefaultLogger::get()->warn("ASE: Position controller uses Bezier/TCB keys. "
  250. "This is not supported.");
  251. }
  252. if ((*i)->mAnim.mRotationType != ASE::Animation::TRACK) {
  253. DefaultLogger::get()->warn("ASE: Rotation controller uses Bezier/TCB keys. "
  254. "This is not supported.");
  255. }
  256. if ((*i)->mAnim.mScalingType != ASE::Animation::TRACK) {
  257. DefaultLogger::get()->warn("ASE: Position controller uses Bezier/TCB keys. "
  258. "This is not supported.");
  259. }
  260. // We compare against 1 here - firstly one key is not
  261. // really an animation and secondly MAX writes dummies
  262. // that represent the node transformation.
  263. if ((*i)->mAnim.akeyPositions.size()>1 || (*i)->mAnim.akeyRotations.size()>1 || (*i)->mAnim.akeyScaling.size()>1){
  264. ++iNum;
  265. }
  266. if ((*i)->mTargetAnim.akeyPositions.size() > 1 && is_not_qnan( (*i)->mTargetPosition.x )) {
  267. ++iNum;
  268. }
  269. }
  270. if (iNum) {
  271. // Generate a new animation channel and setup everything for it
  272. pcScene->mNumAnimations = 1;
  273. pcScene->mAnimations = new aiAnimation*[1];
  274. aiAnimation* pcAnim = pcScene->mAnimations[0] = new aiAnimation();
  275. pcAnim->mNumChannels = iNum;
  276. pcAnim->mChannels = new aiNodeAnim*[iNum];
  277. pcAnim->mTicksPerSecond = mParser->iFrameSpeed * mParser->iTicksPerFrame;
  278. iNum = 0;
  279. // Now iterate through all meshes and collect all data we can find
  280. for (i = nodes.begin();i != nodes.end();++i) {
  281. ASE::BaseNode* me = *i;
  282. if ( me->mTargetAnim.akeyPositions.size() > 1 && is_not_qnan( me->mTargetPosition.x )) {
  283. // Generate an extra channel for the camera/light target.
  284. // BuildNodes() does also generate an extra node, named
  285. // <baseName>.Target.
  286. aiNodeAnim* nd = pcAnim->mChannels[iNum++] = new aiNodeAnim();
  287. nd->mNodeName.Set(me->mName + ".Target");
  288. // If there is no input position channel we will need
  289. // to supply the default position from the node's
  290. // local transformation matrix.
  291. /*TargetAnimationHelper helper;
  292. if (me->mAnim.akeyPositions.empty())
  293. {
  294. aiMatrix4x4& mat = (*i)->mTransform;
  295. helper.SetFixedMainAnimationChannel(aiVector3D(
  296. mat.a4, mat.b4, mat.c4));
  297. }
  298. else helper.SetMainAnimationChannel (&me->mAnim.akeyPositions);
  299. helper.SetTargetAnimationChannel (&me->mTargetAnim.akeyPositions);
  300. helper.Process(&me->mTargetAnim.akeyPositions);*/
  301. // Allocate the key array and fill it
  302. nd->mNumPositionKeys = (unsigned int) me->mTargetAnim.akeyPositions.size();
  303. nd->mPositionKeys = new aiVectorKey[nd->mNumPositionKeys];
  304. ::memcpy(nd->mPositionKeys,&me->mTargetAnim.akeyPositions[0],
  305. nd->mNumPositionKeys * sizeof(aiVectorKey));
  306. }
  307. if (me->mAnim.akeyPositions.size() > 1 || me->mAnim.akeyRotations.size() > 1 || me->mAnim.akeyScaling.size() > 1) {
  308. // Begin a new node animation channel for this node
  309. aiNodeAnim* nd = pcAnim->mChannels[iNum++] = new aiNodeAnim();
  310. nd->mNodeName.Set(me->mName);
  311. // copy position keys
  312. if (me->mAnim.akeyPositions.size() > 1 )
  313. {
  314. // Allocate the key array and fill it
  315. nd->mNumPositionKeys = (unsigned int) me->mAnim.akeyPositions.size();
  316. nd->mPositionKeys = new aiVectorKey[nd->mNumPositionKeys];
  317. ::memcpy(nd->mPositionKeys,&me->mAnim.akeyPositions[0],
  318. nd->mNumPositionKeys * sizeof(aiVectorKey));
  319. }
  320. // copy rotation keys
  321. if (me->mAnim.akeyRotations.size() > 1 ) {
  322. // Allocate the key array and fill it
  323. nd->mNumRotationKeys = (unsigned int) me->mAnim.akeyRotations.size();
  324. nd->mRotationKeys = new aiQuatKey[nd->mNumRotationKeys];
  325. // --------------------------------------------------------------------
  326. // Rotation keys are offsets to the previous keys.
  327. // We have the quaternion representations of all
  328. // of them, so we just need to concatenate all
  329. // (unit-length) quaternions to get the absolute
  330. // rotations.
  331. // Rotation keys are ABSOLUTE for older files
  332. // --------------------------------------------------------------------
  333. aiQuaternion cur;
  334. for (unsigned int a = 0; a < nd->mNumRotationKeys;++a) {
  335. aiQuatKey q = me->mAnim.akeyRotations[a];
  336. if (mParser->iFileFormat > 110) {
  337. cur = (a ? cur*q.mValue : q.mValue);
  338. q.mValue = cur.Normalize();
  339. }
  340. nd->mRotationKeys[a] = q;
  341. // need this to get to Assimp quaternion conventions
  342. nd->mRotationKeys[a].mValue.w *= -1.f;
  343. }
  344. }
  345. // copy scaling keys
  346. if (me->mAnim.akeyScaling.size() > 1 ) {
  347. // Allocate the key array and fill it
  348. nd->mNumScalingKeys = (unsigned int) me->mAnim.akeyScaling.size();
  349. nd->mScalingKeys = new aiVectorKey[nd->mNumScalingKeys];
  350. ::memcpy(nd->mScalingKeys,&me->mAnim.akeyScaling[0],
  351. nd->mNumScalingKeys * sizeof(aiVectorKey));
  352. }
  353. }
  354. }
  355. }
  356. }
  357. // ------------------------------------------------------------------------------------------------
  358. // Build output cameras
  359. void ASEImporter::BuildCameras()
  360. {
  361. if (!mParser->m_vCameras.empty()) {
  362. pcScene->mNumCameras = (unsigned int)mParser->m_vCameras.size();
  363. pcScene->mCameras = new aiCamera*[pcScene->mNumCameras];
  364. for (unsigned int i = 0; i < pcScene->mNumCameras;++i) {
  365. aiCamera* out = pcScene->mCameras[i] = new aiCamera();
  366. ASE::Camera& in = mParser->m_vCameras[i];
  367. // copy members
  368. out->mClipPlaneFar = in.mFar;
  369. out->mClipPlaneNear = (in.mNear ? in.mNear : 0.1f);
  370. out->mHorizontalFOV = in.mFOV;
  371. out->mName.Set(in.mName);
  372. }
  373. }
  374. }
  375. // ------------------------------------------------------------------------------------------------
  376. // Build output lights
  377. void ASEImporter::BuildLights()
  378. {
  379. if (!mParser->m_vLights.empty()) {
  380. pcScene->mNumLights = (unsigned int)mParser->m_vLights.size();
  381. pcScene->mLights = new aiLight*[pcScene->mNumLights];
  382. for (unsigned int i = 0; i < pcScene->mNumLights;++i) {
  383. aiLight* out = pcScene->mLights[i] = new aiLight();
  384. ASE::Light& in = mParser->m_vLights[i];
  385. // The direction is encoded in the transformation matrix of the node.
  386. // In 3DS MAX the light source points into negative Z direction if
  387. // the node transformation is the identity.
  388. out->mDirection = aiVector3D(0.f,0.f,-1.f);
  389. out->mName.Set(in.mName);
  390. switch (in.mLightType)
  391. {
  392. case ASE::Light::TARGET:
  393. out->mType = aiLightSource_SPOT;
  394. out->mAngleInnerCone = AI_DEG_TO_RAD(in.mAngle);
  395. out->mAngleOuterCone = (in.mFalloff ? AI_DEG_TO_RAD(in.mFalloff) : out->mAngleInnerCone);
  396. break;
  397. case ASE::Light::DIRECTIONAL:
  398. out->mType = aiLightSource_DIRECTIONAL;
  399. break;
  400. default:
  401. //case ASE::Light::OMNI:
  402. out->mType = aiLightSource_POINT;
  403. break;
  404. };
  405. out->mColorDiffuse = out->mColorSpecular = in.mColor * in.mIntensity;
  406. }
  407. }
  408. }
  409. // ------------------------------------------------------------------------------------------------
  410. void ASEImporter::AddNodes(const std::vector<BaseNode*>& nodes,
  411. aiNode* pcParent,const char* szName)
  412. {
  413. aiMatrix4x4 m;
  414. AddNodes(nodes,pcParent,szName,m);
  415. }
  416. // ------------------------------------------------------------------------------------------------
  417. // Add meshes to a given node
  418. void ASEImporter::AddMeshes(const ASE::BaseNode* snode,aiNode* node)
  419. {
  420. for (unsigned int i = 0; i < pcScene->mNumMeshes;++i) {
  421. // Get the name of the mesh (the mesh instance has been temporarily stored in the third vertex color)
  422. const aiMesh* pcMesh = pcScene->mMeshes[i];
  423. const ASE::Mesh* mesh = (const ASE::Mesh*)pcMesh->mColors[2];
  424. if (mesh == snode) {
  425. ++node->mNumMeshes;
  426. }
  427. }
  428. if(node->mNumMeshes) {
  429. node->mMeshes = new unsigned int[node->mNumMeshes];
  430. for (unsigned int i = 0, p = 0; i < pcScene->mNumMeshes;++i) {
  431. const aiMesh* pcMesh = pcScene->mMeshes[i];
  432. const ASE::Mesh* mesh = (const ASE::Mesh*)pcMesh->mColors[2];
  433. if (mesh == snode) {
  434. node->mMeshes[p++] = i;
  435. // Transform all vertices of the mesh back into their local space ->
  436. // at the moment they are pretransformed
  437. aiMatrix4x4 m = mesh->mTransform;
  438. m.Inverse();
  439. aiVector3D* pvCurPtr = pcMesh->mVertices;
  440. const aiVector3D* pvEndPtr = pvCurPtr + pcMesh->mNumVertices;
  441. while (pvCurPtr != pvEndPtr) {
  442. *pvCurPtr = m * (*pvCurPtr);
  443. pvCurPtr++;
  444. }
  445. // Do the same for the normal vectors, if we have them.
  446. // As always, inverse transpose.
  447. if (pcMesh->mNormals) {
  448. aiMatrix3x3 m3 = aiMatrix3x3( mesh->mTransform );
  449. m3.Transpose();
  450. pvCurPtr = pcMesh->mNormals;
  451. pvEndPtr = pvCurPtr + pcMesh->mNumVertices;
  452. while (pvCurPtr != pvEndPtr) {
  453. *pvCurPtr = m3 * (*pvCurPtr);
  454. pvCurPtr++;
  455. }
  456. }
  457. }
  458. }
  459. }
  460. }
  461. // ------------------------------------------------------------------------------------------------
  462. // Add child nodes to a given parent node
  463. void ASEImporter::AddNodes (const std::vector<BaseNode*>& nodes,
  464. aiNode* pcParent, const char* szName,
  465. const aiMatrix4x4& mat)
  466. {
  467. const size_t len = szName ? ::strlen(szName) : 0;
  468. ai_assert(4 <= AI_MAX_NUMBER_OF_COLOR_SETS);
  469. // Receives child nodes for the pcParent node
  470. std::vector<aiNode*> apcNodes;
  471. // Now iterate through all nodes in the scene and search for one
  472. // which has *us* as parent.
  473. for (std::vector<BaseNode*>::const_iterator it = nodes.begin(), end = nodes.end(); it != end; ++it) {
  474. const BaseNode* snode = *it;
  475. if (szName) {
  476. if (len != snode->mParent.length() || ::strcmp(szName,snode->mParent.c_str()))
  477. continue;
  478. }
  479. else if (snode->mParent.length())
  480. continue;
  481. (*it)->mProcessed = true;
  482. // Allocate a new node and add it to the output data structure
  483. apcNodes.push_back(new aiNode());
  484. aiNode* node = apcNodes.back();
  485. node->mName.Set((snode->mName.length() ? snode->mName.c_str() : "Unnamed_Node"));
  486. node->mParent = pcParent;
  487. // Setup the transformation matrix of the node
  488. aiMatrix4x4 mParentAdjust = mat;
  489. mParentAdjust.Inverse();
  490. node->mTransformation = mParentAdjust*snode->mTransform;
  491. // Add sub nodes - prevent stack overflow due to recursive parenting
  492. if (node->mName != node->mParent->mName) {
  493. AddNodes(nodes,node,node->mName.data,snode->mTransform);
  494. }
  495. // Further processing depends on the type of the node
  496. if (snode->mType == ASE::BaseNode::Mesh) {
  497. // If the type of this node is "Mesh" we need to search
  498. // the list of output meshes in the data structure for
  499. // all those that belonged to this node once. This is
  500. // slightly inconvinient here and a better solution should
  501. // be used when this code is refactored next.
  502. AddMeshes(snode,node);
  503. }
  504. else if (is_not_qnan( snode->mTargetPosition.x )) {
  505. // If this is a target camera or light we generate a small
  506. // child node which marks the position of the camera
  507. // target (the direction information is contained in *this*
  508. // node's animation track but the exact target position
  509. // would be lost otherwise)
  510. if (!node->mNumChildren) {
  511. node->mChildren = new aiNode*[1];
  512. }
  513. aiNode* nd = new aiNode();
  514. nd->mName.Set ( snode->mName + ".Target" );
  515. nd->mTransformation.a4 = snode->mTargetPosition.x - snode->mTransform.a4;
  516. nd->mTransformation.b4 = snode->mTargetPosition.y - snode->mTransform.b4;
  517. nd->mTransformation.c4 = snode->mTargetPosition.z - snode->mTransform.c4;
  518. nd->mParent = node;
  519. // The .Target node is always the first child node
  520. for (unsigned int m = 0; m < node->mNumChildren;++m)
  521. node->mChildren[m+1] = node->mChildren[m];
  522. node->mChildren[0] = nd;
  523. node->mNumChildren++;
  524. // What we did is so great, it is at least worth a debug message
  525. DefaultLogger::get()->debug("ASE: Generating separate target node ("+snode->mName+")");
  526. }
  527. }
  528. // Allocate enough space for the child nodes
  529. // We allocate one slot more in case this is a target camera/light
  530. pcParent->mNumChildren = (unsigned int)apcNodes.size();
  531. if (pcParent->mNumChildren) {
  532. pcParent->mChildren = new aiNode*[apcNodes.size()+1 /* PLUS ONE !!! */];
  533. // now build all nodes for our nice new children
  534. for (unsigned int p = 0; p < apcNodes.size();++p)
  535. pcParent->mChildren[p] = apcNodes[p];
  536. }
  537. return;
  538. }
  539. // ------------------------------------------------------------------------------------------------
  540. // Build the output node graph
  541. void ASEImporter::BuildNodes(std::vector<BaseNode*>& nodes) {
  542. ai_assert(NULL != pcScene);
  543. // allocate the one and only root node
  544. aiNode* root = pcScene->mRootNode = new aiNode();
  545. root->mName.Set("<ASERoot>");
  546. // Setup the coordinate system transformation
  547. pcScene->mRootNode->mNumChildren = 1;
  548. pcScene->mRootNode->mChildren = new aiNode*[1];
  549. aiNode* ch = pcScene->mRootNode->mChildren[0] = new aiNode();
  550. ch->mParent = root;
  551. // Change the transformation matrix of all nodes
  552. for (std::vector<BaseNode*>::iterator it = nodes.begin(), end = nodes.end();it != end; ++it) {
  553. aiMatrix4x4& m = (*it)->mTransform;
  554. m.Transpose(); // row-order vs column-order
  555. }
  556. // add all nodes
  557. AddNodes(nodes,ch,NULL);
  558. // now iterate through al nodes and find those that have not yet
  559. // been added to the nodegraph (= their parent could not be recognized)
  560. std::vector<const BaseNode*> aiList;
  561. for (std::vector<BaseNode*>::iterator it = nodes.begin(), end = nodes.end();it != end; ++it) {
  562. if ((*it)->mProcessed) {
  563. continue;
  564. }
  565. // check whether our parent is known
  566. bool bKnowParent = false;
  567. // search the list another time, starting *here* and try to find out whether
  568. // there is a node that references *us* as a parent
  569. for (std::vector<BaseNode*>::const_iterator it2 = nodes.begin();it2 != end; ++it2) {
  570. if (it2 == it) {
  571. continue;
  572. }
  573. if ((*it2)->mName == (*it)->mParent) {
  574. bKnowParent = true;
  575. break;
  576. }
  577. }
  578. if (!bKnowParent) {
  579. aiList.push_back(*it);
  580. }
  581. }
  582. // Are there ane orphaned nodes?
  583. if (!aiList.empty()) {
  584. std::vector<aiNode*> apcNodes;
  585. apcNodes.reserve(aiList.size() + pcScene->mRootNode->mNumChildren);
  586. for (unsigned int i = 0; i < pcScene->mRootNode->mNumChildren;++i)
  587. apcNodes.push_back(pcScene->mRootNode->mChildren[i]);
  588. delete[] pcScene->mRootNode->mChildren;
  589. for (std::vector<const BaseNode*>::/*const_*/iterator i = aiList.begin();i != aiList.end();++i) {
  590. const ASE::BaseNode* src = *i;
  591. // The parent is not known, so we can assume that we must add
  592. // this node to the root node of the whole scene
  593. aiNode* pcNode = new aiNode();
  594. pcNode->mParent = pcScene->mRootNode;
  595. pcNode->mName.Set(src->mName);
  596. AddMeshes(src,pcNode);
  597. AddNodes(nodes,pcNode,pcNode->mName.data);
  598. apcNodes.push_back(pcNode);
  599. }
  600. // Regenerate our output array
  601. pcScene->mRootNode->mChildren = new aiNode*[apcNodes.size()];
  602. for (unsigned int i = 0; i < apcNodes.size();++i)
  603. pcScene->mRootNode->mChildren[i] = apcNodes[i];
  604. pcScene->mRootNode->mNumChildren = (unsigned int)apcNodes.size();
  605. }
  606. // Reset the third color set to NULL - we used this field to store a temporary pointer
  607. for (unsigned int i = 0; i < pcScene->mNumMeshes;++i)
  608. pcScene->mMeshes[i]->mColors[2] = NULL;
  609. // The root node should not have at least one child or the file is valid
  610. if (!pcScene->mRootNode->mNumChildren) {
  611. throw DeadlyImportError("ASE: No nodes loaded. The file is either empty or corrupt");
  612. }
  613. // Now rotate the whole scene 90 degrees around the x axis to convert to internal coordinate system
  614. pcScene->mRootNode->mTransformation = aiMatrix4x4(1.f,0.f,0.f,0.f,
  615. 0.f,0.f,1.f,0.f,0.f,-1.f,0.f,0.f,0.f,0.f,0.f,1.f);
  616. }
  617. // ------------------------------------------------------------------------------------------------
  618. // Convert the imported data to the internal verbose representation
  619. void ASEImporter::BuildUniqueRepresentation(ASE::Mesh& mesh) {
  620. // allocate output storage
  621. std::vector<aiVector3D> mPositions;
  622. std::vector<aiVector3D> amTexCoords[AI_MAX_NUMBER_OF_TEXTURECOORDS];
  623. std::vector<aiColor4D> mVertexColors;
  624. std::vector<aiVector3D> mNormals;
  625. std::vector<BoneVertex> mBoneVertices;
  626. unsigned int iSize = (unsigned int)mesh.mFaces.size() * 3;
  627. mPositions.resize(iSize);
  628. // optional texture coordinates
  629. for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS;++i) {
  630. if (!mesh.amTexCoords[i].empty()) {
  631. amTexCoords[i].resize(iSize);
  632. }
  633. }
  634. // optional vertex colors
  635. if (!mesh.mVertexColors.empty()) {
  636. mVertexColors.resize(iSize);
  637. }
  638. // optional vertex normals (vertex normals can simply be copied)
  639. if (!mesh.mNormals.empty()) {
  640. mNormals.resize(iSize);
  641. }
  642. // bone vertices. There is no need to change the bone list
  643. if (!mesh.mBoneVertices.empty()) {
  644. mBoneVertices.resize(iSize);
  645. }
  646. // iterate through all faces in the mesh
  647. unsigned int iCurrent = 0, fi = 0;
  648. for (std::vector<ASE::Face>::iterator i = mesh.mFaces.begin();i != mesh.mFaces.end();++i,++fi) {
  649. for (unsigned int n = 0; n < 3;++n,++iCurrent)
  650. {
  651. mPositions[iCurrent] = mesh.mPositions[(*i).mIndices[n]];
  652. // add texture coordinates
  653. for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS;++c) {
  654. if (mesh.amTexCoords[c].empty())break;
  655. amTexCoords[c][iCurrent] = mesh.amTexCoords[c][(*i).amUVIndices[c][n]];
  656. }
  657. // add vertex colors
  658. if (!mesh.mVertexColors.empty()) {
  659. mVertexColors[iCurrent] = mesh.mVertexColors[(*i).mColorIndices[n]];
  660. }
  661. // add normal vectors
  662. if (!mesh.mNormals.empty()) {
  663. mNormals[iCurrent] = mesh.mNormals[fi*3+n];
  664. mNormals[iCurrent].Normalize();
  665. }
  666. // handle bone vertices
  667. if ((*i).mIndices[n] < mesh.mBoneVertices.size()) {
  668. // (sometimes this will cause bone verts to be duplicated
  669. // however, I' quite sure Schrompf' JoinVerticesStep
  670. // will fix that again ...)
  671. mBoneVertices[iCurrent] = mesh.mBoneVertices[(*i).mIndices[n]];
  672. }
  673. (*i).mIndices[n] = iCurrent;
  674. }
  675. }
  676. // replace the old arrays
  677. mesh.mNormals = mNormals;
  678. mesh.mPositions = mPositions;
  679. mesh.mVertexColors = mVertexColors;
  680. for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS;++c)
  681. mesh.amTexCoords[c] = amTexCoords[c];
  682. }
  683. // ------------------------------------------------------------------------------------------------
  684. // Copy a texture from the ASE structs to the output material
  685. void CopyASETexture(aiMaterial& mat, ASE::Texture& texture, aiTextureType type)
  686. {
  687. // Setup the texture name
  688. aiString tex;
  689. tex.Set( texture.mMapName);
  690. mat.AddProperty( &tex, AI_MATKEY_TEXTURE(type,0));
  691. // Setup the texture blend factor
  692. if (is_not_qnan(texture.mTextureBlend))
  693. mat.AddProperty<float>( &texture.mTextureBlend, 1, AI_MATKEY_TEXBLEND(type,0));
  694. // Setup texture UV transformations
  695. mat.AddProperty<float>(&texture.mOffsetU,5,AI_MATKEY_UVTRANSFORM(type,0));
  696. }
  697. // ------------------------------------------------------------------------------------------------
  698. // Convert from ASE material to output material
  699. void ASEImporter::ConvertMaterial(ASE::Material& mat)
  700. {
  701. // LARGE TODO: Much code her is copied from 3DS ... join them maybe?
  702. // Allocate the output material
  703. mat.pcInstance = new aiMaterial();
  704. // At first add the base ambient color of the
  705. // scene to the material
  706. mat.mAmbient.r += mParser->m_clrAmbient.r;
  707. mat.mAmbient.g += mParser->m_clrAmbient.g;
  708. mat.mAmbient.b += mParser->m_clrAmbient.b;
  709. aiString name;
  710. name.Set( mat.mName);
  711. mat.pcInstance->AddProperty( &name, AI_MATKEY_NAME);
  712. // material colors
  713. mat.pcInstance->AddProperty( &mat.mAmbient, 1, AI_MATKEY_COLOR_AMBIENT);
  714. mat.pcInstance->AddProperty( &mat.mDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  715. mat.pcInstance->AddProperty( &mat.mSpecular, 1, AI_MATKEY_COLOR_SPECULAR);
  716. mat.pcInstance->AddProperty( &mat.mEmissive, 1, AI_MATKEY_COLOR_EMISSIVE);
  717. // shininess
  718. if (0.0f != mat.mSpecularExponent && 0.0f != mat.mShininessStrength)
  719. {
  720. mat.pcInstance->AddProperty( &mat.mSpecularExponent, 1, AI_MATKEY_SHININESS);
  721. mat.pcInstance->AddProperty( &mat.mShininessStrength, 1, AI_MATKEY_SHININESS_STRENGTH);
  722. }
  723. // If there is no shininess, we can disable phong lighting
  724. else if (D3DS::Discreet3DS::Metal == mat.mShading ||
  725. D3DS::Discreet3DS::Phong == mat.mShading ||
  726. D3DS::Discreet3DS::Blinn == mat.mShading)
  727. {
  728. mat.mShading = D3DS::Discreet3DS::Gouraud;
  729. }
  730. // opacity
  731. mat.pcInstance->AddProperty<float>( &mat.mTransparency,1,AI_MATKEY_OPACITY);
  732. // Two sided rendering?
  733. if (mat.mTwoSided)
  734. {
  735. int i = 1;
  736. mat.pcInstance->AddProperty<int>(&i,1,AI_MATKEY_TWOSIDED);
  737. }
  738. // shading mode
  739. aiShadingMode eShading = aiShadingMode_NoShading;
  740. switch (mat.mShading)
  741. {
  742. case D3DS::Discreet3DS::Flat:
  743. eShading = aiShadingMode_Flat; break;
  744. case D3DS::Discreet3DS::Phong :
  745. eShading = aiShadingMode_Phong; break;
  746. case D3DS::Discreet3DS::Blinn :
  747. eShading = aiShadingMode_Blinn; break;
  748. // I don't know what "Wire" shading should be,
  749. // assume it is simple lambertian diffuse (L dot N) shading
  750. case D3DS::Discreet3DS::Wire:
  751. {
  752. // set the wireframe flag
  753. unsigned int iWire = 1;
  754. mat.pcInstance->AddProperty<int>( (int*)&iWire,1,AI_MATKEY_ENABLE_WIREFRAME);
  755. }
  756. case D3DS::Discreet3DS::Gouraud:
  757. eShading = aiShadingMode_Gouraud; break;
  758. case D3DS::Discreet3DS::Metal :
  759. eShading = aiShadingMode_CookTorrance; break;
  760. }
  761. mat.pcInstance->AddProperty<int>( (int*)&eShading,1,AI_MATKEY_SHADING_MODEL);
  762. // DIFFUSE texture
  763. if( mat.sTexDiffuse.mMapName.length() > 0)
  764. CopyASETexture(*mat.pcInstance,mat.sTexDiffuse, aiTextureType_DIFFUSE);
  765. // SPECULAR texture
  766. if( mat.sTexSpecular.mMapName.length() > 0)
  767. CopyASETexture(*mat.pcInstance,mat.sTexSpecular, aiTextureType_SPECULAR);
  768. // AMBIENT texture
  769. if( mat.sTexAmbient.mMapName.length() > 0)
  770. CopyASETexture(*mat.pcInstance,mat.sTexAmbient, aiTextureType_AMBIENT);
  771. // OPACITY texture
  772. if( mat.sTexOpacity.mMapName.length() > 0)
  773. CopyASETexture(*mat.pcInstance,mat.sTexOpacity, aiTextureType_OPACITY);
  774. // EMISSIVE texture
  775. if( mat.sTexEmissive.mMapName.length() > 0)
  776. CopyASETexture(*mat.pcInstance,mat.sTexEmissive, aiTextureType_EMISSIVE);
  777. // BUMP texture
  778. if( mat.sTexBump.mMapName.length() > 0)
  779. CopyASETexture(*mat.pcInstance,mat.sTexBump, aiTextureType_HEIGHT);
  780. // SHININESS texture
  781. if( mat.sTexShininess.mMapName.length() > 0)
  782. CopyASETexture(*mat.pcInstance,mat.sTexShininess, aiTextureType_SHININESS);
  783. // store the name of the material itself, too
  784. if( mat.mName.length() > 0) {
  785. aiString tex;tex.Set( mat.mName);
  786. mat.pcInstance->AddProperty( &tex, AI_MATKEY_NAME);
  787. }
  788. return;
  789. }
  790. // ------------------------------------------------------------------------------------------------
  791. // Build output meshes
  792. void ASEImporter::ConvertMeshes(ASE::Mesh& mesh, std::vector<aiMesh*>& avOutMeshes)
  793. {
  794. // validate the material index of the mesh
  795. if (mesh.iMaterialIndex >= mParser->m_vMaterials.size()) {
  796. mesh.iMaterialIndex = (unsigned int)mParser->m_vMaterials.size()-1;
  797. DefaultLogger::get()->warn("Material index is out of range");
  798. }
  799. // If the material the mesh is assigned to is consisting of submeshes, split it
  800. if (!mParser->m_vMaterials[mesh.iMaterialIndex].avSubMaterials.empty()) {
  801. std::vector<ASE::Material> vSubMaterials = mParser->
  802. m_vMaterials[mesh.iMaterialIndex].avSubMaterials;
  803. std::vector<unsigned int>* aiSplit = new std::vector<unsigned int>[vSubMaterials.size()];
  804. // build a list of all faces per submaterial
  805. for (unsigned int i = 0; i < mesh.mFaces.size();++i) {
  806. // check range
  807. if (mesh.mFaces[i].iMaterial >= vSubMaterials.size()) {
  808. DefaultLogger::get()->warn("Submaterial index is out of range");
  809. // use the last material instead
  810. aiSplit[vSubMaterials.size()-1].push_back(i);
  811. }
  812. else aiSplit[mesh.mFaces[i].iMaterial].push_back(i);
  813. }
  814. // now generate submeshes
  815. for (unsigned int p = 0; p < vSubMaterials.size();++p) {
  816. if (!aiSplit[p].empty()) {
  817. aiMesh* p_pcOut = new aiMesh();
  818. p_pcOut->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  819. // let the sub material index
  820. p_pcOut->mMaterialIndex = p;
  821. // we will need this material
  822. mParser->m_vMaterials[mesh.iMaterialIndex].avSubMaterials[p].bNeed = true;
  823. // store the real index here ... color channel 3
  824. p_pcOut->mColors[3] = (aiColor4D*)(uintptr_t)mesh.iMaterialIndex;
  825. // store a pointer to the mesh in color channel 2
  826. p_pcOut->mColors[2] = (aiColor4D*) &mesh;
  827. avOutMeshes.push_back(p_pcOut);
  828. // convert vertices
  829. p_pcOut->mNumVertices = (unsigned int)aiSplit[p].size()*3;
  830. p_pcOut->mNumFaces = (unsigned int)aiSplit[p].size();
  831. // receive output vertex weights
  832. std::vector<std::pair<unsigned int, float> > *avOutputBones = NULL;
  833. if (!mesh.mBones.empty()) {
  834. avOutputBones = new std::vector<std::pair<unsigned int, float> >[mesh.mBones.size()];
  835. }
  836. // allocate enough storage for faces
  837. p_pcOut->mFaces = new aiFace[p_pcOut->mNumFaces];
  838. unsigned int iBase = 0,iIndex;
  839. if (p_pcOut->mNumVertices) {
  840. p_pcOut->mVertices = new aiVector3D[p_pcOut->mNumVertices];
  841. p_pcOut->mNormals = new aiVector3D[p_pcOut->mNumVertices];
  842. for (unsigned int q = 0; q < aiSplit[p].size();++q) {
  843. iIndex = aiSplit[p][q];
  844. p_pcOut->mFaces[q].mIndices = new unsigned int[3];
  845. p_pcOut->mFaces[q].mNumIndices = 3;
  846. for (unsigned int t = 0; t < 3;++t, ++iBase) {
  847. const uint32_t iIndex2 = mesh.mFaces[iIndex].mIndices[t];
  848. p_pcOut->mVertices[iBase] = mesh.mPositions [iIndex2];
  849. p_pcOut->mNormals [iBase] = mesh.mNormals [iIndex2];
  850. // convert bones, if existing
  851. if (!mesh.mBones.empty()) {
  852. // check whether there is a vertex weight for this vertex index
  853. if (iIndex2 < mesh.mBoneVertices.size()) {
  854. for (std::vector<std::pair<int,float> >::const_iterator
  855. blubb = mesh.mBoneVertices[iIndex2].mBoneWeights.begin();
  856. blubb != mesh.mBoneVertices[iIndex2].mBoneWeights.end();++blubb) {
  857. // NOTE: illegal cases have already been filtered out
  858. avOutputBones[(*blubb).first].push_back(std::pair<unsigned int, float>(
  859. iBase,(*blubb).second));
  860. }
  861. }
  862. }
  863. p_pcOut->mFaces[q].mIndices[t] = iBase;
  864. }
  865. }
  866. }
  867. // convert texture coordinates (up to AI_MAX_NUMBER_OF_TEXTURECOORDS sets supported)
  868. for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS;++c) {
  869. if (!mesh.amTexCoords[c].empty())
  870. {
  871. p_pcOut->mTextureCoords[c] = new aiVector3D[p_pcOut->mNumVertices];
  872. iBase = 0;
  873. for (unsigned int q = 0; q < aiSplit[p].size();++q) {
  874. iIndex = aiSplit[p][q];
  875. for (unsigned int t = 0; t < 3;++t) {
  876. p_pcOut->mTextureCoords[c][iBase++] = mesh.amTexCoords[c][mesh.mFaces[iIndex].mIndices[t]];
  877. }
  878. }
  879. // Setup the number of valid vertex components
  880. p_pcOut->mNumUVComponents[c] = mesh.mNumUVComponents[c];
  881. }
  882. }
  883. // Convert vertex colors (only one set supported)
  884. if (!mesh.mVertexColors.empty()){
  885. p_pcOut->mColors[0] = new aiColor4D[p_pcOut->mNumVertices];
  886. iBase = 0;
  887. for (unsigned int q = 0; q < aiSplit[p].size();++q) {
  888. iIndex = aiSplit[p][q];
  889. for (unsigned int t = 0; t < 3;++t) {
  890. p_pcOut->mColors[0][iBase++] = mesh.mVertexColors[mesh.mFaces[iIndex].mIndices[t]];
  891. }
  892. }
  893. }
  894. // Copy bones
  895. if (!mesh.mBones.empty()) {
  896. p_pcOut->mNumBones = 0;
  897. for (unsigned int mrspock = 0; mrspock < mesh.mBones.size();++mrspock)
  898. if (!avOutputBones[mrspock].empty())p_pcOut->mNumBones++;
  899. p_pcOut->mBones = new aiBone* [ p_pcOut->mNumBones ];
  900. aiBone** pcBone = p_pcOut->mBones;
  901. for (unsigned int mrspock = 0; mrspock < mesh.mBones.size();++mrspock)
  902. {
  903. if (!avOutputBones[mrspock].empty()) {
  904. // we will need this bone. add it to the output mesh and
  905. // add all per-vertex weights
  906. aiBone* pc = *pcBone = new aiBone();
  907. pc->mName.Set(mesh.mBones[mrspock].mName);
  908. pc->mNumWeights = (unsigned int)avOutputBones[mrspock].size();
  909. pc->mWeights = new aiVertexWeight[pc->mNumWeights];
  910. for (unsigned int captainkirk = 0; captainkirk < pc->mNumWeights;++captainkirk)
  911. {
  912. const std::pair<unsigned int,float>& ref = avOutputBones[mrspock][captainkirk];
  913. pc->mWeights[captainkirk].mVertexId = ref.first;
  914. pc->mWeights[captainkirk].mWeight = ref.second;
  915. }
  916. ++pcBone;
  917. }
  918. }
  919. // delete allocated storage
  920. delete[] avOutputBones;
  921. }
  922. }
  923. }
  924. // delete storage
  925. delete[] aiSplit;
  926. }
  927. else
  928. {
  929. // Otherwise we can simply copy the data to one output mesh
  930. // This codepath needs less memory and uses fast memcpy()s
  931. // to do the actual copying. So I think it is worth the
  932. // effort here.
  933. aiMesh* p_pcOut = new aiMesh();
  934. p_pcOut->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  935. // set an empty sub material index
  936. p_pcOut->mMaterialIndex = ASE::Face::DEFAULT_MATINDEX;
  937. mParser->m_vMaterials[mesh.iMaterialIndex].bNeed = true;
  938. // store the real index here ... in color channel 3
  939. p_pcOut->mColors[3] = (aiColor4D*)(uintptr_t)mesh.iMaterialIndex;
  940. // store a pointer to the mesh in color channel 2
  941. p_pcOut->mColors[2] = (aiColor4D*) &mesh;
  942. avOutMeshes.push_back(p_pcOut);
  943. // If the mesh hasn't faces or vertices, there are two cases
  944. // possible: 1. the model is invalid. 2. This is a dummy
  945. // helper object which we are going to remove later ...
  946. if (mesh.mFaces.empty() || mesh.mPositions.empty()) {
  947. return;
  948. }
  949. // convert vertices
  950. p_pcOut->mNumVertices = (unsigned int)mesh.mPositions.size();
  951. p_pcOut->mNumFaces = (unsigned int)mesh.mFaces.size();
  952. // allocate enough storage for faces
  953. p_pcOut->mFaces = new aiFace[p_pcOut->mNumFaces];
  954. // copy vertices
  955. p_pcOut->mVertices = new aiVector3D[mesh.mPositions.size()];
  956. memcpy(p_pcOut->mVertices,&mesh.mPositions[0],
  957. mesh.mPositions.size() * sizeof(aiVector3D));
  958. // copy normals
  959. p_pcOut->mNormals = new aiVector3D[mesh.mNormals.size()];
  960. memcpy(p_pcOut->mNormals,&mesh.mNormals[0],
  961. mesh.mNormals.size() * sizeof(aiVector3D));
  962. // copy texture coordinates
  963. for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS;++c) {
  964. if (!mesh.amTexCoords[c].empty()) {
  965. p_pcOut->mTextureCoords[c] = new aiVector3D[mesh.amTexCoords[c].size()];
  966. memcpy(p_pcOut->mTextureCoords[c],&mesh.amTexCoords[c][0],
  967. mesh.amTexCoords[c].size() * sizeof(aiVector3D));
  968. // setup the number of valid vertex components
  969. p_pcOut->mNumUVComponents[c] = mesh.mNumUVComponents[c];
  970. }
  971. }
  972. // copy vertex colors
  973. if (!mesh.mVertexColors.empty()) {
  974. p_pcOut->mColors[0] = new aiColor4D[mesh.mVertexColors.size()];
  975. memcpy(p_pcOut->mColors[0],&mesh.mVertexColors[0],
  976. mesh.mVertexColors.size() * sizeof(aiColor4D));
  977. }
  978. // copy faces
  979. for (unsigned int iFace = 0; iFace < p_pcOut->mNumFaces;++iFace) {
  980. p_pcOut->mFaces[iFace].mNumIndices = 3;
  981. p_pcOut->mFaces[iFace].mIndices = new unsigned int[3];
  982. // copy indices
  983. p_pcOut->mFaces[iFace].mIndices[0] = mesh.mFaces[iFace].mIndices[0];
  984. p_pcOut->mFaces[iFace].mIndices[1] = mesh.mFaces[iFace].mIndices[1];
  985. p_pcOut->mFaces[iFace].mIndices[2] = mesh.mFaces[iFace].mIndices[2];
  986. }
  987. // copy vertex bones
  988. if (!mesh.mBones.empty() && !mesh.mBoneVertices.empty()) {
  989. std::vector<std::vector<aiVertexWeight> > avBonesOut( mesh.mBones.size() );
  990. // find all vertex weights for this bone
  991. unsigned int quak = 0;
  992. for (std::vector<BoneVertex>::const_iterator harrypotter = mesh.mBoneVertices.begin();
  993. harrypotter != mesh.mBoneVertices.end();++harrypotter,++quak) {
  994. for (std::vector<std::pair<int,float> >::const_iterator
  995. ronaldweasley = (*harrypotter).mBoneWeights.begin();
  996. ronaldweasley != (*harrypotter).mBoneWeights.end();++ronaldweasley)
  997. {
  998. aiVertexWeight weight;
  999. weight.mVertexId = quak;
  1000. weight.mWeight = (*ronaldweasley).second;
  1001. avBonesOut[(*ronaldweasley).first].push_back(weight);
  1002. }
  1003. }
  1004. // now build a final bone list
  1005. p_pcOut->mNumBones = 0;
  1006. for (unsigned int jfkennedy = 0; jfkennedy < mesh.mBones.size();++jfkennedy)
  1007. if (!avBonesOut[jfkennedy].empty())p_pcOut->mNumBones++;
  1008. p_pcOut->mBones = new aiBone*[p_pcOut->mNumBones];
  1009. aiBone** pcBone = p_pcOut->mBones;
  1010. for (unsigned int jfkennedy = 0; jfkennedy < mesh.mBones.size();++jfkennedy) {
  1011. if (!avBonesOut[jfkennedy].empty()) {
  1012. aiBone* pc = *pcBone = new aiBone();
  1013. pc->mName.Set(mesh.mBones[jfkennedy].mName);
  1014. pc->mNumWeights = (unsigned int)avBonesOut[jfkennedy].size();
  1015. pc->mWeights = new aiVertexWeight[pc->mNumWeights];
  1016. ::memcpy(pc->mWeights,&avBonesOut[jfkennedy][0],
  1017. sizeof(aiVertexWeight) * pc->mNumWeights);
  1018. ++pcBone;
  1019. }
  1020. }
  1021. }
  1022. }
  1023. }
  1024. // ------------------------------------------------------------------------------------------------
  1025. // Setup proper material indices and build output materials
  1026. void ASEImporter::BuildMaterialIndices()
  1027. {
  1028. ai_assert(NULL != pcScene);
  1029. // iterate through all materials and check whether we need them
  1030. for (unsigned int iMat = 0; iMat < mParser->m_vMaterials.size();++iMat)
  1031. {
  1032. ASE::Material& mat = mParser->m_vMaterials[iMat];
  1033. if (mat.bNeed) {
  1034. // Convert it to the aiMaterial layout
  1035. ConvertMaterial(mat);
  1036. ++pcScene->mNumMaterials;
  1037. }
  1038. for (unsigned int iSubMat = 0; iSubMat < mat.avSubMaterials.size();++iSubMat)
  1039. {
  1040. ASE::Material& submat = mat.avSubMaterials[iSubMat];
  1041. if (submat.bNeed) {
  1042. // Convert it to the aiMaterial layout
  1043. ConvertMaterial(submat);
  1044. ++pcScene->mNumMaterials;
  1045. }
  1046. }
  1047. }
  1048. // allocate the output material array
  1049. pcScene->mMaterials = new aiMaterial*[pcScene->mNumMaterials];
  1050. D3DS::Material** pcIntMaterials = new D3DS::Material*[pcScene->mNumMaterials];
  1051. unsigned int iNum = 0;
  1052. for (unsigned int iMat = 0; iMat < mParser->m_vMaterials.size();++iMat) {
  1053. ASE::Material& mat = mParser->m_vMaterials[iMat];
  1054. if (mat.bNeed)
  1055. {
  1056. ai_assert(NULL != mat.pcInstance);
  1057. pcScene->mMaterials[iNum] = mat.pcInstance;
  1058. // Store the internal material, too
  1059. pcIntMaterials[iNum] = &mat;
  1060. // Iterate through all meshes and search for one which is using
  1061. // this top-level material index
  1062. for (unsigned int iMesh = 0; iMesh < pcScene->mNumMeshes;++iMesh)
  1063. {
  1064. aiMesh* mesh = pcScene->mMeshes[iMesh];
  1065. if (ASE::Face::DEFAULT_MATINDEX == mesh->mMaterialIndex &&
  1066. iMat == (uintptr_t)mesh->mColors[3])
  1067. {
  1068. mesh->mMaterialIndex = iNum;
  1069. mesh->mColors[3] = NULL;
  1070. }
  1071. }
  1072. iNum++;
  1073. }
  1074. for (unsigned int iSubMat = 0; iSubMat < mat.avSubMaterials.size();++iSubMat) {
  1075. ASE::Material& submat = mat.avSubMaterials[iSubMat];
  1076. if (submat.bNeed) {
  1077. ai_assert(NULL != submat.pcInstance);
  1078. pcScene->mMaterials[iNum] = submat.pcInstance;
  1079. // Store the internal material, too
  1080. pcIntMaterials[iNum] = &submat;
  1081. // Iterate through all meshes and search for one which is using
  1082. // this sub-level material index
  1083. for (unsigned int iMesh = 0; iMesh < pcScene->mNumMeshes;++iMesh) {
  1084. aiMesh* mesh = pcScene->mMeshes[iMesh];
  1085. if (iSubMat == mesh->mMaterialIndex && iMat == (uintptr_t)mesh->mColors[3]) {
  1086. mesh->mMaterialIndex = iNum;
  1087. mesh->mColors[3] = NULL;
  1088. }
  1089. }
  1090. iNum++;
  1091. }
  1092. }
  1093. }
  1094. // Dekete our temporary array
  1095. delete[] pcIntMaterials;
  1096. }
  1097. // ------------------------------------------------------------------------------------------------
  1098. // Generate normal vectors basing on smoothing groups
  1099. bool ASEImporter::GenerateNormals(ASE::Mesh& mesh) {
  1100. if (!mesh.mNormals.empty() && !configRecomputeNormals)
  1101. {
  1102. // Check whether there are only uninitialized normals. If there are
  1103. // some, skip all normals from the file and compute them on our own
  1104. for (std::vector<aiVector3D>::const_iterator qq = mesh.mNormals.begin();qq != mesh.mNormals.end();++qq) {
  1105. if ((*qq).x || (*qq).y || (*qq).z)
  1106. {
  1107. return true;
  1108. }
  1109. }
  1110. }
  1111. // The array is reused.
  1112. ComputeNormalsWithSmoothingsGroups<ASE::Face>(mesh);
  1113. return false;
  1114. }
  1115. #endif // !! ASSIMP_BUILD_NO_BASE_IMPORTER