ASELoader.cpp 52 KB

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