2 * Copyright (c) 2021 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 Dali::HitTestAlgorithm::HitTestFunction mFunc;
96 * Used in the hit-test algorithm to check whether the actor is touchable.
97 * It is used by the touch event processor.
99 struct ActorTouchableCheck : public HitTestInterface
101 bool IsActorHittable(Actor* actor) override
103 return (actor->GetTouchRequired() || actor->IsTouchFocusable()) && // Does the Application or derived actor type require a touch event? or focusable by touch?
104 actor->IsHittable(); // Is actor sensitive, visible and on the scene?
107 bool DescendActorHierarchy(Actor* actor) override
109 return actor->IsVisible() && // Actor is visible, if not visible then none of its children are visible.
110 actor->IsSensitive(); // Actor is sensitive, if insensitive none of its children should be hittable either.
113 bool DoesLayerConsumeHit(Layer* layer) override
115 return layer->IsTouchConsumed();
120 * Check to see if the actor we're about to hit test is exclusively owned by another rendertask?
122 bool IsActorExclusiveToAnotherRenderTask(const Actor& actor,
123 const RenderTask& renderTask,
124 const RenderTaskList::ExclusivesContainer& exclusives)
127 if(exclusives.size())
129 for(const auto& exclusive : exclusives)
131 if((exclusive.renderTaskPtr != &renderTask) && (exclusive.actor.GetActor() == &actor))
141 * Recursively hit test all the actors, without crossing into other layers.
142 * This algorithm performs a Depth-First-Search (DFS) on all Actors within Layer.
143 * Hit-Testing each Actor, noting the distance from the Ray-Origin (3D origin
144 * of touch vector). The closest Hit-Tested Actor is that which is returned.
145 * Exceptions to this rule are:
146 * - When comparing against renderable parents, if Actor is the same distance
147 * or closer than it's renderable parent, then it takes priority.
149 HitActor HitTestWithinLayer(Actor& actor,
150 const RenderTask& renderTask,
151 const RenderTaskList::ExclusivesContainer& exclusives,
152 const Vector4& rayOrigin,
153 const Vector4& rayDir,
154 float& nearClippingPlane,
155 float& farClippingPlane,
156 HitTestInterface& hitCheck,
159 uint32_t clippingDepth,
160 uint32_t clippingBitPlaneMask,
161 const RayTest& rayTest)
165 if(IsActorExclusiveToAnotherRenderTask(actor, renderTask, exclusives))
170 // For clipping, regardless of whether we have hit this actor or not,
171 // we increase the clipping depth if we have hit a clipping actor.
172 // This is used later to ensure all nested clipped children have hit
173 // all clipping actors also for them to be counted as hit.
174 uint32_t newClippingDepth = clippingDepth;
175 bool clippingActor = actor.GetClippingMode() != ClippingMode::DISABLED;
181 // If we are a clipping actor or hittable...
182 if(clippingActor || hitCheck.IsActorHittable(&actor))
184 Vector3 size(actor.GetCurrentSize());
186 // Ensure the actor has a valid size.
187 // If so, perform a quick ray sphere test to see if our ray is close to the actor.
188 if(size.x > 0.0f && size.y > 0.0f && rayTest.SphereTest(actor, rayOrigin, rayDir))
190 Vector2 hitPointLocal;
193 // Finally, perform a more accurate ray test to see if our ray actually hits the actor.
194 if(rayTest.ActorTest(actor, rayOrigin, rayDir, hitPointLocal, distance))
196 if(distance >= nearClippingPlane && distance <= farClippingPlane)
198 // If the hit has happened on a clipping actor, then add this clipping depth to the mask of hit clipping depths.
199 // This mask shows all the actors that have been hit at different clipping depths.
202 clippingBitPlaneMask |= 1u << clippingDepth;
205 if(overlayHit && !actor.IsOverlay())
207 // If we have already hit an overlay and current actor is not an overlay ignore current actor.
211 if(actor.IsOverlay())
216 // At this point we have hit an actor.
217 // Now perform checks for clipping.
218 // Assume we have hit the actor first as if it is not clipped this would be the case.
219 bool haveHitActor = true;
221 // Check if we are performing clipping. IE. if any actors so far have clipping enabled - not necessarily this one.
222 // We can do this by checking the clipping depth has a value 1 or above.
223 if(newClippingDepth >= 1u)
225 // Now for us to count this actor as hit, we must have also hit
226 // all CLIPPING actors up to this point in the hierarchy as well.
227 // This information is stored in the clippingBitPlaneMask we updated above.
228 // Here we calculate a comparison mask by setting all the bits up to the current depth value.
229 // EG. a depth of 4 (10000 binary) = a mask of 1111 binary.
230 // This allows us a fast way of comparing all bits are set up to this depth.
231 // Note: If the current Actor has clipping, that is included in the depth mask too.
232 uint32_t clippingDepthMask = (1u << newClippingDepth) - 1u;
234 // The two masks must be equal to be a hit, as we are already assuming a hit
235 // (for non-clipping mode) then they must be not-equal to disqualify the hit.
236 if(clippingBitPlaneMask != clippingDepthMask)
238 haveHitActor = false;
245 hit.hitPosition = hitPointLocal;
246 hit.distance = distance;
247 hit.depth = actor.GetSortingDepth();
249 if(actor.GetRendererCount() > 0)
251 //Get renderer with maximum depth
252 int rendererMaxDepth(actor.GetRendererAt(0).Get()->GetDepthIndex());
253 for(uint32_t i(1); i < actor.GetRendererCount(); ++i)
255 int depth = actor.GetRendererAt(i).Get()->GetDepthIndex();
256 if(depth > rendererMaxDepth)
258 rendererMaxDepth = depth;
261 hit.depth += rendererMaxDepth;
270 // Find a child hit, until we run out of actors in the current layer.
272 if(actor.GetChildCount() > 0)
274 childHit.distance = std::numeric_limits<float>::max();
275 childHit.depth = std::numeric_limits<int32_t>::min();
276 ActorContainer& children = actor.GetChildrenInternal();
278 // Hit test ALL children and calculate their distance.
279 bool parentIsRenderable = actor.IsRenderable();
281 for(ActorIter iter = children.begin(), endIter = children.end(); iter != endIter; ++iter)
283 // Descend tree only if...
284 if(!(*iter)->IsLayer() && // Child is NOT a layer, hit testing current layer only
285 (hitCheck.DescendActorHierarchy((*iter).Get()))) // We can descend into child hierarchy
287 HitActor currentHit(HitTestWithinLayer((*iter->Get()),
298 clippingBitPlaneMask,
301 // Make sure the set hit actor is actually hittable. This is usually required when we have some
302 // clipping as we need to hit-test all actors as we descend the tree regardless of whether they
303 // are hittable or not.
304 if(currentHit.actor && !hitCheck.IsActorHittable(currentHit.actor))
309 bool updateChildHit = false;
310 if(currentHit.distance >= 0.0f)
314 updateChildHit = ((currentHit.depth > childHit.depth) ||
315 ((currentHit.depth == childHit.depth) && (currentHit.distance < childHit.distance)));
319 updateChildHit = currentHit.depth >= childHit.depth;
325 if(!parentIsRenderable || currentHit.depth > hit.depth ||
326 (layerIs3d && (currentHit.depth == hit.depth && currentHit.distance < hit.distance)))
328 childHit = currentHit;
335 return (childHit.actor) ? childHit : hit;
339 * Return true if actor is sourceActor or a descendent of sourceActor
341 bool IsWithinSourceActors(const Actor& sourceActor, const Actor& actor)
343 if(&sourceActor == &actor)
348 Actor* parent = actor.GetParent();
351 return IsWithinSourceActors(sourceActor, *parent);
354 // Not within source actors
359 * Returns true if the layer and all of the layer's parents are visible and sensitive.
361 inline bool IsActuallyHittable(Layer& layer, const Vector2& screenCoordinates, const Vector2& stageSize, HitTestInterface& hitCheck)
365 if(layer.IsClipping())
367 ClippingBox box = layer.GetClippingBox();
369 if(screenCoordinates.x < static_cast<float>(box.x) ||
370 screenCoordinates.x > static_cast<float>(box.x + box.width) ||
371 screenCoordinates.y < stageSize.y - static_cast<float>(box.y + box.height) ||
372 screenCoordinates.y > stageSize.y - static_cast<float>(box.y))
374 // Not touchable if clipping is enabled in the layer and the screen coordinate is outside the clip region.
381 Actor* actor(&layer);
383 // Ensure that we can descend into the layer's (or any of its parent's) hierarchy.
384 while(actor && hittable)
386 if(!hitCheck.DescendActorHierarchy(actor))
391 actor = actor->GetParent();
399 * Gets the near and far clipping planes of the camera from which the scene is viewed in the render task.
401 void GetCameraClippingPlane(RenderTask& renderTask, float& nearClippingPlane, float& farClippingPlane)
403 CameraActor* cameraActor = renderTask.GetCameraActor();
404 nearClippingPlane = cameraActor->GetNearClippingPlane();
405 farClippingPlane = cameraActor->GetFarClippingPlane();
409 * Hit test a RenderTask
411 bool HitTestRenderTask(const RenderTaskList::ExclusivesContainer& exclusives,
412 const Vector2& sceneSize,
414 RenderTask& renderTask,
415 Vector2 screenCoordinates,
417 HitTestInterface& hitCheck,
418 const RayTest& rayTest)
420 if(renderTask.IsHittable(screenCoordinates))
423 renderTask.GetViewport(viewport);
424 if(screenCoordinates.x < static_cast<float>(viewport.x) ||
425 screenCoordinates.x > static_cast<float>(viewport.x + viewport.width) ||
426 screenCoordinates.y < static_cast<float>(viewport.y) ||
427 screenCoordinates.y > static_cast<float>(viewport.y + viewport.height))
429 // The screen coordinate is outside the viewport of render task. The viewport clips all layers.
433 float nearClippingPlane, farClippingPlane;
434 GetCameraClippingPlane(renderTask, nearClippingPlane, farClippingPlane);
436 // Determine the layer depth of the source actor
437 Actor* sourceActor(renderTask.GetSourceActor());
440 Dali::Layer layer(sourceActor->GetLayer());
443 const uint32_t sourceActorDepth(layer.GetProperty<bool>(Dali::Layer::Property::DEPTH));
445 CameraActor* cameraActor = renderTask.GetCameraActor();
446 bool pickingPossible = cameraActor->BuildPickingRay(
450 results.rayDirection);
456 // Hit test starting with the top layer, working towards the bottom layer.
458 bool overlayHit = false;
459 bool layerConsumesHit = false;
461 for(int32_t i = layers.GetLayerCount() - 1; i >= 0 && !(hit.actor); --i)
463 Layer* layer(layers.GetLayer(i));
466 // Ensure layer is touchable (also checks whether ancestors are also touchable)
467 if(IsActuallyHittable(*layer, screenCoordinates, sceneSize, hitCheck))
469 // Always hit-test the source actor; otherwise test whether the layer is below the source actor in the hierarchy
470 if(sourceActorDepth == static_cast<uint32_t>(i))
472 // Recursively hit test the source actor & children, without crossing into other layers.
473 hit = HitTestWithinLayer(*sourceActor,
477 results.rayDirection,
482 layer->GetBehavior() == Dali::Layer::LAYER_3D,
487 else if(IsWithinSourceActors(*sourceActor, *layer))
489 // Recursively hit test all the actors, without crossing into other layers.
490 hit = HitTestWithinLayer(*layer,
494 results.rayDirection,
499 layer->GetBehavior() == Dali::Layer::LAYER_3D,
505 // If this layer is set to consume the hit, then do not check any layers behind it
506 if(hitCheck.DoesLayerConsumeHit(layer))
508 layerConsumesHit = true;
516 results.renderTask = RenderTaskPtr(&renderTask);
517 results.actor = Dali::Actor(hit.actor);
518 results.actorCoordinates = hit.hitPosition;
520 return true; // Success
525 return true; // Also success if layer is consuming the hit
534 * Iterate through the RenderTaskList and perform hit testing.
536 * @param[in] sceneSize The scene size the tests will be performed in
537 * @param[in] layers The list of layers to test
538 * @param[in] taskList The list of render tasks
539 * @param[out] results Ray information calculated by the camera
540 * @param[in] hitCheck The hit testing interface object to use
541 * @param[in] onScreen True to test on-screen, false to test off-screen
542 * @return True if we have a hit, false otherwise
544 bool HitTestRenderTaskList(const Vector2& sceneSize,
546 RenderTaskList& taskList,
547 const Vector2& screenCoordinates,
549 HitTestInterface& hitCheck,
552 RenderTaskList::RenderTaskContainer& tasks = taskList.GetTasks();
553 RenderTaskList::RenderTaskContainer::reverse_iterator endIter = tasks.rend();
554 const auto& exclusives = taskList.GetExclusivesList();
557 for(RenderTaskList::RenderTaskContainer::reverse_iterator iter = tasks.rbegin(); endIter != iter; ++iter)
559 RenderTask& renderTask = *iter->Get();
560 const bool isOffscreenRenderTask = renderTask.GetFrameBuffer();
561 if((onScreen && isOffscreenRenderTask) || (!onScreen && !isOffscreenRenderTask))
567 if(HitTestRenderTask(exclusives, sceneSize, layers, renderTask, screenCoordinates, results, hitCheck, rayTest))
569 // Return true when an actor is hit (or layer in our render-task consumes the hit)
570 return true; // don't bother checking off screen tasks
578 * Iterate through the RenderTaskList and perform hit testing for both on-screen and off-screen.
580 * @param[in] sceneSize The scene size the tests will be performed in
581 * @param[in] layers The list of layers to test
582 * @param[in] taskList The list of render tasks
583 * @param[out] results Ray information calculated by the camera
584 * @param[in] hitCheck The hit testing interface object to use
585 * @param[in] onScreen True to test on-screen, false to test off-screen
586 * @return True if we have a hit, false otherwise
588 bool HitTestForEachRenderTask(const Vector2& sceneSize,
590 RenderTaskList& taskList,
591 const Vector2& screenCoordinates,
593 HitTestInterface& hitCheck)
597 // Check on-screen tasks before off-screen ones.
598 // Hit test order should be reverse of draw order (see ProcessRenderTasks() where off-screen tasks are drawn first).
599 if(HitTestRenderTaskList(sceneSize, layers, taskList, screenCoordinates, results, hitCheck, true) ||
600 HitTestRenderTaskList(sceneSize, layers, taskList, screenCoordinates, results, hitCheck, false))
609 } // unnamed namespace
611 HitTestInterface::~HitTestInterface() = default;
613 bool HitTest(const Vector2& sceneSize, RenderTaskList& taskList, LayerList& layerList, const Vector2& screenCoordinates, Dali::HitTestAlgorithm::Results& results, Dali::HitTestAlgorithm::HitTestFunction func)
616 // Hit-test the regular on-scene actors
617 Results hitTestResults;
618 HitTestFunctionWrapper hitTestFunctionWrapper(func);
619 if(HitTestForEachRenderTask(sceneSize, layerList, taskList, screenCoordinates, hitTestResults, hitTestFunctionWrapper))
621 results.actor = hitTestResults.actor;
622 results.actorCoordinates = hitTestResults.actorCoordinates;
628 bool HitTest(const Vector2& sceneSize, RenderTaskList& renderTaskList, LayerList& layerList, const Vector2& screenCoordinates, Results& results, HitTestInterface& hitTestInterface)
632 // Hit-test the regular on-scene actors
635 wasHit = HitTestForEachRenderTask(sceneSize, layerList, renderTaskList, screenCoordinates, results, hitTestInterface);
640 bool HitTest(const Vector2& sceneSize, RenderTaskList& renderTaskList, LayerList& layerList, const Vector2& screenCoordinates, Results& results)
642 ActorTouchableCheck actorTouchableCheck;
643 return HitTest(sceneSize, renderTaskList, layerList, screenCoordinates, results, actorTouchableCheck);
646 } // namespace HitTestAlgorithm
648 } // namespace Internal