glTFExporter.cpp 37 KB

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