glTFExporter.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2016, 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 "glTFExporter.h"
  36. #include "Exceptional.h"
  37. #include "StringComparison.h"
  38. #include "ByteSwapper.h"
  39. #include "SplitLargeMeshes.h"
  40. #include "SceneCombiner.h"
  41. #include <assimp/version.h>
  42. #include <assimp/IOSystem.hpp>
  43. #include <assimp/Exporter.hpp>
  44. #include <assimp/material.h>
  45. #include <assimp/scene.h>
  46. // Header files, standart library.
  47. #include <memory>
  48. #include <inttypes.h>
  49. #include "glTFAssetWriter.h"
  50. #ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
  51. // Header files, Open3DGC.
  52. # include <Open3DGC/o3dgcSC3DMCEncoder.h>
  53. #endif
  54. using namespace rapidjson;
  55. using namespace Assimp;
  56. using namespace glTF;
  57. namespace Assimp {
  58. // ------------------------------------------------------------------------------------------------
  59. // Worker function for exporting a scene to GLTF. Prototyped and registered in Exporter.cpp
  60. void ExportSceneGLTF(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
  61. {
  62. // invoke the exporter
  63. glTFExporter exporter(pFile, pIOSystem, pScene, pProperties, false);
  64. }
  65. // ------------------------------------------------------------------------------------------------
  66. // Worker function for exporting a scene to GLB. Prototyped and registered in Exporter.cpp
  67. void ExportSceneGLB(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
  68. {
  69. // invoke the exporter
  70. glTFExporter exporter(pFile, pIOSystem, pScene, pProperties, true);
  71. }
  72. } // end of namespace Assimp
  73. glTFExporter::glTFExporter(const char* filename, IOSystem* pIOSystem, const aiScene* pScene,
  74. const ExportProperties* pProperties, bool isBinary)
  75. : mFilename(filename)
  76. , mIOSystem(pIOSystem)
  77. , mProperties(pProperties)
  78. {
  79. aiScene* sceneCopy_tmp;
  80. SceneCombiner::CopyScene(&sceneCopy_tmp, pScene);
  81. std::unique_ptr<aiScene> sceneCopy(sceneCopy_tmp);
  82. SplitLargeMeshesProcess_Triangle tri_splitter;
  83. tri_splitter.SetLimit(0xffff);
  84. tri_splitter.Execute(sceneCopy.get());
  85. SplitLargeMeshesProcess_Vertex vert_splitter;
  86. vert_splitter.SetLimit(0xffff);
  87. vert_splitter.Execute(sceneCopy.get());
  88. mScene = sceneCopy.get();
  89. std::unique_ptr<Asset> asset();
  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. ExportNode(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. static void CopyValue(const aiMatrix4x4& v, glTF::mat4& o)
  113. {
  114. o[ 0] = v.a1; o[ 1] = v.b1; o[ 2] = v.c1; o[ 3] = v.d1;
  115. o[ 4] = v.a2; o[ 5] = v.b2; o[ 6] = v.c2; o[ 7] = v.d2;
  116. o[ 8] = v.a3; o[ 9] = v.b3; o[10] = v.c3; o[11] = v.d3;
  117. o[12] = v.a4; o[13] = v.b4; o[14] = v.c4; o[15] = v.d4;
  118. }
  119. static void IdentityMatrix4(glTF::mat4& o)
  120. {
  121. o[ 0] = 1; o[ 1] = 0; o[ 2] = 0; o[ 3] = 0;
  122. o[ 4] = 0; o[ 5] = 1; o[ 6] = 0; o[ 7] = 0;
  123. o[ 8] = 0; o[ 9] = 0; o[10] = 1; o[11] = 0;
  124. o[12] = 0; o[13] = 0; o[14] = 0; o[15] = 1;
  125. }
  126. inline Ref<Accessor> ExportData(Asset& a, std::string& meshName, Ref<Buffer>& buffer,
  127. unsigned int count, void* data, AttribType::Value typeIn, AttribType::Value typeOut, ComponentType compType, bool isIndices = false)
  128. {
  129. if (!count || !data) return Ref<Accessor>();
  130. unsigned int numCompsIn = AttribType::GetNumComponents(typeIn);
  131. unsigned int numCompsOut = AttribType::GetNumComponents(typeOut);
  132. unsigned int bytesPerComp = ComponentTypeSize(compType);
  133. size_t offset = buffer->byteLength;
  134. size_t length = count * numCompsOut * bytesPerComp;
  135. buffer->Grow(length);
  136. // bufferView
  137. Ref<BufferView> bv = a.bufferViews.Create(a.FindUniqueID(meshName, "view"));
  138. bv->buffer = buffer;
  139. bv->byteOffset = unsigned(offset);
  140. bv->byteLength = length; //! The target that the WebGL buffer should be bound to.
  141. bv->target = isIndices ? BufferViewTarget_ELEMENT_ARRAY_BUFFER : BufferViewTarget_ARRAY_BUFFER;
  142. // accessor
  143. Ref<Accessor> acc = a.accessors.Create(a.FindUniqueID(meshName, "accessor"));
  144. acc->bufferView = bv;
  145. acc->byteOffset = 0;
  146. acc->byteStride = 0;
  147. acc->componentType = compType;
  148. acc->count = count;
  149. acc->type = typeOut;
  150. // calculate min and max values
  151. {
  152. // Allocate and initialize with large values.
  153. float float_MAX = 10000000000000;
  154. for (int i = 0 ; i < numCompsOut ; i++) {
  155. acc->min.push_back( float_MAX);
  156. acc->max.push_back(-float_MAX);
  157. }
  158. // Search and set extreme values.
  159. float valueTmp;
  160. for (int i = 0 ; i < count ; i++) {
  161. for (int j = 0 ; j < numCompsOut ; j++) {
  162. if (numCompsOut == 1) {
  163. valueTmp = static_cast<unsigned short*>(data)[i];
  164. } else {
  165. valueTmp = static_cast<aiVector3D*>(data)[i][j];
  166. }
  167. if (valueTmp < acc->min[j]) {
  168. acc->min[j] = valueTmp;
  169. }
  170. if (valueTmp > acc->max[j]) {
  171. acc->max[j] = valueTmp;
  172. }
  173. }
  174. }
  175. }
  176. // copy the data
  177. acc->WriteData(count, data, numCompsIn*bytesPerComp);
  178. return acc;
  179. }
  180. namespace {
  181. void GetMatScalar(const aiMaterial* mat, float& val, const char* propName, int type, int idx) {
  182. if (mat->Get(propName, type, idx, val) == AI_SUCCESS) {}
  183. }
  184. }
  185. void glTFExporter::GetTexSampler(const aiMaterial* mat, glTF::TexProperty& prop)
  186. {
  187. std::string samplerId = mAsset->FindUniqueID("", "sampler");
  188. prop.texture->sampler = mAsset->samplers.Create(samplerId);
  189. aiTextureMapMode mapU, mapV;
  190. aiGetMaterialInteger(mat,AI_MATKEY_MAPPINGMODE_U_DIFFUSE(0),(int*)&mapU);
  191. aiGetMaterialInteger(mat,AI_MATKEY_MAPPINGMODE_V_DIFFUSE(0),(int*)&mapV);
  192. switch (mapU) {
  193. case aiTextureMapMode_Wrap:
  194. prop.texture->sampler->wrapS = SamplerWrap_Repeat;
  195. break;
  196. case aiTextureMapMode_Clamp:
  197. prop.texture->sampler->wrapS = SamplerWrap_Clamp_To_Edge;
  198. break;
  199. case aiTextureMapMode_Mirror:
  200. prop.texture->sampler->wrapS = SamplerWrap_Mirrored_Repeat;
  201. break;
  202. case aiTextureMapMode_Decal:
  203. default:
  204. prop.texture->sampler->wrapS = SamplerWrap_Repeat;
  205. break;
  206. };
  207. switch (mapV) {
  208. case aiTextureMapMode_Wrap:
  209. prop.texture->sampler->wrapT = SamplerWrap_Repeat;
  210. break;
  211. case aiTextureMapMode_Clamp:
  212. prop.texture->sampler->wrapT = SamplerWrap_Clamp_To_Edge;
  213. break;
  214. case aiTextureMapMode_Mirror:
  215. prop.texture->sampler->wrapT = SamplerWrap_Mirrored_Repeat;
  216. break;
  217. case aiTextureMapMode_Decal:
  218. default:
  219. prop.texture->sampler->wrapT = SamplerWrap_Repeat;
  220. break;
  221. };
  222. // Hard coded Texture filtering options because I do not know where to find them in the aiMaterial.
  223. prop.texture->sampler->magFilter = SamplerMagFilter_Linear;
  224. prop.texture->sampler->minFilter = SamplerMinFilter_Linear;
  225. }
  226. void glTFExporter::GetMatColorOrTex(const aiMaterial* mat, glTF::TexProperty& prop, const char* propName, int type, int idx, aiTextureType tt)
  227. {
  228. aiString tex;
  229. aiColor4D col;
  230. if (mat->GetTextureCount(tt) > 0) {
  231. if (mat->Get(AI_MATKEY_TEXTURE(tt, 0), tex) == AI_SUCCESS) {
  232. std::string path = tex.C_Str();
  233. if (path.size() > 0) {
  234. if (path[0] != '*') {
  235. std::map<std::string, unsigned int>::iterator it = mTexturesByPath.find(path);
  236. if (it != mTexturesByPath.end()) {
  237. prop.texture = mAsset->textures.Get(it->second);
  238. }
  239. }
  240. if (!prop.texture) {
  241. std::string texId = mAsset->FindUniqueID("", "texture");
  242. prop.texture = mAsset->textures.Create(texId);
  243. mTexturesByPath[path] = prop.texture.GetIndex();
  244. std::string imgId = mAsset->FindUniqueID("", "image");
  245. prop.texture->source = mAsset->images.Create(imgId);
  246. if (path[0] == '*') { // embedded
  247. aiTexture* tex = mScene->mTextures[atoi(&path[1])];
  248. uint8_t* data = reinterpret_cast<uint8_t*>(tex->pcData);
  249. prop.texture->source->SetData(data, tex->mWidth, *mAsset);
  250. if (tex->achFormatHint[0]) {
  251. std::string mimeType = "image/";
  252. mimeType += (memcmp(tex->achFormatHint, "jpg", 3) == 0) ? "jpeg" : tex->achFormatHint;
  253. prop.texture->source->mimeType = mimeType;
  254. }
  255. }
  256. else {
  257. prop.texture->source->uri = path;
  258. }
  259. GetTexSampler(mat, prop);
  260. }
  261. }
  262. }
  263. }
  264. if (mat->Get(propName, type, idx, col) == AI_SUCCESS) {
  265. prop.color[0] = col.r; prop.color[1] = col.g; prop.color[2] = col.b; prop.color[3] = col.a;
  266. }
  267. }
  268. void glTFExporter::ExportMaterials()
  269. {
  270. aiString aiName;
  271. for (unsigned int i = 0; i < mScene->mNumMaterials; ++i) {
  272. const aiMaterial* mat = mScene->mMaterials[i];
  273. std::string name;
  274. if (mat->Get(AI_MATKEY_NAME, aiName) == AI_SUCCESS) {
  275. name = aiName.C_Str();
  276. }
  277. name = mAsset->FindUniqueID(name, "material");
  278. Ref<Material> m = mAsset->materials.Create(name);
  279. GetMatColorOrTex(mat, m->ambient, AI_MATKEY_COLOR_AMBIENT, aiTextureType_AMBIENT);
  280. GetMatColorOrTex(mat, m->diffuse, AI_MATKEY_COLOR_DIFFUSE, aiTextureType_DIFFUSE);
  281. GetMatColorOrTex(mat, m->specular, AI_MATKEY_COLOR_SPECULAR, aiTextureType_SPECULAR);
  282. GetMatColorOrTex(mat, m->emission, AI_MATKEY_COLOR_EMISSIVE, aiTextureType_EMISSIVE);
  283. m->transparent = mat->Get(AI_MATKEY_OPACITY, m->transparency) == aiReturn_SUCCESS && m->transparency != 1.0;
  284. GetMatScalar(mat, m->shininess, AI_MATKEY_SHININESS);
  285. }
  286. }
  287. void ExportSkin(Asset& mAsset, const aiMesh* aim, Ref<Mesh>& meshRef, Ref<Buffer>& bufferRef)
  288. {
  289. std::string skinName = aim->mName.C_Str();
  290. skinName = mAsset.FindUniqueID(skinName, "skin");
  291. Ref<Skin> skinRef = mAsset.skins.Create(skinName);
  292. skinRef->name = skinName;
  293. mat4* inverseBindMatricesData = new mat4[aim->mNumBones];
  294. //-------------------------------------------------------
  295. // Store the vertex joint and weight data.
  296. vec4* vertexJointData = new vec4[aim->mNumVertices];
  297. vec4* vertexWeightData = new vec4[aim->mNumVertices];
  298. unsigned int* jointsPerVertex = new unsigned int[aim->mNumVertices];
  299. for (size_t i = 0; i < aim->mNumVertices; ++i) {
  300. jointsPerVertex[i] = 0;
  301. for (size_t j = 0; j < 4; ++j) {
  302. vertexJointData[i][j] = 0;
  303. vertexWeightData[i][j] = 0;
  304. }
  305. }
  306. for (unsigned int idx_bone = 0; idx_bone < aim->mNumBones; ++idx_bone) {
  307. const aiBone* aib = aim->mBones[idx_bone];
  308. // aib->mName =====> skinRef->jointNames
  309. // Find the node with id = mName.
  310. Ref<Node> nodeRef = mAsset.nodes.Get(aib->mName.C_Str());
  311. nodeRef->jointName = "joint_" + std::to_string(idx_bone);
  312. skinRef->jointNames.push_back("joint_" + std::to_string(idx_bone));
  313. // Identity Matrix =====> skinRef->bindShapeMatrix
  314. // Temporary. Hard-coded identity matrix here
  315. skinRef->bindShapeMatrix.isPresent = true;
  316. IdentityMatrix4(skinRef->bindShapeMatrix.value);
  317. // aib->mOffsetMatrix =====> skinRef->inverseBindMatrices
  318. CopyValue(aib->mOffsetMatrix, inverseBindMatricesData[idx_bone]);
  319. // aib->mWeights =====> vertexWeightData
  320. for (unsigned int idx_weights = 0; idx_weights < aib->mNumWeights; ++idx_weights) {
  321. aiVertexWeight tmpVertWeight = aib->mWeights[idx_weights];
  322. vertexJointData[tmpVertWeight.mVertexId][jointsPerVertex[tmpVertWeight.mVertexId]] = idx_bone;
  323. vertexWeightData[tmpVertWeight.mVertexId][jointsPerVertex[tmpVertWeight.mVertexId]] = tmpVertWeight.mWeight;
  324. jointsPerVertex[tmpVertWeight.mVertexId] += 1;
  325. }
  326. } // End: for-loop mNumMeshes
  327. // Create the Accessor for skinRef->inverseBindMatrices
  328. Ref<Accessor> invBindMatrixAccessor = ExportData(mAsset, skinName, bufferRef, aim->mNumBones, inverseBindMatricesData, AttribType::MAT4, AttribType::MAT4, ComponentType_FLOAT);
  329. if (invBindMatrixAccessor) skinRef->inverseBindMatrices = invBindMatrixAccessor;
  330. Mesh::Primitive& p = meshRef->primitives.back();
  331. Ref<Accessor> vertexJointAccessor = ExportData(mAsset, skinName, bufferRef, aim->mNumVertices, vertexJointData, AttribType::VEC4, AttribType::VEC4, ComponentType_FLOAT);
  332. if (vertexJointAccessor) p.attributes.joint.push_back(vertexJointAccessor);
  333. Ref<Accessor> vertexWeightAccessor = ExportData(mAsset, skinName, bufferRef, aim->mNumVertices, vertexWeightData, AttribType::VEC4, AttribType::VEC4, ComponentType_FLOAT);
  334. if (vertexWeightAccessor) p.attributes.weight.push_back(vertexWeightAccessor);
  335. // Create the skinned mesh instance node.
  336. Ref<Node> node = mAsset.nodes.Create(mAsset.FindUniqueID(skinName, "node"));
  337. // Ref<Node> node = mAsset.nodes.Get(aim->mBones[0]->mName.C_Str());
  338. node->meshes.push_back(meshRef);
  339. node->name = node->id;
  340. node->skeletons.push_back(mAsset.nodes.Get(aim->mBones[0]->mName.C_Str()));
  341. node->skin = skinRef;
  342. }
  343. void glTFExporter::ExportMeshes()
  344. {
  345. // Not for
  346. // using IndicesType = decltype(aiFace::mNumIndices);
  347. // But yes for
  348. // using IndicesType = unsigned short;
  349. // because "ComponentType_UNSIGNED_SHORT" used for indices. And it's a maximal type according to glTF specification.
  350. typedef unsigned short IndicesType;
  351. // Variables needed for compression. BEGIN.
  352. // Indices, not pointers - because pointer to buffer is changing while writing to it.
  353. size_t idx_srcdata_begin;// Index of buffer before writing mesh data. Also, index of begin of coordinates array in buffer.
  354. size_t idx_srcdata_normal = SIZE_MAX;// Index of begin of normals array in buffer. SIZE_MAX - mean that mesh has no normals.
  355. std::vector<size_t> idx_srcdata_tc;// Array of indices. Every index point to begin of texture coordinates array in buffer.
  356. size_t idx_srcdata_ind;// Index of begin of coordinates indices array in buffer.
  357. bool comp_allow;// Point that data of current mesh can be compressed.
  358. // Variables needed for compression. END.
  359. std::string fname = std::string(mFilename);
  360. std::string bufferIdPrefix = fname.substr(0, fname.find("."));
  361. std::string bufferId = mAsset->FindUniqueID("", bufferIdPrefix.c_str());
  362. Ref<Buffer> b = mAsset->GetBodyBuffer();
  363. if (!b) {
  364. b = mAsset->buffers.Create(bufferId);
  365. }
  366. for (unsigned int idx_mesh = 0; idx_mesh < mScene->mNumMeshes; ++idx_mesh) {
  367. const aiMesh* aim = mScene->mMeshes[idx_mesh];
  368. // Check if compressing requested and mesh can be encoded.
  369. #ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
  370. comp_allow = mProperties->GetPropertyBool("extensions.Open3DGC.use", false);
  371. #else
  372. comp_allow = false;
  373. #endif
  374. if(comp_allow && (aim->mPrimitiveTypes == aiPrimitiveType_TRIANGLE) && (aim->mNumVertices > 0) && (aim->mNumFaces > 0))
  375. {
  376. idx_srcdata_tc.clear();
  377. idx_srcdata_tc.reserve(AI_MAX_NUMBER_OF_TEXTURECOORDS);
  378. }
  379. else
  380. {
  381. std::string msg;
  382. if(aim->mPrimitiveTypes != aiPrimitiveType_TRIANGLE)
  383. msg = "all primitives of the mesh must be a triangles.";
  384. else
  385. msg = "mesh must has vertices and faces.";
  386. DefaultLogger::get()->warn("GLTF: can not use Open3DGC-compression: " + msg);
  387. comp_allow = false;
  388. }
  389. std::string meshId = mAsset->FindUniqueID(aim->mName.C_Str(), "mesh");
  390. Ref<Mesh> m = mAsset->meshes.Create(meshId);
  391. m->primitives.resize(1);
  392. Mesh::Primitive& p = m->primitives.back();
  393. p.material = mAsset->materials.Get(aim->mMaterialIndex);
  394. /******************* Vertices ********************/
  395. // If compression is used then you need parameters of uncompressed region: begin and size. At this step "begin" is stored.
  396. if(comp_allow) idx_srcdata_begin = b->byteLength;
  397. Ref<Accessor> v = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mVertices, AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  398. if (v) p.attributes.position.push_back(v);
  399. /******************** Normals ********************/
  400. if(comp_allow && (aim->mNormals > 0)) idx_srcdata_normal = b->byteLength;// Store index of normals array.
  401. Ref<Accessor> n = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mNormals, AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  402. if (n) p.attributes.normal.push_back(n);
  403. /************** Texture coordinates **************/
  404. for (int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  405. // Flip UV y coords
  406. if (aim -> mNumUVComponents[i] > 1) {
  407. for (unsigned int j = 0; j < aim->mNumVertices; ++j) {
  408. aim->mTextureCoords[i][j].y = 1 - aim->mTextureCoords[i][j].y;
  409. }
  410. }
  411. if (aim->mNumUVComponents[i] > 0) {
  412. AttribType::Value type = (aim->mNumUVComponents[i] == 2) ? AttribType::VEC2 : AttribType::VEC3;
  413. if(comp_allow) idx_srcdata_tc.push_back(b->byteLength);// Store index of texture coordinates array.
  414. Ref<Accessor> tc = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mTextureCoords[i], AttribType::VEC3, type, ComponentType_FLOAT, false);
  415. if (tc) p.attributes.texcoord.push_back(tc);
  416. }
  417. }
  418. /*************** Vertices indices ****************/
  419. idx_srcdata_ind = b->byteLength;// Store index of indices array.
  420. if (aim->mNumFaces > 0) {
  421. std::vector<IndicesType> indices;
  422. unsigned int nIndicesPerFace = aim->mFaces[0].mNumIndices;
  423. indices.resize(aim->mNumFaces * nIndicesPerFace);
  424. for (size_t i = 0; i < aim->mNumFaces; ++i) {
  425. for (size_t j = 0; j < nIndicesPerFace; ++j) {
  426. indices[i*nIndicesPerFace + j] = uint16_t(aim->mFaces[i].mIndices[j]);
  427. }
  428. }
  429. p.indices = ExportData(*mAsset, meshId, b, unsigned(indices.size()), &indices[0], AttribType::SCALAR, AttribType::SCALAR, ComponentType_UNSIGNED_SHORT, true);
  430. }
  431. switch (aim->mPrimitiveTypes) {
  432. case aiPrimitiveType_POLYGON:
  433. p.mode = PrimitiveMode_TRIANGLES; break; // TODO implement this
  434. case aiPrimitiveType_LINE:
  435. p.mode = PrimitiveMode_LINES; break;
  436. case aiPrimitiveType_POINT:
  437. p.mode = PrimitiveMode_POINTS; break;
  438. default: // aiPrimitiveType_TRIANGLE
  439. p.mode = PrimitiveMode_TRIANGLES;
  440. }
  441. /*************** Skins ****************/
  442. ///TODO: Fix skinning animation
  443. // if(aim->HasBones()) {
  444. // ExportSkin(*mAsset, aim, m, b);
  445. // }
  446. /****************** Compression ******************/
  447. ///TODO: animation: weights, joints.
  448. if(comp_allow)
  449. {
  450. #ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
  451. // Only one type of compression supported at now - Open3DGC.
  452. //
  453. o3dgc::BinaryStream bs;
  454. o3dgc::SC3DMCEncoder<IndicesType> encoder;
  455. o3dgc::IndexedFaceSet<IndicesType> comp_o3dgc_ifs;
  456. o3dgc::SC3DMCEncodeParams comp_o3dgc_params;
  457. //
  458. // Fill data for encoder.
  459. //
  460. // Quantization
  461. unsigned quant_coord = mProperties->GetPropertyInteger("extensions.Open3DGC.quantization.POSITION", 12);
  462. unsigned quant_normal = mProperties->GetPropertyInteger("extensions.Open3DGC.quantization.NORMAL", 10);
  463. unsigned quant_texcoord = mProperties->GetPropertyInteger("extensions.Open3DGC.quantization.TEXCOORD", 10);
  464. // Prediction
  465. o3dgc::O3DGCSC3DMCPredictionMode prediction_position = o3dgc::O3DGC_SC3DMC_PARALLELOGRAM_PREDICTION;
  466. o3dgc::O3DGCSC3DMCPredictionMode prediction_normal = o3dgc::O3DGC_SC3DMC_SURF_NORMALS_PREDICTION;
  467. o3dgc::O3DGCSC3DMCPredictionMode prediction_texcoord = o3dgc::O3DGC_SC3DMC_PARALLELOGRAM_PREDICTION;
  468. // IndexedFacesSet: "Crease angle", "solid", "convex" are set to default.
  469. comp_o3dgc_ifs.SetCCW(true);
  470. comp_o3dgc_ifs.SetIsTriangularMesh(true);
  471. comp_o3dgc_ifs.SetNumFloatAttributes(0);
  472. // Coordinates
  473. comp_o3dgc_params.SetCoordQuantBits(quant_coord);
  474. comp_o3dgc_params.SetCoordPredMode(prediction_position);
  475. comp_o3dgc_ifs.SetNCoord(aim->mNumVertices);
  476. comp_o3dgc_ifs.SetCoord((o3dgc::Real* const)&b->GetPointer()[idx_srcdata_begin]);
  477. // Normals
  478. if(idx_srcdata_normal != SIZE_MAX)
  479. {
  480. comp_o3dgc_params.SetNormalQuantBits(quant_normal);
  481. comp_o3dgc_params.SetNormalPredMode(prediction_normal);
  482. comp_o3dgc_ifs.SetNNormal(aim->mNumVertices);
  483. comp_o3dgc_ifs.SetNormal((o3dgc::Real* const)&b->GetPointer()[idx_srcdata_normal]);
  484. }
  485. // Texture coordinates
  486. for(size_t num_tc = 0; num_tc < idx_srcdata_tc.size(); num_tc++)
  487. {
  488. size_t num = comp_o3dgc_ifs.GetNumFloatAttributes();
  489. comp_o3dgc_params.SetFloatAttributeQuantBits(num, quant_texcoord);
  490. comp_o3dgc_params.SetFloatAttributePredMode(num, prediction_texcoord);
  491. comp_o3dgc_ifs.SetNFloatAttribute(num, aim->mNumVertices);// number of elements.
  492. comp_o3dgc_ifs.SetFloatAttributeDim(num, aim->mNumUVComponents[num_tc]);// components per element: aiVector3D => x * float
  493. comp_o3dgc_ifs.SetFloatAttributeType(num, o3dgc::O3DGC_IFS_FLOAT_ATTRIBUTE_TYPE_TEXCOORD);
  494. comp_o3dgc_ifs.SetFloatAttribute(num, (o3dgc::Real* const)&b->GetPointer()[idx_srcdata_tc[num_tc]]);
  495. comp_o3dgc_ifs.SetNumFloatAttributes(num + 1);
  496. }
  497. // Coordinates indices
  498. comp_o3dgc_ifs.SetNCoordIndex(aim->mNumFaces);
  499. comp_o3dgc_ifs.SetCoordIndex((IndicesType* const)&b->GetPointer()[idx_srcdata_ind]);
  500. // Prepare to enconding
  501. comp_o3dgc_params.SetNumFloatAttributes(comp_o3dgc_ifs.GetNumFloatAttributes());
  502. if(mProperties->GetPropertyBool("extensions.Open3DGC.binary", true))
  503. comp_o3dgc_params.SetStreamType(o3dgc::O3DGC_STREAM_TYPE_BINARY);
  504. else
  505. comp_o3dgc_params.SetStreamType(o3dgc::O3DGC_STREAM_TYPE_ASCII);
  506. comp_o3dgc_ifs.ComputeMinMax(o3dgc::O3DGC_SC3DMC_MAX_ALL_DIMS);
  507. //
  508. // Encoding
  509. //
  510. encoder.Encode(comp_o3dgc_params, comp_o3dgc_ifs, bs);
  511. // Replace data in buffer.
  512. b->ReplaceData(idx_srcdata_begin, b->byteLength - idx_srcdata_begin, bs.GetBuffer(), bs.GetSize());
  513. //
  514. // Add information about extension to mesh.
  515. //
  516. // Create extension structure.
  517. Mesh::SCompression_Open3DGC* ext = new Mesh::SCompression_Open3DGC;
  518. // Fill it.
  519. ext->Buffer = b->id;
  520. ext->Offset = idx_srcdata_begin;
  521. ext->Count = b->byteLength - idx_srcdata_begin;
  522. ext->Binary = mProperties->GetPropertyBool("extensions.Open3DGC.binary");
  523. ext->IndicesCount = comp_o3dgc_ifs.GetNCoordIndex() * 3;
  524. ext->VerticesCount = comp_o3dgc_ifs.GetNCoord();
  525. // And assign to mesh.
  526. m->Extension.push_back(ext);
  527. #endif
  528. }// if(comp_allow)
  529. }// for (unsigned int i = 0; i < mScene->mNumMeshes; ++i)
  530. }
  531. unsigned int glTFExporter::ExportNode(const aiNode* n)
  532. {
  533. Ref<Node> node = mAsset->nodes.Create(mAsset->FindUniqueID(n->mName.C_Str(), "node"));
  534. if (!n->mTransformation.IsIdentity()) {
  535. node->matrix.isPresent = true;
  536. CopyValue(n->mTransformation, node->matrix.value);
  537. }
  538. for (unsigned int i = 0; i < n->mNumMeshes; ++i) {
  539. node->meshes.push_back(mAsset->meshes.Get(n->mMeshes[i]));
  540. }
  541. for (unsigned int i = 0; i < n->mNumChildren; ++i) {
  542. unsigned int idx = ExportNode(n->mChildren[i]);
  543. node->children.push_back(mAsset->nodes.Get(idx));
  544. }
  545. return node.GetIndex();
  546. }
  547. void glTFExporter::ExportScene()
  548. {
  549. const char* sceneName = "defaultScene";
  550. Ref<Scene> scene = mAsset->scenes.Create(sceneName);
  551. // root node will be the first one exported (idx 0)
  552. if (mAsset->nodes.Size() > 0) {
  553. scene->nodes.push_back(mAsset->nodes.Get(0u));
  554. }
  555. // set as the default scene
  556. mAsset->scene = scene;
  557. }
  558. void glTFExporter::ExportMetadata()
  559. {
  560. glTF::AssetMetadata& asset = mAsset->asset;
  561. asset.version = 1;
  562. char buffer[256];
  563. ai_snprintf(buffer, 256, "Open Asset Import Library (assimp v%d.%d.%d)",
  564. aiGetVersionMajor(), aiGetVersionMinor(), aiGetVersionRevision());
  565. asset.generator = buffer;
  566. }
  567. inline void ExtractAnimationData(Asset& mAsset, std::string& animId, Ref<Animation>& animRef, Ref<Buffer>& buffer, const aiNodeAnim* nodeChannel)
  568. {
  569. // Loop over the data and check to see if it exactly matches an existing buffer.
  570. // If yes, then reference the existing corresponding accessor.
  571. // Otherwise, add to the buffer and create a new accessor.
  572. //-------------------------------------------------------
  573. // Extract TIME parameter data.
  574. // Check if the timeStamps are the same for mPositionKeys, mRotationKeys, and mScalingKeys.
  575. if(nodeChannel->mNumPositionKeys > 0) {
  576. typedef float TimeType;
  577. std::vector<TimeType> timeData;
  578. timeData.resize(nodeChannel->mNumPositionKeys);
  579. for (size_t i = 0; i < nodeChannel->mNumPositionKeys; ++i) {
  580. timeData[i] = nodeChannel->mPositionKeys[i].mTime; // Check if we have to cast type here. e.g. uint16_t()
  581. }
  582. Ref<Accessor> timeAccessor = ExportData(mAsset, animId, buffer, nodeChannel->mNumPositionKeys, &timeData[0], AttribType::SCALAR, AttribType::SCALAR, ComponentType_FLOAT);
  583. if (timeAccessor) animRef->Parameters.TIME = timeAccessor;
  584. }
  585. //-------------------------------------------------------
  586. // Extract translation parameter data
  587. if(nodeChannel->mNumPositionKeys > 0) {
  588. C_STRUCT aiVector3D* translationData = new aiVector3D[nodeChannel->mNumPositionKeys];
  589. for (size_t i = 0; i < nodeChannel->mNumPositionKeys; ++i) {
  590. translationData[i] = nodeChannel->mPositionKeys[i].mValue;
  591. }
  592. Ref<Accessor> tranAccessor = ExportData(mAsset, animId, buffer, nodeChannel->mNumPositionKeys, translationData, AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  593. if (tranAccessor) animRef->Parameters.translation = tranAccessor;
  594. }
  595. //-------------------------------------------------------
  596. // Extract scale parameter data
  597. if(nodeChannel->mNumScalingKeys > 0) {
  598. C_STRUCT aiVector3D* scaleData = new aiVector3D[nodeChannel->mNumScalingKeys];
  599. for (size_t i = 0; i < nodeChannel->mNumScalingKeys; ++i) {
  600. scaleData[i] = nodeChannel->mScalingKeys[i].mValue;
  601. }
  602. Ref<Accessor> scaleAccessor = ExportData(mAsset, animId, buffer, nodeChannel->mNumScalingKeys, scaleData, AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  603. if (scaleAccessor) animRef->Parameters.scale = scaleAccessor;
  604. }
  605. //-------------------------------------------------------
  606. // Extract rotation parameter data
  607. if(nodeChannel->mNumRotationKeys > 0) {
  608. C_STRUCT aiQuaternion* rotationData = new aiQuaternion[nodeChannel->mNumRotationKeys];
  609. for (size_t i = 0; i < nodeChannel->mNumRotationKeys; ++i) {
  610. rotationData[i] = nodeChannel->mRotationKeys[i].mValue;
  611. }
  612. Ref<Accessor> rotAccessor = ExportData(mAsset, animId, buffer, nodeChannel->mNumRotationKeys, rotationData, AttribType::VEC4, AttribType::VEC4, ComponentType_FLOAT);
  613. if (rotAccessor) animRef->Parameters.rotation = rotAccessor;
  614. }
  615. }
  616. void glTFExporter::ExportAnimations()
  617. {
  618. Ref<Buffer> bufferRef = mAsset->buffers.Get(unsigned (0));
  619. for (unsigned int i = 0; i < mScene->mNumAnimations; ++i) {
  620. const aiAnimation* anim = mScene->mAnimations[i];
  621. std::string nameAnim = "anim";
  622. if (anim->mName.length > 0) {
  623. nameAnim = anim->mName.C_Str();
  624. }
  625. for (unsigned int channelIndex = 0; channelIndex < anim->mNumChannels; ++channelIndex) {
  626. const aiNodeAnim* nodeChannel = anim->mChannels[channelIndex];
  627. // It appears that assimp stores this type of animation as multiple animations.
  628. // where each aiNodeAnim in mChannels animates a specific node.
  629. std::string name = nameAnim + "_" + std::to_string(channelIndex);
  630. name = mAsset->FindUniqueID(name, "animation");
  631. Ref<Animation> animRef = mAsset->animations.Create(name);
  632. /******************* Parameters ********************/
  633. ExtractAnimationData(*mAsset, name, animRef, bufferRef, nodeChannel);
  634. for (unsigned int j = 0; j < 3; ++j) {
  635. std::string channelType;
  636. int channelSize;
  637. switch (j) {
  638. case 0:
  639. channelType = "rotation";
  640. channelSize = nodeChannel->mNumRotationKeys;
  641. break;
  642. case 1:
  643. channelType = "scale";
  644. channelSize = nodeChannel->mNumScalingKeys;
  645. break;
  646. case 2:
  647. channelType = "translation";
  648. channelSize = nodeChannel->mNumPositionKeys;
  649. break;
  650. }
  651. if (channelSize < 1) { continue; }
  652. Animation::AnimChannel tmpAnimChannel;
  653. Animation::AnimSampler tmpAnimSampler;
  654. tmpAnimChannel.sampler = name + "_" + channelType;
  655. tmpAnimChannel.target.path = channelType;
  656. tmpAnimSampler.output = channelType;
  657. tmpAnimSampler.id = name + "_" + channelType;
  658. tmpAnimChannel.target.id = mAsset->nodes.Get(nodeChannel->mNodeName.C_Str());
  659. tmpAnimSampler.input = "TIME";
  660. tmpAnimSampler.interpolation = "LINEAR";
  661. animRef->Channels.push_back(tmpAnimChannel);
  662. animRef->Samplers.push_back(tmpAnimSampler);
  663. }
  664. }
  665. // Assimp documentation staes this is not used (not implemented)
  666. // for (unsigned int channelIndex = 0; channelIndex < anim->mNumMeshChannels; ++channelIndex) {
  667. // const aiMeshAnim* meshChannel = anim->mMeshChannels[channelIndex];
  668. // }
  669. } // End: for-loop mNumAnimations
  670. }
  671. #endif // ASSIMP_BUILD_NO_GLTF_EXPORTER
  672. #endif // ASSIMP_BUILD_NO_EXPORT