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