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