ASELoader.cpp 46 KB

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