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