glTFImporter.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  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. #ifndef ASSIMP_BUILD_NO_GLTF_IMPORTER
  34. #include "glTF/glTFImporter.h"
  35. #include "glTF/glTFAsset.h"
  36. #include "glTF/glTFAssetWriter.h"
  37. #include "PostProcessing/MakeVerboseFormat.h"
  38. #include <assimp/StringComparison.h>
  39. #include <assimp/StringUtils.h>
  40. #include <assimp/Importer.hpp>
  41. #include <assimp/scene.h>
  42. #include <assimp/ai_assert.h>
  43. #include <assimp/DefaultLogger.hpp>
  44. #include <assimp/importerdesc.h>
  45. #include <assimp/commonMetaData.h>
  46. #include <memory>
  47. using namespace Assimp;
  48. using namespace glTF;
  49. //
  50. // glTFImporter
  51. //
  52. static const aiImporterDesc desc = {
  53. "glTF Importer",
  54. "",
  55. "",
  56. "",
  57. aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_SupportCompressedFlavour
  58. | aiImporterFlags_LimitedSupport | aiImporterFlags_Experimental,
  59. 0,
  60. 0,
  61. 0,
  62. 0,
  63. "gltf glb"
  64. };
  65. glTFImporter::glTFImporter()
  66. : BaseImporter()
  67. , meshOffsets()
  68. , embeddedTexIdxs()
  69. , mScene( nullptr ) {
  70. // empty
  71. }
  72. glTFImporter::~glTFImporter() {
  73. // empty
  74. }
  75. const aiImporterDesc* glTFImporter::GetInfo() const {
  76. return &desc;
  77. }
  78. bool glTFImporter::CanRead(const std::string& pFile, IOSystem* pIOHandler, bool /* checkSig */) const {
  79. const std::string &extension = GetExtension(pFile);
  80. if (extension != "gltf" && extension != "glb") {
  81. return false;
  82. }
  83. if (pIOHandler) {
  84. glTF::Asset asset(pIOHandler);
  85. try {
  86. asset.Load(pFile, extension == "glb");
  87. std::string version = asset.asset.version;
  88. return !version.empty() && version[0] == '1';
  89. } catch (...) {
  90. return false;
  91. }
  92. }
  93. return false;
  94. }
  95. inline
  96. void SetMaterialColorProperty(std::vector<int>& embeddedTexIdxs, Asset& /*r*/, glTF::TexProperty prop, aiMaterial* mat,
  97. aiTextureType texType, const char* pKey, unsigned int type, unsigned int idx) {
  98. if (prop.texture) {
  99. if (prop.texture->source) {
  100. aiString uri(prop.texture->source->uri);
  101. int texIdx = embeddedTexIdxs[prop.texture->source.GetIndex()];
  102. if (texIdx != -1) { // embedded
  103. // setup texture reference string (copied from ColladaLoader::FindFilenameForEffectTexture)
  104. uri.data[0] = '*';
  105. uri.length = 1 + ASSIMP_itoa10(uri.data + 1, MAXLEN - 1, texIdx);
  106. }
  107. mat->AddProperty(&uri, _AI_MATKEY_TEXTURE_BASE, texType, 0);
  108. }
  109. } else {
  110. aiColor4D col;
  111. CopyValue(prop.color, col);
  112. mat->AddProperty(&col, 1, pKey, type, idx);
  113. }
  114. }
  115. void glTFImporter::ImportMaterials(glTF::Asset& r) {
  116. mScene->mNumMaterials = unsigned(r.materials.Size());
  117. mScene->mMaterials = new aiMaterial*[mScene->mNumMaterials];
  118. for (unsigned int i = 0; i < mScene->mNumMaterials; ++i) {
  119. aiMaterial* aimat = mScene->mMaterials[i] = new aiMaterial();
  120. Material& mat = r.materials[i];
  121. /*if (!mat.name.empty())*/ {
  122. aiString str(mat.id /*mat.name*/);
  123. aimat->AddProperty(&str, AI_MATKEY_NAME);
  124. }
  125. SetMaterialColorProperty(embeddedTexIdxs, r, mat.ambient, aimat, aiTextureType_AMBIENT, AI_MATKEY_COLOR_AMBIENT );
  126. SetMaterialColorProperty(embeddedTexIdxs, r, mat.diffuse, aimat, aiTextureType_DIFFUSE, AI_MATKEY_COLOR_DIFFUSE );
  127. SetMaterialColorProperty(embeddedTexIdxs, r, mat.specular, aimat, aiTextureType_SPECULAR, AI_MATKEY_COLOR_SPECULAR);
  128. SetMaterialColorProperty(embeddedTexIdxs, r, mat.emission, aimat, aiTextureType_EMISSIVE, AI_MATKEY_COLOR_EMISSIVE);
  129. aimat->AddProperty(&mat.doubleSided, 1, AI_MATKEY_TWOSIDED);
  130. if (mat.transparent && (mat.transparency != 1.0f)) {
  131. aimat->AddProperty(&mat.transparency, 1, AI_MATKEY_OPACITY);
  132. }
  133. if (mat.shininess > 0.f) {
  134. aimat->AddProperty(&mat.shininess, 1, AI_MATKEY_SHININESS);
  135. }
  136. }
  137. if (mScene->mNumMaterials == 0) {
  138. mScene->mNumMaterials = 1;
  139. // Delete the array of length zero created above.
  140. delete[] mScene->mMaterials;
  141. mScene->mMaterials = new aiMaterial*[1];
  142. mScene->mMaterials[0] = new aiMaterial();
  143. }
  144. }
  145. static inline void SetFace(aiFace& face, int a)
  146. {
  147. face.mNumIndices = 1;
  148. face.mIndices = new unsigned int[1];
  149. face.mIndices[0] = a;
  150. }
  151. static inline void SetFace(aiFace& face, int a, int b)
  152. {
  153. face.mNumIndices = 2;
  154. face.mIndices = new unsigned int[2];
  155. face.mIndices[0] = a;
  156. face.mIndices[1] = b;
  157. }
  158. static inline void SetFace(aiFace& face, int a, int b, int c)
  159. {
  160. face.mNumIndices = 3;
  161. face.mIndices = new unsigned int[3];
  162. face.mIndices[0] = a;
  163. face.mIndices[1] = b;
  164. face.mIndices[2] = c;
  165. }
  166. #ifdef ASSIMP_BUILD_DEBUG
  167. static inline bool CheckValidFacesIndices(aiFace* faces, unsigned nFaces, unsigned nVerts)
  168. {
  169. for (unsigned i = 0; i < nFaces; ++i) {
  170. for (unsigned j = 0; j < faces[i].mNumIndices; ++j) {
  171. unsigned idx = faces[i].mIndices[j];
  172. if (idx >= nVerts)
  173. return false;
  174. }
  175. }
  176. return true;
  177. }
  178. #endif // ASSIMP_BUILD_DEBUG
  179. void glTFImporter::ImportMeshes(glTF::Asset& r)
  180. {
  181. std::vector<aiMesh*> meshes;
  182. unsigned int k = 0;
  183. meshOffsets.clear();
  184. for (unsigned int m = 0; m < r.meshes.Size(); ++m) {
  185. Mesh& mesh = r.meshes[m];
  186. // Check if mesh extensions is used
  187. if(mesh.Extension.size() > 0)
  188. {
  189. for(Mesh::SExtension* cur_ext : mesh.Extension)
  190. {
  191. #ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
  192. if(cur_ext->Type == Mesh::SExtension::EType::Compression_Open3DGC)
  193. {
  194. // Limitations for meshes when using Open3DGC-compression.
  195. // It's a current limitation of sp... Specification have not this part still - about mesh compression. Why only one primitive?
  196. // Because glTF is very flexibly. But in fact it ugly flexible. Every primitive can has own set of accessors and accessors can
  197. // point to a-a-a-a-any part of buffer (through bufferview of course) and even to another buffer. We know that "Open3DGC-compression"
  198. // is applicable only to part of buffer. As we can't guaranty continuity of the data for decoder, we will limit quantity of primitives.
  199. // Yes indices, coordinates etc. still can br stored in different buffers, but with current specification it's a exporter problem.
  200. // Also primitive can has only one of "POSITION", "NORMAL" and less then "AI_MAX_NUMBER_OF_TEXTURECOORDS" of "TEXCOORD". All accessor
  201. // of primitive must point to one continuous region of the buffer.
  202. if(mesh.primitives.size() > 2) throw DeadlyImportError("GLTF: When using Open3DGC compression then only one primitive per mesh are allowed.");
  203. Mesh::SCompression_Open3DGC* o3dgc_ext = (Mesh::SCompression_Open3DGC*)cur_ext;
  204. Ref<Buffer> buf = r.buffers.Get(o3dgc_ext->Buffer);
  205. buf->EncodedRegion_SetCurrent(mesh.id);
  206. }
  207. else
  208. #endif
  209. {
  210. throw DeadlyImportError("GLTF: Can not import mesh: unknown mesh extension (code: \"" + to_string(cur_ext->Type) +
  211. "\"), only Open3DGC is supported.");
  212. }
  213. }
  214. }// if(mesh.Extension.size() > 0)
  215. meshOffsets.push_back(k);
  216. k += unsigned(mesh.primitives.size());
  217. for (unsigned int p = 0; p < mesh.primitives.size(); ++p) {
  218. Mesh::Primitive& prim = mesh.primitives[p];
  219. aiMesh* aim = new aiMesh();
  220. meshes.push_back(aim);
  221. aim->mName = mesh.id;
  222. if (mesh.primitives.size() > 1) {
  223. ai_uint32& len = aim->mName.length;
  224. aim->mName.data[len] = '-';
  225. len += 1 + ASSIMP_itoa10(aim->mName.data + len + 1, unsigned(MAXLEN - len - 1), p);
  226. }
  227. switch (prim.mode) {
  228. case PrimitiveMode_POINTS:
  229. aim->mPrimitiveTypes |= aiPrimitiveType_POINT;
  230. break;
  231. case PrimitiveMode_LINES:
  232. case PrimitiveMode_LINE_LOOP:
  233. case PrimitiveMode_LINE_STRIP:
  234. aim->mPrimitiveTypes |= aiPrimitiveType_LINE;
  235. break;
  236. case PrimitiveMode_TRIANGLES:
  237. case PrimitiveMode_TRIANGLE_STRIP:
  238. case PrimitiveMode_TRIANGLE_FAN:
  239. aim->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  240. break;
  241. }
  242. Mesh::Primitive::Attributes& attr = prim.attributes;
  243. if (attr.position.size() > 0 && attr.position[0]) {
  244. aim->mNumVertices = attr.position[0]->count;
  245. attr.position[0]->ExtractData(aim->mVertices);
  246. }
  247. if (attr.normal.size() > 0 && attr.normal[0]) attr.normal[0]->ExtractData(aim->mNormals);
  248. for (size_t tc = 0; tc < attr.texcoord.size() && tc < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++tc) {
  249. attr.texcoord[tc]->ExtractData(aim->mTextureCoords[tc]);
  250. aim->mNumUVComponents[tc] = attr.texcoord[tc]->GetNumComponents();
  251. aiVector3D* values = aim->mTextureCoords[tc];
  252. for (unsigned int i = 0; i < aim->mNumVertices; ++i) {
  253. values[i].y = 1 - values[i].y; // Flip Y coords
  254. }
  255. }
  256. aiFace* faces = 0;
  257. unsigned int nFaces = 0;
  258. if (prim.indices) {
  259. unsigned int count = prim.indices->count;
  260. Accessor::Indexer data = prim.indices->GetIndexer();
  261. ai_assert(data.IsValid());
  262. switch (prim.mode) {
  263. case PrimitiveMode_POINTS: {
  264. nFaces = count;
  265. faces = new aiFace[nFaces];
  266. for (unsigned int i = 0; i < count; ++i) {
  267. SetFace(faces[i], data.GetUInt(i));
  268. }
  269. break;
  270. }
  271. case PrimitiveMode_LINES: {
  272. nFaces = count / 2;
  273. if (nFaces * 2 != count) {
  274. ASSIMP_LOG_WARN("The number of vertices was not compatible with the LINES mode. Some vertices were dropped.");
  275. count = nFaces * 2;
  276. }
  277. faces = new aiFace[nFaces];
  278. for (unsigned int i = 0; i < count; i += 2) {
  279. SetFace(faces[i / 2], data.GetUInt(i), data.GetUInt(i + 1));
  280. }
  281. break;
  282. }
  283. case PrimitiveMode_LINE_LOOP:
  284. case PrimitiveMode_LINE_STRIP: {
  285. nFaces = count - ((prim.mode == PrimitiveMode_LINE_STRIP) ? 1 : 0);
  286. faces = new aiFace[nFaces];
  287. SetFace(faces[0], data.GetUInt(0), data.GetUInt(1));
  288. for (unsigned int i = 2; i < count; ++i) {
  289. SetFace(faces[i - 1], faces[i - 2].mIndices[1], data.GetUInt(i));
  290. }
  291. if (prim.mode == PrimitiveMode_LINE_LOOP) { // close the loop
  292. SetFace(faces[count - 1], faces[count - 2].mIndices[1], faces[0].mIndices[0]);
  293. }
  294. break;
  295. }
  296. case PrimitiveMode_TRIANGLES: {
  297. nFaces = count / 3;
  298. if (nFaces * 3 != count) {
  299. ASSIMP_LOG_WARN("The number of vertices was not compatible with the TRIANGLES mode. Some vertices were dropped.");
  300. count = nFaces * 3;
  301. }
  302. faces = new aiFace[nFaces];
  303. for (unsigned int i = 0; i < count; i += 3) {
  304. SetFace(faces[i / 3], data.GetUInt(i), data.GetUInt(i + 1), data.GetUInt(i + 2));
  305. }
  306. break;
  307. }
  308. case PrimitiveMode_TRIANGLE_STRIP: {
  309. nFaces = count - 2;
  310. faces = new aiFace[nFaces];
  311. SetFace(faces[0], data.GetUInt(0), data.GetUInt(1), data.GetUInt(2));
  312. for (unsigned int i = 3; i < count; ++i) {
  313. SetFace(faces[i - 2], faces[i - 1].mIndices[1], faces[i - 1].mIndices[2], data.GetUInt(i));
  314. }
  315. break;
  316. }
  317. case PrimitiveMode_TRIANGLE_FAN:
  318. nFaces = count - 2;
  319. faces = new aiFace[nFaces];
  320. SetFace(faces[0], data.GetUInt(0), data.GetUInt(1), data.GetUInt(2));
  321. for (unsigned int i = 3; i < count; ++i) {
  322. SetFace(faces[i - 2], faces[0].mIndices[0], faces[i - 1].mIndices[2], data.GetUInt(i));
  323. }
  324. break;
  325. }
  326. }
  327. else { // no indices provided so directly generate from counts
  328. // use the already determined count as it includes checks
  329. unsigned int count = aim->mNumVertices;
  330. switch (prim.mode) {
  331. case PrimitiveMode_POINTS: {
  332. nFaces = count;
  333. faces = new aiFace[nFaces];
  334. for (unsigned int i = 0; i < count; ++i) {
  335. SetFace(faces[i], i);
  336. }
  337. break;
  338. }
  339. case PrimitiveMode_LINES: {
  340. nFaces = count / 2;
  341. if (nFaces * 2 != count) {
  342. ASSIMP_LOG_WARN("The number of vertices was not compatible with the LINES mode. Some vertices were dropped.");
  343. count = nFaces * 2;
  344. }
  345. faces = new aiFace[nFaces];
  346. for (unsigned int i = 0; i < count; i += 2) {
  347. SetFace(faces[i / 2], i, i + 1);
  348. }
  349. break;
  350. }
  351. case PrimitiveMode_LINE_LOOP:
  352. case PrimitiveMode_LINE_STRIP: {
  353. nFaces = count - ((prim.mode == PrimitiveMode_LINE_STRIP) ? 1 : 0);
  354. faces = new aiFace[nFaces];
  355. SetFace(faces[0], 0, 1);
  356. for (unsigned int i = 2; i < count; ++i) {
  357. SetFace(faces[i - 1], faces[i - 2].mIndices[1], i);
  358. }
  359. if (prim.mode == PrimitiveMode_LINE_LOOP) { // close the loop
  360. SetFace(faces[count - 1], faces[count - 2].mIndices[1], faces[0].mIndices[0]);
  361. }
  362. break;
  363. }
  364. case PrimitiveMode_TRIANGLES: {
  365. nFaces = count / 3;
  366. if (nFaces * 3 != count) {
  367. ASSIMP_LOG_WARN("The number of vertices was not compatible with the TRIANGLES mode. Some vertices were dropped.");
  368. count = nFaces * 3;
  369. }
  370. faces = new aiFace[nFaces];
  371. for (unsigned int i = 0; i < count; i += 3) {
  372. SetFace(faces[i / 3], i, i + 1, i + 2);
  373. }
  374. break;
  375. }
  376. case PrimitiveMode_TRIANGLE_STRIP: {
  377. nFaces = count - 2;
  378. faces = new aiFace[nFaces];
  379. SetFace(faces[0], 0, 1, 2);
  380. for (unsigned int i = 3; i < count; ++i) {
  381. SetFace(faces[i - 2], faces[i - 1].mIndices[1], faces[i - 1].mIndices[2], i);
  382. }
  383. break;
  384. }
  385. case PrimitiveMode_TRIANGLE_FAN:
  386. nFaces = count - 2;
  387. faces = new aiFace[nFaces];
  388. SetFace(faces[0], 0, 1, 2);
  389. for (unsigned int i = 3; i < count; ++i) {
  390. SetFace(faces[i - 2], faces[0].mIndices[0], faces[i - 1].mIndices[2], i);
  391. }
  392. break;
  393. }
  394. }
  395. if (faces) {
  396. aim->mFaces = faces;
  397. aim->mNumFaces = nFaces;
  398. ai_assert(CheckValidFacesIndices(faces, nFaces, aim->mNumVertices));
  399. }
  400. if (prim.material) {
  401. aim->mMaterialIndex = prim.material.GetIndex();
  402. }
  403. }
  404. }
  405. meshOffsets.push_back(k);
  406. CopyVector(meshes, mScene->mMeshes, mScene->mNumMeshes);
  407. }
  408. void glTFImporter::ImportCameras(glTF::Asset& r) {
  409. if (!r.cameras.Size()) {
  410. return;
  411. }
  412. mScene->mNumCameras = r.cameras.Size();
  413. mScene->mCameras = new aiCamera*[r.cameras.Size()];
  414. for (size_t i = 0; i < r.cameras.Size(); ++i) {
  415. Camera& cam = r.cameras[i];
  416. aiCamera* aicam = mScene->mCameras[i] = new aiCamera();
  417. if (cam.type == Camera::Perspective) {
  418. aicam->mAspect = cam.perspective.aspectRatio;
  419. aicam->mHorizontalFOV = cam.perspective.yfov * ((aicam->mAspect == 0.f) ? 1.f : aicam->mAspect);
  420. aicam->mClipPlaneFar = cam.perspective.zfar;
  421. aicam->mClipPlaneNear = cam.perspective.znear;
  422. } else {
  423. aicam->mClipPlaneFar = cam.ortographic.zfar;
  424. aicam->mClipPlaneNear = cam.ortographic.znear;
  425. aicam->mHorizontalFOV = 0.0;
  426. aicam->mAspect = 1.0f;
  427. if (0.f != cam.ortographic.ymag) {
  428. aicam->mAspect = cam.ortographic.xmag / cam.ortographic.ymag;
  429. }
  430. }
  431. }
  432. }
  433. void glTFImporter::ImportLights(glTF::Asset& r)
  434. {
  435. if (!r.lights.Size()) return;
  436. mScene->mNumLights = r.lights.Size();
  437. mScene->mLights = new aiLight*[r.lights.Size()];
  438. for (size_t i = 0; i < r.lights.Size(); ++i) {
  439. Light& l = r.lights[i];
  440. aiLight* ail = mScene->mLights[i] = new aiLight();
  441. switch (l.type) {
  442. case Light::Type_directional:
  443. ail->mType = aiLightSource_DIRECTIONAL; break;
  444. case Light::Type_spot:
  445. ail->mType = aiLightSource_SPOT; break;
  446. case Light::Type_ambient:
  447. ail->mType = aiLightSource_AMBIENT; break;
  448. default: // Light::Type_point
  449. ail->mType = aiLightSource_POINT; break;
  450. }
  451. CopyValue(l.color, ail->mColorAmbient);
  452. CopyValue(l.color, ail->mColorDiffuse);
  453. CopyValue(l.color, ail->mColorSpecular);
  454. ail->mAngleOuterCone = l.falloffAngle;
  455. ail->mAngleInnerCone = l.falloffExponent; // TODO fix this, it does not look right at all
  456. ail->mAttenuationConstant = l.constantAttenuation;
  457. ail->mAttenuationLinear = l.linearAttenuation;
  458. ail->mAttenuationQuadratic = l.quadraticAttenuation;
  459. }
  460. }
  461. aiNode* ImportNode(aiScene* pScene, glTF::Asset& r, std::vector<unsigned int>& meshOffsets, glTF::Ref<glTF::Node>& ptr)
  462. {
  463. Node& node = *ptr;
  464. aiNode* ainode = new aiNode(node.id);
  465. if (!node.children.empty()) {
  466. ainode->mNumChildren = unsigned(node.children.size());
  467. ainode->mChildren = new aiNode*[ainode->mNumChildren];
  468. for (unsigned int i = 0; i < ainode->mNumChildren; ++i) {
  469. aiNode* child = ImportNode(pScene, r, meshOffsets, node.children[i]);
  470. child->mParent = ainode;
  471. ainode->mChildren[i] = child;
  472. }
  473. }
  474. aiMatrix4x4& matrix = ainode->mTransformation;
  475. if (node.matrix.isPresent) {
  476. CopyValue(node.matrix.value, matrix);
  477. }
  478. else {
  479. if (node.translation.isPresent) {
  480. aiVector3D trans;
  481. CopyValue(node.translation.value, trans);
  482. aiMatrix4x4 t;
  483. aiMatrix4x4::Translation(trans, t);
  484. matrix = t * matrix;
  485. }
  486. if (node.scale.isPresent) {
  487. aiVector3D scal(1.f);
  488. CopyValue(node.scale.value, scal);
  489. aiMatrix4x4 s;
  490. aiMatrix4x4::Scaling(scal, s);
  491. matrix = s * matrix;
  492. }
  493. if (node.rotation.isPresent) {
  494. aiQuaternion rot;
  495. CopyValue(node.rotation.value, rot);
  496. matrix = aiMatrix4x4(rot.GetMatrix()) * matrix;
  497. }
  498. }
  499. if (!node.meshes.empty()) {
  500. int count = 0;
  501. for (size_t i = 0; i < node.meshes.size(); ++i) {
  502. int idx = node.meshes[i].GetIndex();
  503. count += meshOffsets[idx + 1] - meshOffsets[idx];
  504. }
  505. ainode->mNumMeshes = count;
  506. ainode->mMeshes = new unsigned int[count];
  507. int k = 0;
  508. for (size_t i = 0; i < node.meshes.size(); ++i) {
  509. int idx = node.meshes[i].GetIndex();
  510. for (unsigned int j = meshOffsets[idx]; j < meshOffsets[idx + 1]; ++j, ++k) {
  511. ainode->mMeshes[k] = j;
  512. }
  513. }
  514. }
  515. if (node.camera) {
  516. pScene->mCameras[node.camera.GetIndex()]->mName = ainode->mName;
  517. }
  518. if (node.light) {
  519. pScene->mLights[node.light.GetIndex()]->mName = ainode->mName;
  520. }
  521. return ainode;
  522. }
  523. void glTFImporter::ImportNodes(glTF::Asset& r)
  524. {
  525. if (!r.scene) return;
  526. std::vector< Ref<Node> > rootNodes = r.scene->nodes;
  527. // The root nodes
  528. unsigned int numRootNodes = unsigned(rootNodes.size());
  529. if (numRootNodes == 1) { // a single root node: use it
  530. mScene->mRootNode = ImportNode(mScene, r, meshOffsets, rootNodes[0]);
  531. }
  532. else if (numRootNodes > 1) { // more than one root node: create a fake root
  533. aiNode* root = new aiNode("ROOT");
  534. root->mChildren = new aiNode*[numRootNodes];
  535. for (unsigned int i = 0; i < numRootNodes; ++i) {
  536. aiNode* node = ImportNode(mScene, r, meshOffsets, rootNodes[i]);
  537. node->mParent = root;
  538. root->mChildren[root->mNumChildren++] = node;
  539. }
  540. mScene->mRootNode = root;
  541. }
  542. //if (!mScene->mRootNode) {
  543. // mScene->mRootNode = new aiNode("EMPTY");
  544. //}
  545. }
  546. void glTFImporter::ImportEmbeddedTextures(glTF::Asset& r)
  547. {
  548. embeddedTexIdxs.resize(r.images.Size(), -1);
  549. int numEmbeddedTexs = 0;
  550. for (size_t i = 0; i < r.images.Size(); ++i) {
  551. if (r.images[i].HasData())
  552. numEmbeddedTexs += 1;
  553. }
  554. if (numEmbeddedTexs == 0)
  555. return;
  556. mScene->mTextures = new aiTexture*[numEmbeddedTexs];
  557. // Add the embedded textures
  558. for (size_t i = 0; i < r.images.Size(); ++i) {
  559. Image &img = r.images[i];
  560. if (!img.HasData()) continue;
  561. int idx = mScene->mNumTextures++;
  562. embeddedTexIdxs[i] = idx;
  563. aiTexture* tex = mScene->mTextures[idx] = new aiTexture();
  564. size_t length = img.GetDataLength();
  565. void* data = img.StealData();
  566. tex->mFilename = img.name;
  567. tex->mWidth = static_cast<unsigned int>(length);
  568. tex->mHeight = 0;
  569. tex->pcData = reinterpret_cast<aiTexel*>(data);
  570. if (!img.mimeType.empty()) {
  571. const char* ext = strchr(img.mimeType.c_str(), '/') + 1;
  572. if (ext) {
  573. if (strcmp(ext, "jpeg") == 0) ext = "jpg";
  574. size_t len = strlen(ext);
  575. if (len <= 3) {
  576. strcpy(tex->achFormatHint, ext);
  577. }
  578. }
  579. }
  580. }
  581. }
  582. void glTFImporter::ImportCommonMetadata(glTF::Asset& a)
  583. {
  584. ai_assert(mScene->mMetaData == nullptr);
  585. const bool hasVersion = !a.asset.version.empty();
  586. const bool hasGenerator = !a.asset.generator.empty();
  587. const bool hasCopyright = !a.asset.copyright.empty();
  588. if (hasVersion || hasGenerator || hasCopyright)
  589. {
  590. mScene->mMetaData = new aiMetadata;
  591. if (hasVersion)
  592. {
  593. mScene->mMetaData->Add(AI_METADATA_SOURCE_FORMAT_VERSION, aiString(a.asset.version));
  594. }
  595. if (hasGenerator)
  596. {
  597. mScene->mMetaData->Add(AI_METADATA_SOURCE_GENERATOR, aiString(a.asset.generator));
  598. }
  599. if (hasCopyright)
  600. {
  601. mScene->mMetaData->Add(AI_METADATA_SOURCE_COPYRIGHT, aiString(a.asset.copyright));
  602. }
  603. }
  604. }
  605. void glTFImporter::InternReadFile(const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  606. {
  607. // clean all member arrays
  608. meshOffsets.clear();
  609. embeddedTexIdxs.clear();
  610. this->mScene = pScene;
  611. // read the asset file
  612. glTF::Asset asset(pIOHandler);
  613. asset.Load(pFile, GetExtension(pFile) == "glb");
  614. //
  615. // Copy the data out
  616. //
  617. ImportEmbeddedTextures(asset);
  618. ImportMaterials(asset);
  619. ImportMeshes(asset);
  620. ImportCameras(asset);
  621. ImportLights(asset);
  622. ImportNodes(asset);
  623. ImportCommonMetadata(asset);
  624. if (pScene->mNumMeshes == 0) {
  625. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  626. }
  627. }
  628. #endif // ASSIMP_BUILD_NO_GLTF_IMPORTER