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