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