2 * Copyright (c) 2016 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/update/resources/resource-manager-declarations.h>
29 #include <dali/internal/render/common/render-item.h>
30 #include <dali/internal/render/common/render-tracker.h>
31 #include <dali/internal/render/common/render-instruction.h>
32 #include <dali/internal/render/common/render-instruction-container.h>
33 #include <dali/internal/render/shaders/scene-graph-shader.h>
34 #include <dali/internal/render/renderers/render-renderer.h>
35 #include <dali/internal/render/renderers/render-property-buffer.h>
36 #include <dali/internal/update/manager/geometry-batcher.h>
37 #include <dali/internal/update/nodes/scene-graph-layer.h>
41 #if defined(DEBUG_ENABLED)
42 Debug::Filter* gRenderListLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_LISTS");
59 * Function which compares render items by shader/textureSet/geometry
60 * @param[in] lhs Left hand side item
61 * @param[in] rhs Right hand side item
62 * @return True if left item is greater than right
64 bool PartialCompareItems( const RenderInstructionProcessor::SortAttributes& lhs,
65 const RenderInstructionProcessor::SortAttributes& rhs )
67 if( lhs.shader == rhs.shader )
69 if( lhs.textureSet == rhs.textureSet )
71 return lhs.geometry < rhs.geometry;
73 return lhs.textureSet < rhs.textureSet;
75 return lhs.shader < rhs.shader;
79 * Function which sorts render items by depth index then by instance
80 * ptrs of shader/textureSet/geometry.
81 * @param[in] lhs Left hand side item
82 * @param[in] rhs Right hand side item
83 * @return True if left item is greater than right
85 bool CompareItems( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
87 // @todo Consider replacing all these sortAttributes with a single long int that
88 // encapsulates the same data (e.g. the middle-order bits of the ptrs).
89 if( lhs.renderItem->mDepthIndex == rhs.renderItem->mDepthIndex )
91 return PartialCompareItems(lhs, rhs);
93 return lhs.renderItem->mDepthIndex < rhs.renderItem->mDepthIndex;
97 * Function which sorts render items by clipping hierarchy, then depth index and instance
98 * ptrs of shader/geometry/material.
99 * @param[in] lhs Left hand side item
100 * @param[in] rhs Right hand side item
101 * @return True if left item is greater than right
103 bool CompareItemsWithClipping( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
105 // Items must be sorted in order of clipping first, otherwise incorrect clipping regions could be used.
106 if( lhs.renderItem->mNode->mClippingSortModifier == rhs.renderItem->mNode->mClippingSortModifier )
108 return CompareItems( lhs, rhs );
111 return lhs.renderItem->mNode->mClippingSortModifier < rhs.renderItem->mNode->mClippingSortModifier;
115 * Function which sorts the render items by Z function, then
116 * by instance ptrs of shader / geometry / material.
117 * @param[in] lhs Left hand side item
118 * @param[in] rhs Right hand side item
119 * @return True if left item is greater than right
121 bool CompareItems3D( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
123 bool lhsIsOpaque = lhs.renderItem->mIsOpaque;
124 if( lhsIsOpaque == rhs.renderItem->mIsOpaque )
128 // If both RenderItems are opaque, sort using shader, then material then geometry.
129 return PartialCompareItems( lhs, rhs );
133 // If both RenderItems are transparent, sort using Z, then shader, then material, then geometry.
134 if( Equals( lhs.zValue, rhs.zValue ) )
136 return PartialCompareItems( lhs, rhs );
138 return lhs.zValue > rhs.zValue;
148 * Function which sorts render items by clipping hierarchy, then Z function and instance ptrs of shader / geometry / material.
149 * @param[in] lhs Left hand side item
150 * @param[in] rhs Right hand side item
151 * @return True if left item is greater than right
153 bool CompareItems3DWithClipping( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
155 // Items must be sorted in order of clipping first, otherwise incorrect clipping regions could be used.
156 if( lhs.renderItem->mNode->mClippingSortModifier == rhs.renderItem->mNode->mClippingSortModifier )
158 return CompareItems3D( lhs, rhs );
161 return lhs.renderItem->mNode->mClippingSortModifier < rhs.renderItem->mNode->mClippingSortModifier;
165 * Add a renderer to the list
166 * @param updateBufferIndex to read the model matrix from
167 * @param renderList to add the item to
168 * @param renderable Node-Renderer pair
169 * @param viewMatrix used to calculate modelview matrix for the item
170 * @param camera The camera used to render
171 * @param geometryBatcher The instance of the geometry batcher
172 * @param isLayer3d Whether we are processing a 3D layer or not
173 * @param cull Whether frustum culling is enabled or not
175 inline void AddRendererToRenderList( BufferIndex updateBufferIndex,
176 RenderList& renderList,
177 Renderable& renderable,
178 const Matrix& viewMatrix,
179 SceneGraph::Camera& camera,
180 GeometryBatcher& geometryBatcher,
184 // Discard renderable early if it belongs to the batch which has been consumed in during frame.
185 Node* renderableNode = renderable.mNode;
186 const bool batchingValid( renderable.mRenderer->IsBatchingEnabled() && renderableNode->mBatchIndex != BATCH_NULL_HANDLE );
187 if( batchingValid && geometryBatcher.HasRendered( renderableNode->mBatchIndex ) )
193 const Node* batchParentNode = renderable.mNode->GetBatchParent();
194 const Node* node = ( renderable.mRenderer->IsBatchingEnabled() && batchParentNode ) ?
195 batchParentNode : renderableNode;
197 if( cull && !renderable.mRenderer->GetShader().HintEnabled( Dali::Shader::Hint::MODIFIES_GEOMETRY ) )
199 const Vector4& boundingSphere = node->GetBoundingSphere();
200 inside = ( boundingSphere.w > Math::MACHINE_EPSILON_1000 ) &&
201 ( camera.CheckSphereInFrustum( updateBufferIndex, Vector3( boundingSphere ), boundingSphere.w ) );
208 geometryBatcher.SetRendered( renderableNode->mBatchIndex );
211 Renderer::Opacity opacity = renderable.mRenderer->GetOpacity( updateBufferIndex, *renderable.mNode );
212 if( opacity != Renderer::TRANSPARENT )
214 // Get the next free RenderItem.
215 RenderItem& item = renderList.GetNextFreeItem();
216 item.mRenderer = &renderable.mRenderer->GetRenderer();
217 item.mNode = renderable.mNode;
218 item.mTextureSet = renderable.mRenderer->GetTextures();
219 item.mIsOpaque = ( opacity == Renderer::OPAQUE );
220 item.mDepthIndex = renderable.mRenderer->GetDepthIndex();
224 item.mDepthIndex += renderable.mNode->GetDepthIndex();
227 // Save ModelView matrix onto the item.
228 node->GetWorldMatrixAndSize( item.mModelMatrix, item.mSize );
230 Matrix::Multiply( item.mModelViewMatrix, item.mModelMatrix, viewMatrix );
236 * Add all renderers to the list
237 * @param updateBufferIndex to read the model matrix from
238 * @param renderList to add the items to
239 * @param renderers to render
240 * NodeRendererContainer Node-Renderer pairs
241 * @param viewMatrix used to calculate modelview matrix for the items
242 * @param camera The camera used to render
243 * @param geometryBatcher The instance of the geometry batcher
244 * @param isLayer3d Whether we are processing a 3D layer or not
245 * @param cull Whether frustum culling is enabled or not
247 inline void AddRenderersToRenderList( BufferIndex updateBufferIndex,
248 RenderList& renderList,
249 RenderableContainer& renderers,
250 const Matrix& viewMatrix,
251 SceneGraph::Camera& camera,
252 GeometryBatcher* geometryBatcher,
256 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, "AddRenderersToRenderList()\n");
258 unsigned int rendererCount( renderers.Size() );
259 for( unsigned int i(0); i < rendererCount; ++i )
261 AddRendererToRenderList( updateBufferIndex, renderList, renderers[i], viewMatrix, camera, *geometryBatcher, isLayer3d, cull );
266 * Try to reuse cached RenderItems from the RenderList
267 * This avoids recalculating the model view matrices in case this part of the scene was static
268 * An example case is a toolbar layer that rarely changes or a popup on top of the rest of the stage
269 * @param layer that is being processed
270 * @param renderList that is cached from frame N-1
271 * @param renderables list of renderables
273 inline bool TryReuseCachedRenderers( Layer& layer,
274 RenderList& renderList,
275 RenderableContainer& renderables )
277 bool retValue = false;
278 size_t renderableCount = renderables.Size();
279 // Check that the cached list originates from this layer and that the counts match
280 if( ( renderList.GetSourceLayer() == &layer )&&
281 ( renderList.GetCachedItemCount() == renderableCount ) )
283 // Check that all the same renderers are there. This gives us additional security in avoiding rendering the wrong things.
284 // Render list is sorted so at this stage renderers may be in different order.
285 // Therefore we check a combined sum of all renderer addresses.
286 size_t checkSumNew = 0;
287 size_t checkSumOld = 0;
288 for( size_t index = 0; index < renderableCount; ++index )
290 const Render::Renderer& renderer = renderables[index].mRenderer->GetRenderer();
291 checkSumNew += size_t( &renderer );
292 checkSumOld += size_t( &renderList.GetRenderer( index ) );
294 if( checkSumNew == checkSumOld )
296 // tell list to reuse its existing items
297 renderList.ReuseCachedItems();
304 inline bool SetupRenderList( RenderableContainer& renderables,
306 RenderInstruction& instruction,
307 bool tryReuseRenderList,
308 RenderList** renderList )
310 *renderList = &( instruction.GetNextFreeRenderList( renderables.Size() ) );
311 ( *renderList )->SetClipping( layer.IsClipping(), layer.GetClippingBox() );
312 ( *renderList )->SetSourceLayer( &layer );
314 // Try to reuse cached RenderItems from last time around.
315 return ( tryReuseRenderList && TryReuseCachedRenderers( layer, **renderList, renderables ) );
318 } // Anonymous namespace.
321 RenderInstructionProcessor::RenderInstructionProcessor()
324 // Set up a container of comparators for fast run-time selection.
325 mSortComparitors.Reserve( 4u );
327 mSortComparitors.PushBack( CompareItems );
328 mSortComparitors.PushBack( CompareItemsWithClipping );
329 mSortComparitors.PushBack( CompareItems3D );
330 mSortComparitors.PushBack( CompareItems3DWithClipping );
333 RenderInstructionProcessor::~RenderInstructionProcessor()
337 inline void RenderInstructionProcessor::SortRenderItems( BufferIndex bufferIndex, RenderList& renderList, Layer& layer, bool respectClippingOrder )
339 const size_t renderableCount = renderList.Count();
340 // Reserve space if needed.
341 const unsigned int oldcapacity = mSortingHelper.size();
342 if( oldcapacity < renderableCount )
344 mSortingHelper.reserve( renderableCount );
345 // Add real objects (reserve does not construct objects).
346 mSortingHelper.insert( mSortingHelper.begin() + oldcapacity,
347 (renderableCount - oldcapacity),
348 RenderInstructionProcessor::SortAttributes() );
352 // Clear extra elements from helper, does not decrease capability.
353 mSortingHelper.resize( renderableCount );
356 // Calculate the sorting value, once per item by calling the layers sort function.
357 // Using an if and two for-loops rather than if inside for as its better for branch prediction.
358 if( layer.UsesDefaultSortFunction() )
360 for( size_t index = 0; index < renderableCount; ++index )
362 RenderItem& item = renderList.GetItem( index );
364 item.mRenderer->SetSortAttributes( bufferIndex, mSortingHelper[ index ] );
367 mSortingHelper[ index ].textureSet = item.mTextureSet;
369 // The default sorting function should get inlined here.
370 mSortingHelper[ index ].zValue = Internal::Layer::ZValue( item.mModelViewMatrix.GetTranslation3() ) - item.mDepthIndex;
372 // Keep the renderitem pointer in the helper so we can quickly reorder items after sort.
373 mSortingHelper[ index ].renderItem = &item;
378 const Dali::Layer::SortFunctionType sortFunction = layer.GetSortFunction();
379 for( size_t index = 0; index < renderableCount; ++index )
381 RenderItem& item = renderList.GetItem( index );
383 item.mRenderer->SetSortAttributes( bufferIndex, mSortingHelper[ index ] );
386 mSortingHelper[ index ].textureSet = item.mTextureSet;
389 mSortingHelper[ index ].zValue = (*sortFunction)( item.mModelViewMatrix.GetTranslation3() ) - item.mDepthIndex;
391 // Keep the RenderItem pointer in the helper so we can quickly reorder items after sort.
392 mSortingHelper[ index ].renderItem = &item;
396 // Here we detemine which comparitor (of the 4) to use.
397 // The comparitors work like a bitmask.
398 // 1 << 0 is added to select a clipping comparitor.
399 // 1 << 1 is added for 3D comparitors.
400 const unsigned int comparitorIndex = ( respectClippingOrder ? ( 1u << 0u ) : 0u ) |
401 ( layer.GetBehavior() == Dali::Layer::LAYER_3D ? ( 1u << 1u ) : 0u );
403 std::stable_sort( mSortingHelper.begin(), mSortingHelper.end(), mSortComparitors[ comparitorIndex ] );
405 // Reorder / re-populate the RenderItems in the RenderList to correct order based on the sortinghelper.
406 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, "Sorted Transparent List:\n");
407 RenderItemContainer::Iterator renderListIter = renderList.GetContainer().Begin();
408 for( unsigned int index = 0; index < renderableCount; ++index, ++renderListIter )
410 *renderListIter = mSortingHelper[ index ].renderItem;
411 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, " sortedList[%d] = %p\n", index, mSortingHelper[ index ].renderItem->mRenderer);
415 void RenderInstructionProcessor::Prepare( BufferIndex updateBufferIndex,
416 SortedLayerPointers& sortedLayers,
417 RenderTask& renderTask,
419 GeometryBatcher& geometryBatcher,
420 bool hasClippingNodes,
421 RenderInstructionContainer& instructions )
423 // Retrieve the RenderInstruction buffer from the RenderInstructionContainer
424 // then populate with instructions.
425 RenderInstruction& instruction = instructions.GetNextInstruction( updateBufferIndex );
426 renderTask.PrepareRenderInstruction( instruction, updateBufferIndex );
427 bool viewMatrixHasNotChanged = !renderTask.ViewMatrixUpdated();
429 const Matrix& viewMatrix = renderTask.GetViewMatrix( updateBufferIndex );
430 SceneGraph::Camera& camera = renderTask.GetCamera();
432 const SortedLayersIter endIter = sortedLayers.end();
433 for( SortedLayersIter iter = sortedLayers.begin(); iter != endIter; ++iter )
435 Layer& layer = **iter;
436 const bool tryReuseRenderList( viewMatrixHasNotChanged && layer.CanReuseRenderers( &renderTask.GetCamera() ) );
437 const bool isLayer3D = layer.GetBehavior() == Dali::Layer::LAYER_3D;
438 RenderList* renderList = NULL;
440 if( !layer.colorRenderables.Empty() )
442 RenderableContainer& renderables = layer.colorRenderables;
444 if( !SetupRenderList( renderables, layer, instruction, tryReuseRenderList, &renderList ) )
446 renderList->SetHasColorRenderItems( true );
447 AddRenderersToRenderList( updateBufferIndex, *renderList, renderables, viewMatrix, camera, &geometryBatcher, isLayer3D, cull );
449 // We only use the clipping version of the sort comparitor if any clipping nodes exist within the RenderList.
450 SortRenderItems( updateBufferIndex, *renderList, layer, hasClippingNodes );
454 if( !layer.overlayRenderables.Empty() )
456 RenderableContainer& renderables = layer.overlayRenderables;
458 if( !SetupRenderList( renderables, layer, instruction, tryReuseRenderList, &renderList ) )
460 renderList->SetHasColorRenderItems( false );
461 AddRenderersToRenderList( updateBufferIndex, *renderList, renderables, viewMatrix, camera, NULL, isLayer3D, cull );
463 // Clipping hierarchy is irrelevant when sorting overlay items, so we specify using the non-clipping version of the sort comparitor.
464 SortRenderItems( updateBufferIndex, *renderList, layer, false );
469 // Inform the render instruction that all renderers have been added and this frame is complete.
470 instruction.UpdateCompleted();