glTF2Importer.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2019, 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_GLTF_IMPORTER
  34. #include "glTF2Importer.h"
  35. #include <assimp/StringComparison.h>
  36. #include <assimp/StringUtils.h>
  37. #include <assimp/Importer.hpp>
  38. #include <assimp/scene.h>
  39. #include <assimp/ai_assert.h>
  40. #include <assimp/DefaultLogger.hpp>
  41. #include <assimp/importerdesc.h>
  42. #include <assimp/CreateAnimMesh.h>
  43. #include <memory>
  44. #include <unordered_map>
  45. #include "MakeVerboseFormat.h"
  46. #include "glTF2Asset.h"
  47. // This is included here so WriteLazyDict<T>'s definition is found.
  48. #include "glTF2AssetWriter.h"
  49. #include <rapidjson/document.h>
  50. #include <rapidjson/rapidjson.h>
  51. using namespace Assimp;
  52. using namespace glTF2;
  53. namespace {
  54. // generate bitangents from normals and tangents according to spec
  55. struct Tangent {
  56. aiVector3D xyz;
  57. ai_real w;
  58. };
  59. } // namespace
  60. //
  61. // glTF2Importer
  62. //
  63. static const aiImporterDesc desc = {
  64. "glTF2 Importer",
  65. "",
  66. "",
  67. "",
  68. aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_LimitedSupport | aiImporterFlags_Experimental,
  69. 0,
  70. 0,
  71. 0,
  72. 0,
  73. "gltf glb"
  74. };
  75. glTF2Importer::glTF2Importer()
  76. : BaseImporter()
  77. , meshOffsets()
  78. , embeddedTexIdxs()
  79. , mScene( NULL ) {
  80. // empty
  81. }
  82. glTF2Importer::~glTF2Importer() {
  83. // empty
  84. }
  85. const aiImporterDesc* glTF2Importer::GetInfo() const
  86. {
  87. return &desc;
  88. }
  89. bool glTF2Importer::CanRead(const std::string& pFile, IOSystem* pIOHandler, bool /* checkSig */) const
  90. {
  91. const std::string &extension = GetExtension(pFile);
  92. if (extension != "gltf" && extension != "glb")
  93. return false;
  94. if (pIOHandler) {
  95. glTF2::Asset asset(pIOHandler);
  96. asset.Load(pFile, extension == "glb");
  97. std::string version = asset.asset.version;
  98. return !version.empty() && version[0] == '2';
  99. }
  100. return false;
  101. }
  102. static aiTextureMapMode ConvertWrappingMode(SamplerWrap gltfWrapMode)
  103. {
  104. switch (gltfWrapMode) {
  105. case SamplerWrap::Mirrored_Repeat:
  106. return aiTextureMapMode_Mirror;
  107. case SamplerWrap::Clamp_To_Edge:
  108. return aiTextureMapMode_Clamp;
  109. case SamplerWrap::UNSET:
  110. case SamplerWrap::Repeat:
  111. default:
  112. return aiTextureMapMode_Wrap;
  113. }
  114. }
  115. //static void CopyValue(const glTF2::vec3& v, aiColor3D& out)
  116. //{
  117. // out.r = v[0]; out.g = v[1]; out.b = v[2];
  118. //}
  119. static void CopyValue(const glTF2::vec4& v, aiColor4D& out)
  120. {
  121. out.r = v[0]; out.g = v[1]; out.b = v[2]; out.a = v[3];
  122. }
  123. /*static void CopyValue(const glTF2::vec4& v, aiColor3D& out)
  124. {
  125. out.r = v[0]; out.g = v[1]; out.b = v[2];
  126. }*/
  127. static void CopyValue(const glTF2::vec3& v, aiColor4D& out)
  128. {
  129. out.r = v[0]; out.g = v[1]; out.b = v[2]; out.a = 1.0;
  130. }
  131. static void CopyValue(const glTF2::vec3& v, aiVector3D& out)
  132. {
  133. out.x = v[0]; out.y = v[1]; out.z = v[2];
  134. }
  135. static void CopyValue(const glTF2::vec4& v, aiQuaternion& out)
  136. {
  137. out.x = v[0]; out.y = v[1]; out.z = v[2]; out.w = v[3];
  138. }
  139. static void CopyValue(const glTF2::mat4& v, aiMatrix4x4& o)
  140. {
  141. o.a1 = v[ 0]; o.b1 = v[ 1]; o.c1 = v[ 2]; o.d1 = v[ 3];
  142. o.a2 = v[ 4]; o.b2 = v[ 5]; o.c2 = v[ 6]; o.d2 = v[ 7];
  143. o.a3 = v[ 8]; o.b3 = v[ 9]; o.c3 = v[10]; o.d3 = v[11];
  144. o.a4 = v[12]; o.b4 = v[13]; o.c4 = v[14]; o.d4 = v[15];
  145. }
  146. inline void SetMaterialColorProperty(Asset& /*r*/, vec4& prop, aiMaterial* mat, const char* pKey, unsigned int type, unsigned int idx)
  147. {
  148. aiColor4D col;
  149. CopyValue(prop, col);
  150. mat->AddProperty(&col, 1, pKey, type, idx);
  151. }
  152. inline void SetMaterialColorProperty(Asset& /*r*/, vec3& prop, aiMaterial* mat, const char* pKey, unsigned int type, unsigned int idx)
  153. {
  154. aiColor4D col;
  155. CopyValue(prop, col);
  156. mat->AddProperty(&col, 1, pKey, type, idx);
  157. }
  158. inline void SetMaterialTextureProperty(std::vector<int>& embeddedTexIdxs, Asset& /*r*/, glTF2::TextureInfo prop, aiMaterial* mat, aiTextureType texType, unsigned int texSlot = 0)
  159. {
  160. if (prop.texture && prop.texture->source) {
  161. aiString uri(prop.texture->source->uri);
  162. int texIdx = embeddedTexIdxs[prop.texture->source.GetIndex()];
  163. if (texIdx != -1) { // embedded
  164. // setup texture reference string (copied from ColladaLoader::FindFilenameForEffectTexture)
  165. uri.data[0] = '*';
  166. uri.length = 1 + ASSIMP_itoa10(uri.data + 1, MAXLEN - 1, texIdx);
  167. }
  168. mat->AddProperty(&uri, AI_MATKEY_TEXTURE(texType, texSlot));
  169. mat->AddProperty(&prop.texCoord, 1, _AI_MATKEY_GLTF_TEXTURE_TEXCOORD_BASE, texType, texSlot);
  170. if (prop.texture->sampler) {
  171. Ref<Sampler> sampler = prop.texture->sampler;
  172. aiString name(sampler->name);
  173. aiString id(sampler->id);
  174. mat->AddProperty(&name, AI_MATKEY_GLTF_MAPPINGNAME(texType, texSlot));
  175. mat->AddProperty(&id, AI_MATKEY_GLTF_MAPPINGID(texType, texSlot));
  176. aiTextureMapMode wrapS = ConvertWrappingMode(sampler->wrapS);
  177. aiTextureMapMode wrapT = ConvertWrappingMode(sampler->wrapT);
  178. mat->AddProperty(&wrapS, 1, AI_MATKEY_MAPPINGMODE_U(texType, texSlot));
  179. mat->AddProperty(&wrapT, 1, AI_MATKEY_MAPPINGMODE_V(texType, texSlot));
  180. if (sampler->magFilter != SamplerMagFilter::UNSET) {
  181. mat->AddProperty(&sampler->magFilter, 1, AI_MATKEY_GLTF_MAPPINGFILTER_MAG(texType, texSlot));
  182. }
  183. if (sampler->minFilter != SamplerMinFilter::UNSET) {
  184. mat->AddProperty(&sampler->minFilter, 1, AI_MATKEY_GLTF_MAPPINGFILTER_MIN(texType, texSlot));
  185. }
  186. }
  187. }
  188. }
  189. inline void SetMaterialTextureProperty(std::vector<int>& embeddedTexIdxs, Asset& r, glTF2::NormalTextureInfo& prop, aiMaterial* mat, aiTextureType texType, unsigned int texSlot = 0)
  190. {
  191. SetMaterialTextureProperty( embeddedTexIdxs, r, (glTF2::TextureInfo) prop, mat, texType, texSlot );
  192. if (prop.texture && prop.texture->source) {
  193. mat->AddProperty(&prop.scale, 1, AI_MATKEY_GLTF_TEXTURE_SCALE(texType, texSlot));
  194. }
  195. }
  196. inline void SetMaterialTextureProperty(std::vector<int>& embeddedTexIdxs, Asset& r, glTF2::OcclusionTextureInfo& prop, aiMaterial* mat, aiTextureType texType, unsigned int texSlot = 0)
  197. {
  198. SetMaterialTextureProperty( embeddedTexIdxs, r, (glTF2::TextureInfo) prop, mat, texType, texSlot );
  199. if (prop.texture && prop.texture->source) {
  200. mat->AddProperty(&prop.strength, 1, AI_MATKEY_GLTF_TEXTURE_STRENGTH(texType, texSlot));
  201. }
  202. }
  203. static aiMaterial* ImportMaterial(std::vector<int>& embeddedTexIdxs, Asset& r, Material& mat)
  204. {
  205. aiMaterial* aimat = new aiMaterial();
  206. if (!mat.name.empty()) {
  207. aiString str(mat.name);
  208. aimat->AddProperty(&str, AI_MATKEY_NAME);
  209. }
  210. SetMaterialColorProperty(r, mat.pbrMetallicRoughness.baseColorFactor, aimat, AI_MATKEY_COLOR_DIFFUSE);
  211. SetMaterialColorProperty(r, mat.pbrMetallicRoughness.baseColorFactor, aimat, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_FACTOR);
  212. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.baseColorTexture, aimat, aiTextureType_DIFFUSE);
  213. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.baseColorTexture, aimat, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_TEXTURE);
  214. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.metallicRoughnessTexture, aimat, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE);
  215. aimat->AddProperty(&mat.pbrMetallicRoughness.metallicFactor, 1, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLIC_FACTOR);
  216. aimat->AddProperty(&mat.pbrMetallicRoughness.roughnessFactor, 1, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_ROUGHNESS_FACTOR);
  217. float roughnessAsShininess = 1 - mat.pbrMetallicRoughness.roughnessFactor;
  218. roughnessAsShininess *= roughnessAsShininess * 1000;
  219. aimat->AddProperty(&roughnessAsShininess, 1, AI_MATKEY_SHININESS);
  220. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.normalTexture, aimat, aiTextureType_NORMALS);
  221. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.occlusionTexture, aimat, aiTextureType_LIGHTMAP);
  222. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.emissiveTexture, aimat, aiTextureType_EMISSIVE);
  223. SetMaterialColorProperty(r, mat.emissiveFactor, aimat, AI_MATKEY_COLOR_EMISSIVE);
  224. aimat->AddProperty(&mat.doubleSided, 1, AI_MATKEY_TWOSIDED);
  225. aiString alphaMode(mat.alphaMode);
  226. aimat->AddProperty(&alphaMode, AI_MATKEY_GLTF_ALPHAMODE);
  227. aimat->AddProperty(&mat.alphaCutoff, 1, AI_MATKEY_GLTF_ALPHACUTOFF);
  228. //pbrSpecularGlossiness
  229. if (mat.pbrSpecularGlossiness.isPresent) {
  230. PbrSpecularGlossiness &pbrSG = mat.pbrSpecularGlossiness.value;
  231. aimat->AddProperty(&mat.pbrSpecularGlossiness.isPresent, 1, AI_MATKEY_GLTF_PBRSPECULARGLOSSINESS);
  232. SetMaterialColorProperty(r, pbrSG.diffuseFactor, aimat, AI_MATKEY_COLOR_DIFFUSE);
  233. SetMaterialColorProperty(r, pbrSG.specularFactor, aimat, AI_MATKEY_COLOR_SPECULAR);
  234. float glossinessAsShininess = pbrSG.glossinessFactor * 1000.0f;
  235. aimat->AddProperty(&glossinessAsShininess, 1, AI_MATKEY_SHININESS);
  236. aimat->AddProperty(&pbrSG.glossinessFactor, 1, AI_MATKEY_GLTF_PBRSPECULARGLOSSINESS_GLOSSINESS_FACTOR);
  237. SetMaterialTextureProperty(embeddedTexIdxs, r, pbrSG.diffuseTexture, aimat, aiTextureType_DIFFUSE);
  238. SetMaterialTextureProperty(embeddedTexIdxs, r, pbrSG.specularGlossinessTexture, aimat, aiTextureType_SPECULAR);
  239. }
  240. if (mat.unlit) {
  241. aimat->AddProperty(&mat.unlit, 1, AI_MATKEY_GLTF_UNLIT);
  242. }
  243. return aimat;
  244. }
  245. void glTF2Importer::ImportMaterials(glTF2::Asset& r)
  246. {
  247. const unsigned int numImportedMaterials = unsigned(r.materials.Size());
  248. Material defaultMaterial;
  249. mScene->mNumMaterials = numImportedMaterials + 1;
  250. mScene->mMaterials = new aiMaterial*[mScene->mNumMaterials];
  251. mScene->mMaterials[numImportedMaterials] = ImportMaterial(embeddedTexIdxs, r, defaultMaterial);
  252. for (unsigned int i = 0; i < numImportedMaterials; ++i) {
  253. mScene->mMaterials[i] = ImportMaterial(embeddedTexIdxs, r, r.materials[i]);
  254. }
  255. }
  256. static inline void SetFace(aiFace& face, int a)
  257. {
  258. face.mNumIndices = 1;
  259. face.mIndices = new unsigned int[1];
  260. face.mIndices[0] = a;
  261. }
  262. static inline void SetFace(aiFace& face, int a, int b)
  263. {
  264. face.mNumIndices = 2;
  265. face.mIndices = new unsigned int[2];
  266. face.mIndices[0] = a;
  267. face.mIndices[1] = b;
  268. }
  269. static inline void SetFace(aiFace& face, int a, int b, int c)
  270. {
  271. face.mNumIndices = 3;
  272. face.mIndices = new unsigned int[3];
  273. face.mIndices[0] = a;
  274. face.mIndices[1] = b;
  275. face.mIndices[2] = c;
  276. }
  277. #ifdef ASSIMP_BUILD_DEBUG
  278. static inline bool CheckValidFacesIndices(aiFace* faces, unsigned nFaces, unsigned nVerts)
  279. {
  280. for (unsigned i = 0; i < nFaces; ++i) {
  281. for (unsigned j = 0; j < faces[i].mNumIndices; ++j) {
  282. unsigned idx = faces[i].mIndices[j];
  283. if (idx >= nVerts)
  284. return false;
  285. }
  286. }
  287. return true;
  288. }
  289. #endif // ASSIMP_BUILD_DEBUG
  290. void glTF2Importer::ImportMeshes(glTF2::Asset& r)
  291. {
  292. std::vector<aiMesh*> meshes;
  293. unsigned int k = 0;
  294. for (unsigned int m = 0; m < r.meshes.Size(); ++m) {
  295. Mesh& mesh = r.meshes[m];
  296. meshOffsets.push_back(k);
  297. k += unsigned(mesh.primitives.size());
  298. for (unsigned int p = 0; p < mesh.primitives.size(); ++p) {
  299. Mesh::Primitive& prim = mesh.primitives[p];
  300. aiMesh* aim = new aiMesh();
  301. meshes.push_back(aim);
  302. aim->mName = mesh.name.empty() ? mesh.id : mesh.name;
  303. if (mesh.primitives.size() > 1) {
  304. size_t& len = aim->mName.length;
  305. aim->mName.data[len] = '-';
  306. len += 1 + ASSIMP_itoa10(aim->mName.data + len + 1, unsigned(MAXLEN - len - 1), p);
  307. }
  308. switch (prim.mode) {
  309. case PrimitiveMode_POINTS:
  310. aim->mPrimitiveTypes |= aiPrimitiveType_POINT;
  311. break;
  312. case PrimitiveMode_LINES:
  313. case PrimitiveMode_LINE_LOOP:
  314. case PrimitiveMode_LINE_STRIP:
  315. aim->mPrimitiveTypes |= aiPrimitiveType_LINE;
  316. break;
  317. case PrimitiveMode_TRIANGLES:
  318. case PrimitiveMode_TRIANGLE_STRIP:
  319. case PrimitiveMode_TRIANGLE_FAN:
  320. aim->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  321. break;
  322. }
  323. Mesh::Primitive::Attributes& attr = prim.attributes;
  324. if (attr.position.size() > 0 && attr.position[0]) {
  325. aim->mNumVertices = static_cast<unsigned int>(attr.position[0]->count);
  326. attr.position[0]->ExtractData(aim->mVertices);
  327. }
  328. if (attr.normal.size() > 0 && attr.normal[0]) {
  329. attr.normal[0]->ExtractData(aim->mNormals);
  330. // only extract tangents if normals are present
  331. if (attr.tangent.size() > 0 && attr.tangent[0]) {
  332. // generate bitangents from normals and tangents according to spec
  333. Tangent *tangents = nullptr;
  334. attr.tangent[0]->ExtractData(tangents);
  335. aim->mTangents = new aiVector3D[aim->mNumVertices];
  336. aim->mBitangents = new aiVector3D[aim->mNumVertices];
  337. for (unsigned int i = 0; i < aim->mNumVertices; ++i) {
  338. aim->mTangents[i] = tangents[i].xyz;
  339. aim->mBitangents[i] = (aim->mNormals[i] ^ tangents[i].xyz) * tangents[i].w;
  340. }
  341. delete [] tangents;
  342. }
  343. }
  344. for (size_t c = 0; c < attr.color.size() && c < AI_MAX_NUMBER_OF_COLOR_SETS; ++c) {
  345. if (attr.color[c]->count != aim->mNumVertices) {
  346. DefaultLogger::get()->warn("Color stream size in mesh \"" + mesh.name +
  347. "\" does not match the vertex count");
  348. continue;
  349. }
  350. aim->mColors[c] = new aiColor4D[attr.color[c]->count];
  351. attr.color[c]->ExtractData(aim->mColors[c]);
  352. }
  353. for (size_t tc = 0; tc < attr.texcoord.size() && tc < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++tc) {
  354. if (attr.texcoord[tc]->count != aim->mNumVertices) {
  355. DefaultLogger::get()->warn("Texcoord stream size in mesh \"" + mesh.name +
  356. "\" does not match the vertex count");
  357. continue;
  358. }
  359. attr.texcoord[tc]->ExtractData(aim->mTextureCoords[tc]);
  360. aim->mNumUVComponents[tc] = attr.texcoord[tc]->GetNumComponents();
  361. aiVector3D* values = aim->mTextureCoords[tc];
  362. for (unsigned int i = 0; i < aim->mNumVertices; ++i) {
  363. values[i].y = 1 - values[i].y; // Flip Y coords
  364. }
  365. }
  366. std::vector<Mesh::Primitive::Target>& targets = prim.targets;
  367. if (targets.size() > 0) {
  368. aim->mNumAnimMeshes = (unsigned int)targets.size();
  369. aim->mAnimMeshes = new aiAnimMesh*[aim->mNumAnimMeshes];
  370. for (size_t i = 0; i < targets.size(); i++) {
  371. aim->mAnimMeshes[i] = aiCreateAnimMesh(aim);
  372. aiAnimMesh& aiAnimMesh = *(aim->mAnimMeshes[i]);
  373. Mesh::Primitive::Target& target = targets[i];
  374. if (target.position.size() > 0) {
  375. aiVector3D *positionDiff = nullptr;
  376. target.position[0]->ExtractData(positionDiff);
  377. for(unsigned int vertexId = 0; vertexId < aim->mNumVertices; vertexId++) {
  378. aiAnimMesh.mVertices[vertexId] += positionDiff[vertexId];
  379. }
  380. delete [] positionDiff;
  381. }
  382. if (target.normal.size() > 0) {
  383. aiVector3D *normalDiff = nullptr;
  384. target.normal[0]->ExtractData(normalDiff);
  385. for(unsigned int vertexId = 0; vertexId < aim->mNumVertices; vertexId++) {
  386. aiAnimMesh.mNormals[vertexId] += normalDiff[vertexId];
  387. }
  388. delete [] normalDiff;
  389. }
  390. if (target.tangent.size() > 0) {
  391. Tangent *tangent = nullptr;
  392. attr.tangent[0]->ExtractData(tangent);
  393. aiVector3D *tangentDiff = nullptr;
  394. target.tangent[0]->ExtractData(tangentDiff);
  395. for (unsigned int vertexId = 0; vertexId < aim->mNumVertices; ++vertexId) {
  396. tangent[vertexId].xyz += tangentDiff[vertexId];
  397. aiAnimMesh.mTangents[vertexId] = tangent[vertexId].xyz;
  398. aiAnimMesh.mBitangents[vertexId] = (aiAnimMesh.mNormals[vertexId] ^ tangent[vertexId].xyz) * tangent[vertexId].w;
  399. }
  400. delete [] tangent;
  401. delete [] tangentDiff;
  402. }
  403. if (mesh.weights.size() > i) {
  404. aiAnimMesh.mWeight = mesh.weights[i];
  405. }
  406. }
  407. }
  408. aiFace* faces = 0;
  409. size_t nFaces = 0;
  410. if (prim.indices) {
  411. size_t count = prim.indices->count;
  412. Accessor::Indexer data = prim.indices->GetIndexer();
  413. ai_assert(data.IsValid());
  414. switch (prim.mode) {
  415. case PrimitiveMode_POINTS: {
  416. nFaces = count;
  417. faces = new aiFace[nFaces];
  418. for (unsigned int i = 0; i < count; ++i) {
  419. SetFace(faces[i], data.GetUInt(i));
  420. }
  421. break;
  422. }
  423. case PrimitiveMode_LINES: {
  424. nFaces = count / 2;
  425. faces = new aiFace[nFaces];
  426. for (unsigned int i = 0; i < count; i += 2) {
  427. SetFace(faces[i / 2], data.GetUInt(i), data.GetUInt(i + 1));
  428. }
  429. break;
  430. }
  431. case PrimitiveMode_LINE_LOOP:
  432. case PrimitiveMode_LINE_STRIP: {
  433. nFaces = count - ((prim.mode == PrimitiveMode_LINE_STRIP) ? 1 : 0);
  434. faces = new aiFace[nFaces];
  435. SetFace(faces[0], data.GetUInt(0), data.GetUInt(1));
  436. for (unsigned int i = 2; i < count; ++i) {
  437. SetFace(faces[i - 1], faces[i - 2].mIndices[1], data.GetUInt(i));
  438. }
  439. if (prim.mode == PrimitiveMode_LINE_LOOP) { // close the loop
  440. SetFace(faces[count - 1], faces[count - 2].mIndices[1], faces[0].mIndices[0]);
  441. }
  442. break;
  443. }
  444. case PrimitiveMode_TRIANGLES: {
  445. nFaces = count / 3;
  446. faces = new aiFace[nFaces];
  447. for (unsigned int i = 0; i < count; i += 3) {
  448. SetFace(faces[i / 3], data.GetUInt(i), data.GetUInt(i + 1), data.GetUInt(i + 2));
  449. }
  450. break;
  451. }
  452. case PrimitiveMode_TRIANGLE_STRIP: {
  453. nFaces = count - 2;
  454. faces = new aiFace[nFaces];
  455. for (unsigned int i = 0; i < nFaces; ++i) {
  456. //The ordering is to ensure that the triangles are all drawn with the same orientation
  457. if ((i + 1) % 2 == 0)
  458. {
  459. //For even n, vertices n + 1, n, and n + 2 define triangle n
  460. SetFace(faces[i], data.GetUInt(i + 1), data.GetUInt(i), data.GetUInt(i + 2));
  461. }
  462. else
  463. {
  464. //For odd n, vertices n, n+1, and n+2 define triangle n
  465. SetFace(faces[i], data.GetUInt(i), data.GetUInt(i + 1), data.GetUInt(i + 2));
  466. }
  467. }
  468. break;
  469. }
  470. case PrimitiveMode_TRIANGLE_FAN:
  471. nFaces = count - 2;
  472. faces = new aiFace[nFaces];
  473. SetFace(faces[0], data.GetUInt(0), data.GetUInt(1), data.GetUInt(2));
  474. for (unsigned int i = 1; i < nFaces; ++i) {
  475. SetFace(faces[i], faces[0].mIndices[0], faces[i - 1].mIndices[2], data.GetUInt(i + 2));
  476. }
  477. break;
  478. }
  479. }
  480. else { // no indices provided so directly generate from counts
  481. // use the already determined count as it includes checks
  482. unsigned int count = aim->mNumVertices;
  483. switch (prim.mode) {
  484. case PrimitiveMode_POINTS: {
  485. nFaces = count;
  486. faces = new aiFace[nFaces];
  487. for (unsigned int i = 0; i < count; ++i) {
  488. SetFace(faces[i], i);
  489. }
  490. break;
  491. }
  492. case PrimitiveMode_LINES: {
  493. nFaces = count / 2;
  494. faces = new aiFace[nFaces];
  495. for (unsigned int i = 0; i < count; i += 2) {
  496. SetFace(faces[i / 2], i, i + 1);
  497. }
  498. break;
  499. }
  500. case PrimitiveMode_LINE_LOOP:
  501. case PrimitiveMode_LINE_STRIP: {
  502. nFaces = count - ((prim.mode == PrimitiveMode_LINE_STRIP) ? 1 : 0);
  503. faces = new aiFace[nFaces];
  504. SetFace(faces[0], 0, 1);
  505. for (unsigned int i = 2; i < count; ++i) {
  506. SetFace(faces[i - 1], faces[i - 2].mIndices[1], i);
  507. }
  508. if (prim.mode == PrimitiveMode_LINE_LOOP) { // close the loop
  509. SetFace(faces[count - 1], faces[count - 2].mIndices[1], faces[0].mIndices[0]);
  510. }
  511. break;
  512. }
  513. case PrimitiveMode_TRIANGLES: {
  514. nFaces = count / 3;
  515. faces = new aiFace[nFaces];
  516. for (unsigned int i = 0; i < count; i += 3) {
  517. SetFace(faces[i / 3], i, i + 1, i + 2);
  518. }
  519. break;
  520. }
  521. case PrimitiveMode_TRIANGLE_STRIP: {
  522. nFaces = count - 2;
  523. faces = new aiFace[nFaces];
  524. for (unsigned int i = 0; i < nFaces; ++i) {
  525. //The ordering is to ensure that the triangles are all drawn with the same orientation
  526. if ((i+1) % 2 == 0)
  527. {
  528. //For even n, vertices n + 1, n, and n + 2 define triangle n
  529. SetFace(faces[i], i+1, i, i+2);
  530. }
  531. else
  532. {
  533. //For odd n, vertices n, n+1, and n+2 define triangle n
  534. SetFace(faces[i], i, i+1, i+2);
  535. }
  536. }
  537. break;
  538. }
  539. case PrimitiveMode_TRIANGLE_FAN:
  540. nFaces = count - 2;
  541. faces = new aiFace[nFaces];
  542. SetFace(faces[0], 0, 1, 2);
  543. for (unsigned int i = 1; i < nFaces; ++i) {
  544. SetFace(faces[i], faces[0].mIndices[0], faces[i - 1].mIndices[2], i + 2);
  545. }
  546. break;
  547. }
  548. }
  549. if (faces) {
  550. aim->mFaces = faces;
  551. aim->mNumFaces = static_cast<unsigned int>(nFaces);
  552. ai_assert(CheckValidFacesIndices(faces, static_cast<unsigned>(nFaces), aim->mNumVertices));
  553. }
  554. if (prim.material) {
  555. aim->mMaterialIndex = prim.material.GetIndex();
  556. }
  557. else {
  558. aim->mMaterialIndex = mScene->mNumMaterials - 1;
  559. }
  560. }
  561. }
  562. meshOffsets.push_back(k);
  563. CopyVector(meshes, mScene->mMeshes, mScene->mNumMeshes);
  564. }
  565. void glTF2Importer::ImportCameras(glTF2::Asset& r)
  566. {
  567. if (!r.cameras.Size()) return;
  568. mScene->mNumCameras = r.cameras.Size();
  569. mScene->mCameras = new aiCamera*[r.cameras.Size()];
  570. for (size_t i = 0; i < r.cameras.Size(); ++i) {
  571. Camera& cam = r.cameras[i];
  572. aiCamera* aicam = mScene->mCameras[i] = new aiCamera();
  573. // cameras point in -Z by default, rest is specified in node transform
  574. aicam->mLookAt = aiVector3D(0.f,0.f,-1.f);
  575. if (cam.type == Camera::Perspective) {
  576. aicam->mAspect = cam.cameraProperties.perspective.aspectRatio;
  577. aicam->mHorizontalFOV = cam.cameraProperties.perspective.yfov * aicam->mAspect;
  578. aicam->mClipPlaneFar = cam.cameraProperties.perspective.zfar;
  579. aicam->mClipPlaneNear = cam.cameraProperties.perspective.znear;
  580. }
  581. else {
  582. // assimp does not support orthographic cameras
  583. }
  584. }
  585. }
  586. static void GetNodeTransform(aiMatrix4x4& matrix, const glTF2::Node& node) {
  587. if (node.matrix.isPresent) {
  588. CopyValue(node.matrix.value, matrix);
  589. }
  590. else {
  591. if (node.translation.isPresent) {
  592. aiVector3D trans;
  593. CopyValue(node.translation.value, trans);
  594. aiMatrix4x4 t;
  595. aiMatrix4x4::Translation(trans, t);
  596. matrix = matrix * t;
  597. }
  598. if (node.rotation.isPresent) {
  599. aiQuaternion rot;
  600. CopyValue(node.rotation.value, rot);
  601. matrix = matrix * aiMatrix4x4(rot.GetMatrix());
  602. }
  603. if (node.scale.isPresent) {
  604. aiVector3D scal(1.f);
  605. CopyValue(node.scale.value, scal);
  606. aiMatrix4x4 s;
  607. aiMatrix4x4::Scaling(scal, s);
  608. matrix = matrix * s;
  609. }
  610. }
  611. }
  612. static void BuildVertexWeightMapping(Mesh::Primitive& primitive, std::vector<std::vector<aiVertexWeight>>& map)
  613. {
  614. Mesh::Primitive::Attributes& attr = primitive.attributes;
  615. if (attr.weight.empty() || attr.joint.empty()) {
  616. return;
  617. }
  618. if (attr.weight[0]->count != attr.joint[0]->count) {
  619. return;
  620. }
  621. size_t num_vertices = attr.weight[0]->count;
  622. struct Weights { float values[4]; };
  623. Weights* weights = nullptr;
  624. attr.weight[0]->ExtractData(weights);
  625. struct Indices8 { uint8_t values[4]; };
  626. struct Indices16 { uint16_t values[4]; };
  627. Indices8* indices8 = nullptr;
  628. Indices16* indices16 = nullptr;
  629. if (attr.joint[0]->GetElementSize() == 4) {
  630. attr.joint[0]->ExtractData(indices8);
  631. }else {
  632. attr.joint[0]->ExtractData(indices16);
  633. }
  634. //
  635. if (nullptr == indices8 && nullptr == indices16) {
  636. // Something went completely wrong!
  637. ai_assert(false);
  638. return;
  639. }
  640. for (size_t i = 0; i < num_vertices; ++i) {
  641. for (int j = 0; j < 4; ++j) {
  642. const unsigned int bone = (indices8!=nullptr) ? indices8[i].values[j] : indices16[i].values[j];
  643. const float weight = weights[i].values[j];
  644. if (weight > 0 && bone < map.size()) {
  645. map[bone].reserve(8);
  646. map[bone].emplace_back(static_cast<unsigned int>(i), weight);
  647. }
  648. }
  649. }
  650. delete[] weights;
  651. delete[] indices8;
  652. delete[] indices16;
  653. }
  654. aiNode* ImportNode(aiScene* pScene, glTF2::Asset& r, std::vector<unsigned int>& meshOffsets, glTF2::Ref<glTF2::Node>& ptr)
  655. {
  656. Node& node = *ptr;
  657. std::string nameOrId = node.name.empty() ? node.id : node.name;
  658. aiNode* ainode = new aiNode(nameOrId);
  659. if (!node.children.empty()) {
  660. ainode->mNumChildren = unsigned(node.children.size());
  661. ainode->mChildren = new aiNode*[ainode->mNumChildren];
  662. for (unsigned int i = 0; i < ainode->mNumChildren; ++i) {
  663. aiNode* child = ImportNode(pScene, r, meshOffsets, node.children[i]);
  664. child->mParent = ainode;
  665. ainode->mChildren[i] = child;
  666. }
  667. }
  668. GetNodeTransform(ainode->mTransformation, node);
  669. if (!node.meshes.empty()) {
  670. // GLTF files contain at most 1 mesh per node.
  671. assert(node.meshes.size() == 1);
  672. int mesh_idx = node.meshes[0].GetIndex();
  673. int count = meshOffsets[mesh_idx + 1] - meshOffsets[mesh_idx];
  674. ainode->mNumMeshes = count;
  675. ainode->mMeshes = new unsigned int[count];
  676. if (node.skin) {
  677. for (int primitiveNo = 0; primitiveNo < count; ++primitiveNo) {
  678. aiMesh* mesh = pScene->mMeshes[meshOffsets[mesh_idx]+primitiveNo];
  679. mesh->mNumBones = static_cast<unsigned int>(node.skin->jointNames.size());
  680. mesh->mBones = new aiBone*[mesh->mNumBones];
  681. // GLTF and Assimp choose to store bone weights differently.
  682. // GLTF has each vertex specify which bones influence the vertex.
  683. // Assimp has each bone specify which vertices it has influence over.
  684. // To convert this data, we first read over the vertex data and pull
  685. // out the bone-to-vertex mapping. Then, when creating the aiBones,
  686. // we copy the bone-to-vertex mapping into the bone. This is unfortunate
  687. // both because it's somewhat slow and because, for many applications,
  688. // we then need to reconvert the data back into the vertex-to-bone
  689. // mapping which makes things doubly-slow.
  690. std::vector<std::vector<aiVertexWeight>> weighting(mesh->mNumBones);
  691. BuildVertexWeightMapping(node.meshes[0]->primitives[primitiveNo], weighting);
  692. for (uint32_t i = 0; i < mesh->mNumBones; ++i) {
  693. aiBone* bone = new aiBone();
  694. Ref<Node> joint = node.skin->jointNames[i];
  695. if (!joint->name.empty()) {
  696. bone->mName = joint->name;
  697. } else {
  698. // Assimp expects each bone to have a unique name.
  699. static const std::string kDefaultName = "bone_";
  700. char postfix[10] = {0};
  701. ASSIMP_itoa10(postfix, i);
  702. bone->mName = (kDefaultName + postfix);
  703. }
  704. GetNodeTransform(bone->mOffsetMatrix, *joint);
  705. std::vector<aiVertexWeight>& weights = weighting[i];
  706. bone->mNumWeights = static_cast<uint32_t>(weights.size());
  707. if (bone->mNumWeights > 0) {
  708. bone->mWeights = new aiVertexWeight[bone->mNumWeights];
  709. memcpy(bone->mWeights, weights.data(), bone->mNumWeights * sizeof(aiVertexWeight));
  710. } else {
  711. // Assimp expects all bones to have at least 1 weight.
  712. bone->mWeights = new aiVertexWeight[1];
  713. bone->mNumWeights = 1;
  714. bone->mWeights->mVertexId = 0;
  715. bone->mWeights->mWeight = 0.f;
  716. }
  717. mesh->mBones[i] = bone;
  718. }
  719. }
  720. }
  721. int k = 0;
  722. for (unsigned int j = meshOffsets[mesh_idx]; j < meshOffsets[mesh_idx + 1]; ++j, ++k) {
  723. ainode->mMeshes[k] = j;
  724. }
  725. }
  726. if (node.camera) {
  727. pScene->mCameras[node.camera.GetIndex()]->mName = ainode->mName;
  728. }
  729. return ainode;
  730. }
  731. void glTF2Importer::ImportNodes(glTF2::Asset& r)
  732. {
  733. if (!r.scene) return;
  734. std::vector< Ref<Node> > rootNodes = r.scene->nodes;
  735. // The root nodes
  736. unsigned int numRootNodes = unsigned(rootNodes.size());
  737. if (numRootNodes == 1) { // a single root node: use it
  738. mScene->mRootNode = ImportNode(mScene, r, meshOffsets, rootNodes[0]);
  739. }
  740. else if (numRootNodes > 1) { // more than one root node: create a fake root
  741. aiNode* root = new aiNode("ROOT");
  742. root->mChildren = new aiNode*[numRootNodes];
  743. for (unsigned int i = 0; i < numRootNodes; ++i) {
  744. aiNode* node = ImportNode(mScene, r, meshOffsets, rootNodes[i]);
  745. node->mParent = root;
  746. root->mChildren[root->mNumChildren++] = node;
  747. }
  748. mScene->mRootNode = root;
  749. }
  750. //if (!mScene->mRootNode) {
  751. // mScene->mRootNode = new aiNode("EMPTY");
  752. //}
  753. }
  754. struct AnimationSamplers {
  755. AnimationSamplers() : translation(nullptr), rotation(nullptr), scale(nullptr) {}
  756. Animation::Sampler* translation;
  757. Animation::Sampler* rotation;
  758. Animation::Sampler* scale;
  759. };
  760. aiNodeAnim* CreateNodeAnim(glTF2::Asset& r, Node& node, AnimationSamplers& samplers)
  761. {
  762. aiNodeAnim* anim = new aiNodeAnim();
  763. anim->mNodeName = node.name;
  764. static const float kMillisecondsFromSeconds = 1000.f;
  765. if (samplers.translation) {
  766. float* times = nullptr;
  767. samplers.translation->input->ExtractData(times);
  768. aiVector3D* values = nullptr;
  769. samplers.translation->output->ExtractData(values);
  770. anim->mNumPositionKeys = static_cast<uint32_t>(samplers.translation->input->count);
  771. anim->mPositionKeys = new aiVectorKey[anim->mNumPositionKeys];
  772. for (unsigned int i = 0; i < anim->mNumPositionKeys; ++i) {
  773. anim->mPositionKeys[i].mTime = times[i] * kMillisecondsFromSeconds;
  774. anim->mPositionKeys[i].mValue = values[i];
  775. }
  776. delete[] times;
  777. delete[] values;
  778. } else if (node.translation.isPresent) {
  779. anim->mNumPositionKeys = 1;
  780. anim->mPositionKeys = new aiVectorKey();
  781. anim->mPositionKeys->mTime = 0.f;
  782. anim->mPositionKeys->mValue.x = node.translation.value[0];
  783. anim->mPositionKeys->mValue.y = node.translation.value[1];
  784. anim->mPositionKeys->mValue.z = node.translation.value[2];
  785. }
  786. if (samplers.rotation) {
  787. float* times = nullptr;
  788. samplers.rotation->input->ExtractData(times);
  789. aiQuaternion* values = nullptr;
  790. samplers.rotation->output->ExtractData(values);
  791. anim->mNumRotationKeys = static_cast<uint32_t>(samplers.rotation->input->count);
  792. anim->mRotationKeys = new aiQuatKey[anim->mNumRotationKeys];
  793. for (unsigned int i = 0; i < anim->mNumRotationKeys; ++i) {
  794. anim->mRotationKeys[i].mTime = times[i] * kMillisecondsFromSeconds;
  795. anim->mRotationKeys[i].mValue.x = values[i].w;
  796. anim->mRotationKeys[i].mValue.y = values[i].x;
  797. anim->mRotationKeys[i].mValue.z = values[i].y;
  798. anim->mRotationKeys[i].mValue.w = values[i].z;
  799. }
  800. delete[] times;
  801. delete[] values;
  802. } else if (node.rotation.isPresent) {
  803. anim->mNumRotationKeys = 1;
  804. anim->mRotationKeys = new aiQuatKey();
  805. anim->mRotationKeys->mTime = 0.f;
  806. anim->mRotationKeys->mValue.x = node.rotation.value[0];
  807. anim->mRotationKeys->mValue.y = node.rotation.value[1];
  808. anim->mRotationKeys->mValue.z = node.rotation.value[2];
  809. anim->mRotationKeys->mValue.w = node.rotation.value[3];
  810. }
  811. if (samplers.scale) {
  812. float* times = nullptr;
  813. samplers.scale->input->ExtractData(times);
  814. aiVector3D* values = nullptr;
  815. samplers.scale->output->ExtractData(values);
  816. anim->mNumScalingKeys = static_cast<uint32_t>(samplers.scale->input->count);
  817. anim->mScalingKeys = new aiVectorKey[anim->mNumScalingKeys];
  818. for (unsigned int i = 0; i < anim->mNumScalingKeys; ++i) {
  819. anim->mScalingKeys[i].mTime = times[i] * kMillisecondsFromSeconds;
  820. anim->mScalingKeys[i].mValue = values[i];
  821. }
  822. delete[] times;
  823. delete[] values;
  824. } else if (node.scale.isPresent) {
  825. anim->mNumScalingKeys = 1;
  826. anim->mScalingKeys = new aiVectorKey();
  827. anim->mScalingKeys->mTime = 0.f;
  828. anim->mScalingKeys->mValue.x = node.scale.value[0];
  829. anim->mScalingKeys->mValue.y = node.scale.value[1];
  830. anim->mScalingKeys->mValue.z = node.scale.value[2];
  831. }
  832. return anim;
  833. }
  834. std::unordered_map<unsigned int, AnimationSamplers> GatherSamplers(Animation& anim)
  835. {
  836. std::unordered_map<unsigned int, AnimationSamplers> samplers;
  837. for (unsigned int c = 0; c < anim.channels.size(); ++c) {
  838. Animation::Channel& channel = anim.channels[c];
  839. if (channel.sampler >= static_cast<int>(anim.samplers.size())) {
  840. continue;
  841. }
  842. const unsigned int node_index = channel.target.node.GetIndex();
  843. AnimationSamplers& sampler = samplers[node_index];
  844. if (channel.target.path == AnimationPath_TRANSLATION) {
  845. sampler.translation = &anim.samplers[channel.sampler];
  846. } else if (channel.target.path == AnimationPath_ROTATION) {
  847. sampler.rotation = &anim.samplers[channel.sampler];
  848. } else if (channel.target.path == AnimationPath_SCALE) {
  849. sampler.scale = &anim.samplers[channel.sampler];
  850. }
  851. }
  852. return samplers;
  853. }
  854. void glTF2Importer::ImportAnimations(glTF2::Asset& r)
  855. {
  856. if (!r.scene) return;
  857. mScene->mNumAnimations = r.animations.Size();
  858. if (mScene->mNumAnimations == 0) {
  859. return;
  860. }
  861. mScene->mAnimations = new aiAnimation*[mScene->mNumAnimations];
  862. for (unsigned int i = 0; i < r.animations.Size(); ++i) {
  863. Animation& anim = r.animations[i];
  864. aiAnimation* ai_anim = new aiAnimation();
  865. ai_anim->mName = anim.name;
  866. ai_anim->mDuration = 0;
  867. ai_anim->mTicksPerSecond = 0;
  868. std::unordered_map<unsigned int, AnimationSamplers> samplers = GatherSamplers(anim);
  869. ai_anim->mNumChannels = static_cast<uint32_t>(samplers.size());
  870. if (ai_anim->mNumChannels > 0) {
  871. ai_anim->mChannels = new aiNodeAnim*[ai_anim->mNumChannels];
  872. int j = 0;
  873. for (auto& iter : samplers) {
  874. ai_anim->mChannels[j] = CreateNodeAnim(r, r.nodes[iter.first], iter.second);
  875. ++j;
  876. }
  877. }
  878. // Use the latest keyframe for the duration of the animation
  879. double maxDuration = 0;
  880. for (unsigned int j = 0; j < ai_anim->mNumChannels; ++j) {
  881. auto chan = ai_anim->mChannels[j];
  882. if (chan->mNumPositionKeys) {
  883. auto lastPosKey = chan->mPositionKeys[chan->mNumPositionKeys - 1];
  884. if (lastPosKey.mTime > maxDuration) {
  885. maxDuration = lastPosKey.mTime;
  886. }
  887. }
  888. if (chan->mNumRotationKeys) {
  889. auto lastRotKey = chan->mRotationKeys[chan->mNumRotationKeys - 1];
  890. if (lastRotKey.mTime > maxDuration) {
  891. maxDuration = lastRotKey.mTime;
  892. }
  893. }
  894. if (chan->mNumScalingKeys) {
  895. auto lastScaleKey = chan->mScalingKeys[chan->mNumScalingKeys - 1];
  896. if (lastScaleKey.mTime > maxDuration) {
  897. maxDuration = lastScaleKey.mTime;
  898. }
  899. }
  900. }
  901. ai_anim->mDuration = maxDuration;
  902. mScene->mAnimations[i] = ai_anim;
  903. }
  904. }
  905. void glTF2Importer::ImportEmbeddedTextures(glTF2::Asset& r)
  906. {
  907. embeddedTexIdxs.resize(r.images.Size(), -1);
  908. int numEmbeddedTexs = 0;
  909. for (size_t i = 0; i < r.images.Size(); ++i) {
  910. if (r.images[i].HasData())
  911. numEmbeddedTexs += 1;
  912. }
  913. if (numEmbeddedTexs == 0)
  914. return;
  915. mScene->mTextures = new aiTexture*[numEmbeddedTexs];
  916. // Add the embedded textures
  917. for (size_t i = 0; i < r.images.Size(); ++i) {
  918. Image &img = r.images[i];
  919. if (!img.HasData()) continue;
  920. int idx = mScene->mNumTextures++;
  921. embeddedTexIdxs[i] = idx;
  922. aiTexture* tex = mScene->mTextures[idx] = new aiTexture();
  923. size_t length = img.GetDataLength();
  924. void* data = img.StealData();
  925. tex->mWidth = static_cast<unsigned int>(length);
  926. tex->mHeight = 0;
  927. tex->pcData = reinterpret_cast<aiTexel*>(data);
  928. if (!img.mimeType.empty()) {
  929. const char* ext = strchr(img.mimeType.c_str(), '/') + 1;
  930. if (ext) {
  931. if (strcmp(ext, "jpeg") == 0) ext = "jpg";
  932. size_t len = strlen(ext);
  933. if (len <= 3) {
  934. strcpy(tex->achFormatHint, ext);
  935. }
  936. }
  937. }
  938. }
  939. }
  940. void glTF2Importer::InternReadFile(const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) {
  941. this->mScene = pScene;
  942. // read the asset file
  943. glTF2::Asset asset(pIOHandler);
  944. asset.Load(pFile, GetExtension(pFile) == "glb");
  945. //
  946. // Copy the data out
  947. //
  948. ImportEmbeddedTextures(asset);
  949. ImportMaterials(asset);
  950. ImportMeshes(asset);
  951. ImportCameras(asset);
  952. ImportNodes(asset);
  953. ImportAnimations(asset);
  954. if (pScene->mNumMeshes == 0) {
  955. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  956. }
  957. }
  958. #endif // ASSIMP_BUILD_NO_GLTF_IMPORTER