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