2 * Copyright (c) 2022 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <dali-scene3d/internal/controls/model/model-impl.h>
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/devel-api/actors/actor-devel.h>
26 #include <dali/integration-api/debug.h>
27 #include <dali/public-api/object/type-registry-helper.h>
28 #include <dali/public-api/object/type-registry.h>
32 #include <dali-scene3d/internal/controls/scene-view/scene-view-impl.h>
33 #include <dali-scene3d/public-api/controls/model/model.h>
34 #include <dali-scene3d/public-api/loader/animation-definition.h>
35 #include <dali-scene3d/public-api/loader/camera-parameters.h>
36 #include <dali-scene3d/public-api/loader/cube-map-loader.h>
37 #include <dali-scene3d/public-api/loader/dli-loader.h>
38 #include <dali-scene3d/public-api/loader/gltf2-loader.h>
39 #include <dali-scene3d/public-api/loader/light-parameters.h>
40 #include <dali-scene3d/public-api/loader/load-result.h>
41 #include <dali-scene3d/public-api/loader/node-definition.h>
42 #include <dali-scene3d/public-api/loader/scene-definition.h>
43 #include <dali-scene3d/public-api/loader/shader-definition-factory.h>
57 return Scene3D::Model::New(std::string());
60 // Setup properties, signals and actions using the type-registry.
61 DALI_TYPE_REGISTRATION_BEGIN(Scene3D::Model, Toolkit::Control, Create);
62 DALI_TYPE_REGISTRATION_END()
64 static constexpr uint32_t OFFSET_FOR_DIFFUSE_CUBE_TEXTURE = 2u;
65 static constexpr uint32_t OFFSET_FOR_SPECULAR_CUBE_TEXTURE = 1u;
67 static constexpr Vector3 Y_DIRECTION(1.0f, -1.0f, 1.0f);
69 static constexpr bool DEFAULT_MODEL_CHILDREN_SENSITIVE = false;
71 static constexpr std::string_view KTX_EXTENSION = ".ktx";
72 static constexpr std::string_view OBJ_EXTENSION = ".obj";
73 static constexpr std::string_view GLTF_EXTENSION = ".gltf";
74 static constexpr std::string_view DLI_EXTENSION = ".dli";
80 pointMin = Vector3(std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max());
81 pointMax = Vector3(std::numeric_limits<float>::min(), std::numeric_limits<float>::min(), std::numeric_limits<float>::min());
84 void ConsiderNewPointInVolume(const Vector3& position)
86 pointMin.x = std::min(position.x, pointMin.x);
87 pointMin.y = std::min(position.y, pointMin.y);
88 pointMin.z = std::min(position.z, pointMin.z);
90 pointMax.x = std::max(position.x, pointMax.x);
91 pointMax.y = std::max(position.y, pointMax.y);
92 pointMax.z = std::max(position.z, pointMax.z);
95 Vector3 CalculateSize()
97 return pointMax - pointMin;
100 Vector3 CalculatePivot()
102 Vector3 pivot = pointMin / (pointMin - pointMax);
103 for(uint32_t i = 0; i < 3; ++i)
105 // To avoid divid by zero
106 if(pointMin[i] == pointMax[i])
118 void ConfigureBlendShapeShaders(
119 Dali::Scene3D::Loader::ResourceBundle& resources, const Dali::Scene3D::Loader::SceneDefinition& scene, Actor root, std::vector<Dali::Scene3D::Loader::BlendshapeShaderConfigurationRequest>&& requests)
121 std::vector<std::string> errors;
122 auto onError = [&errors](const std::string& msg) { errors.push_back(msg); };
123 if(!scene.ConfigureBlendshapeShaders(resources, root, std::move(requests), onError))
125 Dali::Scene3D::Loader::ExceptionFlinger flinger(ASSERT_LOCATION);
126 for(auto& msg : errors)
128 flinger << msg << '\n';
133 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)
135 static constexpr uint32_t BOX_POINT_COUNT = 8;
136 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}};
139 const Dali::Scene3D::Loader::NodeDefinition* node = scene.GetNode(iNode);
140 Matrix localMatrix = node->GetLocalSpace();
141 Matrix::Multiply(nodeMatrix, localMatrix, parentMatrix);
144 if(node->GetExtents(nodeParams.mResources, volume[0], volume[1]))
146 for(uint32_t i = 0; i < BOX_POINT_COUNT; ++i)
148 Vector4 position = Vector4(volume[BBIndex[i][0]].x, volume[BBIndex[i][1]].y, volume[BBIndex[i][2]].z, 1.0f);
149 Vector4 objectPosition = nodeMatrix * position;
150 objectPosition /= objectPosition.w;
152 AABB.ConsiderNewPointInVolume(Vector3(objectPosition));
156 if(node->mCustomization)
158 if(!node->mChildren.empty())
160 auto choice = choices.Get(node->mCustomization->mTag);
161 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));
163 AddModelTreeToAABB(AABB, scene, choices, node->mChildren[i], nodeParams, nodeMatrix);
168 for(auto i : node->mChildren)
170 AddModelTreeToAABB(AABB, scene, choices, i, nodeParams, nodeMatrix);
175 } // anonymous namespace
177 Model::Model(const std::string& modelUrl, const std::string& resourceDirectoryUrl)
178 : Control(ControlBehaviour(DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS)),
180 mResourceDirectoryUrl(resourceDirectoryUrl),
182 mNaturalSize(Vector3::ZERO),
183 mModelPivot(AnchorPoint::CENTER),
184 mSceneIblScaleFactor(1.0f),
185 mIblScaleFactor(1.0f),
186 mModelChildrenSensitive(DEFAULT_MODEL_CHILDREN_SENSITIVE),
187 mModelResourceReady(false),
188 mIBLResourceReady(true)
196 Dali::Scene3D::Model Model::New(const std::string& modelUrl, const std::string& resourceDirectoryUrl)
198 Model* impl = new Model(modelUrl, resourceDirectoryUrl);
200 Dali::Scene3D::Model handle = Dali::Scene3D::Model(*impl);
202 // Second-phase init of the implementation
203 // This can only be done after the CustomActor connection has been made...
209 const Actor Model::GetModelRoot() const
214 void Model::SetChildrenSensitive(bool enable)
216 if(mModelChildrenSensitive != enable)
218 mModelChildrenSensitive = enable;
221 mModelRoot.SetProperty(Dali::Actor::Property::SENSITIVE, mModelChildrenSensitive);
226 bool Model::GetChildrenSensitive() const
228 return mModelChildrenSensitive;
231 void Model::SetImageBasedLightSource(const std::string& diffuseUrl, const std::string& specularUrl, float scaleFactor)
233 mIBLResourceReady = false;
234 Texture diffuseTexture = (!diffuseUrl.empty()) ? Dali::Scene3D::Loader::LoadCubeMap(diffuseUrl) : Texture();
235 Texture specularTexture = (!specularUrl.empty()) ? Dali::Scene3D::Loader::LoadCubeMap(specularUrl) : Texture();
236 SetImageBasedLightTexture(diffuseTexture, specularTexture, scaleFactor);
237 mIBLResourceReady = true;
239 // If Model resource is already ready, then set resource ready.
240 // If Model resource is still not ready, wait for model resource ready.
241 if(IsResourceReady())
243 SetResourceReady(false);
247 void Model::SetImageBasedLightTexture(Dali::Texture diffuseTexture, Dali::Texture specularTexture, float scaleFactor)
249 // If input texture is wrong, Model is rendered with SceneView's IBL.
250 if(mDiffuseTexture != diffuseTexture || mSpecularTexture != specularTexture)
252 mDiffuseTexture = diffuseTexture;
253 mSpecularTexture = specularTexture;
254 mIblScaleFactor = scaleFactor;
255 UpdateImageBasedLightTexture();
259 void Model::SetImageBasedLightScaleFactor(float scaleFactor)
261 mIblScaleFactor = scaleFactor;
262 if(mDiffuseTexture && mSpecularTexture)
264 UpdateImageBasedLightScaleFactor();
268 float Model::GetImageBasedLightScaleFactor() const
270 return mIblScaleFactor;
273 uint32_t Model::GetAnimationCount() const
275 return mAnimations.size();
278 Dali::Animation Model::GetAnimation(uint32_t index) const
280 Dali::Animation animation;
281 if(mAnimations.size() > index)
283 animation = mAnimations[index].second;
288 Dali::Animation Model::GetAnimation(const std::string& name) const
290 Dali::Animation animation;
293 for(auto&& animationData : mAnimations)
295 if(animationData.first == name)
297 animation = animationData.second;
305 ///////////////////////////////////////////////////////////
310 void Model::OnSceneConnection(int depth)
317 Actor parent = Self().GetParent();
320 Scene3D::SceneView sceneView = Scene3D::SceneView::DownCast(parent);
323 GetImpl(sceneView).RegisterSceneItem(this);
324 mParentSceneView = sceneView;
327 parent = parent.GetParent();
330 Control::OnSceneConnection(depth);
333 void Model::OnSceneDisconnection()
335 Scene3D::SceneView sceneView = mParentSceneView.GetHandle();
338 GetImpl(sceneView).UnregisterSceneItem(this);
339 mParentSceneView.Reset();
341 Control::OnSceneDisconnection();
344 Vector3 Model::GetNaturalSize()
354 float Model::GetHeightForWidth(float width)
357 padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
358 return Control::GetHeightForWidth(width) + padding.top + padding.bottom;
361 float Model::GetWidthForHeight(float height)
364 padding = Self().GetProperty<Extents>(Toolkit::Control::Property::PADDING);
365 return Control::GetWidthForHeight(height) + padding.start + padding.end;
368 void Model::OnRelayout(const Vector2& size, RelayoutContainer& container)
370 Control::OnRelayout(size, container);
374 bool Model::IsResourceReady() const
376 return mModelResourceReady && mIBLResourceReady;
379 void Model::LoadModel()
381 std::filesystem::path modelUrl(mModelUrl);
382 if(mResourceDirectoryUrl.empty())
384 mResourceDirectoryUrl = std::string(modelUrl.parent_path()) + "/";
386 std::string extension = modelUrl.extension();
387 std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
389 Dali::Scene3D::Loader::ResourceBundle::PathProvider pathProvider = [&](Dali::Scene3D::Loader::ResourceType::Value type) {
390 return mResourceDirectoryUrl;
393 Dali::Scene3D::Loader::ResourceBundle resources;
394 Dali::Scene3D::Loader::SceneDefinition scene;
395 std::vector<Dali::Scene3D::Loader::AnimationGroupDefinition> animGroups;
396 std::vector<Dali::Scene3D::Loader::CameraParameters> cameraParameters;
397 std::vector<Dali::Scene3D::Loader::LightParameters> lights;
399 std::vector<Dali::Scene3D::Loader::AnimationDefinition> animations;
402 Dali::Scene3D::Loader::LoadResult output{resources, scene, animations, animGroups, cameraParameters, lights};
404 if(extension == DLI_EXTENSION)
406 Dali::Scene3D::Loader::DliLoader loader;
407 Dali::Scene3D::Loader::DliLoader::InputParams input{
408 pathProvider(Dali::Scene3D::Loader::ResourceType::Mesh),
414 Dali::Scene3D::Loader::DliLoader::LoadParams loadParams{input, output};
415 if(!loader.LoadScene(mModelUrl, loadParams))
417 Dali::Scene3D::Loader::ExceptionFlinger(ASSERT_LOCATION) << "Failed to load scene from '" << mModelUrl << "': " << loader.GetParseError();
420 else if(extension == GLTF_EXTENSION)
422 Dali::Scene3D::Loader::ShaderDefinitionFactory sdf;
423 sdf.SetResources(resources);
424 Dali::Scene3D::Loader::LoadGltfScene(mModelUrl, sdf, output);
426 resources.mEnvironmentMaps.push_back({});
430 DALI_LOG_ERROR("Unsupported model type.\n");
433 Dali::Scene3D::Loader::Transforms xforms{Dali::Scene3D::Loader::MatrixStack{}, Dali::Scene3D::Loader::ViewProjection{}};
434 Dali::Scene3D::Loader::NodeDefinition::CreateParams nodeParams{resources, xforms, {}, {}, {}};
435 Dali::Scene3D::Loader::Customization::Choices choices;
437 mModelRoot = Actor::New();
440 for(auto iRoot : scene.GetRoots())
442 auto resourceRefs = resources.CreateRefCounter();
443 scene.CountResourceRefs(iRoot, choices, resourceRefs);
444 resources.CountEnvironmentReferences(resourceRefs);
446 resources.LoadResources(resourceRefs, pathProvider);
448 // glTF Mesh is defined in right hand coordinate system, with positive Y for Up direction.
449 // Because DALi uses left hand system, Y direciton will be flipped for environment map sampling.
450 for(auto&& env : resources.mEnvironmentMaps)
452 env.first.mYDirection = Y_DIRECTION;
455 if(auto actor = scene.CreateNodes(iRoot, choices, nodeParams))
457 scene.ConfigureSkeletonJoints(iRoot, resources.mSkeletons, actor);
458 scene.ConfigureSkinningShaders(resources, actor, std::move(nodeParams.mSkinnables));
459 ConfigureBlendShapeShaders(resources, scene, actor, std::move(nodeParams.mBlendshapeRequests));
461 scene.ApplyConstraints(actor, std::move(nodeParams.mConstrainables));
463 mModelRoot.Add(actor);
466 AddModelTreeToAABB(AABB, scene, choices, iRoot, nodeParams, Matrix::IDENTITY);
469 if(!resources.mEnvironmentMaps.empty())
471 mDefaultDiffuseTexture = resources.mEnvironmentMaps.front().second.mDiffuse;
472 mDefaultSpecularTexture = resources.mEnvironmentMaps.front().second.mSpecular;
475 if(!animations.empty())
477 auto getActor = [&](const std::string& name) {
478 return mModelRoot.FindChildByName(name);
482 for(auto&& animation : animations)
484 Dali::Animation anim = animation.ReAnimate(getActor);
486 mAnimations.push_back({animation.mName, anim});
490 mRenderableActors.clear();
491 CollectRenderableActor(mModelRoot);
492 UpdateImageBasedLightTexture();
493 UpdateImageBasedLightScaleFactor();
495 mNaturalSize = AABB.CalculateSize();
496 mModelPivot = AABB.CalculatePivot();
497 mModelRoot.SetProperty(Dali::Actor::Property::SIZE, mNaturalSize);
498 Vector3 controlSize = Self().GetProperty<Vector3>(Dali::Actor::Property::SIZE);
499 if(controlSize.x == 0.0f || controlSize.y == 0.0f)
501 Self().SetProperty(Dali::Actor::Property::SIZE, mNaturalSize);
507 mModelRoot.SetProperty(Dali::Actor::Property::SENSITIVE, mModelChildrenSensitive);
509 Self().Add(mModelRoot);
511 Self().SetProperty(Dali::Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
512 Self().SetProperty(Dali::Actor::Property::ANCHOR_POINT, Vector3(mModelPivot.x, 1.0f - mModelPivot.y, mModelPivot.z));
514 mModelResourceReady = true;
516 Control::SetResourceReady(false);
519 void Model::ScaleModel()
524 Vector3 size = Self().GetProperty<Vector3>(Dali::Actor::Property::SIZE);
525 if(size.x > 0.0f && size.y > 0.0f)
528 scale = std::min(size.x / mNaturalSize.x, scale);
529 scale = std::min(size.y / mNaturalSize.y, scale);
531 // Models in glTF and dli are defined as right hand coordinate system.
532 // DALi uses left hand coordinate system. Scaling negative is for change winding order.
533 mModelRoot.SetProperty(Dali::Actor::Property::SCALE, Y_DIRECTION * scale);
537 void Model::FitModelPosition()
541 // Loaded model pivot is not the model center.
542 mModelRoot.SetProperty(Dali::Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
543 mModelRoot.SetProperty(Dali::Actor::Property::ANCHOR_POINT, Vector3::ONE - mModelPivot);
547 void Model::CollectRenderableActor(Actor actor)
549 uint32_t rendererCount = actor.GetRendererCount();
552 mRenderableActors.push_back(actor);
555 uint32_t childrenCount = actor.GetChildCount();
556 for(uint32_t i = 0; i < childrenCount; ++i)
558 CollectRenderableActor(actor.GetChildAt(i));
562 void Model::UpdateImageBasedLightTexture()
564 Dali::Texture currentDiffuseTexture = (mDiffuseTexture) ? mDiffuseTexture : mSceneDiffuseTexture;
565 Dali::Texture currentSpecularTexture = (mSpecularTexture) ? mSpecularTexture : mSceneSpecularTexture;
566 float currentIBLScaleFactor = (mDiffuseTexture && mSpecularTexture) ? mIblScaleFactor : mSceneIblScaleFactor;
567 if(!currentDiffuseTexture || !currentSpecularTexture)
569 currentDiffuseTexture = mDefaultDiffuseTexture;
570 currentSpecularTexture = mDefaultSpecularTexture;
571 currentIBLScaleFactor = Dali::Scene3D::Loader::EnvironmentDefinition::GetDefaultIntensity();
574 for(auto&& actor : mRenderableActors)
576 Actor renderableActor = actor.GetHandle();
579 uint32_t rendererCount = renderableActor.GetRendererCount();
580 for(uint32_t i = 0; i < rendererCount; ++i)
582 Dali::Renderer renderer = renderableActor.GetRendererAt(i);
585 Dali::TextureSet textures = renderer.GetTextures();
588 uint32_t textureCount = textures.GetTextureCount();
589 // EnvMap requires at least 2 texture, diffuse and specular
590 if(textureCount > 2u)
592 textures.SetTexture(textureCount - OFFSET_FOR_DIFFUSE_CUBE_TEXTURE, currentDiffuseTexture);
593 textures.SetTexture(textureCount - OFFSET_FOR_SPECULAR_CUBE_TEXTURE, currentSpecularTexture);
598 renderableActor.RegisterProperty(Dali::Scene3D::Loader::NodeDefinition::GetIblScaleFactorUniformName().data(), currentIBLScaleFactor);
603 void Model::UpdateImageBasedLightScaleFactor()
605 if((!mDiffuseTexture || !mSpecularTexture) &&
606 (!mSceneDiffuseTexture || !mSceneSpecularTexture))
611 float currentIBLScaleFactor = (mDiffuseTexture && mSpecularTexture) ? mIblScaleFactor : mSceneIblScaleFactor;
612 for(auto&& actor : mRenderableActors)
614 Actor renderableActor = actor.GetHandle();
617 renderableActor.RegisterProperty(Dali::Scene3D::Loader::NodeDefinition::GetIblScaleFactorUniformName().data(), currentIBLScaleFactor);
622 void Model::NotifyImageBasedLightTexture(Dali::Texture diffuseTexture, Dali::Texture specularTexture, float scaleFactor)
624 if(mSceneDiffuseTexture != diffuseTexture || mSceneSpecularTexture != specularTexture)
626 mSceneDiffuseTexture = diffuseTexture;
627 mSceneSpecularTexture = specularTexture;
628 mSceneIblScaleFactor = scaleFactor;
629 UpdateImageBasedLightTexture();
633 void Model::NotifyImageBasedLightScaleFactor(float scaleFactor)
635 mSceneIblScaleFactor = scaleFactor;
636 if(mSceneDiffuseTexture && mSceneSpecularTexture)
638 UpdateImageBasedLightScaleFactor();
642 } // namespace Internal
643 } // namespace Scene3D