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