glTF2Importer.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2018, 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 "MakeVerboseFormat.h"
  45. #include "glTF2Asset.h"
  46. // This is included here so WriteLazyDict<T>'s definition is found.
  47. #include "glTF2AssetWriter.h"
  48. #include <rapidjson/document.h>
  49. #include <rapidjson/rapidjson.h>
  50. using namespace Assimp;
  51. using namespace glTF2;
  52. namespace {
  53. // generate bitangents from normals and tangents according to spec
  54. struct Tangent {
  55. aiVector3D xyz;
  56. ai_real w;
  57. };
  58. } // namespace
  59. //
  60. // glTF2Importer
  61. //
  62. static const aiImporterDesc desc = {
  63. "glTF2 Importer",
  64. "",
  65. "",
  66. "",
  67. aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_LimitedSupport | aiImporterFlags_Experimental,
  68. 0,
  69. 0,
  70. 0,
  71. 0,
  72. "gltf glb"
  73. };
  74. glTF2Importer::glTF2Importer()
  75. : BaseImporter()
  76. , meshOffsets()
  77. , embeddedTexIdxs()
  78. , mScene( NULL ) {
  79. // empty
  80. }
  81. glTF2Importer::~glTF2Importer() {
  82. // empty
  83. }
  84. const aiImporterDesc* glTF2Importer::GetInfo() const
  85. {
  86. return &desc;
  87. }
  88. bool glTF2Importer::CanRead(const std::string& pFile, IOSystem* pIOHandler, bool /* checkSig */) const
  89. {
  90. const std::string &extension = GetExtension(pFile);
  91. if (extension != "gltf" && extension != "glb")
  92. return false;
  93. if (pIOHandler) {
  94. glTF2::Asset asset(pIOHandler);
  95. asset.Load(pFile, extension == "glb");
  96. std::string version = asset.asset.version;
  97. return !version.empty() && version[0] == '2';
  98. }
  99. return false;
  100. }
  101. static aiTextureMapMode ConvertWrappingMode(SamplerWrap gltfWrapMode)
  102. {
  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. //static void CopyValue(const glTF2::vec3& v, aiColor3D& out)
  115. //{
  116. // out.r = v[0]; out.g = v[1]; out.b = v[2];
  117. //}
  118. static void CopyValue(const glTF2::vec4& v, aiColor4D& out)
  119. {
  120. out.r = v[0]; out.g = v[1]; out.b = v[2]; out.a = v[3];
  121. }
  122. /*static void CopyValue(const glTF2::vec4& v, aiColor3D& out)
  123. {
  124. out.r = v[0]; out.g = v[1]; out.b = v[2];
  125. }*/
  126. static void CopyValue(const glTF2::vec3& v, aiColor4D& out)
  127. {
  128. out.r = v[0]; out.g = v[1]; out.b = v[2]; out.a = 1.0;
  129. }
  130. static void CopyValue(const glTF2::vec3& v, aiVector3D& out)
  131. {
  132. out.x = v[0]; out.y = v[1]; out.z = v[2];
  133. }
  134. static void CopyValue(const glTF2::vec4& v, aiQuaternion& out)
  135. {
  136. out.x = v[0]; out.y = v[1]; out.z = v[2]; out.w = v[3];
  137. }
  138. static void CopyValue(const glTF2::mat4& v, aiMatrix4x4& o)
  139. {
  140. o.a1 = v[ 0]; o.b1 = v[ 1]; o.c1 = v[ 2]; o.d1 = v[ 3];
  141. o.a2 = v[ 4]; o.b2 = v[ 5]; o.c2 = v[ 6]; o.d2 = v[ 7];
  142. o.a3 = v[ 8]; o.b3 = v[ 9]; o.c3 = v[10]; o.d3 = v[11];
  143. o.a4 = v[12]; o.b4 = v[13]; o.c4 = v[14]; o.d4 = v[15];
  144. }
  145. inline void SetMaterialColorProperty(Asset& /*r*/, vec4& prop, aiMaterial* mat, const char* pKey, unsigned int type, unsigned int idx)
  146. {
  147. aiColor4D col;
  148. CopyValue(prop, col);
  149. mat->AddProperty(&col, 1, pKey, type, idx);
  150. }
  151. inline void SetMaterialColorProperty(Asset& /*r*/, vec3& prop, aiMaterial* mat, const char* pKey, unsigned int type, unsigned int idx)
  152. {
  153. aiColor4D col;
  154. CopyValue(prop, col);
  155. mat->AddProperty(&col, 1, pKey, type, idx);
  156. }
  157. inline void SetMaterialTextureProperty(std::vector<int>& embeddedTexIdxs, Asset& /*r*/, glTF2::TextureInfo prop, aiMaterial* mat, aiTextureType texType, unsigned int texSlot = 0)
  158. {
  159. if (prop.texture && prop.texture->source) {
  160. aiString uri(prop.texture->source->uri);
  161. int texIdx = embeddedTexIdxs[prop.texture->source.GetIndex()];
  162. if (texIdx != -1) { // embedded
  163. // setup texture reference string (copied from ColladaLoader::FindFilenameForEffectTexture)
  164. uri.data[0] = '*';
  165. uri.length = 1 + ASSIMP_itoa10(uri.data + 1, MAXLEN - 1, texIdx);
  166. }
  167. mat->AddProperty(&uri, AI_MATKEY_TEXTURE(texType, texSlot));
  168. mat->AddProperty(&prop.texCoord, 1, _AI_MATKEY_GLTF_TEXTURE_TEXCOORD_BASE, texType, texSlot);
  169. if (prop.texture->sampler) {
  170. Ref<Sampler> sampler = prop.texture->sampler;
  171. aiString name(sampler->name);
  172. aiString id(sampler->id);
  173. mat->AddProperty(&name, AI_MATKEY_GLTF_MAPPINGNAME(texType, texSlot));
  174. mat->AddProperty(&id, AI_MATKEY_GLTF_MAPPINGID(texType, texSlot));
  175. aiTextureMapMode wrapS = ConvertWrappingMode(sampler->wrapS);
  176. aiTextureMapMode wrapT = ConvertWrappingMode(sampler->wrapT);
  177. mat->AddProperty(&wrapS, 1, AI_MATKEY_MAPPINGMODE_U(texType, texSlot));
  178. mat->AddProperty(&wrapT, 1, AI_MATKEY_MAPPINGMODE_V(texType, texSlot));
  179. if (sampler->magFilter != SamplerMagFilter::UNSET) {
  180. mat->AddProperty(&sampler->magFilter, 1, AI_MATKEY_GLTF_MAPPINGFILTER_MAG(texType, texSlot));
  181. }
  182. if (sampler->minFilter != SamplerMinFilter::UNSET) {
  183. mat->AddProperty(&sampler->minFilter, 1, AI_MATKEY_GLTF_MAPPINGFILTER_MIN(texType, texSlot));
  184. }
  185. }
  186. }
  187. }
  188. inline void SetMaterialTextureProperty(std::vector<int>& embeddedTexIdxs, Asset& r, glTF2::NormalTextureInfo& prop, aiMaterial* mat, aiTextureType texType, unsigned int texSlot = 0)
  189. {
  190. SetMaterialTextureProperty( embeddedTexIdxs, r, (glTF2::TextureInfo) prop, mat, texType, texSlot );
  191. if (prop.texture && prop.texture->source) {
  192. mat->AddProperty(&prop.scale, 1, AI_MATKEY_GLTF_TEXTURE_SCALE(texType, texSlot));
  193. }
  194. }
  195. inline void SetMaterialTextureProperty(std::vector<int>& embeddedTexIdxs, Asset& r, glTF2::OcclusionTextureInfo& prop, aiMaterial* mat, aiTextureType texType, unsigned int texSlot = 0)
  196. {
  197. SetMaterialTextureProperty( embeddedTexIdxs, r, (glTF2::TextureInfo) prop, mat, texType, texSlot );
  198. if (prop.texture && prop.texture->source) {
  199. mat->AddProperty(&prop.strength, 1, AI_MATKEY_GLTF_TEXTURE_STRENGTH(texType, texSlot));
  200. }
  201. }
  202. static aiMaterial* ImportMaterial(std::vector<int>& embeddedTexIdxs, Asset& r, Material& mat)
  203. {
  204. aiMaterial* aimat = new aiMaterial();
  205. if (!mat.name.empty()) {
  206. aiString str(mat.name);
  207. aimat->AddProperty(&str, AI_MATKEY_NAME);
  208. }
  209. SetMaterialColorProperty(r, mat.pbrMetallicRoughness.baseColorFactor, aimat, AI_MATKEY_COLOR_DIFFUSE);
  210. SetMaterialColorProperty(r, mat.pbrMetallicRoughness.baseColorFactor, aimat, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_FACTOR);
  211. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.baseColorTexture, aimat, aiTextureType_DIFFUSE);
  212. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.baseColorTexture, aimat, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_TEXTURE);
  213. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.metallicRoughnessTexture, aimat, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE);
  214. aimat->AddProperty(&mat.pbrMetallicRoughness.metallicFactor, 1, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLIC_FACTOR);
  215. aimat->AddProperty(&mat.pbrMetallicRoughness.roughnessFactor, 1, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_ROUGHNESS_FACTOR);
  216. float roughnessAsShininess = (1 - mat.pbrMetallicRoughness.roughnessFactor) * 1000;
  217. aimat->AddProperty(&roughnessAsShininess, 1, AI_MATKEY_SHININESS);
  218. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.normalTexture, aimat, aiTextureType_NORMALS);
  219. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.occlusionTexture, aimat, aiTextureType_LIGHTMAP);
  220. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.emissiveTexture, aimat, aiTextureType_EMISSIVE);
  221. SetMaterialColorProperty(r, mat.emissiveFactor, aimat, AI_MATKEY_COLOR_EMISSIVE);
  222. aimat->AddProperty(&mat.doubleSided, 1, AI_MATKEY_TWOSIDED);
  223. aiString alphaMode(mat.alphaMode);
  224. aimat->AddProperty(&alphaMode, AI_MATKEY_GLTF_ALPHAMODE);
  225. aimat->AddProperty(&mat.alphaCutoff, 1, AI_MATKEY_GLTF_ALPHACUTOFF);
  226. //pbrSpecularGlossiness
  227. if (mat.pbrSpecularGlossiness.isPresent) {
  228. PbrSpecularGlossiness &pbrSG = mat.pbrSpecularGlossiness.value;
  229. aimat->AddProperty(&mat.pbrSpecularGlossiness.isPresent, 1, AI_MATKEY_GLTF_PBRSPECULARGLOSSINESS);
  230. SetMaterialColorProperty(r, pbrSG.diffuseFactor, aimat, AI_MATKEY_COLOR_DIFFUSE);
  231. SetMaterialColorProperty(r, pbrSG.specularFactor, aimat, AI_MATKEY_COLOR_SPECULAR);
  232. float glossinessAsShininess = pbrSG.glossinessFactor * 1000.0f;
  233. aimat->AddProperty(&glossinessAsShininess, 1, AI_MATKEY_SHININESS);
  234. aimat->AddProperty(&pbrSG.glossinessFactor, 1, AI_MATKEY_GLTF_PBRSPECULARGLOSSINESS_GLOSSINESS_FACTOR);
  235. SetMaterialTextureProperty(embeddedTexIdxs, r, pbrSG.diffuseTexture, aimat, aiTextureType_DIFFUSE);
  236. SetMaterialTextureProperty(embeddedTexIdxs, r, pbrSG.specularGlossinessTexture, aimat, aiTextureType_SPECULAR);
  237. }
  238. if (mat.unlit) {
  239. aimat->AddProperty(&mat.unlit, 1, AI_MATKEY_GLTF_UNLIT);
  240. }
  241. return aimat;
  242. }
  243. void glTF2Importer::ImportMaterials(glTF2::Asset& r)
  244. {
  245. const unsigned int numImportedMaterials = unsigned(r.materials.Size());
  246. Material defaultMaterial;
  247. mScene->mNumMaterials = numImportedMaterials + 1;
  248. mScene->mMaterials = new aiMaterial*[mScene->mNumMaterials];
  249. mScene->mMaterials[numImportedMaterials] = ImportMaterial(embeddedTexIdxs, r, defaultMaterial);
  250. for (unsigned int i = 0; i < numImportedMaterials; ++i) {
  251. mScene->mMaterials[i] = ImportMaterial(embeddedTexIdxs, r, r.materials[i]);
  252. }
  253. }
  254. static inline void SetFace(aiFace& face, int a)
  255. {
  256. face.mNumIndices = 1;
  257. face.mIndices = new unsigned int[1];
  258. face.mIndices[0] = a;
  259. }
  260. static inline void SetFace(aiFace& face, int a, int b)
  261. {
  262. face.mNumIndices = 2;
  263. face.mIndices = new unsigned int[2];
  264. face.mIndices[0] = a;
  265. face.mIndices[1] = b;
  266. }
  267. static inline void SetFace(aiFace& face, int a, int b, int c)
  268. {
  269. face.mNumIndices = 3;
  270. face.mIndices = new unsigned int[3];
  271. face.mIndices[0] = a;
  272. face.mIndices[1] = b;
  273. face.mIndices[2] = c;
  274. }
  275. #ifdef ASSIMP_BUILD_DEBUG
  276. static inline bool CheckValidFacesIndices(aiFace* faces, unsigned nFaces, unsigned nVerts)
  277. {
  278. for (unsigned i = 0; i < nFaces; ++i) {
  279. for (unsigned j = 0; j < faces[i].mNumIndices; ++j) {
  280. unsigned idx = faces[i].mIndices[j];
  281. if (idx >= nVerts)
  282. return false;
  283. }
  284. }
  285. return true;
  286. }
  287. #endif // ASSIMP_BUILD_DEBUG
  288. void glTF2Importer::ImportMeshes(glTF2::Asset& r)
  289. {
  290. std::vector<aiMesh*> meshes;
  291. unsigned int k = 0;
  292. for (unsigned int m = 0; m < r.meshes.Size(); ++m) {
  293. Mesh& mesh = r.meshes[m];
  294. meshOffsets.push_back(k);
  295. k += unsigned(mesh.primitives.size());
  296. for (unsigned int p = 0; p < mesh.primitives.size(); ++p) {
  297. Mesh::Primitive& prim = mesh.primitives[p];
  298. aiMesh* aim = new aiMesh();
  299. meshes.push_back(aim);
  300. aim->mName = mesh.name.empty() ? mesh.id : mesh.name;
  301. if (mesh.primitives.size() > 1) {
  302. size_t& len = aim->mName.length;
  303. aim->mName.data[len] = '-';
  304. len += 1 + ASSIMP_itoa10(aim->mName.data + len + 1, unsigned(MAXLEN - len - 1), p);
  305. }
  306. switch (prim.mode) {
  307. case PrimitiveMode_POINTS:
  308. aim->mPrimitiveTypes |= aiPrimitiveType_POINT;
  309. break;
  310. case PrimitiveMode_LINES:
  311. case PrimitiveMode_LINE_LOOP:
  312. case PrimitiveMode_LINE_STRIP:
  313. aim->mPrimitiveTypes |= aiPrimitiveType_LINE;
  314. break;
  315. case PrimitiveMode_TRIANGLES:
  316. case PrimitiveMode_TRIANGLE_STRIP:
  317. case PrimitiveMode_TRIANGLE_FAN:
  318. aim->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  319. break;
  320. }
  321. Mesh::Primitive::Attributes& attr = prim.attributes;
  322. if (attr.position.size() > 0 && attr.position[0]) {
  323. aim->mNumVertices = attr.position[0]->count;
  324. attr.position[0]->ExtractData(aim->mVertices);
  325. }
  326. if (attr.normal.size() > 0 && attr.normal[0]) {
  327. attr.normal[0]->ExtractData(aim->mNormals);
  328. // only extract tangents if normals are present
  329. if (attr.tangent.size() > 0 && attr.tangent[0]) {
  330. // generate bitangents from normals and tangents according to spec
  331. Tangent *tangents = nullptr;
  332. attr.tangent[0]->ExtractData(tangents);
  333. aim->mTangents = new aiVector3D[aim->mNumVertices];
  334. aim->mBitangents = new aiVector3D[aim->mNumVertices];
  335. for (unsigned int i = 0; i < aim->mNumVertices; ++i) {
  336. aim->mTangents[i] = tangents[i].xyz;
  337. aim->mBitangents[i] = (aim->mNormals[i] ^ tangents[i].xyz) * tangents[i].w;
  338. }
  339. delete [] tangents;
  340. }
  341. }
  342. for (size_t tc = 0; tc < attr.texcoord.size() && tc < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++tc) {
  343. if (attr.texcoord[tc]->count != aim->mNumVertices) {
  344. DefaultLogger::get()->warn("Texcoord stream size in mesh \"" + mesh.name +
  345. "\" does not match the vertex count");
  346. continue;
  347. }
  348. attr.texcoord[tc]->ExtractData(aim->mTextureCoords[tc]);
  349. aim->mNumUVComponents[tc] = attr.texcoord[tc]->GetNumComponents();
  350. aiVector3D* values = aim->mTextureCoords[tc];
  351. for (unsigned int i = 0; i < aim->mNumVertices; ++i) {
  352. values[i].y = 1 - values[i].y; // Flip Y coords
  353. }
  354. }
  355. std::vector<Mesh::Primitive::Target>& targets = prim.targets;
  356. if (targets.size() > 0) {
  357. aim->mNumAnimMeshes = (unsigned int)targets.size();
  358. aim->mAnimMeshes = new aiAnimMesh*[aim->mNumAnimMeshes];
  359. for (size_t i = 0; i < targets.size(); i++) {
  360. aim->mAnimMeshes[i] = aiCreateAnimMesh(aim);
  361. aiAnimMesh& aiAnimMesh = *(aim->mAnimMeshes[i]);
  362. Mesh::Primitive::Target& target = targets[i];
  363. if (target.position.size() > 0) {
  364. aiVector3D *positionDiff = nullptr;
  365. target.position[0]->ExtractData(positionDiff);
  366. for(unsigned int vertexId = 0; vertexId < aim->mNumVertices; vertexId++) {
  367. aiAnimMesh.mVertices[vertexId] += positionDiff[vertexId];
  368. }
  369. delete [] positionDiff;
  370. }
  371. if (target.normal.size() > 0) {
  372. aiVector3D *normalDiff = nullptr;
  373. target.normal[0]->ExtractData(normalDiff);
  374. for(unsigned int vertexId = 0; vertexId < aim->mNumVertices; vertexId++) {
  375. aiAnimMesh.mNormals[vertexId] += normalDiff[vertexId];
  376. }
  377. delete [] normalDiff;
  378. }
  379. if (target.tangent.size() > 0) {
  380. Tangent *tangent = nullptr;
  381. attr.tangent[0]->ExtractData(tangent);
  382. aiVector3D *tangentDiff = nullptr;
  383. target.tangent[0]->ExtractData(tangentDiff);
  384. for (unsigned int vertexId = 0; vertexId < aim->mNumVertices; ++vertexId) {
  385. tangent[vertexId].xyz += tangentDiff[vertexId];
  386. aiAnimMesh.mTangents[vertexId] = tangent[vertexId].xyz;
  387. aiAnimMesh.mBitangents[vertexId] = (aiAnimMesh.mNormals[vertexId] ^ tangent[vertexId].xyz) * tangent[vertexId].w;
  388. }
  389. delete [] tangent;
  390. delete [] tangentDiff;
  391. }
  392. if (mesh.weights.size() > i) {
  393. aiAnimMesh.mWeight = mesh.weights[i];
  394. }
  395. }
  396. }
  397. aiFace* faces = 0;
  398. unsigned int nFaces = 0;
  399. if (prim.indices) {
  400. unsigned int count = prim.indices->count;
  401. Accessor::Indexer data = prim.indices->GetIndexer();
  402. ai_assert(data.IsValid());
  403. switch (prim.mode) {
  404. case PrimitiveMode_POINTS: {
  405. nFaces = count;
  406. faces = new aiFace[nFaces];
  407. for (unsigned int i = 0; i < count; ++i) {
  408. SetFace(faces[i], data.GetUInt(i));
  409. }
  410. break;
  411. }
  412. case PrimitiveMode_LINES: {
  413. nFaces = count / 2;
  414. faces = new aiFace[nFaces];
  415. for (unsigned int i = 0; i < count; i += 2) {
  416. SetFace(faces[i / 2], data.GetUInt(i), data.GetUInt(i + 1));
  417. }
  418. break;
  419. }
  420. case PrimitiveMode_LINE_LOOP:
  421. case PrimitiveMode_LINE_STRIP: {
  422. nFaces = count - ((prim.mode == PrimitiveMode_LINE_STRIP) ? 1 : 0);
  423. faces = new aiFace[nFaces];
  424. SetFace(faces[0], data.GetUInt(0), data.GetUInt(1));
  425. for (unsigned int i = 2; i < count; ++i) {
  426. SetFace(faces[i - 1], faces[i - 2].mIndices[1], data.GetUInt(i));
  427. }
  428. if (prim.mode == PrimitiveMode_LINE_LOOP) { // close the loop
  429. SetFace(faces[count - 1], faces[count - 2].mIndices[1], faces[0].mIndices[0]);
  430. }
  431. break;
  432. }
  433. case PrimitiveMode_TRIANGLES: {
  434. nFaces = count / 3;
  435. faces = new aiFace[nFaces];
  436. for (unsigned int i = 0; i < count; i += 3) {
  437. SetFace(faces[i / 3], data.GetUInt(i), data.GetUInt(i + 1), data.GetUInt(i + 2));
  438. }
  439. break;
  440. }
  441. case PrimitiveMode_TRIANGLE_STRIP: {
  442. nFaces = count - 2;
  443. faces = new aiFace[nFaces];
  444. for (unsigned int i = 0; i < nFaces; ++i) {
  445. //The ordering is to ensure that the triangles are all drawn with the same orientation
  446. if ((i + 1) % 2 == 0)
  447. {
  448. //For even n, vertices n + 1, n, and n + 2 define triangle n
  449. SetFace(faces[i], data.GetUInt(i + 1), data.GetUInt(i), data.GetUInt(i + 2));
  450. }
  451. else
  452. {
  453. //For odd n, vertices n, n+1, and n+2 define triangle n
  454. SetFace(faces[i], data.GetUInt(i), data.GetUInt(i + 1), data.GetUInt(i + 2));
  455. }
  456. }
  457. break;
  458. }
  459. case PrimitiveMode_TRIANGLE_FAN:
  460. nFaces = count - 2;
  461. faces = new aiFace[nFaces];
  462. SetFace(faces[0], data.GetUInt(0), data.GetUInt(1), data.GetUInt(2));
  463. for (unsigned int i = 1; i < nFaces; ++i) {
  464. SetFace(faces[i], faces[0].mIndices[0], faces[i - 1].mIndices[2], data.GetUInt(i + 2));
  465. }
  466. break;
  467. }
  468. }
  469. else { // no indices provided so directly generate from counts
  470. // use the already determined count as it includes checks
  471. unsigned int count = aim->mNumVertices;
  472. switch (prim.mode) {
  473. case PrimitiveMode_POINTS: {
  474. nFaces = count;
  475. faces = new aiFace[nFaces];
  476. for (unsigned int i = 0; i < count; ++i) {
  477. SetFace(faces[i], i);
  478. }
  479. break;
  480. }
  481. case PrimitiveMode_LINES: {
  482. nFaces = count / 2;
  483. faces = new aiFace[nFaces];
  484. for (unsigned int i = 0; i < count; i += 2) {
  485. SetFace(faces[i / 2], i, i + 1);
  486. }
  487. break;
  488. }
  489. case PrimitiveMode_LINE_LOOP:
  490. case PrimitiveMode_LINE_STRIP: {
  491. nFaces = count - ((prim.mode == PrimitiveMode_LINE_STRIP) ? 1 : 0);
  492. faces = new aiFace[nFaces];
  493. SetFace(faces[0], 0, 1);
  494. for (unsigned int i = 2; i < count; ++i) {
  495. SetFace(faces[i - 1], faces[i - 2].mIndices[1], i);
  496. }
  497. if (prim.mode == PrimitiveMode_LINE_LOOP) { // close the loop
  498. SetFace(faces[count - 1], faces[count - 2].mIndices[1], faces[0].mIndices[0]);
  499. }
  500. break;
  501. }
  502. case PrimitiveMode_TRIANGLES: {
  503. nFaces = count / 3;
  504. faces = new aiFace[nFaces];
  505. for (unsigned int i = 0; i < count; i += 3) {
  506. SetFace(faces[i / 3], i, i + 1, i + 2);
  507. }
  508. break;
  509. }
  510. case PrimitiveMode_TRIANGLE_STRIP: {
  511. nFaces = count - 2;
  512. faces = new aiFace[nFaces];
  513. for (unsigned int i = 0; i < nFaces; ++i) {
  514. //The ordering is to ensure that the triangles are all drawn with the same orientation
  515. if ((i+1) % 2 == 0)
  516. {
  517. //For even n, vertices n + 1, n, and n + 2 define triangle n
  518. SetFace(faces[i], i+1, i, i+2);
  519. }
  520. else
  521. {
  522. //For odd n, vertices n, n+1, and n+2 define triangle n
  523. SetFace(faces[i], i, i+1, i+2);
  524. }
  525. }
  526. break;
  527. }
  528. case PrimitiveMode_TRIANGLE_FAN:
  529. nFaces = count - 2;
  530. faces = new aiFace[nFaces];
  531. SetFace(faces[0], 0, 1, 2);
  532. for (unsigned int i = 1; i < nFaces; ++i) {
  533. SetFace(faces[i], faces[0].mIndices[0], faces[i - 1].mIndices[2], i + 2);
  534. }
  535. break;
  536. }
  537. }
  538. if (faces) {
  539. aim->mFaces = faces;
  540. aim->mNumFaces = nFaces;
  541. ai_assert(CheckValidFacesIndices(faces, nFaces, aim->mNumVertices));
  542. }
  543. if (prim.material) {
  544. aim->mMaterialIndex = prim.material.GetIndex();
  545. }
  546. else {
  547. aim->mMaterialIndex = mScene->mNumMaterials - 1;
  548. }
  549. }
  550. }
  551. meshOffsets.push_back(k);
  552. CopyVector(meshes, mScene->mMeshes, mScene->mNumMeshes);
  553. }
  554. void glTF2Importer::ImportCameras(glTF2::Asset& r)
  555. {
  556. if (!r.cameras.Size()) return;
  557. mScene->mNumCameras = r.cameras.Size();
  558. mScene->mCameras = new aiCamera*[r.cameras.Size()];
  559. for (size_t i = 0; i < r.cameras.Size(); ++i) {
  560. Camera& cam = r.cameras[i];
  561. aiCamera* aicam = mScene->mCameras[i] = new aiCamera();
  562. // cameras point in -Z by default, rest is specified in node transform
  563. aicam->mLookAt = aiVector3D(0.f,0.f,-1.f);
  564. if (cam.type == Camera::Perspective) {
  565. aicam->mAspect = cam.cameraProperties.perspective.aspectRatio;
  566. aicam->mHorizontalFOV = cam.cameraProperties.perspective.yfov * aicam->mAspect;
  567. aicam->mClipPlaneFar = cam.cameraProperties.perspective.zfar;
  568. aicam->mClipPlaneNear = cam.cameraProperties.perspective.znear;
  569. }
  570. else {
  571. // assimp does not support orthographic cameras
  572. }
  573. }
  574. }
  575. aiNode* ImportNode(aiScene* pScene, glTF2::Asset& r, std::vector<unsigned int>& meshOffsets, glTF2::Ref<glTF2::Node>& ptr)
  576. {
  577. Node& node = *ptr;
  578. std::string nameOrId = node.name.empty() ? node.id : node.name;
  579. aiNode* ainode = new aiNode(nameOrId);
  580. if (!node.children.empty()) {
  581. ainode->mNumChildren = unsigned(node.children.size());
  582. ainode->mChildren = new aiNode*[ainode->mNumChildren];
  583. for (unsigned int i = 0; i < ainode->mNumChildren; ++i) {
  584. aiNode* child = ImportNode(pScene, r, meshOffsets, node.children[i]);
  585. child->mParent = ainode;
  586. ainode->mChildren[i] = child;
  587. }
  588. }
  589. aiMatrix4x4& matrix = ainode->mTransformation;
  590. if (node.matrix.isPresent) {
  591. CopyValue(node.matrix.value, matrix);
  592. }
  593. else {
  594. if (node.translation.isPresent) {
  595. aiVector3D trans;
  596. CopyValue(node.translation.value, trans);
  597. aiMatrix4x4 t;
  598. aiMatrix4x4::Translation(trans, t);
  599. matrix = matrix * t;
  600. }
  601. if (node.rotation.isPresent) {
  602. aiQuaternion rot;
  603. CopyValue(node.rotation.value, rot);
  604. matrix = matrix * aiMatrix4x4(rot.GetMatrix());
  605. }
  606. if (node.scale.isPresent) {
  607. aiVector3D scal(1.f);
  608. CopyValue(node.scale.value, scal);
  609. aiMatrix4x4 s;
  610. aiMatrix4x4::Scaling(scal, s);
  611. matrix = matrix * s;
  612. }
  613. }
  614. if (!node.meshes.empty()) {
  615. int count = 0;
  616. for (size_t i = 0; i < node.meshes.size(); ++i) {
  617. int idx = node.meshes[i].GetIndex();
  618. count += meshOffsets[idx + 1] - meshOffsets[idx];
  619. }
  620. ainode->mNumMeshes = count;
  621. ainode->mMeshes = new unsigned int[count];
  622. int k = 0;
  623. for (size_t i = 0; i < node.meshes.size(); ++i) {
  624. int idx = node.meshes[i].GetIndex();
  625. for (unsigned int j = meshOffsets[idx]; j < meshOffsets[idx + 1]; ++j, ++k) {
  626. ainode->mMeshes[k] = j;
  627. }
  628. }
  629. }
  630. if (node.camera) {
  631. pScene->mCameras[node.camera.GetIndex()]->mName = ainode->mName;
  632. }
  633. return ainode;
  634. }
  635. void glTF2Importer::ImportNodes(glTF2::Asset& r)
  636. {
  637. if (!r.scene) return;
  638. std::vector< Ref<Node> > rootNodes = r.scene->nodes;
  639. // The root nodes
  640. unsigned int numRootNodes = unsigned(rootNodes.size());
  641. if (numRootNodes == 1) { // a single root node: use it
  642. mScene->mRootNode = ImportNode(mScene, r, meshOffsets, rootNodes[0]);
  643. }
  644. else if (numRootNodes > 1) { // more than one root node: create a fake root
  645. aiNode* root = new aiNode("ROOT");
  646. root->mChildren = new aiNode*[numRootNodes];
  647. for (unsigned int i = 0; i < numRootNodes; ++i) {
  648. aiNode* node = ImportNode(mScene, r, meshOffsets, rootNodes[i]);
  649. node->mParent = root;
  650. root->mChildren[root->mNumChildren++] = node;
  651. }
  652. mScene->mRootNode = root;
  653. }
  654. //if (!mScene->mRootNode) {
  655. // mScene->mRootNode = new aiNode("EMPTY");
  656. //}
  657. }
  658. void glTF2Importer::ImportEmbeddedTextures(glTF2::Asset& r)
  659. {
  660. embeddedTexIdxs.resize(r.images.Size(), -1);
  661. int numEmbeddedTexs = 0;
  662. for (size_t i = 0; i < r.images.Size(); ++i) {
  663. if (r.images[i].HasData())
  664. numEmbeddedTexs += 1;
  665. }
  666. if (numEmbeddedTexs == 0)
  667. return;
  668. mScene->mTextures = new aiTexture*[numEmbeddedTexs];
  669. // Add the embedded textures
  670. for (size_t i = 0; i < r.images.Size(); ++i) {
  671. Image &img = r.images[i];
  672. if (!img.HasData()) continue;
  673. int idx = mScene->mNumTextures++;
  674. embeddedTexIdxs[i] = idx;
  675. aiTexture* tex = mScene->mTextures[idx] = new aiTexture();
  676. size_t length = img.GetDataLength();
  677. void* data = img.StealData();
  678. tex->mWidth = static_cast<unsigned int>(length);
  679. tex->mHeight = 0;
  680. tex->pcData = reinterpret_cast<aiTexel*>(data);
  681. if (!img.mimeType.empty()) {
  682. const char* ext = strchr(img.mimeType.c_str(), '/') + 1;
  683. if (ext) {
  684. if (strcmp(ext, "jpeg") == 0) ext = "jpg";
  685. size_t len = strlen(ext);
  686. if (len <= 3) {
  687. strcpy(tex->achFormatHint, ext);
  688. }
  689. }
  690. }
  691. }
  692. }
  693. void glTF2Importer::InternReadFile(const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) {
  694. this->mScene = pScene;
  695. // read the asset file
  696. glTF2::Asset asset(pIOHandler);
  697. asset.Load(pFile, GetExtension(pFile) == "glb");
  698. //
  699. // Copy the data out
  700. //
  701. ImportEmbeddedTextures(asset);
  702. ImportMaterials(asset);
  703. ImportMeshes(asset);
  704. ImportCameras(asset);
  705. ImportNodes(asset);
  706. if (pScene->mNumMeshes == 0) {
  707. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  708. }
  709. }
  710. #endif // ASSIMP_BUILD_NO_GLTF_IMPORTER