glTFExporter.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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 <assimp/version.h>
  40. #include <assimp/IOSystem.hpp>
  41. #include <assimp/Exporter.hpp>
  42. #include <assimp/material.h>
  43. #include <assimp/scene.h>
  44. // Header files, standart library.
  45. #include <memory>
  46. #include <inttypes.h>
  47. #include "glTFAssetWriter.h"
  48. // Header files, Open3DGC.
  49. #include <Open3DGC/o3dgcSC3DMCEncoder.h>
  50. using namespace rapidjson;
  51. using namespace Assimp;
  52. using namespace glTF;
  53. namespace Assimp {
  54. // ------------------------------------------------------------------------------------------------
  55. // Worker function for exporting a scene to GLTF. Prototyped and registered in Exporter.cpp
  56. void ExportSceneGLTF(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
  57. {
  58. // invoke the exporter
  59. glTFExporter exporter(pFile, pIOSystem, pScene, pProperties, false);
  60. }
  61. // ------------------------------------------------------------------------------------------------
  62. // Worker function for exporting a scene to GLB. Prototyped and registered in Exporter.cpp
  63. void ExportSceneGLB(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
  64. {
  65. // invoke the exporter
  66. glTFExporter exporter(pFile, pIOSystem, pScene, pProperties, true);
  67. }
  68. } // end of namespace Assimp
  69. glTFExporter::glTFExporter(const char* filename, IOSystem* pIOSystem, const aiScene* pScene,
  70. const ExportProperties* pProperties, bool isBinary)
  71. : mFilename(filename)
  72. , mIOSystem(pIOSystem)
  73. , mScene(pScene)
  74. , mProperties(pProperties)
  75. {
  76. std::unique_ptr<Asset> asset(new glTF::Asset(pIOSystem));
  77. mAsset = asset.get();
  78. if (isBinary) {
  79. asset->SetAsBinary();
  80. }
  81. ExportMetadata();
  82. //for (unsigned int i = 0; i < pScene->mNumAnimations; ++i) {}
  83. //for (unsigned int i = 0; i < pScene->mNumCameras; ++i) {}
  84. //for (unsigned int i = 0; i < pScene->mNumLights; ++i) {}
  85. ExportMaterials();
  86. ExportMeshes();
  87. //for (unsigned int i = 0; i < pScene->mNumTextures; ++i) {}
  88. if (mScene->mRootNode) {
  89. ExportNode(mScene->mRootNode);
  90. }
  91. ExportScene();
  92. glTF::AssetWriter writer(*mAsset);
  93. writer.WriteFile(filename);
  94. }
  95. static void CopyValue(const aiMatrix4x4& v, glTF::mat4& o)
  96. {
  97. o[ 0] = v.a1; o[ 1] = v.b1; o[ 2] = v.c1; o[ 3] = v.d1;
  98. o[ 4] = v.a2; o[ 5] = v.b2; o[ 6] = v.c2; o[ 7] = v.d2;
  99. o[ 8] = v.a3; o[ 9] = v.b3; o[10] = v.c3; o[11] = v.d3;
  100. o[12] = v.a4; o[13] = v.b4; o[14] = v.c4; o[15] = v.d4;
  101. }
  102. inline Ref<Accessor> ExportData(Asset& a, std::string& meshName, Ref<Buffer>& buffer,
  103. unsigned int count, void* data, AttribType::Value typeIn, AttribType::Value typeOut, ComponentType compType, bool isIndices = false)
  104. {
  105. if (!count || !data) return Ref<Accessor>();
  106. unsigned int numCompsIn = AttribType::GetNumComponents(typeIn);
  107. unsigned int numCompsOut = AttribType::GetNumComponents(typeOut);
  108. unsigned int bytesPerComp = ComponentTypeSize(compType);
  109. size_t offset = buffer->byteLength;
  110. size_t length = count * numCompsOut * bytesPerComp;
  111. buffer->Grow(length);
  112. // bufferView
  113. Ref<BufferView> bv = a.bufferViews.Create(a.FindUniqueID(meshName, "view"));
  114. bv->buffer = buffer;
  115. bv->byteOffset = unsigned(offset);
  116. bv->byteLength = length; //! The target that the WebGL buffer should be bound to.
  117. bv->target = isIndices ? BufferViewTarget_ELEMENT_ARRAY_BUFFER : BufferViewTarget_ARRAY_BUFFER;
  118. // accessor
  119. Ref<Accessor> acc = a.accessors.Create(a.FindUniqueID(meshName, "accessor"));
  120. acc->bufferView = bv;
  121. acc->byteOffset = 0;
  122. acc->byteStride = 0;
  123. acc->componentType = compType;
  124. acc->count = count;
  125. acc->type = typeOut;
  126. // copy the data
  127. acc->WriteData(count, data, numCompsIn*bytesPerComp);
  128. return acc;
  129. }
  130. namespace {
  131. void GetMatScalar(const aiMaterial* mat, float& val, const char* propName, int type, int idx) {
  132. if (mat->Get(propName, type, idx, val) == AI_SUCCESS) {}
  133. }
  134. }
  135. void glTFExporter::GetMatColorOrTex(const aiMaterial* mat, glTF::TexProperty& prop, const char* propName, int type, int idx, aiTextureType tt)
  136. {
  137. aiString tex;
  138. aiColor4D col;
  139. if (mat->GetTextureCount(tt) > 0) {
  140. if (mat->Get(AI_MATKEY_TEXTURE(tt, 0), tex) == AI_SUCCESS) {
  141. std::string path = tex.C_Str();
  142. if (path.size() > 0) {
  143. if (path[0] != '*') {
  144. std::map<std::string, unsigned int>::iterator it = mTexturesByPath.find(path);
  145. if (it != mTexturesByPath.end()) {
  146. prop.texture = mAsset->textures.Get(it->second);
  147. }
  148. }
  149. if (!prop.texture) {
  150. std::string texId = mAsset->FindUniqueID("", "texture");
  151. prop.texture = mAsset->textures.Create(texId);
  152. mTexturesByPath[path] = prop.texture.GetIndex();
  153. std::string imgId = mAsset->FindUniqueID("", "image");
  154. prop.texture->source = mAsset->images.Create(imgId);
  155. if (path[0] == '*') { // embedded
  156. aiTexture* tex = mScene->mTextures[atoi(&path[1])];
  157. uint8_t* data = reinterpret_cast<uint8_t*>(tex->pcData);
  158. prop.texture->source->SetData(data, tex->mWidth, *mAsset);
  159. if (tex->achFormatHint[0]) {
  160. std::string mimeType = "image/";
  161. mimeType += (memcmp(tex->achFormatHint, "jpg", 3) == 0) ? "jpeg" : tex->achFormatHint;
  162. prop.texture->source->mimeType = mimeType;
  163. }
  164. }
  165. else {
  166. prop.texture->source->uri = path;
  167. }
  168. }
  169. }
  170. }
  171. }
  172. if (mat->Get(propName, type, idx, col) == AI_SUCCESS) {
  173. prop.color[0] = col.r; prop.color[1] = col.g; prop.color[2] = col.b; prop.color[3] = col.a;
  174. }
  175. }
  176. void glTFExporter::ExportMaterials()
  177. {
  178. aiString aiName;
  179. for (unsigned int i = 0; i < mScene->mNumMaterials; ++i) {
  180. const aiMaterial* mat = mScene->mMaterials[i];
  181. std::string name;
  182. if (mat->Get(AI_MATKEY_NAME, aiName) == AI_SUCCESS) {
  183. name = aiName.C_Str();
  184. }
  185. name = mAsset->FindUniqueID(name, "material");
  186. Ref<Material> m = mAsset->materials.Create(name);
  187. GetMatColorOrTex(mat, m->ambient, AI_MATKEY_COLOR_AMBIENT, aiTextureType_AMBIENT);
  188. GetMatColorOrTex(mat, m->diffuse, AI_MATKEY_COLOR_DIFFUSE, aiTextureType_DIFFUSE);
  189. GetMatColorOrTex(mat, m->specular, AI_MATKEY_COLOR_SPECULAR, aiTextureType_SPECULAR);
  190. GetMatColorOrTex(mat, m->emission, AI_MATKEY_COLOR_EMISSIVE, aiTextureType_EMISSIVE);
  191. GetMatScalar(mat, m->shininess, AI_MATKEY_SHININESS);
  192. }
  193. }
  194. void glTFExporter::ExportMeshes()
  195. {
  196. // Not for
  197. // using IndicesType = decltype(aiFace::mNumIndices);
  198. // But yes for
  199. // using IndicesType = unsigned short;
  200. // because "ComponentType_UNSIGNED_SHORT" used for indices. And its maximal type according to glTF specification.
  201. using IndicesType = unsigned short;
  202. // Variables needed for compression. BEGIN.
  203. // Indices, not pointers - because pointer to buffer is changin while writing to it.
  204. size_t idx_srcdata_begin;// Index of buffer before writing mesh data. Also, index of begin of coordinates array in buffer.
  205. size_t idx_srcdata_normal = SIZE_MAX;// Index of begin of normals array in buffer. SIZE_MAX - mean that mesh has no normals.
  206. std::vector<size_t> idx_srcdata_tc;// Array of indices. Every index point to begin of texture coordinates array in buffer.
  207. size_t idx_srcdata_ind;// Index of begin of coordinates indices array in buffer.
  208. bool comp_allow;// Point that data of current mesh can be compressed.
  209. // Variables needed for compression. END.
  210. for (unsigned int i = 0; i < mScene->mNumMeshes; ++i) {
  211. const aiMesh* aim = mScene->mMeshes[i];
  212. // Check if compressing requested and mesh can be encoded.
  213. if((aim->mPrimitiveTypes == aiPrimitiveType_TRIANGLE) && (aim->mNumVertices > 0))///TODO: export properties if(compression is needed)
  214. {
  215. comp_allow = true;
  216. idx_srcdata_tc.reserve(AI_MAX_NUMBER_OF_TEXTURECOORDS);
  217. }
  218. else
  219. {
  220. comp_allow = false;
  221. }
  222. std::string meshId = mAsset->FindUniqueID(aim->mName.C_Str(), "mesh");
  223. Ref<Mesh> m = mAsset->meshes.Create(meshId);
  224. m->primitives.resize(1);
  225. Mesh::Primitive& p = m->primitives.back();
  226. p.material = mAsset->materials.Get(aim->mMaterialIndex);
  227. std::string bufferId = mAsset->FindUniqueID(meshId, "buffer");
  228. Ref<Buffer> b = mAsset->GetBodyBuffer();
  229. if (!b) {
  230. b = mAsset->buffers.Create(bufferId);
  231. }
  232. /******************* Vertices ********************/
  233. // If compression is used then you need parameters of uncompressed region: begin and size. At this step "begin" is stored.
  234. if(comp_allow) idx_srcdata_begin = b->byteLength;
  235. Ref<Accessor> v = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mVertices, AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  236. if (v) p.attributes.position.push_back(v);
  237. /******************** Normals ********************/
  238. if(comp_allow && (aim->mNormals > 0)) idx_srcdata_normal = b->byteLength;// Store index of normals array.
  239. Ref<Accessor> n = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mNormals, AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  240. if (n) p.attributes.normal.push_back(n);
  241. /************** Texture coordinates **************/
  242. for (int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  243. if (aim->mNumUVComponents[i] > 0) {
  244. AttribType::Value type = (aim->mNumUVComponents[i] == 2) ? AttribType::VEC2 : AttribType::VEC3;
  245. if(comp_allow) idx_srcdata_tc.push_back(b->byteLength);// Store index of texture coordinates array.
  246. Ref<Accessor> tc = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mTextureCoords[i], AttribType::VEC3, type, ComponentType_FLOAT, true);
  247. if (tc) p.attributes.texcoord.push_back(tc);
  248. }
  249. }
  250. /*************** Vertices indices ****************/
  251. idx_srcdata_ind = b->byteLength;// Store index of indices array.
  252. if (aim->mNumFaces > 0) {
  253. std::vector<IndicesType> indices;
  254. unsigned int nIndicesPerFace = aim->mFaces[0].mNumIndices;
  255. indices.resize(aim->mNumFaces * nIndicesPerFace);
  256. for (size_t i = 0; i < aim->mNumFaces; ++i) {
  257. for (size_t j = 0; j < nIndicesPerFace; ++j) {
  258. indices[i*nIndicesPerFace + j] = uint16_t(aim->mFaces[i].mIndices[j]);
  259. }
  260. }
  261. p.indices = ExportData(*mAsset, meshId, b, unsigned(indices.size()), &indices[0], AttribType::SCALAR, AttribType::SCALAR, ComponentType_UNSIGNED_SHORT, true);
  262. }
  263. switch (aim->mPrimitiveTypes) {
  264. case aiPrimitiveType_POLYGON:
  265. p.mode = PrimitiveMode_TRIANGLES; break; // TODO implement this
  266. case aiPrimitiveType_LINE:
  267. p.mode = PrimitiveMode_LINES; break;
  268. case aiPrimitiveType_POINT:
  269. p.mode = PrimitiveMode_POINTS; break;
  270. default: // aiPrimitiveType_TRIANGLE
  271. p.mode = PrimitiveMode_TRIANGLES;
  272. }
  273. /****************** Compression ******************/
  274. ///TODO: animation: weights, joints.
  275. if(comp_allow)
  276. {
  277. o3dgc::BinaryStream bs;
  278. o3dgc::SC3DMCEncoder<IndicesType> encoder;
  279. o3dgc::IndexedFaceSet<IndicesType> comp_o3dgc_ifs;
  280. o3dgc::SC3DMCEncodeParams comp_o3dgc_params;
  281. unsigned qcoord = 12;///TODO: dbg
  282. unsigned qnormal = 10;///TODO: dbg
  283. unsigned qtexCoord = 10;///TODO: dbg
  284. o3dgc::O3DGCSC3DMCPredictionMode positionPrediction = o3dgc::O3DGC_SC3DMC_PARALLELOGRAM_PREDICTION;///TODO: dbg
  285. o3dgc::O3DGCSC3DMCPredictionMode normalPrediction = o3dgc::O3DGC_SC3DMC_SURF_NORMALS_PREDICTION;///TODO: dbg
  286. o3dgc::O3DGCSC3DMCPredictionMode texcoordPrediction = o3dgc::O3DGC_SC3DMC_PARALLELOGRAM_PREDICTION;///TODO: dbg
  287. // IndexedFacesSet: "Crease angle", "solid", "convex" are set to default.
  288. comp_o3dgc_ifs.SetCCW(true);
  289. comp_o3dgc_ifs.SetIsTriangularMesh(true);
  290. comp_o3dgc_ifs.SetNumFloatAttributes(0);
  291. // Coordinates
  292. comp_o3dgc_params.SetCoordQuantBits(qcoord);///TODO: IME
  293. comp_o3dgc_params.SetCoordPredMode(positionPrediction);///TODO: IME
  294. comp_o3dgc_ifs.SetNCoord(aim->mNumVertices);
  295. comp_o3dgc_ifs.SetCoord((o3dgc::Real* const)&b->GetPointer()[idx_srcdata_begin]);
  296. // Normals
  297. if(idx_srcdata_normal != SIZE_MAX)
  298. {
  299. comp_o3dgc_params.SetNormalQuantBits(qnormal);///TODO: IME
  300. comp_o3dgc_params.SetNormalPredMode(normalPrediction);///TODO: IME
  301. comp_o3dgc_ifs.SetNNormal(aim->mNumVertices);
  302. comp_o3dgc_ifs.SetNormal((o3dgc::Real* const)&b->GetPointer()[idx_srcdata_normal]);
  303. }
  304. // Texture coordinates
  305. for(size_t num_tc = 0; num_tc < idx_srcdata_tc.size(); num_tc++)
  306. {
  307. size_t num = comp_o3dgc_ifs.GetNumFloatAttributes();
  308. comp_o3dgc_params.SetFloatAttributeQuantBits(num, qtexCoord);///TODO: IME
  309. comp_o3dgc_params.SetFloatAttributePredMode(num, texcoordPrediction);///TODO: IME
  310. comp_o3dgc_ifs.SetNFloatAttribute(num, aim->mNumVertices);// number of elements.
  311. comp_o3dgc_ifs.SetFloatAttributeDim(num, aim->mNumUVComponents[i]);// components per element: aiVector3D => x * float
  312. comp_o3dgc_ifs.SetFloatAttributeType(num, o3dgc::O3DGC_IFS_FLOAT_ATTRIBUTE_TYPE_TEXCOORD);
  313. comp_o3dgc_ifs.SetFloatAttribute(num, (o3dgc::Real* const)&b->GetPointer()[idx_srcdata_tc[num_tc]]);
  314. comp_o3dgc_ifs.SetNumFloatAttributes(num + 1);
  315. }
  316. // Coordinates indices
  317. comp_o3dgc_ifs.SetNCoordIndex(aim->mNumFaces);
  318. comp_o3dgc_ifs.SetCoordIndex((IndicesType* const)&b->GetPointer()[idx_srcdata_ind]);
  319. // Prepare to enconding
  320. comp_o3dgc_params.SetNumFloatAttributes(comp_o3dgc_ifs.GetNumFloatAttributes());
  321. comp_o3dgc_params.SetStreamType(o3dgc::O3DGC_STREAM_TYPE_BINARY);///TODO: exporter params
  322. // Encoding
  323. encoder.Encode(comp_o3dgc_params, comp_o3dgc_ifs, bs);
  324. ///TODO: replace data in buffer
  325. }// if(comp_allow)
  326. }// for (unsigned int i = 0; i < mScene->mNumMeshes; ++i) {
  327. ///TODO: export properties if(compression is used)
  328. }
  329. unsigned int glTFExporter::ExportNode(const aiNode* n)
  330. {
  331. Ref<Node> node = mAsset->nodes.Create(mAsset->FindUniqueID(n->mName.C_Str(), "node"));
  332. if (!n->mTransformation.IsIdentity()) {
  333. node->matrix.isPresent = true;
  334. CopyValue(n->mTransformation, node->matrix.value);
  335. }
  336. for (unsigned int i = 0; i < n->mNumMeshes; ++i) {
  337. node->meshes.push_back(mAsset->meshes.Get(n->mMeshes[i]));
  338. }
  339. for (unsigned int i = 0; i < n->mNumChildren; ++i) {
  340. unsigned int idx = ExportNode(n->mChildren[i]);
  341. node->children.push_back(mAsset->nodes.Get(idx));
  342. }
  343. return node.GetIndex();
  344. }
  345. void glTFExporter::ExportScene()
  346. {
  347. const char* sceneName = "defaultScene";
  348. Ref<Scene> scene = mAsset->scenes.Create(sceneName);
  349. // root node will be the first one exported (idx 0)
  350. if (mAsset->nodes.Size() > 0) {
  351. scene->nodes.push_back(mAsset->nodes.Get(0u));
  352. }
  353. // set as the default scene
  354. mAsset->scene = scene;
  355. }
  356. void glTFExporter::ExportMetadata()
  357. {
  358. glTF::AssetMetadata& asset = mAsset->asset;
  359. asset.version = 1;
  360. char buffer[256];
  361. ai_snprintf(buffer, 256, "Open Asset Import Library (assimp v%d.%d.%d)",
  362. aiGetVersionMajor(), aiGetVersionMinor(), aiGetVersionRevision());
  363. asset.generator = buffer;
  364. }
  365. #endif // ASSIMP_BUILD_NO_GLTF_EXPORTER
  366. #endif // ASSIMP_BUILD_NO_EXPORT