2
0

ASELoader.cpp 52 KB

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