M3DImporter.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2021, assimp team
  5. Copyright (c) 2019 bzt
  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
  9. following 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. #ifndef ASSIMP_BUILD_NO_M3D_IMPORTER
  35. #define M3D_IMPLEMENTATION
  36. #define M3D_NONORMALS /* leave the post-processing to Assimp */
  37. #define M3D_NOWEIGHTS
  38. #define M3D_NOANIMATION
  39. #include <assimp/DefaultIOSystem.h>
  40. #include <assimp/IOStreamBuffer.h>
  41. #include <assimp/ai_assert.h>
  42. #include <assimp/importerdesc.h>
  43. #include <assimp/scene.h>
  44. #include <assimp/DefaultLogger.hpp>
  45. #include <assimp/Importer.hpp>
  46. #include <memory>
  47. #include "M3DImporter.h"
  48. #include "M3DMaterials.h"
  49. #include "M3DWrapper.h"
  50. // RESOURCES:
  51. // https://gitlab.com/bztsrc/model3d/blob/master/docs/m3d_format.md
  52. // https://gitlab.com/bztsrc/model3d/blob/master/docs/a3d_format.md
  53. /*
  54. Unfortunately aiNode has bone structures and meshes too, yet we can't assign
  55. the mesh to a bone aiNode as a skin may refer to several aiNodes. Therefore
  56. I've decided to import into this structure:
  57. aiScene->mRootNode
  58. | |->mMeshes (all the meshes)
  59. | \->children (empty if there's no skeleton imported, no meshes)
  60. | \->skeleton root aiNode*
  61. | |->bone aiNode
  62. | | \->subbone aiNode
  63. | |->bone aiNode
  64. | | ...
  65. | \->bone aiNode
  66. \->mMeshes[]
  67. \->aiBone, referencing mesh-less aiNodes from above
  68. * - normally one, but if a model has several skeleton roots, then all of them
  69. are listed in aiScene->mRootNode->children, but all without meshes
  70. */
  71. static const aiImporterDesc desc = {
  72. "Model 3D Importer",
  73. "",
  74. "",
  75. "",
  76. aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour,
  77. 0,
  78. 0,
  79. 0,
  80. 0,
  81. "m3d a3d"
  82. };
  83. namespace Assimp {
  84. using namespace std;
  85. // ------------------------------------------------------------------------------------------------
  86. // Default constructor
  87. M3DImporter::M3DImporter() :
  88. mScene(nullptr) {
  89. // empty
  90. }
  91. // ------------------------------------------------------------------------------------------------
  92. // Returns true, if file is a binary or ASCII Model 3D file.
  93. bool M3DImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool checkSig) const {
  94. const std::string extension = GetExtension(pFile);
  95. if (extension == "m3d"
  96. || extension == "a3d"
  97. )
  98. return true;
  99. else if (!extension.length() || checkSig) {
  100. if (!pIOHandler) {
  101. return true;
  102. }
  103. /*
  104. * don't use CheckMagicToken because that checks with swapped bytes too, leading to false
  105. * positives. This magic is not uint32_t, but char[4], so memcmp is the best way
  106. const char* tokens[] = {"3DMO", "3dmo"};
  107. return CheckMagicToken(pIOHandler,pFile,tokens,2,0,4);
  108. */
  109. std::unique_ptr<IOStream> pStream(pIOHandler->Open(pFile, "rb"));
  110. unsigned char data[4];
  111. if (!pStream || 4 != pStream->Read(data, 1, 4)) {
  112. return false;
  113. }
  114. return !memcmp(data, "3DMO", 4) /* bin */
  115. || !memcmp(data, "3dmo", 4) /* ASCII */
  116. ;
  117. }
  118. return false;
  119. }
  120. // ------------------------------------------------------------------------------------------------
  121. const aiImporterDesc *M3DImporter::GetInfo() const {
  122. return &desc;
  123. }
  124. // ------------------------------------------------------------------------------------------------
  125. // Model 3D import implementation
  126. void M3DImporter::InternReadFile(const std::string &file, aiScene *pScene, IOSystem *pIOHandler) {
  127. // Read file into memory
  128. std::unique_ptr<IOStream> pStream(pIOHandler->Open(file, "rb"));
  129. if (!pStream.get()) {
  130. throw DeadlyImportError("Failed to open file ", file, ".");
  131. }
  132. // Get the file-size and validate it, throwing an exception when fails
  133. size_t fileSize = pStream->FileSize();
  134. if (fileSize < 8) {
  135. throw DeadlyImportError("M3D-file ", file, " is too small.");
  136. }
  137. std::vector<unsigned char> buffer(fileSize);
  138. if (fileSize != pStream->Read(buffer.data(), 1, fileSize)) {
  139. throw DeadlyImportError("Failed to read the file ", file, ".");
  140. }
  141. // extra check for binary format's first 8 bytes. Not done for the ASCII variant
  142. if (!memcmp(buffer.data(), "3DMO", 4) && memcmp(buffer.data() + 4, &fileSize, 4)) {
  143. throw DeadlyImportError("Bad binary header in file ", file, ".");
  144. }
  145. // make sure there's a terminator zero character, as input must be ASCIIZ
  146. if (!memcmp(buffer.data(), "3dmo", 4)) {
  147. buffer.push_back(0);
  148. }
  149. // Get the path for external assets
  150. std::string folderName("./");
  151. std::string::size_type pos = file.find_last_of("\\/");
  152. if (pos != std::string::npos) {
  153. folderName = file.substr(0, pos);
  154. if (!folderName.empty()) {
  155. pIOHandler->PushDirectory(folderName);
  156. }
  157. }
  158. //DefaultLogger::create("/dev/stderr", Logger::VERBOSE);
  159. ASSIMP_LOG_DEBUG("M3D: loading ", file);
  160. // let the C SDK do the hard work for us
  161. M3DWrapper m3d(pIOHandler, buffer);
  162. if (!m3d) {
  163. throw DeadlyImportError("Unable to parse ", file, " as M3D.");
  164. }
  165. // create the root node
  166. pScene->mRootNode = new aiNode;
  167. pScene->mRootNode->mName = aiString(m3d.Name());
  168. pScene->mRootNode->mTransformation = aiMatrix4x4();
  169. pScene->mRootNode->mNumChildren = 0;
  170. mScene = pScene;
  171. ASSIMP_LOG_DEBUG("M3D: root node ", m3d.Name());
  172. // now we just have to fill up the Assimp structures in pScene
  173. importMaterials(m3d);
  174. importTextures(m3d);
  175. importBones(m3d, M3D_NOTDEFINED, pScene->mRootNode);
  176. importMeshes(m3d);
  177. importAnimations(m3d);
  178. // Pop directory stack
  179. if (pIOHandler->StackSize() > 0) {
  180. pIOHandler->PopDirectory();
  181. }
  182. }
  183. // ------------------------------------------------------------------------------------------------
  184. // convert materials. properties are converted using a static table in M3DMaterials.h
  185. void M3DImporter::importMaterials(const M3DWrapper &m3d) {
  186. unsigned int i, j, k, l, n;
  187. m3dm_t *m;
  188. aiString name = aiString(AI_DEFAULT_MATERIAL_NAME);
  189. aiColor4D c;
  190. ai_real f;
  191. ai_assert(mScene != nullptr);
  192. ai_assert(m3d);
  193. mScene->mNumMaterials = m3d->nummaterial + 1;
  194. mScene->mMaterials = new aiMaterial *[mScene->mNumMaterials];
  195. ASSIMP_LOG_DEBUG("M3D: importMaterials ", mScene->mNumMaterials);
  196. // add a default material as first
  197. aiMaterial *mat = new aiMaterial;
  198. mat->AddProperty(&name, AI_MATKEY_NAME);
  199. c.a = 1.0f;
  200. c.b = c.g = c.r = 0.6f;
  201. mat->AddProperty(&c, 1, AI_MATKEY_COLOR_DIFFUSE);
  202. mScene->mMaterials[0] = mat;
  203. if (!m3d->nummaterial || !m3d->material) {
  204. return;
  205. }
  206. for (i = 0; i < m3d->nummaterial; i++) {
  207. m = &m3d->material[i];
  208. aiMaterial *newMat = new aiMaterial;
  209. name.Set(std::string(m->name));
  210. newMat->AddProperty(&name, AI_MATKEY_NAME);
  211. for (j = 0; j < m->numprop; j++) {
  212. // look up property type
  213. // 0 - 127 scalar values,
  214. // 128 - 255 the same properties but for texture maps
  215. k = 256;
  216. for (l = 0; l < sizeof(m3d_propertytypes) / sizeof(m3d_propertytypes[0]); l++)
  217. if (m->prop[j].type == m3d_propertytypes[l].id ||
  218. m->prop[j].type == m3d_propertytypes[l].id + 128) {
  219. k = l;
  220. break;
  221. }
  222. // should never happen, but be safe than sorry
  223. if (k == 256)
  224. continue;
  225. // scalar properties
  226. if (m->prop[j].type < 128 && aiProps[k].pKey) {
  227. switch (m3d_propertytypes[k].format) {
  228. case m3dpf_color:
  229. c = mkColor(m->prop[j].value.color);
  230. newMat->AddProperty(&c, 1, aiProps[k].pKey, aiProps[k].type, aiProps[k].index);
  231. break;
  232. case m3dpf_float:
  233. f = m->prop[j].value.fnum;
  234. newMat->AddProperty(&f, 1, aiProps[k].pKey, aiProps[k].type, aiProps[k].index);
  235. break;
  236. default:
  237. n = m->prop[j].value.num;
  238. if (m->prop[j].type == m3dp_il) {
  239. switch (n) {
  240. case 0:
  241. n = aiShadingMode_NoShading;
  242. break;
  243. case 2:
  244. n = aiShadingMode_Phong;
  245. break;
  246. default:
  247. n = aiShadingMode_Gouraud;
  248. break;
  249. }
  250. }
  251. newMat->AddProperty(&n, 1, aiProps[k].pKey, aiProps[k].type, aiProps[k].index);
  252. break;
  253. }
  254. }
  255. // texture map properties
  256. if (m->prop[j].type >= 128 && aiTxProps[k].pKey &&
  257. // extra check, should never happen, do we have the refered texture?
  258. m->prop[j].value.textureid < m3d->numtexture &&
  259. m3d->texture[m->prop[j].value.textureid].name) {
  260. name.Set(std::string(std::string(m3d->texture[m->prop[j].value.textureid].name) + ".png"));
  261. mat->AddProperty(&name, aiTxProps[k].pKey, aiTxProps[k].type, aiTxProps[k].index);
  262. n = 0;
  263. mat->AddProperty(&n, 1, _AI_MATKEY_UVWSRC_BASE, aiProps[k].type, aiProps[k].index);
  264. }
  265. }
  266. mScene->mMaterials[i + 1] = mat;
  267. }
  268. }
  269. // ------------------------------------------------------------------------------------------------
  270. // import textures, this is the simplest of all
  271. void M3DImporter::importTextures(const M3DWrapper &m3d) {
  272. unsigned int i;
  273. const char *formatHint[] = {
  274. "rgba0800",
  275. "rgba0808",
  276. "rgba8880",
  277. "rgba8888"
  278. };
  279. m3dtx_t *t;
  280. ai_assert(mScene != nullptr);
  281. ai_assert(m3d);
  282. mScene->mNumTextures = m3d->numtexture;
  283. ASSIMP_LOG_DEBUG("M3D: importTextures ", mScene->mNumTextures);
  284. if (!m3d->numtexture || !m3d->texture) {
  285. return;
  286. }
  287. mScene->mTextures = new aiTexture *[m3d->numtexture];
  288. for (i = 0; i < m3d->numtexture; i++) {
  289. unsigned int j, k;
  290. t = &m3d->texture[i];
  291. aiTexture *tx = new aiTexture;
  292. tx->mFilename = aiString(std::string(t->name) + ".png");
  293. if (!t->w || !t->h || !t->f || !t->d) {
  294. /* without ASSIMP_USE_M3D_READFILECB, we only have the filename, but no texture data ever */
  295. tx->mWidth = 0;
  296. tx->mHeight = 0;
  297. memcpy(tx->achFormatHint, "png\000", 4);
  298. tx->pcData = nullptr;
  299. } else {
  300. /* if we have the texture loaded, set format hint and pcData too */
  301. tx->mWidth = t->w;
  302. tx->mHeight = t->h;
  303. strcpy(tx->achFormatHint, formatHint[t->f - 1]);
  304. tx->pcData = new aiTexel[tx->mWidth * tx->mHeight];
  305. for (j = k = 0; j < tx->mWidth * tx->mHeight; j++) {
  306. switch (t->f) {
  307. case 1: tx->pcData[j].g = t->d[k++]; break;
  308. case 2:
  309. tx->pcData[j].g = t->d[k++];
  310. tx->pcData[j].a = t->d[k++];
  311. break;
  312. case 3:
  313. tx->pcData[j].r = t->d[k++];
  314. tx->pcData[j].g = t->d[k++];
  315. tx->pcData[j].b = t->d[k++];
  316. tx->pcData[j].a = 255;
  317. break;
  318. case 4:
  319. tx->pcData[j].r = t->d[k++];
  320. tx->pcData[j].g = t->d[k++];
  321. tx->pcData[j].b = t->d[k++];
  322. tx->pcData[j].a = t->d[k++];
  323. break;
  324. }
  325. }
  326. }
  327. mScene->mTextures[i] = tx;
  328. }
  329. }
  330. // ------------------------------------------------------------------------------------------------
  331. // this is tricky. M3D has a global vertex and UV list, and faces are indexing them
  332. // individually. In assimp there're per mesh vertex and UV lists, and they must be
  333. // indexed simultaneously.
  334. void M3DImporter::importMeshes(const M3DWrapper &m3d) {
  335. ASSIMP_LOG_DEBUG("M3D: importMeshes ", m3d->numface);
  336. if (!m3d->numface || !m3d->face || !m3d->numvertex || !m3d->vertex) {
  337. return;
  338. }
  339. unsigned int i, j, k, l, numpoly = 3, lastMat = M3D_INDEXMAX;
  340. std::vector<aiMesh *> *meshes = new std::vector<aiMesh *>();
  341. std::vector<aiFace> *faces = nullptr;
  342. std::vector<aiVector3D> *vertices = nullptr;
  343. std::vector<aiVector3D> *normals = nullptr;
  344. std::vector<aiVector3D> *texcoords = nullptr;
  345. std::vector<aiColor4D> *colors = nullptr;
  346. std::vector<unsigned int> *vertexids = nullptr;
  347. aiMesh *pMesh = nullptr;
  348. ai_assert(mScene != nullptr);
  349. ai_assert(m3d);
  350. ai_assert(mScene->mRootNode != nullptr);
  351. for (i = 0; i < m3d->numface; i++) {
  352. // we must switch mesh if material changes
  353. if (lastMat != m3d->face[i].materialid) {
  354. lastMat = m3d->face[i].materialid;
  355. if (pMesh && vertices && vertices->size() && faces && faces->size()) {
  356. populateMesh(m3d, pMesh, faces, vertices, normals, texcoords, colors, vertexids);
  357. meshes->push_back(pMesh);
  358. delete faces;
  359. delete vertices;
  360. delete normals;
  361. delete texcoords;
  362. delete colors;
  363. delete vertexids; // this is not stored in pMesh, just to collect bone vertices
  364. }
  365. pMesh = new aiMesh;
  366. pMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  367. pMesh->mMaterialIndex = lastMat + 1;
  368. faces = new std::vector<aiFace>();
  369. vertices = new std::vector<aiVector3D>();
  370. normals = new std::vector<aiVector3D>();
  371. texcoords = new std::vector<aiVector3D>();
  372. colors = new std::vector<aiColor4D>();
  373. vertexids = new std::vector<unsigned int>();
  374. }
  375. // add a face to temporary vector
  376. aiFace *pFace = new aiFace;
  377. pFace->mNumIndices = numpoly;
  378. pFace->mIndices = new unsigned int[numpoly];
  379. for (j = 0; j < numpoly; j++) {
  380. aiVector3D pos, uv, norm;
  381. k = static_cast<unsigned int>(vertices->size());
  382. pFace->mIndices[j] = k;
  383. l = m3d->face[i].vertex[j];
  384. if (l >= m3d->numvertex) continue;
  385. pos.x = m3d->vertex[l].x;
  386. pos.y = m3d->vertex[l].y;
  387. pos.z = m3d->vertex[l].z;
  388. vertices->push_back(pos);
  389. colors->push_back(mkColor(m3d->vertex[l].color));
  390. // add a bone to temporary vector
  391. if (m3d->vertex[l].skinid != M3D_UNDEF && m3d->vertex[l].skinid != M3D_INDEXMAX && m3d->skin && m3d->bone) {
  392. // this is complicated, because M3D stores a list of bone id / weight pairs per
  393. // vertex but assimp uses lists of local vertex id/weight pairs per local bone list
  394. vertexids->push_back(l);
  395. }
  396. l = m3d->face[i].texcoord[j];
  397. if (l != M3D_UNDEF && l < m3d->numtmap) {
  398. uv.x = m3d->tmap[l].u;
  399. uv.y = m3d->tmap[l].v;
  400. uv.z = 0.0;
  401. texcoords->push_back(uv);
  402. }
  403. l = m3d->face[i].normal[j];
  404. if (l != M3D_UNDEF && l < m3d->numvertex) {
  405. norm.x = m3d->vertex[l].x;
  406. norm.y = m3d->vertex[l].y;
  407. norm.z = m3d->vertex[l].z;
  408. normals->push_back(norm);
  409. }
  410. }
  411. faces->push_back(*pFace);
  412. delete pFace;
  413. }
  414. // if there's data left in the temporary vectors, flush them
  415. if (pMesh && vertices->size() && faces->size()) {
  416. populateMesh(m3d, pMesh, faces, vertices, normals, texcoords, colors, vertexids);
  417. meshes->push_back(pMesh);
  418. }
  419. // create global mesh list in scene
  420. mScene->mNumMeshes = static_cast<unsigned int>(meshes->size());
  421. mScene->mMeshes = new aiMesh *[mScene->mNumMeshes];
  422. std::copy(meshes->begin(), meshes->end(), mScene->mMeshes);
  423. // create mesh indeces in root node
  424. mScene->mRootNode->mNumMeshes = static_cast<unsigned int>(meshes->size());
  425. mScene->mRootNode->mMeshes = new unsigned int[meshes->size()];
  426. for (i = 0; i < meshes->size(); i++) {
  427. mScene->mRootNode->mMeshes[i] = i;
  428. }
  429. delete meshes;
  430. if (faces) delete faces;
  431. if (vertices) delete vertices;
  432. if (normals) delete normals;
  433. if (texcoords) delete texcoords;
  434. if (colors) delete colors;
  435. if (vertexids) delete vertexids;
  436. }
  437. // ------------------------------------------------------------------------------------------------
  438. // a reentrant node parser. Otherwise this is simple
  439. void M3DImporter::importBones(const M3DWrapper &m3d, unsigned int parentid, aiNode *pParent) {
  440. unsigned int i, n;
  441. ai_assert(pParent != nullptr);
  442. ai_assert(mScene != nullptr);
  443. ai_assert(m3d);
  444. ASSIMP_LOG_DEBUG("M3D: importBones ", m3d->numbone, " parentid ", (int)parentid);
  445. if (!m3d->numbone || !m3d->bone) {
  446. return;
  447. }
  448. for (n = 0, i = parentid + 1; i < m3d->numbone; i++) {
  449. if (m3d->bone[i].parent == parentid) {
  450. n++;
  451. }
  452. }
  453. pParent->mChildren = new aiNode *[n];
  454. for (i = parentid + 1; i < m3d->numbone; i++) {
  455. if (m3d->bone[i].parent == parentid) {
  456. aiNode *pChild = new aiNode;
  457. pChild->mParent = pParent;
  458. pChild->mName = aiString(std::string(m3d->bone[i].name));
  459. convertPose(m3d, &pChild->mTransformation, m3d->bone[i].pos, m3d->bone[i].ori);
  460. pChild->mNumChildren = 0;
  461. pParent->mChildren[pParent->mNumChildren] = pChild;
  462. pParent->mNumChildren++;
  463. importBones(m3d, i, pChild);
  464. }
  465. }
  466. }
  467. // ------------------------------------------------------------------------------------------------
  468. // this is another headache. M3D stores list of changed bone id/position/orientation triplets and
  469. // a timestamp per frame, but assimp needs timestamp and lists of position, orientation lists per
  470. // bone, so we have to convert between the two conceptually different representation forms
  471. void M3DImporter::importAnimations(const M3DWrapper &m3d) {
  472. unsigned int i, j, k, l, pos, ori;
  473. double t;
  474. m3da_t *a;
  475. ai_assert(mScene != nullptr);
  476. ai_assert(m3d);
  477. mScene->mNumAnimations = m3d->numaction;
  478. ASSIMP_LOG_DEBUG("M3D: importAnimations ", mScene->mNumAnimations);
  479. if (!m3d->numaction || !m3d->action || !m3d->numbone || !m3d->bone || !m3d->vertex) {
  480. return;
  481. }
  482. mScene->mAnimations = new aiAnimation *[m3d->numaction];
  483. for (i = 0; i < m3d->numaction; i++) {
  484. a = &m3d->action[i];
  485. aiAnimation *pAnim = new aiAnimation;
  486. pAnim->mName = aiString(std::string(a->name));
  487. pAnim->mDuration = ((double)a->durationmsec) / 10;
  488. pAnim->mTicksPerSecond = 100;
  489. // now we know how many bones are referenced in this animation
  490. pAnim->mNumChannels = m3d->numbone;
  491. pAnim->mChannels = new aiNodeAnim *[pAnim->mNumChannels];
  492. for (l = 0; l < m3d->numbone; l++) {
  493. unsigned int n;
  494. pAnim->mChannels[l] = new aiNodeAnim;
  495. pAnim->mChannels[l]->mNodeName = aiString(std::string(m3d->bone[l].name));
  496. // now n is the size of positions / orientations arrays
  497. pAnim->mChannels[l]->mNumPositionKeys = pAnim->mChannels[l]->mNumRotationKeys = a->numframe;
  498. pAnim->mChannels[l]->mPositionKeys = new aiVectorKey[a->numframe];
  499. pAnim->mChannels[l]->mRotationKeys = new aiQuatKey[a->numframe];
  500. pos = m3d->bone[l].pos;
  501. ori = m3d->bone[l].ori;
  502. for (j = n = 0; j < a->numframe; j++) {
  503. t = ((double)a->frame[j].msec) / 10;
  504. for (k = 0; k < a->frame[j].numtransform; k++) {
  505. if (a->frame[j].transform[k].boneid == l) {
  506. pos = a->frame[j].transform[k].pos;
  507. ori = a->frame[j].transform[k].ori;
  508. }
  509. }
  510. if (pos >= m3d->numvertex || ori >= m3d->numvertex) continue;
  511. m3dv_t *v = &m3d->vertex[pos];
  512. m3dv_t *q = &m3d->vertex[ori];
  513. pAnim->mChannels[l]->mPositionKeys[j].mTime = t;
  514. pAnim->mChannels[l]->mPositionKeys[j].mValue.x = v->x;
  515. pAnim->mChannels[l]->mPositionKeys[j].mValue.y = v->y;
  516. pAnim->mChannels[l]->mPositionKeys[j].mValue.z = v->z;
  517. pAnim->mChannels[l]->mRotationKeys[j].mTime = t;
  518. pAnim->mChannels[l]->mRotationKeys[j].mValue.w = q->w;
  519. pAnim->mChannels[l]->mRotationKeys[j].mValue.x = q->x;
  520. pAnim->mChannels[l]->mRotationKeys[j].mValue.y = q->y;
  521. pAnim->mChannels[l]->mRotationKeys[j].mValue.z = q->z;
  522. } // foreach frame
  523. } // foreach bones
  524. mScene->mAnimations[i] = pAnim;
  525. }
  526. }
  527. // ------------------------------------------------------------------------------------------------
  528. // convert uint32_t into aiColor4D
  529. aiColor4D M3DImporter::mkColor(uint32_t c) {
  530. aiColor4D color;
  531. color.a = ((float)((c >> 24) & 0xff)) / 255;
  532. color.b = ((float)((c >> 16) & 0xff)) / 255;
  533. color.g = ((float)((c >> 8) & 0xff)) / 255;
  534. color.r = ((float)((c >> 0) & 0xff)) / 255;
  535. return color;
  536. }
  537. // ------------------------------------------------------------------------------------------------
  538. // convert a position id and orientation id into a 4 x 4 transformation matrix
  539. void M3DImporter::convertPose(const M3DWrapper &m3d, aiMatrix4x4 *m, unsigned int posid, unsigned int orientid) {
  540. ai_assert(m != nullptr);
  541. ai_assert(m3d);
  542. ai_assert(posid != M3D_UNDEF);
  543. ai_assert(posid < m3d->numvertex);
  544. ai_assert(orientid != M3D_UNDEF);
  545. ai_assert(orientid < m3d->numvertex);
  546. if (!m3d->numvertex || !m3d->vertex)
  547. return;
  548. m3dv_t *p = &m3d->vertex[posid];
  549. m3dv_t *q = &m3d->vertex[orientid];
  550. /* quaternion to matrix. Do NOT use aiQuaternion to aiMatrix3x3, gives bad results */
  551. if (q->x == 0.0 && q->y == 0.0 && q->z >= 0.7071065 && q->z <= 0.7071075 && q->w == 0.0) {
  552. m->a2 = m->a3 = m->b1 = m->b3 = m->c1 = m->c2 = 0.0;
  553. m->a1 = m->b2 = m->c3 = -1.0;
  554. } else {
  555. m->a1 = 1 - 2 * (q->y * q->y + q->z * q->z);
  556. if (m->a1 > -M3D_EPSILON && m->a1 < M3D_EPSILON) m->a1 = 0.0;
  557. m->a2 = 2 * (q->x * q->y - q->z * q->w);
  558. if (m->a2 > -M3D_EPSILON && m->a2 < M3D_EPSILON) m->a2 = 0.0;
  559. m->a3 = 2 * (q->x * q->z + q->y * q->w);
  560. if (m->a3 > -M3D_EPSILON && m->a3 < M3D_EPSILON) m->a3 = 0.0;
  561. m->b1 = 2 * (q->x * q->y + q->z * q->w);
  562. if (m->b1 > -M3D_EPSILON && m->b1 < M3D_EPSILON) m->b1 = 0.0;
  563. m->b2 = 1 - 2 * (q->x * q->x + q->z * q->z);
  564. if (m->b2 > -M3D_EPSILON && m->b2 < M3D_EPSILON) m->b2 = 0.0;
  565. m->b3 = 2 * (q->y * q->z - q->x * q->w);
  566. if (m->b3 > -M3D_EPSILON && m->b3 < M3D_EPSILON) m->b3 = 0.0;
  567. m->c1 = 2 * (q->x * q->z - q->y * q->w);
  568. if (m->c1 > -M3D_EPSILON && m->c1 < M3D_EPSILON) m->c1 = 0.0;
  569. m->c2 = 2 * (q->y * q->z + q->x * q->w);
  570. if (m->c2 > -M3D_EPSILON && m->c2 < M3D_EPSILON) m->c2 = 0.0;
  571. m->c3 = 1 - 2 * (q->x * q->x + q->y * q->y);
  572. if (m->c3 > -M3D_EPSILON && m->c3 < M3D_EPSILON) m->c3 = 0.0;
  573. }
  574. /* set translation */
  575. m->a4 = p->x;
  576. m->b4 = p->y;
  577. m->c4 = p->z;
  578. m->d1 = 0;
  579. m->d2 = 0;
  580. m->d3 = 0;
  581. m->d4 = 1;
  582. }
  583. // ------------------------------------------------------------------------------------------------
  584. // find a node by name
  585. aiNode *M3DImporter::findNode(aiNode *pNode, aiString name) {
  586. ai_assert(pNode != nullptr);
  587. ai_assert(mScene != nullptr);
  588. if (pNode->mName == name) {
  589. return pNode;
  590. }
  591. for (unsigned int i = 0; i < pNode->mNumChildren; i++) {
  592. aiNode *pChild = findNode(pNode->mChildren[i], name);
  593. if (pChild) {
  594. return pChild;
  595. }
  596. }
  597. return nullptr;
  598. }
  599. // ------------------------------------------------------------------------------------------------
  600. // fills up offsetmatrix in mBones
  601. void M3DImporter::calculateOffsetMatrix(aiNode *pNode, aiMatrix4x4 *m) {
  602. ai_assert(pNode != nullptr);
  603. ai_assert(mScene != nullptr);
  604. if (pNode->mParent) {
  605. calculateOffsetMatrix(pNode->mParent, m);
  606. *m *= pNode->mTransformation;
  607. } else {
  608. *m = pNode->mTransformation;
  609. }
  610. }
  611. // ------------------------------------------------------------------------------------------------
  612. // because M3D has a global mesh, global vertex ids and stores materialid on the face, we need
  613. // temporary lists to collect data for an aiMesh, which requires local arrays and local indeces
  614. // this function fills up an aiMesh with those temporary lists
  615. void M3DImporter::populateMesh(const M3DWrapper &m3d, aiMesh *pMesh, std::vector<aiFace> *faces, std::vector<aiVector3D> *vertices,
  616. std::vector<aiVector3D> *normals, std::vector<aiVector3D> *texcoords, std::vector<aiColor4D> *colors,
  617. std::vector<unsigned int> *vertexids) {
  618. ai_assert(pMesh != nullptr);
  619. ai_assert(faces != nullptr);
  620. ai_assert(vertices != nullptr);
  621. ai_assert(normals != nullptr);
  622. ai_assert(texcoords != nullptr);
  623. ai_assert(colors != nullptr);
  624. ai_assert(vertexids != nullptr);
  625. ai_assert(m3d);
  626. ASSIMP_LOG_DEBUG("M3D: populateMesh numvertices ", vertices->size(), " numfaces ", faces->size(),
  627. " numnormals ", normals->size(), " numtexcoord ", texcoords->size(), " numbones ", m3d->numbone);
  628. if (vertices->size() && faces->size()) {
  629. pMesh->mNumFaces = static_cast<unsigned int>(faces->size());
  630. pMesh->mFaces = new aiFace[pMesh->mNumFaces];
  631. std::copy(faces->begin(), faces->end(), pMesh->mFaces);
  632. pMesh->mNumVertices = static_cast<unsigned int>(vertices->size());
  633. pMesh->mVertices = new aiVector3D[pMesh->mNumVertices];
  634. std::copy(vertices->begin(), vertices->end(), pMesh->mVertices);
  635. if (normals->size() == vertices->size()) {
  636. pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
  637. std::copy(normals->begin(), normals->end(), pMesh->mNormals);
  638. }
  639. if (texcoords->size() == vertices->size()) {
  640. pMesh->mTextureCoords[0] = new aiVector3D[pMesh->mNumVertices];
  641. std::copy(texcoords->begin(), texcoords->end(), pMesh->mTextureCoords[0]);
  642. pMesh->mNumUVComponents[0] = 2;
  643. }
  644. if (colors->size() == vertices->size()) {
  645. pMesh->mColors[0] = new aiColor4D[pMesh->mNumVertices];
  646. std::copy(colors->begin(), colors->end(), pMesh->mColors[0]);
  647. }
  648. // this is complicated, because M3D stores a list of bone id / weight pairs per
  649. // vertex but assimp uses lists of local vertex id/weight pairs per local bone list
  650. pMesh->mNumBones = m3d->numbone;
  651. // we need aiBone with mOffsetMatrix for bones without weights as well
  652. if (pMesh->mNumBones && m3d->numbone && m3d->bone) {
  653. pMesh->mBones = new aiBone *[pMesh->mNumBones];
  654. for (unsigned int i = 0; i < m3d->numbone; i++) {
  655. aiNode *pNode;
  656. pMesh->mBones[i] = new aiBone;
  657. pMesh->mBones[i]->mName = aiString(std::string(m3d->bone[i].name));
  658. pMesh->mBones[i]->mNumWeights = 0;
  659. pNode = findNode(mScene->mRootNode, pMesh->mBones[i]->mName);
  660. if (pNode) {
  661. calculateOffsetMatrix(pNode, &pMesh->mBones[i]->mOffsetMatrix);
  662. pMesh->mBones[i]->mOffsetMatrix.Inverse();
  663. } else
  664. pMesh->mBones[i]->mOffsetMatrix = aiMatrix4x4();
  665. }
  666. if (vertexids->size() && m3d->numvertex && m3d->vertex && m3d->numskin && m3d->skin) {
  667. unsigned int i, j;
  668. // first count how many vertices we have per bone
  669. for (i = 0; i < vertexids->size(); i++) {
  670. if (vertexids->at(i) >= m3d->numvertex) {
  671. continue;
  672. }
  673. unsigned int s = m3d->vertex[vertexids->at(i)].skinid;
  674. if (s != M3D_UNDEF && s != M3D_INDEXMAX) {
  675. for (unsigned int k = 0; k < M3D_NUMBONE && m3d->skin[s].weight[k] > 0.0; k++) {
  676. aiString name = aiString(std::string(m3d->bone[m3d->skin[s].boneid[k]].name));
  677. for (j = 0; j < pMesh->mNumBones; j++) {
  678. if (pMesh->mBones[j]->mName == name) {
  679. pMesh->mBones[j]->mNumWeights++;
  680. break;
  681. }
  682. }
  683. }
  684. }
  685. }
  686. // allocate mWeights
  687. for (j = 0; j < pMesh->mNumBones; j++) {
  688. aiBone *pBone = pMesh->mBones[j];
  689. if (pBone->mNumWeights) {
  690. pBone->mWeights = new aiVertexWeight[pBone->mNumWeights];
  691. pBone->mNumWeights = 0;
  692. }
  693. }
  694. // fill up with data
  695. for (i = 0; i < vertexids->size(); i++) {
  696. if (vertexids->at(i) >= m3d->numvertex) continue;
  697. unsigned int s = m3d->vertex[vertexids->at(i)].skinid;
  698. if (s != M3D_UNDEF && s != M3D_INDEXMAX && s < m3d->numskin) {
  699. for (unsigned int k = 0; k < M3D_NUMBONE && m3d->skin[s].weight[k] > 0.0; k++) {
  700. if (m3d->skin[s].boneid[k] >= m3d->numbone) continue;
  701. aiString name = aiString(std::string(m3d->bone[m3d->skin[s].boneid[k]].name));
  702. for (j = 0; j < pMesh->mNumBones; j++) {
  703. if (pMesh->mBones[j]->mName == name) {
  704. aiBone *pBone = pMesh->mBones[j];
  705. pBone->mWeights[pBone->mNumWeights].mVertexId = i;
  706. pBone->mWeights[pBone->mNumWeights].mWeight = m3d->skin[s].weight[k];
  707. pBone->mNumWeights++;
  708. break;
  709. }
  710. }
  711. } // foreach skin
  712. }
  713. } // foreach vertexids
  714. }
  715. }
  716. }
  717. }
  718. // ------------------------------------------------------------------------------------------------
  719. } // Namespace Assimp
  720. #endif // !! ASSIMP_BUILD_NO_M3D_IMPORTER