glTFExporter.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2020, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. #ifndef ASSIMP_BUILD_NO_EXPORT
  34. #ifndef ASSIMP_BUILD_NO_GLTF_EXPORTER
  35. #include "glTF/glTFExporter.h"
  36. #include "glTF/glTFAssetWriter.h"
  37. #include "PostProcessing/SplitLargeMeshes.h"
  38. #include <assimp/commonMetaData.h>
  39. #include <assimp/Exceptional.h>
  40. #include <assimp/StringComparison.h>
  41. #include <assimp/ByteSwapper.h>
  42. #include <assimp/SceneCombiner.h>
  43. #include <assimp/version.h>
  44. #include <assimp/IOSystem.hpp>
  45. #include <assimp/Exporter.hpp>
  46. #include <assimp/material.h>
  47. #include <assimp/scene.h>
  48. // Header files, standard library.
  49. #include <memory>
  50. #include <limits>
  51. #include <inttypes.h>
  52. #ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
  53. // Header files, Open3DGC.
  54. # include <Open3DGC/o3dgcSC3DMCEncoder.h>
  55. #endif
  56. using namespace rapidjson;
  57. using namespace Assimp;
  58. using namespace glTF;
  59. namespace Assimp {
  60. // ------------------------------------------------------------------------------------------------
  61. // Worker function for exporting a scene to GLTF. Prototyped and registered in Exporter.cpp
  62. void ExportSceneGLTF(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
  63. {
  64. // invoke the exporter
  65. glTFExporter exporter(pFile, pIOSystem, pScene, pProperties, false);
  66. }
  67. // ------------------------------------------------------------------------------------------------
  68. // Worker function for exporting a scene to GLB. Prototyped and registered in Exporter.cpp
  69. void ExportSceneGLB(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
  70. {
  71. // invoke the exporter
  72. glTFExporter exporter(pFile, pIOSystem, pScene, pProperties, true);
  73. }
  74. } // end of namespace Assimp
  75. glTFExporter::glTFExporter(const char* filename, IOSystem* pIOSystem, const aiScene* pScene,
  76. const ExportProperties* pProperties, bool isBinary)
  77. : mFilename(filename)
  78. , mIOSystem(pIOSystem)
  79. , mProperties(pProperties)
  80. {
  81. aiScene* sceneCopy_tmp;
  82. SceneCombiner::CopyScene(&sceneCopy_tmp, pScene);
  83. SplitLargeMeshesProcess_Triangle tri_splitter;
  84. tri_splitter.SetLimit(0xffff);
  85. tri_splitter.Execute(sceneCopy_tmp);
  86. SplitLargeMeshesProcess_Vertex vert_splitter;
  87. vert_splitter.SetLimit(0xffff);
  88. vert_splitter.Execute(sceneCopy_tmp);
  89. mScene.reset(sceneCopy_tmp);
  90. mAsset.reset( new glTF::Asset( pIOSystem ) );
  91. if (isBinary) {
  92. mAsset->SetAsBinary();
  93. }
  94. ExportMetadata();
  95. //for (unsigned int i = 0; i < pScene->mNumCameras; ++i) {}
  96. //for (unsigned int i = 0; i < pScene->mNumLights; ++i) {}
  97. ExportMaterials();
  98. if (mScene->mRootNode) {
  99. ExportNodeHierarchy(mScene->mRootNode);
  100. }
  101. ExportMeshes();
  102. //for (unsigned int i = 0; i < pScene->mNumTextures; ++i) {}
  103. ExportScene();
  104. ExportAnimations();
  105. glTF::AssetWriter writer(*mAsset);
  106. if (isBinary) {
  107. writer.WriteGLBFile(filename);
  108. } else {
  109. writer.WriteFile(filename);
  110. }
  111. }
  112. /*
  113. * Copy a 4x4 matrix from struct aiMatrix to typedef mat4.
  114. * Also converts from row-major to column-major storage.
  115. */
  116. static void CopyValue(const aiMatrix4x4& v, glTF::mat4& o)
  117. {
  118. o[ 0] = v.a1; o[ 1] = v.b1; o[ 2] = v.c1; o[ 3] = v.d1;
  119. o[ 4] = v.a2; o[ 5] = v.b2; o[ 6] = v.c2; o[ 7] = v.d2;
  120. o[ 8] = v.a3; o[ 9] = v.b3; o[10] = v.c3; o[11] = v.d3;
  121. o[12] = v.a4; o[13] = v.b4; o[14] = v.c4; o[15] = v.d4;
  122. }
  123. static void CopyValue(const aiMatrix4x4& v, aiMatrix4x4& o)
  124. {
  125. memcpy(&o, &v, sizeof(aiMatrix4x4));
  126. }
  127. static void IdentityMatrix4(glTF::mat4& o)
  128. {
  129. o[ 0] = 1; o[ 1] = 0; o[ 2] = 0; o[ 3] = 0;
  130. o[ 4] = 0; o[ 5] = 1; o[ 6] = 0; o[ 7] = 0;
  131. o[ 8] = 0; o[ 9] = 0; o[10] = 1; o[11] = 0;
  132. o[12] = 0; o[13] = 0; o[14] = 0; o[15] = 1;
  133. }
  134. template<typename T>
  135. void SetAccessorRange(Ref<Accessor> acc, void* data, unsigned int count,
  136. unsigned int numCompsIn, unsigned int numCompsOut)
  137. {
  138. ai_assert(numCompsOut <= numCompsIn);
  139. // Allocate and initialize with large values.
  140. for (unsigned int i = 0 ; i < numCompsOut ; i++) {
  141. acc->min.push_back( std::numeric_limits<double>::max());
  142. acc->max.push_back(-std::numeric_limits<double>::max());
  143. }
  144. size_t totalComps = count * numCompsIn;
  145. T* buffer_ptr = static_cast<T*>(data);
  146. T* buffer_end = buffer_ptr + totalComps;
  147. // Search and set extreme values.
  148. for (; buffer_ptr < buffer_end ; buffer_ptr += numCompsIn) {
  149. for (unsigned int j = 0 ; j < numCompsOut ; j++) {
  150. double valueTmp = buffer_ptr[j];
  151. if (valueTmp < acc->min[j]) {
  152. acc->min[j] = valueTmp;
  153. }
  154. if (valueTmp > acc->max[j]) {
  155. acc->max[j] = valueTmp;
  156. }
  157. }
  158. }
  159. }
  160. inline void SetAccessorRange(ComponentType compType, Ref<Accessor> acc, void* data,
  161. unsigned int count, unsigned int numCompsIn, unsigned int numCompsOut)
  162. {
  163. switch (compType) {
  164. case ComponentType_SHORT:
  165. SetAccessorRange<short>(acc, data, count, numCompsIn, numCompsOut);
  166. return;
  167. case ComponentType_UNSIGNED_SHORT:
  168. SetAccessorRange<unsigned short>(acc, data, count, numCompsIn, numCompsOut);
  169. return;
  170. case ComponentType_UNSIGNED_INT:
  171. SetAccessorRange<unsigned int>(acc, data, count, numCompsIn, numCompsOut);
  172. return;
  173. case ComponentType_FLOAT:
  174. SetAccessorRange<float>(acc, data, count, numCompsIn, numCompsOut);
  175. return;
  176. case ComponentType_BYTE:
  177. SetAccessorRange<int8_t>(acc, data, count, numCompsIn, numCompsOut);
  178. return;
  179. case ComponentType_UNSIGNED_BYTE:
  180. SetAccessorRange<uint8_t>(acc, data, count, numCompsIn, numCompsOut);
  181. return;
  182. }
  183. }
  184. inline Ref<Accessor> ExportData(Asset &a, std::string &meshName, Ref<Buffer> &buffer,
  185. unsigned int count, void *data, AttribType::Value typeIn, AttribType::Value typeOut, ComponentType compType, BufferViewTarget target = BufferViewTarget_NONE) {
  186. if (!count || !data) return Ref<Accessor>();
  187. unsigned int numCompsIn = AttribType::GetNumComponents(typeIn);
  188. unsigned int numCompsOut = AttribType::GetNumComponents(typeOut);
  189. unsigned int bytesPerComp = ComponentTypeSize(compType);
  190. size_t offset = buffer->byteLength;
  191. // make sure offset is correctly byte-aligned, as required by spec
  192. size_t padding = offset % bytesPerComp;
  193. offset += padding;
  194. size_t length = count * numCompsOut * bytesPerComp;
  195. buffer->Grow(length + padding);
  196. // bufferView
  197. Ref<BufferView> bv = a.bufferViews.Create(a.FindUniqueID(meshName, "view"));
  198. bv->buffer = buffer;
  199. bv->byteOffset = unsigned(offset);
  200. bv->byteLength = length; //! The target that the WebGL buffer should be bound to.
  201. bv->target = target;
  202. // accessor
  203. Ref<Accessor> acc = a.accessors.Create(a.FindUniqueID(meshName, "accessor"));
  204. acc->bufferView = bv;
  205. acc->byteOffset = 0;
  206. acc->byteStride = 0;
  207. acc->componentType = compType;
  208. acc->count = count;
  209. acc->type = typeOut;
  210. // calculate min and max values
  211. SetAccessorRange(compType, acc, data, count, numCompsIn, numCompsOut);
  212. // copy the data
  213. acc->WriteData(count, data, numCompsIn*bytesPerComp);
  214. return acc;
  215. }
  216. namespace {
  217. void GetMatScalar(const aiMaterial* mat, float& val, const char* propName, int type, int idx) {
  218. ai_assert( nullptr != mat );
  219. if ( nullptr != mat ) {
  220. mat->Get(propName, type, idx, val);
  221. }
  222. }
  223. }
  224. void glTFExporter::GetTexSampler(const aiMaterial* mat, glTF::TexProperty& prop)
  225. {
  226. std::string samplerId = mAsset->FindUniqueID("", "sampler");
  227. prop.texture->sampler = mAsset->samplers.Create(samplerId);
  228. aiTextureMapMode mapU, mapV;
  229. aiGetMaterialInteger(mat,AI_MATKEY_MAPPINGMODE_U_DIFFUSE(0),(int*)&mapU);
  230. aiGetMaterialInteger(mat,AI_MATKEY_MAPPINGMODE_V_DIFFUSE(0),(int*)&mapV);
  231. switch (mapU) {
  232. case aiTextureMapMode_Wrap:
  233. prop.texture->sampler->wrapS = SamplerWrap_Repeat;
  234. break;
  235. case aiTextureMapMode_Clamp:
  236. prop.texture->sampler->wrapS = SamplerWrap_Clamp_To_Edge;
  237. break;
  238. case aiTextureMapMode_Mirror:
  239. prop.texture->sampler->wrapS = SamplerWrap_Mirrored_Repeat;
  240. break;
  241. case aiTextureMapMode_Decal:
  242. default:
  243. prop.texture->sampler->wrapS = SamplerWrap_Repeat;
  244. break;
  245. };
  246. switch (mapV) {
  247. case aiTextureMapMode_Wrap:
  248. prop.texture->sampler->wrapT = SamplerWrap_Repeat;
  249. break;
  250. case aiTextureMapMode_Clamp:
  251. prop.texture->sampler->wrapT = SamplerWrap_Clamp_To_Edge;
  252. break;
  253. case aiTextureMapMode_Mirror:
  254. prop.texture->sampler->wrapT = SamplerWrap_Mirrored_Repeat;
  255. break;
  256. case aiTextureMapMode_Decal:
  257. default:
  258. prop.texture->sampler->wrapT = SamplerWrap_Repeat;
  259. break;
  260. };
  261. // Hard coded Texture filtering options because I do not know where to find them in the aiMaterial.
  262. prop.texture->sampler->magFilter = SamplerMagFilter_Linear;
  263. prop.texture->sampler->minFilter = SamplerMinFilter_Linear;
  264. }
  265. void glTFExporter::GetMatColorOrTex(const aiMaterial* mat, glTF::TexProperty& prop, const char* propName, int type, int idx, aiTextureType tt)
  266. {
  267. aiString tex;
  268. aiColor4D col;
  269. if (mat->GetTextureCount(tt) > 0) {
  270. if (mat->Get(AI_MATKEY_TEXTURE(tt, 0), tex) == AI_SUCCESS) {
  271. std::string path = tex.C_Str();
  272. if (path.size() > 0) {
  273. if (path[0] != '*') {
  274. std::map<std::string, unsigned int>::iterator it = mTexturesByPath.find(path);
  275. if (it != mTexturesByPath.end()) {
  276. prop.texture = mAsset->textures.Get(it->second);
  277. }
  278. }
  279. if (!prop.texture) {
  280. std::string texId = mAsset->FindUniqueID("", "texture");
  281. prop.texture = mAsset->textures.Create(texId);
  282. mTexturesByPath[path] = prop.texture.GetIndex();
  283. std::string imgId = mAsset->FindUniqueID("", "image");
  284. prop.texture->source = mAsset->images.Create(imgId);
  285. if (path[0] == '*') { // embedded
  286. aiTexture* tex = mScene->mTextures[atoi(&path[1])];
  287. prop.texture->source->name = tex->mFilename.C_Str();
  288. uint8_t* data = reinterpret_cast<uint8_t*>(tex->pcData);
  289. prop.texture->source->SetData(data, tex->mWidth, *mAsset);
  290. if (tex->achFormatHint[0]) {
  291. std::string mimeType = "image/";
  292. mimeType += (memcmp(tex->achFormatHint, "jpg", 3) == 0) ? "jpeg" : tex->achFormatHint;
  293. prop.texture->source->mimeType = mimeType;
  294. }
  295. }
  296. else {
  297. prop.texture->source->uri = path;
  298. }
  299. GetTexSampler(mat, prop);
  300. }
  301. }
  302. }
  303. }
  304. if (mat->Get(propName, type, idx, col) == AI_SUCCESS) {
  305. prop.color[0] = col.r; prop.color[1] = col.g; prop.color[2] = col.b; prop.color[3] = col.a;
  306. }
  307. }
  308. void glTFExporter::ExportMaterials()
  309. {
  310. aiString aiName;
  311. for (unsigned int i = 0; i < mScene->mNumMaterials; ++i) {
  312. const aiMaterial* mat = mScene->mMaterials[i];
  313. std::string name;
  314. if (mat->Get(AI_MATKEY_NAME, aiName) == AI_SUCCESS) {
  315. name = aiName.C_Str();
  316. }
  317. name = mAsset->FindUniqueID(name, "material");
  318. Ref<Material> m = mAsset->materials.Create(name);
  319. GetMatColorOrTex(mat, m->ambient, AI_MATKEY_COLOR_AMBIENT, aiTextureType_AMBIENT);
  320. GetMatColorOrTex(mat, m->diffuse, AI_MATKEY_COLOR_DIFFUSE, aiTextureType_DIFFUSE);
  321. GetMatColorOrTex(mat, m->specular, AI_MATKEY_COLOR_SPECULAR, aiTextureType_SPECULAR);
  322. GetMatColorOrTex(mat, m->emission, AI_MATKEY_COLOR_EMISSIVE, aiTextureType_EMISSIVE);
  323. m->transparent = mat->Get(AI_MATKEY_OPACITY, m->transparency) == aiReturn_SUCCESS && m->transparency != 1.0;
  324. GetMatScalar(mat, m->shininess, AI_MATKEY_SHININESS);
  325. }
  326. }
  327. /*
  328. * Search through node hierarchy and find the node containing the given meshID.
  329. * Returns true on success, and false otherwise.
  330. */
  331. bool FindMeshNode(Ref<Node>& nodeIn, Ref<Node>& meshNode, std::string meshID)
  332. {
  333. for (unsigned int i = 0; i < nodeIn->meshes.size(); ++i) {
  334. if (meshID.compare(nodeIn->meshes[i]->id) == 0) {
  335. meshNode = nodeIn;
  336. return true;
  337. }
  338. }
  339. for (unsigned int i = 0; i < nodeIn->children.size(); ++i) {
  340. if(FindMeshNode(nodeIn->children[i], meshNode, meshID)) {
  341. return true;
  342. }
  343. }
  344. return false;
  345. }
  346. /*
  347. * Find the root joint of the skeleton.
  348. * Starts will any joint node and traces up the tree,
  349. * until a parent is found that does not have a jointName.
  350. * Returns the first parent Ref<Node> found that does not have a jointName.
  351. */
  352. Ref<Node> FindSkeletonRootJoint(Ref<Skin>& skinRef)
  353. {
  354. Ref<Node> startNodeRef;
  355. Ref<Node> parentNodeRef;
  356. // Arbitrarily use the first joint to start the search.
  357. startNodeRef = skinRef->jointNames[0];
  358. parentNodeRef = skinRef->jointNames[0];
  359. do {
  360. startNodeRef = parentNodeRef;
  361. parentNodeRef = startNodeRef->parent;
  362. } while (!parentNodeRef->jointName.empty());
  363. return parentNodeRef;
  364. }
  365. void ExportSkin(Asset& mAsset, const aiMesh* aimesh, Ref<Mesh>& meshRef, Ref<Buffer>& bufferRef, Ref<Skin>& skinRef, std::vector<aiMatrix4x4>& inverseBindMatricesData)
  366. {
  367. if (aimesh->mNumBones < 1) {
  368. return;
  369. }
  370. // Store the vertex joint and weight data.
  371. const size_t NumVerts( aimesh->mNumVertices );
  372. vec4* vertexJointData = new vec4[ NumVerts ];
  373. vec4* vertexWeightData = new vec4[ NumVerts ];
  374. int* jointsPerVertex = new int[ NumVerts ];
  375. for (size_t i = 0; i < NumVerts; ++i) {
  376. jointsPerVertex[i] = 0;
  377. for (size_t j = 0; j < 4; ++j) {
  378. vertexJointData[i][j] = 0;
  379. vertexWeightData[i][j] = 0;
  380. }
  381. }
  382. for (unsigned int idx_bone = 0; idx_bone < aimesh->mNumBones; ++idx_bone) {
  383. const aiBone* aib = aimesh->mBones[idx_bone];
  384. // aib->mName =====> skinRef->jointNames
  385. // Find the node with id = mName.
  386. Ref<Node> nodeRef = mAsset.nodes.Get(aib->mName.C_Str());
  387. nodeRef->jointName = nodeRef->id;
  388. unsigned int jointNamesIndex = 0;
  389. bool addJointToJointNames = true;
  390. for ( unsigned int idx_joint = 0; idx_joint < skinRef->jointNames.size(); ++idx_joint) {
  391. if (skinRef->jointNames[idx_joint]->jointName.compare(nodeRef->jointName) == 0) {
  392. addJointToJointNames = false;
  393. jointNamesIndex = idx_joint;
  394. }
  395. }
  396. if (addJointToJointNames) {
  397. skinRef->jointNames.push_back(nodeRef);
  398. // aib->mOffsetMatrix =====> skinRef->inverseBindMatrices
  399. aiMatrix4x4 tmpMatrix4;
  400. CopyValue(aib->mOffsetMatrix, tmpMatrix4);
  401. inverseBindMatricesData.push_back(tmpMatrix4);
  402. jointNamesIndex = static_cast<unsigned int>(inverseBindMatricesData.size() - 1);
  403. }
  404. // aib->mWeights =====> vertexWeightData
  405. for (unsigned int idx_weights = 0; idx_weights < aib->mNumWeights; ++idx_weights) {
  406. unsigned int vertexId = aib->mWeights[idx_weights].mVertexId;
  407. float vertWeight = aib->mWeights[idx_weights].mWeight;
  408. // A vertex can only have at most four joint weights. Ignore all others.
  409. if (jointsPerVertex[vertexId] > 3) {
  410. continue;
  411. }
  412. vertexJointData[vertexId][jointsPerVertex[vertexId]] = static_cast<float>(jointNamesIndex);
  413. vertexWeightData[vertexId][jointsPerVertex[vertexId]] = vertWeight;
  414. jointsPerVertex[vertexId] += 1;
  415. }
  416. } // End: for-loop mNumMeshes
  417. Mesh::Primitive& p = meshRef->primitives.back();
  418. Ref<Accessor> vertexJointAccessor = ExportData(mAsset, skinRef->id, bufferRef, aimesh->mNumVertices, vertexJointData, AttribType::VEC4, AttribType::VEC4, ComponentType_FLOAT);
  419. if ( vertexJointAccessor ) {
  420. p.attributes.joint.push_back( vertexJointAccessor );
  421. }
  422. Ref<Accessor> vertexWeightAccessor = ExportData(mAsset, skinRef->id, bufferRef, aimesh->mNumVertices, vertexWeightData, AttribType::VEC4, AttribType::VEC4, ComponentType_FLOAT);
  423. if ( vertexWeightAccessor ) {
  424. p.attributes.weight.push_back( vertexWeightAccessor );
  425. }
  426. delete[] jointsPerVertex;
  427. delete[] vertexWeightData;
  428. delete[] vertexJointData;
  429. }
  430. void glTFExporter::ExportMeshes()
  431. {
  432. // Not for
  433. // using IndicesType = decltype(aiFace::mNumIndices);
  434. // But yes for
  435. // using IndicesType = unsigned short;
  436. // because "ComponentType_UNSIGNED_SHORT" used for indices. And it's a maximal type according to glTF specification.
  437. typedef unsigned short IndicesType;
  438. // Variables needed for compression. BEGIN.
  439. // Indices, not pointers - because pointer to buffer is changing while writing to it.
  440. size_t idx_srcdata_begin = 0; // Index of buffer before writing mesh data. Also, index of begin of coordinates array in buffer.
  441. size_t idx_srcdata_normal = SIZE_MAX;// Index of begin of normals array in buffer. SIZE_MAX - mean that mesh has no normals.
  442. std::vector<size_t> idx_srcdata_tc;// Array of indices. Every index point to begin of texture coordinates array in buffer.
  443. size_t idx_srcdata_ind;// Index of begin of coordinates indices array in buffer.
  444. bool comp_allow;// Point that data of current mesh can be compressed.
  445. // Variables needed for compression. END.
  446. std::string fname = std::string(mFilename);
  447. std::string bufferIdPrefix = fname.substr(0, fname.rfind(".gltf"));
  448. std::string bufferId = mAsset->FindUniqueID("", bufferIdPrefix.c_str());
  449. Ref<Buffer> b = mAsset->GetBodyBuffer();
  450. if (!b) {
  451. b = mAsset->buffers.Create(bufferId);
  452. }
  453. //----------------------------------------
  454. // Initialize variables for the skin
  455. bool createSkin = false;
  456. for (unsigned int idx_mesh = 0; idx_mesh < mScene->mNumMeshes; ++idx_mesh) {
  457. const aiMesh* aim = mScene->mMeshes[idx_mesh];
  458. if(aim->HasBones()) {
  459. createSkin = true;
  460. break;
  461. }
  462. }
  463. Ref<Skin> skinRef;
  464. std::string skinName = mAsset->FindUniqueID("skin", "skin");
  465. std::vector<aiMatrix4x4> inverseBindMatricesData;
  466. if(createSkin) {
  467. skinRef = mAsset->skins.Create(skinName);
  468. skinRef->name = skinName;
  469. }
  470. //----------------------------------------
  471. for (unsigned int idx_mesh = 0; idx_mesh < mScene->mNumMeshes; ++idx_mesh) {
  472. const aiMesh* aim = mScene->mMeshes[idx_mesh];
  473. // Check if compressing requested and mesh can be encoded.
  474. #ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
  475. comp_allow = mProperties->GetPropertyBool("extensions.Open3DGC.use", false);
  476. #else
  477. comp_allow = false;
  478. #endif
  479. if(comp_allow && (aim->mPrimitiveTypes == aiPrimitiveType_TRIANGLE) && (aim->mNumVertices > 0) && (aim->mNumFaces > 0))
  480. {
  481. idx_srcdata_tc.clear();
  482. idx_srcdata_tc.reserve(AI_MAX_NUMBER_OF_TEXTURECOORDS);
  483. }
  484. else
  485. {
  486. std::string msg;
  487. if(aim->mPrimitiveTypes != aiPrimitiveType_TRIANGLE)
  488. msg = "all primitives of the mesh must be a triangles.";
  489. else
  490. msg = "mesh must has vertices and faces.";
  491. ASSIMP_LOG_WARN_F("GLTF: can not use Open3DGC-compression: ", msg);
  492. comp_allow = false;
  493. }
  494. std::string meshId = mAsset->FindUniqueID(aim->mName.C_Str(), "mesh");
  495. Ref<Mesh> m = mAsset->meshes.Create(meshId);
  496. m->primitives.resize(1);
  497. Mesh::Primitive& p = m->primitives.back();
  498. p.material = mAsset->materials.Get(aim->mMaterialIndex);
  499. /******************* Vertices ********************/
  500. // If compression is used then you need parameters of uncompressed region: begin and size. At this step "begin" is stored.
  501. if(comp_allow) idx_srcdata_begin = b->byteLength;
  502. Ref<Accessor> v = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mVertices, AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT, BufferViewTarget_ARRAY_BUFFER);
  503. if (v) p.attributes.position.push_back(v);
  504. /******************** Normals ********************/
  505. if(comp_allow && (aim->mNormals != 0)) idx_srcdata_normal = b->byteLength;// Store index of normals array.
  506. Ref<Accessor> n = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mNormals, AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT, BufferViewTarget_ARRAY_BUFFER);
  507. if (n) p.attributes.normal.push_back(n);
  508. /************** Texture coordinates **************/
  509. for (int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  510. // Flip UV y coords
  511. if (aim -> mNumUVComponents[i] > 1) {
  512. for (unsigned int j = 0; j < aim->mNumVertices; ++j) {
  513. aim->mTextureCoords[i][j].y = 1 - aim->mTextureCoords[i][j].y;
  514. }
  515. }
  516. if (aim->mNumUVComponents[i] > 0) {
  517. AttribType::Value type = (aim->mNumUVComponents[i] == 2) ? AttribType::VEC2 : AttribType::VEC3;
  518. if(comp_allow) idx_srcdata_tc.push_back(b->byteLength);// Store index of texture coordinates array.
  519. Ref<Accessor> tc = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mTextureCoords[i], AttribType::VEC3, type, ComponentType_FLOAT, BufferViewTarget_ARRAY_BUFFER);
  520. if (tc) p.attributes.texcoord.push_back(tc);
  521. }
  522. }
  523. /*************** Vertices indices ****************/
  524. idx_srcdata_ind = b->byteLength;// Store index of indices array.
  525. if (aim->mNumFaces > 0) {
  526. std::vector<IndicesType> indices;
  527. unsigned int nIndicesPerFace = aim->mFaces[0].mNumIndices;
  528. indices.resize(aim->mNumFaces * nIndicesPerFace);
  529. for (size_t i = 0; i < aim->mNumFaces; ++i) {
  530. for (size_t j = 0; j < nIndicesPerFace; ++j) {
  531. indices[i*nIndicesPerFace + j] = uint16_t(aim->mFaces[i].mIndices[j]);
  532. }
  533. }
  534. p.indices = ExportData(*mAsset, meshId, b, unsigned(indices.size()), &indices[0], AttribType::SCALAR, AttribType::SCALAR, ComponentType_UNSIGNED_SHORT, BufferViewTarget_ELEMENT_ARRAY_BUFFER);
  535. }
  536. switch (aim->mPrimitiveTypes) {
  537. case aiPrimitiveType_POLYGON:
  538. p.mode = PrimitiveMode_TRIANGLES; break; // TODO implement this
  539. case aiPrimitiveType_LINE:
  540. p.mode = PrimitiveMode_LINES; break;
  541. case aiPrimitiveType_POINT:
  542. p.mode = PrimitiveMode_POINTS; break;
  543. default: // aiPrimitiveType_TRIANGLE
  544. p.mode = PrimitiveMode_TRIANGLES;
  545. }
  546. /*************** Skins ****************/
  547. if(aim->HasBones()) {
  548. ExportSkin(*mAsset, aim, m, b, skinRef, inverseBindMatricesData);
  549. }
  550. /****************** Compression ******************/
  551. ///TODO: animation: weights, joints.
  552. if(comp_allow)
  553. {
  554. #ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
  555. // Only one type of compression supported at now - Open3DGC.
  556. //
  557. o3dgc::BinaryStream bs;
  558. o3dgc::SC3DMCEncoder<IndicesType> encoder;
  559. o3dgc::IndexedFaceSet<IndicesType> comp_o3dgc_ifs;
  560. o3dgc::SC3DMCEncodeParams comp_o3dgc_params;
  561. //
  562. // Fill data for encoder.
  563. //
  564. // Quantization
  565. unsigned quant_coord = mProperties->GetPropertyInteger("extensions.Open3DGC.quantization.POSITION", 12);
  566. unsigned quant_normal = mProperties->GetPropertyInteger("extensions.Open3DGC.quantization.NORMAL", 10);
  567. unsigned quant_texcoord = mProperties->GetPropertyInteger("extensions.Open3DGC.quantization.TEXCOORD", 10);
  568. // Prediction
  569. o3dgc::O3DGCSC3DMCPredictionMode prediction_position = o3dgc::O3DGC_SC3DMC_PARALLELOGRAM_PREDICTION;
  570. o3dgc::O3DGCSC3DMCPredictionMode prediction_normal = o3dgc::O3DGC_SC3DMC_SURF_NORMALS_PREDICTION;
  571. o3dgc::O3DGCSC3DMCPredictionMode prediction_texcoord = o3dgc::O3DGC_SC3DMC_PARALLELOGRAM_PREDICTION;
  572. // IndexedFacesSet: "Crease angle", "solid", "convex" are set to default.
  573. comp_o3dgc_ifs.SetCCW(true);
  574. comp_o3dgc_ifs.SetIsTriangularMesh(true);
  575. comp_o3dgc_ifs.SetNumFloatAttributes(0);
  576. // Coordinates
  577. comp_o3dgc_params.SetCoordQuantBits(quant_coord);
  578. comp_o3dgc_params.SetCoordPredMode(prediction_position);
  579. comp_o3dgc_ifs.SetNCoord(aim->mNumVertices);
  580. comp_o3dgc_ifs.SetCoord((o3dgc::Real* const)&b->GetPointer()[idx_srcdata_begin]);
  581. // Normals
  582. if(idx_srcdata_normal != SIZE_MAX)
  583. {
  584. comp_o3dgc_params.SetNormalQuantBits(quant_normal);
  585. comp_o3dgc_params.SetNormalPredMode(prediction_normal);
  586. comp_o3dgc_ifs.SetNNormal(aim->mNumVertices);
  587. comp_o3dgc_ifs.SetNormal((o3dgc::Real* const)&b->GetPointer()[idx_srcdata_normal]);
  588. }
  589. // Texture coordinates
  590. for(size_t num_tc = 0; num_tc < idx_srcdata_tc.size(); num_tc++)
  591. {
  592. size_t num = comp_o3dgc_ifs.GetNumFloatAttributes();
  593. comp_o3dgc_params.SetFloatAttributeQuantBits(static_cast<unsigned long>(num), quant_texcoord);
  594. comp_o3dgc_params.SetFloatAttributePredMode(static_cast<unsigned long>(num), prediction_texcoord);
  595. comp_o3dgc_ifs.SetNFloatAttribute(static_cast<unsigned long>(num), aim->mNumVertices);// number of elements.
  596. comp_o3dgc_ifs.SetFloatAttributeDim(static_cast<unsigned long>(num), aim->mNumUVComponents[num_tc]);// components per element: aiVector3D => x * float
  597. comp_o3dgc_ifs.SetFloatAttributeType(static_cast<unsigned long>(num), o3dgc::O3DGC_IFS_FLOAT_ATTRIBUTE_TYPE_TEXCOORD);
  598. comp_o3dgc_ifs.SetFloatAttribute(static_cast<unsigned long>(num), (o3dgc::Real* const)&b->GetPointer()[idx_srcdata_tc[num_tc]]);
  599. comp_o3dgc_ifs.SetNumFloatAttributes(static_cast<unsigned long>(num + 1));
  600. }
  601. // Coordinates indices
  602. comp_o3dgc_ifs.SetNCoordIndex(aim->mNumFaces);
  603. comp_o3dgc_ifs.SetCoordIndex((IndicesType* const)&b->GetPointer()[idx_srcdata_ind]);
  604. // Prepare to encoding
  605. comp_o3dgc_params.SetNumFloatAttributes(comp_o3dgc_ifs.GetNumFloatAttributes());
  606. if(mProperties->GetPropertyBool("extensions.Open3DGC.binary", true))
  607. comp_o3dgc_params.SetStreamType(o3dgc::O3DGC_STREAM_TYPE_BINARY);
  608. else
  609. comp_o3dgc_params.SetStreamType(o3dgc::O3DGC_STREAM_TYPE_ASCII);
  610. comp_o3dgc_ifs.ComputeMinMax(o3dgc::O3DGC_SC3DMC_MAX_ALL_DIMS);
  611. //
  612. // Encoding
  613. //
  614. encoder.Encode(comp_o3dgc_params, comp_o3dgc_ifs, bs);
  615. // Replace data in buffer.
  616. b->ReplaceData(idx_srcdata_begin, b->byteLength - idx_srcdata_begin, bs.GetBuffer(), bs.GetSize());
  617. //
  618. // Add information about extension to mesh.
  619. //
  620. // Create extension structure.
  621. Mesh::SCompression_Open3DGC* ext = new Mesh::SCompression_Open3DGC;
  622. // Fill it.
  623. ext->Buffer = b->id;
  624. ext->Offset = idx_srcdata_begin;
  625. ext->Count = b->byteLength - idx_srcdata_begin;
  626. ext->Binary = mProperties->GetPropertyBool("extensions.Open3DGC.binary");
  627. ext->IndicesCount = comp_o3dgc_ifs.GetNCoordIndex() * 3;
  628. ext->VerticesCount = comp_o3dgc_ifs.GetNCoord();
  629. // And assign to mesh.
  630. m->Extension.push_back(ext);
  631. #endif
  632. }// if(comp_allow)
  633. }// for (unsigned int i = 0; i < mScene->mNumMeshes; ++i)
  634. //----------------------------------------
  635. // Finish the skin
  636. // Create the Accessor for skinRef->inverseBindMatrices
  637. if (createSkin) {
  638. mat4* invBindMatrixData = new mat4[inverseBindMatricesData.size()];
  639. for ( unsigned int idx_joint = 0; idx_joint < inverseBindMatricesData.size(); ++idx_joint) {
  640. CopyValue(inverseBindMatricesData[idx_joint], invBindMatrixData[idx_joint]);
  641. }
  642. Ref<Accessor> invBindMatrixAccessor = ExportData(*mAsset, skinName, b, static_cast<unsigned int>(inverseBindMatricesData.size()), invBindMatrixData, AttribType::MAT4, AttribType::MAT4, ComponentType_FLOAT);
  643. if (invBindMatrixAccessor) skinRef->inverseBindMatrices = invBindMatrixAccessor;
  644. // Identity Matrix =====> skinRef->bindShapeMatrix
  645. // Temporary. Hard-coded identity matrix here
  646. skinRef->bindShapeMatrix.isPresent = true;
  647. IdentityMatrix4(skinRef->bindShapeMatrix.value);
  648. // Find node that contains this mesh and add "skeletons" and "skin" attributes to that node.
  649. Ref<Node> rootNode = mAsset->nodes.Get(unsigned(0));
  650. Ref<Node> meshNode;
  651. std::string meshID = mAsset->meshes.Get(unsigned(0))->id;
  652. FindMeshNode(rootNode, meshNode, meshID);
  653. Ref<Node> rootJoint = FindSkeletonRootJoint(skinRef);
  654. meshNode->skeletons.push_back(rootJoint);
  655. meshNode->skin = skinRef;
  656. }
  657. }
  658. /*
  659. * Export the root node of the node hierarchy.
  660. * Calls ExportNode for all children.
  661. */
  662. unsigned int glTFExporter::ExportNodeHierarchy(const aiNode* n)
  663. {
  664. Ref<Node> node = mAsset->nodes.Create(mAsset->FindUniqueID(n->mName.C_Str(), "node"));
  665. if (!n->mTransformation.IsIdentity()) {
  666. node->matrix.isPresent = true;
  667. CopyValue(n->mTransformation, node->matrix.value);
  668. }
  669. for (unsigned int i = 0; i < n->mNumMeshes; ++i) {
  670. node->meshes.push_back(mAsset->meshes.Get(n->mMeshes[i]));
  671. }
  672. for (unsigned int i = 0; i < n->mNumChildren; ++i) {
  673. unsigned int idx = ExportNode(n->mChildren[i], node);
  674. node->children.push_back(mAsset->nodes.Get(idx));
  675. }
  676. return node.GetIndex();
  677. }
  678. /*
  679. * Export node and recursively calls ExportNode for all children.
  680. * Since these nodes are not the root node, we also export the parent Ref<Node>
  681. */
  682. unsigned int glTFExporter::ExportNode(const aiNode* n, Ref<Node>& parent)
  683. {
  684. Ref<Node> node = mAsset->nodes.Create(mAsset->FindUniqueID(n->mName.C_Str(), "node"));
  685. node->parent = parent;
  686. if (!n->mTransformation.IsIdentity()) {
  687. node->matrix.isPresent = true;
  688. CopyValue(n->mTransformation, node->matrix.value);
  689. }
  690. for (unsigned int i = 0; i < n->mNumMeshes; ++i) {
  691. node->meshes.push_back(mAsset->meshes.Get(n->mMeshes[i]));
  692. }
  693. for (unsigned int i = 0; i < n->mNumChildren; ++i) {
  694. unsigned int idx = ExportNode(n->mChildren[i], node);
  695. node->children.push_back(mAsset->nodes.Get(idx));
  696. }
  697. return node.GetIndex();
  698. }
  699. void glTFExporter::ExportScene()
  700. {
  701. const char* sceneName = "defaultScene";
  702. Ref<Scene> scene = mAsset->scenes.Create(sceneName);
  703. // root node will be the first one exported (idx 0)
  704. if (mAsset->nodes.Size() > 0) {
  705. scene->nodes.push_back(mAsset->nodes.Get(0u));
  706. }
  707. // set as the default scene
  708. mAsset->scene = scene;
  709. }
  710. void glTFExporter::ExportMetadata()
  711. {
  712. glTF::AssetMetadata& asset = mAsset->asset;
  713. asset.version = "1.0";
  714. char buffer[256];
  715. ai_snprintf(buffer, 256, "Open Asset Import Library (assimp v%d.%d.%x)",
  716. aiGetVersionMajor(), aiGetVersionMinor(), aiGetVersionRevision());
  717. asset.generator = buffer;
  718. // Copyright
  719. aiString copyright_str;
  720. if (mScene->mMetaData != nullptr && mScene->mMetaData->Get(AI_METADATA_SOURCE_COPYRIGHT, copyright_str)) {
  721. asset.copyright = copyright_str.C_Str();
  722. }
  723. }
  724. inline void ExtractAnimationData(Asset& mAsset, std::string& animId, Ref<Animation>& animRef, Ref<Buffer>& buffer, const aiNodeAnim* nodeChannel, float ticksPerSecond)
  725. {
  726. // Loop over the data and check to see if it exactly matches an existing buffer.
  727. // If yes, then reference the existing corresponding accessor.
  728. // Otherwise, add to the buffer and create a new accessor.
  729. size_t counts[3] = {
  730. nodeChannel->mNumPositionKeys,
  731. nodeChannel->mNumScalingKeys,
  732. nodeChannel->mNumRotationKeys,
  733. };
  734. size_t numKeyframes = 1;
  735. for (int i = 0; i < 3; ++i) {
  736. if (counts[i] > numKeyframes) {
  737. numKeyframes = counts[i];
  738. }
  739. }
  740. //-------------------------------------------------------
  741. // Extract TIME parameter data.
  742. // Check if the timeStamps are the same for mPositionKeys, mRotationKeys, and mScalingKeys.
  743. if(nodeChannel->mNumPositionKeys > 0) {
  744. typedef float TimeType;
  745. std::vector<TimeType> timeData;
  746. timeData.resize(numKeyframes);
  747. for (size_t i = 0; i < numKeyframes; ++i) {
  748. size_t frameIndex = i * nodeChannel->mNumPositionKeys / numKeyframes;
  749. // mTime is measured in ticks, but GLTF time is measured in seconds, so convert.
  750. // Check if we have to cast type here. e.g. uint16_t()
  751. timeData[i] = static_cast<float>(nodeChannel->mPositionKeys[frameIndex].mTime / ticksPerSecond);
  752. }
  753. Ref<Accessor> timeAccessor = ExportData(mAsset, animId, buffer, static_cast<unsigned int>(numKeyframes), &timeData[0], AttribType::SCALAR, AttribType::SCALAR, ComponentType_FLOAT);
  754. if (timeAccessor) animRef->Parameters.TIME = timeAccessor;
  755. }
  756. //-------------------------------------------------------
  757. // Extract translation parameter data
  758. if(nodeChannel->mNumPositionKeys > 0) {
  759. C_STRUCT aiVector3D* translationData = new aiVector3D[numKeyframes];
  760. for (size_t i = 0; i < numKeyframes; ++i) {
  761. size_t frameIndex = i * nodeChannel->mNumPositionKeys / numKeyframes;
  762. translationData[i] = nodeChannel->mPositionKeys[frameIndex].mValue;
  763. }
  764. Ref<Accessor> tranAccessor = ExportData(mAsset, animId, buffer, static_cast<unsigned int>(numKeyframes), translationData, AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  765. if ( tranAccessor ) {
  766. animRef->Parameters.translation = tranAccessor;
  767. }
  768. delete[] translationData;
  769. }
  770. //-------------------------------------------------------
  771. // Extract scale parameter data
  772. if(nodeChannel->mNumScalingKeys > 0) {
  773. C_STRUCT aiVector3D* scaleData = new aiVector3D[numKeyframes];
  774. for (size_t i = 0; i < numKeyframes; ++i) {
  775. size_t frameIndex = i * nodeChannel->mNumScalingKeys / numKeyframes;
  776. scaleData[i] = nodeChannel->mScalingKeys[frameIndex].mValue;
  777. }
  778. Ref<Accessor> scaleAccessor = ExportData(mAsset, animId, buffer, static_cast<unsigned int>(numKeyframes), scaleData, AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  779. if ( scaleAccessor ) {
  780. animRef->Parameters.scale = scaleAccessor;
  781. }
  782. delete[] scaleData;
  783. }
  784. //-------------------------------------------------------
  785. // Extract rotation parameter data
  786. if(nodeChannel->mNumRotationKeys > 0) {
  787. vec4* rotationData = new vec4[numKeyframes];
  788. for (size_t i = 0; i < numKeyframes; ++i) {
  789. size_t frameIndex = i * nodeChannel->mNumRotationKeys / numKeyframes;
  790. rotationData[i][0] = nodeChannel->mRotationKeys[frameIndex].mValue.x;
  791. rotationData[i][1] = nodeChannel->mRotationKeys[frameIndex].mValue.y;
  792. rotationData[i][2] = nodeChannel->mRotationKeys[frameIndex].mValue.z;
  793. rotationData[i][3] = nodeChannel->mRotationKeys[frameIndex].mValue.w;
  794. }
  795. Ref<Accessor> rotAccessor = ExportData(mAsset, animId, buffer, static_cast<unsigned int>(numKeyframes), rotationData, AttribType::VEC4, AttribType::VEC4, ComponentType_FLOAT);
  796. if ( rotAccessor ) {
  797. animRef->Parameters.rotation = rotAccessor;
  798. }
  799. delete[] rotationData;
  800. }
  801. }
  802. void glTFExporter::ExportAnimations()
  803. {
  804. Ref<Buffer> bufferRef = mAsset->buffers.Get(unsigned (0));
  805. for (unsigned int i = 0; i < mScene->mNumAnimations; ++i) {
  806. const aiAnimation* anim = mScene->mAnimations[i];
  807. std::string nameAnim = "anim";
  808. if (anim->mName.length > 0) {
  809. nameAnim = anim->mName.C_Str();
  810. }
  811. for (unsigned int channelIndex = 0; channelIndex < anim->mNumChannels; ++channelIndex) {
  812. const aiNodeAnim* nodeChannel = anim->mChannels[channelIndex];
  813. // It appears that assimp stores this type of animation as multiple animations.
  814. // where each aiNodeAnim in mChannels animates a specific node.
  815. std::string name = nameAnim + "_" + to_string(channelIndex);
  816. name = mAsset->FindUniqueID(name, "animation");
  817. Ref<Animation> animRef = mAsset->animations.Create(name);
  818. /******************* Parameters ********************/
  819. ExtractAnimationData(*mAsset, name, animRef, bufferRef, nodeChannel, static_cast<float>(anim->mTicksPerSecond));
  820. for (unsigned int j = 0; j < 3; ++j) {
  821. std::string channelType;
  822. int channelSize;
  823. switch (j) {
  824. case 0:
  825. channelType = "rotation";
  826. channelSize = nodeChannel->mNumRotationKeys;
  827. break;
  828. case 1:
  829. channelType = "scale";
  830. channelSize = nodeChannel->mNumScalingKeys;
  831. break;
  832. case 2:
  833. channelType = "translation";
  834. channelSize = nodeChannel->mNumPositionKeys;
  835. break;
  836. }
  837. if (channelSize < 1) { continue; }
  838. Animation::AnimChannel tmpAnimChannel;
  839. Animation::AnimSampler tmpAnimSampler;
  840. tmpAnimChannel.sampler = name + "_" + channelType;
  841. tmpAnimChannel.target.path = channelType;
  842. tmpAnimSampler.output = channelType;
  843. tmpAnimSampler.id = name + "_" + channelType;
  844. tmpAnimChannel.target.id = mAsset->nodes.Get(nodeChannel->mNodeName.C_Str());
  845. tmpAnimSampler.input = "TIME";
  846. tmpAnimSampler.interpolation = "LINEAR";
  847. animRef->Channels.push_back(tmpAnimChannel);
  848. animRef->Samplers.push_back(tmpAnimSampler);
  849. }
  850. }
  851. // Assimp documentation staes this is not used (not implemented)
  852. // for (unsigned int channelIndex = 0; channelIndex < anim->mNumMeshChannels; ++channelIndex) {
  853. // const aiMeshAnim* meshChannel = anim->mMeshChannels[channelIndex];
  854. // }
  855. } // End: for-loop mNumAnimations
  856. }
  857. #endif // ASSIMP_BUILD_NO_GLTF_EXPORTER
  858. #endif // ASSIMP_BUILD_NO_EXPORT