Change ModelView to Model
[platform/core/uifw/dali-toolkit.git] / dali-scene3d / internal / controls / model / model-impl.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 // CLASS HEADER
19 #include <dali-scene3d/internal/controls/model/model-impl.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali-toolkit/dali-toolkit.h>
23 #include <dali-toolkit/internal/controls/control/control-data-impl.h>
24 #include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
25 #include <dali/integration-api/debug.h>
26 #include <dali/public-api/object/type-registry-helper.h>
27 #include <dali/public-api/object/type-registry.h>
28 #include <filesystem>
29
30 // INTERNAL INCLUDES
31 #include <dali-scene3d/public-api/controls/model/model.h>
32 #include <dali-scene3d/internal/controls/scene-view/scene-view-impl.h>
33 #include <dali-scene3d/public-api/loader/animation-definition.h>
34 #include <dali-scene3d/public-api/loader/camera-parameters.h>
35 #include <dali-scene3d/public-api/loader/cube-map-loader.h>
36 #include <dali-scene3d/public-api/loader/dli-loader.h>
37 #include <dali-scene3d/public-api/loader/gltf2-loader.h>
38 #include <dali-scene3d/public-api/loader/light-parameters.h>
39 #include <dali-scene3d/public-api/loader/load-result.h>
40 #include <dali-scene3d/public-api/loader/node-definition.h>
41 #include <dali-scene3d/public-api/loader/scene-definition.h>
42 #include <dali-scene3d/public-api/loader/shader-definition-factory.h>
43
44 using namespace Dali;
45
46 namespace Dali
47 {
48 namespace Scene3D
49 {
50 namespace Internal
51 {
52 namespace
53 {
54 BaseHandle Create()
55 {
56   return Scene3D::Model::New(std::string());
57 }
58
59 // Setup properties, signals and actions using the type-registry.
60 DALI_TYPE_REGISTRATION_BEGIN(Scene3D::Model, Toolkit::Control, Create);
61 DALI_TYPE_REGISTRATION_END()
62
63 static constexpr uint32_t OFFSET_FOR_DIFFUSE_CUBE_TEXTURE  = 2u;
64 static constexpr uint32_t OFFSET_FOR_SPECULAR_CUBE_TEXTURE = 1u;
65
66 static constexpr Vector3 Y_DIRECTION(1.0f, -1.0f, 1.0f);
67
68 static constexpr std::string_view KTX_EXTENSION  = ".ktx";
69 static constexpr std::string_view OBJ_EXTENSION  = ".obj";
70 static constexpr std::string_view GLTF_EXTENSION = ".gltf";
71 static constexpr std::string_view DLI_EXTENSION  = ".dli";
72
73 struct BoundingVolume
74 {
75   void Init()
76   {
77     pointMin = Vector3(std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max());
78     pointMax = Vector3(std::numeric_limits<float>::min(), std::numeric_limits<float>::min(), std::numeric_limits<float>::min());
79   }
80
81   void ConsiderNewPointInVolume(const Vector3& position)
82   {
83     pointMin.x = std::min(position.x, pointMin.x);
84     pointMin.y = std::min(position.y, pointMin.y);
85     pointMin.z = std::min(position.z, pointMin.z);
86
87     pointMax.x = std::max(position.x, pointMax.x);
88     pointMax.y = std::max(position.y, pointMax.y);
89     pointMax.z = std::max(position.z, pointMax.z);
90   }
91
92   Vector3 CalculateSize()
93   {
94     return pointMax - pointMin;
95   }
96
97   Vector3 CalculatePivot()
98   {
99     Vector3 pivot = pointMin / (pointMin - pointMax);
100     for(uint32_t i = 0; i < 3; ++i)
101     {
102       // To avoid divid by zero
103       if(pointMin[i] == pointMax[i])
104       {
105         pivot[i] = 0.5f;
106       }
107     }
108     return pivot;
109   }
110
111   Vector3 pointMin;
112   Vector3 pointMax;
113 };
114
115 void ConfigureBlendShapeShaders(
116   Dali::Scene3D::Loader::ResourceBundle& resources, const Dali::Scene3D::Loader::SceneDefinition& scene, Actor root, std::vector<Dali::Scene3D::Loader::BlendshapeShaderConfigurationRequest>&& requests)
117 {
118   std::vector<std::string> errors;
119   auto                     onError = [&errors](const std::string& msg) { errors.push_back(msg); };
120   if(!scene.ConfigureBlendshapeShaders(resources, root, std::move(requests), onError))
121   {
122     Dali::Scene3D::Loader::ExceptionFlinger flinger(ASSERT_LOCATION);
123     for(auto& msg : errors)
124     {
125       flinger << msg << '\n';
126     }
127   }
128 }
129
130 void AddModelTreeToAABB(BoundingVolume& AABB, const Dali::Scene3D::Loader::SceneDefinition& scene, const Dali::Scene3D::Loader::Customization::Choices& choices, Dali::Scene3D::Loader::Index iNode, Dali::Scene3D::Loader::NodeDefinition::CreateParams& nodeParams, Matrix parentMatrix)
131 {
132   static constexpr uint32_t BOX_POINT_COUNT             = 8;
133   static uint32_t           BBIndex[BOX_POINT_COUNT][3] = {{0, 0, 0}, {0, 1, 0}, {1, 0, 0}, {1, 1, 0}, {0, 0, 1}, {0, 1, 1}, {1, 0, 1}, {1, 1, 1}};
134
135   Matrix                                       nodeMatrix;
136   const Dali::Scene3D::Loader::NodeDefinition* node        = scene.GetNode(iNode);
137   Matrix                                       localMatrix = node->GetLocalSpace();
138   Matrix::Multiply(nodeMatrix, localMatrix, parentMatrix);
139
140   Vector3 volume[2];
141   if(node->GetExtents(nodeParams.mResources, volume[0], volume[1]))
142   {
143     for(uint32_t i = 0; i < BOX_POINT_COUNT; ++i)
144     {
145       Vector4 position       = Vector4(volume[BBIndex[i][0]].x, volume[BBIndex[i][1]].y, volume[BBIndex[i][2]].z, 1.0f);
146       Vector4 objectPosition = nodeMatrix * position;
147       objectPosition /= objectPosition.w;
148
149       AABB.ConsiderNewPointInVolume(Vector3(objectPosition));
150     }
151   }
152
153   if(node->mCustomization)
154   {
155     if(!node->mChildren.empty())
156     {
157       auto                         choice = choices.Get(node->mCustomization->mTag);
158       Dali::Scene3D::Loader::Index i      = std::min(choice != Dali::Scene3D::Loader::Customization::NONE ? choice : 0, static_cast<Dali::Scene3D::Loader::Index>(node->mChildren.size() - 1));
159
160       AddModelTreeToAABB(AABB, scene, choices, node->mChildren[i], nodeParams, nodeMatrix);
161     }
162   }
163   else
164   {
165     for(auto i : node->mChildren)
166     {
167       AddModelTreeToAABB(AABB, scene, choices, i, nodeParams, nodeMatrix);
168     }
169   }
170 }
171
172 } // anonymous namespace
173
174 Model::Model(const std::string& modelUrl, const std::string& resourceDirectoryUrl)
175 : Control(ControlBehaviour(DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS)),
176   mModelUrl(modelUrl),
177   mResourceDirectoryUrl(resourceDirectoryUrl),
178   mModelRoot(),
179   mNaturalSize(Vector3::ZERO),
180   mModelPivot(AnchorPoint::CENTER),
181   mIblScaleFactor(1.0f),
182   mModelResourceReady(false),
183   mIBLResourceReady(true)
184 {
185 }
186
187 Model::~Model()
188 {
189 }
190
191 Dali::Scene3D::Model Model::New(const std::string& modelUrl, const std::string& resourceDirectoryUrl)
192 {
193   Model* impl = new Model(modelUrl, resourceDirectoryUrl);
194
195   Dali::Scene3D::Model handle = Dali::Scene3D::Model(*impl);
196
197   // Second-phase init of the implementation
198   // This can only be done after the CustomActor connection has been made...
199   impl->Initialize();
200
201   return handle;
202 }
203
204 const Actor Model::GetModelRoot() const
205 {
206   return mModelRoot;
207 }
208
209 void Model::SetImageBasedLightSource(const std::string& diffuseUrl, const std::string& specularUrl, float scaleFactor)
210 {
211   mIBLResourceReady = false;
212   Texture diffuseTexture  = Dali::Scene3D::Loader::LoadCubeMap(diffuseUrl);
213   Texture specularTexture = Dali::Scene3D::Loader::LoadCubeMap(specularUrl);
214   SetImageBasedLightTexture(diffuseTexture, specularTexture, scaleFactor);
215   mIBLResourceReady = true;
216
217   // If Model resource is already ready, then set resource ready.
218   // If Model resource is still not ready, wait for model resource ready.
219   if(IsResourceReady())
220   {
221     SetResourceReady(false);
222   }
223 }
224
225 void Model::SetImageBasedLightTexture(Dali::Texture diffuseTexture, Dali::Texture specularTexture, float scaleFactor)
226 {
227   if(diffuseTexture && specularTexture)
228   {
229     if(mDiffuseTexture != diffuseTexture || mSpecularTexture != specularTexture)
230     {
231       mDiffuseTexture  = diffuseTexture;
232       mSpecularTexture = specularTexture;
233       UpdateImageBasedLightTexture();
234     }
235     if(mIblScaleFactor != scaleFactor)
236     {
237       mIblScaleFactor = scaleFactor;
238       UpdateImageBasedLightScaleFactor();
239     }
240
241   }
242 }
243
244 void Model::SetImageBasedLightScaleFactor(float scaleFactor)
245 {
246   mIblScaleFactor = scaleFactor;
247   if(mDiffuseTexture && mSpecularTexture)
248   {
249     UpdateImageBasedLightScaleFactor();
250   }
251 }
252
253 float Model::GetImageBasedLightScaleFactor() const
254 {
255   return mIblScaleFactor;
256 }
257
258 uint32_t Model::GetAnimationCount() const
259 {
260   return mAnimations.size();
261 }
262
263 Dali::Animation Model::GetAnimation(uint32_t index) const
264 {
265   Dali::Animation animation;
266   if(mAnimations.size() > index)
267   {
268     animation = mAnimations[index].second;
269   }
270   return animation;
271 }
272
273 Dali::Animation Model::GetAnimation(const std::string& name) const
274 {
275   Dali::Animation animation;
276   if(!name.empty())
277   {
278     for(auto&& animationData : mAnimations)
279     {
280       if(animationData.first == name)
281       {
282         animation = animationData.second;
283         break;
284       }
285     }
286   }
287   return animation;
288 }
289
290 ///////////////////////////////////////////////////////////
291 //
292 // Private methods
293 //
294
295 void Model::OnSceneConnection(int depth)
296 {
297   if(!mModelRoot)
298   {
299     LoadModel();
300   }
301
302   Actor parent = Self().GetParent();
303   while(parent)
304   {
305     Scene3D::SceneView sceneView = Scene3D::SceneView::DownCast(parent);
306     if(sceneView)
307     {
308       GetImpl(sceneView).RegisterModel(Scene3D::Model::DownCast(Self()));
309       mParentSceneView = sceneView;
310       break;
311     }
312     parent = parent.GetParent();
313   }
314
315   Control::OnSceneConnection(depth);
316 }
317
318 void Model::OnSceneDisconnection()
319 {
320   Scene3D::SceneView sceneView = mParentSceneView.GetHandle();
321   if(sceneView)
322   {
323     GetImpl(sceneView).UnregisterModel(Scene3D::Model::DownCast(Self()));
324     mParentSceneView.Reset();
325   }
326   Control::OnSceneDisconnection();
327 }
328
329 Vector3 Model::GetNaturalSize()
330 {
331   if(!mModelRoot)
332   {
333     LoadModel();
334   }
335
336   return mNaturalSize;
337 }
338
339 float Model::GetHeightForWidth(float width)
340 {
341   Extents padding;
342   padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
343   return Control::GetHeightForWidth(width) + padding.top + padding.bottom;
344 }
345
346 float Model::GetWidthForHeight(float height)
347 {
348   Extents padding;
349   padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
350   return Control::GetWidthForHeight(height) + padding.start + padding.end;
351 }
352
353 void Model::OnRelayout(const Vector2& size, RelayoutContainer& container)
354 {
355   Control::OnRelayout(size, container);
356   ScaleModel();
357 }
358
359 bool Model::IsResourceReady() const
360 {
361   return mModelResourceReady && mIBLResourceReady;
362 }
363
364 void Model::LoadModel()
365 {
366   std::filesystem::path modelUrl(mModelUrl);
367   if(mResourceDirectoryUrl.empty())
368   {
369     mResourceDirectoryUrl = std::string(modelUrl.parent_path()) + "/";
370   }
371   std::string extension = modelUrl.extension();
372   std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
373
374   Dali::Scene3D::Loader::ResourceBundle::PathProvider pathProvider = [&](Dali::Scene3D::Loader::ResourceType::Value type) {
375     return mResourceDirectoryUrl;
376   };
377
378   Dali::Scene3D::Loader::ResourceBundle                        resources;
379   Dali::Scene3D::Loader::SceneDefinition                       scene;
380   std::vector<Dali::Scene3D::Loader::AnimationGroupDefinition> animGroups;
381   std::vector<Dali::Scene3D::Loader::CameraParameters>         cameraParameters;
382   std::vector<Dali::Scene3D::Loader::LightParameters>          lights;
383
384   std::vector<Dali::Scene3D::Loader::AnimationDefinition> animations;
385   animations.clear();
386
387   Dali::Scene3D::Loader::LoadResult output{resources, scene, animations, animGroups, cameraParameters, lights};
388
389   if(extension == DLI_EXTENSION)
390   {
391     Dali::Scene3D::Loader::DliLoader              loader;
392     Dali::Scene3D::Loader::DliLoader::InputParams input{
393       pathProvider(Dali::Scene3D::Loader::ResourceType::Mesh),
394       nullptr,
395       {},
396       {},
397       nullptr,
398       {}};
399     Dali::Scene3D::Loader::DliLoader::LoadParams loadParams{input, output};
400     if(!loader.LoadScene(mModelUrl, loadParams))
401     {
402       Dali::Scene3D::Loader::ExceptionFlinger(ASSERT_LOCATION) << "Failed to load scene from '" << mModelUrl << "': " << loader.GetParseError();
403     }
404   }
405   else if(extension == GLTF_EXTENSION)
406   {
407     Dali::Scene3D::Loader::ShaderDefinitionFactory sdf;
408     sdf.SetResources(resources);
409     Dali::Scene3D::Loader::LoadGltfScene(mModelUrl, sdf, output);
410
411     resources.mEnvironmentMaps.push_back({});
412   }
413   else
414   {
415     DALI_LOG_ERROR("Unsupported model type.\n");
416   }
417
418   Dali::Scene3D::Loader::Transforms                   xforms{Dali::Scene3D::Loader::MatrixStack{}, Dali::Scene3D::Loader::ViewProjection{}};
419   Dali::Scene3D::Loader::NodeDefinition::CreateParams nodeParams{resources, xforms, {}, {}, {}};
420   Dali::Scene3D::Loader::Customization::Choices       choices;
421
422   mModelRoot = Actor::New();
423
424   BoundingVolume AABB;
425   for(auto iRoot : scene.GetRoots())
426   {
427     auto resourceRefs = resources.CreateRefCounter();
428     scene.CountResourceRefs(iRoot, choices, resourceRefs);
429     resources.CountEnvironmentReferences(resourceRefs);
430
431     resources.LoadResources(resourceRefs, pathProvider);
432
433     // glTF Mesh is defined in right hand coordinate system, with positive Y for Up direction.
434     // Because DALi uses left hand system, Y direciton will be flipped for environment map sampling.
435     for(auto&& env : resources.mEnvironmentMaps)
436     {
437       env.first.mYDirection = Y_DIRECTION;
438     }
439
440     if(auto actor = scene.CreateNodes(iRoot, choices, nodeParams))
441     {
442       scene.ConfigureSkeletonJoints(iRoot, resources.mSkeletons, actor);
443       scene.ConfigureSkinningShaders(resources, actor, std::move(nodeParams.mSkinnables));
444       ConfigureBlendShapeShaders(resources, scene, actor, std::move(nodeParams.mBlendshapeRequests));
445
446       scene.ApplyConstraints(actor, std::move(nodeParams.mConstrainables));
447
448       mModelRoot.Add(actor);
449     }
450
451     AddModelTreeToAABB(AABB, scene, choices, iRoot, nodeParams, Matrix::IDENTITY);
452   }
453
454   if(!animations.empty())
455   {
456     auto getActor = [&](const std::string& name) {
457       return mModelRoot.FindChildByName(name);
458     };
459
460     mAnimations.clear();
461     for(auto&& animation : animations)
462     {
463       Dali::Animation anim = animation.ReAnimate(getActor);
464
465       mAnimations.push_back({animation.mName, anim});
466     }
467   }
468
469   mRenderableActors.clear();
470   CollectRenderableActor(mModelRoot);
471   UpdateImageBasedLightTexture();
472   UpdateImageBasedLightScaleFactor();
473
474   mNaturalSize = AABB.CalculateSize();
475   mModelPivot  = AABB.CalculatePivot();
476   mModelRoot.SetProperty(Dali::Actor::Property::SIZE, mNaturalSize);
477   Vector3 controlSize = Self().GetProperty<Vector3>(Dali::Actor::Property::SIZE);
478   if(controlSize.x == 0.0f || controlSize.y == 0.0f)
479   {
480     Self().SetProperty(Dali::Actor::Property::SIZE, mNaturalSize);
481   }
482
483   FitModelPosition();
484   ScaleModel();
485
486   Self().Add(mModelRoot);
487
488   Self().SetProperty(Dali::Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
489   Self().SetProperty(Dali::Actor::Property::ANCHOR_POINT, Vector3(mModelPivot.x, 1.0f - mModelPivot.y, mModelPivot.z));
490
491   mModelResourceReady = true;
492
493   Control::SetResourceReady(false);
494 }
495
496 void Model::ScaleModel()
497 {
498   if(mModelRoot)
499   {
500     float   scale = 1.0f;
501     Vector3 size  = Self().GetProperty<Vector3>(Dali::Actor::Property::SIZE);
502     if(size.x > 0.0f && size.y > 0.0f)
503     {
504       scale = MAXFLOAT;
505       scale = std::min(size.x / mNaturalSize.x, scale);
506       scale = std::min(size.y / mNaturalSize.y, scale);
507     }
508     // Models in glTF and dli are defined as right hand coordinate system.
509     // DALi uses left hand coordinate system. Scaling negative is for change winding order.
510     mModelRoot.SetProperty(Dali::Actor::Property::SCALE, Y_DIRECTION * scale);
511   }
512 }
513
514 void Model::FitModelPosition()
515 {
516   if(mModelRoot)
517   {
518     // Loaded model pivot is not the model center.
519     mModelRoot.SetProperty(Dali::Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
520     mModelRoot.SetProperty(Dali::Actor::Property::ANCHOR_POINT, Vector3::ONE - mModelPivot);
521   }
522 }
523
524 void Model::CollectRenderableActor(Actor actor)
525 {
526   uint32_t rendererCount = actor.GetRendererCount();
527   if(rendererCount)
528   {
529     mRenderableActors.push_back(actor);
530   }
531
532   uint32_t childrenCount = actor.GetChildCount();
533   for(uint32_t i = 0; i < childrenCount; ++i)
534   {
535     CollectRenderableActor(actor.GetChildAt(i));
536   }
537 }
538
539 void Model::UpdateImageBasedLightTexture()
540 {
541   if(!mDiffuseTexture || !mSpecularTexture)
542   {
543     return;
544   }
545
546   for(auto&& actor : mRenderableActors)
547   {
548     Actor renderableActor = actor.GetHandle();
549     if(renderableActor)
550     {
551       uint32_t rendererCount = renderableActor.GetRendererCount();
552       for(uint32_t i = 0; i < rendererCount; ++i)
553       {
554         Dali::Renderer renderer = renderableActor.GetRendererAt(i);
555         if(renderer)
556         {
557           Dali::TextureSet textures = renderer.GetTextures();
558           if(textures)
559           {
560             uint32_t textureCount = textures.GetTextureCount();
561             // EnvMap requires at least 2 texture, diffuse and specular
562             if(textureCount > 2u)
563             {
564               textures.SetTexture(textureCount - OFFSET_FOR_DIFFUSE_CUBE_TEXTURE, mDiffuseTexture);
565               textures.SetTexture(textureCount - OFFSET_FOR_SPECULAR_CUBE_TEXTURE, mSpecularTexture);
566             }
567           }
568         }
569       }
570     }
571   }
572 }
573
574 void Model::UpdateImageBasedLightScaleFactor()
575 {
576   if(!mDiffuseTexture || !mSpecularTexture)
577   {
578     return;
579   }
580   for(auto&& actor : mRenderableActors)
581   {
582     Actor renderableActor = actor.GetHandle();
583     if(renderableActor)
584     {
585       renderableActor.RegisterProperty(Dali::Scene3D::Loader::NodeDefinition::GetIblScaleFactorUniformName().data(), mIblScaleFactor);
586     }
587   }
588 }
589
590 } // namespace Internal
591 } // namespace Scene3D
592 } // namespace Dali