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/internal/event/events/hit-test-algorithm-impl.h>
22 #include <dali/integration-api/debug.h>
23 #include <dali/internal/event/actors/actor-impl.h>
24 #include <dali/internal/event/actors/camera-actor-impl.h>
25 #include <dali/internal/event/actors/layer-impl.h>
26 #include <dali/internal/event/actors/layer-list.h>
27 #include <dali/internal/event/common/projection.h>
28 #include <dali/internal/event/events/ray-test.h>
29 #include <dali/internal/event/render-tasks/render-task-impl.h>
30 #include <dali/internal/event/render-tasks/render-task-list-impl.h>
31 #include <dali/internal/event/rendering/renderer-impl.h>
32 #include <dali/public-api/actors/layer.h>
33 #include <dali/public-api/math/vector2.h>
34 #include <dali/public-api/math/vector4.h>
40 namespace HitTestAlgorithm
48 distance(std::numeric_limits<float>::max()),
49 depth(std::numeric_limits<int>::min())
53 Actor* actor; ///< The actor hit (if actor is hit, then this is initialised).
54 Vector2 hitPosition; ///< Position of hit (only valid if actor valid).
55 float distance; ///< Distance from ray origin to hit actor.
56 int32_t depth; ///< Depth index of this actor.
60 * Creates an Actor handle so that a HitTestFunction provided via the public API can be called.
62 struct HitTestFunctionWrapper : public HitTestInterface
67 * @param[in] func HitTestFunction to call with an Actor handle.
69 HitTestFunctionWrapper(Dali::HitTestAlgorithm::HitTestFunction func)
74 bool IsActorHittable(Actor* actor) override
76 return mFunc(Dali::Actor(actor), Dali::HitTestAlgorithm::CHECK_ACTOR);
79 bool DescendActorHierarchy(Actor* actor) override
81 return mFunc(Dali::Actor(actor), Dali::HitTestAlgorithm::DESCEND_ACTOR_TREE);
84 bool DoesLayerConsumeHit(Layer* layer) override
86 // Layer::IsTouchConsumed() focuses on touch only. Here we are a wrapper for the public-api
87 // where the caller may want to check for something completely different.
88 // TODO: Should provide a means to let caller decide. For now do not allow layers to consume
92 bool ActorRequiresHitResultCheck(Actor* actor, Integration::Point point, Vector2 hitPointLocal, uint32_t timeStamp) override
94 return actor->EmitHitTestResultSignal(point, hitPointLocal, timeStamp);
97 Dali::HitTestAlgorithm::HitTestFunction mFunc;
101 * Used in the hit-test algorithm to check whether the actor is touchable.
102 * It is used by the touch event processor.
104 struct ActorTouchableCheck : public HitTestInterface
106 bool IsActorHittable(Actor* actor) override
108 return (actor->GetTouchRequired() || actor->GetInterceptTouchRequired() || actor->IsTouchFocusable()) && // Does the Application or derived actor type require a touch event or a intercept touch event? or focusable by touch?
109 actor->IsHittable(); // Is actor sensitive, visible and on the scene?
112 bool DescendActorHierarchy(Actor* actor) override
114 return actor->IsVisible() && // Actor is visible, if not visible then none of its children are visible.
115 actor->IsSensitive(); // Actor is sensitive, if insensitive none of its children should be hittable either.
118 bool DoesLayerConsumeHit(Layer* layer) override
120 return layer->IsTouchConsumed();
123 bool ActorRequiresHitResultCheck(Actor* actor, Integration::Point point, Vector2 hitPointLocal, uint32_t timeStamp) override
125 return actor->EmitHitTestResultSignal(point, hitPointLocal, timeStamp);
130 * Check to see if the actor we're about to hit test is exclusively owned by another rendertask?
132 bool IsActorExclusiveToAnotherRenderTask(const Actor& actor,
133 const RenderTask& renderTask,
134 const RenderTaskList::ExclusivesContainer& exclusives)
137 if(exclusives.size())
139 for(const auto& exclusive : exclusives)
141 if((exclusive.renderTaskPtr != &renderTask) && (exclusive.actor.GetActor() == &actor))
151 * Recursively hit test all the actors, without crossing into other layers.
152 * This algorithm performs a Depth-First-Search (DFS) on all Actors within Layer.
153 * Hit-Testing each Actor, noting the distance from the Ray-Origin (3D origin
154 * of touch vector). The closest Hit-Tested Actor is that which is returned.
155 * Exceptions to this rule are:
156 * - When comparing against renderable parents, if Actor is the same distance
157 * or closer than it's renderable parent, then it takes priority.
159 HitActor HitTestWithinLayer(Actor& actor,
160 const RenderTask& renderTask,
161 const RenderTaskList::ExclusivesContainer& exclusives,
162 const Vector4& rayOrigin,
163 const Vector4& rayDir,
164 const float& nearClippingPlane,
165 const float& farClippingPlane,
166 HitTestInterface& hitCheck,
167 const bool& overlayed,
170 uint32_t clippingDepth,
171 uint32_t clippingBitPlaneMask,
172 const RayTest& rayTest,
173 const Integration::Point& point,
174 const uint32_t eventTime)
178 if(IsActorExclusiveToAnotherRenderTask(actor, renderTask, exclusives))
183 // For clipping, regardless of whether we have hit this actor or not,
184 // we increase the clipping depth if we have hit a clipping actor.
185 // This is used later to ensure all nested clipped children have hit
186 // all clipping actors also for them to be counted as hit.
187 uint32_t newClippingDepth = clippingDepth;
188 bool clippingActor = actor.GetClippingMode() != ClippingMode::DISABLED;
189 bool overlayedActor = overlayed || actor.IsOverlay();
195 // If we are a clipping actor or hittable...
196 if(clippingActor || hitCheck.IsActorHittable(&actor))
198 Vector3 size(actor.GetCurrentSize());
200 // Ensure the actor has a valid size.
201 // If so, perform a quick ray sphere test to see if our ray is close to the actor.
202 if(size.x > 0.0f && size.y > 0.0f && rayTest.SphereTest(actor, rayOrigin, rayDir))
204 Vector2 hitPointLocal;
207 // Finally, perform a more accurate ray test to see if our ray actually hits the actor.
208 if(rayTest.ActorTest(actor, rayOrigin, rayDir, hitPointLocal, distance))
210 // Calculate z coordinate value in Camera Space.
211 const Matrix& viewMatrix = renderTask.GetCameraActor()->GetViewMatrix();
212 const Vector4& hitDir = Vector4(rayDir.x * distance, rayDir.y * distance, rayDir.z * distance, 0.0f);
213 const float cameraDepthDistance = (viewMatrix * hitDir).z;
215 // Check if cameraDepthDistance is between clipping plane
216 if(cameraDepthDistance >= nearClippingPlane && cameraDepthDistance <= farClippingPlane)
218 // If the hit has happened on a clipping actor, then add this clipping depth to the mask of hit clipping depths.
219 // This mask shows all the actors that have been hit at different clipping depths.
222 clippingBitPlaneMask |= 1u << clippingDepth;
225 if(overlayHit && !overlayedActor)
227 // If we have already hit an overlay and current actor is not an overlay ignore current actor.
236 // At this point we have hit an actor.
237 // Now perform checks for clipping.
238 // Assume we have hit the actor first as if it is not clipped this would be the case.
239 bool haveHitActor = true;
241 // Check if we are performing clipping. IE. if any actors so far have clipping enabled - not necessarily this one.
242 // We can do this by checking the clipping depth has a value 1 or above.
243 if(newClippingDepth >= 1u)
245 // Now for us to count this actor as hit, we must have also hit
246 // all CLIPPING actors up to this point in the hierarchy as well.
247 // This information is stored in the clippingBitPlaneMask we updated above.
248 // Here we calculate a comparison mask by setting all the bits up to the current depth value.
249 // EG. a depth of 4 (10000 binary) = a mask of 1111 binary.
250 // This allows us a fast way of comparing all bits are set up to this depth.
251 // Note: If the current Actor has clipping, that is included in the depth mask too.
252 uint32_t clippingDepthMask = (1u << newClippingDepth) - 1u;
254 // The two masks must be equal to be a hit, as we are already assuming a hit
255 // (for non-clipping mode) then they must be not-equal to disqualify the hit.
256 if(clippingBitPlaneMask != clippingDepthMask)
258 haveHitActor = false;
262 // If CapturesAllTouchAfterStart() is true, it should be hit only after touchdown.
263 // If the touch moves after another actor has been touched so that the current actor is hit, it should behave as if it didn't hit.
264 if(actor.CapturesAllTouchAfterStart() && point.GetState() != PointState::STARTED)
266 haveHitActor = false;
269 // If the hit actor does not want to hit, the hit-test continues.
270 if(haveHitActor && hitCheck.ActorRequiresHitResultCheck(&actor, point, hitPointLocal, eventTime))
273 hit.hitPosition = hitPointLocal;
274 hit.distance = distance;
275 hit.depth = actor.GetSortingDepth();
277 if(actor.GetRendererCount() > 0)
279 //Get renderer with maximum depth
280 int rendererMaxDepth(actor.GetRendererAt(0).Get()->GetDepthIndex());
281 for(uint32_t i(1); i < actor.GetRendererCount(); ++i)
283 int depth = actor.GetRendererAt(i).Get()->GetDepthIndex();
284 if(depth > rendererMaxDepth)
286 rendererMaxDepth = depth;
289 hit.depth += rendererMaxDepth;
298 // Find a child hit, until we run out of actors in the current layer.
300 if(actor.GetChildCount() > 0)
302 childHit.distance = std::numeric_limits<float>::max();
303 childHit.depth = std::numeric_limits<int32_t>::min();
304 ActorContainer& children = actor.GetChildrenInternal();
306 // Hit test ALL children and calculate their distance.
307 bool parentIsRenderable = actor.IsRenderable();
309 for(ActorIter iter = children.begin(), endIter = children.end(); iter != endIter; ++iter)
311 // Descend tree only if...
312 if(!(*iter)->IsLayer() && // Child is NOT a layer, hit testing current layer only
313 (hitCheck.DescendActorHierarchy((*iter).Get()))) // We can descend into child hierarchy
315 HitActor currentHit(HitTestWithinLayer((*iter->Get()),
327 clippingBitPlaneMask,
332 // Make sure the set hit actor is actually hittable. This is usually required when we have some
333 // clipping as we need to hit-test all actors as we descend the tree regardless of whether they
334 // are hittable or not.
335 if(currentHit.actor && (!hitCheck.IsActorHittable(currentHit.actor)))
340 bool updateChildHit = false;
341 if(currentHit.distance >= 0.0f)
345 updateChildHit = ((currentHit.depth > childHit.depth) ||
346 ((currentHit.depth == childHit.depth) && (currentHit.distance < childHit.distance)));
350 updateChildHit = currentHit.depth >= childHit.depth;
356 if(!parentIsRenderable || currentHit.depth > hit.depth ||
357 (layerIs3d && (currentHit.depth == hit.depth && currentHit.distance < hit.distance)))
359 childHit = currentHit;
366 return (childHit.actor) ? childHit : hit;
370 * Return true if actor is sourceActor or a descendent of sourceActor
372 bool IsWithinSourceActors(const Actor& sourceActor, const Actor& actor)
374 if(&sourceActor == &actor)
379 Actor* parent = actor.GetParent();
382 return IsWithinSourceActors(sourceActor, *parent);
385 // Not within source actors
390 * Returns true if the layer and all of the layer's parents are visible and sensitive.
392 inline bool IsActuallyHittable(Layer& layer, const Vector2& screenCoordinates, const Vector2& stageSize, HitTestInterface& hitCheck)
396 if(layer.IsClipping())
398 ClippingBox box = layer.GetClippingBox();
400 if(screenCoordinates.x < static_cast<float>(box.x) ||
401 screenCoordinates.x > static_cast<float>(box.x + box.width) ||
402 screenCoordinates.y < stageSize.y - static_cast<float>(box.y + box.height) ||
403 screenCoordinates.y > stageSize.y - static_cast<float>(box.y))
405 // Not touchable if clipping is enabled in the layer and the screen coordinate is outside the clip region.
412 Actor* actor(&layer);
414 // Ensure that we can descend into the layer's (or any of its parent's) hierarchy.
415 while(actor && hittable)
417 if(!hitCheck.DescendActorHierarchy(actor))
422 actor = actor->GetParent();
430 * Gets the near and far clipping planes of the camera from which the scene is viewed in the render task.
432 void GetCameraClippingPlane(RenderTask& renderTask, float& nearClippingPlane, float& farClippingPlane)
434 CameraActor* cameraActor = renderTask.GetCameraActor();
435 nearClippingPlane = cameraActor->GetNearClippingPlane();
436 farClippingPlane = cameraActor->GetFarClippingPlane();
440 * Hit test a RenderTask
442 bool HitTestRenderTask(const RenderTaskList::ExclusivesContainer& exclusives,
443 const Vector2& sceneSize,
445 RenderTask& renderTask,
446 Vector2 screenCoordinates,
448 HitTestInterface& hitCheck,
449 const RayTest& rayTest)
451 if(renderTask.IsHittable(screenCoordinates))
454 renderTask.GetViewport(viewport);
455 if(screenCoordinates.x < static_cast<float>(viewport.x) ||
456 screenCoordinates.x > static_cast<float>(viewport.x + viewport.width) ||
457 screenCoordinates.y < static_cast<float>(viewport.y) ||
458 screenCoordinates.y > static_cast<float>(viewport.y + viewport.height))
460 // The screen coordinate is outside the viewport of render task. The viewport clips all layers.
464 float nearClippingPlane, farClippingPlane;
465 GetCameraClippingPlane(renderTask, nearClippingPlane, farClippingPlane);
467 // Determine the layer depth of the source actor
468 Actor* sourceActor(renderTask.GetSourceActor());
471 Dali::Layer layer(sourceActor->GetLayer());
474 const uint32_t sourceActorDepth(layer.GetProperty<bool>(Dali::Layer::Property::DEPTH));
476 CameraActor* cameraActor = renderTask.GetCameraActor();
477 bool pickingPossible = cameraActor->BuildPickingRay(
481 results.rayDirection);
487 // Hit test starting with the top layer, working towards the bottom layer.
489 bool overlayHit = false;
490 bool layerConsumesHit = false;
492 for(int32_t i = layers.GetLayerCount() - 1; i >= 0 && !(hit.actor); --i)
494 Layer* layer(layers.GetLayer(i));
497 // Ensure layer is touchable (also checks whether ancestors are also touchable)
498 if(IsActuallyHittable(*layer, screenCoordinates, sceneSize, hitCheck))
500 // Always hit-test the source actor; otherwise test whether the layer is below the source actor in the hierarchy
501 if(sourceActorDepth == static_cast<uint32_t>(i))
503 // Recursively hit test the source actor & children, without crossing into other layers.
504 hit = HitTestWithinLayer(*sourceActor,
508 results.rayDirection,
514 layer->GetBehavior() == Dali::Layer::LAYER_3D,
521 else if(IsWithinSourceActors(*sourceActor, *layer))
523 // Recursively hit test all the actors, without crossing into other layers.
524 hit = HitTestWithinLayer(*layer,
528 results.rayDirection,
534 layer->GetBehavior() == Dali::Layer::LAYER_3D,
542 // If this layer is set to consume the hit, then do not check any layers behind it
543 if(hitCheck.DoesLayerConsumeHit(layer))
545 layerConsumesHit = true;
553 results.renderTask = RenderTaskPtr(&renderTask);
554 results.actor = Dali::Actor(hit.actor);
555 results.actorCoordinates = hit.hitPosition;
557 return true; // Success
562 return true; // Also success if layer is consuming the hit
571 * Iterate through the RenderTaskList and perform hit testing.
573 * @param[in] sceneSize The scene size the tests will be performed in
574 * @param[in] layers The list of layers to test
575 * @param[in] taskList The list of render tasks
576 * @param[out] results Ray information calculated by the camera
577 * @param[in] hitCheck The hit testing interface object to use
578 * @param[in] onScreen True to test on-screen, false to test off-screen
579 * @return True if we have a hit, false otherwise
581 bool HitTestRenderTaskList(const Vector2& sceneSize,
583 RenderTaskList& taskList,
584 const Vector2& screenCoordinates,
586 HitTestInterface& hitCheck,
589 RenderTaskList::RenderTaskContainer& tasks = taskList.GetTasks();
590 RenderTaskList::RenderTaskContainer::reverse_iterator endIter = tasks.rend();
591 const auto& exclusives = taskList.GetExclusivesList();
594 for(RenderTaskList::RenderTaskContainer::reverse_iterator iter = tasks.rbegin(); endIter != iter; ++iter)
596 RenderTask& renderTask = *iter->Get();
597 const bool isOffscreenRenderTask = renderTask.GetFrameBuffer();
598 if((onScreen && isOffscreenRenderTask) || (!onScreen && !isOffscreenRenderTask))
603 if(HitTestRenderTask(exclusives, sceneSize, layers, renderTask, screenCoordinates, results, hitCheck, rayTest))
605 // Return true when an actor is hit (or layer in our render-task consumes the hit)
606 return true; // don't bother checking off screen tasks
614 * Iterate through the RenderTaskList and perform hit testing for both on-screen and off-screen.
616 * @param[in] sceneSize The scene size the tests will be performed in
617 * @param[in] layers The list of layers to test
618 * @param[in] taskList The list of render tasks
619 * @param[out] results Ray information calculated by the camera
620 * @param[in] hitCheck The hit testing interface object to use
621 * @param[in] onScreen True to test on-screen, false to test off-screen
622 * @return True if we have a hit, false otherwise
624 bool HitTestForEachRenderTask(const Vector2& sceneSize,
626 RenderTaskList& taskList,
627 const Vector2& screenCoordinates,
629 HitTestInterface& hitCheck)
633 // Check on-screen tasks before off-screen ones.
634 // Hit test order should be reverse of draw order (see ProcessRenderTasks() where off-screen tasks are drawn first).
635 if(HitTestRenderTaskList(sceneSize, layers, taskList, screenCoordinates, results, hitCheck, true) ||
636 HitTestRenderTaskList(sceneSize, layers, taskList, screenCoordinates, results, hitCheck, false))
645 } // unnamed namespace
647 HitTestInterface::~HitTestInterface() = default;
649 bool HitTest(const Vector2& sceneSize, RenderTaskList& taskList, LayerList& layerList, const Vector2& screenCoordinates, Dali::HitTestAlgorithm::Results& results, Dali::HitTestAlgorithm::HitTestFunction func)
652 // Hit-test the regular on-scene actors
653 Results hitTestResults;
654 HitTestFunctionWrapper hitTestFunctionWrapper(func);
655 if(HitTestForEachRenderTask(sceneSize, layerList, taskList, screenCoordinates, hitTestResults, hitTestFunctionWrapper))
657 results.actor = hitTestResults.actor;
658 results.actorCoordinates = hitTestResults.actorCoordinates;
664 bool HitTest(const Vector2& sceneSize, RenderTaskList& renderTaskList, LayerList& layerList, const Vector2& screenCoordinates, Results& results, HitTestInterface& hitTestInterface)
668 // Hit-test the regular on-scene actors
671 wasHit = HitTestForEachRenderTask(sceneSize, layerList, renderTaskList, screenCoordinates, results, hitTestInterface);
676 bool HitTest(const Vector2& sceneSize, RenderTaskList& renderTaskList, LayerList& layerList, const Vector2& screenCoordinates, Results& results)
678 ActorTouchableCheck actorTouchableCheck;
679 return HitTest(sceneSize, renderTaskList, layerList, screenCoordinates, results, actorTouchableCheck);
682 } // namespace HitTestAlgorithm
684 } // namespace Internal