M3DImporter.cpp 30 KB

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