glTFImporter.cpp 26 KB

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