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 sorts render items by depth index then by instance
60 * ptrs of shader/geometry/material.
61 * @param[in] lhs Left hand side item
62 * @param[in] rhs Right hand side item
63 * @return True if left item is greater than right
65 bool CompareItems( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
67 // @todo Consider replacing all these sortAttributes with a single long int that
68 // encapsulates the same data (e.g. the middle-order bits of the ptrs).
69 if( lhs.renderItem->mDepthIndex == rhs.renderItem->mDepthIndex )
71 if( lhs.shader == rhs.shader )
73 if( lhs.textureResourceId == rhs.textureResourceId )
75 return lhs.geometry < rhs.geometry;
77 return lhs.textureResourceId < rhs.textureResourceId;
79 return lhs.shader < rhs.shader;
81 return lhs.renderItem->mDepthIndex < rhs.renderItem->mDepthIndex;
85 * Function which sorts render items by clipping hierarchy, then depth index and instance
86 * ptrs of shader/geometry/material.
87 * @param[in] lhs Left hand side item
88 * @param[in] rhs Right hand side item
89 * @return True if left item is greater than right
91 bool CompareItemsWithClipping( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
93 // Items must be sorted in order of clipping first, otherwise incorrect clipping regions could be used.
94 if( lhs.renderItem->mNode->mClippingSortModifier == rhs.renderItem->mNode->mClippingSortModifier )
96 return CompareItems( lhs, rhs );
99 return lhs.renderItem->mNode->mClippingSortModifier < rhs.renderItem->mNode->mClippingSortModifier;
103 * Function which sorts the render items by Z function, then
104 * by instance ptrs of shader / geometry / material.
105 * @param[in] lhs Left hand side item
106 * @param[in] rhs Right hand side item
107 * @return True if left item is greater than right
109 bool CompareItems3D( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
111 bool lhsIsOpaque = lhs.renderItem->mIsOpaque;
112 if( lhsIsOpaque == rhs.renderItem->mIsOpaque )
116 // If both RenderItems are opaque, sort using shader, then material then geometry.
117 if( lhs.shader == rhs.shader )
119 if( lhs.textureResourceId == rhs.textureResourceId )
121 return lhs.geometry < rhs.geometry;
123 return lhs.textureResourceId < rhs.textureResourceId;
125 return lhs.shader < rhs.shader;
129 // If both RenderItems are transparent, sort using Z, then shader, then material, then geometry.
130 if( Equals( lhs.zValue, rhs.zValue ) )
132 if( lhs.shader == rhs.shader )
134 if( lhs.textureResourceId == rhs.textureResourceId )
136 return lhs.geometry < rhs.geometry;
138 return lhs.textureResourceId < rhs.textureResourceId;
140 return lhs.shader < rhs.shader;
142 return lhs.zValue > rhs.zValue;
152 * Function which sorts render items by clipping hierarchy, then Z function and instance ptrs of shader / geometry / material.
153 * @param[in] lhs Left hand side item
154 * @param[in] rhs Right hand side item
155 * @return True if left item is greater than right
157 bool CompareItems3DWithClipping( const RenderInstructionProcessor::SortAttributes& lhs, const RenderInstructionProcessor::SortAttributes& rhs )
159 // Items must be sorted in order of clipping first, otherwise incorrect clipping regions could be used.
160 if( lhs.renderItem->mNode->mClippingSortModifier == rhs.renderItem->mNode->mClippingSortModifier )
162 return CompareItems3D( lhs, rhs );
165 return lhs.renderItem->mNode->mClippingSortModifier < rhs.renderItem->mNode->mClippingSortModifier;
169 * Add a renderer to the list
170 * @param updateBufferIndex to read the model matrix from
171 * @param renderList to add the item to
172 * @param renderable Node-Renderer pair
173 * @param viewMatrix used to calculate modelview matrix for the item
174 * @param camera The camera used to render
175 * @param geometryBatcher The instance of the geometry batcher
176 * @param isLayer3d Whether we are processing a 3D layer or not
177 * @param cull Whether frustum culling is enabled or not
179 inline void AddRendererToRenderList( BufferIndex updateBufferIndex,
180 RenderList& renderList,
181 Renderable& renderable,
182 const Matrix& viewMatrix,
183 SceneGraph::Camera& camera,
184 GeometryBatcher& geometryBatcher,
188 // Discard renderable early if it belongs to the batch which has been consumed in during frame.
189 Node* renderableNode = renderable.mNode;
190 const bool batchingValid( renderable.mRenderer->IsBatchingEnabled() && renderableNode->mBatchIndex != BATCH_NULL_HANDLE );
191 if( batchingValid && geometryBatcher.HasRendered( renderableNode->mBatchIndex ) )
197 const Node* batchParentNode = renderable.mNode->GetBatchParent();
198 const Node* node = ( renderable.mRenderer->IsBatchingEnabled() && batchParentNode ) ?
199 batchParentNode : renderableNode;
201 if( cull && !renderable.mRenderer->GetShader().HintEnabled( Dali::Shader::Hint::MODIFIES_GEOMETRY ) )
203 const Vector4& boundingSphere = node->GetBoundingSphere();
204 inside = ( boundingSphere.w > Math::MACHINE_EPSILON_1000 ) &&
205 ( camera.CheckSphereInFrustum( updateBufferIndex, Vector3( boundingSphere ), boundingSphere.w ) );
212 geometryBatcher.SetRendered( renderableNode->mBatchIndex );
215 Renderer::Opacity opacity = renderable.mRenderer->GetOpacity( updateBufferIndex, *renderable.mNode );
216 if( opacity != Renderer::TRANSPARENT )
218 // Get the next free RenderItem.
219 RenderItem& item = renderList.GetNextFreeItem();
220 item.mRenderer = &renderable.mRenderer->GetRenderer();
221 item.mNode = renderable.mNode;
222 item.mIsOpaque = ( opacity == Renderer::OPAQUE );
223 item.mDepthIndex = renderable.mRenderer->GetDepthIndex();
227 item.mDepthIndex += renderable.mNode->GetDepthIndex();
230 // Save ModelView matrix onto the item.
231 node->GetWorldMatrixAndSize( item.mModelMatrix, item.mSize );
233 Matrix::Multiply( item.mModelViewMatrix, item.mModelMatrix, viewMatrix );
239 * Add all renderers to the list
240 * @param updateBufferIndex to read the model matrix from
241 * @param renderList to add the items to
242 * @param renderers to render
243 * NodeRendererContainer Node-Renderer pairs
244 * @param viewMatrix used to calculate modelview matrix for the items
245 * @param camera The camera used to render
246 * @param geometryBatcher The instance of the geometry batcher
247 * @param isLayer3d Whether we are processing a 3D layer or not
248 * @param cull Whether frustum culling is enabled or not
250 inline void AddRenderersToRenderList( BufferIndex updateBufferIndex,
251 RenderList& renderList,
252 RenderableContainer& renderers,
253 const Matrix& viewMatrix,
254 SceneGraph::Camera& camera,
255 GeometryBatcher* geometryBatcher,
259 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, "AddRenderersToRenderList()\n");
261 unsigned int rendererCount( renderers.Size() );
262 for( unsigned int i(0); i < rendererCount; ++i )
264 AddRendererToRenderList( updateBufferIndex, renderList, renderers[i], viewMatrix, camera, *geometryBatcher, isLayer3d, cull );
269 * Try to reuse cached RenderItems from the RenderList
270 * This avoids recalculating the model view matrices in case this part of the scene was static
271 * An example case is a toolbar layer that rarely changes or a popup on top of the rest of the stage
272 * @param layer that is being processed
273 * @param renderList that is cached from frame N-1
274 * @param renderables list of renderables
276 inline bool TryReuseCachedRenderers( Layer& layer,
277 RenderList& renderList,
278 RenderableContainer& renderables )
280 bool retValue = false;
281 size_t renderableCount = renderables.Size();
282 // Check that the cached list originates from this layer and that the counts match
283 if( ( renderList.GetSourceLayer() == &layer )&&
284 ( renderList.GetCachedItemCount() == renderableCount ) )
286 // Check that all the same renderers are there. This gives us additional security in avoiding rendering the wrong things.
287 // Render list is sorted so at this stage renderers may be in different order.
288 // Therefore we check a combined sum of all renderer addresses.
289 size_t checkSumNew = 0;
290 size_t checkSumOld = 0;
291 for( size_t index = 0; index < renderableCount; ++index )
293 const Render::Renderer& renderer = renderables[index].mRenderer->GetRenderer();
294 checkSumNew += size_t( &renderer );
295 checkSumOld += size_t( &renderList.GetRenderer( index ) );
297 if( checkSumNew == checkSumOld )
299 // tell list to reuse its existing items
300 renderList.ReuseCachedItems();
307 inline bool SetupRenderList( RenderableContainer& renderables,
309 RenderInstruction& instruction,
310 bool tryReuseRenderList,
311 RenderList** renderList )
313 *renderList = &( instruction.GetNextFreeRenderList( renderables.Size() ) );
314 ( *renderList )->SetClipping( layer.IsClipping(), layer.GetClippingBox() );
315 ( *renderList )->SetSourceLayer( &layer );
317 // Try to reuse cached RenderItems from last time around.
318 return ( tryReuseRenderList && TryReuseCachedRenderers( layer, **renderList, renderables ) );
321 } // Anonymous namespace.
324 RenderInstructionProcessor::RenderInstructionProcessor()
327 // Set up a container of comparators for fast run-time selection.
328 mSortComparitors.Reserve( 4u );
330 mSortComparitors.PushBack( CompareItems );
331 mSortComparitors.PushBack( CompareItemsWithClipping );
332 mSortComparitors.PushBack( CompareItems3D );
333 mSortComparitors.PushBack( CompareItems3DWithClipping );
336 RenderInstructionProcessor::~RenderInstructionProcessor()
340 inline void RenderInstructionProcessor::SortRenderItems( BufferIndex bufferIndex, RenderList& renderList, Layer& layer, bool respectClippingOrder )
342 const size_t renderableCount = renderList.Count();
343 // Reserve space if needed.
344 const unsigned int oldcapacity = mSortingHelper.size();
345 if( oldcapacity < renderableCount )
347 mSortingHelper.reserve( renderableCount );
348 // Add real objects (reserve does not construct objects).
349 mSortingHelper.insert( mSortingHelper.begin() + oldcapacity,
350 (renderableCount - oldcapacity),
351 RenderInstructionProcessor::SortAttributes() );
355 // Clear extra elements from helper, does not decrease capability.
356 mSortingHelper.resize( renderableCount );
359 // Calculate the sorting value, once per item by calling the layers sort function.
360 // Using an if and two for-loops rather than if inside for as its better for branch prediction.
361 if( layer.UsesDefaultSortFunction() )
363 for( size_t index = 0; index < renderableCount; ++index )
365 RenderItem& item = renderList.GetItem( index );
367 item.mRenderer->SetSortAttributes( bufferIndex, mSortingHelper[ index ] );
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 ] );
384 mSortingHelper[ index ].zValue = (*sortFunction)( item.mModelViewMatrix.GetTranslation3() ) - item.mDepthIndex;
386 // Keep the RenderItem pointer in the helper so we can quickly reorder items after sort.
387 mSortingHelper[ index ].renderItem = &item;
391 // Here we detemine which comparitor (of the 4) to use.
392 // The comparitors work like a bitmask.
393 // 1 << 0 is added to select a clipping comparitor.
394 // 1 << 1 is added for 3D comparitors.
395 const unsigned int comparitorIndex = ( respectClippingOrder ? ( 1u << 0u ) : 0u ) |
396 ( layer.GetBehavior() == Dali::Layer::LAYER_3D ? ( 1u << 1u ) : 0u );
398 std::stable_sort( mSortingHelper.begin(), mSortingHelper.end(), mSortComparitors[ comparitorIndex ] );
400 // Reorder / re-populate the RenderItems in the RenderList to correct order based on the sortinghelper.
401 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, "Sorted Transparent List:\n");
402 RenderItemContainer::Iterator renderListIter = renderList.GetContainer().Begin();
403 for( unsigned int index = 0; index < renderableCount; ++index, ++renderListIter )
405 *renderListIter = mSortingHelper[ index ].renderItem;
406 DALI_LOG_INFO( gRenderListLogFilter, Debug::Verbose, " sortedList[%d] = %p\n", index, mSortingHelper[ index ].renderItem->mRenderer);
410 void RenderInstructionProcessor::Prepare( BufferIndex updateBufferIndex,
411 SortedLayerPointers& sortedLayers,
412 RenderTask& renderTask,
414 GeometryBatcher& geometryBatcher,
415 bool hasClippingNodes,
416 RenderInstructionContainer& instructions )
418 // Retrieve the RenderInstruction buffer from the RenderInstructionContainer
419 // then populate with instructions.
420 RenderInstruction& instruction = instructions.GetNextInstruction( updateBufferIndex );
421 renderTask.PrepareRenderInstruction( instruction, updateBufferIndex );
422 bool viewMatrixHasNotChanged = !renderTask.ViewMatrixUpdated();
424 const Matrix& viewMatrix = renderTask.GetViewMatrix( updateBufferIndex );
425 SceneGraph::Camera& camera = renderTask.GetCamera();
427 const SortedLayersIter endIter = sortedLayers.end();
428 for( SortedLayersIter iter = sortedLayers.begin(); iter != endIter; ++iter )
430 Layer& layer = **iter;
431 const bool tryReuseRenderList( viewMatrixHasNotChanged && layer.CanReuseRenderers( &renderTask.GetCamera() ) );
432 const bool isLayer3D = layer.GetBehavior() == Dali::Layer::LAYER_3D;
433 RenderList* renderList = NULL;
435 if( !layer.colorRenderables.Empty() )
437 RenderableContainer& renderables = layer.colorRenderables;
439 if( !SetupRenderList( renderables, layer, instruction, tryReuseRenderList, &renderList ) )
441 renderList->SetHasColorRenderItems( true );
442 AddRenderersToRenderList( updateBufferIndex, *renderList, renderables, viewMatrix, camera, &geometryBatcher, isLayer3D, cull );
444 // We only use the clipping version of the sort comparitor if any clipping nodes exist within the RenderList.
445 SortRenderItems( updateBufferIndex, *renderList, layer, hasClippingNodes );
449 if( !layer.overlayRenderables.Empty() )
451 RenderableContainer& renderables = layer.overlayRenderables;
453 if( !SetupRenderList( renderables, layer, instruction, tryReuseRenderList, &renderList ) )
455 renderList->SetHasColorRenderItems( false );
456 AddRenderersToRenderList( updateBufferIndex, *renderList, renderables, viewMatrix, camera, NULL, isLayer3D, cull );
458 // Clipping hierarchy is irrelevant when sorting overlay items, so we specify using the non-clipping version of the sort comparitor.
459 SortRenderItems( updateBufferIndex, *renderList, layer, false );
464 // Inform the render instruction that all renderers have been added and this frame is complete.
465 instruction.UpdateCompleted();