2 * Copyright (c) 2020 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/public-api/actors/layer.h>
23 #include <dali/integration-api/debug.h>
24 #include <dali/internal/event/actors/layer-impl.h> // for the default sorting function
25 #include <dali/internal/update/manager/sorted-layers.h>
26 #include <dali/internal/update/render-tasks/scene-graph-render-task.h>
27 #include <dali/internal/update/rendering/scene-graph-texture-set.h>
28 #include <dali/internal/render/common/render-item.h>
29 #include <dali/internal/render/common/render-tracker.h>
30 #include <dali/internal/render/common/render-instruction.h>
31 #include <dali/internal/render/common/render-instruction-container.h>
32 #include <dali/internal/render/shaders/scene-graph-shader.h>
33 #include <dali/internal/render/renderers/render-renderer.h>
34 #include <dali/internal/render/renderers/render-property-buffer.h>
35 #include <dali/internal/update/nodes/scene-graph-layer.h>
39 #if defined(DEBUG_ENABLED)
40 Debug::Filter* gRenderListLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_LISTS");
57 * Function which compares render items by shader/textureSet/geometry
58 * @param[in] lhs Left hand side item
59 * @param[in] rhs Right hand side item
60 * @return True if left item is greater than right
62 inline bool PartialCompareItems( const RenderInstructionProcessor::SortAttributes& lhs,
63 const RenderInstructionProcessor::SortAttributes& rhs )
65 if( lhs.shader == rhs.shader )
67 if( lhs.textureSet == rhs.textureSet )
69 return lhs.geometry < rhs.geometry;
71 return lhs.textureSet < rhs.textureSet;
73 return lhs.shader < rhs.shader;
77 * Function which sorts render items by depth index then by instance
78 * ptrs of shader/textureSet/geometry.
79 * @param[in] lhs Left hand side item
80 * @param[in] rhs Right hand side item
81 * @return True if left item is greater than right
83 bool CompareItems( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
85 // @todo Consider replacing all these sortAttributes with a single long int that
86 // encapsulates the same data (e.g. the middle-order bits of the ptrs).
87 if( lhs.renderItem->mDepthIndex == rhs.renderItem->mDepthIndex )
89 return PartialCompareItems( lhs, rhs );
91 return lhs.renderItem->mDepthIndex < rhs.renderItem->mDepthIndex;
95 * Function which sorts the render items by Z function, then
96 * by instance ptrs of shader / geometry / material.
97 * @param[in] lhs Left hand side item
98 * @param[in] rhs Right hand side item
99 * @return True if left item is greater than right
101 bool CompareItems3D( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
103 const bool lhsIsOpaque = lhs.renderItem->mIsOpaque;
104 if( lhsIsOpaque == rhs.renderItem->mIsOpaque )
108 // If both RenderItems are opaque, sort using shader, then material then geometry.
109 return PartialCompareItems( lhs, rhs );
113 // If both RenderItems are transparent, sort using Z, then shader, then material, then geometry.
114 if( Equals( lhs.zValue, rhs.zValue ) )
116 return PartialCompareItems( lhs, rhs );
118 return lhs.zValue > rhs.zValue;
128 * Function which sorts render items by clipping hierarchy, then Z function and instance ptrs of shader / geometry / material.
129 * @param[in] lhs Left hand side item
130 * @param[in] rhs Right hand side item
131 * @return True if left item is greater than right
133 bool CompareItems3DWithClipping( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
135 // Items must be sorted in order of clipping first, otherwise incorrect clipping regions could be used.
136 if( lhs.renderItem->mNode->mClippingSortModifier == rhs.renderItem->mNode->mClippingSortModifier )
138 return CompareItems3D( lhs, rhs );
141 return lhs.renderItem->mNode->mClippingSortModifier < rhs.renderItem->mNode->mClippingSortModifier;
145 * Add a renderer to the list
146 * @param updateBufferIndex to read the model matrix from
147 * @param renderList to add the item to
148 * @param renderable Node-Renderer pair
149 * @param viewMatrix used to calculate modelview matrix for the item
150 * @param camera The camera used to render
151 * @param isLayer3d Whether we are processing a 3D layer or not
152 * @param cull Whether frustum culling is enabled or not
154 inline void AddRendererToRenderList(BufferIndex updateBufferIndex,
155 RenderList& renderList,
156 Renderable& renderable,
157 const Matrix& viewMatrix,
158 SceneGraph::Camera& camera,
163 Node* node = renderable.mNode;
165 if (cull && renderable.mRenderer && !renderable.mRenderer->GetShader().HintEnabled(Dali::Shader::Hint::MODIFIES_GEOMETRY))
167 const Vector4& boundingSphere = node->GetBoundingSphere();
168 inside = (boundingSphere.w > Math::MACHINE_EPSILON_1000) &&
169 (camera.CheckSphereInFrustum(updateBufferIndex, Vector3(boundingSphere), boundingSphere.w));
174 Renderer::OpacityType opacityType = renderable.mRenderer ? renderable.mRenderer->GetOpacityType( updateBufferIndex, *renderable.mNode ) : Renderer::OPAQUE;
175 if (opacityType != Renderer::TRANSPARENT || node->GetClippingMode() == ClippingMode::CLIP_CHILDREN)
177 // Get the next free RenderItem.
178 RenderItem& item = renderList.GetNextFreeItem();
180 item.mIsUpdated = (item.mNode != renderable.mNode);
181 item.mNode = renderable.mNode;
183 bool prevIsOpaque = item.mIsOpaque;
184 item.mIsOpaque = (opacityType == Renderer::OPAQUE);
185 item.mIsUpdated |= (prevIsOpaque != item.mIsOpaque);
187 int prevDepthIndex = item.mDepthIndex;
188 item.mDepthIndex = 0;
191 item.mDepthIndex = renderable.mNode->GetDepthIndex();
194 Render::Renderer* prevRenderer = item.mRenderer;
195 if (DALI_LIKELY(renderable.mRenderer))
197 item.mRenderer = &renderable.mRenderer->GetRenderer();
198 const void* prevTextureSet = item.mTextureSet;
199 item.mTextureSet = renderable.mRenderer->GetTextures();
200 item.mIsUpdated |= (prevTextureSet != item.mTextureSet);
201 item.mDepthIndex += renderable.mRenderer->GetDepthIndex();
205 item.mRenderer = nullptr;
208 item.mIsUpdated |= (prevDepthIndex != item.mDepthIndex);
209 item.mIsUpdated |= (prevRenderer != item.mRenderer);
210 item.mIsUpdated |= isLayer3d;
212 if (!item.mIsUpdated)
214 Matrix prevModelViewMatrix = item.mModelViewMatrix;
215 Vector3 prevSize = item.mSize;
217 // Save ModelView matrix onto the item.
218 node->GetWorldMatrixAndSize( item.mModelMatrix, item.mSize );
219 Matrix::Multiply( item.mModelViewMatrix, item.mModelMatrix, viewMatrix );
221 item.mIsUpdated = ((prevSize != item.mSize) || (item.mModelViewMatrix != prevModelViewMatrix));
225 // Save ModelView matrix onto the item.
226 node->GetWorldMatrixAndSize( item.mModelMatrix, item.mSize );
227 Matrix::Multiply( item.mModelViewMatrix, item.mModelMatrix, viewMatrix );
230 item.mUpdateSize = node->GetUpdateSizeHint();
231 if (item.mUpdateSize == Vector3::ZERO)
233 // RenderItem::CalculateViewportSpaceAABB cannot cope with z transform
234 // I don't use item.mModelMatrix.GetTransformComponents() for z transform, would be to slow
235 if (!isLayer3d && item.mModelMatrix.GetZAxis() == Vector3(0.0f, 0.0f, 1.0f))
237 item.mUpdateSize = item.mSize;
242 node->SetCulled( updateBufferIndex, false );
246 node->SetCulled( updateBufferIndex, true );
251 * Add all renderers to the list
252 * @param updateBufferIndex to read the model matrix from
253 * @param renderList to add the items to
254 * @param renderers to render
255 * NodeRendererContainer Node-Renderer pairs
256 * @param viewMatrix used to calculate modelview matrix for the items
257 * @param camera The camera used to render
258 * @param isLayer3d Whether we are processing a 3D layer or not
259 * @param cull Whether frustum culling is enabled or not
261 inline void AddRenderersToRenderList( BufferIndex updateBufferIndex,
262 RenderList& renderList,
263 RenderableContainer& renderers,
264 const Matrix& viewMatrix,
265 SceneGraph::Camera& camera,
269 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, "AddRenderersToRenderList()\n");
271 for( auto&& renderer : renderers )
273 AddRendererToRenderList( updateBufferIndex,
284 * Try to reuse cached RenderItems from the RenderList
285 * This avoids recalculating the model view matrices in case this part of the scene was static
286 * An example case is a toolbar layer that rarely changes or a popup on top of the rest of the stage
287 * @param layer that is being processed
288 * @param renderList that is cached from frame N-1
289 * @param renderables list of renderables
291 inline bool TryReuseCachedRenderers( Layer& layer,
292 RenderList& renderList,
293 RenderableContainer& renderables )
295 bool retValue = false;
296 uint32_t renderableCount = static_cast<uint32_t>( renderables.Size() );
297 // Check that the cached list originates from this layer and that the counts match
298 if( ( renderList.GetSourceLayer() == &layer )&&
299 ( renderList.GetCachedItemCount() == renderableCount ) )
301 // Check that all the same renderers are there. This gives us additional security in avoiding rendering the wrong things.
302 // Render list is sorted so at this stage renderers may be in different order.
303 // Therefore we check a combined sum of all renderer addresses.
304 size_t checkSumNew = 0;
305 size_t checkSumOld = 0;
306 for( uint32_t index = 0; index < renderableCount; ++index )
308 const Render::Renderer& renderer = renderables[index].mRenderer->GetRenderer();
309 checkSumNew += reinterpret_cast<std::size_t>( &renderer );
310 checkSumOld += reinterpret_cast<std::size_t>( &renderList.GetRenderer( index ) );
312 if( checkSumNew == checkSumOld )
314 // tell list to reuse its existing items
315 renderList.ReuseCachedItems();
323 inline bool SetupRenderList( RenderableContainer& renderables,
325 RenderInstruction& instruction,
326 bool tryReuseRenderList,
327 RenderList** renderList )
329 *renderList = &( instruction.GetNextFreeRenderList( renderables.Size() ) );
330 ( *renderList )->SetClipping( layer.IsClipping(), layer.GetClippingBox() );
331 ( *renderList )->SetSourceLayer( &layer );
333 // Try to reuse cached RenderItems from last time around.
334 return ( tryReuseRenderList && TryReuseCachedRenderers( layer, **renderList, renderables ) );
337 } // Anonymous namespace.
340 RenderInstructionProcessor::RenderInstructionProcessor()
343 // Set up a container of comparators for fast run-time selection.
344 mSortComparitors.Reserve( 3u );
346 mSortComparitors.PushBack( CompareItems );
347 mSortComparitors.PushBack( CompareItems3D );
348 mSortComparitors.PushBack( CompareItems3DWithClipping );
351 RenderInstructionProcessor::~RenderInstructionProcessor()
355 inline void RenderInstructionProcessor::SortRenderItems( BufferIndex bufferIndex, RenderList& renderList, Layer& layer, bool respectClippingOrder )
357 const uint32_t renderableCount = static_cast<uint32_t>( renderList.Count() );
358 // Reserve space if needed.
359 const uint32_t oldcapacity = static_cast<uint32_t>( mSortingHelper.size() );
360 if( oldcapacity < renderableCount )
362 mSortingHelper.reserve( renderableCount );
363 // Add real objects (reserve does not construct objects).
364 mSortingHelper.insert( mSortingHelper.begin() + oldcapacity,
365 (renderableCount - oldcapacity),
366 RenderInstructionProcessor::SortAttributes() );
370 // Clear extra elements from helper, does not decrease capability.
371 mSortingHelper.resize( renderableCount );
374 // Calculate the sorting value, once per item by calling the layers sort function.
375 // Using an if and two for-loops rather than if inside for as its better for branch prediction.
376 if( layer.UsesDefaultSortFunction() )
378 for( uint32_t index = 0; index < renderableCount; ++index )
380 RenderItem& item = renderList.GetItem( index );
384 item.mRenderer->SetSortAttributes( bufferIndex, mSortingHelper[ index ] );
388 mSortingHelper[ index ].textureSet = item.mTextureSet;
390 // The default sorting function should get inlined here.
391 mSortingHelper[ index ].zValue = Internal::Layer::ZValue( item.mModelViewMatrix.GetTranslation3() ) - static_cast<float>( item.mDepthIndex );
393 // Keep the renderitem pointer in the helper so we can quickly reorder items after sort.
394 mSortingHelper[ index ].renderItem = &item;
399 const Dali::Layer::SortFunctionType sortFunction = layer.GetSortFunction();
400 for( uint32_t index = 0; index < renderableCount; ++index )
402 RenderItem& item = renderList.GetItem( index );
404 item.mRenderer->SetSortAttributes( bufferIndex, mSortingHelper[ index ] );
407 mSortingHelper[ index ].textureSet = item.mTextureSet;
410 mSortingHelper[ index ].zValue = (*sortFunction)( item.mModelViewMatrix.GetTranslation3() ) - static_cast<float>( item.mDepthIndex );
412 // Keep the RenderItem pointer in the helper so we can quickly reorder items after sort.
413 mSortingHelper[ index ].renderItem = &item;
417 // Here we determine which comparitor (of the 3) to use.
420 // 2 is LAYER_3D + Clipping
421 const unsigned int comparitorIndex = layer.GetBehavior() == Dali::Layer::LAYER_3D ? respectClippingOrder ? 2u : 1u : 0u;
423 std::stable_sort( mSortingHelper.begin(), mSortingHelper.end(), mSortComparitors[ comparitorIndex ] );
425 // Reorder / re-populate the RenderItems in the RenderList to correct order based on the sortinghelper.
426 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, "Sorted Transparent List:\n");
427 RenderItemContainer::Iterator renderListIter = renderList.GetContainer().Begin();
428 for( uint32_t index = 0; index < renderableCount; ++index, ++renderListIter )
430 *renderListIter = mSortingHelper[ index ].renderItem;
431 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, " sortedList[%d] = %p\n", index, mSortingHelper[ index ].renderItem->mRenderer);
435 void RenderInstructionProcessor::Prepare( BufferIndex updateBufferIndex,
436 SortedLayerPointers& sortedLayers,
438 RenderTask& renderTask,
440 bool hasClippingNodes,
441 RenderInstructionContainer& instructions )
443 // Retrieve the RenderInstruction buffer from the RenderInstructionContainer
444 // then populate with instructions.
445 RenderInstruction& instruction = renderTask.PrepareRenderInstruction( updateBufferIndex );
446 bool viewMatrixHasNotChanged = !renderTask.ViewMatrixUpdated();
447 bool isRenderListAdded = false;
448 bool isRootLayerDirty = false;
450 const Matrix& viewMatrix = renderTask.GetViewMatrix( updateBufferIndex );
451 SceneGraph::Camera& camera = renderTask.GetCamera();
453 const SortedLayersIter endIter = sortedLayers.end();
454 for( SortedLayersIter iter = sortedLayers.begin(); iter != endIter; ++iter )
456 Layer& layer = **iter;
457 const bool tryReuseRenderList( viewMatrixHasNotChanged && layer.CanReuseRenderers( &renderTask.GetCamera() ) );
458 const bool isLayer3D = layer.GetBehavior() == Dali::Layer::LAYER_3D;
459 RenderList* renderList = NULL;
461 if( layer.IsRoot() && ( layer.GetDirtyFlags() != NodePropertyFlags::NOTHING ) )
463 // 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
464 isRootLayerDirty = true;
467 if( !layer.colorRenderables.Empty() )
469 RenderableContainer& renderables = layer.colorRenderables;
471 if( !SetupRenderList( renderables, layer, instruction, tryReuseRenderList, &renderList ) )
473 renderList->SetHasColorRenderItems( true );
474 AddRenderersToRenderList( updateBufferIndex,
482 // We only use the clipping version of the sort comparitor if any clipping nodes exist within the RenderList.
483 SortRenderItems( updateBufferIndex, *renderList, layer, hasClippingNodes );
486 isRenderListAdded = true;
489 if( !layer.overlayRenderables.Empty() )
491 RenderableContainer& renderables = layer.overlayRenderables;
493 if( !SetupRenderList( renderables, layer, instruction, tryReuseRenderList, &renderList ) )
495 renderList->SetHasColorRenderItems( false );
496 AddRenderersToRenderList( updateBufferIndex,
504 // Clipping hierarchy is irrelevant when sorting overlay items, so we specify using the non-clipping version of the sort comparitor.
505 SortRenderItems( updateBufferIndex, *renderList, layer, false );
508 isRenderListAdded = true;
512 // Inform the render instruction that all renderers have been added and this frame is complete.
513 instruction.UpdateCompleted();
515 if( isRenderListAdded || instruction.mIsClearColorSet || isRootLayerDirty )
517 instruction.mContext = &context;
518 instructions.PushBack( updateBufferIndex, &instruction );