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