M3DImporter.cpp 31 KB

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