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/render/common/render-manager.h>
25 #include <dali/devel-api/threading/thread-pool.h>
26 #include <dali/integration-api/core.h>
27 #include <dali/integration-api/gl-context-helper-abstraction.h>
28 #include <dali/internal/event/common/scene-impl.h>
29 #include <dali/internal/render/common/render-algorithms.h>
30 #include <dali/internal/render/common/render-debug.h>
31 #include <dali/internal/render/common/render-tracker.h>
32 #include <dali/internal/render/queue/render-queue.h>
33 #include <dali/internal/render/shaders/program-controller.h>
44 #if defined(DEBUG_ENABLED)
47 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_MANAGER" );
48 } // unnamed namespace
53 DirtyRect(Node* node, Render::Renderer* renderer, int frame, Rect<int>& rect)
71 bool operator<(const DirtyRect& rhs) const
75 if (renderer == rhs.renderer)
77 return frame > rhs.frame; // Most recent rects come first
81 return renderer < rhs.renderer;
86 return node < rhs.node;
91 Render::Renderer* renderer;
99 * Structure to contain internal data
101 struct RenderManager::Impl
103 Impl( Integration::GlAbstraction& glAbstraction,
104 Integration::GlSyncAbstraction& glSyncAbstraction,
105 Integration::GlContextHelperAbstraction& glContextHelperAbstraction,
106 Integration::DepthBufferAvailable depthBufferAvailableParam,
107 Integration::StencilBufferAvailable stencilBufferAvailableParam,
108 Integration::PartialUpdateAvailable partialUpdateAvailableParam )
109 : context( glAbstraction, &sceneContextContainer ),
110 currentContext( &context ),
111 glAbstraction( glAbstraction ),
112 glSyncAbstraction( glSyncAbstraction ),
113 glContextHelperAbstraction( glContextHelperAbstraction ),
117 renderBufferIndex( SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX ),
118 defaultSurfaceRect(),
122 frameBufferContainer(),
123 lastFrameWasRendered( false ),
124 programController( glAbstraction ),
125 depthBufferAvailable( depthBufferAvailableParam ),
126 stencilBufferAvailable( stencilBufferAvailableParam ),
127 partialUpdateAvailable( partialUpdateAvailableParam ),
130 // Create thread pool with just one thread ( there may be a need to create more threads in the future ).
131 threadPool = std::unique_ptr<Dali::ThreadPool>( new Dali::ThreadPool() );
132 threadPool->Initialize( 1u );
137 threadPool.reset( nullptr ); // reset now to maintain correct destruction order
140 void AddRenderTracker( Render::RenderTracker* renderTracker )
142 DALI_ASSERT_DEBUG( renderTracker != NULL );
143 mRenderTrackers.PushBack( renderTracker );
146 void RemoveRenderTracker( Render::RenderTracker* renderTracker )
148 mRenderTrackers.EraseObject( renderTracker );
151 Context* CreateSceneContext()
153 Context* context = new Context( glAbstraction );
155 //TODO: Need eglMakeCurrent first
156 context->GlContextCreated();
158 sceneContextContainer.PushBack( context );
162 void DestroySceneContext( Context* sceneContext )
164 auto iter = std::find( sceneContextContainer.Begin(), sceneContextContainer.End(), sceneContext );
165 if( iter != sceneContextContainer.End() )
167 ( *iter )->GlContextDestroyed();
168 sceneContextContainer.Erase( iter );
172 Context* ReplaceSceneContext( Context* oldSceneContext )
174 Context* newContext = new Context( glAbstraction );
176 oldSceneContext->GlContextDestroyed();
177 //TODO: Need eglMakeCurrent first
178 newContext->GlContextCreated();
180 std::replace( sceneContextContainer.begin(), sceneContextContainer.end(), oldSceneContext, newContext );
184 void UpdateTrackers()
186 for( auto&& iter : mRenderTrackers )
188 iter->PollSyncObject();
192 // the order is important for destruction,
193 // programs are owned by context at the moment.
194 Context context; ///< Holds the GL state of the share resource context
195 Context* currentContext; ///< Holds the GL state of the current context for rendering
196 OwnerContainer< Context* > sceneContextContainer; ///< List of owned contexts holding the GL state per scene
197 Integration::GlAbstraction& glAbstraction; ///< GL abstraction
198 Integration::GlSyncAbstraction& glSyncAbstraction; ///< GL sync abstraction
199 Integration::GlContextHelperAbstraction& glContextHelperAbstraction; ///< GL context helper abstraction
200 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
202 std::vector< SceneGraph::Scene* > sceneContainer; ///< List of pointers to the scene graph objects of the scenes
204 Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
206 uint32_t frameCount; ///< The current frame count
207 BufferIndex renderBufferIndex; ///< The index of the buffer to read from; this is opposite of the "update" buffer
209 Rect<int32_t> defaultSurfaceRect; ///< Rectangle for the default surface we are rendering to
211 OwnerContainer< Render::Renderer* > rendererContainer; ///< List of owned renderers
212 OwnerContainer< Render::Sampler* > samplerContainer; ///< List of owned samplers
213 OwnerContainer< Render::Texture* > textureContainer; ///< List of owned textures
214 OwnerContainer< Render::FrameBuffer* > frameBufferContainer; ///< List of owned framebuffers
215 OwnerContainer< Render::PropertyBuffer* > propertyBufferContainer; ///< List of owned property buffers
216 OwnerContainer< Render::Geometry* > geometryContainer; ///< List of owned Geometries
218 bool lastFrameWasRendered; ///< Keeps track of the last frame being rendered due to having render instructions
220 OwnerContainer< Render::RenderTracker* > mRenderTrackers; ///< List of render trackers
222 ProgramController programController; ///< Owner of the GL programs
224 Integration::DepthBufferAvailable depthBufferAvailable; ///< Whether the depth buffer is available
225 Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
226 Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
228 std::unique_ptr<Dali::ThreadPool> threadPool; ///< The thread pool
229 Vector<GLuint> boundTextures; ///< The textures bound for rendering
230 Vector<GLuint> textureDependencyList; ///< The dependency list of binded textures
231 std::size_t itemsCheckSum; ///< The damaged render items checksum from previous prerender phase.
232 std::vector<DirtyRect> itemsDirtyRects;
235 RenderManager* RenderManager::New( Integration::GlAbstraction& glAbstraction,
236 Integration::GlSyncAbstraction& glSyncAbstraction,
237 Integration::GlContextHelperAbstraction& glContextHelperAbstraction,
238 Integration::DepthBufferAvailable depthBufferAvailable,
239 Integration::StencilBufferAvailable stencilBufferAvailable,
240 Integration::PartialUpdateAvailable partialUpdateAvailable )
242 RenderManager* manager = new RenderManager;
243 manager->mImpl = new Impl( glAbstraction,
245 glContextHelperAbstraction,
246 depthBufferAvailable,
247 stencilBufferAvailable,
248 partialUpdateAvailable );
252 RenderManager::RenderManager()
257 RenderManager::~RenderManager()
262 RenderQueue& RenderManager::GetRenderQueue()
264 return mImpl->renderQueue;
267 void RenderManager::ContextCreated()
269 mImpl->context.GlContextCreated();
270 mImpl->programController.GlContextCreated();
272 // renderers, textures and gpu buffers cannot reinitialize themselves
273 // so they rely on someone reloading the data for them
276 void RenderManager::ContextDestroyed()
278 mImpl->context.GlContextDestroyed();
279 mImpl->programController.GlContextDestroyed();
282 for( auto&& texture : mImpl->textureContainer )
284 texture->GlContextDestroyed();
287 //Inform framebuffers
288 for( auto&& framebuffer : mImpl->frameBufferContainer )
290 framebuffer->GlContextDestroyed();
294 for( auto&& renderer : mImpl->rendererContainer )
296 renderer->GlContextDestroyed();
300 for( auto&& context : mImpl->sceneContextContainer )
302 context->GlContextDestroyed();
306 void RenderManager::SetShaderSaver( ShaderSaver& upstream )
308 mImpl->programController.SetShaderSaver( upstream );
311 void RenderManager::SetDefaultSurfaceRect(const Rect<int32_t>& rect)
313 mImpl->defaultSurfaceRect = rect;
316 void RenderManager::AddRenderer( OwnerPointer< Render::Renderer >& renderer )
318 // Initialize the renderer as we are now in render thread
319 renderer->Initialize( mImpl->context );
321 mImpl->rendererContainer.PushBack( renderer.Release() );
324 void RenderManager::RemoveRenderer( Render::Renderer* renderer )
326 mImpl->rendererContainer.EraseObject( renderer );
329 void RenderManager::AddSampler( OwnerPointer< Render::Sampler >& sampler )
331 mImpl->samplerContainer.PushBack( sampler.Release() );
334 void RenderManager::RemoveSampler( Render::Sampler* sampler )
336 mImpl->samplerContainer.EraseObject( sampler );
339 void RenderManager::AddTexture( OwnerPointer< Render::Texture >& texture )
341 texture->Initialize( mImpl->context );
342 mImpl->textureContainer.PushBack( texture.Release() );
345 void RenderManager::RemoveTexture( Render::Texture* texture )
347 DALI_ASSERT_DEBUG( NULL != texture );
349 // Find the texture, use reference to pointer so we can do the erase safely
350 for ( auto&& iter : mImpl->textureContainer )
352 if ( iter == texture )
354 texture->Destroy( mImpl->context );
355 mImpl->textureContainer.Erase( &iter ); // Texture found; now destroy it
361 void RenderManager::UploadTexture( Render::Texture* texture, PixelDataPtr pixelData, const Texture::UploadParams& params )
363 texture->Upload( mImpl->context, pixelData, params );
366 void RenderManager::GenerateMipmaps( Render::Texture* texture )
368 texture->GenerateMipmaps( mImpl->context );
371 void RenderManager::SetFilterMode( Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode )
373 sampler->mMinificationFilter = static_cast<Dali::FilterMode::Type>(minFilterMode);
374 sampler->mMagnificationFilter = static_cast<Dali::FilterMode::Type>(magFilterMode );
377 void RenderManager::SetWrapMode( Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode )
379 sampler->mRWrapMode = static_cast<Dali::WrapMode::Type>(rWrapMode);
380 sampler->mSWrapMode = static_cast<Dali::WrapMode::Type>(sWrapMode);
381 sampler->mTWrapMode = static_cast<Dali::WrapMode::Type>(tWrapMode);
384 void RenderManager::AddFrameBuffer( OwnerPointer< Render::FrameBuffer >& frameBuffer )
386 Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
387 mImpl->frameBufferContainer.PushBack( frameBufferPtr );
388 frameBufferPtr->Initialize( mImpl->context );
391 void RenderManager::RemoveFrameBuffer( Render::FrameBuffer* frameBuffer )
393 DALI_ASSERT_DEBUG( NULL != frameBuffer );
395 // Find the sampler, use reference so we can safely do the erase
396 for ( auto&& iter : mImpl->frameBufferContainer )
398 if ( iter == frameBuffer )
400 frameBuffer->Destroy( mImpl->context );
401 mImpl->frameBufferContainer.Erase( &iter ); // frameBuffer found; now destroy it
407 void RenderManager::InitializeScene( SceneGraph::Scene* scene )
409 scene->Initialize( *mImpl->CreateSceneContext() );
410 mImpl->sceneContainer.push_back( scene );
413 void RenderManager::UninitializeScene( SceneGraph::Scene* scene )
415 mImpl->DestroySceneContext( scene->GetContext() );
417 auto iter = std::find( mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene );
418 if( iter != mImpl->sceneContainer.end() )
420 mImpl->sceneContainer.erase( iter );
424 void RenderManager::SurfaceReplaced( SceneGraph::Scene* scene )
426 Context* newContext = mImpl->ReplaceSceneContext( scene->GetContext() );
427 scene->Initialize( *newContext );
430 void RenderManager::AttachColorTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer )
432 frameBuffer->AttachColorTexture( mImpl->context, texture, mipmapLevel, layer );
435 void RenderManager::AttachDepthTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel )
437 frameBuffer->AttachDepthTexture( mImpl->context, texture, mipmapLevel );
440 void RenderManager::AttachDepthStencilTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel )
442 frameBuffer->AttachDepthStencilTexture( mImpl->context, texture, mipmapLevel );
445 void RenderManager::AddPropertyBuffer( OwnerPointer< Render::PropertyBuffer >& propertyBuffer )
447 mImpl->propertyBufferContainer.PushBack( propertyBuffer.Release() );
450 void RenderManager::RemovePropertyBuffer( Render::PropertyBuffer* propertyBuffer )
452 mImpl->propertyBufferContainer.EraseObject( propertyBuffer );
455 void RenderManager::SetPropertyBufferFormat( Render::PropertyBuffer* propertyBuffer, OwnerPointer< Render::PropertyBuffer::Format>& format )
457 propertyBuffer->SetFormat( format.Release() );
460 void RenderManager::SetPropertyBufferData( Render::PropertyBuffer* propertyBuffer, OwnerPointer< Vector<uint8_t> >& data, uint32_t size )
462 propertyBuffer->SetData( data.Release(), size );
465 void RenderManager::SetIndexBuffer( Render::Geometry* geometry, Dali::Vector<uint16_t>& indices )
467 geometry->SetIndexBuffer( indices );
470 void RenderManager::AddGeometry( OwnerPointer< Render::Geometry >& geometry )
472 mImpl->geometryContainer.PushBack( geometry.Release() );
475 void RenderManager::RemoveGeometry( Render::Geometry* geometry )
477 mImpl->geometryContainer.EraseObject( geometry );
480 void RenderManager::AttachVertexBuffer( Render::Geometry* geometry, Render::PropertyBuffer* propertyBuffer )
482 DALI_ASSERT_DEBUG( NULL != geometry );
485 for ( auto&& iter : mImpl->geometryContainer )
487 if ( iter == geometry )
489 iter->AddPropertyBuffer( propertyBuffer );
495 void RenderManager::RemoveVertexBuffer( Render::Geometry* geometry, Render::PropertyBuffer* propertyBuffer )
497 DALI_ASSERT_DEBUG( NULL != geometry );
500 for ( auto&& iter : mImpl->geometryContainer )
502 if ( iter == geometry )
504 iter->RemovePropertyBuffer( propertyBuffer );
510 void RenderManager::SetGeometryType( Render::Geometry* geometry, uint32_t geometryType )
512 geometry->SetType( Render::Geometry::Type(geometryType) );
515 void RenderManager::AddRenderTracker( Render::RenderTracker* renderTracker )
517 mImpl->AddRenderTracker(renderTracker);
520 void RenderManager::RemoveRenderTracker( Render::RenderTracker* renderTracker )
522 mImpl->RemoveRenderTracker(renderTracker);
525 ProgramCache* RenderManager::GetProgramCache()
527 return &(mImpl->programController);
530 void RenderManager::PreRender( Integration::RenderStatus& status, bool forceClear, bool uploadOnly )
532 DALI_PRINT_RENDER_START( mImpl->renderBufferIndex );
534 // Core::Render documents that GL context must be current before calling Render
535 DALI_ASSERT_DEBUG( mImpl->context.IsGlContextCreated() );
537 // Increment the frame count at the beginning of each frame
540 // Process messages queued during previous update
541 mImpl->renderQueue.ProcessMessages( mImpl->renderBufferIndex );
544 for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
546 count += mImpl->sceneContainer[i]->GetRenderInstructions().Count( mImpl->renderBufferIndex );
549 const bool haveInstructions = count > 0u;
551 DALI_LOG_INFO( gLogFilter, Debug::General,
552 "Render: haveInstructions(%s) || mImpl->lastFrameWasRendered(%s) || forceClear(%s)\n",
553 haveInstructions ? "true" : "false",
554 mImpl->lastFrameWasRendered ? "true" : "false",
555 forceClear ? "true" : "false" );
557 // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
558 if( haveInstructions || mImpl->lastFrameWasRendered || forceClear )
560 DALI_LOG_INFO( gLogFilter, Debug::General, "Render: Processing\n" );
562 // Switch to the shared context
563 if ( mImpl->currentContext != &mImpl->context )
565 mImpl->currentContext = &mImpl->context;
567 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
569 mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
572 // Clear the current cached program when the context is switched
573 mImpl->programController.ClearCurrentProgram();
576 // Upload the geometries
577 for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
579 RenderInstructionContainer& instructions = mImpl->sceneContainer[i]->GetRenderInstructions();
580 for ( uint32_t j = 0; j < instructions.Count( mImpl->renderBufferIndex ); ++j )
582 RenderInstruction& instruction = instructions.At( mImpl->renderBufferIndex, j );
584 const Matrix* viewMatrix = instruction.GetViewMatrix( mImpl->renderBufferIndex );
585 const Matrix* projectionMatrix = instruction.GetProjectionMatrix( mImpl->renderBufferIndex );
587 DALI_ASSERT_DEBUG( viewMatrix );
588 DALI_ASSERT_DEBUG( projectionMatrix );
590 if( viewMatrix && projectionMatrix )
592 const RenderListContainer::SizeType renderListCount = instruction.RenderListCount();
594 // Iterate through each render list.
595 for( RenderListContainer::SizeType index = 0; index < renderListCount; ++index )
597 const RenderList* renderList = instruction.GetRenderList( index );
599 if( renderList && !renderList->IsEmpty() )
601 const std::size_t itemCount = renderList->Count();
602 for( uint32_t itemIndex = 0u; itemIndex < itemCount; ++itemIndex )
604 const RenderItem& item = renderList->GetItem( itemIndex );
605 if( DALI_LIKELY( item.mRenderer ) )
607 item.mRenderer->Upload( *mImpl->currentContext );
618 void RenderManager::PreRender( Integration::Scene& scene, std::vector<Rect<int>>& damagedRects )
620 if (mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
625 class DamagedRectsCleaner
628 DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects)
629 : mDamagedRects(damagedRects),
634 void SetCleanOnReturn(bool cleanOnReturn)
636 mCleanOnReturn = cleanOnReturn;
639 ~DamagedRectsCleaner()
643 mDamagedRects.clear();
648 std::vector<Rect<int>>& mDamagedRects;
652 Rect<int32_t> surfaceRect = Rect<int32_t>(0, 0, static_cast<int32_t>( scene.GetSize().width ), static_cast<int32_t>( scene.GetSize().height ));
654 // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
655 DamagedRectsCleaner damagedRectCleaner(damagedRects);
657 // Mark previous dirty rects in the sorted array. The array is already sorted by node and renderer, frame number.
658 // so you don't need to sort: std::stable_sort(mImpl->itemsDirtyRects.begin(), mImpl->itemsDirtyRects.end());
659 for (DirtyRect& dirtyRect : mImpl->itemsDirtyRects)
661 dirtyRect.visited = false;
664 Internal::Scene& sceneInternal = GetImplementation(scene);
665 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
666 uint32_t count = sceneObject->GetRenderInstructions().Count( mImpl->renderBufferIndex );
667 for (uint32_t i = 0; i < count; ++i)
669 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At( mImpl->renderBufferIndex, i );
671 if (instruction.mFrameBuffer)
673 return; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
676 const Camera* camera = instruction.GetCamera();
677 if (camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
679 const Node* node = instruction.GetCamera()->GetNode();
684 Quaternion orientation;
685 node->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
687 Vector3 orientationAxis;
688 Radian orientationAngle;
689 orientation.ToAxisAngle( orientationAxis, orientationAngle );
691 if (position.x > Math::MACHINE_EPSILON_10000 ||
692 position.y > Math::MACHINE_EPSILON_10000 ||
693 orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
694 orientationAngle != ANGLE_180 ||
695 scale != Vector3(1.0f, 1.0f, 1.0f))
706 Rect<int32_t> viewportRect;
707 if (instruction.mIsViewportSet)
709 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
710 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
711 if (viewportRect.IsEmpty() || !viewportRect.IsValid())
713 return; // just skip funny use cases for now, empty viewport means it is set somewhere else
718 viewportRect = surfaceRect;
721 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
722 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
723 if (viewMatrix && projectionMatrix)
725 const RenderListContainer::SizeType count = instruction.RenderListCount();
726 for (RenderListContainer::SizeType index = 0u; index < count; ++index)
728 const RenderList* renderList = instruction.GetRenderList( index );
729 if (renderList && !renderList->IsEmpty())
731 const std::size_t count = renderList->Count();
732 for (uint32_t index = 0u; index < count; ++index)
734 RenderItem& item = renderList->GetItem( index );
735 // If the item does 3D transformation, do early exit and clean the damaged rect array
736 if (item.mUpdateSize == Vector3::ZERO)
742 DirtyRect dirtyRect(item.mNode, item.mRenderer, mImpl->frameCount, rect);
743 // If the item refers to updated node or renderer.
744 if (item.mIsUpdated ||
746 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex, item.mNode)))))
748 item.mIsUpdated = false;
749 item.mNode->SetUpdated(false);
751 rect = item.CalculateViewportSpaceAABB(item.mUpdateSize, viewportRect.width, viewportRect.height);
752 if (rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
754 const int left = rect.x;
755 const int top = rect.y;
756 const int right = rect.x + rect.width;
757 const int bottom = rect.y + rect.height;
758 rect.x = (left / 16) * 16;
759 rect.y = (top / 16) * 16;
760 rect.width = ((right + 16) / 16) * 16 - rect.x;
761 rect.height = ((bottom + 16) / 16) * 16 - rect.y;
763 // Found valid dirty rect.
764 // 1. Insert it in the sorted array of the dirty rects.
765 // 2. Mark the related dirty rects as visited so they will not be removed below.
766 // 3. Keep only last 3 dirty rects for the same node and renderer (Tizen uses 3 back buffers, Ubuntu 1).
767 dirtyRect.rect = rect;
768 auto dirtyRectPos = std::lower_bound(mImpl->itemsDirtyRects.begin(), mImpl->itemsDirtyRects.end(), dirtyRect);
769 dirtyRectPos = mImpl->itemsDirtyRects.insert(dirtyRectPos, dirtyRect);
772 while (++dirtyRectPos != mImpl->itemsDirtyRects.end())
774 if (dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
779 dirtyRectPos->visited = true;
780 Rect<int>& dirtRect = dirtyRectPos->rect;
781 rect.Merge(dirtRect);
784 if (c > 3) // no more then 3 previous rects
786 mImpl->itemsDirtyRects.erase(dirtyRectPos);
791 damagedRects.push_back(rect);
796 // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
797 // 2. Mark the related dirty rects as visited so they will not be removed below.
798 auto dirtyRectPos = std::lower_bound(mImpl->itemsDirtyRects.begin(), mImpl->itemsDirtyRects.end(), dirtyRect);
799 while (dirtyRectPos != mImpl->itemsDirtyRects.end())
801 if (dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
806 dirtyRectPos->visited = true;
816 // Check removed nodes or removed renderers dirty rects
817 auto i = mImpl->itemsDirtyRects.begin();
818 auto j = mImpl->itemsDirtyRects.begin();
819 while (i != mImpl->itemsDirtyRects.end())
827 Rect<int>& dirtRect = i->rect;
828 damagedRects.push_back(dirtRect);
833 mImpl->itemsDirtyRects.resize(j - mImpl->itemsDirtyRects.begin());
834 damagedRectCleaner.SetCleanOnReturn(false);
837 void RenderManager::RenderScene( Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo )
839 Rect<int> clippingRect;
840 RenderScene( status, scene, renderToFbo, clippingRect);
843 void RenderManager::RenderScene( Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect )
845 Internal::Scene& sceneInternal = GetImplementation( scene );
846 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
848 uint32_t count = sceneObject->GetRenderInstructions().Count( mImpl->renderBufferIndex );
850 for( uint32_t i = 0; i < count; ++i )
852 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At( mImpl->renderBufferIndex, i );
854 if ( ( renderToFbo && !instruction.mFrameBuffer ) || ( !renderToFbo && instruction.mFrameBuffer ) )
859 // Mark that we will require a post-render step to be performed (includes swap-buffers).
860 status.SetNeedsPostRender( true );
862 Rect<int32_t> viewportRect;
865 if ( instruction.mIsClearColorSet )
867 clearColor = instruction.mClearColor;
871 clearColor = Dali::RenderTask::DEFAULT_CLEAR_COLOR;
874 Rect<int32_t> surfaceRect = mImpl->defaultSurfaceRect;
875 Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
876 Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
878 if ( instruction.mFrameBuffer )
881 if ( mImpl->currentContext != &mImpl->context )
883 // Switch to shared context for off-screen buffer
884 mImpl->currentContext = &mImpl->context;
886 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
888 mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
891 // Clear the current cached program when the context is switched
892 mImpl->programController.ClearCurrentProgram();
897 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
899 if ( mImpl->currentContext != sceneObject->GetContext() )
901 // Switch the correct context if rendering to a surface
902 mImpl->currentContext = sceneObject->GetContext();
904 // Clear the current cached program when the context is switched
905 mImpl->programController.ClearCurrentProgram();
909 surfaceRect = Rect<int32_t>( 0, 0, static_cast<int32_t>( scene.GetSize().width ), static_cast<int32_t>( scene.GetSize().height ) );
912 DALI_ASSERT_DEBUG( mImpl->currentContext->IsGlContextCreated() );
914 // reset the program matrices for all programs once per frame
915 // this ensures we will set view and projection matrix once per program per camera
916 mImpl->programController.ResetProgramMatrices();
918 if( instruction.mFrameBuffer )
920 instruction.mFrameBuffer->Bind( *mImpl->currentContext );
922 // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
923 for (unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
925 mImpl->textureDependencyList.PushBack( instruction.mFrameBuffer->GetTextureId(i0) );
930 mImpl->currentContext->BindFramebuffer( GL_FRAMEBUFFER, 0u );
933 if ( !instruction.mFrameBuffer )
935 mImpl->currentContext->Viewport( surfaceRect.x,
938 surfaceRect.height );
941 // Clear the entire color, depth and stencil buffers for the default framebuffer, if required.
942 // It is important to clear all 3 buffers when they are being used, for performance on deferred renderers
943 // e.g. previously when the depth & stencil buffers were NOT cleared, it caused the DDK to exceed a "vertex count limit",
944 // and then stall. That problem is only noticeable when rendering a large number of vertices per frame.
945 GLbitfield clearMask = GL_COLOR_BUFFER_BIT;
947 mImpl->currentContext->ColorMask( true );
949 if( depthBufferAvailable == Integration::DepthBufferAvailable::TRUE )
951 mImpl->currentContext->DepthMask( true );
952 clearMask |= GL_DEPTH_BUFFER_BIT;
955 if( stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE)
957 mImpl->currentContext->ClearStencil( 0 );
958 mImpl->currentContext->StencilMask( 0xFF ); // 8 bit stencil mask, all 1's
959 clearMask |= GL_STENCIL_BUFFER_BIT;
962 if( !instruction.mIgnoreRenderToFbo && ( instruction.mFrameBuffer != 0 ) )
964 // Offscreen buffer rendering
965 if ( instruction.mIsViewportSet )
967 // For glViewport the lower-left corner is (0,0)
968 const int32_t y = ( instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height ) - instruction.mViewport.y;
969 viewportRect.Set( instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height );
973 viewportRect.Set( 0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight() );
976 else // No Offscreen frame buffer rendering
978 // Check whether a viewport is specified, otherwise the full surface size is used
979 if ( instruction.mIsViewportSet )
981 // For glViewport the lower-left corner is (0,0)
982 const int32_t y = ( surfaceRect.height - instruction.mViewport.height ) - instruction.mViewport.y;
983 viewportRect.Set( instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height );
987 viewportRect = surfaceRect;
991 bool clearFullFrameRect = true;
992 if( instruction.mFrameBuffer != 0 )
994 Viewport frameRect( 0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight() );
995 clearFullFrameRect = ( frameRect == viewportRect );
999 clearFullFrameRect = ( surfaceRect == viewportRect );
1002 if (!clippingRect.IsEmpty())
1004 if (!clippingRect.Intersect(viewportRect))
1006 DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
1007 clippingRect = Rect<int>();
1009 clearFullFrameRect = false;
1012 mImpl->currentContext->Viewport(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
1014 if (instruction.mIsClearColorSet)
1016 mImpl->currentContext->ClearColor(clearColor.r,
1020 if (!clearFullFrameRect)
1022 if (!clippingRect.IsEmpty())
1024 mImpl->currentContext->SetScissorTest(true);
1025 mImpl->currentContext->Scissor(clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
1026 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
1027 mImpl->currentContext->SetScissorTest(false);
1031 mImpl->currentContext->SetScissorTest(true);
1032 mImpl->currentContext->Scissor(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
1033 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
1034 mImpl->currentContext->SetScissorTest(false);
1039 mImpl->currentContext->SetScissorTest(false);
1040 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
1044 // Clear the list of bound textures
1045 mImpl->boundTextures.Clear();
1047 mImpl->renderAlgorithms.ProcessRenderInstruction(
1049 *mImpl->currentContext,
1050 mImpl->renderBufferIndex,
1051 depthBufferAvailable,
1052 stencilBufferAvailable,
1053 mImpl->boundTextures,
1056 // Synchronise the FBO/Texture access when there are multiple contexts
1057 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
1059 // Check whether any binded texture is in the dependency list
1060 bool textureFound = false;
1062 if ( mImpl->boundTextures.Count() > 0u && mImpl->textureDependencyList.Count() > 0u )
1064 for ( auto textureId : mImpl->textureDependencyList )
1067 textureFound = std::find_if( mImpl->boundTextures.Begin(), mImpl->boundTextures.End(),
1068 [textureId]( GLuint id )
1070 return textureId == id;
1071 } ) != mImpl->boundTextures.End();
1077 if ( instruction.mFrameBuffer )
1079 // For off-screen buffer
1081 // Wait until all rendering calls for the currently context are executed
1082 mImpl->glContextHelperAbstraction.WaitClient();
1084 // Clear the dependency list
1085 mImpl->textureDependencyList.Clear();
1089 // Worker thread lambda function
1090 auto& glContextHelperAbstraction = mImpl->glContextHelperAbstraction;
1091 auto workerFunction = [&glContextHelperAbstraction]( int workerThread )
1093 // Switch to the shared context in the worker thread
1094 glContextHelperAbstraction.MakeSurfacelessContextCurrent();
1096 // Wait until all rendering calls for the shared context are executed
1097 glContextHelperAbstraction.WaitClient();
1099 // Must clear the context in the worker thread
1100 // Otherwise the shared context cannot be switched to from the render thread
1101 glContextHelperAbstraction.MakeContextNull();
1104 auto future = mImpl->threadPool->SubmitTask( 0u, workerFunction );
1107 mImpl->threadPool->Wait();
1109 // Clear the dependency list
1110 mImpl->textureDependencyList.Clear();
1116 if( instruction.mRenderTracker && instruction.mFrameBuffer )
1118 // This will create a sync object every frame this render tracker
1119 // is alive (though it should be now be created only for
1120 // render-once render tasks)
1121 instruction.mRenderTracker->CreateSyncObject( mImpl->glSyncAbstraction );
1122 instruction.mRenderTracker = nullptr; // Only create once.
1127 mImpl->currentContext->Flush();
1131 GLenum attachments[] = { GL_DEPTH, GL_STENCIL };
1132 mImpl->currentContext->InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
1135 void RenderManager::PostRender( bool uploadOnly )
1139 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
1141 mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
1144 GLenum attachments[] = { GL_DEPTH, GL_STENCIL };
1145 mImpl->context.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
1148 //Notify RenderGeometries that rendering has finished
1149 for ( auto&& iter : mImpl->geometryContainer )
1151 iter->OnRenderFinished();
1154 mImpl->UpdateTrackers();
1157 uint32_t count = 0u;
1158 for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
1160 count += mImpl->sceneContainer[i]->GetRenderInstructions().Count( mImpl->renderBufferIndex );
1163 const bool haveInstructions = count > 0u;
1165 // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
1166 mImpl->lastFrameWasRendered = haveInstructions;
1169 * The rendering has finished; swap to the next buffer.
1170 * Ideally the update has just finished using this buffer; otherwise the render thread
1171 * should block until the update has finished.
1173 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1175 DALI_PRINT_RENDER_END();
1178 } // namespace SceneGraph
1180 } // namespace Internal