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