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