2 * Copyright (c) 2014 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/system-overlay.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/actors/renderable-actor-impl.h>
31 #include <dali/internal/event/common/system-overlay-impl.h>
32 #include <dali/internal/event/common/stage-impl.h>
33 #include <dali/internal/event/common/projection.h>
34 #include <dali/internal/event/images/frame-buffer-image-impl.h>
35 #include <dali/internal/event/render-tasks/render-task-impl.h>
36 #include <dali/internal/event/render-tasks/render-task-list-impl.h>
44 namespace HitTestAlgorithm
56 distance( std::numeric_limits<float>::max() ),
62 Actor *actor; ///< the actor hit. (if actor hit, then initialised)
63 float x; ///< x position of hit (only valid if actor valid)
64 float y; ///< y position of hit (only valid if actor valid)
65 float distance; ///< distance from ray origin to hit actor
66 bool overlay; ///< true if the hit actor is an overlay
71 * Creates an Actor handle so that a HitTestFunction provided via the public API can be called.
73 struct HitTestFunctionWrapper : public HitTestInterface
78 * @param[in] func HitTestFunction to call with an Actor handle.
80 HitTestFunctionWrapper( Dali::HitTestAlgorithm::HitTestFunction func )
85 virtual bool IsActorHittable( Actor* actor )
87 return mFunc( Dali::Actor( actor ), Dali::HitTestAlgorithm::CHECK_ACTOR );
90 virtual bool DescendActorHierarchy( Actor* actor )
92 return mFunc( Dali::Actor( actor ), Dali::HitTestAlgorithm::DESCEND_ACTOR_TREE );
95 virtual bool DoesLayerConsumeHit( Layer* layer )
97 // Layer::IsTouchConsumed() focuses on touch only. Here we are a wrapper for the public-api
98 // where the caller may want to check for something completely different.
99 // TODO: Should provide a means to let caller decide. For now do not allow layers to consume
103 Dali::HitTestAlgorithm::HitTestFunction mFunc;
107 * Used in the hit-test algorithm to check whether the actor is touchable.
108 * It is used by the touch event processor.
110 struct ActorTouchableCheck : public HitTestInterface
112 virtual bool IsActorHittable( Actor* actor )
114 return actor->GetTouchRequired() && // Does the Application or derived actor type require a touch event?
115 actor->IsHittable(); // Is actor sensitive, visible and on the scene?
118 virtual bool DescendActorHierarchy( Actor* actor )
120 return actor->IsVisible() && // Actor is visible, if not visible then none of its children are visible.
121 actor->IsSensitive(); // Actor is sensitive, if insensitive none of its children should be hittable either.
124 virtual bool DoesLayerConsumeHit( Layer* layer )
126 return layer->IsTouchConsumed();
131 * Recursively hit test all the actors, without crossing into other layers.
132 * This algorithm performs a Depth-First-Search (DFS) on all Actors within Layer.
133 * Hit-Testing each Actor, noting the distance from the Ray-Origin (3D origin
134 * of touch vector). The closest Hit-Tested Actor is that which is returned.
135 * Exceptions to this rule are:
136 * - If the Actor is an overlay then it is considered closer than all previous
137 * overlays encountered in the hit test traversal.
138 * - When comparing against renderable parents, if Actor is the same distance
139 * or closer than it's renderable parent, then it takes priority.
141 HitActor HitTestWithinLayer( Actor& actor,
142 const Vector4& rayOrigin,
143 const Vector4& rayDir,
145 float& nearClippingPlane,
146 float& farClippingPlane,
147 HitTestInterface& hitCheck,
148 bool& stencilOnLayer,
150 bool parentIsStencil )
152 worldOverlay |= actor.IsOverlay();
156 // Children should inherit the stencil draw mode
157 bool isStencil = parentIsStencil;
159 if ( actor.GetDrawMode() == DrawMode::STENCIL && actor.IsVisible() )
162 stencilOnLayer = true;
165 // If we are a stencil or hittable...
166 if ( isStencil || hitCheck.IsActorHittable( &actor ) )
168 Vector3 size( actor.GetCurrentSize() );
170 if ( size.x > 0.0f && size.y > 0.0f && // Ensure the actor has a valid size.
171 actor.RaySphereTest( rayOrigin, rayDir ) ) // Perform quicker ray sphere test to see if our ray is close to the actor.
173 Vector4 hitPointLocal;
176 // Finally, perform a more accurate ray test to see if our ray actually hits the actor.
177 if( actor.RayActorTest( rayOrigin, rayDir, hitPointLocal, distance ) )
179 if( distance >= nearClippingPlane && distance <= farClippingPlane )
181 // If the hit has happened on a stencil then register, but don't record as hit result
189 hit.x = hitPointLocal.x;
190 hit.y = hitPointLocal.y;
191 hit.distance = distance;
192 hit.overlay = worldOverlay;
199 // If we are a stencil (or a child of a stencil) and we have already ascertained that the stencil has been hit then there is no need to hit-test the children of this stencil-actor
200 if ( isStencil && stencilHit )
205 // Find a child hit, until we run out of actors in the current layer.
207 if( actor.GetChildCount() > 0 )
209 childHit.distance = std::numeric_limits<float>::max();
210 ActorContainer& children = actor.GetChildrenInternal();
212 // Hit test ALL children and calculate their distance.
213 bool parentIsRenderable = actor.IsRenderable();
215 for( ActorIter iter = children.begin(), endIter = children.end(); iter != endIter; ++iter )
217 // Descend tree only if...
218 if ( !iter->IsLayer() && // Child is NOT a layer, hit testing current layer only or Child is not a layer and we've inherited the stencil draw mode
219 ( isStencil || hitCheck.DescendActorHierarchy( &GetImplementation( *iter ) ) ) ) // We are a stencil OR we can descend into child hierarchy
221 HitActor currentHit( HitTestWithinLayer( GetImplementation(*iter), rayOrigin, rayDir, worldOverlay, nearClippingPlane, farClippingPlane, hitCheck, stencilOnLayer, stencilHit, isStencil ) );
223 // If Current child is an overlay, then it takes priority.
224 // If it is not an overlay, and the previously hit sibling is also not an overlay, then closest takes priority.
225 // (last overlay sibling has priority as is rendered on top)
226 if ( currentHit.distance >= 0.f && (currentHit.overlay || (!childHit.overlay && currentHit.distance < childHit.distance) ) )
228 if ( !parentIsRenderable )
230 // If our parent is not renderable, then child should be hit regardless of distance.
231 childHit = currentHit;
233 else if ( currentHit.overlay || (!hit.overlay && currentHit.distance <= hit.distance) )
235 // If our parent is renderable, then child should only be hit if it is an overlay, or if it is closer than a non-overlay.
236 // (child overlay has priority as is rendered on top of it's parent)
237 childHit = currentHit;
243 return ( childHit.actor ) ? childHit : hit;
247 * Return true if actor is sourceActor or a descendent of sourceActor
249 bool IsWithinSourceActors( const Actor& sourceActor, const Actor& actor )
251 if ( &sourceActor == &actor )
257 Actor* parent = actor.GetParent();
260 return IsWithinSourceActors( sourceActor, *parent );
264 // Not within source actors
269 * Returns true if the layer and all of the layer's parents are visible and sensitive.
271 inline bool IsActuallyHittable( Layer& layer, const Vector2& screenCoordinates, const Vector2& stageSize, HitTestInterface& hitCheck )
273 bool hittable( true );
275 if(layer.IsClipping())
277 ClippingBox box = layer.GetClippingBox();
279 if( screenCoordinates.x < box.x ||
280 screenCoordinates.x > box.x + box.width ||
281 screenCoordinates.y < stageSize.y - (box.y + box.height) ||
282 screenCoordinates.y > stageSize.y - box.y)
284 // Not touchable if clipping is enabled in the layer and the screen coordinate is outside the clip region.
291 Actor* actor( &layer );
293 // Ensure that we can descend into the layer's (or any of its parent's) hierarchy.
294 while ( actor && hittable )
296 if ( ! hitCheck.DescendActorHierarchy( actor ) )
301 actor = actor->GetParent();
309 * Gets the near and far clipping planes of the camera from which the scene is viewed in the render task.
311 void GetCameraClippingPlane( RenderTask& renderTask, float& nearClippingPlane, float& farClippingPlane )
313 CameraActor* cameraActor = renderTask.GetCameraActor();
314 nearClippingPlane = cameraActor->GetNearClippingPlane();
315 farClippingPlane = cameraActor->GetFarClippingPlane();
319 * Hit test a RenderTask
321 bool HitTestRenderTask( Stage& stage,
323 RenderTask& renderTask,
324 Vector2 screenCoordinates,
326 HitTestInterface& hitCheck )
328 if ( renderTask.IsHittable( screenCoordinates ) )
331 renderTask.GetViewport( viewport );
332 if( screenCoordinates.x < viewport.x ||
333 screenCoordinates.x > viewport.x + viewport.width ||
334 screenCoordinates.y < viewport.y ||
335 screenCoordinates.y > viewport.y + viewport.height )
337 // The screen coordinate is outside the viewport of render task. The viewport clips all layers.
341 float nearClippingPlane, farClippingPlane;
342 GetCameraClippingPlane(renderTask, nearClippingPlane, farClippingPlane);
344 // Determine the layer depth of the source actor
345 Actor* sourceActor( renderTask.GetSourceActor() );
348 Dali::Layer layer( sourceActor->GetLayer() );
351 const unsigned int sourceActorDepth( layer.GetDepth() );
353 CameraActor* cameraActor = renderTask.GetCameraActor();
354 bool pickingPossible = cameraActor->BuildPickingRay(
358 results.rayDirection );
359 if( !pickingPossible )
364 // Hit test starting with the top layer, working towards the bottom layer.
366 bool stencilOnLayer = false;
367 bool stencilHit = false;
368 bool layerConsumesHit = false;
370 const Vector2& stageSize = stage.GetSize();
372 for (int i=layers.GetLayerCount()-1; i>=0 && !(hit.actor); --i)
374 Layer* layer( layers.GetLayer(i) );
376 HitActor previousHit = hit;
377 stencilOnLayer = false;
380 // Ensure layer is touchable (also checks whether ancestors are also touchable)
381 if ( IsActuallyHittable ( *layer, screenCoordinates, stageSize, hitCheck ) )
383 // Always hit-test the source actor; otherwise test whether the layer is below the source actor in the hierarchy
384 if ( sourceActorDepth == static_cast<unsigned int>(i) )
386 // Recursively hit test the source actor & children, without crossing into other layers.
387 hit = HitTestWithinLayer( *sourceActor, results.rayOrigin, results.rayDirection, false, nearClippingPlane, farClippingPlane, hitCheck, stencilOnLayer, stencilHit, false );
389 else if ( IsWithinSourceActors( *sourceActor, *layer ) )
391 // Recursively hit test all the actors, without crossing into other layers.
392 hit = HitTestWithinLayer( *layer, results.rayOrigin, results.rayDirection, false, nearClippingPlane, farClippingPlane, hitCheck, stencilOnLayer, stencilHit, false );
395 // If a stencil on this layer hasn't been hit, then discard hit results for this layer if our current hit actor is renderable
396 if ( stencilOnLayer && !stencilHit &&
397 hit.actor && hit.actor->IsRenderable() )
402 // If this layer is set to consume the hit, then do not check any layers behind it
403 if ( hitCheck.DoesLayerConsumeHit( layer ) )
405 layerConsumesHit = true;
412 results.renderTask = Dali::RenderTask(&renderTask);
413 results.actor = Dali::Actor(hit.actor);
414 results.actorCoordinates.x = hit.x;
415 results.actorCoordinates.y = hit.y;
416 return true; // Success
418 else if ( layerConsumesHit )
420 return true; // Also success if layer is consuming the hit
429 * Iterate through RenderTaskList and perform hit test.
431 * @return true if we have a hit, false otherwise
433 bool HitTestForEachRenderTask( Stage& stage,
435 RenderTaskList& taskList,
436 const Vector2& screenCoordinates,
438 HitTestInterface& hitCheck )
440 RenderTaskList::RenderTaskContainer& tasks = taskList.GetTasks();
441 RenderTaskList::RenderTaskContainer::reverse_iterator endIter = tasks.rend();
443 // Check onscreen tasks before offscreen ones, hit test order should be reverse of draw order (see ProcessRenderTasks() where offscreen tasks are drawn first).
446 for ( RenderTaskList::RenderTaskContainer::reverse_iterator iter = tasks.rbegin(); endIter != iter; ++iter )
448 RenderTask& renderTask = GetImplementation( *iter );
449 Dali::FrameBufferImage frameBufferImage = renderTask.GetTargetFrameBuffer();
451 // Note that if frameBufferImage is NULL we are using the default (on screen) render target
454 ResourceId id = GetImplementation(frameBufferImage).GetResourceId();
464 if ( HitTestRenderTask( stage, layers, renderTask, screenCoordinates, results, hitCheck ) )
466 // Return true when an actor is hit (or layer in our render-task consumes the hit)
467 return true; // don't bother checking off screen tasks
472 for ( RenderTaskList::RenderTaskContainer::reverse_iterator iter = tasks.rbegin(); endIter != iter; ++iter )
474 RenderTask& renderTask = GetImplementation( *iter );
475 Dali::FrameBufferImage frameBufferImage = renderTask.GetTargetFrameBuffer();
477 // Note that if frameBufferImage is NULL we are using the default (on screen) render target
480 ResourceId id = GetImplementation(frameBufferImage).GetResourceId();
489 if ( HitTestRenderTask( stage, layers, renderTask, screenCoordinates, results, hitCheck ) )
491 // Return true when an actor is hit (or a layer in our render-task consumes the hit)
499 } // unnamed namespace
501 bool HitTest( Stage& stage, const Vector2& screenCoordinates, Dali::HitTestAlgorithm::Results& results, Dali::HitTestAlgorithm::HitTestFunction func )
503 bool wasHit( false );
504 // Hit-test the regular on-stage actors
505 RenderTaskList& taskList = stage.GetRenderTaskList();
506 LayerList& layerList = stage.GetLayerList();
508 Results hitTestResults;
509 HitTestFunctionWrapper hitTestFunctionWrapper( func );
510 if ( HitTestForEachRenderTask( stage, layerList, taskList, screenCoordinates, hitTestResults, hitTestFunctionWrapper ) )
512 results.actor = hitTestResults.actor;
513 results.actorCoordinates = hitTestResults.actorCoordinates;
519 bool HitTest( Stage& stage, const Vector2& screenCoordinates, Results& results, HitTestInterface& hitTestInterface )
521 bool wasHit( false );
523 // Hit-test the system-overlay actors first
524 SystemOverlay* systemOverlay = stage.GetSystemOverlayInternal();
528 RenderTaskList& overlayTaskList = systemOverlay->GetOverlayRenderTasks();
529 LayerList& overlayLayerList = systemOverlay->GetLayerList();
531 wasHit = HitTestForEachRenderTask( stage, overlayLayerList, overlayTaskList, screenCoordinates, results, hitTestInterface );
534 // Hit-test the regular on-stage actors
537 RenderTaskList& taskList = stage.GetRenderTaskList();
538 LayerList& layerList = stage.GetLayerList();
540 wasHit = HitTestForEachRenderTask( stage, layerList, taskList, screenCoordinates, results, hitTestInterface );
545 bool HitTest( Stage& stage, const Vector2& screenCoordinates, Results& results )
547 ActorTouchableCheck actorTouchableCheck;
548 return HitTest( stage, screenCoordinates, results, actorTouchableCheck );
551 bool HitTest( Stage& stage, RenderTask& renderTask, const Vector2& screenCoordinates,
552 Dali::HitTestAlgorithm::Results& results, Dali::HitTestAlgorithm::HitTestFunction func )
554 bool wasHit( false );
555 Results hitTestResults;
557 HitTestFunctionWrapper hitTestFunctionWrapper( func );
558 if ( HitTestRenderTask( stage, stage.GetLayerList(), renderTask, screenCoordinates, hitTestResults, hitTestFunctionWrapper ) )
560 results.actor = hitTestResults.actor;
561 results.actorCoordinates = hitTestResults.actorCoordinates;
567 } // namespace HitTestAlgorithm
569 } // namespace Internal