M3DImporter.cpp 32 KB

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