Merge "Changed draw ordering to take into account the depth of the node in the hierar...
[platform/core/uifw/dali-core.git] / dali / internal / event / events / hit-test-algorithm-impl.cpp
1 /*
2  * Copyright (c) 2014 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali/internal/event/events/hit-test-algorithm-impl.h>
20
21 // INTERNAL INCLUDES
22 #include <dali/integration-api/system-overlay.h>
23 #include <dali/public-api/actors/layer.h>
24 #include <dali/public-api/math/vector2.h>
25 #include <dali/public-api/math/vector4.h>
26 #include <dali/integration-api/debug.h>
27 #include <dali/internal/event/actors/actor-impl.h>
28 #include <dali/internal/event/actors/camera-actor-impl.h>
29 #include <dali/internal/event/actors/image-actor-impl.h>
30 #include <dali/internal/event/actors/layer-impl.h>
31 #include <dali/internal/event/actors/layer-list.h>
32 #include <dali/internal/event/common/system-overlay-impl.h>
33 #include <dali/internal/event/common/stage-impl.h>
34 #include <dali/internal/event/common/projection.h>
35 #include <dali/internal/event/images/frame-buffer-image-impl.h>
36 #include <dali/internal/event/render-tasks/render-task-impl.h>
37 #include <dali/internal/event/render-tasks/render-task-list-impl.h>
38
39 namespace Dali
40 {
41
42 namespace Internal
43 {
44
45 namespace HitTestAlgorithm
46 {
47
48 namespace
49 {
50
51 struct HitActor
52 {
53   HitActor()
54   : actor( NULL ),
55     x( 0 ),
56     y( 0 ),
57     distance( std::numeric_limits<float>::max() ),
58     depth( std::numeric_limits<int>::min() )
59   {
60   }
61
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   int depth;                            ///< depth index of this actor
67
68 };
69
70 /**
71  * Creates an Actor handle so that a HitTestFunction provided via the public API can be called.
72  */
73 struct HitTestFunctionWrapper : public HitTestInterface
74 {
75   /**
76    * Constructor
77    *
78    * @param[in] func HitTestFunction to call with an Actor handle.
79    */
80   HitTestFunctionWrapper( Dali::HitTestAlgorithm::HitTestFunction func )
81   : mFunc( func )
82   {
83   }
84
85   virtual bool IsActorHittable( Actor* actor )
86   {
87     return mFunc( Dali::Actor( actor ), Dali::HitTestAlgorithm::CHECK_ACTOR );
88   }
89
90   virtual bool DescendActorHierarchy( Actor* actor )
91   {
92     return mFunc( Dali::Actor( actor ), Dali::HitTestAlgorithm::DESCEND_ACTOR_TREE );
93   }
94
95   virtual bool DoesLayerConsumeHit( Layer* layer )
96   {
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
100     return false;
101   }
102
103   Dali::HitTestAlgorithm::HitTestFunction mFunc;
104 };
105
106 /**
107  * Used in the hit-test algorithm to check whether the actor is touchable.
108  * It is used by the touch event processor.
109  */
110 struct ActorTouchableCheck : public HitTestInterface
111 {
112   virtual bool IsActorHittable( Actor* actor )
113   {
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?
116   }
117
118   virtual bool DescendActorHierarchy( Actor* actor )
119   {
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.
122   }
123
124   virtual bool DoesLayerConsumeHit( Layer* layer )
125   {
126     return layer->IsTouchConsumed();
127   }
128 };
129
130 /**
131  * Check to see if the actor we're about to hit test is exclusively owned by another rendertask?
132  */
133 bool IsActorExclusiveToAnotherRenderTask( const Actor& actor,
134                                           const RenderTask& renderTask,
135                                           const Vector< RenderTaskList::Exclusive >& exclusives )
136
137 {
138   if ( exclusives.Size() )
139   {
140     for ( Vector< RenderTaskList::Exclusive >::Iterator exclusiveIt = exclusives.Begin(); exclusives.End() != exclusiveIt; ++exclusiveIt )
141     {
142       if ( exclusiveIt->renderTaskPtr != &renderTask )
143       {
144         if ( exclusiveIt->actorPtr == &actor )
145         {
146           return true;
147         }
148       }
149     }
150   }
151   return false;
152 }
153
154 /**
155  * Recursively hit test all the actors, without crossing into other layers.
156  * This algorithm performs a Depth-First-Search (DFS) on all Actors within Layer.
157  * Hit-Testing each Actor, noting the distance from the Ray-Origin (3D origin
158  * of touch vector). The closest Hit-Tested Actor is that which is returned.
159  * Exceptions to this rule are:
160  * - When comparing against renderable parents, if Actor is the same distance
161  * or closer than it's renderable parent, then it takes priority.
162  */
163 HitActor HitTestWithinLayer( Actor& actor,
164                              const RenderTask& renderTask,
165                              const Vector< RenderTaskList::Exclusive >& exclusives,
166                              const Vector4& rayOrigin,
167                              const Vector4& rayDir,
168                              float& nearClippingPlane,
169                              float& farClippingPlane,
170                              HitTestInterface& hitCheck,
171                              bool& stencilOnLayer,
172                              bool& stencilHit,
173                              bool parentIsStencil,
174                              bool layerIs3d )
175 {
176   HitActor hit;
177
178   if ( IsActorExclusiveToAnotherRenderTask( actor, renderTask, exclusives ) )
179   {
180     return hit;
181   }
182
183   // Children should inherit the stencil draw mode
184   bool isStencil = parentIsStencil;
185
186   if ( actor.GetDrawMode() == DrawMode::STENCIL && actor.IsVisible() )
187   {
188     isStencil = true;
189     stencilOnLayer = true;
190   }
191
192   // If we are a stencil or hittable...
193   if ( isStencil || hitCheck.IsActorHittable( &actor ) )
194   {
195     Vector3 size( actor.GetCurrentSize() );
196
197     if ( size.x > 0.0f && size.y > 0.0f &&          // Ensure the actor has a valid size.
198          actor.RaySphereTest( rayOrigin, rayDir ) ) // Perform quicker ray sphere test to see if our ray is close to the actor.
199     {
200       Vector4 hitPointLocal;
201       float distance;
202
203       // Finally, perform a more accurate ray test to see if our ray actually hits the actor.
204       if( actor.RayActorTest( rayOrigin, rayDir, hitPointLocal, distance ) )
205       {
206         if( distance >= nearClippingPlane && distance <= farClippingPlane )
207         {
208           // If the hit has happened on a stencil then register, but don't record as hit result
209           if ( isStencil )
210           {
211             stencilHit = true;
212           }
213           else
214           {
215             hit.actor = &actor;
216             hit.x = hitPointLocal.x;
217             hit.y = hitPointLocal.y;
218             hit.distance = distance;
219
220             // Is this actor an Image Actor or contains a renderer?
221             if ( ImageActor* imageActor = dynamic_cast< ImageActor* >( &actor ) )
222             {
223               hit.depth = imageActor->GetDepthIndex();
224             }
225             else
226             {
227               if ( actor.GetRendererCount() )
228               {
229                 hit.depth = actor.GetHierarchyDepth() * Dali::Layer::TREE_DEPTH_MULTIPLIER + actor.GetRendererAt( 0 ).GetDepthIndex();
230               }
231               else
232               {
233                 hit.depth = 0;
234               }
235             }
236           }
237         }
238       }
239     }
240   }
241
242   // 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
243   if ( isStencil && stencilHit  )
244   {
245     return hit;
246   }
247
248   // Find a child hit, until we run out of actors in the current layer.
249   HitActor childHit;
250   if( actor.GetChildCount() > 0 )
251   {
252     childHit.distance = std::numeric_limits<float>::max();
253     childHit.depth = std::numeric_limits<int>::min();
254     ActorContainer& children = actor.GetChildrenInternal();
255
256     // Hit test ALL children and calculate their distance.
257     bool parentIsRenderable = actor.IsRenderable();
258
259     for( ActorIter iter = children.begin(), endIter = children.end(); iter != endIter; ++iter )
260     {
261       // Descend tree only if...
262       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
263            ( isStencil || hitCheck.DescendActorHierarchy( ( *iter ).Get() ) ) ) // We are a stencil OR we can descend into child hierarchy
264       {
265         HitActor currentHit( HitTestWithinLayer(  (*iter->Get()),
266                                                   renderTask,
267                                                   exclusives,
268                                                   rayOrigin,
269                                                   rayDir,
270                                                   nearClippingPlane,
271                                                   farClippingPlane,
272                                                   hitCheck,
273                                                   stencilOnLayer,
274                                                   stencilHit,
275                                                   isStencil,
276                                                   layerIs3d) );
277
278         bool updateChildHit = false;
279         // If our ray casting hit, then check then if the hit actor's depth is greater that the favorite, it will be preferred
280         if ( currentHit.distance >= 0.0f )
281         {
282           if ( currentHit.depth > childHit.depth )
283           {
284             updateChildHit = true;
285           }
286
287           // In a 3D layer, if the hit actor's depth is equal to current favorite, then we check the distance and prefer the closer
288           else if ( layerIs3d && currentHit.depth == childHit.depth )
289           {
290             if ( currentHit.distance < childHit.distance )
291             {
292               updateChildHit = true;
293             }
294           }
295         }
296
297         if ( updateChildHit )
298         {
299           if( !parentIsRenderable || currentHit.depth > hit.depth ||
300             ( layerIs3d && ( currentHit.depth == hit.depth && currentHit.distance < hit.distance )) )
301             {
302               childHit = currentHit;
303             }
304         }
305       }
306     }
307   }
308   return ( childHit.actor ) ? childHit : hit;
309 }
310
311 /**
312  * Return true if actor is sourceActor or a descendent of sourceActor
313  */
314 bool IsWithinSourceActors( const Actor& sourceActor, const Actor& actor )
315 {
316   if ( &sourceActor == &actor )
317   {
318     return true;
319   }
320   else
321   {
322     Actor* parent = actor.GetParent();
323     if ( parent )
324     {
325       return IsWithinSourceActors( sourceActor, *parent );
326     }
327   }
328
329   // Not within source actors
330   return false;
331 }
332
333 /**
334  * Returns true if the layer and all of the layer's parents are visible and sensitive.
335  */
336 inline bool IsActuallyHittable( Layer& layer, const Vector2& screenCoordinates, const Vector2& stageSize, HitTestInterface& hitCheck )
337 {
338   bool hittable( true );
339
340   if(layer.IsClipping())
341   {
342     ClippingBox box = layer.GetClippingBox();
343
344     if( screenCoordinates.x < box.x ||
345         screenCoordinates.x > box.x + box.width ||
346         screenCoordinates.y < stageSize.y - (box.y + box.height) ||
347         screenCoordinates.y > stageSize.y - box.y)
348     {
349       // Not touchable if clipping is enabled in the layer and the screen coordinate is outside the clip region.
350       hittable = false;
351     }
352   }
353
354   if(hittable)
355   {
356     Actor* actor( &layer );
357
358     // Ensure that we can descend into the layer's (or any of its parent's) hierarchy.
359     while ( actor && hittable )
360     {
361       if ( ! hitCheck.DescendActorHierarchy( actor ) )
362       {
363         hittable = false;
364         break;
365       }
366       actor = actor->GetParent();
367     }
368   }
369
370   return hittable;
371 }
372
373 /**
374  * Gets the near and far clipping planes of the camera from which the scene is viewed in the render task.
375  */
376 void GetCameraClippingPlane( RenderTask& renderTask, float& nearClippingPlane, float& farClippingPlane )
377 {
378   CameraActor* cameraActor = renderTask.GetCameraActor();
379   nearClippingPlane = cameraActor->GetNearClippingPlane();
380   farClippingPlane = cameraActor->GetFarClippingPlane();
381 }
382
383 /**
384  * Hit test a RenderTask
385  */
386 bool HitTestRenderTask( const Vector< RenderTaskList::Exclusive >& exclusives,
387                         Stage& stage,
388                         LayerList& layers,
389                         RenderTask& renderTask,
390                         Vector2 screenCoordinates,
391                         Results& results,
392                         HitTestInterface& hitCheck )
393 {
394   if ( renderTask.IsHittable( screenCoordinates ) )
395   {
396     Viewport viewport;
397     renderTask.GetViewport( viewport );
398     if( screenCoordinates.x < viewport.x ||
399         screenCoordinates.x > viewport.x + viewport.width ||
400         screenCoordinates.y < viewport.y ||
401         screenCoordinates.y > viewport.y + viewport.height )
402     {
403       // The screen coordinate is outside the viewport of render task. The viewport clips all layers.
404       return false;
405     }
406
407     float nearClippingPlane, farClippingPlane;
408     GetCameraClippingPlane(renderTask, nearClippingPlane, farClippingPlane);
409
410     // Determine the layer depth of the source actor
411     Actor* sourceActor( renderTask.GetSourceActor() );
412     if ( sourceActor )
413     {
414       Dali::Layer layer( sourceActor->GetLayer() );
415       if ( layer )
416       {
417         const unsigned int sourceActorDepth( layer.GetDepth() );
418
419         CameraActor* cameraActor = renderTask.GetCameraActor();
420         bool pickingPossible = cameraActor->BuildPickingRay(
421             screenCoordinates,
422             viewport,
423             results.rayOrigin,
424             results.rayDirection );
425         if( !pickingPossible )
426         {
427           return false;
428         }
429
430         // Hit test starting with the top layer, working towards the bottom layer.
431         HitActor hit;
432         bool stencilOnLayer = false;
433         bool stencilHit = false;
434         bool layerConsumesHit = false;
435
436         const Vector2& stageSize = stage.GetSize();
437
438         for (int i=layers.GetLayerCount()-1; i>=0 && !(hit.actor); --i)
439         {
440           Layer* layer( layers.GetLayer(i) );
441           HitActor previousHit = hit;
442           stencilOnLayer = false;
443           stencilHit = false;
444
445           // Ensure layer is touchable (also checks whether ancestors are also touchable)
446           if ( IsActuallyHittable ( *layer, screenCoordinates, stageSize, hitCheck ) )
447           {
448             // Always hit-test the source actor; otherwise test whether the layer is below the source actor in the hierarchy
449             if ( sourceActorDepth == static_cast<unsigned int>(i) )
450             {
451               // Recursively hit test the source actor & children, without crossing into other layers.
452               hit = HitTestWithinLayer( *sourceActor,
453                                         renderTask,
454                                         exclusives,
455                                         results.rayOrigin,
456                                         results.rayDirection,
457                                         nearClippingPlane,
458                                         farClippingPlane,
459                                         hitCheck,
460                                         stencilOnLayer,
461                                         stencilHit,
462                                         false,
463                                         layer->GetBehavior() == Dali::Layer::LAYER_3D);
464             }
465             else if ( IsWithinSourceActors( *sourceActor, *layer ) )
466             {
467               // Recursively hit test all the actors, without crossing into other layers.
468               hit = HitTestWithinLayer( *layer,
469                                         renderTask,
470                                         exclusives,
471                                         results.rayOrigin,
472                                         results.rayDirection,
473                                         nearClippingPlane,
474                                         farClippingPlane,
475                                         hitCheck,
476                                         stencilOnLayer,
477                                         stencilHit,
478                                         false,
479                                         layer->GetBehavior() == Dali::Layer::LAYER_3D);
480             }
481
482             // If a stencil on this layer hasn't been hit, then discard hit results for this layer if our current hit actor is renderable
483             if ( stencilOnLayer && !stencilHit &&
484                  hit.actor && hit.actor->IsRenderable() )
485             {
486               hit = previousHit;
487             }
488
489             // If this layer is set to consume the hit, then do not check any layers behind it
490             if ( hitCheck.DoesLayerConsumeHit( layer ) )
491             {
492               layerConsumesHit = true;
493               break;
494             }
495           }
496         }
497         if ( hit.actor )
498         {
499           results.renderTask = Dali::RenderTask(&renderTask);
500           results.actor = Dali::Actor(hit.actor);
501           results.actorCoordinates.x = hit.x;
502           results.actorCoordinates.y = hit.y;
503           return true; // Success
504         }
505         else if ( layerConsumesHit )
506         {
507           return true; // Also success if layer is consuming the hit
508         }
509       }
510     }
511   }
512   return false;
513 }
514
515 /**
516  * Iterate through RenderTaskList and perform hit test.
517  *
518  * @return true if we have a hit, false otherwise
519  */
520 bool HitTestForEachRenderTask( Stage& stage,
521                                LayerList& layers,
522                                RenderTaskList& taskList,
523                                const Vector2& screenCoordinates,
524                                Results& results,
525                                HitTestInterface& hitCheck )
526 {
527   RenderTaskList::RenderTaskContainer& tasks = taskList.GetTasks();
528   RenderTaskList::RenderTaskContainer::reverse_iterator endIter = tasks.rend();
529
530   const Vector< RenderTaskList::Exclusive >& exclusives = taskList.GetExclusivesList();
531
532   // Check onscreen tasks before offscreen ones, hit test order should be reverse of draw order (see ProcessRenderTasks() where offscreen tasks are drawn first).
533
534   // on screen
535   for ( RenderTaskList::RenderTaskContainer::reverse_iterator iter = tasks.rbegin(); endIter != iter; ++iter )
536   {
537     RenderTask& renderTask = GetImplementation( *iter );
538     Dali::FrameBufferImage frameBufferImage = renderTask.GetTargetFrameBuffer();
539
540     // Note that if frameBufferImage is NULL we are using the default (on screen) render target
541     if(frameBufferImage)
542     {
543       ResourceId id = GetImplementation(frameBufferImage).GetResourceId();
544
545       // on screen only
546       if(0 != id)
547       {
548         // Skip to next task
549         continue;
550       }
551     }
552
553     if ( HitTestRenderTask( exclusives, stage, layers, renderTask, screenCoordinates, results, hitCheck ) )
554     {
555       // Return true when an actor is hit (or layer in our render-task consumes the hit)
556       return true; // don't bother checking off screen tasks
557     }
558   }
559
560   // off screen
561   for ( RenderTaskList::RenderTaskContainer::reverse_iterator iter = tasks.rbegin(); endIter != iter; ++iter )
562   {
563     RenderTask& renderTask = GetImplementation( *iter );
564     Dali::FrameBufferImage frameBufferImage = renderTask.GetTargetFrameBuffer();
565
566     // Note that if frameBufferImage is NULL we are using the default (on screen) render target
567     if(frameBufferImage)
568     {
569       ResourceId id = GetImplementation(frameBufferImage).GetResourceId();
570
571       // off screen only
572       if(0 == id)
573       {
574         // Skip to next task
575         continue;
576       }
577
578       if ( HitTestRenderTask( exclusives, stage, layers, renderTask, screenCoordinates, results, hitCheck ) )
579       {
580         // Return true when an actor is hit (or a layer in our render-task consumes the hit)
581         return true;
582       }
583     }
584   }
585   return false;
586 }
587
588 } // unnamed namespace
589
590 bool HitTest( Stage& stage, const Vector2& screenCoordinates, Dali::HitTestAlgorithm::Results& results, Dali::HitTestAlgorithm::HitTestFunction func )
591 {
592   bool wasHit( false );
593   // Hit-test the regular on-stage actors
594   RenderTaskList& taskList = stage.GetRenderTaskList();
595   LayerList& layerList = stage.GetLayerList();
596
597   Results hitTestResults;
598   HitTestFunctionWrapper hitTestFunctionWrapper( func );
599   if (  HitTestForEachRenderTask( stage, layerList, taskList, screenCoordinates, hitTestResults, hitTestFunctionWrapper ) )
600   {
601     results.actor = hitTestResults.actor;
602     results.actorCoordinates = hitTestResults.actorCoordinates;
603     wasHit = true;
604   }
605   return wasHit;
606 }
607
608 bool HitTest( Stage& stage, const Vector2& screenCoordinates, Results& results, HitTestInterface& hitTestInterface )
609 {
610   bool wasHit( false );
611
612   // Hit-test the system-overlay actors first
613   SystemOverlay* systemOverlay = stage.GetSystemOverlayInternal();
614
615   if ( systemOverlay )
616   {
617     RenderTaskList& overlayTaskList = systemOverlay->GetOverlayRenderTasks();
618     LayerList& overlayLayerList = systemOverlay->GetLayerList();
619
620     wasHit = HitTestForEachRenderTask( stage, overlayLayerList, overlayTaskList, screenCoordinates, results, hitTestInterface );
621   }
622
623   // Hit-test the regular on-stage actors
624   if ( !wasHit )
625   {
626     RenderTaskList& taskList = stage.GetRenderTaskList();
627     LayerList& layerList = stage.GetLayerList();
628
629     wasHit = HitTestForEachRenderTask( stage, layerList, taskList, screenCoordinates, results, hitTestInterface );
630   }
631   return wasHit;
632 }
633
634 bool HitTest( Stage& stage, const Vector2& screenCoordinates, Results& results )
635 {
636   ActorTouchableCheck actorTouchableCheck;
637   return HitTest( stage, screenCoordinates, results, actorTouchableCheck );
638 }
639
640 bool HitTest( Stage& stage, RenderTask& renderTask, const Vector2& screenCoordinates,
641               Dali::HitTestAlgorithm::Results& results, Dali::HitTestAlgorithm::HitTestFunction func )
642 {
643   bool wasHit( false );
644   Results hitTestResults;
645
646   const Vector< RenderTaskList::Exclusive >& exclusives = Stage::GetCurrent()->GetRenderTaskList().GetExclusivesList();
647   HitTestFunctionWrapper hitTestFunctionWrapper( func );
648   if ( HitTestRenderTask( exclusives, stage, stage.GetLayerList(), renderTask, screenCoordinates, hitTestResults, hitTestFunctionWrapper ) )
649   {
650     results.actor = hitTestResults.actor;
651     results.actorCoordinates = hitTestResults.actorCoordinates;
652     wasHit = true;
653   }
654   return wasHit;
655 }
656
657 } // namespace HitTestAlgorithm
658
659 } // namespace Internal
660
661 } // namespace Dali