[dali_2.3.28] Merge branch 'devel/master'
[platform/core/uifw/dali-core.git] / dali / internal / update / manager / render-instruction-processor.cpp
1 /*
2  * Copyright (c) 2024 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/common/matrix-utils.h>
24 #include <dali/internal/event/actors/layer-impl.h> // for the default sorting function
25 #include <dali/internal/render/common/render-instruction-container.h>
26 #include <dali/internal/render/common/render-instruction.h>
27 #include <dali/internal/render/common/render-item.h>
28 #include <dali/internal/render/common/render-tracker.h>
29 #include <dali/internal/render/renderers/render-renderer.h>
30 #include <dali/internal/render/shaders/render-shader.h>
31 #include <dali/internal/update/manager/sorted-layers.h>
32 #include <dali/internal/update/nodes/partial-rendering-data.h>
33 #include <dali/internal/update/nodes/scene-graph-layer.h>
34 #include <dali/internal/update/render-tasks/scene-graph-render-task.h>
35 #include <dali/internal/update/rendering/scene-graph-texture-set.h>
36 #include <dali/public-api/actors/layer.h>
37
38 namespace
39 {
40 #if defined(DEBUG_ENABLED)
41 Debug::Filter* gRenderListLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_LISTS");
42 #endif
43 } // namespace
44
45 namespace Dali
46 {
47 namespace Internal
48 {
49 namespace SceneGraph
50 {
51 namespace
52 {
53 /**
54  * Function which compares render items by shader/textureSet/geometry
55  * @param[in] lhs Left hand side item
56  * @param[in] rhs Right hand side item
57  * @return True if left item is greater than right
58  */
59 inline bool PartialCompareItems(const RenderInstructionProcessor::SortAttributes& lhs,
60                                 const RenderInstructionProcessor::SortAttributes& rhs)
61 {
62   if(lhs.shader == rhs.shader)
63   {
64     if(lhs.textureSet == rhs.textureSet)
65     {
66       return lhs.geometry < rhs.geometry;
67     }
68     return lhs.textureSet < rhs.textureSet;
69   }
70   return lhs.shader < rhs.shader;
71 }
72
73 /**
74  * Function which sorts render items by depth index then by instance
75  * ptrs of shader/textureSet/geometry.
76  * @param[in] lhs Left hand side item
77  * @param[in] rhs Right hand side item
78  * @return True if left item is greater than right
79  */
80 bool CompareItems(const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs)
81 {
82   // @todo Consider replacing all these sortAttributes with a single long int that
83   // encapsulates the same data (e.g. the middle-order bits of the ptrs).
84   if(lhs.renderItem->mDepthIndex == rhs.renderItem->mDepthIndex)
85   {
86     return PartialCompareItems(lhs, rhs);
87   }
88   return lhs.renderItem->mDepthIndex < rhs.renderItem->mDepthIndex;
89 }
90
91 /**
92  * Function which sorts the render items by Z function, then
93  * by instance ptrs of shader / geometry / material.
94  * @param[in] lhs Left hand side item
95  * @param[in] rhs Right hand side item
96  * @return True if left item is greater than right
97  */
98 bool CompareItems3D(const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs)
99 {
100   const bool lhsIsOpaque = lhs.renderItem->mIsOpaque;
101   if(lhsIsOpaque == rhs.renderItem->mIsOpaque)
102   {
103     if(lhsIsOpaque)
104     {
105       // If both RenderItems are opaque, sort using shader, then material then geometry.
106       return PartialCompareItems(lhs, rhs);
107     }
108     else
109     {
110       if(lhs.renderItem->mDepthIndex != rhs.renderItem->mDepthIndex)
111       {
112         return lhs.renderItem->mDepthIndex < rhs.renderItem->mDepthIndex;
113       }
114
115       // If both RenderItems are transparent, sort using Z, then shader, then material, then geometry.
116       if(Equals(lhs.zValue, rhs.zValue))
117       {
118         return PartialCompareItems(lhs, rhs);
119       }
120       return lhs.zValue > rhs.zValue;
121     }
122   }
123   else
124   {
125     return lhsIsOpaque;
126   }
127 }
128
129 /**
130  * Function which sorts render items by clipping hierarchy, then Z function and instance ptrs of shader / geometry / material.
131  * @param[in] lhs Left hand side item
132  * @param[in] rhs Right hand side item
133  * @return True if left item is greater than right
134  */
135 bool CompareItems3DWithClipping(const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs)
136 {
137   // Items must be sorted in order of clipping first, otherwise incorrect clipping regions could be used.
138   if(lhs.renderItem->mNode->mClippingSortModifier == rhs.renderItem->mNode->mClippingSortModifier)
139   {
140     return CompareItems3D(lhs, rhs);
141   }
142
143   return lhs.renderItem->mNode->mClippingSortModifier < rhs.renderItem->mNode->mClippingSortModifier;
144 }
145
146 /**
147  * Set the update area of the node
148  * @param[in] node The node of the renderer
149  * @param[in] isLayer3d Whether we are processing a 3D layer or not
150  * @param[in,out] nodeWorldMatrix The world matrix of the node
151  * @param[in,out] nodeSize The size of the node
152  * @param[in,out] nodeUpdateArea The update area of the node
153  *
154  * @return True if node use it's own UpdateAreaHint, or z transform occured. False if we use nodeUpdateArea equal with Vector4(0, 0, nodeSize.width, nodeSize.height).
155  */
156 inline bool SetNodeUpdateArea(Node* node, bool isLayer3d, Matrix& nodeWorldMatrix, Vector3& nodeSize, Vector4& nodeUpdateArea)
157 {
158   node->GetWorldMatrixAndSize(nodeWorldMatrix, nodeSize);
159
160   if(node->GetUpdateAreaHint() == Vector4::ZERO)
161   {
162     if(isLayer3d)
163     {
164       return true;
165     }
166     // RenderItem::CalculateViewportSpaceAABB cannot cope with z transform
167     // I don't use item.mModelMatrix.GetTransformComponents() for z transform, would be too slow
168     Vector3 zaxis = nodeWorldMatrix.GetZAxis();
169     if(EqualsZero(zaxis.x) && EqualsZero(zaxis.y))
170     {
171       nodeUpdateArea = Vector4(0.0f, 0.0f, nodeSize.width, nodeSize.height);
172       return false;
173     }
174     // Keep nodeUpdateArea as Vector4::ZERO, and return true.
175     return true;
176   }
177   else
178   {
179     nodeUpdateArea = node->GetUpdateAreaHint();
180     return true;
181   }
182 }
183
184 /**
185  * Add a renderer to the list
186  * @param updateBufferIndex to read the model matrix from
187  * @param renderPass render pass for this render instruction
188  * @param renderList to add the item to
189  * @param renderable Node-Renderer pair
190  * @param viewMatrix used to calculate modelview matrix for the item
191  * @param viewMatrixChanged Whether view matrix chagned for this time or not.
192  * @param camera The camera used to render
193  * @param isLayer3d Whether we are processing a 3D layer or not
194  * @param viewportSet Whether the viewport is set or not
195  * @param viewport The viewport
196  * @param cullingEnabled Whether frustum culling is enabled or not
197  * @param stopperNode Marker node that stops rendering(must be rendered)
198  */
199 inline void AddRendererToRenderList(BufferIndex               updateBufferIndex,
200                                     uint32_t                  renderPass,
201                                     RenderList&               renderList,
202                                     Renderable&               renderable,
203                                     const Matrix&             viewMatrix,
204                                     bool                      viewMatrixChanged,
205                                     const SceneGraph::Camera& camera,
206                                     bool                      isLayer3d,
207                                     bool                      viewportSet,
208                                     const Viewport&           viewport,
209                                     bool                      cullingEnabled,
210                                     Node*                     stopperNode)
211 {
212   bool    inside(true);
213   Node*   node = renderable.mNode;
214   Matrix  nodeWorldMatrix(false);
215   Vector3 nodeScale;
216   Vector3 nodeSize;
217   Vector4 nodeUpdateArea;
218   bool    nodeUpdateAreaSet(false);
219   Matrix  nodeModelViewMatrix(false);
220   bool    nodeModelViewMatrixSet(false);
221
222   const bool rendererExist(renderable.mRenderer);
223
224   // Don't cull items which have render callback
225   bool hasRenderCallback = (rendererExist && renderable.mRenderer->GetRenderCallback());
226
227   auto requiredInsideCheck = [&]() {
228     if(node != stopperNode &&
229        cullingEnabled &&
230        !hasRenderCallback &&
231        node->GetClippingMode() == ClippingMode::DISABLED &&
232        rendererExist)
233     {
234       const auto& shaderData = renderable.mRenderer->GetShader().GetShaderData(renderPass);
235       return (shaderData && !shaderData->HintEnabled(Dali::Shader::Hint::MODIFIES_GEOMETRY));
236     }
237     return false;
238   };
239
240   if(requiredInsideCheck())
241   {
242     const Vector4& boundingSphere = node->GetBoundingSphere();
243
244     inside = (boundingSphere.w > Math::MACHINE_EPSILON_1000) &&
245              (camera.CheckSphereInFrustum(updateBufferIndex, Vector3(boundingSphere), boundingSphere.w));
246
247     if(inside && !isLayer3d && viewportSet)
248     {
249       SetNodeUpdateArea(node, isLayer3d, nodeWorldMatrix, nodeSize, nodeUpdateArea);
250       nodeUpdateAreaSet = true;
251
252       nodeScale = nodeWorldMatrix.GetScale();
253
254       const Vector3& size = Vector3(nodeUpdateArea.z, nodeUpdateArea.w, 0.0f) * nodeScale;
255
256       if(size.LengthSquared() > Math::MACHINE_EPSILON_1000)
257       {
258         MatrixUtils::MultiplyTransformMatrix(nodeModelViewMatrix, nodeWorldMatrix, viewMatrix);
259         nodeModelViewMatrixSet = true;
260
261         // Assume actors are at z=0, compute AABB in view space & test rect intersection
262         // against z=0 plane boundaries for frustum. (NOT viewport). This should take into account
263         // magnification due to FOV etc.
264
265         // TODO : Below logic might need to refactor it.
266         // If camera is Perspective, we need to calculate clipping box by FoV. Currently, we just believe default camera setup OrthographicSize well.
267         //  - If then, It must use math calculate like tan(fov) internally. So, we might need calculate it only one times, and cache.
268         ClippingBox boundingBox = RenderItem::CalculateTransformSpaceAABB(nodeModelViewMatrix, Vector3(nodeUpdateArea.x, nodeUpdateArea.y, 0.0f), Vector3(nodeUpdateArea.z, nodeUpdateArea.w, 0.0f));
269         ClippingBox clippingBox = camera.GetOrthographicClippingBox(updateBufferIndex);
270         inside                  = clippingBox.Intersects(boundingBox);
271       }
272     }
273     /*
274      * Note, the API Camera::CheckAABBInFrustum() can be used to test if a bounding box is (partially/fully) inside the view frustum.
275      */
276   }
277
278   if(inside)
279   {
280     bool skipRender(false);
281     bool isOpaque = true;
282     if(!hasRenderCallback)
283     {
284       const bool isVisualRendererUnder3D = (isLayer3d && !!(renderable.mRenderer && renderable.mRenderer->GetVisualProperties()));
285
286       const Renderer::OpacityType opacityType = rendererExist ? (isVisualRendererUnder3D ? Renderer::TRANSLUCENT : renderable.mRenderer->GetOpacityType(updateBufferIndex, renderPass, *node)) : Renderer::OPAQUE;
287
288       // We can skip render when node is not clipping and transparent
289       // We must not skip when node is a stopper
290       skipRender = (opacityType == Renderer::TRANSPARENT &&
291           node->GetClippingMode() == ClippingMode::DISABLED &&
292           node != stopperNode);
293
294       isOpaque = (opacityType == Renderer::OPAQUE);
295     }
296
297     if(!skipRender)
298     {
299       // Get the next free RenderItem.
300       RenderItem& item = renderList.GetNextFreeItem();
301
302       item.mNode       = node;
303       item.mIsOpaque   = isOpaque;
304       item.mDepthIndex = isLayer3d ? 0 : node->GetDepthIndex();
305
306       if(DALI_LIKELY(rendererExist))
307       {
308         item.mRenderer   = renderable.mRenderer->GetRenderer();
309         item.mTextureSet = renderable.mRenderer->GetTextureSet();
310         item.mDepthIndex += renderable.mRenderer->GetDepthIndex();
311       }
312       else
313       {
314         item.mRenderer = Render::RendererKey{};
315       }
316
317       item.mIsUpdated = (viewMatrixChanged || isLayer3d);
318
319       if(!nodeUpdateAreaSet)
320       {
321         SetNodeUpdateArea(node, isLayer3d, nodeWorldMatrix, nodeSize, nodeUpdateArea);
322         nodeScale = nodeWorldMatrix.GetScale();
323       }
324
325       item.mScale       = nodeScale;
326       item.mSize        = nodeSize;
327       item.mUpdateArea  = nodeUpdateArea;
328       item.mModelMatrix = nodeWorldMatrix;
329
330       if(!nodeModelViewMatrixSet)
331       {
332         MatrixUtils::MultiplyTransformMatrix(nodeModelViewMatrix, nodeWorldMatrix, viewMatrix);
333       }
334       item.mModelViewMatrix = nodeModelViewMatrix;
335
336       auto& nodePartialRenderingData = node->GetPartialRenderingData();
337
338       if(nodePartialRenderingData.mUpdateDecay == PartialRenderingData::Decay::UPDATED_CURRENT_FRAME)
339       {
340         item.mIsUpdated = nodePartialRenderingData.mUpdated;
341       }
342       else
343       {
344         PartialRenderingData partialRenderingData;
345         partialRenderingData.color               = node->GetWorldColor(updateBufferIndex);
346         partialRenderingData.matrix              = item.mModelMatrix;
347         partialRenderingData.updatedPositionSize = item.mUpdateArea;
348         partialRenderingData.size                = item.mSize;
349
350         // Update current node's partial update data as latest.
351         if(nodePartialRenderingData.IsUpdated(partialRenderingData))
352         {
353           item.mIsUpdated = true;
354           nodePartialRenderingData.Update(partialRenderingData);
355         }
356       }
357     }
358
359     node->SetCulled(updateBufferIndex, false);
360   }
361   else
362   {
363     node->SetCulled(updateBufferIndex, true);
364   }
365 }
366
367 /**
368  * Add all renderers to the list
369  * @param updateBufferIndex to read the model matrix from
370  * @param renderPass render pass for this render instruction
371  * @param renderList to add the items to
372  * @param renderers to render NodeRendererContainer Node-Renderer pairs
373  * @param viewMatrix used to calculate modelview matrix for the items
374  * @param viewMatrixChanged Whether view matrix chagned for this time or not.
375  * @param camera The camera used to render
376  * @param isLayer3d Whether we are processing a 3D layer or not
377  * @param viewportSet Whether the viewport is set or not
378  * @param viewport The viewport
379  * @param cullingEnabled Whether frustum culling is enabled or not
380  * @param stopperNode Marker node that stops rendering(must be rendered)
381  */
382 inline void AddRenderersToRenderList(BufferIndex               updateBufferIndex,
383                                      uint32_t                  renderPass,
384                                      RenderList&               renderList,
385                                      RenderableContainer&      renderers,
386                                      const Matrix&             viewMatrix,
387                                      bool                      viewMatrixChanged,
388                                      const SceneGraph::Camera& camera,
389                                      bool                      isLayer3d,
390                                      bool                      viewportSet,
391                                      const Viewport&           viewport,
392                                      bool                      cullingEnabled,
393                                      Node*                     stopperNode)
394 {
395   DALI_LOG_INFO(gRenderListLogFilter, Debug::Verbose, "AddRenderersToRenderList()\n");
396
397   for(auto&& renderer : renderers)
398   {
399     AddRendererToRenderList(updateBufferIndex,
400                             renderPass,
401                             renderList,
402                             renderer,
403                             viewMatrix,
404                             viewMatrixChanged,
405                             camera,
406                             isLayer3d,
407                             viewportSet,
408                             viewport,
409                             cullingEnabled,
410                             stopperNode);
411   }
412 }
413
414 /**
415  * Try to reuse cached RenderItems from the RenderList
416  * This avoids recalculating the model view matrices in case this part of the scene was static
417  * An example case is a toolbar layer that rarely changes or a popup on top of the rest of the stage
418  * @param layer that is being processed
419  * @param renderList that is cached from frame N-1
420  * @param renderables list of renderables
421  */
422 inline bool TryReuseCachedRenderers(Layer&               layer,
423                                     RenderList&          renderList,
424                                     RenderableContainer& renderables)
425 {
426   bool     retValue        = false;
427   uint32_t renderableCount = static_cast<uint32_t>(renderables.Size());
428   // Check that the cached list originates from this layer and that the counts match
429   if((renderList.GetSourceLayer() == &layer) &&
430      (renderList.GetCachedItemCount() == renderableCount))
431   {
432     // Check that all the same renderers are there. This gives us additional security in avoiding rendering the wrong things.
433     // Render list is sorted so at this stage renderers may be in different order.
434     // Therefore we check a combined sum of all renderer addresses.
435     size_t checkSumNew = 0;
436     size_t checkSumOld = 0;
437     //@todo just use keys, don't deref.
438     for(uint32_t index = 0; index < renderableCount; ++index)
439     {
440       if(DALI_LIKELY(renderables[index].mRenderer))
441       {
442         Render::RendererKey renderer = renderables[index].mRenderer->GetRenderer();
443         checkSumNew += renderer.Value();
444       }
445       if(DALI_LIKELY(renderList.GetItem(index).mRenderer))
446       {
447         checkSumOld += renderList.GetItem(index).mRenderer.Value();
448       }
449     }
450     if(checkSumNew == checkSumOld)
451     {
452       // tell list to reuse its existing items
453       renderList.ReuseCachedItems();
454       retValue = true;
455     }
456   }
457
458   return retValue;
459 }
460
461 inline bool SetupRenderList(RenderableContainer& renderables,
462                             Layer&               layer,
463                             RenderInstruction&   instruction,
464                             bool                 tryReuseRenderList,
465                             RenderList**         renderList)
466 {
467   *renderList = &(instruction.GetNextFreeRenderList(renderables.Size()));
468   (*renderList)->SetClipping(layer.IsClipping(), layer.GetClippingBox());
469   (*renderList)->SetSourceLayer(&layer);
470
471   // Try to reuse cached RenderItems from last time around.
472   return (tryReuseRenderList && TryReuseCachedRenderers(layer, **renderList, renderables));
473 }
474
475 } // Anonymous namespace.
476
477 RenderInstructionProcessor::RenderInstructionProcessor()
478 : mSortingHelper()
479 {
480   // Set up a container of comparators for fast run-time selection.
481   mSortComparitors.Reserve(3u);
482
483   mSortComparitors.PushBack(CompareItems);
484   mSortComparitors.PushBack(CompareItems3D);
485   mSortComparitors.PushBack(CompareItems3DWithClipping);
486 }
487
488 RenderInstructionProcessor::~RenderInstructionProcessor() = default;
489
490 inline void RenderInstructionProcessor::SortRenderItems(BufferIndex bufferIndex, RenderList& renderList, Layer& layer, bool respectClippingOrder, bool isOrthographicCamera)
491 {
492   const uint32_t renderableCount = static_cast<uint32_t>(renderList.Count());
493   // Reserve space if needed.
494   const uint32_t oldcapacity = static_cast<uint32_t>(mSortingHelper.size());
495   if(oldcapacity < renderableCount)
496   {
497     mSortingHelper.reserve(renderableCount);
498     // Add real objects (reserve does not construct objects).
499     mSortingHelper.insert(mSortingHelper.begin() + oldcapacity,
500                           (renderableCount - oldcapacity),
501                           RenderInstructionProcessor::SortAttributes());
502   }
503   else
504   {
505     // Clear extra elements from helper, does not decrease capability.
506     mSortingHelper.resize(renderableCount);
507   }
508
509   // Calculate the sorting value, once per item by calling the layers sort function.
510   // Using an if and two for-loops rather than if inside for as its better for branch prediction.
511
512   // List of zValue calculating functions.
513   const Dali::Layer::SortFunctionType zValueFunctionFromVector3[] = {
514     [](const Vector3& position) { return position.z; },
515     [](const Vector3& position) { return position.LengthSquared(); },
516     layer.GetSortFunction(),
517   };
518
519   // Determine whether we need to use zValue as Euclidean distance or translatoin's z value.
520   // If layer is LAYER_UI or camera is OrthographicProjection mode, we don't need to calculate
521   // renderItem's distance from camera.
522
523   // Here we determine which zValue SortFunctionType (of the 3) to use.
524   //   0 is position z value : Default LAYER_UI or Orthographic camera
525   //   1 is distance square value : Default LAYER_3D and Perspective camera
526   //   2 is user defined function.
527   const int zValueFunctionIndex = layer.UsesDefaultSortFunction() ? ((layer.GetBehavior() == Dali::Layer::LAYER_UI || isOrthographicCamera) ? 0 : 1) : 2;
528
529   for(uint32_t index = 0; index < renderableCount; ++index)
530   {
531     RenderItemKey itemKey = renderList.GetItemKey(index);
532     RenderItem&   item    = *itemKey.Get();
533     if(DALI_LIKELY(item.mRenderer))
534     {
535       item.mRenderer->SetSortAttributes(mSortingHelper[index]);
536     }
537
538     // texture set
539     mSortingHelper[index].textureSet = item.mTextureSet;
540
541     mSortingHelper[index].zValue = zValueFunctionFromVector3[zValueFunctionIndex](item.mModelViewMatrix.GetTranslation3()) - static_cast<float>(item.mDepthIndex);
542
543     // Keep the renderitem pointer in the helper so we can quickly reorder items after sort.
544     mSortingHelper[index].renderItem = itemKey;
545   }
546
547   // Here we determine which comparitor (of the 3) to use.
548   //   0 is LAYER_UI
549   //   1 is LAYER_3D
550   //   2 is LAYER_3D + Clipping
551   const unsigned int comparitorIndex = layer.GetBehavior() == Dali::Layer::LAYER_3D ? respectClippingOrder ? 2u : 1u : 0u;
552
553   std::stable_sort(mSortingHelper.begin(), mSortingHelper.end(), mSortComparitors[comparitorIndex]);
554
555   // Reorder / re-populate the RenderItems in the RenderList to correct order based on the sortinghelper.
556   DALI_LOG_INFO(gRenderListLogFilter, Debug::Verbose, "Sorted Transparent List:\n");
557   RenderItemContainer::Iterator renderListIter = renderList.GetContainer().Begin();
558   for(uint32_t index = 0; index < renderableCount; ++index, ++renderListIter)
559   {
560     *renderListIter = mSortingHelper[index].renderItem;
561     DALI_LOG_INFO(gRenderListLogFilter, Debug::Verbose, "  sortedList[%d] = node : %x renderer : %x\n", index, mSortingHelper[index].renderItem->mNode, mSortingHelper[index].renderItem->mRenderer.Get());
562   }
563 }
564
565 void RenderInstructionProcessor::Prepare(BufferIndex                 updateBufferIndex,
566                                          SortedLayerPointers&        sortedLayers,
567                                          RenderTask&                 renderTask,
568                                          bool                        cull,
569                                          bool                        hasClippingNodes,
570                                          RenderInstructionContainer& instructions)
571 {
572   // Retrieve the RenderInstruction buffer from the RenderInstructionContainer
573   // then populate with instructions.
574   RenderInstruction& instruction             = renderTask.PrepareRenderInstruction(updateBufferIndex);
575   bool               viewMatrixHasNotChanged = !renderTask.ViewMatrixUpdated();
576   bool               isRenderListAdded       = false;
577   bool               isRootLayerDirty        = false;
578
579   const Matrix&             viewMatrix           = renderTask.GetViewMatrix(updateBufferIndex);
580   const SceneGraph::Camera& camera               = renderTask.GetCamera();
581   const bool                isOrthographicCamera = camera.mProjectionMode[0] == Dali::Camera::ProjectionMode::ORTHOGRAPHIC_PROJECTION;
582
583   Viewport viewport;
584   bool     viewportSet = renderTask.QueryViewport(updateBufferIndex, viewport);
585
586   Node* stopperNode = renderTask.GetStopperNode();
587
588   const SortedLayersIter endIter = sortedLayers.end();
589   for(SortedLayersIter iter = sortedLayers.begin(); iter != endIter; ++iter)
590   {
591     Layer&      layer = **iter;
592     const bool  tryReuseRenderList(viewMatrixHasNotChanged && layer.CanReuseRenderers(&camera));
593     const bool  isLayer3D  = layer.GetBehavior() == Dali::Layer::LAYER_3D;
594     RenderList* renderList = nullptr;
595
596     if(layer.IsRoot() && (layer.GetDirtyFlags() != NodePropertyFlags::NOTHING))
597     {
598       // 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
599       isRootLayerDirty = true;
600     }
601
602     if(!layer.colorRenderables.Empty())
603     {
604       RenderableContainer& renderables = layer.colorRenderables;
605
606       if(!SetupRenderList(renderables, layer, instruction, tryReuseRenderList, &renderList))
607       {
608         renderList->SetHasColorRenderItems(true);
609         AddRenderersToRenderList(updateBufferIndex,
610                                  instruction.mRenderPassTag,
611                                  *renderList,
612                                  renderables,
613                                  viewMatrix,
614                                  !viewMatrixHasNotChanged,
615                                  camera,
616                                  isLayer3D,
617                                  viewportSet,
618                                  viewport,
619                                  cull,
620                                  stopperNode);
621
622         // We only use the clipping version of the sort comparitor if any clipping nodes exist within the RenderList.
623         SortRenderItems(updateBufferIndex, *renderList, layer, hasClippingNodes, isOrthographicCamera);
624       }
625       else
626       {
627         renderList->SetHasColorRenderItems(true);
628       }
629
630       isRenderListAdded = true;
631
632       if(stopperNode && renderList->RenderUntil(stopperNode))
633       {
634         break;
635       }
636     }
637
638     if(!layer.overlayRenderables.Empty())
639     {
640       RenderableContainer& renderables = layer.overlayRenderables;
641
642       if(!SetupRenderList(renderables, layer, instruction, tryReuseRenderList, &renderList))
643       {
644         renderList->SetHasColorRenderItems(false);
645         AddRenderersToRenderList(updateBufferIndex,
646                                  instruction.mRenderPassTag,
647                                  *renderList,
648                                  renderables,
649                                  viewMatrix,
650                                  !viewMatrixHasNotChanged,
651                                  camera,
652                                  isLayer3D,
653                                  viewportSet,
654                                  viewport,
655                                  cull,
656                                  stopperNode);
657
658         // Clipping hierarchy is irrelevant when sorting overlay items, so we specify using the non-clipping version of the sort comparitor.
659         SortRenderItems(updateBufferIndex, *renderList, layer, false, isOrthographicCamera);
660       }
661       else
662       {
663         renderList->SetHasColorRenderItems(false);
664       }
665
666       isRenderListAdded = true;
667
668       if(stopperNode && renderList->RenderUntil(stopperNode))
669       {
670         break;
671       }
672     }
673   }
674
675   // Inform the render instruction that all renderers have been added and this frame is complete.
676   instruction.UpdateCompleted();
677
678   if(isRenderListAdded || instruction.mIsClearColorSet || isRootLayerDirty)
679   {
680     instructions.PushBack(updateBufferIndex, &instruction);
681   }
682 }
683
684 } // namespace SceneGraph
685
686 } // namespace Internal
687
688 } // namespace Dali