Merge "Fix webp&gif issue" into devel/master
[platform/core/uifw/dali-toolkit.git] / automated-tests / src / dali-scene-loader / utc-Dali-Gltf2Loader.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
18 // Enable debug log for test coverage
19 #define DEBUG_ENABLED 1
20
21 #include <dali-test-suite-utils.h>
22 #include <string_view>
23 #include "dali-scene-loader/public-api/gltf2-loader.h"
24 #include "dali-scene-loader/public-api/load-result.h"
25 #include "dali-scene-loader/public-api/resource-bundle.h"
26 #include "dali-scene-loader/public-api/scene-definition.h"
27 #include "dali-scene-loader/public-api/shader-definition-factory.h"
28
29 using namespace Dali;
30 using namespace Dali::SceneLoader;
31
32 #define DALI_TEST_THROW(expression, exception, predicate) \
33   {                                                       \
34     bool daliTestThrowSuccess__ = false;                  \
35     try                                                   \
36     {                                                     \
37       do                                                  \
38       {                                                   \
39         expression;                                       \
40       } while(0);                                         \
41       printf("No exception was thrown.\n");               \
42     }                                                     \
43     catch(std::decay<exception>::type & ex)               \
44     {                                                     \
45       daliTestThrowSuccess__ = predicate(ex);             \
46     }                                                     \
47     catch(...)                                            \
48     {                                                     \
49       printf("Wrong type of exception thrown.\n");        \
50     }                                                     \
51     DALI_TEST_CHECK(daliTestThrowSuccess__);              \
52   }
53
54 namespace
55 {
56 struct Context
57 {
58   ResourceBundle::PathProvider pathProvider = [](ResourceType::Value type) {
59     return TEST_RESOURCE_DIR "/";
60   };
61
62   ResourceBundle  resources;
63   SceneDefinition scene;
64
65   std::vector<AnimationDefinition>      animations;
66   std::vector<AnimationGroupDefinition> animationGroups;
67   std::vector<CameraParameters>         cameras;
68   std::vector<LightParameters>          lights;
69
70   LoadResult loadResult{
71     resources,
72     scene,
73     animations,
74     animationGroups,
75     cameras,
76     lights};
77 };
78
79 struct ExceptionMessageStartsWith
80 {
81   const std::string_view expected;
82
83   bool operator()(const std::runtime_error& e)
84   {
85     const bool success = (0 == strncmp(e.what(), expected.data(), expected.size()));
86     if(!success)
87     {
88       printf("Expected: %s, got: %s.\n", expected.data(), e.what());
89     }
90     return success;
91   }
92 };
93
94 } // namespace
95
96 int UtcDaliGltfLoaderFailedToLoad(void)
97 {
98   Context ctx;
99
100   ShaderDefinitionFactory sdf;
101   sdf.SetResources(ctx.resources);
102
103   DALI_TEST_THROW(LoadGltfScene("non-existent.gltf", sdf, ctx.loadResult),
104                   std::runtime_error,
105                   ExceptionMessageStartsWith{"Failed to load"});
106
107   DALI_TEST_EQUAL(0, ctx.scene.GetRoots().size());
108   DALI_TEST_EQUAL(0, ctx.scene.GetNodeCount());
109
110   DALI_TEST_EQUAL(0, ctx.resources.mEnvironmentMaps.size());
111   DALI_TEST_EQUAL(0, ctx.resources.mMaterials.size());
112   DALI_TEST_EQUAL(0, ctx.resources.mMeshes.size());
113   DALI_TEST_EQUAL(0, ctx.resources.mShaders.size());
114   DALI_TEST_EQUAL(0, ctx.resources.mSkeletons.size());
115
116   DALI_TEST_EQUAL(0, ctx.cameras.size());
117   DALI_TEST_EQUAL(0, ctx.lights.size());
118   DALI_TEST_EQUAL(0, ctx.animations.size());
119   DALI_TEST_EQUAL(0, ctx.animationGroups.size());
120
121   END_TEST;
122 }
123
124 int UtcDaliGltfLoaderFailedToParse(void)
125 {
126   Context ctx;
127
128   ShaderDefinitionFactory sdf;
129   sdf.SetResources(ctx.resources);
130
131   DALI_TEST_THROW(LoadGltfScene(TEST_RESOURCE_DIR "/invalid.gltf", sdf, ctx.loadResult),
132                   std::runtime_error,
133                   ExceptionMessageStartsWith{"Failed to parse"});
134
135   DALI_TEST_EQUAL(0, ctx.scene.GetRoots().size());
136   DALI_TEST_EQUAL(0, ctx.scene.GetNodeCount());
137
138   DALI_TEST_EQUAL(0, ctx.resources.mEnvironmentMaps.size());
139   DALI_TEST_EQUAL(0, ctx.resources.mMaterials.size());
140   DALI_TEST_EQUAL(0, ctx.resources.mMeshes.size());
141   DALI_TEST_EQUAL(0, ctx.resources.mShaders.size());
142   DALI_TEST_EQUAL(0, ctx.resources.mSkeletons.size());
143
144   DALI_TEST_EQUAL(0, ctx.cameras.size());
145   DALI_TEST_EQUAL(0, ctx.lights.size());
146   DALI_TEST_EQUAL(0, ctx.animations.size());
147   DALI_TEST_EQUAL(0, ctx.animationGroups.size());
148
149   END_TEST;
150 }
151
152 int UtcDaliGltfLoaderSuccess1(void)
153 {
154   Context ctx;
155
156   ShaderDefinitionFactory sdf;
157   sdf.SetResources(ctx.resources);
158
159   LoadGltfScene(TEST_RESOURCE_DIR "/AnimatedCube.gltf", sdf, ctx.loadResult);
160
161   DALI_TEST_EQUAL(1u, ctx.scene.GetRoots().size());
162   DALI_TEST_EQUAL(6u, ctx.scene.GetNodeCount());
163
164   DALI_TEST_EQUAL(0u, ctx.resources.mEnvironmentMaps.size());
165
166   auto& materials = ctx.resources.mMaterials;
167   DALI_TEST_EQUAL(2u, materials.size());
168   const MaterialDefinition materialGroundTruth[]{
169     {MaterialDefinition::ALBEDO | MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS |
170        MaterialDefinition::EMISSIVE | MaterialDefinition::OCCLUSION |
171        MaterialDefinition::NORMAL | MaterialDefinition::TRANSPARENCY | MaterialDefinition::GLTF_CHANNELS |
172        (0x80 << MaterialDefinition::ALPHA_CUTOFF_SHIFT),
173      0,
174      Vector4(1.f, .766f, .336f, 1.f),
175      Vector3(0.2, 0.1, 0.0),
176      1.f,
177      0.f,
178      1.f,
179      {
180        {MaterialDefinition::ALBEDO,
181         {"AnimatedCube_BaseColor.png",
182          SamplerFlags::Encode(FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR, WrapMode::CLAMP_TO_EDGE, WrapMode::REPEAT)}},
183        {MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS | MaterialDefinition::GLTF_CHANNELS,
184         {"AnimatedCube_MetallicRoughness.png",
185          SamplerFlags::Encode(FilterMode::NEAREST_MIPMAP_LINEAR, FilterMode::NEAREST, WrapMode::CLAMP_TO_EDGE, WrapMode::MIRRORED_REPEAT)}},
186        {MaterialDefinition::NORMAL,
187         {"AnimatedCube_BaseColor.png",
188          SamplerFlags::Encode(FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR, WrapMode::CLAMP_TO_EDGE, WrapMode::REPEAT)}},
189        {MaterialDefinition::OCCLUSION,
190         {"AnimatedCube_BaseColor.png",
191          SamplerFlags::Encode(FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR, WrapMode::CLAMP_TO_EDGE, WrapMode::REPEAT)}},
192        {MaterialDefinition::EMISSIVE,
193         {"AnimatedCube_BaseColor.png",
194          SamplerFlags::Encode(FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR, WrapMode::CLAMP_TO_EDGE, WrapMode::REPEAT)}},
195      }},
196     {MaterialDefinition::ALBEDO | MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS |
197        MaterialDefinition::EMISSIVE | MaterialDefinition::OCCLUSION |
198        MaterialDefinition::NORMAL | MaterialDefinition::GLTF_CHANNELS,
199      0,
200      Vector4(1.f, .766f, .336f, 1.f),
201      Vector3(0.2, 0.1, 0.0),
202      1.f,
203      0.f,
204      1.f,
205      {
206        {MaterialDefinition::ALBEDO,
207         {"AnimatedCube_BaseColor.png",
208          SamplerFlags::Encode(FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR, WrapMode::CLAMP_TO_EDGE, WrapMode::REPEAT)}},
209        {MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS | MaterialDefinition::GLTF_CHANNELS,
210         {"AnimatedCube_MetallicRoughness.png",
211          SamplerFlags::Encode(FilterMode::NEAREST_MIPMAP_LINEAR, FilterMode::NEAREST, WrapMode::CLAMP_TO_EDGE, WrapMode::MIRRORED_REPEAT)}},
212        {MaterialDefinition::NORMAL,
213         {"AnimatedCube_BaseColor.png",
214          SamplerFlags::Encode(FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR, WrapMode::CLAMP_TO_EDGE, WrapMode::REPEAT)}},
215        {MaterialDefinition::OCCLUSION,
216         {"AnimatedCube_BaseColor.png",
217          SamplerFlags::Encode(FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR, WrapMode::CLAMP_TO_EDGE, WrapMode::REPEAT)}},
218        {MaterialDefinition::EMISSIVE,
219         {"AnimatedCube_BaseColor.png",
220          SamplerFlags::Encode(FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR, WrapMode::CLAMP_TO_EDGE, WrapMode::REPEAT)}},
221      }},
222   };
223
224   auto iMaterial = materials.begin();
225   for(auto& m : materialGroundTruth)
226   {
227     printf("material %ld\n", iMaterial - materials.begin());
228     auto& md = iMaterial->first;
229     DALI_TEST_EQUAL(md.mFlags, m.mFlags);
230     DALI_TEST_EQUAL(md.mEnvironmentIdx, m.mEnvironmentIdx);
231     DALI_TEST_EQUAL(md.mColor, m.mColor);
232     DALI_TEST_EQUAL(md.mMetallic, m.mMetallic);
233     DALI_TEST_EQUAL(md.mRoughness, m.mRoughness);
234
235     DALI_TEST_EQUAL(md.mTextureStages.size(), m.mTextureStages.size());
236     auto iTexture = md.mTextureStages.begin();
237     for(auto& ts : m.mTextureStages)
238     {
239       printf("texture %ld\n", iTexture - md.mTextureStages.begin());
240       DALI_TEST_EQUAL(iTexture->mSemantic, ts.mSemantic);
241       DALI_TEST_EQUAL(iTexture->mTexture.mImageUri, ts.mTexture.mImageUri);
242       DALI_TEST_EQUAL(uint32_t(iTexture->mTexture.mSamplerFlags), uint32_t(ts.mTexture.mSamplerFlags)); // don't interpret it as a character
243       ++iTexture;
244     }
245     ++iMaterial;
246   }
247
248   auto& meshes = ctx.resources.mMeshes;
249   DALI_TEST_EQUAL(2u, meshes.size());
250
251   using Blob     = MeshDefinition::Blob;
252   using Accessor = MeshDefinition::Accessor;
253   const MeshDefinition meshGroundTruth[]{
254     {
255       0,
256       Geometry::TRIANGLES,
257       "AnimatedCube.bin",
258       Accessor{Blob{0, 0}, {}},
259       Accessor{Blob{0, 0}, {}},
260       Accessor{Blob{0, 0}, {}},
261       Accessor{Blob{0, 0}, {}},
262       Accessor{Blob{0, 0}, {}},
263     },
264     {
265       0,
266       Geometry::TRIANGLES,
267       "AnimatedCube.bin",
268       Accessor{Blob{0, 0}, {}},
269       Accessor{Blob{0, 0}, {}},
270       Accessor{Blob{0, 0}, {}},
271       Accessor{Blob{0, 0}, {}},
272       Accessor{Blob{0, 0}, {}},
273     },
274   };
275
276   auto iMesh = meshes.begin();
277   for(auto& m : meshGroundTruth)
278   {
279     printf("mesh %ld\n", iMesh - meshes.begin());
280
281     auto& md = iMesh->first;
282     DALI_TEST_EQUAL(md.mFlags, m.mFlags);
283     DALI_TEST_EQUAL(md.mPrimitiveType, m.mPrimitiveType);
284     for(auto mp : {
285           &MeshDefinition::mIndices,
286           &MeshDefinition::mPositions,
287           &MeshDefinition::mNormals,
288           &MeshDefinition::mTexCoords,
289           &MeshDefinition::mTangents,
290           &MeshDefinition::mJoints0,
291           &MeshDefinition::mWeights0})
292     {
293       DALI_TEST_EQUAL((md.*mp).IsDefined(), (m.*mp).IsDefined());
294       DALI_TEST_EQUAL((md.*mp).mBlob.IsDefined(), (m.*mp).mBlob.IsDefined());
295     }
296
297     DALI_TEST_EQUAL(md.mBlendShapeHeader.IsDefined(), m.mBlendShapeHeader.IsDefined());
298
299     ++iMesh;
300   }
301
302   DALI_TEST_EQUAL(2u, ctx.resources.mShaders.size());
303   DALI_TEST_EQUAL(0u, ctx.resources.mSkeletons.size());
304
305   DALI_TEST_EQUAL(3u, ctx.cameras.size());
306   DALI_TEST_EQUAL(0u, ctx.lights.size());
307   DALI_TEST_EQUAL(1u, ctx.animations.size());
308   DALI_TEST_EQUAL(0u, ctx.animationGroups.size());
309
310   END_TEST;
311 }
312
313 int UtcDaliGltfLoaderSuccessShort(void)
314 {
315   TestApplication app;
316
317   const std::string resourcePath = TEST_RESOURCE_DIR "/";
318   auto              pathProvider = [resourcePath](ResourceType::Value) {
319     return resourcePath;
320   };
321
322   Customization::Choices choices;
323   for(auto modelName : {
324         "2CylinderEngine",
325         "AnimatedMorphCube",
326         "AnimatedMorphSphere",
327         "AnimatedTriangle",
328         "BoxAnimated",
329         "CesiumMan",
330         "CesiumMilkTruck",
331         "EnvironmentTest",
332         "MetalRoughSpheres",
333         "MorphPrimitivesTest",
334         "MRendererTest",
335         "SimpleSparseAccessor",
336       })
337   {
338     Context ctx;
339
340     ShaderDefinitionFactory sdf;
341
342     auto& resources = ctx.resources;
343     resources.mEnvironmentMaps.push_back({});
344
345     sdf.SetResources(resources);
346
347     printf("%s\n", modelName);
348     LoadGltfScene(resourcePath + modelName + ".gltf", sdf, ctx.loadResult);
349     DALI_TEST_CHECK(ctx.scene.GetNodeCount() > 0);
350
351     auto& scene = ctx.scene;
352     for(auto iRoot : scene.GetRoots())
353     {
354       struct Visitor : NodeDefinition::IVisitor
355       {
356         struct ResourceReceiver : IResourceReceiver
357         {
358           std::vector<bool> mCounts;
359
360           void Register(ResourceType::Value type, Index id) override
361           {
362             if(type == ResourceType::Mesh)
363             {
364               mCounts[id] = true;
365             }
366           }
367         } receiver;
368
369         void Start(NodeDefinition& n) override
370         {
371           if(n.mRenderable)
372           {
373             n.mRenderable->RegisterResources(receiver);
374           }
375         }
376
377         void Finish(NodeDefinition& n) override
378         {
379         }
380       } visitor;
381       visitor.receiver.mCounts.resize(resources.mMeshes.size(), false);
382
383       scene.Visit(iRoot, choices, visitor);
384       for(uint32_t i0 = 0, i1 = resources.mMeshes.size(); i0 < i1; ++i0)
385       {
386         if(visitor.receiver.mCounts[i0])
387         {
388           auto raw = resources.mMeshes[i0].first.LoadRaw(resourcePath);
389           DALI_TEST_CHECK(!raw.mAttribs.empty());
390
391           resources.mMeshes[i0].second = resources.mMeshes[i0].first.Load(std::move(raw));
392           DALI_TEST_CHECK(resources.mMeshes[i0].second.geometry);
393         }
394       }
395     }
396   }
397
398   END_TEST;
399 }
400
401 int UtcDaliGltfLoaderMRendererTest(void)
402 {
403   Context ctx;
404
405   ShaderDefinitionFactory sdf;
406   sdf.SetResources(ctx.resources);
407   auto& resources = ctx.resources;
408   resources.mEnvironmentMaps.push_back({});
409
410   LoadGltfScene(TEST_RESOURCE_DIR "/MRendererTest.gltf", sdf, ctx.loadResult);
411
412   auto& scene = ctx.scene;
413   auto& roots = scene.GetRoots();
414   DALI_TEST_EQUAL(roots.size(), 1u);
415   DALI_TEST_EQUAL(scene.GetNode(roots[0])->mName, "RootNode");
416   DALI_TEST_EQUAL(scene.GetNode(roots[0])->mScale, Vector3(1.0f, 1.0f, 1.0f));
417
418   DALI_TEST_EQUAL(scene.GetNodeCount(), 1u);
419
420   ViewProjection viewProjection;
421   Transforms     xforms{
422     MatrixStack{},
423     viewProjection};
424   NodeDefinition::CreateParams nodeParams{
425     resources,
426     xforms,
427   };
428
429   Customization::Choices choices;
430
431   TestApplication app;
432
433   Actor root = Actor::New();
434   SetActorCentered(root);
435   for(auto iRoot : roots)
436   {
437     auto resourceRefs = resources.CreateRefCounter();
438     scene.CountResourceRefs(iRoot, choices, resourceRefs);
439     resources.CountEnvironmentReferences(resourceRefs);
440     resources.LoadResources(resourceRefs, ctx.pathProvider);
441     if(auto actor = scene.CreateNodes(iRoot, choices, nodeParams))
442     {
443       scene.ConfigureSkeletonJoints(iRoot, resources.mSkeletons, actor);
444       scene.ConfigureSkinningShaders(resources, actor, std::move(nodeParams.mSkinnables));
445       scene.ApplyConstraints(actor, std::move(nodeParams.mConstrainables));
446       root.Add(actor);
447     }
448   }
449
450   DALI_TEST_EQUAL(root.GetChildCount(), 1u);
451   DALI_TEST_EQUAL(root.GetChildAt(0).GetProperty(Actor::Property::NAME).Get<std::string>(), "RootNode");
452   DALI_TEST_EQUAL(root.GetChildAt(0).GetProperty(Actor::Property::SCALE).Get<Vector3>(), Vector3(1.0f, 1.0f, 1.0f));
453
454   END_TEST;
455 }