glTFExporter.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. #include <memory>
  45. #include "glTFAssetWriter.h"
  46. using namespace rapidjson;
  47. using namespace Assimp;
  48. using namespace glTF;
  49. namespace Assimp {
  50. // ------------------------------------------------------------------------------------------------
  51. // Worker function for exporting a scene to GLTF. Prototyped and registered in Exporter.cpp
  52. void ExportSceneGLTF(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
  53. {
  54. // invoke the exporter
  55. glTFExporter exporter(pFile, pIOSystem, pScene, pProperties, false);
  56. }
  57. // ------------------------------------------------------------------------------------------------
  58. // Worker function for exporting a scene to GLB. Prototyped and registered in Exporter.cpp
  59. void ExportSceneGLB(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
  60. {
  61. // invoke the exporter
  62. glTFExporter exporter(pFile, pIOSystem, pScene, pProperties, true);
  63. }
  64. } // end of namespace Assimp
  65. glTFExporter::glTFExporter(const char* filename, IOSystem* pIOSystem, const aiScene* pScene,
  66. const ExportProperties* pProperties, bool isBinary)
  67. : mFilename(filename)
  68. , mIOSystem(pIOSystem)
  69. , mScene(pScene)
  70. , mProperties(pProperties)
  71. {
  72. std::unique_ptr<Asset> asset(new glTF::Asset(pIOSystem));
  73. mAsset = asset.get();
  74. if (isBinary) {
  75. asset->SetAsBinary();
  76. }
  77. ExportMetadata();
  78. //for (unsigned int i = 0; i < pScene->mNumAnimations; ++i) {}
  79. //for (unsigned int i = 0; i < pScene->mNumCameras; ++i) {}
  80. //for (unsigned int i = 0; i < pScene->mNumLights; ++i) {}
  81. ExportMaterials();
  82. ExportMeshes();
  83. //for (unsigned int i = 0; i < pScene->mNumTextures; ++i) {}
  84. if (mScene->mRootNode) {
  85. ExportNode(mScene->mRootNode);
  86. }
  87. ExportScene();
  88. glTF::AssetWriter writer(*mAsset);
  89. writer.WriteFile(filename);
  90. }
  91. static void CopyValue(const aiMatrix4x4& v, glTF::mat4& o)
  92. {
  93. o[ 0] = v.a1; o[ 1] = v.b1; o[ 2] = v.c1; o[ 3] = v.d1;
  94. o[ 4] = v.a2; o[ 5] = v.b2; o[ 6] = v.c2; o[ 7] = v.d2;
  95. o[ 8] = v.a3; o[ 9] = v.b3; o[10] = v.c3; o[11] = v.d3;
  96. o[12] = v.a4; o[13] = v.b4; o[14] = v.c4; o[15] = v.d4;
  97. }
  98. inline Ref<Accessor> ExportData(Asset& a, std::string& meshName, Ref<Buffer>& buffer,
  99. unsigned int count, void* data, AttribType::Value typeIn, AttribType::Value typeOut, ComponentType compType, bool isIndices = false)
  100. {
  101. if (!count || !data) return Ref<Accessor>();
  102. unsigned int numCompsIn = AttribType::GetNumComponents(typeIn);
  103. unsigned int numCompsOut = AttribType::GetNumComponents(typeOut);
  104. unsigned int bytesPerComp = ComponentTypeSize(compType);
  105. size_t offset = buffer->byteLength;
  106. size_t length = count * numCompsOut * bytesPerComp;
  107. buffer->Grow(length);
  108. // bufferView
  109. Ref<BufferView> bv = a.bufferViews.Create(a.FindUniqueID(meshName, "view"));
  110. bv->buffer = buffer;
  111. bv->byteOffset = unsigned(offset);
  112. bv->byteLength = length; //! The target that the WebGL buffer should be bound to.
  113. bv->target = isIndices ? BufferViewTarget_ELEMENT_ARRAY_BUFFER : BufferViewTarget_ARRAY_BUFFER;
  114. // accessor
  115. Ref<Accessor> acc = a.accessors.Create(a.FindUniqueID(meshName, "accessor"));
  116. acc->bufferView = bv;
  117. acc->byteOffset = 0;
  118. acc->byteStride = 0;
  119. acc->componentType = compType;
  120. acc->count = count;
  121. acc->type = typeOut;
  122. // copy the data
  123. acc->WriteData(count, data, numCompsIn*bytesPerComp);
  124. return acc;
  125. }
  126. namespace {
  127. void GetMatScalar(const aiMaterial* mat, float& val, const char* propName, int type, int idx) {
  128. if (mat->Get(propName, type, idx, val) == AI_SUCCESS) {}
  129. }
  130. }
  131. void glTFExporter::GetMatColorOrTex(const aiMaterial* mat, glTF::TexProperty& prop, const char* propName, int type, int idx, aiTextureType tt)
  132. {
  133. aiString tex;
  134. aiColor4D col;
  135. if (mat->GetTextureCount(tt) > 0) {
  136. if (mat->Get(AI_MATKEY_TEXTURE(tt, 0), tex) == AI_SUCCESS) {
  137. std::string path = tex.C_Str();
  138. if (path.size() > 0) {
  139. if (path[0] != '*') {
  140. std::map<std::string, unsigned int>::iterator it = mTexturesByPath.find(path);
  141. if (it != mTexturesByPath.end()) {
  142. prop.texture = mAsset->textures.Get(it->second);
  143. }
  144. }
  145. if (!prop.texture) {
  146. std::string texId = mAsset->FindUniqueID("", "texture");
  147. prop.texture = mAsset->textures.Create(texId);
  148. mTexturesByPath[path] = prop.texture.GetIndex();
  149. std::string imgId = mAsset->FindUniqueID("", "image");
  150. prop.texture->source = mAsset->images.Create(imgId);
  151. if (path[0] == '*') { // embedded
  152. aiTexture* tex = mScene->mTextures[atoi(&path[1])];
  153. uint8_t* data = reinterpret_cast<uint8_t*>(tex->pcData);
  154. prop.texture->source->SetData(data, tex->mWidth, *mAsset);
  155. if (tex->achFormatHint[0]) {
  156. std::string mimeType = "image/";
  157. mimeType += (memcmp(tex->achFormatHint, "jpg", 3) == 0) ? "jpeg" : tex->achFormatHint;
  158. prop.texture->source->mimeType = mimeType;
  159. }
  160. }
  161. else {
  162. prop.texture->source->uri = path;
  163. }
  164. }
  165. }
  166. }
  167. }
  168. if (mat->Get(propName, type, idx, col) == AI_SUCCESS) {
  169. prop.color[0] = col.r; prop.color[1] = col.g; prop.color[2] = col.b; prop.color[3] = col.a;
  170. }
  171. }
  172. void glTFExporter::ExportMaterials()
  173. {
  174. aiString aiName;
  175. for (unsigned int i = 0; i < mScene->mNumMaterials; ++i) {
  176. const aiMaterial* mat = mScene->mMaterials[i];
  177. std::string name;
  178. if (mat->Get(AI_MATKEY_NAME, aiName) == AI_SUCCESS) {
  179. name = aiName.C_Str();
  180. }
  181. name = mAsset->FindUniqueID(name, "material");
  182. Ref<Material> m = mAsset->materials.Create(name);
  183. GetMatColorOrTex(mat, m->ambient, AI_MATKEY_COLOR_AMBIENT, aiTextureType_AMBIENT);
  184. GetMatColorOrTex(mat, m->diffuse, AI_MATKEY_COLOR_DIFFUSE, aiTextureType_DIFFUSE);
  185. GetMatColorOrTex(mat, m->specular, AI_MATKEY_COLOR_SPECULAR, aiTextureType_SPECULAR);
  186. GetMatColorOrTex(mat, m->emission, AI_MATKEY_COLOR_EMISSIVE, aiTextureType_EMISSIVE);
  187. GetMatScalar(mat, m->shininess, AI_MATKEY_SHININESS);
  188. }
  189. }
  190. void glTFExporter::ExportMeshes()
  191. {
  192. for (unsigned int i = 0; i < mScene->mNumMeshes; ++i) {
  193. const aiMesh* aim = mScene->mMeshes[i];
  194. std::string meshId = mAsset->FindUniqueID(aim->mName.C_Str(), "mesh");
  195. Ref<Mesh> m = mAsset->meshes.Create(meshId);
  196. m->primitives.resize(1);
  197. Mesh::Primitive& p = m->primitives.back();
  198. p.material = mAsset->materials.Get(aim->mMaterialIndex);
  199. std::string bufferId = mAsset->FindUniqueID(meshId, "buffer");
  200. Ref<Buffer> b = mAsset->GetBodyBuffer();
  201. if (!b) {
  202. b = mAsset->buffers.Create(bufferId);
  203. }
  204. Ref<Accessor> v = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mVertices, AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  205. if (v) p.attributes.position.push_back(v);
  206. Ref<Accessor> n = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mNormals, AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  207. if (n) p.attributes.normal.push_back(n);
  208. for (int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  209. if (aim->mNumUVComponents[i] > 0) {
  210. AttribType::Value type = (aim->mNumUVComponents[i] == 2) ? AttribType::VEC2 : AttribType::VEC3;
  211. Ref<Accessor> tc = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mTextureCoords[i], AttribType::VEC3, type, ComponentType_FLOAT, true);
  212. if (tc) p.attributes.texcoord.push_back(tc);
  213. }
  214. }
  215. if (aim->mNumFaces > 0) {
  216. unsigned int nIndicesPerFace = aim->mFaces[0].mNumIndices;
  217. std::vector<uint16_t> indices;
  218. indices.resize(aim->mNumFaces * nIndicesPerFace);
  219. for (size_t i = 0; i < aim->mNumFaces; ++i) {
  220. for (size_t j = 0; j < nIndicesPerFace; ++j) {
  221. indices[i*nIndicesPerFace + j] = uint16_t(aim->mFaces[i].mIndices[j]);
  222. }
  223. }
  224. p.indices = ExportData(*mAsset, meshId, b, unsigned(indices.size()), &indices[0], AttribType::SCALAR, AttribType::SCALAR, ComponentType_UNSIGNED_SHORT, true);
  225. }
  226. switch (aim->mPrimitiveTypes) {
  227. case aiPrimitiveType_POLYGON:
  228. p.mode = PrimitiveMode_TRIANGLES; break; // TODO implement this
  229. case aiPrimitiveType_LINE:
  230. p.mode = PrimitiveMode_LINES; break;
  231. case aiPrimitiveType_POINT:
  232. p.mode = PrimitiveMode_POINTS; break;
  233. default: // aiPrimitiveType_TRIANGLE
  234. p.mode = PrimitiveMode_TRIANGLES;
  235. }
  236. }
  237. }
  238. unsigned int glTFExporter::ExportNode(const aiNode* n)
  239. {
  240. Ref<Node> node = mAsset->nodes.Create(mAsset->FindUniqueID(n->mName.C_Str(), "node"));
  241. if (!n->mTransformation.IsIdentity()) {
  242. node->matrix.isPresent = true;
  243. CopyValue(n->mTransformation, node->matrix.value);
  244. }
  245. for (unsigned int i = 0; i < n->mNumMeshes; ++i) {
  246. node->meshes.push_back(mAsset->meshes.Get(n->mMeshes[i]));
  247. }
  248. for (unsigned int i = 0; i < n->mNumChildren; ++i) {
  249. unsigned int idx = ExportNode(n->mChildren[i]);
  250. node->children.push_back(mAsset->nodes.Get(idx));
  251. }
  252. return node.GetIndex();
  253. }
  254. void glTFExporter::ExportScene()
  255. {
  256. const char* sceneName = "defaultScene";
  257. Ref<Scene> scene = mAsset->scenes.Create(sceneName);
  258. // root node will be the first one exported (idx 0)
  259. if (mAsset->nodes.Size() > 0) {
  260. scene->nodes.push_back(mAsset->nodes.Get(0u));
  261. }
  262. // set as the default scene
  263. mAsset->scene = scene;
  264. }
  265. void glTFExporter::ExportMetadata()
  266. {
  267. glTF::AssetMetadata& asset = mAsset->asset;
  268. asset.version = 1;
  269. char buffer[256];
  270. ai_snprintf(buffer, 256, "Open Asset Import Library (assimp v%d.%d.%d)",
  271. aiGetVersionMajor(), aiGetVersionMinor(), aiGetVersionRevision());
  272. asset.generator = buffer;
  273. }
  274. #endif // ASSIMP_BUILD_NO_GLTF_EXPORTER
  275. #endif // ASSIMP_BUILD_NO_EXPORT