M3DImporter.cpp 30 KB

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