M3DImporter.cpp 27 KB

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