ASELoader.cpp 51 KB

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