257ba321495289e3b6ef772ff4339f9d42a6c5d4
[platform/core/uifw/dali-toolkit.git] / dali-scene3d / public-api / loader / gltf2-loader.cpp
1 /*
2  * Copyright (c) 2022 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // FILE HEADER
19 #include <dali-scene3d/public-api/loader/gltf2-loader.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/integration-api/debug.h>
23 #include <dali/public-api/images/image-operations.h>
24 #include <dali/public-api/math/quaternion.h>
25 #include <fstream>
26
27 // INTERNAL INCLUDES
28 #include <dali-scene3d/internal/loader/gltf2-asset.h>
29 #include <dali-scene3d/public-api/loader/load-result.h>
30 #include <dali-scene3d/public-api/loader/resource-bundle.h>
31 #include <dali-scene3d/public-api/loader/scene-definition.h>
32 #include <dali-scene3d/public-api/loader/shader-definition-factory.h>
33 #include <dali-scene3d/public-api/loader/utils.h>
34
35 namespace gt = gltf2;
36 namespace js = json;
37
38 namespace Dali
39 {
40 namespace Scene3D
41 {
42 namespace Loader
43 {
44 namespace
45 {
46 const std::string POSITION_PROPERTY("position");
47 const std::string ORIENTATION_PROPERTY("orientation");
48 const std::string SCALE_PROPERTY("scale");
49 const std::string BLEND_SHAPE_WEIGHTS_UNIFORM("uBlendShapeWeight");
50 const std::string MRENDERER_MODEL_IDENTIFICATION("M-Renderer");
51 const std::string ROOT_NODE_NAME("RootNode");
52 const Vector3     SCALE_TO_ADJUST(100.0f, 100.0f, 100.0f);
53
54 const Geometry::Type GLTF2_TO_DALI_PRIMITIVES[]{
55   Geometry::POINTS,
56   Geometry::LINES,
57   Geometry::LINE_LOOP,
58   Geometry::LINE_STRIP,
59   Geometry::TRIANGLES,
60   Geometry::TRIANGLE_STRIP,
61   Geometry::TRIANGLE_FAN}; //...because Dali swaps the last two.
62
63 struct AttributeMapping
64 {
65   gt::Attribute::Type      mType;
66   MeshDefinition::Accessor MeshDefinition::*mAccessor;
67   uint16_t                                  mElementSizeRequired;
68 } ATTRIBUTE_MAPPINGS[]{
69   {gt::Attribute::NORMAL, &MeshDefinition::mNormals, sizeof(Vector3)},
70   {gt::Attribute::TANGENT, &MeshDefinition::mTangents, sizeof(Vector3)},
71   {gt::Attribute::TEXCOORD_0, &MeshDefinition::mTexCoords, sizeof(Vector2)},
72   {gt::Attribute::COLOR_0, &MeshDefinition::mColors, sizeof(Vector4)},
73   {gt::Attribute::JOINTS_0, &MeshDefinition::mJoints0, sizeof(Vector4)},
74   {gt::Attribute::WEIGHTS_0, &MeshDefinition::mWeights0, sizeof(Vector4)},
75 };
76
77 std::vector<gt::Animation> ReadAnimationArray(const json_value_s& j)
78 {
79   gt::Animation proxy;
80   SetRefReaderObject(proxy);
81
82   auto results = js::Read::Array<gt::Animation, js::ObjectReader<gt::Animation>::Read>(j);
83
84   for(auto& animation : results)
85   {
86     for(auto& channel : animation.mChannels)
87     {
88       channel.mSampler.UpdateVector(animation.mSamplers);
89     }
90   }
91
92   return results;
93 }
94
95 void ApplyAccessorMinMax(const gt::Accessor& acc, float* values)
96 {
97   DALI_ASSERT_ALWAYS(acc.mMax.empty() || gt::AccessorType::ElementCount(acc.mType) == acc.mMax.size());
98   DALI_ASSERT_ALWAYS(acc.mMin.empty() || gt::AccessorType::ElementCount(acc.mType) == acc.mMin.size());
99   MeshDefinition::Blob::ApplyMinMax(acc.mMin, acc.mMax, acc.mCount, values);
100 }
101
102 const auto BUFFER_READER = std::move(js::Reader<gt::Buffer>()
103                                        .Register(*js::MakeProperty("byteLength", js::Read::Number<uint32_t>, &gt::Buffer::mByteLength))
104                                        .Register(*js::MakeProperty("uri", js::Read::StringView, &gt::Buffer::mUri)));
105
106 const auto BUFFER_VIEW_READER = std::move(js::Reader<gt::BufferView>()
107                                             .Register(*js::MakeProperty("buffer", gt::RefReader<gt::Document>::Read<gt::Buffer, &gt::Document::mBuffers>, &gt::BufferView::mBuffer))
108                                             .Register(*js::MakeProperty("byteOffset", js::Read::Number<uint32_t>, &gt::BufferView::mByteOffset))
109                                             .Register(*js::MakeProperty("byteLength", js::Read::Number<uint32_t>, &gt::BufferView::mByteLength))
110                                             .Register(*js::MakeProperty("byteStride", js::Read::Number<uint32_t>, &gt::BufferView::mByteStride))
111                                             .Register(*js::MakeProperty("target", js::Read::Number<uint32_t>, &gt::BufferView::mTarget)));
112
113 const auto BUFFER_VIEW_CLIENT_READER = std::move(js::Reader<gt::BufferViewClient>()
114                                                    .Register(*js::MakeProperty("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, &gt::Document::mBufferViews>, &gt::BufferViewClient::mBufferView))
115                                                    .Register(*js::MakeProperty("byteOffset", js::Read::Number<uint32_t>, &gt::BufferViewClient::mByteOffset)));
116
117 const auto COMPONENT_TYPED_BUFFER_VIEW_CLIENT_READER = std::move(js::Reader<gt::ComponentTypedBufferViewClient>()
118                                                                    .Register(*new js::Property<gt::ComponentTypedBufferViewClient, gt::Ref<gt::BufferView>>("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, &gt::Document::mBufferViews>, &gt::ComponentTypedBufferViewClient::mBufferView))
119                                                                    .Register(*new js::Property<gt::ComponentTypedBufferViewClient, uint32_t>("byteOffset", js::Read::Number<uint32_t>, &gt::ComponentTypedBufferViewClient::mByteOffset))
120                                                                    .Register(*js::MakeProperty("componentType", js::Read::Enum<gt::Component::Type>, &gt::ComponentTypedBufferViewClient::mComponentType)));
121
122 const auto ACCESSOR_SPARSE_READER = std::move(js::Reader<gt::Accessor::Sparse>()
123                                                 .Register(*js::MakeProperty("count", js::Read::Number<uint32_t>, &gt::Accessor::Sparse::mCount))
124                                                 .Register(*js::MakeProperty("indices", js::ObjectReader<gt::ComponentTypedBufferViewClient>::Read, &gt::Accessor::Sparse::mIndices))
125                                                 .Register(*js::MakeProperty("values", js::ObjectReader<gt::BufferViewClient>::Read, &gt::Accessor::Sparse::mValues)));
126
127 const auto ACCESSOR_READER = std::move(js::Reader<gt::Accessor>()
128                                          .Register(*new js::Property<gt::Accessor, gt::Ref<gt::BufferView>>("bufferView",
129                                                                                                             gt::RefReader<gt::Document>::Read<gt::BufferView, &gt::Document::mBufferViews>,
130                                                                                                             &gt::Accessor::mBufferView))
131                                          .Register(*new js::Property<gt::Accessor, uint32_t>("byteOffset",
132                                                                                              js::Read::Number<uint32_t>,
133                                                                                              &gt::Accessor::mByteOffset))
134                                          .Register(*new js::Property<gt::Accessor, gt::Component::Type>("componentType",
135                                                                                                         js::Read::Enum<gt::Component::Type>,
136                                                                                                         &gt::Accessor::mComponentType))
137                                          .Register(*new js::Property<gt::Accessor, std::string_view>("name", js::Read::StringView, &gt::Accessor::mName))
138                                          .Register(*js::MakeProperty("count", js::Read::Number<uint32_t>, &gt::Accessor::mCount))
139                                          .Register(*js::MakeProperty("normalized", js::Read::Boolean, &gt::Accessor::mNormalized))
140                                          .Register(*js::MakeProperty("type", gt::ReadStringEnum<gt::AccessorType>, &gt::Accessor::mType))
141                                          .Register(*js::MakeProperty("min", js::Read::Array<float, js::Read::Number>, &gt::Accessor::mMin))
142                                          .Register(*js::MakeProperty("max", js::Read::Array<float, js::Read::Number>, &gt::Accessor::mMax))
143                                          .Register(*new js::Property<gt::Accessor, gt::Accessor::Sparse>("sparse", js::ObjectReader<gt::Accessor::Sparse>::Read, &gt::Accessor::SetSparse)));
144
145 const auto IMAGE_READER = std::move(js::Reader<gt::Image>()
146                                       .Register(*new js::Property<gt::Image, std::string_view>("name", js::Read::StringView, &gt::Material::mName))
147                                       .Register(*js::MakeProperty("uri", js::Read::StringView, &gt::Image::mUri))
148                                       .Register(*js::MakeProperty("mimeType", js::Read::StringView, &gt::Image::mMimeType))
149                                       .Register(*js::MakeProperty("bufferView", gt::RefReader<gt::Document>::Read<gt::BufferView, &gt::Document::mBufferViews>, &gt::Image::mBufferView)));
150
151 const auto SAMPLER_READER = std::move(js::Reader<gt::Sampler>()
152                                         .Register(*js::MakeProperty("minFilter", js::Read::Enum<gt::Filter::Type>, &gt::Sampler::mMinFilter))
153                                         .Register(*js::MakeProperty("magFilter", js::Read::Enum<gt::Filter::Type>, &gt::Sampler::mMagFilter))
154                                         .Register(*js::MakeProperty("wrapS", js::Read::Enum<gt::Wrap::Type>, &gt::Sampler::mWrapS))
155                                         .Register(*js::MakeProperty("wrapT", js::Read::Enum<gt::Wrap::Type>, &gt::Sampler::mWrapT)));
156
157 const auto TEXURE_READER = std::move(js::Reader<gt::Texture>()
158                                        .Register(*js::MakeProperty("source", gt::RefReader<gt::Document>::Read<gt::Image, &gt::Document::mImages>, &gt::Texture::mSource))
159                                        .Register(*js::MakeProperty("sampler", gt::RefReader<gt::Document>::Read<gt::Sampler, &gt::Document::mSamplers>, &gt::Texture::mSampler)));
160
161 const auto TEXURE_INFO_READER = std::move(js::Reader<gt::TextureInfo>()
162                                             .Register(*js::MakeProperty("index", gt::RefReader<gt::Document>::Read<gt::Texture, &gt::Document::mTextures>, &gt::TextureInfo::mTexture))
163                                             .Register(*js::MakeProperty("texCoord", js::Read::Number<uint32_t>, &gt::TextureInfo::mTexCoord))
164                                             .Register(*js::MakeProperty("scale", js::Read::Number<float>, &gt::TextureInfo::mScale))
165                                             .Register(*js::MakeProperty("strength", js::Read::Number<float>, &gt::TextureInfo::mStrength)));
166
167 const auto MATERIAL_PBR_READER = std::move(js::Reader<gt::Material::Pbr>()
168                                              .Register(*js::MakeProperty("baseColorFactor", gt::ReadDaliVector<Vector4>, &gt::Material::Pbr::mBaseColorFactor))
169                                              .Register(*js::MakeProperty("baseColorTexture", js::ObjectReader<gt::TextureInfo>::Read, &gt::Material::Pbr::mBaseColorTexture))
170                                              .Register(*js::MakeProperty("metallicFactor", js::Read::Number<float>, &gt::Material::Pbr::mMetallicFactor))
171                                              .Register(*js::MakeProperty("roughnessFactor", js::Read::Number<float>, &gt::Material::Pbr::mRoughnessFactor))
172                                              .Register(*js::MakeProperty("metallicRoughnessTexture", js::ObjectReader<gt::TextureInfo>::Read, &gt::Material::Pbr::mMetallicRoughnessTexture)));
173
174 const auto MATERIAL_SPECULAR_READER = std::move(js::Reader<gt::MaterialSpecular>()
175                                                   .Register(*js::MakeProperty("specularFactor", js::Read::Number<float>, &gt::MaterialSpecular::mSpecularFactor))
176                                                   .Register(*js::MakeProperty("specularTexture", js::ObjectReader<gt::TextureInfo>::Read, &gt::MaterialSpecular::mSpecularTexture))
177                                                   .Register(*js::MakeProperty("specularColorFactor", gt::ReadDaliVector<Vector3>, &gt::MaterialSpecular::mSpecularColorFactor))
178                                                   .Register(*js::MakeProperty("specularColorTexture", js::ObjectReader<gt::TextureInfo>::Read, &gt::MaterialSpecular::mSpecularColorTexture)));
179
180 const auto MATERIAL_IOR_READER = std::move(js::Reader<gt::MaterialIor>()
181                                              .Register(*js::MakeProperty("ior", js::Read::Number<float>, &gt::MaterialIor::mIor)));
182
183 const auto MATERIAL_EXTENSION_READER = std::move(js::Reader<gt::MaterialExtensions>()
184                                                    .Register(*js::MakeProperty("KHR_materials_ior", js::ObjectReader<gt::MaterialIor>::Read, &gt::MaterialExtensions::mMaterialIor))
185                                                    .Register(*js::MakeProperty("KHR_materials_specular", js::ObjectReader<gt::MaterialSpecular>::Read, &gt::MaterialExtensions::mMaterialSpecular)));
186
187 const auto MATERIAL_READER = std::move(js::Reader<gt::Material>()
188                                          .Register(*new js::Property<gt::Material, std::string_view>("name", js::Read::StringView, &gt::Material::mName))
189                                          .Register(*js::MakeProperty("pbrMetallicRoughness", js::ObjectReader<gt::Material::Pbr>::Read, &gt::Material::mPbrMetallicRoughness))
190                                          .Register(*js::MakeProperty("normalTexture", js::ObjectReader<gt::TextureInfo>::Read, &gt::Material::mNormalTexture))
191                                          .Register(*js::MakeProperty("occlusionTexture", js::ObjectReader<gt::TextureInfo>::Read, &gt::Material::mOcclusionTexture))
192                                          .Register(*js::MakeProperty("emissiveTexture", js::ObjectReader<gt::TextureInfo>::Read, &gt::Material::mEmissiveTexture))
193                                          .Register(*js::MakeProperty("emissiveFactor", gt::ReadDaliVector<Vector3>, &gt::Material::mEmissiveFactor))
194                                          .Register(*js::MakeProperty("alphaMode", gt::ReadStringEnum<gt::AlphaMode>, &gt::Material::mAlphaMode))
195                                          .Register(*js::MakeProperty("alphaCutoff", js::Read::Number<float>, &gt::Material::mAlphaCutoff))
196                                          .Register(*js::MakeProperty("doubleSided", js::Read::Boolean, &gt::Material::mDoubleSided))
197                                          .Register(*js::MakeProperty("extensions", js::ObjectReader<gt::MaterialExtensions>::Read, &gt::Material::mMaterialExtensions)));
198
199 std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>> ReadMeshPrimitiveAttributes(const json_value_s& j)
200 {
201   auto&                                                jo = js::Cast<json_object_s>(j);
202   std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>> result;
203
204   auto i = jo.start;
205   while(i)
206   {
207     auto jstr                                                        = *i->name;
208     result[gt::Attribute::FromString(jstr.string, jstr.string_size)] = gt::RefReader<gt::Document>::Read<gt::Accessor, &gt::Document::mAccessors>(*i->value);
209     i                                                                = i->next;
210   }
211   return result;
212 }
213
214 std::vector<std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>>> ReadMeshPrimitiveTargets(const json_value_s& j)
215 {
216   auto&                                                             jo = js::Cast<json_array_s>(j);
217   std::vector<std::map<gt::Attribute::Type, gt::Ref<gt::Accessor>>> result;
218
219   result.reserve(jo.length);
220
221   auto i = jo.start;
222   while(i)
223   {
224     result.push_back(std::move(ReadMeshPrimitiveAttributes(*i->value)));
225     i = i->next;
226   }
227
228   return result;
229 }
230
231 const auto MESH_PRIMITIVE_READER = std::move(js::Reader<gt::Mesh::Primitive>()
232                                                .Register(*js::MakeProperty("attributes", ReadMeshPrimitiveAttributes, &gt::Mesh::Primitive::mAttributes))
233                                                .Register(*js::MakeProperty("indices", gt::RefReader<gt::Document>::Read<gt::Accessor, &gt::Document::mAccessors>, &gt::Mesh::Primitive::mIndices))
234                                                .Register(*js::MakeProperty("material", gt::RefReader<gt::Document>::Read<gt::Material, &gt::Document::mMaterials>, &gt::Mesh::Primitive::mMaterial))
235                                                .Register(*js::MakeProperty("mode", js::Read::Enum<gt::Mesh::Primitive::Mode>, &gt::Mesh::Primitive::mMode))
236                                                .Register(*js::MakeProperty("targets", ReadMeshPrimitiveTargets, &gt::Mesh::Primitive::mTargets)));
237
238 const auto MESH_READER = std::move(js::Reader<gt::Mesh>()
239                                      .Register(*new js::Property<gt::Mesh, std::string_view>("name", js::Read::StringView, &gt::Mesh::mName))
240                                      .Register(*js::MakeProperty("primitives",
241                                                                  js::Read::Array<gt::Mesh::Primitive, js::ObjectReader<gt::Mesh::Primitive>::Read>,
242                                                                  &gt::Mesh::mPrimitives))
243                                      .Register(*js::MakeProperty("weights", js::Read::Array<float, js::Read::Number>, &gt::Mesh::mWeights)));
244
245 const auto SKIN_READER = std::move(js::Reader<gt::Skin>()
246                                      .Register(*new js::Property<gt::Skin, std::string_view>("name", js::Read::StringView, &gt::Skin::mName))
247                                      .Register(*js::MakeProperty("inverseBindMatrices",
248                                                                  gt::RefReader<gt::Document>::Read<gt::Accessor, &gt::Document::mAccessors>,
249                                                                  &gt::Skin::mInverseBindMatrices))
250                                      .Register(*js::MakeProperty("skeleton",
251                                                                  gt::RefReader<gt::Document>::Read<gt::Node, &gt::Document::mNodes>,
252                                                                  &gt::Skin::mSkeleton))
253                                      .Register(*js::MakeProperty("joints",
254                                                                  js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, &gt::Document::mNodes>>,
255                                                                  &gt::Skin::mJoints)));
256
257 const auto CAMERA_PERSPECTIVE_READER = std::move(js::Reader<gt::Camera::Perspective>()
258                                                    .Register(*js::MakeProperty("aspectRatio", js::Read::Number<float>, &gt::Camera::Perspective::mAspectRatio))
259                                                    .Register(*js::MakeProperty("yfov", js::Read::Number<float>, &gt::Camera::Perspective::mYFov))
260                                                    .Register(*js::MakeProperty("zfar", js::Read::Number<float>, &gt::Camera::Perspective::mZFar))
261                                                    .Register(*js::MakeProperty("znear", js::Read::Number<float>, &gt::Camera::Perspective::mZNear))); // TODO: infinite perspective projection, where znear is omitted
262
263 const auto CAMERA_ORTHOGRAPHIC_READER = std::move(js::Reader<gt::Camera::Orthographic>()
264                                                     .Register(*js::MakeProperty("xmag", js::Read::Number<float>, &gt::Camera::Orthographic::mXMag))
265                                                     .Register(*js::MakeProperty("ymag", js::Read::Number<float>, &gt::Camera::Orthographic::mXMag))
266                                                     .Register(*js::MakeProperty("zfar", js::Read::Number<float>, &gt::Camera::Orthographic::mZFar))
267                                                     .Register(*js::MakeProperty("znear", js::Read::Number<float>, &gt::Camera::Orthographic::mZNear)));
268
269 const auto CAMERA_READER = std::move(js::Reader<gt::Camera>()
270                                        .Register(*new js::Property<gt::Camera, std::string_view>("name", js::Read::StringView, &gt::Camera::mName))
271                                        .Register(*js::MakeProperty("type", js::Read::StringView, &gt::Camera::mType))
272                                        .Register(*js::MakeProperty("perspective", js::ObjectReader<gt::Camera::Perspective>::Read, &gt::Camera::mPerspective))
273                                        .Register(*js::MakeProperty("orthographic", js::ObjectReader<gt::Camera::Orthographic>::Read, &gt::Camera::mOrthographic)));
274
275 const auto NODE_READER = std::move(js::Reader<gt::Node>()
276                                      .Register(*new js::Property<gt::Node, std::string_view>("name", js::Read::StringView, &gt::Node::mName))
277                                      .Register(*js::MakeProperty("translation", gt::ReadDaliVector<Vector3>, &gt::Node::mTranslation))
278                                      .Register(*js::MakeProperty("rotation", gt::ReadQuaternion, &gt::Node::mRotation))
279                                      .Register(*js::MakeProperty("scale", gt::ReadDaliVector<Vector3>, &gt::Node::mScale))
280                                      .Register(*new js::Property<gt::Node, Matrix>("matrix", gt::ReadDaliVector<Matrix>, &gt::Node::SetMatrix))
281                                      .Register(*js::MakeProperty("camera", gt::RefReader<gt::Document>::Read<gt::Camera, &gt::Document::mCameras>, &gt::Node::mCamera))
282                                      .Register(*js::MakeProperty("children", js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, &gt::Document::mNodes>>, &gt::Node::mChildren))
283                                      .Register(*js::MakeProperty("mesh", gt::RefReader<gt::Document>::Read<gt::Mesh, &gt::Document::mMeshes>, &gt::Node::mMesh))
284                                      .Register(*js::MakeProperty("skin", gt::RefReader<gt::Document>::Read<gt::Skin, &gt::Document::mSkins>, &gt::Node::mSkin)));
285
286 const auto ANIMATION_SAMPLER_READER = std::move(js::Reader<gt::Animation::Sampler>()
287                                                   .Register(*js::MakeProperty("input", gt::RefReader<gt::Document>::Read<gt::Accessor, &gt::Document::mAccessors>, &gt::Animation::Sampler::mInput))
288                                                   .Register(*js::MakeProperty("output", gt::RefReader<gt::Document>::Read<gt::Accessor, &gt::Document::mAccessors>, &gt::Animation::Sampler::mOutput))
289                                                   .Register(*js::MakeProperty("interpolation", gt::ReadStringEnum<gt::Animation::Sampler::Interpolation>, &gt::Animation::Sampler::mInterpolation)));
290
291 const auto ANIMATION_TARGET_READER = std::move(js::Reader<gt::Animation::Channel::Target>()
292                                                  .Register(*js::MakeProperty("node", gt::RefReader<gt::Document>::Read<gt::Node, &gt::Document::mNodes>, &gt::Animation::Channel::Target::mNode))
293                                                  .Register(*js::MakeProperty("path", gt::ReadStringEnum<gt::Animation::Channel::Target>, &gt::Animation::Channel::Target::mPath)));
294
295 const auto ANIMATION_CHANNEL_READER = std::move(js::Reader<gt::Animation::Channel>()
296                                                   .Register(*js::MakeProperty("target", js::ObjectReader<gt::Animation::Channel::Target>::Read, &gt::Animation::Channel::mTarget))
297                                                   .Register(*js::MakeProperty("sampler", gt::RefReader<gt::Animation>::Read<gt::Animation::Sampler, &gt::Animation::mSamplers>, &gt::Animation::Channel::mSampler)));
298
299 const auto ANIMATION_READER = std::move(js::Reader<gt::Animation>()
300                                           .Register(*new js::Property<gt::Animation, std::string_view>("name", js::Read::StringView, &gt::Animation::mName))
301                                           .Register(*js::MakeProperty("samplers",
302                                                                       js::Read::Array<gt::Animation::Sampler, js::ObjectReader<gt::Animation::Sampler>::Read>,
303                                                                       &gt::Animation::mSamplers))
304                                           .Register(*js::MakeProperty("channels",
305                                                                       js::Read::Array<gt::Animation::Channel, js::ObjectReader<gt::Animation::Channel>::Read>,
306                                                                       &gt::Animation::mChannels)));
307
308 const auto SCENE_READER = std::move(js::Reader<gt::Scene>()
309                                       .Register(*new js::Property<gt::Scene, std::string_view>("name", js::Read::StringView, &gt::Scene::mName))
310                                       .Register(*js::MakeProperty("nodes",
311                                                                   js::Read::Array<gt::Ref<gt::Node>, gt::RefReader<gt::Document>::Read<gt::Node, &gt::Document::mNodes>>,
312                                                                   &gt::Scene::mNodes)));
313
314 const auto DOCUMENT_READER = std::move(js::Reader<gt::Document>()
315                                          .Register(*js::MakeProperty("buffers",
316                                                                      js::Read::Array<gt::Buffer, js::ObjectReader<gt::Buffer>::Read>,
317                                                                      &gt::Document::mBuffers))
318                                          .Register(*js::MakeProperty("bufferViews",
319                                                                      js::Read::Array<gt::BufferView, js::ObjectReader<gt::BufferView>::Read>,
320                                                                      &gt::Document::mBufferViews))
321                                          .Register(*js::MakeProperty("accessors",
322                                                                      js::Read::Array<gt::Accessor, js::ObjectReader<gt::Accessor>::Read>,
323                                                                      &gt::Document::mAccessors))
324                                          .Register(*js::MakeProperty("images",
325                                                                      js::Read::Array<gt::Image, js::ObjectReader<gt::Image>::Read>,
326                                                                      &gt::Document::mImages))
327                                          .Register(*js::MakeProperty("samplers",
328                                                                      js::Read::Array<gt::Sampler, js::ObjectReader<gt::Sampler>::Read>,
329                                                                      &gt::Document::mSamplers))
330                                          .Register(*js::MakeProperty("textures",
331                                                                      js::Read::Array<gt::Texture, js::ObjectReader<gt::Texture>::Read>,
332                                                                      &gt::Document::mTextures))
333                                          .Register(*js::MakeProperty("materials",
334                                                                      js::Read::Array<gt::Material, js::ObjectReader<gt::Material>::Read>,
335                                                                      &gt::Document::mMaterials))
336                                          .Register(*js::MakeProperty("meshes",
337                                                                      js::Read::Array<gt::Mesh, js::ObjectReader<gt::Mesh>::Read>,
338                                                                      &gt::Document::mMeshes))
339                                          .Register(*js::MakeProperty("skins",
340                                                                      js::Read::Array<gt::Skin, js::ObjectReader<gt::Skin>::Read>,
341                                                                      &gt::Document::mSkins))
342                                          .Register(*js::MakeProperty("cameras",
343                                                                      js::Read::Array<gt::Camera, js::ObjectReader<gt::Camera>::Read>,
344                                                                      &gt::Document::mCameras))
345                                          .Register(*js::MakeProperty("nodes",
346                                                                      js::Read::Array<gt::Node, js::ObjectReader<gt::Node>::Read>,
347                                                                      &gt::Document::mNodes))
348                                          .Register(*js::MakeProperty("animations",
349                                                                      ReadAnimationArray,
350                                                                      &gt::Document::mAnimations))
351                                          .Register(*js::MakeProperty("scenes",
352                                                                      js::Read::Array<gt::Scene, js::ObjectReader<gt::Scene>::Read>,
353                                                                      &gt::Document::mScenes))
354                                          .Register(*js::MakeProperty("scene", gt::RefReader<gt::Document>::Read<gt::Scene, &gt::Document::mScenes>, &gt::Document::mScene)));
355
356 struct NodeMapping
357 {
358   Index gltfIdx;
359   Index runtimeIdx;
360 };
361
362 bool operator<(const NodeMapping& mapping, Index gltfIdx)
363 {
364   return mapping.gltfIdx < gltfIdx;
365 }
366
367 class NodeIndexMapper
368 {
369 public:
370   NodeIndexMapper()                       = default;
371   NodeIndexMapper(const NodeIndexMapper&) = delete;
372   NodeIndexMapper& operator=(const NodeIndexMapper&) = delete;
373
374   ///@brief Registers a mapping of the @a gltfIdx of a node to its @a runtimeIdx .
375   ///@note If the indices are the same, the registration is omitted, in order to
376   /// save growing a vector.
377   void RegisterMapping(Index gltfIdx, Index runtimeIdx)
378   {
379     if(gltfIdx != runtimeIdx)
380     {
381       auto iInsert = std::lower_bound(mNodes.begin(), mNodes.end(), gltfIdx);
382       DALI_ASSERT_DEBUG(iInsert == mNodes.end() || iInsert->gltfIdx != gltfIdx);
383       mNodes.insert(iInsert, NodeMapping{gltfIdx, runtimeIdx});
384     }
385   }
386
387   ///@brief Retrieves the runtime index of a Node, mapped to the given @a gltfIdx.
388   Index GetRuntimeId(Index gltfIdx) const
389   {
390     auto iFind = std::lower_bound(mNodes.begin(), mNodes.end(), gltfIdx); // using custom operator<
391     return (iFind != mNodes.end() && iFind->gltfIdx == gltfIdx) ? iFind->runtimeIdx : gltfIdx;
392   }
393
394 private:
395   std::vector<NodeMapping> mNodes;
396 };
397
398 struct ConversionContext
399 {
400   LoadResult& mOutput;
401
402   std::string mPath;
403   Index       mDefaultMaterial;
404
405   std::vector<Index> mMeshIds;
406   NodeIndexMapper    mNodeIndices;
407 };
408
409 SamplerFlags::Type ConvertWrapMode(gt::Wrap::Type w)
410 {
411   switch(w)
412   {
413     case gt::Wrap::REPEAT:
414       return SamplerFlags::WRAP_REPEAT;
415     case gt::Wrap::CLAMP_TO_EDGE:
416       return SamplerFlags::WRAP_CLAMP;
417     case gt::Wrap::MIRRORED_REPEAT:
418       return SamplerFlags::WRAP_MIRROR;
419     default:
420       throw std::runtime_error("Invalid wrap type.");
421   }
422 }
423
424 SamplerFlags::Type ConvertSampler(const gt::Ref<gt::Sampler>& s)
425 {
426   if(s)
427   {
428     return ((s->mMinFilter < gt::Filter::NEAREST_MIPMAP_NEAREST) ? (s->mMinFilter - gt::Filter::NEAREST) : ((s->mMinFilter - gt::Filter::NEAREST_MIPMAP_NEAREST) + 2)) | 
429            ((s->mMagFilter - gt::Filter::NEAREST) << SamplerFlags::FILTER_MAG_SHIFT) | 
430            (ConvertWrapMode(s->mWrapS) << SamplerFlags::WRAP_S_SHIFT) | 
431            (ConvertWrapMode(s->mWrapT) << SamplerFlags::WRAP_T_SHIFT);
432   }
433   else
434   {
435     // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#texturesampler
436     // "The index of the sampler used by this texture. When undefined, a sampler with repeat wrapping and auto filtering should be used."
437     // "What is an auto filtering", I hear you ask. Since there's nothing else to determine mipmapping from - including glTF image
438     // properties, if not in some extension -, we will simply assume linear filtering.
439     return SamplerFlags::FILTER_LINEAR | (SamplerFlags::FILTER_LINEAR << SamplerFlags::FILTER_MAG_SHIFT) |
440            (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_S_SHIFT) | (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_T_SHIFT);
441   }
442 }
443
444 TextureDefinition ConvertTextureInfo(const gt::TextureInfo& mm, const ImageMetadata& metaData = ImageMetadata())
445 {
446   return TextureDefinition{std::string(mm.mTexture->mSource->mUri), ConvertSampler(mm.mTexture->mSampler), metaData.mMinSize, metaData.mSamplingMode};
447 }
448
449 void ConvertMaterial(const gt::Material& material, const std::unordered_map<std::string, ImageMetadata>& imageMetaData, decltype(ResourceBundle::mMaterials)& outMaterials)
450 {
451   auto getTextureMetaData = [](const std::unordered_map<std::string, ImageMetadata>& metaData, const gt::TextureInfo& info) {
452     if(auto search = metaData.find(info.mTexture->mSource->mUri.data()); search != metaData.end())
453     {
454       return search->second;
455     }
456     else
457     {
458       return ImageMetadata();
459     }
460   };
461
462   MaterialDefinition matDef;
463
464   auto& pbr = material.mPbrMetallicRoughness;
465   if(material.mAlphaMode == gt::AlphaMode::BLEND)
466   {
467     matDef.mIsOpaque = false;
468     matDef.mFlags |= MaterialDefinition::TRANSPARENCY;
469   }
470   else if(material.mAlphaMode == gt::AlphaMode::MASK)
471   {
472     matDef.mIsMask = true;
473     matDef.SetAlphaCutoff(std::min(1.f, std::max(0.f, material.mAlphaCutoff)));
474   }
475
476   matDef.mBaseColorFactor = pbr.mBaseColorFactor;
477
478   matDef.mTextureStages.reserve(!!pbr.mBaseColorTexture + !!pbr.mMetallicRoughnessTexture + !!material.mNormalTexture + !!material.mOcclusionTexture + !!material.mEmissiveTexture);
479   if(pbr.mBaseColorTexture)
480   {
481     const auto semantic = MaterialDefinition::ALBEDO;
482     matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(pbr.mBaseColorTexture, getTextureMetaData(imageMetaData, pbr.mBaseColorTexture))});
483     // TODO: and there had better be one
484     matDef.mFlags |= semantic;
485   }
486   else
487   {
488     matDef.mNeedAlbedoTexture = false;
489   }
490
491   matDef.mMetallic  = pbr.mMetallicFactor;
492   matDef.mRoughness = pbr.mRoughnessFactor;
493
494   if(pbr.mMetallicRoughnessTexture)
495   {
496     const auto semantic = MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS |
497                           MaterialDefinition::GLTF_CHANNELS;
498     matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(pbr.mMetallicRoughnessTexture, getTextureMetaData(imageMetaData, pbr.mMetallicRoughnessTexture))});
499     // TODO: and there had better be one
500     matDef.mFlags |= semantic;
501   }
502   else
503   {
504     matDef.mNeedMetallicRoughnessTexture = false;
505   }
506
507   matDef.mNormalScale = material.mNormalTexture.mScale;
508   if(material.mNormalTexture)
509   {
510     const auto semantic = MaterialDefinition::NORMAL;
511     matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(material.mNormalTexture, getTextureMetaData(imageMetaData, material.mNormalTexture))});
512     // TODO: and there had better be one
513     matDef.mFlags |= semantic;
514   }
515   else
516   {
517     matDef.mNeedNormalTexture = false;
518   }
519
520   if(material.mOcclusionTexture)
521   {
522     const auto semantic = MaterialDefinition::OCCLUSION;
523     matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(material.mOcclusionTexture, getTextureMetaData(imageMetaData, material.mOcclusionTexture))});
524     // TODO: and there had better be one
525     matDef.mFlags |= semantic;
526     matDef.mOcclusionStrength = material.mOcclusionTexture.mStrength;
527   }
528
529   if(material.mEmissiveTexture)
530   {
531     const auto semantic = MaterialDefinition::EMISSIVE;
532     matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(material.mEmissiveTexture, getTextureMetaData(imageMetaData, material.mEmissiveTexture))});
533     // TODO: and there had better be one
534     matDef.mFlags |= semantic;
535     matDef.mEmissiveFactor = material.mEmissiveFactor;
536   }
537
538   if(material.mMaterialExtensions.mMaterialIor.mIor < MAXFLOAT)
539   {
540     float ior                  = material.mMaterialExtensions.mMaterialIor.mIor;
541     matDef.mDielectricSpecular = powf((ior - 1.0f) / (ior + 1.0f), 2.0f);
542   }
543   matDef.mSpecularFactor      = material.mMaterialExtensions.mMaterialSpecular.mSpecularFactor;
544   matDef.mSpecularColorFactor = material.mMaterialExtensions.mMaterialSpecular.mSpecularColorFactor;
545
546   if(material.mMaterialExtensions.mMaterialSpecular.mSpecularTexture)
547   {
548     const auto semantic = MaterialDefinition::SPECULAR;
549     matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(material.mMaterialExtensions.mMaterialSpecular.mSpecularTexture, getTextureMetaData(imageMetaData, material.mMaterialExtensions.mMaterialSpecular.mSpecularTexture))});
550     matDef.mFlags |= semantic;
551   }
552
553   if(material.mMaterialExtensions.mMaterialSpecular.mSpecularColorTexture)
554   {
555     const auto semantic = MaterialDefinition::SPECULAR_COLOR;
556     matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(material.mMaterialExtensions.mMaterialSpecular.mSpecularColorTexture, getTextureMetaData(imageMetaData, material.mMaterialExtensions.mMaterialSpecular.mSpecularColorTexture))});
557     matDef.mFlags |= semantic;
558   }
559
560   matDef.mDoubleSided = material.mDoubleSided;
561
562   outMaterials.emplace_back(std::move(matDef), TextureSet());
563 }
564
565 void ConvertMaterials(const gt::Document& doc, ConversionContext& context)
566 {
567   auto& imageMetaData = context.mOutput.mSceneMetadata.mImageMetadata;
568
569   auto& outMaterials = context.mOutput.mResources.mMaterials;
570   outMaterials.reserve(doc.mMaterials.size());
571
572   for(auto& m : doc.mMaterials)
573   {
574     ConvertMaterial(m, imageMetaData, outMaterials);
575   }
576 }
577
578 MeshDefinition::Accessor ConvertMeshPrimitiveAccessor(const gt::Accessor& acc)
579 {
580   DALI_ASSERT_ALWAYS((acc.mBufferView &&
581                       (acc.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max())) ||
582                      (acc.mSparse && !acc.mBufferView));
583
584   DALI_ASSERT_ALWAYS(!acc.mSparse ||
585                      ((acc.mSparse->mIndices.mBufferView && (acc.mSparse->mIndices.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max())) &&
586                       (acc.mSparse->mValues.mBufferView && (acc.mSparse->mValues.mBufferView->mByteStride < std::numeric_limits<uint16_t>::max()))));
587
588   MeshDefinition::SparseBlob sparseBlob;
589   if(acc.mSparse)
590   {
591     const gt::Accessor::Sparse&               sparse  = *acc.mSparse;
592     const gt::ComponentTypedBufferViewClient& indices = sparse.mIndices;
593     const gt::BufferViewClient&               values  = sparse.mValues;
594
595     MeshDefinition::Blob indicesBlob(
596       indices.mBufferView->mByteOffset + indices.mByteOffset,
597       sparse.mCount * indices.GetBytesPerComponent(),
598       static_cast<uint16_t>(indices.mBufferView->mByteStride),
599       static_cast<uint16_t>(indices.GetBytesPerComponent()),
600       {},
601       {});
602     MeshDefinition::Blob valuesBlob(
603       values.mBufferView->mByteOffset + values.mByteOffset,
604       sparse.mCount * acc.GetElementSizeBytes(),
605       static_cast<uint16_t>(values.mBufferView->mByteStride),
606       static_cast<uint16_t>(acc.GetElementSizeBytes()),
607       {},
608       {});
609
610     sparseBlob = std::move(MeshDefinition::SparseBlob(std::move(indicesBlob), std::move(valuesBlob), acc.mSparse->mCount));
611   }
612
613   uint32_t bufferViewOffset = 0u;
614   uint32_t bufferViewStride = 0u;
615   if(acc.mBufferView)
616   {
617     bufferViewOffset = acc.mBufferView->mByteOffset;
618     bufferViewStride = acc.mBufferView->mByteStride;
619   }
620
621   return MeshDefinition::Accessor{
622     std::move(MeshDefinition::Blob{bufferViewOffset + acc.mByteOffset,
623                                    acc.GetBytesLength(),
624                                    static_cast<uint16_t>(bufferViewStride),
625                                    static_cast<uint16_t>(acc.GetElementSizeBytes()),
626                                    acc.mMin,
627                                    acc.mMax}),
628     std::move(sparseBlob)};
629 }
630
631 void ConvertMeshes(const gt::Document& doc, ConversionContext& context)
632 {
633   uint32_t meshCount = 0;
634   context.mMeshIds.reserve(doc.mMeshes.size());
635   for(auto& mesh : doc.mMeshes)
636   {
637     context.mMeshIds.push_back(meshCount);
638     meshCount += mesh.mPrimitives.size();
639   }
640
641   auto& outMeshes = context.mOutput.mResources.mMeshes;
642   outMeshes.reserve(meshCount);
643   for(auto& mesh : doc.mMeshes)
644   {
645     for(auto& primitive : mesh.mPrimitives)
646     {
647       MeshDefinition meshDefinition;
648
649       auto& attribs                 = primitive.mAttributes;
650       meshDefinition.mUri           = attribs.begin()->second->mBufferView->mBuffer->mUri;
651       meshDefinition.mPrimitiveType = GLTF2_TO_DALI_PRIMITIVES[primitive.mMode];
652
653       auto& accPositions        = *attribs.find(gt::Attribute::POSITION)->second;
654       meshDefinition.mPositions = ConvertMeshPrimitiveAccessor(accPositions);
655       // glTF2 support vector4 tangent for mesh.
656       // https://www.khronos.org/registry/glTF/specs/2.0/glTF-2.0.html#meshes-overview
657       meshDefinition.mTangentType = Property::VECTOR4;
658
659       const bool needNormalsTangents = accPositions.mType == gt::AccessorType::VEC3;
660       for(auto& am : ATTRIBUTE_MAPPINGS)
661       {
662         auto iFind = attribs.find(am.mType);
663         if(iFind != attribs.end())
664         {
665           DALI_ASSERT_DEBUG(iFind->second->mBufferView->mBuffer->mUri.compare(meshDefinition.mUri) == 0);
666           auto& accessor = meshDefinition.*(am.mAccessor);
667           accessor       = ConvertMeshPrimitiveAccessor(*iFind->second);
668
669           if(iFind->first == gt::Attribute::JOINTS_0)
670           {
671             meshDefinition.mFlags |= (iFind->second->mComponentType == gt::Component::UNSIGNED_SHORT) * MeshDefinition::U16_JOINT_IDS;
672             DALI_ASSERT_DEBUG(MaskMatch(meshDefinition.mFlags, MeshDefinition::U16_JOINT_IDS) || iFind->second->mComponentType == gt::Component::FLOAT);
673           }
674         }
675         else if(needNormalsTangents)
676         {
677           switch(am.mType)
678           {
679             case gt::Attribute::NORMAL:
680               meshDefinition.RequestNormals();
681               break;
682
683             case gt::Attribute::TANGENT:
684               meshDefinition.RequestTangents();
685               break;
686
687             default:
688               break;
689           }
690         }
691       }
692
693       if(primitive.mIndices)
694       {
695         meshDefinition.mIndices = ConvertMeshPrimitiveAccessor(*primitive.mIndices);
696         meshDefinition.mFlags |= (primitive.mIndices->mComponentType == gt::Component::UNSIGNED_INT) * MeshDefinition::U32_INDICES;
697         DALI_ASSERT_DEBUG(MaskMatch(meshDefinition.mFlags, MeshDefinition::U32_INDICES) || primitive.mIndices->mComponentType == gt::Component::UNSIGNED_SHORT);
698       }
699
700       if(!primitive.mTargets.empty())
701       {
702         meshDefinition.mBlendShapes.reserve(primitive.mTargets.size());
703         meshDefinition.mBlendShapeVersion = BlendShapes::Version::VERSION_2_0;
704         for(const auto& target : primitive.mTargets)
705         {
706           MeshDefinition::BlendShape blendShape;
707
708           auto endIt = target.end();
709           auto it    = target.find(gt::Attribute::POSITION);
710           if(it != endIt)
711           {
712             blendShape.deltas = ConvertMeshPrimitiveAccessor(*it->second);
713           }
714           it = target.find(gt::Attribute::NORMAL);
715           if(it != endIt)
716           {
717             blendShape.normals = ConvertMeshPrimitiveAccessor(*it->second);
718           }
719           it = target.find(gt::Attribute::TANGENT);
720           if(it != endIt)
721           {
722             blendShape.tangents = ConvertMeshPrimitiveAccessor(*it->second);
723           }
724
725           if(!mesh.mWeights.empty())
726           {
727             blendShape.weight = mesh.mWeights[meshDefinition.mBlendShapes.size()];
728           }
729
730           meshDefinition.mBlendShapes.push_back(std::move(blendShape));
731         }
732       }
733
734       outMeshes.push_back({std::move(meshDefinition), MeshGeometry{}});
735     }
736   }
737 }
738
739 ModelRenderable* MakeModelRenderable(const gt::Mesh::Primitive& prim, ConversionContext& context)
740 {
741   auto modelRenderable = new ModelRenderable();
742
743   modelRenderable->mShaderIdx = 0; // TODO: further thought
744
745   auto materialIdx = prim.mMaterial.GetIndex();
746   if(INVALID_INDEX == materialIdx)
747   {
748     // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#default-material
749     if(INVALID_INDEX == context.mDefaultMaterial)
750     {
751       auto& outMaterials       = context.mOutput.mResources.mMaterials;
752       context.mDefaultMaterial = outMaterials.size();
753
754       ConvertMaterial(gt::Material{}, context.mOutput.mSceneMetadata.mImageMetadata, outMaterials);
755     }
756
757     materialIdx = context.mDefaultMaterial;
758   }
759
760   modelRenderable->mMaterialIdx = materialIdx;
761
762   return modelRenderable;
763 }
764
765 void ConvertCamera(const gt::Camera& camera, CameraParameters& camParams)
766 {
767   camParams.isPerspective = camera.mType.compare("perspective") == 0;
768   if(camParams.isPerspective)
769   {
770     auto& perspective = camera.mPerspective;
771     camParams.yFov    = Degree(Radian(perspective.mYFov)).degree;
772     camParams.zNear   = perspective.mZNear;
773     camParams.zFar    = perspective.mZFar;
774     // TODO: yes, we seem to ignore aspectRatio in CameraParameters.
775   }
776   else
777   {
778     auto& ortho                = camera.mOrthographic;
779     camParams.orthographicSize = ortho.mYMag * .5f;
780     camParams.aspectRatio      = ortho.mXMag / ortho.mYMag;
781     camParams.zNear            = ortho.mZNear;
782     camParams.zFar             = ortho.mZFar;
783   }
784 }
785
786 void ConvertNode(gt::Node const& node, const Index gltfIdx, Index parentIdx, ConversionContext& context, bool isMRendererModel)
787 {
788   auto& output    = context.mOutput;
789   auto& scene     = output.mScene;
790   auto& resources = output.mResources;
791
792   const auto idx      = scene.GetNodeCount();
793   auto       weakNode = scene.AddNode([&]() {
794     std::unique_ptr<NodeDefinition> nodeDef{new NodeDefinition()};
795
796     nodeDef->mParentIdx = parentIdx;
797     nodeDef->mName      = node.mName;
798     if(nodeDef->mName.empty())
799     {
800       // TODO: Production quality generation of unique names.
801       nodeDef->mName = std::to_string(reinterpret_cast<uintptr_t>(nodeDef.get()));
802     }
803
804     if(!node.mSkin) // Nodes with skinned meshes are not supposed to have local transforms.
805     {
806       nodeDef->mPosition    = node.mTranslation;
807       nodeDef->mOrientation = node.mRotation;
808       nodeDef->mScale       = node.mScale;
809
810       if(isMRendererModel && node.mName == ROOT_NODE_NAME && node.mScale == SCALE_TO_ADJUST)
811       {
812         nodeDef->mScale *= 0.01f;
813       }
814     }
815
816     return nodeDef;
817   }());
818   if(!weakNode)
819   {
820     ExceptionFlinger(ASSERT_LOCATION) << "Node name '" << node.mName << "' is not unique; scene is invalid.";
821   }
822
823   context.mNodeIndices.RegisterMapping(gltfIdx, idx);
824
825   Index skeletonIdx = node.mSkin ? node.mSkin.GetIndex() : INVALID_INDEX;
826   if(node.mMesh)
827   {
828     auto&    mesh           = *node.mMesh;
829     uint32_t primitiveCount = mesh.mPrimitives.size();
830     auto     meshIdx        = context.mMeshIds[node.mMesh.GetIndex()];
831     weakNode->mRenderables.reserve(primitiveCount);
832     for(uint32_t i = 0; i < primitiveCount; ++i)
833     {
834       std::unique_ptr<NodeDefinition::Renderable> renderable;
835       auto                                        modelRenderable = MakeModelRenderable(mesh.mPrimitives[i], context);
836       modelRenderable->mMeshIdx                                   = meshIdx + i;
837
838       DALI_ASSERT_DEBUG(resources.mMeshes[modelRenderable->mMeshIdx].first.mSkeletonIdx == INVALID_INDEX ||
839                         resources.mMeshes[modelRenderable->mMeshIdx].first.mSkeletonIdx == skeletonIdx);
840       resources.mMeshes[modelRenderable->mMeshIdx].first.mSkeletonIdx = skeletonIdx;
841
842       renderable.reset(modelRenderable);
843       weakNode->mRenderables.push_back(std::move(renderable));
844     }
845   }
846
847   if(node.mCamera)
848   {
849     CameraParameters camParams;
850     ConvertCamera(*node.mCamera, camParams);
851
852     camParams.matrix.SetTransformComponents(node.mScale, node.mRotation, node.mTranslation);
853     output.mCameraParameters.push_back(camParams);
854   }
855
856   for(auto& n : node.mChildren)
857   {
858     ConvertNode(*n, n.GetIndex(), idx, context, isMRendererModel);
859   }
860 }
861
862 void ConvertSceneNodes(const gt::Scene& scene, ConversionContext& context, bool isMRendererModel)
863 {
864   auto& outScene = context.mOutput.mScene;
865   Index rootIdx  = outScene.GetNodeCount();
866   switch(scene.mNodes.size())
867   {
868     case 0:
869       break;
870
871     case 1:
872       ConvertNode(*scene.mNodes[0], scene.mNodes[0].GetIndex(), INVALID_INDEX, context, isMRendererModel);
873       outScene.AddRootNode(rootIdx);
874       break;
875
876     default:
877     {
878       std::unique_ptr<NodeDefinition> sceneRoot{new NodeDefinition()};
879       sceneRoot->mName = "GLTF_LOADER_SCENE_ROOT_" + std::to_string(outScene.GetRoots().size());
880
881       outScene.AddNode(std::move(sceneRoot));
882       outScene.AddRootNode(rootIdx);
883
884       for(auto& n : scene.mNodes)
885       {
886         ConvertNode(*n, n.GetIndex(), rootIdx, context, isMRendererModel);
887       }
888       break;
889     }
890   }
891 }
892
893 void ConvertNodes(const gt::Document& doc, ConversionContext& context, bool isMRendererModel)
894 {
895   if(!doc.mScenes.empty())
896   {
897     uint32_t rootSceneIndex = 0u;
898     if(doc.mScene)
899     {
900       rootSceneIndex = doc.mScene.GetIndex();
901     }
902     ConvertSceneNodes(doc.mScenes[rootSceneIndex], context, isMRendererModel);
903
904     for(uint32_t i = 0, i1 = rootSceneIndex; i < i1; ++i)
905     {
906       ConvertSceneNodes(doc.mScenes[i], context, isMRendererModel);
907     }
908
909     for(uint32_t i = rootSceneIndex + 1; i < doc.mScenes.size(); ++i)
910     {
911       ConvertSceneNodes(doc.mScenes[i], context, isMRendererModel);
912     }
913   }
914 }
915
916 template<typename T>
917 void LoadDataFromAccessor(const std::string& path, Vector<T>& dataBuffer, uint32_t offset, uint32_t size)
918 {
919   std::ifstream animationBinaryFile(path, std::ifstream::binary);
920
921   if(!animationBinaryFile.is_open())
922   {
923     throw std::runtime_error("Failed to load " + path);
924   }
925
926   animationBinaryFile.seekg(offset);
927   animationBinaryFile.read(reinterpret_cast<char*>(dataBuffer.Begin()), size);
928   animationBinaryFile.close();
929 }
930
931 template<typename T>
932 float LoadDataFromAccessors(const std::string& path, const gltf2::Accessor& input, const gltf2::Accessor& output, Vector<float>& inputDataBuffer, Vector<T>& outputDataBuffer)
933 {
934   inputDataBuffer.Resize(input.mCount);
935   outputDataBuffer.Resize(output.mCount);
936
937   const uint32_t inputDataBufferSize  = input.GetBytesLength();
938   const uint32_t outputDataBufferSize = output.GetBytesLength();
939
940   LoadDataFromAccessor<float>(path + std::string(input.mBufferView->mBuffer->mUri), inputDataBuffer, input.mBufferView->mByteOffset + input.mByteOffset, inputDataBufferSize);
941   LoadDataFromAccessor<T>(path + std::string(output.mBufferView->mBuffer->mUri), outputDataBuffer, output.mBufferView->mByteOffset + output.mByteOffset, outputDataBufferSize);
942   ApplyAccessorMinMax(output, reinterpret_cast<float*>(outputDataBuffer.begin()));
943
944   return inputDataBuffer[input.mCount - 1u];
945 }
946
947 template<typename T>
948 float LoadKeyFrames(const std::string& path, const gt::Animation::Channel& channel, KeyFrames& keyFrames, gt::Animation::Channel::Target::Type type)
949 {
950   const gltf2::Accessor& input  = *channel.mSampler->mInput;
951   const gltf2::Accessor& output = *channel.mSampler->mOutput;
952
953   Vector<float> inputDataBuffer;
954   Vector<T>     outputDataBuffer;
955
956   const float duration = LoadDataFromAccessors<T>(path, input, output, inputDataBuffer, outputDataBuffer);
957
958   for(uint32_t i = 0; i < input.mCount; ++i)
959   {
960     keyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i]);
961   }
962
963   return duration;
964 }
965
966 float LoadBlendShapeKeyFrames(const std::string& path, const gt::Animation::Channel& channel, Index nodeIndex, uint32_t& propertyIndex, std::vector<Dali::Scene3D::Loader::AnimatedProperty>& properties)
967 {
968   const gltf2::Accessor& input  = *channel.mSampler->mInput;
969   const gltf2::Accessor& output = *channel.mSampler->mOutput;
970
971   Vector<float> inputDataBuffer;
972   Vector<float> outputDataBuffer;
973
974   const float duration = LoadDataFromAccessors<float>(path, input, output, inputDataBuffer, outputDataBuffer);
975
976   char        weightNameBuffer[32];
977   auto        prefixSize    = snprintf(weightNameBuffer, sizeof(weightNameBuffer), "%s[", BLEND_SHAPE_WEIGHTS_UNIFORM.c_str());
978   char* const pWeightName   = weightNameBuffer + prefixSize;
979   const auto  remainingSize = sizeof(weightNameBuffer) - prefixSize;
980   for(uint32_t weightIndex = 0u, endWeightIndex = channel.mSampler->mOutput->mCount / channel.mSampler->mInput->mCount; weightIndex < endWeightIndex; ++weightIndex)
981   {
982     AnimatedProperty& animatedProperty = properties[propertyIndex++];
983
984     animatedProperty.mNodeIndex = nodeIndex;
985     snprintf(pWeightName, remainingSize, "%d]", weightIndex);
986     animatedProperty.mPropertyName = std::string(weightNameBuffer);
987
988     animatedProperty.mKeyFrames = KeyFrames::New();
989     for(uint32_t i = 0; i < input.mCount; ++i)
990     {
991       animatedProperty.mKeyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i * endWeightIndex + weightIndex]);
992     }
993
994     animatedProperty.mTimePeriod = {0.f, duration};
995   }
996
997   return duration;
998 }
999
1000 void ConvertAnimations(const gt::Document& doc, ConversionContext& context)
1001 {
1002   auto& output = context.mOutput;
1003
1004   output.mAnimationDefinitions.reserve(output.mAnimationDefinitions.size() + doc.mAnimations.size());
1005
1006   for(const auto& animation : doc.mAnimations)
1007   {
1008     AnimationDefinition animationDef;
1009
1010     if(!animation.mName.empty())
1011     {
1012       animationDef.mName = animation.mName;
1013     }
1014
1015     uint32_t numberOfProperties = 0u;
1016     for(const auto& channel : animation.mChannels)
1017     {
1018       if(channel.mTarget.mPath == gt::Animation::Channel::Target::WEIGHTS)
1019       {
1020         numberOfProperties += channel.mSampler->mOutput->mCount / channel.mSampler->mInput->mCount;
1021       }
1022       else
1023       {
1024         numberOfProperties++;
1025       }
1026     }
1027     animationDef.mProperties.resize(numberOfProperties);
1028
1029     Index propertyIndex = 0u;
1030     for(const auto& channel : animation.mChannels)
1031     {
1032       Index nodeIndex    = context.mNodeIndices.GetRuntimeId(channel.mTarget.mNode.GetIndex());
1033       float duration = 0.f;
1034
1035       switch(channel.mTarget.mPath)
1036       {
1037         case gt::Animation::Channel::Target::TRANSLATION:
1038         {
1039           AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
1040
1041           animatedProperty.mNodeIndex    = nodeIndex;
1042           animatedProperty.mPropertyName = POSITION_PROPERTY;
1043
1044           animatedProperty.mKeyFrames = KeyFrames::New();
1045           duration                    = LoadKeyFrames<Vector3>(context.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
1046
1047           animatedProperty.mTimePeriod = {0.f, duration};
1048           break;
1049         }
1050         case gt::Animation::Channel::Target::ROTATION:
1051         {
1052           AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
1053
1054           animatedProperty.mNodeIndex    = nodeIndex;
1055           animatedProperty.mPropertyName = ORIENTATION_PROPERTY;
1056
1057           animatedProperty.mKeyFrames = KeyFrames::New();
1058           duration                    = LoadKeyFrames<Quaternion>(context.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
1059
1060           animatedProperty.mTimePeriod = {0.f, duration};
1061           break;
1062         }
1063         case gt::Animation::Channel::Target::SCALE:
1064         {
1065           AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex];
1066
1067           animatedProperty.mNodeIndex    = nodeIndex;
1068           animatedProperty.mPropertyName = SCALE_PROPERTY;
1069
1070           animatedProperty.mKeyFrames = KeyFrames::New();
1071           duration                    = LoadKeyFrames<Vector3>(context.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath);
1072
1073           animatedProperty.mTimePeriod = {0.f, duration};
1074           break;
1075         }
1076         case gt::Animation::Channel::Target::WEIGHTS:
1077         {
1078           duration = LoadBlendShapeKeyFrames(context.mPath, channel, nodeIndex, propertyIndex, animationDef.mProperties);
1079
1080           break;
1081         }
1082         default:
1083         {
1084           // nothing to animate.
1085           break;
1086         }
1087       }
1088
1089       animationDef.mDuration = std::max(duration, animationDef.mDuration);
1090
1091       ++propertyIndex;
1092     }
1093
1094     output.mAnimationDefinitions.push_back(std::move(animationDef));
1095   }
1096 }
1097
1098 void ProcessSkins(const gt::Document& doc, ConversionContext& context)
1099 {
1100   // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skininversebindmatrices
1101   // If an inverseBindMatrices accessor was provided, we'll load the joint data from the buffer,
1102   // otherwise we'll set identity matrices for inverse bind pose.
1103   struct IInverseBindMatrixProvider
1104   {
1105     virtual ~IInverseBindMatrixProvider()
1106     {
1107     }
1108     virtual void Provide(Matrix& ibm) = 0;
1109   };
1110
1111   struct InverseBindMatrixAccessor : public IInverseBindMatrixProvider
1112   {
1113     std::ifstream  mStream;
1114     const uint32_t mElementSizeBytes;
1115
1116     InverseBindMatrixAccessor(const gt::Accessor& accessor, const std::string& path)
1117     : mStream(path + std::string(accessor.mBufferView->mBuffer->mUri), std::ios::binary),
1118       mElementSizeBytes(accessor.GetElementSizeBytes())
1119     {
1120       DALI_ASSERT_ALWAYS(mStream);
1121       DALI_ASSERT_DEBUG(accessor.mType == gt::AccessorType::MAT4 && accessor.mComponentType == gt::Component::FLOAT);
1122
1123       mStream.seekg(accessor.mBufferView->mByteOffset + accessor.mByteOffset);
1124     }
1125
1126     virtual void Provide(Matrix& ibm) override
1127     {
1128       DALI_ASSERT_ALWAYS(mStream.read(reinterpret_cast<char*>(ibm.AsFloat()), mElementSizeBytes));
1129     }
1130   };
1131
1132   struct DefaultInverseBindMatrixProvider : public IInverseBindMatrixProvider
1133   {
1134     virtual void Provide(Matrix& ibm) override
1135     {
1136       ibm = Matrix::IDENTITY;
1137     }
1138   };
1139
1140   auto& resources = context.mOutput.mResources;
1141   resources.mSkeletons.reserve(doc.mSkins.size());
1142
1143   for(auto& s : doc.mSkins)
1144   {
1145     std::unique_ptr<IInverseBindMatrixProvider> ibmProvider;
1146     if(s.mInverseBindMatrices)
1147     {
1148       ibmProvider.reset(new InverseBindMatrixAccessor(*s.mInverseBindMatrices, context.mPath));
1149     }
1150     else
1151     {
1152       ibmProvider.reset(new DefaultInverseBindMatrixProvider());
1153     }
1154
1155     SkeletonDefinition skeleton;
1156     if(s.mSkeleton.GetIndex() != INVALID_INDEX)
1157     {
1158       skeleton.mRootNodeIdx = context.mNodeIndices.GetRuntimeId(s.mSkeleton.GetIndex());
1159     }
1160
1161     skeleton.mJoints.resize(s.mJoints.size());
1162     auto iJoint = skeleton.mJoints.begin();
1163     for(auto& j : s.mJoints)
1164     {
1165       iJoint->mNodeIdx = context.mNodeIndices.GetRuntimeId(j.GetIndex());
1166
1167       ibmProvider->Provide(iJoint->mInverseBindMatrix);
1168
1169       ++iJoint;
1170     }
1171
1172     resources.mSkeletons.push_back(std::move(skeleton));
1173   }
1174 }
1175
1176 void ProduceShaders(ShaderDefinitionFactory& shaderFactory, SceneDefinition& scene)
1177 {
1178   uint32_t nodeCount = scene.GetNodeCount();
1179   for(uint32_t i = 0; i < nodeCount; ++i)
1180   {
1181     auto nodeDef = scene.GetNode(i);
1182     for(auto& renderable : nodeDef->mRenderables)
1183     {
1184       if(shaderFactory.ProduceShader(*renderable) == INVALID_INDEX)
1185       {
1186         DALI_LOG_ERROR("Fail to produce shader\n");
1187       }
1188     }
1189   }
1190 }
1191
1192 void SetObjectReaders()
1193 {
1194   js::SetObjectReader(BUFFER_READER);
1195   js::SetObjectReader(BUFFER_VIEW_READER);
1196   js::SetObjectReader(BUFFER_VIEW_CLIENT_READER);
1197   js::SetObjectReader(COMPONENT_TYPED_BUFFER_VIEW_CLIENT_READER);
1198   js::SetObjectReader(ACCESSOR_SPARSE_READER);
1199   js::SetObjectReader(ACCESSOR_READER);
1200   js::SetObjectReader(IMAGE_READER);
1201   js::SetObjectReader(SAMPLER_READER);
1202   js::SetObjectReader(TEXURE_READER);
1203   js::SetObjectReader(TEXURE_INFO_READER);
1204   js::SetObjectReader(MATERIAL_PBR_READER);
1205   js::SetObjectReader(MATERIAL_SPECULAR_READER);
1206   js::SetObjectReader(MATERIAL_IOR_READER);
1207   js::SetObjectReader(MATERIAL_EXTENSION_READER);
1208   js::SetObjectReader(MATERIAL_READER);
1209   js::SetObjectReader(MESH_PRIMITIVE_READER);
1210   js::SetObjectReader(MESH_READER);
1211   js::SetObjectReader(SKIN_READER);
1212   js::SetObjectReader(CAMERA_PERSPECTIVE_READER);
1213   js::SetObjectReader(CAMERA_ORTHOGRAPHIC_READER);
1214   js::SetObjectReader(CAMERA_READER);
1215   js::SetObjectReader(NODE_READER);
1216   js::SetObjectReader(ANIMATION_SAMPLER_READER);
1217   js::SetObjectReader(ANIMATION_TARGET_READER);
1218   js::SetObjectReader(ANIMATION_CHANNEL_READER);
1219   js::SetObjectReader(ANIMATION_READER);
1220   js::SetObjectReader(SCENE_READER);
1221 }
1222
1223 void SetDefaultEnvironmentMap(const gt::Document& doc, ConversionContext& context)
1224 {
1225   EnvironmentDefinition envDef;
1226   envDef.mUseBrdfTexture = true;
1227   envDef.mIblIntensity   = Scene3D::Loader::EnvironmentDefinition::GetDefaultIntensity();
1228   context.mOutput.mResources.mEnvironmentMaps.push_back({std::move(envDef), EnvironmentDefinition::Textures()});
1229 }
1230
1231 } // namespace
1232
1233 void LoadGltfScene(const std::string& url, ShaderDefinitionFactory& shaderFactory, LoadResult& params)
1234 {
1235   bool failed = false;
1236   auto js     = LoadTextFile(url.c_str(), &failed);
1237   if(failed)
1238   {
1239     throw std::runtime_error("Failed to load " + url);
1240   }
1241
1242   json::unique_ptr root(json_parse(js.c_str(), js.size()));
1243   if(!root)
1244   {
1245     throw std::runtime_error("Failed to parse " + url);
1246   }
1247
1248   static bool setObjectReaders = true;
1249   if(setObjectReaders)
1250   {
1251     // NOTE: only referencing own, anonymous namespace, const objects; the pointers will never need to change.
1252     SetObjectReaders();
1253     setObjectReaders = false;
1254   }
1255
1256   gt::Document doc;
1257
1258   auto& rootObj = js::Cast<json_object_s>(*root);
1259   auto  jsAsset = js::FindObjectChild("asset", rootObj);
1260
1261   auto jsAssetVersion = js::FindObjectChild("version", js::Cast<json_object_s>(*jsAsset));
1262   if(jsAssetVersion)
1263   {
1264     doc.mAsset.mVersion = js::Read::StringView(*jsAssetVersion);
1265   }
1266
1267   bool isMRendererModel(false);
1268   auto jsAssetGenerator = js::FindObjectChild("generator", js::Cast<json_object_s>(*jsAsset));
1269   if(jsAssetGenerator)
1270   {
1271     doc.mAsset.mGenerator = js::Read::StringView(*jsAssetGenerator);
1272     isMRendererModel      = (doc.mAsset.mGenerator.find(MRENDERER_MODEL_IDENTIFICATION) != std::string_view::npos);
1273   }
1274
1275   gt::SetRefReaderObject(doc);
1276   DOCUMENT_READER.Read(rootObj, doc);
1277
1278   auto              path = url.substr(0, url.rfind('/') + 1);
1279   ConversionContext context{params, path, INVALID_INDEX};
1280
1281   ConvertMaterials(doc, context);
1282   ConvertMeshes(doc, context);
1283   ConvertNodes(doc, context, isMRendererModel);
1284   ConvertAnimations(doc, context);
1285   ProcessSkins(doc, context);
1286   ProduceShaders(shaderFactory, params.mScene);
1287   params.mScene.EnsureUniqueSkinningShaderInstances(params.mResources);
1288
1289   // Set Default Environment map
1290   SetDefaultEnvironmentMap(doc, context);
1291 }
1292
1293 } // namespace Loader
1294 } // namespace Scene3D
1295 } // namespace Dali