ASELoader.cpp 53 KB

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