2 * Copyright (c) 2022 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <dali/internal/update/manager/render-instruction-processor.h>
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>
40 #if defined(DEBUG_ENABLED)
41 Debug::Filter* gRenderListLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_LISTS");
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
59 inline bool PartialCompareItems(const RenderInstructionProcessor::SortAttributes& lhs,
60 const RenderInstructionProcessor::SortAttributes& rhs)
62 if(lhs.shader == rhs.shader)
64 if(lhs.textureSet == rhs.textureSet)
66 return lhs.geometry < rhs.geometry;
68 return lhs.textureSet < rhs.textureSet;
70 return lhs.shader < rhs.shader;
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
80 bool CompareItems(const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs)
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)
86 return PartialCompareItems(lhs, rhs);
88 return lhs.renderItem->mDepthIndex < rhs.renderItem->mDepthIndex;
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
98 bool CompareItems3D(const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs)
100 const bool lhsIsOpaque = lhs.renderItem->mIsOpaque;
101 if(lhsIsOpaque == rhs.renderItem->mIsOpaque)
105 // If both RenderItems are opaque, sort using shader, then material then geometry.
106 return PartialCompareItems(lhs, rhs);
110 // If both RenderItems are transparent, sort using Z, then shader, then material, then geometry.
111 if(Equals(lhs.zValue, rhs.zValue))
113 return PartialCompareItems(lhs, rhs);
115 return lhs.zValue > rhs.zValue;
125 * Function which sorts render items by clipping hierarchy, then Z function and instance ptrs of shader / geometry / material.
126 * @param[in] lhs Left hand side item
127 * @param[in] rhs Right hand side item
128 * @return True if left item is greater than right
130 bool CompareItems3DWithClipping(const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs)
132 // Items must be sorted in order of clipping first, otherwise incorrect clipping regions could be used.
133 if(lhs.renderItem->mNode->mClippingSortModifier == rhs.renderItem->mNode->mClippingSortModifier)
135 return CompareItems3D(lhs, rhs);
138 return lhs.renderItem->mNode->mClippingSortModifier < rhs.renderItem->mNode->mClippingSortModifier;
142 * Set the update area of the node
143 * @param[in] node The node of the renderer
144 * @param[in] isLayer3d Whether we are processing a 3D layer or not
145 * @param[in,out] nodeWorldMatrix The world matrix of the node
146 * @param[in,out] nodeSize The size of the node
147 * @param[in,out] nodeUpdateArea The update area of the node
149 * @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).
151 inline bool SetNodeUpdateArea(Node* node, bool isLayer3d, Matrix& nodeWorldMatrix, Vector3& nodeSize, Vector4& nodeUpdateArea)
153 node->GetWorldMatrixAndSize(nodeWorldMatrix, nodeSize);
155 if(node->GetUpdateAreaHint() == Vector4::ZERO)
157 // RenderItem::CalculateViewportSpaceAABB cannot cope with z transform
158 // I don't use item.mModelMatrix.GetTransformComponents() for z transform, would be too slow
159 if(!isLayer3d && nodeWorldMatrix.GetZAxis() == Vector3(0.0f, 0.0f, 1.0f))
161 nodeUpdateArea = Vector4(0.0f, 0.0f, nodeSize.width, nodeSize.height);
164 // Keep nodeUpdateArea as Vector4::ZERO, and return true.
169 nodeUpdateArea = node->GetUpdateAreaHint();
175 * Add a renderer to the list
176 * @param updateBufferIndex to read the model matrix from
177 * @param renderList to add the item to
178 * @param renderable Node-Renderer pair
179 * @param viewMatrix used to calculate modelview matrix for the item
180 * @param camera The camera used to render
181 * @param isLayer3d Whether we are processing a 3D layer or not
182 * @param viewportSet Whether the viewport is set or not
183 * @param viewport The viewport
184 * @param cull Whether frustum culling is enabled or not
186 inline void AddRendererToRenderList(BufferIndex updateBufferIndex,
187 RenderList& renderList,
188 Renderable& renderable,
189 const Matrix& viewMatrix,
190 const SceneGraph::Camera& camera,
193 const Viewport& viewport,
197 Node* node = renderable.mNode;
198 Matrix nodeWorldMatrix(false);
200 Vector4 nodeUpdateArea;
201 bool nodeUpdateAreaSet(false);
202 Matrix nodeModelViewMatrix(false);
203 bool nodeModelViewMatrixSet(false);
205 // Don't cull items which have render callback
206 bool hasRenderCallback = (renderable.mRenderer && renderable.mRenderer->GetRenderCallback());
208 if(cull && renderable.mRenderer && !hasRenderCallback && !renderable.mRenderer->GetShader().HintEnabled(Dali::Shader::Hint::MODIFIES_GEOMETRY) && node->GetClippingMode() == ClippingMode::DISABLED)
210 const Vector4& boundingSphere = node->GetBoundingSphere();
211 inside = (boundingSphere.w > Math::MACHINE_EPSILON_1000) &&
212 (camera.CheckSphereInFrustum(updateBufferIndex, Vector3(boundingSphere), boundingSphere.w));
214 if(inside && !isLayer3d && viewportSet)
216 SetNodeUpdateArea(node, isLayer3d, nodeWorldMatrix, nodeSize, nodeUpdateArea);
217 nodeUpdateAreaSet = true;
219 const Vector3& scale = node->GetWorldScale(updateBufferIndex);
220 const Vector3& size = Vector3(nodeUpdateArea.z, nodeUpdateArea.w, 1.0f) * scale;
222 if(size.LengthSquared() > Math::MACHINE_EPSILON_1000)
224 MatrixUtils::Multiply(nodeModelViewMatrix, nodeWorldMatrix, viewMatrix);
225 nodeModelViewMatrixSet = true;
227 // Assume actors are at z=0, compute AABB in view space & test rect intersection
228 // against z=0 plane boundaries for frustum. (NOT viewport). This should take into account
229 // magnification due to FOV etc.
231 // TODO : Below logic might need to refactor it.
232 // If camera is Perspective, we need to calculate clipping box by FoV. Currently, we just believe default camera setup OrthographicSize well.
233 // - If then, It must use math calculate like tan(fov) internally. So, we might need calculate it only one times, and cache.
234 ClippingBox boundingBox = RenderItem::CalculateTransformSpaceAABB(nodeModelViewMatrix, Vector3(nodeUpdateArea.x, nodeUpdateArea.y, 0.0f), Vector3(nodeUpdateArea.z, nodeUpdateArea.w, 0.0f));
235 ClippingBox clippingBox = camera.GetOrthographicClippingBox(updateBufferIndex);
236 inside = clippingBox.Intersects(boundingBox);
240 * Note, the API Camera::CheckAABBInFrustum() can be used to test if a bounding box is (partially/fully) inside the view frustum.
246 bool skipRender(false);
247 bool isOpaque = true;
248 if(!hasRenderCallback)
250 Renderer::OpacityType opacityType = renderable.mRenderer ? renderable.mRenderer->GetOpacityType(updateBufferIndex, *node) : Renderer::OPAQUE;
252 // We can skip render when node is not clipping and transparent
253 skipRender = (opacityType == Renderer::TRANSPARENT && node->GetClippingMode() == ClippingMode::DISABLED);
255 isOpaque = (opacityType == Renderer::OPAQUE);
260 // Get the next free RenderItem.
261 RenderItem& item = renderList.GetNextFreeItem();
264 item.mIsOpaque = isOpaque;
265 item.mDepthIndex = isLayer3d ? 0 : node->GetDepthIndex();
267 if(DALI_LIKELY(renderable.mRenderer))
269 item.mRenderer = &renderable.mRenderer->GetRenderer();
270 item.mTextureSet = renderable.mRenderer->GetTextureSet();
271 item.mDepthIndex += renderable.mRenderer->GetDepthIndex();
275 item.mRenderer = nullptr;
278 item.mIsUpdated |= isLayer3d;
280 if(!nodeUpdateAreaSet)
282 SetNodeUpdateArea(node, isLayer3d, nodeWorldMatrix, nodeSize, nodeUpdateArea);
285 item.mSize = nodeSize;
286 item.mUpdateArea = nodeUpdateArea;
287 item.mModelMatrix = nodeWorldMatrix;
289 if(!nodeModelViewMatrixSet)
291 MatrixUtils::Multiply(nodeModelViewMatrix, nodeWorldMatrix, viewMatrix);
293 item.mModelViewMatrix = nodeModelViewMatrix;
295 PartialRenderingData partialRenderingData;
296 partialRenderingData.color = node->GetWorldColor(updateBufferIndex);
297 partialRenderingData.matrix = item.mModelViewMatrix;
298 partialRenderingData.updatedPositionSize = item.mUpdateArea;
299 partialRenderingData.size = item.mSize;
301 auto& nodePartialRenderingData = node->GetPartialRenderingData();
302 item.mIsUpdated = nodePartialRenderingData.IsUpdated(partialRenderingData) || item.mIsUpdated;
304 nodePartialRenderingData.Update(partialRenderingData);
308 // Mark as not rendered
309 auto& nodePartialRenderingData = node->GetPartialRenderingData();
310 nodePartialRenderingData.mRendered = false;
313 node->SetCulled(updateBufferIndex, false);
317 // Mark as not rendered
318 auto& nodePartialRenderingData = node->GetPartialRenderingData();
319 nodePartialRenderingData.mRendered = false;
321 node->SetCulled(updateBufferIndex, true);
326 * Add all renderers to the list
327 * @param updateBufferIndex to read the model matrix from
328 * @param renderList to add the items to
329 * @param renderers to render
330 * NodeRendererContainer Node-Renderer pairs
331 * @param viewMatrix used to calculate modelview matrix for the items
332 * @param camera The camera used to render
333 * @param isLayer3d Whether we are processing a 3D layer or not
334 * @param cull Whether frustum culling is enabled or not
336 inline void AddRenderersToRenderList(BufferIndex updateBufferIndex,
337 RenderList& renderList,
338 RenderableContainer& renderers,
339 const Matrix& viewMatrix,
340 const SceneGraph::Camera& camera,
343 const Viewport& viewport,
346 DALI_LOG_INFO(gRenderListLogFilter, Debug::Verbose, "AddRenderersToRenderList()\n");
348 for(auto&& renderer : renderers)
350 AddRendererToRenderList(updateBufferIndex,
363 * Try to reuse cached RenderItems from the RenderList
364 * This avoids recalculating the model view matrices in case this part of the scene was static
365 * An example case is a toolbar layer that rarely changes or a popup on top of the rest of the stage
366 * @param layer that is being processed
367 * @param renderList that is cached from frame N-1
368 * @param renderables list of renderables
370 inline bool TryReuseCachedRenderers(Layer& layer,
371 RenderList& renderList,
372 RenderableContainer& renderables)
374 bool retValue = false;
375 uint32_t renderableCount = static_cast<uint32_t>(renderables.Size());
376 // Check that the cached list originates from this layer and that the counts match
377 if((renderList.GetSourceLayer() == &layer) &&
378 (renderList.GetCachedItemCount() == renderableCount))
380 // Check that all the same renderers are there. This gives us additional security in avoiding rendering the wrong things.
381 // Render list is sorted so at this stage renderers may be in different order.
382 // Therefore we check a combined sum of all renderer addresses.
383 size_t checkSumNew = 0;
384 size_t checkSumOld = 0;
385 for(uint32_t index = 0; index < renderableCount; ++index)
387 if(DALI_LIKELY(renderables[index].mRenderer))
389 const Render::Renderer& renderer = renderables[index].mRenderer->GetRenderer();
390 checkSumNew += reinterpret_cast<std::size_t>(&renderer);
392 if(DALI_LIKELY(renderList.GetItem(index).mRenderer))
394 checkSumOld += reinterpret_cast<std::size_t>(&renderList.GetRenderer(index));
397 if(checkSumNew == checkSumOld)
399 // tell list to reuse its existing items
400 renderList.ReuseCachedItems();
408 inline bool SetupRenderList(RenderableContainer& renderables,
410 RenderInstruction& instruction,
411 bool tryReuseRenderList,
412 RenderList** renderList)
414 *renderList = &(instruction.GetNextFreeRenderList(renderables.Size()));
415 (*renderList)->SetClipping(layer.IsClipping(), layer.GetClippingBox());
416 (*renderList)->SetSourceLayer(&layer);
418 // Try to reuse cached RenderItems from last time around.
419 return (tryReuseRenderList && TryReuseCachedRenderers(layer, **renderList, renderables));
422 } // Anonymous namespace.
424 RenderInstructionProcessor::RenderInstructionProcessor()
427 // Set up a container of comparators for fast run-time selection.
428 mSortComparitors.Reserve(3u);
430 mSortComparitors.PushBack(CompareItems);
431 mSortComparitors.PushBack(CompareItems3D);
432 mSortComparitors.PushBack(CompareItems3DWithClipping);
435 RenderInstructionProcessor::~RenderInstructionProcessor() = default;
437 inline void RenderInstructionProcessor::SortRenderItems(BufferIndex bufferIndex, RenderList& renderList, Layer& layer, bool respectClippingOrder, bool isOrthographicCamera)
439 const uint32_t renderableCount = static_cast<uint32_t>(renderList.Count());
440 // Reserve space if needed.
441 const uint32_t oldcapacity = static_cast<uint32_t>(mSortingHelper.size());
442 if(oldcapacity < renderableCount)
444 mSortingHelper.reserve(renderableCount);
445 // Add real objects (reserve does not construct objects).
446 mSortingHelper.insert(mSortingHelper.begin() + oldcapacity,
447 (renderableCount - oldcapacity),
448 RenderInstructionProcessor::SortAttributes());
452 // Clear extra elements from helper, does not decrease capability.
453 mSortingHelper.resize(renderableCount);
456 // Calculate the sorting value, once per item by calling the layers sort function.
457 // Using an if and two for-loops rather than if inside for as its better for branch prediction.
459 // List of zValue calculating functions.
460 const Dali::Layer::SortFunctionType zValueFunctionFromVector3[] = {
461 [](const Vector3& position) { return position.z; },
462 [](const Vector3& position) { return position.LengthSquared(); },
463 layer.GetSortFunction(),
466 // Determine whether we need to use zValue as Euclidean distance or translatoin's z value.
467 // If layer is LAYER_UI or camera is OrthographicProjection mode, we don't need to calculate
468 // renderItem's distance from camera.
470 // Here we determine which zValue SortFunctionType (of the 3) to use.
471 // 0 is position z value : Default LAYER_UI or Orthographic camera
472 // 1 is distance square value : Default LAYER_3D and Perspective camera
473 // 2 is user defined function.
474 const int zValueFunctionIndex = layer.UsesDefaultSortFunction() ? ((layer.GetBehavior() == Dali::Layer::LAYER_UI || isOrthographicCamera) ? 0 : 1) : 2;
476 for(uint32_t index = 0; index < renderableCount; ++index)
478 RenderItem& item = renderList.GetItem(index);
480 if(DALI_LIKELY(item.mRenderer))
482 item.mRenderer->SetSortAttributes(mSortingHelper[index]);
486 mSortingHelper[index].textureSet = item.mTextureSet;
488 mSortingHelper[index].zValue = zValueFunctionFromVector3[zValueFunctionIndex](item.mModelViewMatrix.GetTranslation3()) - static_cast<float>(item.mDepthIndex);
490 // Keep the renderitem pointer in the helper so we can quickly reorder items after sort.
491 mSortingHelper[index].renderItem = &item;
494 // Here we determine which comparitor (of the 3) to use.
497 // 2 is LAYER_3D + Clipping
498 const unsigned int comparitorIndex = layer.GetBehavior() == Dali::Layer::LAYER_3D ? respectClippingOrder ? 2u : 1u : 0u;
500 std::stable_sort(mSortingHelper.begin(), mSortingHelper.end(), mSortComparitors[comparitorIndex]);
502 // Reorder / re-populate the RenderItems in the RenderList to correct order based on the sortinghelper.
503 DALI_LOG_INFO(gRenderListLogFilter, Debug::Verbose, "Sorted Transparent List:\n");
504 RenderItemContainer::Iterator renderListIter = renderList.GetContainer().Begin();
505 for(uint32_t index = 0; index < renderableCount; ++index, ++renderListIter)
507 *renderListIter = mSortingHelper[index].renderItem;
508 DALI_LOG_INFO(gRenderListLogFilter, Debug::Verbose, " sortedList[%d] = %p\n", index, mSortingHelper[index].renderItem->mRenderer);
512 void RenderInstructionProcessor::Prepare(BufferIndex updateBufferIndex,
513 SortedLayerPointers& sortedLayers,
514 RenderTask& renderTask,
516 bool hasClippingNodes,
517 RenderInstructionContainer& instructions)
519 // Retrieve the RenderInstruction buffer from the RenderInstructionContainer
520 // then populate with instructions.
521 RenderInstruction& instruction = renderTask.PrepareRenderInstruction(updateBufferIndex);
522 bool viewMatrixHasNotChanged = !renderTask.ViewMatrixUpdated();
523 bool isRenderListAdded = false;
524 bool isRootLayerDirty = false;
526 const Matrix& viewMatrix = renderTask.GetViewMatrix(updateBufferIndex);
527 const SceneGraph::Camera& camera = renderTask.GetCamera();
528 const bool isOrthographicCamera = camera.mProjectionMode == Dali::Camera::ProjectionMode::ORTHOGRAPHIC_PROJECTION;
531 bool viewportSet = renderTask.QueryViewport(updateBufferIndex, viewport);
533 const SortedLayersIter endIter = sortedLayers.end();
534 for(SortedLayersIter iter = sortedLayers.begin(); iter != endIter; ++iter)
536 Layer& layer = **iter;
537 const bool tryReuseRenderList(viewMatrixHasNotChanged && layer.CanReuseRenderers(&camera));
538 const bool isLayer3D = layer.GetBehavior() == Dali::Layer::LAYER_3D;
539 RenderList* renderList = nullptr;
541 if(layer.IsRoot() && (layer.GetDirtyFlags() != NodePropertyFlags::NOTHING))
543 // 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
544 isRootLayerDirty = true;
547 if(!layer.colorRenderables.Empty())
549 RenderableContainer& renderables = layer.colorRenderables;
551 if(!SetupRenderList(renderables, layer, instruction, tryReuseRenderList, &renderList))
553 renderList->SetHasColorRenderItems(true);
554 AddRenderersToRenderList(updateBufferIndex,
564 // We only use the clipping version of the sort comparitor if any clipping nodes exist within the RenderList.
565 SortRenderItems(updateBufferIndex, *renderList, layer, hasClippingNodes, isOrthographicCamera);
568 isRenderListAdded = true;
571 if(!layer.overlayRenderables.Empty())
573 RenderableContainer& renderables = layer.overlayRenderables;
575 if(!SetupRenderList(renderables, layer, instruction, tryReuseRenderList, &renderList))
577 renderList->SetHasColorRenderItems(false);
578 AddRenderersToRenderList(updateBufferIndex,
588 // Clipping hierarchy is irrelevant when sorting overlay items, so we specify using the non-clipping version of the sort comparitor.
589 SortRenderItems(updateBufferIndex, *renderList, layer, false, isOrthographicCamera);
592 isRenderListAdded = true;
596 // Inform the render instruction that all renderers have been added and this frame is complete.
597 instruction.UpdateCompleted();
599 if(isRenderListAdded || instruction.mIsClearColorSet || isRootLayerDirty)
601 instructions.PushBack(updateBufferIndex, &instruction);
605 } // namespace SceneGraph
607 } // namespace Internal