glTF2Importer.cpp 25 KB

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