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