ASELoader.cpp 52 KB

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