[3.0] Clipping API feature in Actor
[platform/core/uifw/dali-core.git] / dali / internal / update / manager / render-instruction-processor.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/update/manager/render-instruction-processor.h>
20
21 // INTERNAL INCLUDES
22 #include <dali/public-api/shader-effects/shader-effect.h>
23 #include <dali/public-api/actors/layer.h>
24 #include <dali/integration-api/debug.h>
25 #include <dali/internal/event/actors/layer-impl.h> // for the default sorting function
26 #include <dali/internal/update/manager/sorted-layers.h>
27 #include <dali/internal/update/render-tasks/scene-graph-render-task.h>
28 #include <dali/internal/update/rendering/scene-graph-texture-set.h>
29 #include <dali/internal/update/resources/resource-manager-declarations.h>
30 #include <dali/internal/render/common/render-item.h>
31 #include <dali/internal/render/common/render-tracker.h>
32 #include <dali/internal/render/common/render-instruction.h>
33 #include <dali/internal/render/common/render-instruction-container.h>
34 #include <dali/internal/render/shaders/scene-graph-shader.h>
35 #include <dali/internal/render/renderers/render-renderer.h>
36 #include <dali/internal/render/renderers/render-property-buffer.h>
37 #include <dali/internal/update/nodes/scene-graph-layer.h>
38
39 namespace
40 {
41 #if defined(DEBUG_ENABLED)
42 Debug::Filter* gRenderListLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_LISTS");
43 #endif
44 }
45
46 namespace Dali
47 {
48
49 namespace Internal
50 {
51
52 namespace SceneGraph
53 {
54
55 namespace
56 {
57
58 /**
59  * Function which sorts render items by depth index then by instance
60  * ptrs of shader/geometry/material.
61  * @param[in] lhs Left hand side item
62  * @param[in] rhs Right hand side item
63  * @return True if left item is greater than right
64  */
65 bool CompareItems( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
66 {
67   // @todo Consider replacing all these sortAttributes with a single long int that
68   // encapsulates the same data (e.g. the middle-order bits of the ptrs).
69   if( lhs.renderItem->mDepthIndex == rhs.renderItem->mDepthIndex )
70   {
71     if( lhs.shader == rhs.shader )
72     {
73       if( lhs.textureResourceId == rhs.textureResourceId )
74       {
75         return lhs.geometry < rhs.geometry;
76       }
77       return lhs.textureResourceId < rhs.textureResourceId;
78     }
79     return lhs.shader < rhs.shader;
80   }
81   return lhs.renderItem->mDepthIndex < rhs.renderItem->mDepthIndex;
82 }
83
84 /**
85  * Function which sorts render items by clipping hierarchy, then depth index and instance
86  * ptrs of shader/geometry/material.
87  * @param[in] lhs Left hand side item
88  * @param[in] rhs Right hand side item
89  * @return True if left item is greater than right
90  */
91 bool CompareItemsWithClipping( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
92 {
93   // Items must be sorted in order of clipping first, otherwise incorrect clipping regions could be used.
94   if( lhs.renderItem->mNode->mClippingSortModifier == rhs.renderItem->mNode->mClippingSortModifier )
95   {
96     return CompareItems( lhs, rhs );
97   }
98
99   return lhs.renderItem->mNode->mClippingSortModifier < rhs.renderItem->mNode->mClippingSortModifier;
100 }
101
102 /**
103  * Function which sorts the render items by Z function, then
104  * by instance ptrs of shader / geometry / material.
105  * @param[in] lhs Left hand side item
106  * @param[in] rhs Right hand side item
107  * @return True if left item is greater than right
108  */
109 bool CompareItems3D( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
110 {
111   bool lhsIsOpaque = lhs.renderItem->mIsOpaque;
112   if( lhsIsOpaque == rhs.renderItem->mIsOpaque )
113   {
114     if( lhsIsOpaque )
115     {
116       // If both RenderItems are opaque, sort using shader, then material then geometry.
117       if( lhs.shader == rhs.shader )
118       {
119         if( lhs.textureResourceId == rhs.textureResourceId )
120         {
121           return lhs.geometry < rhs.geometry;
122         }
123         return lhs.textureResourceId < rhs.textureResourceId;
124       }
125       return lhs.shader < rhs.shader;
126     }
127     else
128     {
129       // If both RenderItems are transparent, sort using Z, then shader, then material, then geometry.
130       if( Equals( lhs.zValue, rhs.zValue ) )
131       {
132         if( lhs.shader == rhs.shader )
133         {
134           if( lhs.textureResourceId == rhs.textureResourceId )
135           {
136             return lhs.geometry < rhs.geometry;
137           }
138           return lhs.textureResourceId < rhs.textureResourceId;
139         }
140         return lhs.shader < rhs.shader;
141       }
142       return lhs.zValue > rhs.zValue;
143     }
144   }
145   else
146   {
147     return lhsIsOpaque;
148   }
149 }
150
151 /**
152  * Function which sorts render items by clipping hierarchy, then Z function and instance ptrs of shader / geometry / material.
153  * @param[in] lhs Left hand side item
154  * @param[in] rhs Right hand side item
155  * @return True if left item is greater than right
156  */
157 bool CompareItems3DWithClipping( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
158 {
159   // Items must be sorted in order of clipping first, otherwise incorrect clipping regions could be used.
160   if( lhs.renderItem->mNode->mClippingSortModifier == rhs.renderItem->mNode->mClippingSortModifier )
161   {
162     return CompareItems3D( lhs, rhs );
163   }
164
165   return lhs.renderItem->mNode->mClippingSortModifier < rhs.renderItem->mNode->mClippingSortModifier;
166 }
167
168 /**
169  * Add a renderer to the list
170  * @param updateBufferIndex to read the model matrix from
171  * @param renderList to add the item to
172  * @param renderable Node-Renderer pair
173  * @param viewMatrix used to calculate modelview matrix for the item
174  * @param camera The camera used to render
175  * @param isLayer3d Whether we are processing a 3D layer or not
176  * @param cull Whether frustum culling is enabled or not
177  */
178 inline void AddRendererToRenderList( BufferIndex updateBufferIndex,
179                                      RenderList& renderList,
180                                      Renderable& renderable,
181                                      const Matrix& viewMatrix,
182                                      SceneGraph::Camera& camera,
183                                      bool isLayer3d,
184                                      bool cull )
185 {
186   bool inside( true );
187   if ( cull && !renderable.mRenderer->GetShader().HintEnabled( Dali::Shader::Hint::MODIFIES_GEOMETRY ) )
188   {
189     const Vector4& boundingSphere = renderable.mNode->GetBoundingSphere();
190     inside = (boundingSphere.w > Math::MACHINE_EPSILON_1000) &&
191              (camera.CheckSphereInFrustum( updateBufferIndex, Vector3(boundingSphere), boundingSphere.w ) );
192   }
193
194   if ( inside )
195   {
196     Renderer::Opacity opacity = renderable.mRenderer->GetOpacity( updateBufferIndex, *renderable.mNode );
197     if( opacity != Renderer::TRANSPARENT )
198     {
199       // Get the next free RenderItem.
200       RenderItem& item = renderList.GetNextFreeItem();
201       item.mRenderer = &renderable.mRenderer->GetRenderer();
202       item.mNode = renderable.mNode;
203       item.mIsOpaque = ( opacity == Renderer::OPAQUE );
204       item.mDepthIndex = renderable.mRenderer->GetDepthIndex();
205
206       if( !isLayer3d )
207       {
208         item.mDepthIndex += static_cast<int>( renderable.mNode->GetDepth() ) * Dali::Layer::TREE_DEPTH_MULTIPLIER;
209       }
210
211       // Save ModelView matrix onto the item.
212       renderable.mNode->GetWorldMatrixAndSize( item.mModelMatrix, item.mSize );
213       Matrix::Multiply( item.mModelViewMatrix, item.mModelMatrix, viewMatrix );
214     }
215   }
216 }
217
218 /**
219  * Add all renderers to the list
220  * @param updateBufferIndex to read the model matrix from
221  * @param renderList to add the items to
222  * @param renderers to render
223  * NodeRendererContainer Node-Renderer pairs
224  * @param viewMatrix used to calculate modelview matrix for the items
225  * @param camera The camera used to render
226  * @param isLayer3d Whether we are processing a 3D layer or not
227  * @param cull Whether frustum culling is enabled or not
228  */
229 inline void AddRenderersToRenderList( BufferIndex updateBufferIndex,
230                                       RenderList& renderList,
231                                       RenderableContainer& renderers,
232                                       const Matrix& viewMatrix,
233                                       SceneGraph::Camera& camera,
234                                       bool isLayer3d,
235                                       bool cull )
236 {
237   DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, "AddRenderersToRenderList()\n");
238
239   unsigned int rendererCount( renderers.Size() );
240   for( unsigned int i(0); i < rendererCount; ++i )
241   {
242     AddRendererToRenderList( updateBufferIndex, renderList, renderers[i], viewMatrix, camera, isLayer3d, cull );
243   }
244 }
245
246 /**
247  * Try to reuse cached RenderItems from the RenderList
248  * This avoids recalculating the model view matrices in case this part of the scene was static
249  * An example case is a toolbar layer that rarely changes or a popup on top of the rest of the stage
250  * @param layer that is being processed
251  * @param renderList that is cached from frame N-1
252  * @param renderables list of renderables
253  */
254 inline bool TryReuseCachedRenderers( Layer& layer,
255                                      RenderList& renderList,
256                                      RenderableContainer& renderables )
257 {
258   bool retValue = false;
259   size_t renderableCount = renderables.Size();
260   // Check that the cached list originates from this layer and that the counts match
261   if( ( renderList.GetSourceLayer() == &layer )&&
262       ( renderList.GetCachedItemCount() == renderableCount ) )
263   {
264     // Check that all the same renderers are there. This gives us additional security in avoiding rendering the wrong things.
265     // Render list is sorted so at this stage renderers may be in different order.
266     // Therefore we check a combined sum of all renderer addresses.
267     size_t checkSumNew = 0;
268     size_t checkSumOld = 0;
269     for( size_t index = 0; index < renderableCount; ++index )
270     {
271       const Render::Renderer& renderer = renderables[index].mRenderer->GetRenderer();
272       checkSumNew += size_t( &renderer );
273       checkSumOld += size_t( &renderList.GetRenderer( index ) );
274     }
275     if( checkSumNew == checkSumOld )
276     {
277       // tell list to reuse its existing items
278       renderList.ReuseCachedItems();
279       retValue = true;
280     }
281   }
282   return retValue;
283 }
284
285 inline bool SetupRenderList( RenderableContainer& renderables,
286                              Layer& layer,
287                              RenderInstruction& instruction,
288                              bool tryReuseRenderList,
289                              RenderList** renderList )
290 {
291   *renderList = &( instruction.GetNextFreeRenderList( renderables.Size() ) );
292   ( *renderList )->SetClipping( layer.IsClipping(), layer.GetClippingBox() );
293   ( *renderList )->SetSourceLayer( &layer );
294
295   // Try to reuse cached RenderItems from last time around.
296   return ( tryReuseRenderList && TryReuseCachedRenderers( layer, **renderList, renderables ) );
297 }
298
299 } // Anonymous namespace.
300
301
302 RenderInstructionProcessor::RenderInstructionProcessor()
303 : mSortingHelper()
304 {
305   // Set up a container of comparators for fast run-time selection.
306   mSortComparitors.Reserve( 4u );
307
308   mSortComparitors.PushBack( CompareItems );
309   mSortComparitors.PushBack( CompareItemsWithClipping );
310   mSortComparitors.PushBack( CompareItems3D );
311   mSortComparitors.PushBack( CompareItems3DWithClipping );
312 }
313
314 RenderInstructionProcessor::~RenderInstructionProcessor()
315 {
316 }
317
318 inline void RenderInstructionProcessor::SortRenderItems( BufferIndex bufferIndex, RenderList& renderList, Layer& layer, bool respectClippingOrder )
319 {
320   const size_t renderableCount = renderList.Count();
321   // Reserve space if needed.
322   const unsigned int oldcapacity = mSortingHelper.size();
323   if( oldcapacity < renderableCount )
324   {
325     mSortingHelper.reserve( renderableCount );
326     // Add real objects (reserve does not construct objects).
327     mSortingHelper.insert( mSortingHelper.begin() + oldcapacity,
328                           (renderableCount - oldcapacity),
329                           RenderInstructionProcessor::SortAttributes() );
330   }
331   else
332   {
333     // Clear extra elements from helper, does not decrease capability.
334     mSortingHelper.resize( renderableCount );
335   }
336
337   // Calculate the sorting value, once per item by calling the layers sort function.
338   // Using an if and two for-loops rather than if inside for as its better for branch prediction.
339   if( layer.UsesDefaultSortFunction() )
340   {
341     for( size_t index = 0; index < renderableCount; ++index )
342     {
343       RenderItem& item = renderList.GetItem( index );
344
345       item.mRenderer->SetSortAttributes( bufferIndex, mSortingHelper[ index ] );
346
347       // The default sorting function should get inlined here.
348       mSortingHelper[ index ].zValue = Internal::Layer::ZValue( item.mModelViewMatrix.GetTranslation3() ) - item.mDepthIndex;
349
350       // Keep the renderitem pointer in the helper so we can quickly reorder items after sort.
351       mSortingHelper[ index ].renderItem = &item;
352     }
353   }
354   else
355   {
356     const Dali::Layer::SortFunctionType sortFunction = layer.GetSortFunction();
357     for( size_t index = 0; index < renderableCount; ++index )
358     {
359       RenderItem& item = renderList.GetItem( index );
360
361       item.mRenderer->SetSortAttributes( bufferIndex, mSortingHelper[ index ] );
362       mSortingHelper[ index ].zValue = (*sortFunction)( item.mModelViewMatrix.GetTranslation3() ) - item.mDepthIndex;
363
364       // Keep the RenderItem pointer in the helper so we can quickly reorder items after sort.
365       mSortingHelper[ index ].renderItem = &item;
366     }
367   }
368
369   // Here we detemine which comparitor (of the 4) to use.
370   // The comparitors work like a bitmask.
371   //   1 << 0  is added to select a clipping comparitor.
372   //   1 << 1  is added for 3D comparitors.
373   const unsigned int comparitorIndex = ( respectClippingOrder                         ? ( 1u << 0u ) : 0u ) |
374                                        ( layer.GetBehavior() == Dali::Layer::LAYER_3D ? ( 1u << 1u ) : 0u );
375
376   std::stable_sort( mSortingHelper.begin(), mSortingHelper.end(), mSortComparitors[ comparitorIndex ] );
377
378   // Reorder / re-populate the RenderItems in the RenderList to correct order based on the sortinghelper.
379   DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, "Sorted Transparent List:\n");
380   RenderItemContainer::Iterator renderListIter = renderList.GetContainer().Begin();
381   for( unsigned int index = 0; index < renderableCount; ++index, ++renderListIter )
382   {
383     *renderListIter = mSortingHelper[ index ].renderItem;
384     DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, "  sortedList[%d] = %p\n", index, mSortingHelper[ index ].renderItem->mRenderer);
385   }
386 }
387
388 void RenderInstructionProcessor::Prepare( BufferIndex updateBufferIndex,
389                                           SortedLayerPointers& sortedLayers,
390                                           RenderTask& renderTask,
391                                           bool cull,
392                                           bool hasClippingNodes,
393                                           RenderInstructionContainer& instructions )
394 {
395   // Retrieve the RenderInstruction buffer from the RenderInstructionContainer
396   // then populate with instructions.
397   RenderInstruction& instruction = instructions.GetNextInstruction( updateBufferIndex );
398   renderTask.PrepareRenderInstruction( instruction, updateBufferIndex );
399   bool viewMatrixHasNotChanged = !renderTask.ViewMatrixUpdated();
400
401   const Matrix& viewMatrix = renderTask.GetViewMatrix( updateBufferIndex );
402   SceneGraph::Camera& camera = renderTask.GetCamera();
403
404   const SortedLayersIter endIter = sortedLayers.end();
405   for( SortedLayersIter iter = sortedLayers.begin(); iter != endIter; ++iter )
406   {
407     Layer& layer = **iter;
408     const bool tryReuseRenderList( viewMatrixHasNotChanged && layer.CanReuseRenderers( &renderTask.GetCamera() ) );
409     const bool isLayer3D = layer.GetBehavior() == Dali::Layer::LAYER_3D;
410     RenderList* renderList = NULL;
411
412     if( !layer.colorRenderables.Empty() )
413     {
414       RenderableContainer& renderables = layer.colorRenderables;
415
416       if( !SetupRenderList( renderables, layer, instruction, tryReuseRenderList, &renderList ) )
417       {
418         renderList->SetHasColorRenderItems( true );
419         AddRenderersToRenderList( updateBufferIndex, *renderList, renderables, viewMatrix, camera, isLayer3D, cull );
420
421         // We only use the clipping version of the sort comparitor if any clipping nodes exist within the RenderList.
422         SortRenderItems( updateBufferIndex, *renderList, layer, hasClippingNodes );
423       }
424     }
425
426     if( !layer.overlayRenderables.Empty() )
427     {
428       RenderableContainer& renderables = layer.overlayRenderables;
429
430       if( !SetupRenderList( renderables, layer, instruction, tryReuseRenderList, &renderList ) )
431       {
432         renderList->SetHasColorRenderItems( false );
433         AddRenderersToRenderList( updateBufferIndex, *renderList, renderables, viewMatrix, camera, isLayer3D, cull );
434
435         // Clipping hierarchy is irrelevant when sorting overlay items, so we specify using the non-clipping version of the sort comparitor.
436         SortRenderItems( updateBufferIndex, *renderList, layer, false );
437       }
438     }
439   }
440
441   // Inform the render instruction that all renderers have been added and this frame is complete.
442   instruction.UpdateCompleted();
443 }
444
445
446 } // SceneGraph
447
448 } // Internal
449
450 } // Dali