2 * Copyright (c) 2018 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/public-api/actors/layer.h>
23 #include <dali/public-api/math/vector2.h>
24 #include <dali/public-api/math/vector4.h>
25 #include <dali/integration-api/debug.h>
26 #include <dali/internal/event/actors/actor-impl.h>
27 #include <dali/internal/event/actors/camera-actor-impl.h>
28 #include <dali/internal/event/actors/layer-impl.h>
29 #include <dali/internal/event/actors/layer-list.h>
30 #include <dali/internal/event/common/projection.h>
31 #include <dali/internal/event/images/frame-buffer-image-impl.h>
32 #include <dali/internal/event/render-tasks/render-task-impl.h>
33 #include <dali/internal/event/render-tasks/render-task-list-impl.h>
41 namespace HitTestAlgorithm
51 distance( std::numeric_limits<float>::max() ),
52 depth( std::numeric_limits<int>::min() )
56 Actor *actor; ///< The actor hit (if actor is hit, then this is initialised).
57 Vector2 hitPosition; ///< Position of hit (only valid if actor valid).
58 float distance; ///< Distance from ray origin to hit actor.
59 int32_t depth; ///< Depth index of this actor.
63 * Creates an Actor handle so that a HitTestFunction provided via the public API can be called.
65 struct HitTestFunctionWrapper : public HitTestInterface
70 * @param[in] func HitTestFunction to call with an Actor handle.
72 HitTestFunctionWrapper( Dali::HitTestAlgorithm::HitTestFunction func )
77 virtual bool IsActorHittable( Actor* actor )
79 return mFunc( Dali::Actor( actor ), Dali::HitTestAlgorithm::CHECK_ACTOR );
82 virtual bool DescendActorHierarchy( Actor* actor )
84 return mFunc( Dali::Actor( actor ), Dali::HitTestAlgorithm::DESCEND_ACTOR_TREE );
87 virtual bool DoesLayerConsumeHit( Layer* layer )
89 // Layer::IsTouchConsumed() focuses on touch only. Here we are a wrapper for the public-api
90 // where the caller may want to check for something completely different.
91 // TODO: Should provide a means to let caller decide. For now do not allow layers to consume
95 Dali::HitTestAlgorithm::HitTestFunction mFunc;
99 * Used in the hit-test algorithm to check whether the actor is touchable.
100 * It is used by the touch event processor.
102 struct ActorTouchableCheck : public HitTestInterface
104 virtual bool IsActorHittable( Actor* actor )
106 return actor->GetTouchRequired() && // Does the Application or derived actor type require a touch event?
107 actor->IsHittable(); // Is actor sensitive, visible and on the scene?
110 virtual bool DescendActorHierarchy( Actor* actor )
112 return actor->IsVisible() && // Actor is visible, if not visible then none of its children are visible.
113 actor->IsSensitive(); // Actor is sensitive, if insensitive none of its children should be hittable either.
116 virtual bool DoesLayerConsumeHit( Layer* layer )
118 return layer->IsTouchConsumed();
123 * Check to see if the actor we're about to hit test is exclusively owned by another rendertask?
125 bool IsActorExclusiveToAnotherRenderTask( const Actor& actor,
126 const RenderTask& renderTask,
127 const Vector< RenderTaskList::Exclusive >& exclusives )
130 if( exclusives.Size() )
132 for( Vector< RenderTaskList::Exclusive >::Iterator exclusiveIt = exclusives.Begin(); exclusives.End() != exclusiveIt; ++exclusiveIt )
134 if( ( exclusiveIt->renderTaskPtr != &renderTask ) && ( exclusiveIt->actorPtr == &actor ) )
144 * Recursively hit test all the actors, without crossing into other layers.
145 * This algorithm performs a Depth-First-Search (DFS) on all Actors within Layer.
146 * Hit-Testing each Actor, noting the distance from the Ray-Origin (3D origin
147 * of touch vector). The closest Hit-Tested Actor is that which is returned.
148 * Exceptions to this rule are:
149 * - When comparing against renderable parents, if Actor is the same distance
150 * or closer than it's renderable parent, then it takes priority.
152 HitActor HitTestWithinLayer( Actor& actor,
153 const RenderTask& renderTask,
154 const Vector< RenderTaskList::Exclusive >& exclusives,
155 const Vector4& rayOrigin,
156 const Vector4& rayDir,
157 float& nearClippingPlane,
158 float& farClippingPlane,
159 HitTestInterface& hitCheck,
162 uint32_t clippingDepth,
163 uint32_t clippingBitPlaneMask )
167 if( IsActorExclusiveToAnotherRenderTask( actor, renderTask, exclusives ) )
172 // For clipping, regardless of whether we have hit this actor or not,
173 // we increase the clipping depth if we have hit a clipping actor.
174 // This is used later to ensure all nested clipped children have hit
175 // all clipping actors also for them to be counted as hit.
176 uint32_t newClippingDepth = clippingDepth;
177 bool clippingActor = actor.GetClippingMode() != ClippingMode::DISABLED;
183 // If we are a clipping actor or hittable...
184 if( clippingActor || hitCheck.IsActorHittable( &actor ) )
186 Vector3 size( actor.GetCurrentSize() );
188 // Ensure the actor has a valid size.
189 // If so, perform a quick ray sphere test to see if our ray is close to the actor.
190 if( size.x > 0.0f && size.y > 0.0f && actor.RaySphereTest( rayOrigin, rayDir ) )
192 Vector2 hitPointLocal;
195 // Finally, perform a more accurate ray test to see if our ray actually hits the actor.
196 if( actor.RayActorTest( rayOrigin, rayDir, hitPointLocal, distance ) )
198 if( distance >= nearClippingPlane && distance <= farClippingPlane )
200 // If the hit has happened on a clipping actor, then add this clipping depth to the mask of hit clipping depths.
201 // This mask shows all the actors that have been hit at different clipping depths.
204 clippingBitPlaneMask |= 1u << clippingDepth;
207 if( overlayHit && !actor.IsOverlay() )
209 // If we have already hit an overlay and current actor is not an overlay ignore current actor.
213 if( actor.IsOverlay() )
218 // At this point we have hit an actor.
219 // Now perform checks for clipping.
220 // Assume we have hit the actor first as if it is not clipped this would be the case.
221 bool haveHitActor = true;
223 // Check if we are performing clipping. IE. if any actors so far have clipping enabled - not necessarily this one.
224 // We can do this by checking the clipping depth has a value 1 or above.
225 if( newClippingDepth >= 1u )
227 // Now for us to count this actor as hit, we must have also hit
228 // all CLIPPING actors up to this point in the hierarchy as well.
229 // This information is stored in the clippingBitPlaneMask we updated above.
230 // Here we calculate a comparison mask by setting all the bits up to the current depth value.
231 // EG. a depth of 4 (10000 binary) = a mask of 1111 binary.
232 // This allows us a fast way of comparing all bits are set up to this depth.
233 // Note: If the current Actor has clipping, that is included in the depth mask too.
234 uint32_t clippingDepthMask = ( 1u << newClippingDepth ) - 1u;
236 // The two masks must be equal to be a hit, as we are already assuming a hit
237 // (for non-clipping mode) then they must be not-equal to disqualify the hit.
238 if( clippingBitPlaneMask != clippingDepthMask )
240 haveHitActor = false;
247 hit.hitPosition = hitPointLocal;
248 hit.distance = distance;
249 hit.depth = actor.GetSortingDepth() ;
251 if( actor.GetRendererCount() > 0 )
253 //Get renderer with maximum depth
254 int rendererMaxDepth(actor.GetRendererAt( 0 ).Get()->GetDepthIndex());
255 for( uint32_t i(1); i < actor.GetRendererCount(); ++i )
257 int depth = actor.GetRendererAt( i ).Get()->GetDepthIndex();
258 if( depth > rendererMaxDepth )
260 rendererMaxDepth = depth;
263 hit.depth += rendererMaxDepth;
272 // Find a child hit, until we run out of actors in the current layer.
274 if( actor.GetChildCount() > 0 )
276 childHit.distance = std::numeric_limits<float>::max();
277 childHit.depth = std::numeric_limits<int32_t>::min();
278 ActorContainer& children = actor.GetChildrenInternal();
280 // Hit test ALL children and calculate their distance.
281 bool parentIsRenderable = actor.IsRenderable();
283 for( ActorIter iter = children.begin(), endIter = children.end(); iter != endIter; ++iter )
285 // Descend tree only if...
286 if ( !( *iter )->IsLayer() && // Child is NOT a layer, hit testing current layer only
287 ( hitCheck.DescendActorHierarchy( ( *iter ).Get() ) ) ) // We can descend into child hierarchy
289 HitActor currentHit( HitTestWithinLayer( ( *iter->Get() ),
300 clippingBitPlaneMask ) );
302 bool updateChildHit = false;
303 if( currentHit.distance >= 0.0f )
307 updateChildHit = ( ( currentHit.depth > childHit.depth ) ||
308 ( ( currentHit.depth == childHit.depth ) && ( currentHit.distance < childHit.distance ) ) );
312 updateChildHit = currentHit.depth >= childHit.depth;
318 if( !parentIsRenderable || currentHit.depth > hit.depth ||
319 ( layerIs3d && ( currentHit.depth == hit.depth && currentHit.distance < hit.distance )) )
321 childHit = currentHit;
328 return ( childHit.actor ) ? childHit : hit;
332 * Return true if actor is sourceActor or a descendent of sourceActor
334 bool IsWithinSourceActors( const Actor& sourceActor, const Actor& actor )
336 if ( &sourceActor == &actor )
341 Actor* parent = actor.GetParent();
344 return IsWithinSourceActors( sourceActor, *parent );
347 // Not within source actors
352 * Returns true if the layer and all of the layer's parents are visible and sensitive.
354 inline bool IsActuallyHittable( Layer& layer, const Vector2& screenCoordinates, const Vector2& stageSize, HitTestInterface& hitCheck )
356 bool hittable( true );
358 if( layer.IsClipping() )
360 ClippingBox box = layer.GetClippingBox();
362 if( screenCoordinates.x < static_cast<float>( box.x )||
363 screenCoordinates.x > static_cast<float>( box.x + box.width )||
364 screenCoordinates.y < stageSize.y - static_cast<float>( box.y + box.height ) ||
365 screenCoordinates.y > stageSize.y - static_cast<float>( box.y ) )
367 // Not touchable if clipping is enabled in the layer and the screen coordinate is outside the clip region.
374 Actor* actor( &layer );
376 // Ensure that we can descend into the layer's (or any of its parent's) hierarchy.
377 while( actor && hittable )
379 if( ! hitCheck.DescendActorHierarchy( actor ) )
384 actor = actor->GetParent();
392 * Gets the near and far clipping planes of the camera from which the scene is viewed in the render task.
394 void GetCameraClippingPlane( RenderTask& renderTask, float& nearClippingPlane, float& farClippingPlane )
396 CameraActor* cameraActor = renderTask.GetCameraActor();
397 nearClippingPlane = cameraActor->GetNearClippingPlane();
398 farClippingPlane = cameraActor->GetFarClippingPlane();
402 * Hit test a RenderTask
404 bool HitTestRenderTask( const Vector< RenderTaskList::Exclusive >& exclusives,
405 const Vector2& sceneSize,
407 RenderTask& renderTask,
408 Vector2 screenCoordinates,
410 HitTestInterface& hitCheck )
412 if ( renderTask.IsHittable( screenCoordinates ) )
415 renderTask.GetViewport( viewport );
416 if( screenCoordinates.x < static_cast<float>( viewport.x ) ||
417 screenCoordinates.x > static_cast<float>( viewport.x + viewport.width ) ||
418 screenCoordinates.y < static_cast<float>( viewport.y ) ||
419 screenCoordinates.y > static_cast<float>( viewport.y + viewport.height ) )
421 // The screen coordinate is outside the viewport of render task. The viewport clips all layers.
425 float nearClippingPlane, farClippingPlane;
426 GetCameraClippingPlane( renderTask, nearClippingPlane, farClippingPlane );
428 // Determine the layer depth of the source actor
429 Actor* sourceActor( renderTask.GetSourceActor() );
432 Dali::Layer layer( sourceActor->GetLayer() );
435 const uint32_t sourceActorDepth( layer.GetDepth() );
437 CameraActor* cameraActor = renderTask.GetCameraActor();
438 bool pickingPossible = cameraActor->BuildPickingRay(
442 results.rayDirection );
443 if( !pickingPossible )
448 // Hit test starting with the top layer, working towards the bottom layer.
450 bool overlayHit = false;
451 bool layerConsumesHit = false;
453 for( int32_t i = layers.GetLayerCount() - 1; i >= 0 && !( hit.actor ); --i )
455 Layer* layer( layers.GetLayer( i ) );
458 // Ensure layer is touchable (also checks whether ancestors are also touchable)
459 if( IsActuallyHittable( *layer, screenCoordinates, sceneSize, hitCheck ) )
461 // Always hit-test the source actor; otherwise test whether the layer is below the source actor in the hierarchy
462 if( sourceActorDepth == static_cast<uint32_t>( i ) )
464 // Recursively hit test the source actor & children, without crossing into other layers.
465 hit = HitTestWithinLayer( *sourceActor,
469 results.rayDirection,
474 layer->GetBehavior() == Dali::Layer::LAYER_3D,
478 else if( IsWithinSourceActors( *sourceActor, *layer ) )
480 // Recursively hit test all the actors, without crossing into other layers.
481 hit = HitTestWithinLayer( *layer,
485 results.rayDirection,
490 layer->GetBehavior() == Dali::Layer::LAYER_3D,
495 // If this layer is set to consume the hit, then do not check any layers behind it
496 if( hitCheck.DoesLayerConsumeHit( layer ) )
498 layerConsumesHit = true;
506 results.renderTask = RenderTaskPtr( &renderTask );
507 results.actor = Dali::Actor( hit.actor );
508 results.actorCoordinates = hit.hitPosition;
510 return true; // Success
513 if( layerConsumesHit )
515 return true; // Also success if layer is consuming the hit
524 * Iterate through the RenderTaskList and perform hit testing.
526 * @param[in] sceneSize The scene size the tests will be performed in
527 * @param[in] layers The list of layers to test
528 * @param[in] taskList The list of render tasks
529 * @param[out] results Ray information calculated by the camera
530 * @param[in] hitCheck The hit testing interface object to use
531 * @param[in] onScreen True to test on-screen, false to test off-screen
532 * @return True if we have a hit, false otherwise
534 bool HitTestRenderTaskList( const Vector2& sceneSize,
536 RenderTaskList& taskList,
537 const Vector2& screenCoordinates,
539 HitTestInterface& hitCheck,
542 RenderTaskList::RenderTaskContainer& tasks = taskList.GetTasks();
543 RenderTaskList::RenderTaskContainer::reverse_iterator endIter = tasks.rend();
544 const Vector< RenderTaskList::Exclusive >& exclusives = taskList.GetExclusivesList();
546 for( RenderTaskList::RenderTaskContainer::reverse_iterator iter = tasks.rbegin(); endIter != iter; ++iter )
548 RenderTask& renderTask = *iter->Get();
549 bool isOffscreenRenderTask = ( renderTask.GetTargetFrameBuffer() || renderTask.GetFrameBuffer() );
550 if( (onScreen && isOffscreenRenderTask) || (!onScreen && !isOffscreenRenderTask) )
556 if( HitTestRenderTask( exclusives, sceneSize, layers, renderTask, screenCoordinates, results, hitCheck ) )
558 // Return true when an actor is hit (or layer in our render-task consumes the hit)
559 return true; // don't bother checking off screen tasks
567 * Iterate through the RenderTaskList and perform hit testing for both on-screen and off-screen.
569 * @param[in] sceneSize The scene size the tests will be performed in
570 * @param[in] layers The list of layers to test
571 * @param[in] taskList The list of render tasks
572 * @param[out] results Ray information calculated by the camera
573 * @param[in] hitCheck The hit testing interface object to use
574 * @param[in] onScreen True to test on-screen, false to test off-screen
575 * @return True if we have a hit, false otherwise
577 bool HitTestForEachRenderTask( const Vector2& sceneSize,
579 RenderTaskList& taskList,
580 const Vector2& screenCoordinates,
582 HitTestInterface& hitCheck )
586 // Check on-screen tasks before off-screen ones.
587 // Hit test order should be reverse of draw order (see ProcessRenderTasks() where off-screen tasks are drawn first).
588 if( HitTestRenderTaskList( sceneSize, layers, taskList, screenCoordinates, results, hitCheck, true ) ||
589 HitTestRenderTaskList( sceneSize, layers, taskList, screenCoordinates, results, hitCheck, false ) )
598 } // unnamed namespace
600 HitTestInterface::~HitTestInterface()
604 bool HitTest( const Vector2& sceneSize, RenderTaskList& taskList, LayerList& layerList, const Vector2& screenCoordinates, Dali::HitTestAlgorithm::Results& results, Dali::HitTestAlgorithm::HitTestFunction func )
606 bool wasHit( false );
607 // Hit-test the regular on-scene actors
608 Results hitTestResults;
609 HitTestFunctionWrapper hitTestFunctionWrapper( func );
610 if( HitTestForEachRenderTask( sceneSize, layerList, taskList, screenCoordinates, hitTestResults, hitTestFunctionWrapper ) )
612 results.actor = hitTestResults.actor;
613 results.actorCoordinates = hitTestResults.actorCoordinates;
619 bool HitTest( const Vector2& sceneSize, RenderTaskList& renderTaskList, LayerList& layerList, const Vector2& screenCoordinates, Results& results, HitTestInterface& hitTestInterface )
621 bool wasHit( false );
623 // Hit-test the regular on-scene actors
626 wasHit = HitTestForEachRenderTask( sceneSize, layerList, renderTaskList, screenCoordinates, results, hitTestInterface );
631 bool HitTest( const Vector2& sceneSize, RenderTaskList& renderTaskList, LayerList& layerList, const Vector2& screenCoordinates, Results& results )
633 ActorTouchableCheck actorTouchableCheck;
634 return HitTest( sceneSize, renderTaskList, layerList, screenCoordinates, results, actorTouchableCheck );
637 bool HitTest( const Vector2& sceneSize, RenderTaskList& renderTaskList, LayerList& layerList, RenderTask& renderTask, const Vector2& screenCoordinates,
638 Dali::HitTestAlgorithm::Results& results, Dali::HitTestAlgorithm::HitTestFunction func )
640 bool wasHit( false );
641 Results hitTestResults;
643 const Vector< RenderTaskList::Exclusive >& exclusives = renderTaskList.GetExclusivesList();
644 HitTestFunctionWrapper hitTestFunctionWrapper( func );
645 if( HitTestRenderTask( exclusives, sceneSize, layerList, renderTask, screenCoordinates, hitTestResults, hitTestFunctionWrapper ) )
647 results.actor = hitTestResults.actor;
648 results.actorCoordinates = hitTestResults.actorCoordinates;
655 } // namespace HitTestAlgorithm
657 } // namespace Internal