ASELoader.cpp 46 KB

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