glTF2Importer.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2020, 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. #if !defined(ASSIMP_BUILD_NO_GLTF_IMPORTER) && !defined(ASSIMP_BUILD_NO_GLTF2_IMPORTER)
  34. #include "AssetLib/glTF2/glTF2Importer.h"
  35. #include "PostProcessing/MakeVerboseFormat.h"
  36. #include "AssetLib/glTF2/glTF2Asset.h"
  37. #include "AssetLib/glTF2/glTF2AssetWriter.h"
  38. #include <assimp/CreateAnimMesh.h>
  39. #include <assimp/StringComparison.h>
  40. #include <assimp/StringUtils.h>
  41. #include <assimp/ai_assert.h>
  42. #include <assimp/importerdesc.h>
  43. #include <assimp/scene.h>
  44. #include <assimp/DefaultLogger.hpp>
  45. #include <assimp/Importer.hpp>
  46. #include <assimp/commonMetaData.h>
  47. #include <memory>
  48. #include <unordered_map>
  49. #include <rapidjson/document.h>
  50. #include <rapidjson/rapidjson.h>
  51. using namespace Assimp;
  52. using namespace glTF2;
  53. using namespace glTFCommon;
  54. namespace {
  55. // generate bi-tangents from normals and tangents according to spec
  56. struct Tangent {
  57. aiVector3D xyz;
  58. ai_real w;
  59. };
  60. } // namespace
  61. //
  62. // glTF2Importer
  63. //
  64. static const aiImporterDesc desc = {
  65. "glTF2 Importer",
  66. "",
  67. "",
  68. "",
  69. aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_LimitedSupport | aiImporterFlags_Experimental,
  70. 0,
  71. 0,
  72. 0,
  73. 0,
  74. "gltf glb"
  75. };
  76. glTF2Importer::glTF2Importer() :
  77. BaseImporter(),
  78. meshOffsets(),
  79. embeddedTexIdxs(),
  80. mScene(nullptr) {
  81. // empty
  82. }
  83. glTF2Importer::~glTF2Importer() {
  84. // empty
  85. }
  86. const aiImporterDesc *glTF2Importer::GetInfo() const {
  87. return &desc;
  88. }
  89. bool glTF2Importer::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /* checkSig */) const {
  90. const std::string &extension = GetExtension(pFile);
  91. if (extension != "gltf" && extension != "glb") {
  92. return false;
  93. }
  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. switch (gltfWrapMode) {
  104. case SamplerWrap::Mirrored_Repeat:
  105. return aiTextureMapMode_Mirror;
  106. case SamplerWrap::Clamp_To_Edge:
  107. return aiTextureMapMode_Clamp;
  108. case SamplerWrap::UNSET:
  109. case SamplerWrap::Repeat:
  110. default:
  111. return aiTextureMapMode_Wrap;
  112. }
  113. }
  114. inline void SetMaterialColorProperty(Asset & /*r*/, vec4 &prop, aiMaterial *mat, const char *pKey, unsigned int type, unsigned int idx) {
  115. aiColor4D col;
  116. CopyValue(prop, col);
  117. mat->AddProperty(&col, 1, pKey, type, idx);
  118. }
  119. inline void SetMaterialColorProperty(Asset & /*r*/, vec3 &prop, aiMaterial *mat, const char *pKey, unsigned int type, unsigned int idx) {
  120. aiColor4D col;
  121. glTFCommon::CopyValue(prop, col);
  122. mat->AddProperty(&col, 1, pKey, type, idx);
  123. }
  124. inline void SetMaterialTextureProperty(std::vector<int> &embeddedTexIdxs, Asset & /*r*/, glTF2::TextureInfo prop, aiMaterial *mat, aiTextureType texType, unsigned int texSlot = 0) {
  125. if (prop.texture && prop.texture->source) {
  126. aiString uri(prop.texture->source->uri);
  127. int texIdx = embeddedTexIdxs[prop.texture->source.GetIndex()];
  128. if (texIdx != -1) { // embedded
  129. // setup texture reference string (copied from ColladaLoader::FindFilenameForEffectTexture)
  130. uri.data[0] = '*';
  131. uri.length = 1 + ASSIMP_itoa10(uri.data + 1, MAXLEN - 1, texIdx);
  132. }
  133. mat->AddProperty(&uri, AI_MATKEY_TEXTURE(texType, texSlot));
  134. mat->AddProperty(&prop.texCoord, 1, AI_MATKEY_GLTF_TEXTURE_TEXCOORD(texType, texSlot));
  135. if (prop.textureTransformSupported) {
  136. aiUVTransform transform;
  137. transform.mScaling.x = prop.TextureTransformExt_t.scale[0];
  138. transform.mScaling.y = prop.TextureTransformExt_t.scale[1];
  139. transform.mRotation = -prop.TextureTransformExt_t.rotation; // must be negated
  140. // A change of coordinates is required to map glTF UV transformations into the space used by
  141. // Assimp. In glTF all UV origins are at 0,1 (top left of texture) in Assimp space. In Assimp
  142. // rotation occurs around the image center (0.5,0.5) where as in glTF rotation is around the
  143. // texture origin. All three can be corrected for solely by a change of the translation since
  144. // the transformations available are shape preserving. Note the importer already flips the V
  145. // coordinate of the actual meshes during import.
  146. const ai_real rcos(cos(-transform.mRotation));
  147. const ai_real rsin(sin(-transform.mRotation));
  148. transform.mTranslation.x = (static_cast<ai_real>( 0.5 ) * transform.mScaling.x) * (-rcos + rsin + 1) + prop.TextureTransformExt_t.offset[0];
  149. transform.mTranslation.y = ((static_cast<ai_real>( 0.5 ) * transform.mScaling.y) * (rsin + rcos - 1)) + 1 - transform.mScaling.y - prop.TextureTransformExt_t.offset[1];;
  150. mat->AddProperty(&transform, 1, _AI_MATKEY_UVTRANSFORM_BASE, texType, texSlot);
  151. }
  152. if (prop.texture->sampler) {
  153. Ref<Sampler> sampler = prop.texture->sampler;
  154. aiString name(sampler->name);
  155. aiString id(sampler->id);
  156. mat->AddProperty(&name, AI_MATKEY_GLTF_MAPPINGNAME(texType, texSlot));
  157. mat->AddProperty(&id, AI_MATKEY_GLTF_MAPPINGID(texType, texSlot));
  158. aiTextureMapMode wrapS = ConvertWrappingMode(sampler->wrapS);
  159. aiTextureMapMode wrapT = ConvertWrappingMode(sampler->wrapT);
  160. mat->AddProperty(&wrapS, 1, AI_MATKEY_MAPPINGMODE_U(texType, texSlot));
  161. mat->AddProperty(&wrapT, 1, AI_MATKEY_MAPPINGMODE_V(texType, texSlot));
  162. if (sampler->magFilter != SamplerMagFilter::UNSET) {
  163. mat->AddProperty(&sampler->magFilter, 1, AI_MATKEY_GLTF_MAPPINGFILTER_MAG(texType, texSlot));
  164. }
  165. if (sampler->minFilter != SamplerMinFilter::UNSET) {
  166. mat->AddProperty(&sampler->minFilter, 1, AI_MATKEY_GLTF_MAPPINGFILTER_MIN(texType, texSlot));
  167. }
  168. }
  169. }
  170. }
  171. inline void SetMaterialTextureProperty(std::vector<int> &embeddedTexIdxs, Asset &r, glTF2::NormalTextureInfo &prop, aiMaterial *mat, aiTextureType texType, unsigned int texSlot = 0) {
  172. SetMaterialTextureProperty(embeddedTexIdxs, r, (glTF2::TextureInfo)prop, mat, texType, texSlot);
  173. if (prop.texture && prop.texture->source) {
  174. mat->AddProperty(&prop.scale, 1, AI_MATKEY_GLTF_TEXTURE_SCALE(texType, texSlot));
  175. }
  176. }
  177. inline void SetMaterialTextureProperty(std::vector<int> &embeddedTexIdxs, Asset &r, glTF2::OcclusionTextureInfo &prop, aiMaterial *mat, aiTextureType texType, unsigned int texSlot = 0) {
  178. SetMaterialTextureProperty(embeddedTexIdxs, r, (glTF2::TextureInfo)prop, mat, texType, texSlot);
  179. if (prop.texture && prop.texture->source) {
  180. mat->AddProperty(&prop.strength, 1, AI_MATKEY_GLTF_TEXTURE_STRENGTH(texType, texSlot));
  181. }
  182. }
  183. static aiMaterial *ImportMaterial(std::vector<int> &embeddedTexIdxs, Asset &r, Material &mat) {
  184. aiMaterial *aimat = new aiMaterial();
  185. if (!mat.name.empty()) {
  186. aiString str(mat.name);
  187. aimat->AddProperty(&str, AI_MATKEY_NAME);
  188. }
  189. SetMaterialColorProperty(r, mat.pbrMetallicRoughness.baseColorFactor, aimat, AI_MATKEY_COLOR_DIFFUSE);
  190. SetMaterialColorProperty(r, mat.pbrMetallicRoughness.baseColorFactor, aimat, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_FACTOR);
  191. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.baseColorTexture, aimat, aiTextureType_DIFFUSE);
  192. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.baseColorTexture, aimat, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_TEXTURE);
  193. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.metallicRoughnessTexture, aimat, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE);
  194. aimat->AddProperty(&mat.pbrMetallicRoughness.metallicFactor, 1, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLIC_FACTOR);
  195. aimat->AddProperty(&mat.pbrMetallicRoughness.roughnessFactor, 1, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_ROUGHNESS_FACTOR);
  196. float roughnessAsShininess = 1 - mat.pbrMetallicRoughness.roughnessFactor;
  197. roughnessAsShininess *= roughnessAsShininess * 1000;
  198. aimat->AddProperty(&roughnessAsShininess, 1, AI_MATKEY_SHININESS);
  199. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.normalTexture, aimat, aiTextureType_NORMALS);
  200. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.occlusionTexture, aimat, aiTextureType_LIGHTMAP);
  201. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.emissiveTexture, aimat, aiTextureType_EMISSIVE);
  202. SetMaterialColorProperty(r, mat.emissiveFactor, aimat, AI_MATKEY_COLOR_EMISSIVE);
  203. aimat->AddProperty(&mat.doubleSided, 1, AI_MATKEY_TWOSIDED);
  204. aiString alphaMode(mat.alphaMode);
  205. aimat->AddProperty(&alphaMode, AI_MATKEY_GLTF_ALPHAMODE);
  206. aimat->AddProperty(&mat.alphaCutoff, 1, AI_MATKEY_GLTF_ALPHACUTOFF);
  207. //pbrSpecularGlossiness
  208. if (mat.pbrSpecularGlossiness.isPresent) {
  209. PbrSpecularGlossiness &pbrSG = mat.pbrSpecularGlossiness.value;
  210. aimat->AddProperty(&mat.pbrSpecularGlossiness.isPresent, 1, AI_MATKEY_GLTF_PBRSPECULARGLOSSINESS);
  211. SetMaterialColorProperty(r, pbrSG.diffuseFactor, aimat, AI_MATKEY_COLOR_DIFFUSE);
  212. SetMaterialColorProperty(r, pbrSG.specularFactor, aimat, AI_MATKEY_COLOR_SPECULAR);
  213. float glossinessAsShininess = pbrSG.glossinessFactor * 1000.0f;
  214. aimat->AddProperty(&glossinessAsShininess, 1, AI_MATKEY_SHININESS);
  215. aimat->AddProperty(&pbrSG.glossinessFactor, 1, AI_MATKEY_GLTF_PBRSPECULARGLOSSINESS_GLOSSINESS_FACTOR);
  216. SetMaterialTextureProperty(embeddedTexIdxs, r, pbrSG.diffuseTexture, aimat, aiTextureType_DIFFUSE);
  217. SetMaterialTextureProperty(embeddedTexIdxs, r, pbrSG.specularGlossinessTexture, aimat, aiTextureType_SPECULAR);
  218. }
  219. if (mat.unlit) {
  220. aimat->AddProperty(&mat.unlit, 1, AI_MATKEY_GLTF_UNLIT);
  221. }
  222. return aimat;
  223. }
  224. void glTF2Importer::ImportMaterials(glTF2::Asset &r) {
  225. const unsigned int numImportedMaterials = unsigned(r.materials.Size());
  226. ASSIMP_LOG_DEBUG_F("Importing ", numImportedMaterials, " materials");
  227. Material defaultMaterial;
  228. mScene->mNumMaterials = numImportedMaterials + 1;
  229. mScene->mMaterials = new aiMaterial *[mScene->mNumMaterials];
  230. mScene->mMaterials[numImportedMaterials] = ImportMaterial(embeddedTexIdxs, r, defaultMaterial);
  231. for (unsigned int i = 0; i < numImportedMaterials; ++i) {
  232. mScene->mMaterials[i] = ImportMaterial(embeddedTexIdxs, r, r.materials[i]);
  233. }
  234. }
  235. static inline void SetFaceAndAdvance1(aiFace*& face, unsigned int numVertices, unsigned int a) {
  236. if (a >= numVertices) {
  237. return;
  238. }
  239. face->mNumIndices = 1;
  240. face->mIndices = new unsigned int[1];
  241. face->mIndices[0] = a;
  242. ++face;
  243. }
  244. static inline void SetFaceAndAdvance2(aiFace*& face, unsigned int numVertices, unsigned int a, unsigned int b) {
  245. if ((a >= numVertices) || (b >= numVertices)) {
  246. return;
  247. }
  248. face->mNumIndices = 2;
  249. face->mIndices = new unsigned int[2];
  250. face->mIndices[0] = a;
  251. face->mIndices[1] = b;
  252. ++face;
  253. }
  254. static inline void SetFaceAndAdvance3(aiFace*& face, unsigned int numVertices, unsigned int a, unsigned int b, unsigned int c) {
  255. if ((a >= numVertices) || (b >= numVertices) || (c >= numVertices)) {
  256. return;
  257. }
  258. face->mNumIndices = 3;
  259. face->mIndices = new unsigned int[3];
  260. face->mIndices[0] = a;
  261. face->mIndices[1] = b;
  262. face->mIndices[2] = c;
  263. ++face;
  264. }
  265. #ifdef ASSIMP_BUILD_DEBUG
  266. static inline bool CheckValidFacesIndices(aiFace *faces, unsigned nFaces, unsigned nVerts) {
  267. for (unsigned i = 0; i < nFaces; ++i) {
  268. for (unsigned j = 0; j < faces[i].mNumIndices; ++j) {
  269. unsigned idx = faces[i].mIndices[j];
  270. if (idx >= nVerts) {
  271. return false;
  272. }
  273. }
  274. }
  275. return true;
  276. }
  277. #endif // ASSIMP_BUILD_DEBUG
  278. void glTF2Importer::ImportMeshes(glTF2::Asset &r) {
  279. ASSIMP_LOG_DEBUG_F("Importing ", r.meshes.Size(), " meshes");
  280. std::vector<std::unique_ptr<aiMesh>> meshes;
  281. unsigned int k = 0;
  282. meshOffsets.clear();
  283. for (unsigned int m = 0; m < r.meshes.Size(); ++m) {
  284. Mesh &mesh = r.meshes[m];
  285. meshOffsets.push_back(k);
  286. k += unsigned(mesh.primitives.size());
  287. for (unsigned int p = 0; p < mesh.primitives.size(); ++p) {
  288. Mesh::Primitive &prim = mesh.primitives[p];
  289. aiMesh *aim = new aiMesh();
  290. meshes.push_back(std::unique_ptr<aiMesh>(aim));
  291. aim->mName = mesh.name.empty() ? mesh.id : mesh.name;
  292. if (mesh.primitives.size() > 1) {
  293. ai_uint32 &len = aim->mName.length;
  294. aim->mName.data[len] = '-';
  295. len += 1 + ASSIMP_itoa10(aim->mName.data + len + 1, unsigned(MAXLEN - len - 1), p);
  296. }
  297. switch (prim.mode) {
  298. case PrimitiveMode_POINTS:
  299. aim->mPrimitiveTypes |= aiPrimitiveType_POINT;
  300. break;
  301. case PrimitiveMode_LINES:
  302. case PrimitiveMode_LINE_LOOP:
  303. case PrimitiveMode_LINE_STRIP:
  304. aim->mPrimitiveTypes |= aiPrimitiveType_LINE;
  305. break;
  306. case PrimitiveMode_TRIANGLES:
  307. case PrimitiveMode_TRIANGLE_STRIP:
  308. case PrimitiveMode_TRIANGLE_FAN:
  309. aim->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  310. break;
  311. }
  312. Mesh::Primitive::Attributes &attr = prim.attributes;
  313. if (attr.position.size() > 0 && attr.position[0]) {
  314. aim->mNumVertices = static_cast<unsigned int>(attr.position[0]->count);
  315. attr.position[0]->ExtractData(aim->mVertices);
  316. }
  317. if (attr.normal.size() > 0 && attr.normal[0]) {
  318. attr.normal[0]->ExtractData(aim->mNormals);
  319. // only extract tangents if normals are present
  320. if (attr.tangent.size() > 0 && attr.tangent[0]) {
  321. // generate bitangents from normals and tangents according to spec
  322. Tangent *tangents = nullptr;
  323. attr.tangent[0]->ExtractData(tangents);
  324. aim->mTangents = new aiVector3D[aim->mNumVertices];
  325. aim->mBitangents = new aiVector3D[aim->mNumVertices];
  326. for (unsigned int i = 0; i < aim->mNumVertices; ++i) {
  327. aim->mTangents[i] = tangents[i].xyz;
  328. aim->mBitangents[i] = (aim->mNormals[i] ^ tangents[i].xyz) * tangents[i].w;
  329. }
  330. delete[] tangents;
  331. }
  332. }
  333. for (size_t c = 0; c < attr.color.size() && c < AI_MAX_NUMBER_OF_COLOR_SETS; ++c) {
  334. if (attr.color[c]->count != aim->mNumVertices) {
  335. DefaultLogger::get()->warn("Color stream size in mesh \"" + mesh.name +
  336. "\" does not match the vertex count");
  337. continue;
  338. }
  339. attr.color[c]->ExtractData(aim->mColors[c]);
  340. }
  341. for (size_t tc = 0; tc < attr.texcoord.size() && tc < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++tc) {
  342. if (!attr.texcoord[tc]) {
  343. DefaultLogger::get()->warn("Texture coordinate accessor not found or non-contiguous texture coordinate sets.");
  344. continue;
  345. }
  346. if (attr.texcoord[tc]->count != aim->mNumVertices) {
  347. DefaultLogger::get()->warn("Texcoord stream size in mesh \"" + mesh.name +
  348. "\" does not match the vertex count");
  349. continue;
  350. }
  351. attr.texcoord[tc]->ExtractData(aim->mTextureCoords[tc]);
  352. aim->mNumUVComponents[tc] = attr.texcoord[tc]->GetNumComponents();
  353. aiVector3D *values = aim->mTextureCoords[tc];
  354. for (unsigned int i = 0; i < aim->mNumVertices; ++i) {
  355. values[i].y = 1 - values[i].y; // Flip Y coords
  356. }
  357. }
  358. std::vector<Mesh::Primitive::Target> &targets = prim.targets;
  359. if (targets.size() > 0) {
  360. aim->mNumAnimMeshes = (unsigned int)targets.size();
  361. aim->mAnimMeshes = new aiAnimMesh *[aim->mNumAnimMeshes];
  362. for (size_t i = 0; i < targets.size(); i++) {
  363. aim->mAnimMeshes[i] = aiCreateAnimMesh(aim);
  364. aiAnimMesh &aiAnimMesh = *(aim->mAnimMeshes[i]);
  365. Mesh::Primitive::Target &target = targets[i];
  366. if (target.position.size() > 0) {
  367. aiVector3D *positionDiff = nullptr;
  368. target.position[0]->ExtractData(positionDiff);
  369. for (unsigned int vertexId = 0; vertexId < aim->mNumVertices; vertexId++) {
  370. aiAnimMesh.mVertices[vertexId] += positionDiff[vertexId];
  371. }
  372. delete[] positionDiff;
  373. }
  374. if (target.normal.size() > 0) {
  375. aiVector3D *normalDiff = nullptr;
  376. target.normal[0]->ExtractData(normalDiff);
  377. for (unsigned int vertexId = 0; vertexId < aim->mNumVertices; vertexId++) {
  378. aiAnimMesh.mNormals[vertexId] += normalDiff[vertexId];
  379. }
  380. delete[] normalDiff;
  381. }
  382. if (target.tangent.size() > 0) {
  383. Tangent *tangent = nullptr;
  384. attr.tangent[0]->ExtractData(tangent);
  385. aiVector3D *tangentDiff = nullptr;
  386. target.tangent[0]->ExtractData(tangentDiff);
  387. for (unsigned int vertexId = 0; vertexId < aim->mNumVertices; ++vertexId) {
  388. tangent[vertexId].xyz += tangentDiff[vertexId];
  389. aiAnimMesh.mTangents[vertexId] = tangent[vertexId].xyz;
  390. aiAnimMesh.mBitangents[vertexId] = (aiAnimMesh.mNormals[vertexId] ^ tangent[vertexId].xyz) * tangent[vertexId].w;
  391. }
  392. delete[] tangent;
  393. delete[] tangentDiff;
  394. }
  395. if (mesh.weights.size() > i) {
  396. aiAnimMesh.mWeight = mesh.weights[i];
  397. }
  398. if (mesh.targetNames.size() > i) {
  399. aiAnimMesh.mName = mesh.targetNames[i];
  400. }
  401. }
  402. }
  403. aiFace *faces = nullptr;
  404. aiFace *facePtr = nullptr;
  405. size_t nFaces = 0;
  406. if (prim.indices) {
  407. size_t count = prim.indices->count;
  408. Accessor::Indexer data = prim.indices->GetIndexer();
  409. ai_assert(data.IsValid());
  410. switch (prim.mode) {
  411. case PrimitiveMode_POINTS: {
  412. nFaces = count;
  413. facePtr = faces = new aiFace[nFaces];
  414. for (unsigned int i = 0; i < count; ++i) {
  415. SetFaceAndAdvance1(facePtr, aim->mNumVertices, data.GetUInt(i));
  416. }
  417. break;
  418. }
  419. case PrimitiveMode_LINES: {
  420. nFaces = count / 2;
  421. if (nFaces * 2 != count) {
  422. ASSIMP_LOG_WARN("The number of vertices was not compatible with the LINES mode. Some vertices were dropped.");
  423. count = nFaces * 2;
  424. }
  425. facePtr = faces = new aiFace[nFaces];
  426. for (unsigned int i = 0; i < count; i += 2) {
  427. SetFaceAndAdvance2(facePtr, aim->mNumVertices, 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. facePtr = faces = new aiFace[nFaces];
  435. SetFaceAndAdvance2(facePtr, aim->mNumVertices, data.GetUInt(0), data.GetUInt(1));
  436. for (unsigned int i = 2; i < count; ++i) {
  437. SetFaceAndAdvance2(facePtr, aim->mNumVertices, data.GetUInt(i - 1), data.GetUInt(i));
  438. }
  439. if (prim.mode == PrimitiveMode_LINE_LOOP) { // close the loop
  440. SetFaceAndAdvance2(facePtr, aim->mNumVertices, data.GetUInt(static_cast<int>(count) - 1), faces[0].mIndices[0]);
  441. }
  442. break;
  443. }
  444. case PrimitiveMode_TRIANGLES: {
  445. nFaces = count / 3;
  446. if (nFaces * 3 != count) {
  447. ASSIMP_LOG_WARN("The number of vertices was not compatible with the TRIANGLES mode. Some vertices were dropped.");
  448. count = nFaces * 3;
  449. }
  450. facePtr = faces = new aiFace[nFaces];
  451. for (unsigned int i = 0; i < count; i += 3) {
  452. SetFaceAndAdvance3(facePtr, aim->mNumVertices, data.GetUInt(i), data.GetUInt(i + 1), data.GetUInt(i + 2));
  453. }
  454. break;
  455. }
  456. case PrimitiveMode_TRIANGLE_STRIP: {
  457. nFaces = count - 2;
  458. facePtr = faces = new aiFace[nFaces];
  459. for (unsigned int i = 0; i < nFaces; ++i) {
  460. //The ordering is to ensure that the triangles are all drawn with the same orientation
  461. if ((i + 1) % 2 == 0) {
  462. //For even n, vertices n + 1, n, and n + 2 define triangle n
  463. SetFaceAndAdvance3(facePtr, aim->mNumVertices, data.GetUInt(i + 1), data.GetUInt(i), data.GetUInt(i + 2));
  464. } else {
  465. //For odd n, vertices n, n+1, and n+2 define triangle n
  466. SetFaceAndAdvance3(facePtr, aim->mNumVertices, data.GetUInt(i), data.GetUInt(i + 1), data.GetUInt(i + 2));
  467. }
  468. }
  469. break;
  470. }
  471. case PrimitiveMode_TRIANGLE_FAN:
  472. nFaces = count - 2;
  473. facePtr = faces = new aiFace[nFaces];
  474. SetFaceAndAdvance3(facePtr, aim->mNumVertices, data.GetUInt(0), data.GetUInt(1), data.GetUInt(2));
  475. for (unsigned int i = 1; i < nFaces; ++i) {
  476. SetFaceAndAdvance3(facePtr, aim->mNumVertices, data.GetUInt(0), data.GetUInt(i + 1), data.GetUInt(i + 2));
  477. }
  478. break;
  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. facePtr = faces = new aiFace[nFaces];
  487. for (unsigned int i = 0; i < count; ++i) {
  488. SetFaceAndAdvance1(facePtr, aim->mNumVertices, i);
  489. }
  490. break;
  491. }
  492. case PrimitiveMode_LINES: {
  493. nFaces = count / 2;
  494. if (nFaces * 2 != count) {
  495. ASSIMP_LOG_WARN("The number of vertices was not compatible with the LINES mode. Some vertices were dropped.");
  496. count = (unsigned int)nFaces * 2;
  497. }
  498. facePtr = faces = new aiFace[nFaces];
  499. for (unsigned int i = 0; i < count; i += 2) {
  500. SetFaceAndAdvance2(facePtr, aim->mNumVertices, i, i + 1);
  501. }
  502. break;
  503. }
  504. case PrimitiveMode_LINE_LOOP:
  505. case PrimitiveMode_LINE_STRIP: {
  506. nFaces = count - ((prim.mode == PrimitiveMode_LINE_STRIP) ? 1 : 0);
  507. facePtr = faces = new aiFace[nFaces];
  508. SetFaceAndAdvance2(facePtr, aim->mNumVertices, 0, 1);
  509. for (unsigned int i = 2; i < count; ++i) {
  510. SetFaceAndAdvance2(facePtr, aim->mNumVertices, i - 1, i);
  511. }
  512. if (prim.mode == PrimitiveMode_LINE_LOOP) { // close the loop
  513. SetFaceAndAdvance2(facePtr, aim->mNumVertices, count - 1, 0);
  514. }
  515. break;
  516. }
  517. case PrimitiveMode_TRIANGLES: {
  518. nFaces = count / 3;
  519. if (nFaces * 3 != count) {
  520. ASSIMP_LOG_WARN("The number of vertices was not compatible with the TRIANGLES mode. Some vertices were dropped.");
  521. count = (unsigned int)nFaces * 3;
  522. }
  523. facePtr = faces = new aiFace[nFaces];
  524. for (unsigned int i = 0; i < count; i += 3) {
  525. SetFaceAndAdvance3(facePtr, aim->mNumVertices, i, i + 1, i + 2);
  526. }
  527. break;
  528. }
  529. case PrimitiveMode_TRIANGLE_STRIP: {
  530. nFaces = count - 2;
  531. facePtr = faces = new aiFace[nFaces];
  532. for (unsigned int i = 0; i < nFaces; ++i) {
  533. //The ordering is to ensure that the triangles are all drawn with the same orientation
  534. if ((i + 1) % 2 == 0) {
  535. //For even n, vertices n + 1, n, and n + 2 define triangle n
  536. SetFaceAndAdvance3(facePtr, aim->mNumVertices, i + 1, i, i + 2);
  537. } else {
  538. //For odd n, vertices n, n+1, and n+2 define triangle n
  539. SetFaceAndAdvance3(facePtr, aim->mNumVertices, i, i + 1, i + 2);
  540. }
  541. }
  542. break;
  543. }
  544. case PrimitiveMode_TRIANGLE_FAN:
  545. nFaces = count - 2;
  546. facePtr = faces = new aiFace[nFaces];
  547. SetFaceAndAdvance3(facePtr, aim->mNumVertices, 0, 1, 2);
  548. for (unsigned int i = 1; i < nFaces; ++i) {
  549. SetFaceAndAdvance3(facePtr, aim->mNumVertices, 0, i + 1, i + 2);
  550. }
  551. break;
  552. }
  553. }
  554. if (faces) {
  555. aim->mFaces = faces;
  556. const unsigned int actualNumFaces = static_cast<unsigned int>(facePtr - faces);
  557. if (actualNumFaces < nFaces) {
  558. ASSIMP_LOG_WARN("Some faces had out-of-range indices. Those faces were dropped.");
  559. }
  560. if (actualNumFaces == 0)
  561. {
  562. throw DeadlyImportError("Mesh \"", aim->mName.C_Str(), "\" has no faces");
  563. }
  564. aim->mNumFaces = actualNumFaces;
  565. ai_assert(CheckValidFacesIndices(faces, actualNumFaces, aim->mNumVertices));
  566. }
  567. if (prim.material) {
  568. aim->mMaterialIndex = prim.material.GetIndex();
  569. } else {
  570. aim->mMaterialIndex = mScene->mNumMaterials - 1;
  571. }
  572. }
  573. }
  574. meshOffsets.push_back(k);
  575. CopyVector(meshes, mScene->mMeshes, mScene->mNumMeshes);
  576. }
  577. void glTF2Importer::ImportCameras(glTF2::Asset &r) {
  578. if (!r.cameras.Size()) return;
  579. const unsigned int numCameras = r.cameras.Size();
  580. ASSIMP_LOG_DEBUG_F("Importing ", numCameras, " cameras");
  581. mScene->mNumCameras = numCameras;
  582. mScene->mCameras = new aiCamera *[numCameras];
  583. for (size_t i = 0; i < numCameras; ++i) {
  584. Camera &cam = r.cameras[i];
  585. aiCamera *aicam = mScene->mCameras[i] = new aiCamera();
  586. // cameras point in -Z by default, rest is specified in node transform
  587. aicam->mLookAt = aiVector3D(0.f, 0.f, -1.f);
  588. if (cam.type == Camera::Perspective) {
  589. aicam->mAspect = cam.cameraProperties.perspective.aspectRatio;
  590. aicam->mHorizontalFOV = cam.cameraProperties.perspective.yfov * ((aicam->mAspect == 0.f) ? 1.f : aicam->mAspect);
  591. aicam->mClipPlaneFar = cam.cameraProperties.perspective.zfar;
  592. aicam->mClipPlaneNear = cam.cameraProperties.perspective.znear;
  593. } else {
  594. aicam->mClipPlaneFar = cam.cameraProperties.ortographic.zfar;
  595. aicam->mClipPlaneNear = cam.cameraProperties.ortographic.znear;
  596. aicam->mHorizontalFOV = 0.0;
  597. aicam->mOrthographicWidth = cam.cameraProperties.ortographic.xmag;
  598. aicam->mAspect = 1.0f;
  599. if (0.f != cam.cameraProperties.ortographic.ymag) {
  600. aicam->mAspect = cam.cameraProperties.ortographic.xmag / cam.cameraProperties.ortographic.ymag;
  601. }
  602. }
  603. }
  604. }
  605. void glTF2Importer::ImportLights(glTF2::Asset &r) {
  606. if (!r.lights.Size())
  607. return;
  608. const unsigned int numLights = r.lights.Size();
  609. ASSIMP_LOG_DEBUG_F("Importing ", numLights, " lights");
  610. mScene->mNumLights = numLights;
  611. mScene->mLights = new aiLight *[numLights];
  612. for (size_t i = 0; i < numLights; ++i) {
  613. Light &light = r.lights[i];
  614. aiLight *ail = mScene->mLights[i] = new aiLight();
  615. switch (light.type) {
  616. case Light::Directional:
  617. ail->mType = aiLightSource_DIRECTIONAL;
  618. break;
  619. case Light::Point:
  620. ail->mType = aiLightSource_POINT;
  621. break;
  622. case Light::Spot:
  623. ail->mType = aiLightSource_SPOT;
  624. break;
  625. }
  626. if (ail->mType != aiLightSource_POINT) {
  627. ail->mDirection = aiVector3D(0.0f, 0.0f, -1.0f);
  628. ail->mUp = aiVector3D(0.0f, 1.0f, 0.0f);
  629. }
  630. vec3 colorWithIntensity = { light.color[0] * light.intensity, light.color[1] * light.intensity, light.color[2] * light.intensity };
  631. CopyValue(colorWithIntensity, ail->mColorAmbient);
  632. CopyValue(colorWithIntensity, ail->mColorDiffuse);
  633. CopyValue(colorWithIntensity, ail->mColorSpecular);
  634. if (ail->mType == aiLightSource_DIRECTIONAL) {
  635. ail->mAttenuationConstant = 1.0;
  636. ail->mAttenuationLinear = 0.0;
  637. ail->mAttenuationQuadratic = 0.0;
  638. } else {
  639. //in PBR attenuation is calculated using inverse square law which can be expressed
  640. //using assimps equation: 1/(att0 + att1 * d + att2 * d*d) with the following parameters
  641. //this is correct equation for the case when range (see
  642. //https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual)
  643. //is not present. When range is not present it is assumed that it is infinite and so numerator is 1.
  644. //When range is present then numerator might be any value in range [0,1] and then assimps equation
  645. //will not suffice. In this case range is added into metadata in ImportNode function
  646. //and its up to implementation to read it when it wants to
  647. ail->mAttenuationConstant = 0.0;
  648. ail->mAttenuationLinear = 0.0;
  649. ail->mAttenuationQuadratic = 1.0;
  650. }
  651. if (ail->mType == aiLightSource_SPOT) {
  652. ail->mAngleInnerCone = light.innerConeAngle;
  653. ail->mAngleOuterCone = light.outerConeAngle;
  654. }
  655. }
  656. }
  657. static void GetNodeTransform(aiMatrix4x4 &matrix, const glTF2::Node &node) {
  658. if (node.matrix.isPresent) {
  659. CopyValue(node.matrix.value, matrix);
  660. } else {
  661. if (node.translation.isPresent) {
  662. aiVector3D trans;
  663. CopyValue(node.translation.value, trans);
  664. aiMatrix4x4 t;
  665. aiMatrix4x4::Translation(trans, t);
  666. matrix = matrix * t;
  667. }
  668. if (node.rotation.isPresent) {
  669. aiQuaternion rot;
  670. CopyValue(node.rotation.value, rot);
  671. matrix = matrix * aiMatrix4x4(rot.GetMatrix());
  672. }
  673. if (node.scale.isPresent) {
  674. aiVector3D scal(1.f);
  675. CopyValue(node.scale.value, scal);
  676. aiMatrix4x4 s;
  677. aiMatrix4x4::Scaling(scal, s);
  678. matrix = matrix * s;
  679. }
  680. }
  681. }
  682. static void BuildVertexWeightMapping(Mesh::Primitive &primitive, std::vector<std::vector<aiVertexWeight>> &map) {
  683. Mesh::Primitive::Attributes &attr = primitive.attributes;
  684. if (attr.weight.empty() || attr.joint.empty()) {
  685. return;
  686. }
  687. if (attr.weight[0]->count != attr.joint[0]->count) {
  688. return;
  689. }
  690. size_t num_vertices = attr.weight[0]->count;
  691. struct Weights {
  692. float values[4];
  693. };
  694. Weights *weights = nullptr;
  695. attr.weight[0]->ExtractData(weights);
  696. struct Indices8 {
  697. uint8_t values[4];
  698. };
  699. struct Indices16 {
  700. uint16_t values[4];
  701. };
  702. Indices8 *indices8 = nullptr;
  703. Indices16 *indices16 = nullptr;
  704. if (attr.joint[0]->GetElementSize() == 4) {
  705. attr.joint[0]->ExtractData(indices8);
  706. } else {
  707. attr.joint[0]->ExtractData(indices16);
  708. }
  709. //
  710. if (nullptr == indices8 && nullptr == indices16) {
  711. // Something went completely wrong!
  712. ai_assert(false);
  713. return;
  714. }
  715. for (size_t i = 0; i < num_vertices; ++i) {
  716. for (int j = 0; j < 4; ++j) {
  717. const unsigned int bone = (indices8 != nullptr) ? indices8[i].values[j] : indices16[i].values[j];
  718. const float weight = weights[i].values[j];
  719. if (weight > 0 && bone < map.size()) {
  720. map[bone].reserve(8);
  721. map[bone].emplace_back(static_cast<unsigned int>(i), weight);
  722. }
  723. }
  724. }
  725. delete[] weights;
  726. delete[] indices8;
  727. delete[] indices16;
  728. }
  729. static std::string GetNodeName(const Node &node) {
  730. return node.name.empty() ? node.id : node.name;
  731. }
  732. void ParseExtensions(aiMetadata *metadata, const CustomExtension &extension) {
  733. if (extension.mStringValue.isPresent) {
  734. metadata->Add(extension.name.c_str(), aiString(extension.mStringValue.value));
  735. } else if (extension.mDoubleValue.isPresent) {
  736. metadata->Add(extension.name.c_str(), extension.mDoubleValue.value);
  737. } else if (extension.mUint64Value.isPresent) {
  738. metadata->Add(extension.name.c_str(), extension.mUint64Value.value);
  739. } else if (extension.mInt64Value.isPresent) {
  740. metadata->Add(extension.name.c_str(), static_cast<int32_t>(extension.mInt64Value.value));
  741. } else if (extension.mBoolValue.isPresent) {
  742. metadata->Add(extension.name.c_str(), extension.mBoolValue.value);
  743. } else if (extension.mValues.isPresent) {
  744. aiMetadata val;
  745. for (size_t i = 0; i < extension.mValues.value.size(); ++i) {
  746. ParseExtensions(&val, extension.mValues.value[i]);
  747. }
  748. metadata->Add(extension.name.c_str(), val);
  749. }
  750. }
  751. aiNode *ImportNode(aiScene *pScene, glTF2::Asset &r, std::vector<unsigned int> &meshOffsets, glTF2::Ref<glTF2::Node> &ptr) {
  752. Node &node = *ptr;
  753. aiNode *ainode = new aiNode(GetNodeName(node));
  754. if (!node.children.empty()) {
  755. ainode->mNumChildren = unsigned(node.children.size());
  756. ainode->mChildren = new aiNode *[ainode->mNumChildren];
  757. for (unsigned int i = 0; i < ainode->mNumChildren; ++i) {
  758. aiNode *child = ImportNode(pScene, r, meshOffsets, node.children[i]);
  759. child->mParent = ainode;
  760. ainode->mChildren[i] = child;
  761. }
  762. }
  763. if (node.extensions) {
  764. ainode->mMetaData = new aiMetadata;
  765. ParseExtensions(ainode->mMetaData, node.extensions);
  766. }
  767. GetNodeTransform(ainode->mTransformation, node);
  768. if (!node.meshes.empty()) {
  769. // GLTF files contain at most 1 mesh per node.
  770. assert(node.meshes.size() == 1);
  771. int mesh_idx = node.meshes[0].GetIndex();
  772. int count = meshOffsets[mesh_idx + 1] - meshOffsets[mesh_idx];
  773. ainode->mNumMeshes = count;
  774. ainode->mMeshes = new unsigned int[count];
  775. if (node.skin) {
  776. for (int primitiveNo = 0; primitiveNo < count; ++primitiveNo) {
  777. aiMesh *mesh = pScene->mMeshes[meshOffsets[mesh_idx] + primitiveNo];
  778. unsigned int numBones =static_cast<unsigned int>(node.skin->jointNames.size());
  779. std::vector<std::vector<aiVertexWeight>> weighting(numBones);
  780. BuildVertexWeightMapping(node.meshes[0]->primitives[primitiveNo], weighting);
  781. unsigned int realNumBones = 0;
  782. for (uint32_t i = 0; i < numBones; ++i) {
  783. if (weighting[i].size() > 0) {
  784. realNumBones++;
  785. }
  786. }
  787. mesh->mNumBones = static_cast<unsigned int>(realNumBones);
  788. mesh->mBones = new aiBone *[mesh->mNumBones];
  789. // GLTF and Assimp choose to store bone weights differently.
  790. // GLTF has each vertex specify which bones influence the vertex.
  791. // Assimp has each bone specify which vertices it has influence over.
  792. // To convert this data, we first read over the vertex data and pull
  793. // out the bone-to-vertex mapping. Then, when creating the aiBones,
  794. // we copy the bone-to-vertex mapping into the bone. This is unfortunate
  795. // both because it's somewhat slow and because, for many applications,
  796. // we then need to reconvert the data back into the vertex-to-bone
  797. // mapping which makes things doubly-slow.
  798. mat4 *pbindMatrices = nullptr;
  799. node.skin->inverseBindMatrices->ExtractData(pbindMatrices);
  800. int cb = 0;
  801. for (uint32_t i = 0; i < numBones; ++i) {
  802. const std::vector<aiVertexWeight> &weights = weighting[i];
  803. if (weights.size() > 0) {
  804. aiBone *bone = new aiBone();
  805. Ref<Node> joint = node.skin->jointNames[i];
  806. if (!joint->name.empty()) {
  807. bone->mName = joint->name;
  808. } else {
  809. // Assimp expects each bone to have a unique name.
  810. static const std::string kDefaultName = "bone_";
  811. char postfix[10] = { 0 };
  812. ASSIMP_itoa10(postfix, i);
  813. bone->mName = (kDefaultName + postfix);
  814. }
  815. GetNodeTransform(bone->mOffsetMatrix, *joint);
  816. CopyValue(pbindMatrices[i], bone->mOffsetMatrix);
  817. bone->mNumWeights = static_cast<uint32_t>(weights.size());
  818. bone->mWeights = new aiVertexWeight[bone->mNumWeights];
  819. memcpy(bone->mWeights, weights.data(), bone->mNumWeights * sizeof(aiVertexWeight));
  820. mesh->mBones[cb++] = bone;
  821. }
  822. }
  823. if (pbindMatrices) {
  824. delete[] pbindMatrices;
  825. }
  826. }
  827. }
  828. int k = 0;
  829. for (unsigned int j = meshOffsets[mesh_idx]; j < meshOffsets[mesh_idx + 1]; ++j, ++k) {
  830. ainode->mMeshes[k] = j;
  831. }
  832. }
  833. if (node.camera) {
  834. pScene->mCameras[node.camera.GetIndex()]->mName = ainode->mName;
  835. if (node.translation.isPresent) {
  836. aiVector3D trans;
  837. CopyValue(node.translation.value, trans);
  838. pScene->mCameras[node.camera.GetIndex()]->mPosition = trans;
  839. }
  840. }
  841. if (node.light) {
  842. pScene->mLights[node.light.GetIndex()]->mName = ainode->mName;
  843. //range is optional - see https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  844. //it is added to meta data of parent node, because there is no other place to put it
  845. if (node.light->range.isPresent) {
  846. if (!ainode->mMetaData) {
  847. ainode->mMetaData = aiMetadata::Alloc(1);
  848. ainode->mMetaData->Set(0, "PBR_LightRange", node.light->range.value);
  849. }
  850. else {
  851. ainode->mMetaData->Add("PBR_LightRange", node.light->range.value);
  852. }
  853. }
  854. }
  855. return ainode;
  856. }
  857. void glTF2Importer::ImportNodes(glTF2::Asset &r) {
  858. if (!r.scene) {
  859. throw DeadlyImportError("GLTF: No scene");
  860. }
  861. ASSIMP_LOG_DEBUG("Importing nodes");
  862. std::vector<Ref<Node>> rootNodes = r.scene->nodes;
  863. // The root nodes
  864. unsigned int numRootNodes = unsigned(rootNodes.size());
  865. if (numRootNodes == 1) { // a single root node: use it
  866. mScene->mRootNode = ImportNode(mScene, r, meshOffsets, rootNodes[0]);
  867. } else if (numRootNodes > 1) { // more than one root node: create a fake root
  868. aiNode *root = new aiNode("ROOT");
  869. root->mChildren = new aiNode *[numRootNodes];
  870. for (unsigned int i = 0; i < numRootNodes; ++i) {
  871. aiNode *node = ImportNode(mScene, r, meshOffsets, rootNodes[i]);
  872. node->mParent = root;
  873. root->mChildren[root->mNumChildren++] = node;
  874. }
  875. mScene->mRootNode = root;
  876. } else {
  877. mScene->mRootNode = new aiNode("ROOT");
  878. }
  879. }
  880. struct AnimationSamplers {
  881. AnimationSamplers() :
  882. translation(nullptr),
  883. rotation(nullptr),
  884. scale(nullptr),
  885. weight(nullptr) {
  886. // empty
  887. }
  888. Animation::Sampler *translation;
  889. Animation::Sampler *rotation;
  890. Animation::Sampler *scale;
  891. Animation::Sampler *weight;
  892. };
  893. aiNodeAnim *CreateNodeAnim(glTF2::Asset&, Node &node, AnimationSamplers &samplers) {
  894. aiNodeAnim *anim = new aiNodeAnim();
  895. anim->mNodeName = GetNodeName(node);
  896. static const float kMillisecondsFromSeconds = 1000.f;
  897. if (samplers.translation) {
  898. float *times = nullptr;
  899. samplers.translation->input->ExtractData(times);
  900. aiVector3D *values = nullptr;
  901. samplers.translation->output->ExtractData(values);
  902. anim->mNumPositionKeys = static_cast<uint32_t>(samplers.translation->input->count);
  903. anim->mPositionKeys = new aiVectorKey[anim->mNumPositionKeys];
  904. for (unsigned int i = 0; i < anim->mNumPositionKeys; ++i) {
  905. anim->mPositionKeys[i].mTime = times[i] * kMillisecondsFromSeconds;
  906. anim->mPositionKeys[i].mValue = values[i];
  907. }
  908. delete[] times;
  909. delete[] values;
  910. } else if (node.translation.isPresent) {
  911. anim->mNumPositionKeys = 1;
  912. anim->mPositionKeys = new aiVectorKey[anim->mNumPositionKeys];
  913. anim->mPositionKeys->mTime = 0.f;
  914. anim->mPositionKeys->mValue.x = node.translation.value[0];
  915. anim->mPositionKeys->mValue.y = node.translation.value[1];
  916. anim->mPositionKeys->mValue.z = node.translation.value[2];
  917. }
  918. if (samplers.rotation) {
  919. float *times = nullptr;
  920. samplers.rotation->input->ExtractData(times);
  921. aiQuaternion *values = nullptr;
  922. samplers.rotation->output->ExtractData(values);
  923. anim->mNumRotationKeys = static_cast<uint32_t>(samplers.rotation->input->count);
  924. anim->mRotationKeys = new aiQuatKey[anim->mNumRotationKeys];
  925. for (unsigned int i = 0; i < anim->mNumRotationKeys; ++i) {
  926. anim->mRotationKeys[i].mTime = times[i] * kMillisecondsFromSeconds;
  927. anim->mRotationKeys[i].mValue.x = values[i].w;
  928. anim->mRotationKeys[i].mValue.y = values[i].x;
  929. anim->mRotationKeys[i].mValue.z = values[i].y;
  930. anim->mRotationKeys[i].mValue.w = values[i].z;
  931. }
  932. delete[] times;
  933. delete[] values;
  934. } else if (node.rotation.isPresent) {
  935. anim->mNumRotationKeys = 1;
  936. anim->mRotationKeys = new aiQuatKey[anim->mNumRotationKeys];
  937. anim->mRotationKeys->mTime = 0.f;
  938. anim->mRotationKeys->mValue.x = node.rotation.value[0];
  939. anim->mRotationKeys->mValue.y = node.rotation.value[1];
  940. anim->mRotationKeys->mValue.z = node.rotation.value[2];
  941. anim->mRotationKeys->mValue.w = node.rotation.value[3];
  942. }
  943. if (samplers.scale) {
  944. float *times = nullptr;
  945. samplers.scale->input->ExtractData(times);
  946. aiVector3D *values = nullptr;
  947. samplers.scale->output->ExtractData(values);
  948. anim->mNumScalingKeys = static_cast<uint32_t>(samplers.scale->input->count);
  949. anim->mScalingKeys = new aiVectorKey[anim->mNumScalingKeys];
  950. for (unsigned int i = 0; i < anim->mNumScalingKeys; ++i) {
  951. anim->mScalingKeys[i].mTime = times[i] * kMillisecondsFromSeconds;
  952. anim->mScalingKeys[i].mValue = values[i];
  953. }
  954. delete[] times;
  955. delete[] values;
  956. } else if (node.scale.isPresent) {
  957. anim->mNumScalingKeys = 1;
  958. anim->mScalingKeys = new aiVectorKey[anim->mNumScalingKeys];
  959. anim->mScalingKeys->mTime = 0.f;
  960. anim->mScalingKeys->mValue.x = node.scale.value[0];
  961. anim->mScalingKeys->mValue.y = node.scale.value[1];
  962. anim->mScalingKeys->mValue.z = node.scale.value[2];
  963. }
  964. return anim;
  965. }
  966. aiMeshMorphAnim *CreateMeshMorphAnim(glTF2::Asset&, Node &node, AnimationSamplers &samplers) {
  967. aiMeshMorphAnim *anim = new aiMeshMorphAnim();
  968. anim->mName = GetNodeName(node);
  969. static const float kMillisecondsFromSeconds = 1000.f;
  970. if (nullptr != samplers.weight) {
  971. float *times = nullptr;
  972. samplers.weight->input->ExtractData(times);
  973. float *values = nullptr;
  974. samplers.weight->output->ExtractData(values);
  975. anim->mNumKeys = static_cast<uint32_t>(samplers.weight->input->count);
  976. const unsigned int numMorphs = (unsigned int)samplers.weight->output->count / anim->mNumKeys;
  977. anim->mKeys = new aiMeshMorphKey[anim->mNumKeys];
  978. unsigned int k = 0u;
  979. for (unsigned int i = 0u; i < anim->mNumKeys; ++i) {
  980. anim->mKeys[i].mTime = times[i] * kMillisecondsFromSeconds;
  981. anim->mKeys[i].mNumValuesAndWeights = numMorphs;
  982. anim->mKeys[i].mValues = new unsigned int[numMorphs];
  983. anim->mKeys[i].mWeights = new double[numMorphs];
  984. for (unsigned int j = 0u; j < numMorphs; ++j, ++k) {
  985. anim->mKeys[i].mValues[j] = j;
  986. anim->mKeys[i].mWeights[j] = (0.f > values[k]) ? 0.f : values[k];
  987. }
  988. }
  989. delete[] times;
  990. delete[] values;
  991. }
  992. return anim;
  993. }
  994. std::unordered_map<unsigned int, AnimationSamplers> GatherSamplers(Animation &anim) {
  995. std::unordered_map<unsigned int, AnimationSamplers> samplers;
  996. for (unsigned int c = 0; c < anim.channels.size(); ++c) {
  997. Animation::Channel &channel = anim.channels[c];
  998. if (channel.sampler >= static_cast<int>(anim.samplers.size())) {
  999. continue;
  1000. }
  1001. const unsigned int node_index = channel.target.node.GetIndex();
  1002. AnimationSamplers &sampler = samplers[node_index];
  1003. if (channel.target.path == AnimationPath_TRANSLATION) {
  1004. sampler.translation = &anim.samplers[channel.sampler];
  1005. } else if (channel.target.path == AnimationPath_ROTATION) {
  1006. sampler.rotation = &anim.samplers[channel.sampler];
  1007. } else if (channel.target.path == AnimationPath_SCALE) {
  1008. sampler.scale = &anim.samplers[channel.sampler];
  1009. } else if (channel.target.path == AnimationPath_WEIGHTS) {
  1010. sampler.weight = &anim.samplers[channel.sampler];
  1011. }
  1012. }
  1013. return samplers;
  1014. }
  1015. void glTF2Importer::ImportAnimations(glTF2::Asset &r) {
  1016. if (!r.scene) return;
  1017. const unsigned numAnimations = r.animations.Size();
  1018. ASSIMP_LOG_DEBUG_F("Importing ", numAnimations, " animations");
  1019. mScene->mNumAnimations = numAnimations;
  1020. if (mScene->mNumAnimations == 0) {
  1021. return;
  1022. }
  1023. mScene->mAnimations = new aiAnimation *[numAnimations];
  1024. for (unsigned int i = 0; i < numAnimations; ++i) {
  1025. Animation &anim = r.animations[i];
  1026. aiAnimation *ai_anim = new aiAnimation();
  1027. ai_anim->mName = anim.name;
  1028. ai_anim->mDuration = 0;
  1029. ai_anim->mTicksPerSecond = 0;
  1030. std::unordered_map<unsigned int, AnimationSamplers> samplers = GatherSamplers(anim);
  1031. uint32_t numChannels = 0u;
  1032. uint32_t numMorphMeshChannels = 0u;
  1033. for (auto &iter : samplers) {
  1034. if ((nullptr != iter.second.rotation) || (nullptr != iter.second.scale) || (nullptr != iter.second.translation)) {
  1035. ++numChannels;
  1036. }
  1037. if (nullptr != iter.second.weight) {
  1038. ++numMorphMeshChannels;
  1039. }
  1040. }
  1041. ai_anim->mNumChannels = numChannels;
  1042. if (ai_anim->mNumChannels > 0) {
  1043. ai_anim->mChannels = new aiNodeAnim *[ai_anim->mNumChannels];
  1044. int j = 0;
  1045. for (auto &iter : samplers) {
  1046. if ((nullptr != iter.second.rotation) || (nullptr != iter.second.scale) || (nullptr != iter.second.translation)) {
  1047. ai_anim->mChannels[j] = CreateNodeAnim(r, r.nodes[iter.first], iter.second);
  1048. ++j;
  1049. }
  1050. }
  1051. }
  1052. ai_anim->mNumMorphMeshChannels = numMorphMeshChannels;
  1053. if (ai_anim->mNumMorphMeshChannels > 0) {
  1054. ai_anim->mMorphMeshChannels = new aiMeshMorphAnim *[ai_anim->mNumMorphMeshChannels];
  1055. int j = 0;
  1056. for (auto &iter : samplers) {
  1057. if (nullptr != iter.second.weight) {
  1058. ai_anim->mMorphMeshChannels[j] = CreateMeshMorphAnim(r, r.nodes[iter.first], iter.second);
  1059. ++j;
  1060. }
  1061. }
  1062. }
  1063. // Use the latest keyframe for the duration of the animation
  1064. double maxDuration = 0;
  1065. unsigned int maxNumberOfKeys = 0;
  1066. for (unsigned int j = 0; j < ai_anim->mNumChannels; ++j) {
  1067. auto chan = ai_anim->mChannels[j];
  1068. if (chan->mNumPositionKeys) {
  1069. auto lastPosKey = chan->mPositionKeys[chan->mNumPositionKeys - 1];
  1070. if (lastPosKey.mTime > maxDuration) {
  1071. maxDuration = lastPosKey.mTime;
  1072. }
  1073. maxNumberOfKeys = std::max(maxNumberOfKeys, chan->mNumPositionKeys);
  1074. }
  1075. if (chan->mNumRotationKeys) {
  1076. auto lastRotKey = chan->mRotationKeys[chan->mNumRotationKeys - 1];
  1077. if (lastRotKey.mTime > maxDuration) {
  1078. maxDuration = lastRotKey.mTime;
  1079. }
  1080. maxNumberOfKeys = std::max(maxNumberOfKeys, chan->mNumRotationKeys);
  1081. }
  1082. if (chan->mNumScalingKeys) {
  1083. auto lastScaleKey = chan->mScalingKeys[chan->mNumScalingKeys - 1];
  1084. if (lastScaleKey.mTime > maxDuration) {
  1085. maxDuration = lastScaleKey.mTime;
  1086. }
  1087. maxNumberOfKeys = std::max(maxNumberOfKeys, chan->mNumScalingKeys);
  1088. }
  1089. }
  1090. for (unsigned int j = 0; j < ai_anim->mNumMorphMeshChannels; ++j) {
  1091. const auto *const chan = ai_anim->mMorphMeshChannels[j];
  1092. if (0u != chan->mNumKeys) {
  1093. const auto &lastKey = chan->mKeys[chan->mNumKeys - 1u];
  1094. if (lastKey.mTime > maxDuration) {
  1095. maxDuration = lastKey.mTime;
  1096. }
  1097. maxNumberOfKeys = std::max(maxNumberOfKeys, chan->mNumKeys);
  1098. }
  1099. }
  1100. ai_anim->mDuration = maxDuration;
  1101. ai_anim->mTicksPerSecond = 1000.0;
  1102. mScene->mAnimations[i] = ai_anim;
  1103. }
  1104. }
  1105. void glTF2Importer::ImportEmbeddedTextures(glTF2::Asset &r) {
  1106. embeddedTexIdxs.resize(r.images.Size(), -1);
  1107. int numEmbeddedTexs = 0;
  1108. for (size_t i = 0; i < r.images.Size(); ++i) {
  1109. if (r.images[i].HasData()) {
  1110. numEmbeddedTexs += 1;
  1111. }
  1112. }
  1113. if (numEmbeddedTexs == 0)
  1114. return;
  1115. ASSIMP_LOG_DEBUG_F("Importing ", numEmbeddedTexs, " embedded textures");
  1116. mScene->mTextures = new aiTexture *[numEmbeddedTexs];
  1117. // Add the embedded textures
  1118. for (size_t i = 0; i < r.images.Size(); ++i) {
  1119. Image &img = r.images[i];
  1120. if (!img.HasData()) {
  1121. continue;
  1122. }
  1123. int idx = mScene->mNumTextures++;
  1124. embeddedTexIdxs[i] = idx;
  1125. aiTexture *tex = mScene->mTextures[idx] = new aiTexture();
  1126. size_t length = img.GetDataLength();
  1127. void *data = img.StealData();
  1128. tex->mFilename = img.name;
  1129. tex->mWidth = static_cast<unsigned int>(length);
  1130. tex->mHeight = 0;
  1131. tex->pcData = reinterpret_cast<aiTexel *>(data);
  1132. if (!img.mimeType.empty()) {
  1133. const char *ext = strchr(img.mimeType.c_str(), '/') + 1;
  1134. if (ext) {
  1135. if (strcmp(ext, "jpeg") == 0) {
  1136. ext = "jpg";
  1137. }
  1138. size_t len = strlen(ext);
  1139. if (len <= 3) {
  1140. strcpy(tex->achFormatHint, ext);
  1141. }
  1142. }
  1143. }
  1144. }
  1145. }
  1146. void glTF2Importer::ImportCommonMetadata(glTF2::Asset& a) {
  1147. ASSIMP_LOG_DEBUG("Importing metadata");
  1148. ai_assert(mScene->mMetaData == nullptr);
  1149. const bool hasVersion = !a.asset.version.empty();
  1150. const bool hasGenerator = !a.asset.generator.empty();
  1151. const bool hasCopyright = !a.asset.copyright.empty();
  1152. if (hasVersion || hasGenerator || hasCopyright) {
  1153. mScene->mMetaData = new aiMetadata;
  1154. if (hasVersion) {
  1155. mScene->mMetaData->Add(AI_METADATA_SOURCE_FORMAT_VERSION, aiString(a.asset.version));
  1156. }
  1157. if (hasGenerator) {
  1158. mScene->mMetaData->Add(AI_METADATA_SOURCE_GENERATOR, aiString(a.asset.generator));
  1159. }
  1160. if (hasCopyright) {
  1161. mScene->mMetaData->Add(AI_METADATA_SOURCE_COPYRIGHT, aiString(a.asset.copyright));
  1162. }
  1163. }
  1164. }
  1165. void glTF2Importer::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) {
  1166. ASSIMP_LOG_DEBUG("Reading GLTF2 file");
  1167. // clean all member arrays
  1168. meshOffsets.clear();
  1169. embeddedTexIdxs.clear();
  1170. this->mScene = pScene;
  1171. // read the asset file
  1172. glTF2::Asset asset(pIOHandler);
  1173. asset.Load(pFile, GetExtension(pFile) == "glb");
  1174. //
  1175. // Copy the data out
  1176. //
  1177. ImportEmbeddedTextures(asset);
  1178. ImportMaterials(asset);
  1179. ImportMeshes(asset);
  1180. ImportCameras(asset);
  1181. ImportLights(asset);
  1182. ImportNodes(asset);
  1183. ImportAnimations(asset);
  1184. ImportCommonMetadata(asset);
  1185. if (pScene->mNumMeshes == 0) {
  1186. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  1187. }
  1188. }
  1189. #endif // ASSIMP_BUILD_NO_GLTF_IMPORTER