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 ),
129 defaultSurfaceOrientation( 0 )
131 // Create thread pool with just one thread ( there may be a need to create more threads in the future ).
132 threadPool = std::unique_ptr<Dali::ThreadPool>( new Dali::ThreadPool() );
133 threadPool->Initialize( 1u );
138 threadPool.reset( nullptr ); // reset now to maintain correct destruction order
141 void AddRenderTracker( Render::RenderTracker* renderTracker )
143 DALI_ASSERT_DEBUG( renderTracker != NULL );
144 mRenderTrackers.PushBack( renderTracker );
147 void RemoveRenderTracker( Render::RenderTracker* renderTracker )
149 mRenderTrackers.EraseObject( renderTracker );
152 Context* CreateSceneContext()
154 Context* context = new Context( glAbstraction );
155 sceneContextContainer.PushBack( context );
159 void DestroySceneContext( Context* sceneContext )
161 auto iter = std::find( sceneContextContainer.Begin(), sceneContextContainer.End(), sceneContext );
162 if( iter != sceneContextContainer.End() )
164 ( *iter )->GlContextDestroyed();
165 sceneContextContainer.Erase( iter );
169 Context* ReplaceSceneContext( Context* oldSceneContext )
171 Context* newContext = new Context( glAbstraction );
173 oldSceneContext->GlContextDestroyed();
175 std::replace( sceneContextContainer.begin(), sceneContextContainer.end(), oldSceneContext, newContext );
179 void UpdateTrackers()
181 for( auto&& iter : mRenderTrackers )
183 iter->PollSyncObject();
187 // the order is important for destruction,
188 // programs are owned by context at the moment.
189 Context context; ///< Holds the GL state of the share resource context
190 Context* currentContext; ///< Holds the GL state of the current context for rendering
191 OwnerContainer< Context* > sceneContextContainer; ///< List of owned contexts holding the GL state per scene
192 Integration::GlAbstraction& glAbstraction; ///< GL abstraction
193 Integration::GlSyncAbstraction& glSyncAbstraction; ///< GL sync abstraction
194 Integration::GlContextHelperAbstraction& glContextHelperAbstraction; ///< GL context helper abstraction
195 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
197 std::vector< SceneGraph::Scene* > sceneContainer; ///< List of pointers to the scene graph objects of the scenes
199 Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
201 uint32_t frameCount; ///< The current frame count
202 BufferIndex renderBufferIndex; ///< The index of the buffer to read from; this is opposite of the "update" buffer
204 Rect<int32_t> defaultSurfaceRect; ///< Rectangle for the default surface we are rendering to
206 OwnerContainer< Render::Renderer* > rendererContainer; ///< List of owned renderers
207 OwnerContainer< Render::Sampler* > samplerContainer; ///< List of owned samplers
208 OwnerContainer< Render::Texture* > textureContainer; ///< List of owned textures
209 OwnerContainer< Render::FrameBuffer* > frameBufferContainer; ///< List of owned framebuffers
210 OwnerContainer< Render::VertexBuffer* > vertexBufferContainer; ///< List of owned vertex buffers
211 OwnerContainer< Render::Geometry* > geometryContainer; ///< List of owned Geometries
213 bool lastFrameWasRendered; ///< Keeps track of the last frame being rendered due to having render instructions
215 OwnerContainer< Render::RenderTracker* > mRenderTrackers; ///< List of render trackers
217 ProgramController programController; ///< Owner of the GL programs
219 Integration::DepthBufferAvailable depthBufferAvailable; ///< Whether the depth buffer is available
220 Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
221 Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
223 std::unique_ptr<Dali::ThreadPool> threadPool; ///< The thread pool
224 Vector<GLuint> boundTextures; ///< The textures bound for rendering
225 Vector<GLuint> textureDependencyList; ///< The dependency list of binded textures
226 std::size_t itemsCheckSum; ///< The damaged render items checksum from previous prerender phase.
227 std::vector<DirtyRect> itemsDirtyRects;
228 int defaultSurfaceOrientation; ///< defaultSurfaceOrientation for the default surface we are rendering to
231 RenderManager* RenderManager::New( Integration::GlAbstraction& glAbstraction,
232 Integration::GlSyncAbstraction& glSyncAbstraction,
233 Integration::GlContextHelperAbstraction& glContextHelperAbstraction,
234 Integration::DepthBufferAvailable depthBufferAvailable,
235 Integration::StencilBufferAvailable stencilBufferAvailable,
236 Integration::PartialUpdateAvailable partialUpdateAvailable )
238 RenderManager* manager = new RenderManager;
239 manager->mImpl = new Impl( glAbstraction,
241 glContextHelperAbstraction,
242 depthBufferAvailable,
243 stencilBufferAvailable,
244 partialUpdateAvailable );
248 RenderManager::RenderManager()
253 RenderManager::~RenderManager()
258 RenderQueue& RenderManager::GetRenderQueue()
260 return mImpl->renderQueue;
263 void RenderManager::ContextCreated()
265 mImpl->context.GlContextCreated();
266 mImpl->programController.GlContextCreated();
268 // renderers, textures and gpu buffers cannot reinitialize themselves
269 // so they rely on someone reloading the data for them
272 void RenderManager::ContextDestroyed()
274 mImpl->context.GlContextDestroyed();
275 mImpl->programController.GlContextDestroyed();
278 for( auto&& texture : mImpl->textureContainer )
280 texture->GlContextDestroyed();
283 //Inform framebuffers
284 for( auto&& framebuffer : mImpl->frameBufferContainer )
286 framebuffer->GlContextDestroyed();
290 for( auto&& renderer : mImpl->rendererContainer )
292 renderer->GlContextDestroyed();
296 for( auto&& context : mImpl->sceneContextContainer )
298 context->GlContextDestroyed();
302 void RenderManager::SetShaderSaver( ShaderSaver& upstream )
304 mImpl->programController.SetShaderSaver( upstream );
307 void RenderManager::SetDefaultSurfaceRect(const Rect<int32_t>& rect)
309 mImpl->defaultSurfaceRect = rect;
312 void RenderManager::SetDefaultSurfaceOrientation( int orientation )
314 mImpl->defaultSurfaceOrientation = orientation;
317 void RenderManager::AddRenderer( OwnerPointer< Render::Renderer >& renderer )
319 // Initialize the renderer as we are now in render thread
320 renderer->Initialize( mImpl->context );
322 mImpl->rendererContainer.PushBack( renderer.Release() );
325 void RenderManager::RemoveRenderer( Render::Renderer* renderer )
327 mImpl->rendererContainer.EraseObject( renderer );
330 void RenderManager::AddSampler( OwnerPointer< Render::Sampler >& sampler )
332 mImpl->samplerContainer.PushBack( sampler.Release() );
335 void RenderManager::RemoveSampler( Render::Sampler* sampler )
337 mImpl->samplerContainer.EraseObject( sampler );
340 void RenderManager::AddTexture( OwnerPointer< Render::Texture >& texture )
342 texture->Initialize( mImpl->context );
343 mImpl->textureContainer.PushBack( texture.Release() );
346 void RenderManager::RemoveTexture( Render::Texture* texture )
348 DALI_ASSERT_DEBUG( NULL != texture );
350 // Find the texture, use reference to pointer so we can do the erase safely
351 for ( auto&& iter : mImpl->textureContainer )
353 if ( iter == texture )
355 texture->Destroy( mImpl->context );
356 mImpl->textureContainer.Erase( &iter ); // Texture found; now destroy it
362 void RenderManager::UploadTexture( Render::Texture* texture, PixelDataPtr pixelData, const Texture::UploadParams& params )
364 texture->Upload( mImpl->context, pixelData, params );
367 void RenderManager::GenerateMipmaps( Render::Texture* texture )
369 texture->GenerateMipmaps( mImpl->context );
372 void RenderManager::SetFilterMode( Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode )
374 sampler->mMinificationFilter = static_cast<Dali::FilterMode::Type>(minFilterMode);
375 sampler->mMagnificationFilter = static_cast<Dali::FilterMode::Type>(magFilterMode );
378 void RenderManager::SetWrapMode( Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode )
380 sampler->mRWrapMode = static_cast<Dali::WrapMode::Type>(rWrapMode);
381 sampler->mSWrapMode = static_cast<Dali::WrapMode::Type>(sWrapMode);
382 sampler->mTWrapMode = static_cast<Dali::WrapMode::Type>(tWrapMode);
385 void RenderManager::AddFrameBuffer( OwnerPointer< Render::FrameBuffer >& frameBuffer )
387 Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
388 mImpl->frameBufferContainer.PushBack( frameBufferPtr );
389 frameBufferPtr->Initialize( mImpl->context );
392 void RenderManager::RemoveFrameBuffer( Render::FrameBuffer* frameBuffer )
394 DALI_ASSERT_DEBUG( NULL != frameBuffer );
396 // Find the sampler, use reference so we can safely do the erase
397 for ( auto&& iter : mImpl->frameBufferContainer )
399 if ( iter == frameBuffer )
401 frameBuffer->Destroy( mImpl->context );
402 mImpl->frameBufferContainer.Erase( &iter ); // frameBuffer found; now destroy it
408 void RenderManager::InitializeScene( SceneGraph::Scene* scene )
410 scene->Initialize( *mImpl->CreateSceneContext() );
411 mImpl->sceneContainer.push_back( scene );
414 void RenderManager::UninitializeScene( SceneGraph::Scene* scene )
416 mImpl->DestroySceneContext( scene->GetContext() );
418 auto iter = std::find( mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene );
419 if( iter != mImpl->sceneContainer.end() )
421 mImpl->sceneContainer.erase( iter );
425 void RenderManager::SurfaceReplaced( SceneGraph::Scene* scene )
427 Context* newContext = mImpl->ReplaceSceneContext( scene->GetContext() );
428 scene->Initialize( *newContext );
431 void RenderManager::AttachColorTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer )
433 frameBuffer->AttachColorTexture( mImpl->context, texture, mipmapLevel, layer );
436 void RenderManager::AttachDepthTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel )
438 frameBuffer->AttachDepthTexture( mImpl->context, texture, mipmapLevel );
441 void RenderManager::AttachDepthStencilTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel )
443 frameBuffer->AttachDepthStencilTexture( mImpl->context, texture, mipmapLevel );
446 void RenderManager::AddVertexBuffer( OwnerPointer< Render::VertexBuffer >& vertexBuffer )
448 mImpl->vertexBufferContainer.PushBack( vertexBuffer.Release() );
451 void RenderManager::RemoveVertexBuffer( Render::VertexBuffer* vertexBuffer )
453 mImpl->vertexBufferContainer.EraseObject( vertexBuffer );
456 void RenderManager::SetVertexBufferFormat( Render::VertexBuffer* vertexBuffer, OwnerPointer< Render::VertexBuffer::Format>& format )
458 vertexBuffer->SetFormat( format.Release() );
461 void RenderManager::SetVertexBufferData( Render::VertexBuffer* vertexBuffer, OwnerPointer< Vector<uint8_t> >& data, uint32_t size )
463 vertexBuffer->SetData( data.Release(), size );
466 void RenderManager::SetIndexBuffer( Render::Geometry* geometry, Dali::Vector<uint16_t>& indices )
468 geometry->SetIndexBuffer( indices );
471 void RenderManager::AddGeometry( OwnerPointer< Render::Geometry >& geometry )
473 mImpl->geometryContainer.PushBack( geometry.Release() );
476 void RenderManager::RemoveGeometry( Render::Geometry* geometry )
478 mImpl->geometryContainer.EraseObject( geometry );
481 void RenderManager::AttachVertexBuffer( Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer )
483 DALI_ASSERT_DEBUG( NULL != geometry );
486 for ( auto&& iter : mImpl->geometryContainer )
488 if ( iter == geometry )
490 iter->AddVertexBuffer( vertexBuffer );
496 void RenderManager::RemoveVertexBuffer( Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer )
498 DALI_ASSERT_DEBUG( NULL != geometry );
501 for ( auto&& iter : mImpl->geometryContainer )
503 if ( iter == geometry )
505 iter->RemoveVertexBuffer( vertexBuffer );
511 void RenderManager::SetGeometryType( Render::Geometry* geometry, uint32_t geometryType )
513 geometry->SetType( Render::Geometry::Type(geometryType) );
516 void RenderManager::AddRenderTracker( Render::RenderTracker* renderTracker )
518 mImpl->AddRenderTracker(renderTracker);
521 void RenderManager::RemoveRenderTracker( Render::RenderTracker* renderTracker )
523 mImpl->RemoveRenderTracker(renderTracker);
526 ProgramCache* RenderManager::GetProgramCache()
528 return &(mImpl->programController);
531 void RenderManager::PreRender( Integration::RenderStatus& status, bool forceClear, bool uploadOnly )
533 DALI_PRINT_RENDER_START( mImpl->renderBufferIndex );
535 // Core::Render documents that GL context must be current before calling Render
536 DALI_ASSERT_DEBUG( mImpl->context.IsGlContextCreated() );
538 // Increment the frame count at the beginning of each frame
541 // Process messages queued during previous update
542 mImpl->renderQueue.ProcessMessages( mImpl->renderBufferIndex );
545 for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
547 count += mImpl->sceneContainer[i]->GetRenderInstructions().Count( mImpl->renderBufferIndex );
550 const bool haveInstructions = count > 0u;
552 DALI_LOG_INFO( gLogFilter, Debug::General,
553 "Render: haveInstructions(%s) || mImpl->lastFrameWasRendered(%s) || forceClear(%s)\n",
554 haveInstructions ? "true" : "false",
555 mImpl->lastFrameWasRendered ? "true" : "false",
556 forceClear ? "true" : "false" );
558 // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
559 if( haveInstructions || mImpl->lastFrameWasRendered || forceClear )
561 DALI_LOG_INFO( gLogFilter, Debug::General, "Render: Processing\n" );
563 // Switch to the shared context
564 if ( mImpl->currentContext != &mImpl->context )
566 mImpl->currentContext = &mImpl->context;
568 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
570 mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
573 // Clear the current cached program when the context is switched
574 mImpl->programController.ClearCurrentProgram();
577 // Upload the geometries
578 for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
580 RenderInstructionContainer& instructions = mImpl->sceneContainer[i]->GetRenderInstructions();
581 for ( uint32_t j = 0; j < instructions.Count( mImpl->renderBufferIndex ); ++j )
583 RenderInstruction& instruction = instructions.At( mImpl->renderBufferIndex, j );
585 const Matrix* viewMatrix = instruction.GetViewMatrix( mImpl->renderBufferIndex );
586 const Matrix* projectionMatrix = instruction.GetProjectionMatrix( mImpl->renderBufferIndex );
588 DALI_ASSERT_DEBUG( viewMatrix );
589 DALI_ASSERT_DEBUG( projectionMatrix );
591 if( viewMatrix && projectionMatrix )
593 const RenderListContainer::SizeType renderListCount = instruction.RenderListCount();
595 // Iterate through each render list.
596 for( RenderListContainer::SizeType index = 0; index < renderListCount; ++index )
598 const RenderList* renderList = instruction.GetRenderList( index );
600 if( renderList && !renderList->IsEmpty() )
602 const std::size_t itemCount = renderList->Count();
603 for( uint32_t itemIndex = 0u; itemIndex < itemCount; ++itemIndex )
605 const RenderItem& item = renderList->GetItem( itemIndex );
606 if( DALI_LIKELY( item.mRenderer ) )
608 item.mRenderer->Upload( *mImpl->currentContext );
619 void RenderManager::PreRender( Integration::Scene& scene, std::vector<Rect<int>>& damagedRects )
621 if (mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
626 class DamagedRectsCleaner
629 DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects)
630 : mDamagedRects(damagedRects),
635 void SetCleanOnReturn(bool cleanOnReturn)
637 mCleanOnReturn = cleanOnReturn;
640 ~DamagedRectsCleaner()
644 mDamagedRects.clear();
649 std::vector<Rect<int>>& mDamagedRects;
653 Rect<int32_t> surfaceRect = Rect<int32_t>(0, 0, static_cast<int32_t>( scene.GetSize().width ), static_cast<int32_t>( scene.GetSize().height ));
655 // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
656 DamagedRectsCleaner damagedRectCleaner(damagedRects);
658 // Mark previous dirty rects in the sorted array. The array is already sorted by node and renderer, frame number.
659 // so you don't need to sort: std::stable_sort(mImpl->itemsDirtyRects.begin(), mImpl->itemsDirtyRects.end());
660 for (DirtyRect& dirtyRect : mImpl->itemsDirtyRects)
662 dirtyRect.visited = false;
665 Internal::Scene& sceneInternal = GetImplementation(scene);
666 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
667 uint32_t count = sceneObject->GetRenderInstructions().Count( mImpl->renderBufferIndex );
668 for (uint32_t i = 0; i < count; ++i)
670 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At( mImpl->renderBufferIndex, i );
672 if (instruction.mFrameBuffer)
674 return; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
677 const Camera* camera = instruction.GetCamera();
678 if (camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
680 const Node* node = instruction.GetCamera()->GetNode();
685 Quaternion orientation;
686 node->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
688 Vector3 orientationAxis;
689 Radian orientationAngle;
690 orientation.ToAxisAngle( orientationAxis, orientationAngle );
692 if (position.x > Math::MACHINE_EPSILON_10000 ||
693 position.y > Math::MACHINE_EPSILON_10000 ||
694 orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
695 orientationAngle != ANGLE_180 ||
696 scale != Vector3(1.0f, 1.0f, 1.0f))
707 Rect<int32_t> viewportRect;
708 if (instruction.mIsViewportSet)
710 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
711 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
712 if (viewportRect.IsEmpty() || !viewportRect.IsValid())
714 return; // just skip funny use cases for now, empty viewport means it is set somewhere else
719 viewportRect = surfaceRect;
722 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
723 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
724 if (viewMatrix && projectionMatrix)
726 const RenderListContainer::SizeType count = instruction.RenderListCount();
727 for (RenderListContainer::SizeType index = 0u; index < count; ++index)
729 const RenderList* renderList = instruction.GetRenderList( index );
730 if (renderList && !renderList->IsEmpty())
732 const std::size_t count = renderList->Count();
733 for (uint32_t index = 0u; index < count; ++index)
735 RenderItem& item = renderList->GetItem( index );
736 // If the item does 3D transformation, do early exit and clean the damaged rect array
737 if (item.mUpdateSize == Vector3::ZERO)
743 DirtyRect dirtyRect(item.mNode, item.mRenderer, mImpl->frameCount, rect);
744 // If the item refers to updated node or renderer.
745 if (item.mIsUpdated ||
747 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex, item.mNode)))))
749 item.mIsUpdated = false;
750 item.mNode->SetUpdated(false);
752 rect = item.CalculateViewportSpaceAABB(item.mUpdateSize, viewportRect.width, viewportRect.height);
753 if (rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
755 const int left = rect.x;
756 const int top = rect.y;
757 const int right = rect.x + rect.width;
758 const int bottom = rect.y + rect.height;
759 rect.x = (left / 16) * 16;
760 rect.y = (top / 16) * 16;
761 rect.width = ((right + 16) / 16) * 16 - rect.x;
762 rect.height = ((bottom + 16) / 16) * 16 - rect.y;
764 // Found valid dirty rect.
765 // 1. Insert it in the sorted array of the dirty rects.
766 // 2. Mark the related dirty rects as visited so they will not be removed below.
767 // 3. Keep only last 3 dirty rects for the same node and renderer (Tizen uses 3 back buffers, Ubuntu 1).
768 dirtyRect.rect = rect;
769 auto dirtyRectPos = std::lower_bound(mImpl->itemsDirtyRects.begin(), mImpl->itemsDirtyRects.end(), dirtyRect);
770 dirtyRectPos = mImpl->itemsDirtyRects.insert(dirtyRectPos, dirtyRect);
773 while (++dirtyRectPos != mImpl->itemsDirtyRects.end())
775 if (dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
780 dirtyRectPos->visited = true;
781 Rect<int>& dirtRect = dirtyRectPos->rect;
782 rect.Merge(dirtRect);
785 if (c > 3) // no more then 3 previous rects
787 mImpl->itemsDirtyRects.erase(dirtyRectPos);
792 damagedRects.push_back(rect);
797 // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
798 // 2. Mark the related dirty rects as visited so they will not be removed below.
799 auto dirtyRectPos = std::lower_bound(mImpl->itemsDirtyRects.begin(), mImpl->itemsDirtyRects.end(), dirtyRect);
800 while (dirtyRectPos != mImpl->itemsDirtyRects.end())
802 if (dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
807 dirtyRectPos->visited = true;
817 // Check removed nodes or removed renderers dirty rects
818 auto i = mImpl->itemsDirtyRects.begin();
819 auto j = mImpl->itemsDirtyRects.begin();
820 while (i != mImpl->itemsDirtyRects.end())
828 Rect<int>& dirtRect = i->rect;
829 damagedRects.push_back(dirtRect);
834 mImpl->itemsDirtyRects.resize(j - mImpl->itemsDirtyRects.begin());
835 damagedRectCleaner.SetCleanOnReturn(false);
838 void RenderManager::RenderScene( Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo )
840 Rect<int> clippingRect;
841 RenderScene( status, scene, renderToFbo, clippingRect);
844 void RenderManager::RenderScene( Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect )
846 Internal::Scene& sceneInternal = GetImplementation( scene );
847 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
849 uint32_t count = sceneObject->GetRenderInstructions().Count( mImpl->renderBufferIndex );
851 for( uint32_t i = 0; i < count; ++i )
853 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At( mImpl->renderBufferIndex, i );
855 if ( ( renderToFbo && !instruction.mFrameBuffer ) || ( !renderToFbo && instruction.mFrameBuffer ) )
860 // Mark that we will require a post-render step to be performed (includes swap-buffers).
861 status.SetNeedsPostRender( true );
863 Rect<int32_t> viewportRect;
866 if ( instruction.mIsClearColorSet )
868 clearColor = instruction.mClearColor;
872 clearColor = Dali::RenderTask::DEFAULT_CLEAR_COLOR;
875 Rect<int32_t> surfaceRect = mImpl->defaultSurfaceRect;
876 Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
877 Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
878 int surfaceOrientation = mImpl->defaultSurfaceOrientation;
880 if ( instruction.mFrameBuffer )
883 if ( mImpl->currentContext != &mImpl->context )
885 // Switch to shared context for off-screen buffer
886 mImpl->currentContext = &mImpl->context;
888 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
890 mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
893 // Clear the current cached program when the context is switched
894 mImpl->programController.ClearCurrentProgram();
899 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
901 if ( mImpl->currentContext != sceneObject->GetContext() )
903 // Switch the correct context if rendering to a surface
904 mImpl->currentContext = sceneObject->GetContext();
906 // Clear the current cached program when the context is switched
907 mImpl->programController.ClearCurrentProgram();
911 surfaceRect = Rect<int32_t>( 0, 0, static_cast<int32_t>( scene.GetSize().width ), static_cast<int32_t>( scene.GetSize().height ) );
914 // Make sure that GL context must be created
915 mImpl->currentContext->GlContextCreated();
917 // reset the program matrices for all programs once per frame
918 // this ensures we will set view and projection matrix once per program per camera
919 mImpl->programController.ResetProgramMatrices();
921 if( instruction.mFrameBuffer )
923 instruction.mFrameBuffer->Bind( *mImpl->currentContext );
925 // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
926 for (unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
928 mImpl->textureDependencyList.PushBack( instruction.mFrameBuffer->GetTextureId(i0) );
933 mImpl->currentContext->BindFramebuffer( GL_FRAMEBUFFER, 0u );
936 if ( !instruction.mFrameBuffer )
938 mImpl->currentContext->Viewport( surfaceRect.x,
941 surfaceRect.height );
944 // Clear the entire color, depth and stencil buffers for the default framebuffer, if required.
945 // It is important to clear all 3 buffers when they are being used, for performance on deferred renderers
946 // e.g. previously when the depth & stencil buffers were NOT cleared, it caused the DDK to exceed a "vertex count limit",
947 // and then stall. That problem is only noticeable when rendering a large number of vertices per frame.
948 GLbitfield clearMask = GL_COLOR_BUFFER_BIT;
950 mImpl->currentContext->ColorMask( true );
952 if( depthBufferAvailable == Integration::DepthBufferAvailable::TRUE )
954 mImpl->currentContext->DepthMask( true );
955 clearMask |= GL_DEPTH_BUFFER_BIT;
958 if( stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE)
960 mImpl->currentContext->ClearStencil( 0 );
961 mImpl->currentContext->StencilMask( 0xFF ); // 8 bit stencil mask, all 1's
962 clearMask |= GL_STENCIL_BUFFER_BIT;
965 if( !instruction.mIgnoreRenderToFbo && ( instruction.mFrameBuffer != nullptr ) )
967 // Offscreen buffer rendering
968 if ( instruction.mIsViewportSet )
970 // For glViewport the lower-left corner is (0,0)
971 const int32_t y = ( instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height ) - instruction.mViewport.y;
972 viewportRect.Set( instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height );
976 viewportRect.Set( 0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight() );
978 surfaceOrientation = 0;
980 else // No Offscreen frame buffer rendering
982 // Check whether a viewport is specified, otherwise the full surface size is used
983 if ( instruction.mIsViewportSet )
985 // For glViewport the lower-left corner is (0,0)
986 const int32_t y = ( surfaceRect.height - instruction.mViewport.height ) - instruction.mViewport.y;
987 viewportRect.Set( instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height );
991 viewportRect = surfaceRect;
995 if( surfaceOrientation == 90 || surfaceOrientation == 270 )
997 int temp = viewportRect.width;
998 viewportRect.width = viewportRect.height;
999 viewportRect.height = temp;
1002 bool clearFullFrameRect = true;
1003 if( instruction.mFrameBuffer != nullptr )
1005 Viewport frameRect( 0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight() );
1006 clearFullFrameRect = ( frameRect == viewportRect );
1010 clearFullFrameRect = ( surfaceRect == viewportRect );
1013 if (!clippingRect.IsEmpty())
1015 if (!clippingRect.Intersect(viewportRect))
1017 DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
1018 clippingRect = Rect<int>();
1020 clearFullFrameRect = false;
1023 mImpl->currentContext->Viewport(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
1025 if (instruction.mIsClearColorSet)
1027 mImpl->currentContext->ClearColor(clearColor.r,
1031 if (!clearFullFrameRect)
1033 if (!clippingRect.IsEmpty())
1035 mImpl->currentContext->SetScissorTest(true);
1036 mImpl->currentContext->Scissor(clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
1037 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
1038 mImpl->currentContext->SetScissorTest(false);
1042 mImpl->currentContext->SetScissorTest(true);
1043 mImpl->currentContext->Scissor(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
1044 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
1045 mImpl->currentContext->SetScissorTest(false);
1050 mImpl->currentContext->SetScissorTest(false);
1051 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
1055 // Clear the list of bound textures
1056 mImpl->boundTextures.Clear();
1058 mImpl->renderAlgorithms.ProcessRenderInstruction(
1060 *mImpl->currentContext,
1061 mImpl->renderBufferIndex,
1062 depthBufferAvailable,
1063 stencilBufferAvailable,
1064 mImpl->boundTextures,
1066 surfaceOrientation );
1068 // Synchronise the FBO/Texture access when there are multiple contexts
1069 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
1071 // Check whether any binded texture is in the dependency list
1072 bool textureFound = false;
1074 if ( mImpl->boundTextures.Count() > 0u && mImpl->textureDependencyList.Count() > 0u )
1076 for ( auto textureId : mImpl->textureDependencyList )
1079 textureFound = std::find_if( mImpl->boundTextures.Begin(), mImpl->boundTextures.End(),
1080 [textureId]( GLuint id )
1082 return textureId == id;
1083 } ) != mImpl->boundTextures.End();
1089 if ( instruction.mFrameBuffer )
1091 // For off-screen buffer
1093 // Wait until all rendering calls for the currently context are executed
1094 mImpl->glContextHelperAbstraction.WaitClient();
1096 // Clear the dependency list
1097 mImpl->textureDependencyList.Clear();
1101 // Worker thread lambda function
1102 auto& glContextHelperAbstraction = mImpl->glContextHelperAbstraction;
1103 auto workerFunction = [&glContextHelperAbstraction]( int workerThread )
1105 // Switch to the shared context in the worker thread
1106 glContextHelperAbstraction.MakeSurfacelessContextCurrent();
1108 // Wait until all rendering calls for the shared context are executed
1109 glContextHelperAbstraction.WaitClient();
1111 // Must clear the context in the worker thread
1112 // Otherwise the shared context cannot be switched to from the render thread
1113 glContextHelperAbstraction.MakeContextNull();
1116 auto future = mImpl->threadPool->SubmitTask( 0u, workerFunction );
1119 mImpl->threadPool->Wait();
1121 // Clear the dependency list
1122 mImpl->textureDependencyList.Clear();
1128 if( instruction.mRenderTracker && instruction.mFrameBuffer )
1130 // This will create a sync object every frame this render tracker
1131 // is alive (though it should be now be created only for
1132 // render-once render tasks)
1133 instruction.mRenderTracker->CreateSyncObject( mImpl->glSyncAbstraction );
1134 instruction.mRenderTracker = nullptr; // Only create once.
1139 mImpl->currentContext->Flush();
1143 GLenum attachments[] = { GL_DEPTH, GL_STENCIL };
1144 mImpl->currentContext->InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
1147 void RenderManager::PostRender( bool uploadOnly )
1151 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
1153 mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
1156 GLenum attachments[] = { GL_DEPTH, GL_STENCIL };
1157 mImpl->context.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
1160 //Notify RenderGeometries that rendering has finished
1161 for ( auto&& iter : mImpl->geometryContainer )
1163 iter->OnRenderFinished();
1166 mImpl->UpdateTrackers();
1169 uint32_t count = 0u;
1170 for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
1172 count += mImpl->sceneContainer[i]->GetRenderInstructions().Count( mImpl->renderBufferIndex );
1175 const bool haveInstructions = count > 0u;
1177 // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
1178 mImpl->lastFrameWasRendered = haveInstructions;
1181 * The rendering has finished; swap to the next buffer.
1182 * Ideally the update has just finished using this buffer; otherwise the render thread
1183 * should block until the update has finished.
1185 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1187 DALI_PRINT_RENDER_END();
1190 } // namespace SceneGraph
1192 } // namespace Internal