ASELoader.cpp 46 KB

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