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