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 );
156 //TODO: Need eglMakeCurrent first
157 context->GlContextCreated();
159 sceneContextContainer.PushBack( context );
163 void DestroySceneContext( Context* sceneContext )
165 auto iter = std::find( sceneContextContainer.Begin(), sceneContextContainer.End(), sceneContext );
166 if( iter != sceneContextContainer.End() )
168 ( *iter )->GlContextDestroyed();
169 sceneContextContainer.Erase( iter );
173 Context* ReplaceSceneContext( Context* oldSceneContext )
175 Context* newContext = new Context( glAbstraction );
177 oldSceneContext->GlContextDestroyed();
178 //TODO: Need eglMakeCurrent first
179 newContext->GlContextCreated();
181 std::replace( sceneContextContainer.begin(), sceneContextContainer.end(), oldSceneContext, newContext );
185 void UpdateTrackers()
187 for( auto&& iter : mRenderTrackers )
189 iter->PollSyncObject();
193 // the order is important for destruction,
194 // programs are owned by context at the moment.
195 Context context; ///< Holds the GL state of the share resource context
196 Context* currentContext; ///< Holds the GL state of the current context for rendering
197 OwnerContainer< Context* > sceneContextContainer; ///< List of owned contexts holding the GL state per scene
198 Integration::GlAbstraction& glAbstraction; ///< GL abstraction
199 Integration::GlSyncAbstraction& glSyncAbstraction; ///< GL sync abstraction
200 Integration::GlContextHelperAbstraction& glContextHelperAbstraction; ///< GL context helper abstraction
201 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
203 std::vector< SceneGraph::Scene* > sceneContainer; ///< List of pointers to the scene graph objects of the scenes
205 Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
207 uint32_t frameCount; ///< The current frame count
208 BufferIndex renderBufferIndex; ///< The index of the buffer to read from; this is opposite of the "update" buffer
210 Rect<int32_t> defaultSurfaceRect; ///< Rectangle for the default surface we are rendering to
212 OwnerContainer< Render::Renderer* > rendererContainer; ///< List of owned renderers
213 OwnerContainer< Render::Sampler* > samplerContainer; ///< List of owned samplers
214 OwnerContainer< Render::Texture* > textureContainer; ///< List of owned textures
215 OwnerContainer< Render::FrameBuffer* > frameBufferContainer; ///< List of owned framebuffers
216 OwnerContainer< Render::PropertyBuffer* > propertyBufferContainer; ///< List of owned property buffers
217 OwnerContainer< Render::Geometry* > geometryContainer; ///< List of owned Geometries
219 bool lastFrameWasRendered; ///< Keeps track of the last frame being rendered due to having render instructions
221 OwnerContainer< Render::RenderTracker* > mRenderTrackers; ///< List of render trackers
223 ProgramController programController; ///< Owner of the GL programs
225 Integration::DepthBufferAvailable depthBufferAvailable; ///< Whether the depth buffer is available
226 Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
227 Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
229 std::unique_ptr<Dali::ThreadPool> threadPool; ///< The thread pool
230 Vector<GLuint> boundTextures; ///< The textures bound for rendering
231 Vector<GLuint> textureDependencyList; ///< The dependency list of binded textures
232 std::size_t itemsCheckSum; ///< The damaged render items checksum from previous prerender phase.
233 std::vector<DirtyRect> itemsDirtyRects;
234 int defaultSurfaceOrientation; ///< defaultSurfaceOrientation for the default surface we are rendering to
237 RenderManager* RenderManager::New( Integration::GlAbstraction& glAbstraction,
238 Integration::GlSyncAbstraction& glSyncAbstraction,
239 Integration::GlContextHelperAbstraction& glContextHelperAbstraction,
240 Integration::DepthBufferAvailable depthBufferAvailable,
241 Integration::StencilBufferAvailable stencilBufferAvailable,
242 Integration::PartialUpdateAvailable partialUpdateAvailable )
244 RenderManager* manager = new RenderManager;
245 manager->mImpl = new Impl( glAbstraction,
247 glContextHelperAbstraction,
248 depthBufferAvailable,
249 stencilBufferAvailable,
250 partialUpdateAvailable );
254 RenderManager::RenderManager()
259 RenderManager::~RenderManager()
264 RenderQueue& RenderManager::GetRenderQueue()
266 return mImpl->renderQueue;
269 void RenderManager::ContextCreated()
271 mImpl->context.GlContextCreated();
272 mImpl->programController.GlContextCreated();
274 // renderers, textures and gpu buffers cannot reinitialize themselves
275 // so they rely on someone reloading the data for them
278 void RenderManager::ContextDestroyed()
280 mImpl->context.GlContextDestroyed();
281 mImpl->programController.GlContextDestroyed();
284 for( auto&& texture : mImpl->textureContainer )
286 texture->GlContextDestroyed();
289 //Inform framebuffers
290 for( auto&& framebuffer : mImpl->frameBufferContainer )
292 framebuffer->GlContextDestroyed();
296 for( auto&& renderer : mImpl->rendererContainer )
298 renderer->GlContextDestroyed();
302 for( auto&& context : mImpl->sceneContextContainer )
304 context->GlContextDestroyed();
308 void RenderManager::SetShaderSaver( ShaderSaver& upstream )
310 mImpl->programController.SetShaderSaver( upstream );
313 void RenderManager::SetDefaultSurfaceRect(const Rect<int32_t>& rect)
315 mImpl->defaultSurfaceRect = rect;
318 void RenderManager::SetDefaultSurfaceOrientation( int orientation )
320 mImpl->defaultSurfaceOrientation = orientation;
323 void RenderManager::AddRenderer( OwnerPointer< Render::Renderer >& renderer )
325 // Initialize the renderer as we are now in render thread
326 renderer->Initialize( mImpl->context );
328 mImpl->rendererContainer.PushBack( renderer.Release() );
331 void RenderManager::RemoveRenderer( Render::Renderer* renderer )
333 mImpl->rendererContainer.EraseObject( renderer );
336 void RenderManager::AddSampler( OwnerPointer< Render::Sampler >& sampler )
338 mImpl->samplerContainer.PushBack( sampler.Release() );
341 void RenderManager::RemoveSampler( Render::Sampler* sampler )
343 mImpl->samplerContainer.EraseObject( sampler );
346 void RenderManager::AddTexture( OwnerPointer< Render::Texture >& texture )
348 texture->Initialize( mImpl->context );
349 mImpl->textureContainer.PushBack( texture.Release() );
352 void RenderManager::RemoveTexture( Render::Texture* texture )
354 DALI_ASSERT_DEBUG( NULL != texture );
356 // Find the texture, use reference to pointer so we can do the erase safely
357 for ( auto&& iter : mImpl->textureContainer )
359 if ( iter == texture )
361 texture->Destroy( mImpl->context );
362 mImpl->textureContainer.Erase( &iter ); // Texture found; now destroy it
368 void RenderManager::UploadTexture( Render::Texture* texture, PixelDataPtr pixelData, const Texture::UploadParams& params )
370 texture->Upload( mImpl->context, pixelData, params );
373 void RenderManager::GenerateMipmaps( Render::Texture* texture )
375 texture->GenerateMipmaps( mImpl->context );
378 void RenderManager::SetFilterMode( Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode )
380 sampler->mMinificationFilter = static_cast<Dali::FilterMode::Type>(minFilterMode);
381 sampler->mMagnificationFilter = static_cast<Dali::FilterMode::Type>(magFilterMode );
384 void RenderManager::SetWrapMode( Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode )
386 sampler->mRWrapMode = static_cast<Dali::WrapMode::Type>(rWrapMode);
387 sampler->mSWrapMode = static_cast<Dali::WrapMode::Type>(sWrapMode);
388 sampler->mTWrapMode = static_cast<Dali::WrapMode::Type>(tWrapMode);
391 void RenderManager::AddFrameBuffer( OwnerPointer< Render::FrameBuffer >& frameBuffer )
393 Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
394 mImpl->frameBufferContainer.PushBack( frameBufferPtr );
395 frameBufferPtr->Initialize( mImpl->context );
398 void RenderManager::RemoveFrameBuffer( Render::FrameBuffer* frameBuffer )
400 DALI_ASSERT_DEBUG( NULL != frameBuffer );
402 // Find the sampler, use reference so we can safely do the erase
403 for ( auto&& iter : mImpl->frameBufferContainer )
405 if ( iter == frameBuffer )
407 frameBuffer->Destroy( mImpl->context );
408 mImpl->frameBufferContainer.Erase( &iter ); // frameBuffer found; now destroy it
414 void RenderManager::InitializeScene( SceneGraph::Scene* scene )
416 scene->Initialize( *mImpl->CreateSceneContext() );
417 mImpl->sceneContainer.push_back( scene );
420 void RenderManager::UninitializeScene( SceneGraph::Scene* scene )
422 mImpl->DestroySceneContext( scene->GetContext() );
424 auto iter = std::find( mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene );
425 if( iter != mImpl->sceneContainer.end() )
427 mImpl->sceneContainer.erase( iter );
431 void RenderManager::SurfaceReplaced( SceneGraph::Scene* scene )
433 Context* newContext = mImpl->ReplaceSceneContext( scene->GetContext() );
434 scene->Initialize( *newContext );
437 void RenderManager::AttachColorTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer )
439 frameBuffer->AttachColorTexture( mImpl->context, texture, mipmapLevel, layer );
442 void RenderManager::AttachDepthTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel )
444 frameBuffer->AttachDepthTexture( mImpl->context, texture, mipmapLevel );
447 void RenderManager::AttachDepthStencilTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel )
449 frameBuffer->AttachDepthStencilTexture( mImpl->context, texture, mipmapLevel );
452 void RenderManager::AddPropertyBuffer( OwnerPointer< Render::PropertyBuffer >& propertyBuffer )
454 mImpl->propertyBufferContainer.PushBack( propertyBuffer.Release() );
457 void RenderManager::RemovePropertyBuffer( Render::PropertyBuffer* propertyBuffer )
459 mImpl->propertyBufferContainer.EraseObject( propertyBuffer );
462 void RenderManager::SetPropertyBufferFormat( Render::PropertyBuffer* propertyBuffer, OwnerPointer< Render::PropertyBuffer::Format>& format )
464 propertyBuffer->SetFormat( format.Release() );
467 void RenderManager::SetPropertyBufferData( Render::PropertyBuffer* propertyBuffer, OwnerPointer< Vector<uint8_t> >& data, uint32_t size )
469 propertyBuffer->SetData( data.Release(), size );
472 void RenderManager::SetIndexBuffer( Render::Geometry* geometry, Dali::Vector<uint16_t>& indices )
474 geometry->SetIndexBuffer( indices );
477 void RenderManager::AddGeometry( OwnerPointer< Render::Geometry >& geometry )
479 mImpl->geometryContainer.PushBack( geometry.Release() );
482 void RenderManager::RemoveGeometry( Render::Geometry* geometry )
484 mImpl->geometryContainer.EraseObject( geometry );
487 void RenderManager::AttachVertexBuffer( Render::Geometry* geometry, Render::PropertyBuffer* propertyBuffer )
489 DALI_ASSERT_DEBUG( NULL != geometry );
492 for ( auto&& iter : mImpl->geometryContainer )
494 if ( iter == geometry )
496 iter->AddPropertyBuffer( propertyBuffer );
502 void RenderManager::RemoveVertexBuffer( Render::Geometry* geometry, Render::PropertyBuffer* propertyBuffer )
504 DALI_ASSERT_DEBUG( NULL != geometry );
507 for ( auto&& iter : mImpl->geometryContainer )
509 if ( iter == geometry )
511 iter->RemovePropertyBuffer( propertyBuffer );
517 void RenderManager::SetGeometryType( Render::Geometry* geometry, uint32_t geometryType )
519 geometry->SetType( Render::Geometry::Type(geometryType) );
522 void RenderManager::AddRenderTracker( Render::RenderTracker* renderTracker )
524 mImpl->AddRenderTracker(renderTracker);
527 void RenderManager::RemoveRenderTracker( Render::RenderTracker* renderTracker )
529 mImpl->RemoveRenderTracker(renderTracker);
532 ProgramCache* RenderManager::GetProgramCache()
534 return &(mImpl->programController);
537 void RenderManager::PreRender( Integration::RenderStatus& status, bool forceClear, bool uploadOnly )
539 DALI_PRINT_RENDER_START( mImpl->renderBufferIndex );
541 // Core::Render documents that GL context must be current before calling Render
542 DALI_ASSERT_DEBUG( mImpl->context.IsGlContextCreated() );
544 // Increment the frame count at the beginning of each frame
547 // Process messages queued during previous update
548 mImpl->renderQueue.ProcessMessages( mImpl->renderBufferIndex );
551 for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
553 count += mImpl->sceneContainer[i]->GetRenderInstructions().Count( mImpl->renderBufferIndex );
556 const bool haveInstructions = count > 0u;
558 DALI_LOG_INFO( gLogFilter, Debug::General,
559 "Render: haveInstructions(%s) || mImpl->lastFrameWasRendered(%s) || forceClear(%s)\n",
560 haveInstructions ? "true" : "false",
561 mImpl->lastFrameWasRendered ? "true" : "false",
562 forceClear ? "true" : "false" );
564 // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
565 if( haveInstructions || mImpl->lastFrameWasRendered || forceClear )
567 DALI_LOG_INFO( gLogFilter, Debug::General, "Render: Processing\n" );
569 // Switch to the shared context
570 if ( mImpl->currentContext != &mImpl->context )
572 mImpl->currentContext = &mImpl->context;
574 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
576 mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
579 // Clear the current cached program when the context is switched
580 mImpl->programController.ClearCurrentProgram();
583 // Upload the geometries
584 for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
586 RenderInstructionContainer& instructions = mImpl->sceneContainer[i]->GetRenderInstructions();
587 for ( uint32_t j = 0; j < instructions.Count( mImpl->renderBufferIndex ); ++j )
589 RenderInstruction& instruction = instructions.At( mImpl->renderBufferIndex, j );
591 const Matrix* viewMatrix = instruction.GetViewMatrix( mImpl->renderBufferIndex );
592 const Matrix* projectionMatrix = instruction.GetProjectionMatrix( mImpl->renderBufferIndex );
594 DALI_ASSERT_DEBUG( viewMatrix );
595 DALI_ASSERT_DEBUG( projectionMatrix );
597 if( viewMatrix && projectionMatrix )
599 const RenderListContainer::SizeType renderListCount = instruction.RenderListCount();
601 // Iterate through each render list.
602 for( RenderListContainer::SizeType index = 0; index < renderListCount; ++index )
604 const RenderList* renderList = instruction.GetRenderList( index );
606 if( renderList && !renderList->IsEmpty() )
608 const std::size_t itemCount = renderList->Count();
609 for( uint32_t itemIndex = 0u; itemIndex < itemCount; ++itemIndex )
611 const RenderItem& item = renderList->GetItem( itemIndex );
612 if( DALI_LIKELY( item.mRenderer ) )
614 item.mRenderer->Upload( *mImpl->currentContext );
625 void RenderManager::PreRender( Integration::Scene& scene, std::vector<Rect<int>>& damagedRects )
627 if (mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
632 // @TODO We need to do partial rendering rotation.
633 if( mImpl->defaultSurfaceOrientation != 0 )
638 class DamagedRectsCleaner
641 DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects)
642 : mDamagedRects(damagedRects),
647 void SetCleanOnReturn(bool cleanOnReturn)
649 mCleanOnReturn = cleanOnReturn;
652 ~DamagedRectsCleaner()
656 mDamagedRects.clear();
661 std::vector<Rect<int>>& mDamagedRects;
665 Rect<int32_t> surfaceRect = Rect<int32_t>(0, 0, static_cast<int32_t>( scene.GetSize().width ), static_cast<int32_t>( scene.GetSize().height ));
667 // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
668 DamagedRectsCleaner damagedRectCleaner(damagedRects);
670 // Mark previous dirty rects in the sorted array. The array is already sorted by node and renderer, frame number.
671 // so you don't need to sort: std::stable_sort(mImpl->itemsDirtyRects.begin(), mImpl->itemsDirtyRects.end());
672 for (DirtyRect& dirtyRect : mImpl->itemsDirtyRects)
674 dirtyRect.visited = false;
677 Internal::Scene& sceneInternal = GetImplementation(scene);
678 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
679 uint32_t count = sceneObject->GetRenderInstructions().Count( mImpl->renderBufferIndex );
680 for (uint32_t i = 0; i < count; ++i)
682 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At( mImpl->renderBufferIndex, i );
684 if (instruction.mFrameBuffer)
686 return; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
689 const Camera* camera = instruction.GetCamera();
690 if (camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
692 const Node* node = instruction.GetCamera()->GetNode();
697 Quaternion orientation;
698 node->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
700 Vector3 orientationAxis;
701 Radian orientationAngle;
702 orientation.ToAxisAngle( orientationAxis, orientationAngle );
704 if (position.x > Math::MACHINE_EPSILON_10000 ||
705 position.y > Math::MACHINE_EPSILON_10000 ||
706 orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
707 orientationAngle != ANGLE_180 ||
708 scale != Vector3(1.0f, 1.0f, 1.0f))
719 Rect<int32_t> viewportRect;
720 if (instruction.mIsViewportSet)
722 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
723 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
724 if (viewportRect.IsEmpty() || !viewportRect.IsValid())
726 return; // just skip funny use cases for now, empty viewport means it is set somewhere else
731 viewportRect = surfaceRect;
734 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
735 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
736 if (viewMatrix && projectionMatrix)
738 const RenderListContainer::SizeType count = instruction.RenderListCount();
739 for (RenderListContainer::SizeType index = 0u; index < count; ++index)
741 const RenderList* renderList = instruction.GetRenderList( index );
742 if (renderList && !renderList->IsEmpty())
744 const std::size_t count = renderList->Count();
745 for (uint32_t index = 0u; index < count; ++index)
747 RenderItem& item = renderList->GetItem( index );
748 // If the item does 3D transformation, do early exit and clean the damaged rect array
749 if (item.mUpdateSize == Vector3::ZERO)
755 DirtyRect dirtyRect(item.mNode, item.mRenderer, mImpl->frameCount, rect);
756 // If the item refers to updated node or renderer.
757 if (item.mIsUpdated ||
759 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex, item.mNode)))))
761 item.mIsUpdated = false;
762 item.mNode->SetUpdated(false);
764 rect = item.CalculateViewportSpaceAABB(item.mUpdateSize, viewportRect.width, viewportRect.height);
765 if (rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
767 const int left = rect.x;
768 const int top = rect.y;
769 const int right = rect.x + rect.width;
770 const int bottom = rect.y + rect.height;
771 rect.x = (left / 16) * 16;
772 rect.y = (top / 16) * 16;
773 rect.width = ((right + 16) / 16) * 16 - rect.x;
774 rect.height = ((bottom + 16) / 16) * 16 - rect.y;
776 // Found valid dirty rect.
777 // 1. Insert it in the sorted array of the dirty rects.
778 // 2. Mark the related dirty rects as visited so they will not be removed below.
779 // 3. Keep only last 3 dirty rects for the same node and renderer (Tizen uses 3 back buffers, Ubuntu 1).
780 dirtyRect.rect = rect;
781 auto dirtyRectPos = std::lower_bound(mImpl->itemsDirtyRects.begin(), mImpl->itemsDirtyRects.end(), dirtyRect);
782 dirtyRectPos = mImpl->itemsDirtyRects.insert(dirtyRectPos, dirtyRect);
785 while (++dirtyRectPos != mImpl->itemsDirtyRects.end())
787 if (dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
792 dirtyRectPos->visited = true;
793 Rect<int>& dirtRect = dirtyRectPos->rect;
794 rect.Merge(dirtRect);
797 if (c > 3) // no more then 3 previous rects
799 mImpl->itemsDirtyRects.erase(dirtyRectPos);
804 damagedRects.push_back(rect);
809 // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
810 // 2. Mark the related dirty rects as visited so they will not be removed below.
811 auto dirtyRectPos = std::lower_bound(mImpl->itemsDirtyRects.begin(), mImpl->itemsDirtyRects.end(), dirtyRect);
812 while (dirtyRectPos != mImpl->itemsDirtyRects.end())
814 if (dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
819 dirtyRectPos->visited = true;
829 // Check removed nodes or removed renderers dirty rects
830 auto i = mImpl->itemsDirtyRects.begin();
831 auto j = mImpl->itemsDirtyRects.begin();
832 while (i != mImpl->itemsDirtyRects.end())
840 Rect<int>& dirtRect = i->rect;
841 damagedRects.push_back(dirtRect);
846 if( j != mImpl->itemsDirtyRects.begin() )
848 mImpl->itemsDirtyRects.resize(j - mImpl->itemsDirtyRects.begin());
850 damagedRectCleaner.SetCleanOnReturn(false);
853 void RenderManager::RenderScene( Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo )
855 Rect<int> clippingRect;
856 RenderScene( status, scene, renderToFbo, clippingRect);
859 void RenderManager::RenderScene( Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect )
861 Internal::Scene& sceneInternal = GetImplementation( scene );
862 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
864 uint32_t count = sceneObject->GetRenderInstructions().Count( mImpl->renderBufferIndex );
866 for( uint32_t i = 0; i < count; ++i )
868 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At( mImpl->renderBufferIndex, i );
870 if ( ( renderToFbo && !instruction.mFrameBuffer ) || ( !renderToFbo && instruction.mFrameBuffer ) )
875 // Mark that we will require a post-render step to be performed (includes swap-buffers).
876 status.SetNeedsPostRender( true );
878 Rect<int32_t> viewportRect;
881 if ( instruction.mIsClearColorSet )
883 clearColor = instruction.mClearColor;
887 clearColor = Dali::RenderTask::DEFAULT_CLEAR_COLOR;
890 Rect<int32_t> surfaceRect = mImpl->defaultSurfaceRect;
891 Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
892 Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
893 int surfaceOrientation = mImpl->defaultSurfaceOrientation;
895 if ( instruction.mFrameBuffer )
898 if ( mImpl->currentContext != &mImpl->context )
900 // Switch to shared context for off-screen buffer
901 mImpl->currentContext = &mImpl->context;
903 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
905 mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
908 // Clear the current cached program when the context is switched
909 mImpl->programController.ClearCurrentProgram();
914 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
916 if ( mImpl->currentContext != sceneObject->GetContext() )
918 // Switch the correct context if rendering to a surface
919 mImpl->currentContext = sceneObject->GetContext();
921 // Clear the current cached program when the context is switched
922 mImpl->programController.ClearCurrentProgram();
926 surfaceRect = Rect<int32_t>( 0, 0, static_cast<int32_t>( scene.GetSize().width ), static_cast<int32_t>( scene.GetSize().height ) );
929 DALI_ASSERT_DEBUG( mImpl->currentContext->IsGlContextCreated() );
931 // reset the program matrices for all programs once per frame
932 // this ensures we will set view and projection matrix once per program per camera
933 mImpl->programController.ResetProgramMatrices();
935 if( instruction.mFrameBuffer )
937 instruction.mFrameBuffer->Bind( *mImpl->currentContext );
939 // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
940 for (unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
942 mImpl->textureDependencyList.PushBack( instruction.mFrameBuffer->GetTextureId(i0) );
947 mImpl->currentContext->BindFramebuffer( GL_FRAMEBUFFER, 0u );
950 if ( !instruction.mFrameBuffer )
952 mImpl->currentContext->Viewport( surfaceRect.x,
955 surfaceRect.height );
958 // Clear the entire color, depth and stencil buffers for the default framebuffer, if required.
959 // It is important to clear all 3 buffers when they are being used, for performance on deferred renderers
960 // e.g. previously when the depth & stencil buffers were NOT cleared, it caused the DDK to exceed a "vertex count limit",
961 // and then stall. That problem is only noticeable when rendering a large number of vertices per frame.
962 GLbitfield clearMask = GL_COLOR_BUFFER_BIT;
964 mImpl->currentContext->ColorMask( true );
966 if( depthBufferAvailable == Integration::DepthBufferAvailable::TRUE )
968 mImpl->currentContext->DepthMask( true );
969 clearMask |= GL_DEPTH_BUFFER_BIT;
972 if( stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE)
974 mImpl->currentContext->ClearStencil( 0 );
975 mImpl->currentContext->StencilMask( 0xFF ); // 8 bit stencil mask, all 1's
976 clearMask |= GL_STENCIL_BUFFER_BIT;
979 if( !instruction.mIgnoreRenderToFbo && ( instruction.mFrameBuffer != 0 ) )
981 // Offscreen buffer rendering
982 if ( instruction.mIsViewportSet )
984 // For glViewport the lower-left corner is (0,0)
985 const int32_t y = ( instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height ) - instruction.mViewport.y;
986 viewportRect.Set( instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height );
990 viewportRect.Set( 0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight() );
992 surfaceOrientation = 0;
994 else // No Offscreen frame buffer rendering
996 // Check whether a viewport is specified, otherwise the full surface size is used
997 if ( instruction.mIsViewportSet )
999 // For glViewport the lower-left corner is (0,0)
1000 const int32_t y = ( surfaceRect.height - instruction.mViewport.height ) - instruction.mViewport.y;
1001 viewportRect.Set( instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height );
1005 viewportRect = surfaceRect;
1009 if( surfaceOrientation == 90 || surfaceOrientation == 270 )
1011 int temp = viewportRect.width;
1012 viewportRect.width = viewportRect.height;
1013 viewportRect.height = temp;
1016 bool clearFullFrameRect = true;
1017 if( instruction.mFrameBuffer != 0 )
1019 Viewport frameRect( 0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight() );
1020 clearFullFrameRect = ( frameRect == viewportRect );
1024 clearFullFrameRect = ( surfaceRect == viewportRect );
1027 if (!clippingRect.IsEmpty())
1029 if (!clippingRect.Intersect(viewportRect))
1031 DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
1032 clippingRect = Rect<int>();
1034 clearFullFrameRect = false;
1037 mImpl->currentContext->Viewport(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
1039 if (instruction.mIsClearColorSet)
1041 mImpl->currentContext->ClearColor(clearColor.r,
1045 if (!clearFullFrameRect)
1047 if (!clippingRect.IsEmpty())
1049 mImpl->currentContext->SetScissorTest(true);
1050 mImpl->currentContext->Scissor(clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
1051 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
1052 mImpl->currentContext->SetScissorTest(false);
1056 mImpl->currentContext->SetScissorTest(true);
1057 mImpl->currentContext->Scissor(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
1058 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
1059 mImpl->currentContext->SetScissorTest(false);
1064 mImpl->currentContext->SetScissorTest(false);
1065 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
1069 // Clear the list of bound textures
1070 mImpl->boundTextures.Clear();
1072 mImpl->renderAlgorithms.ProcessRenderInstruction(
1074 *mImpl->currentContext,
1075 mImpl->renderBufferIndex,
1076 depthBufferAvailable,
1077 stencilBufferAvailable,
1078 mImpl->boundTextures,
1080 surfaceOrientation );
1082 // Synchronise the FBO/Texture access when there are multiple contexts
1083 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
1085 // Check whether any binded texture is in the dependency list
1086 bool textureFound = false;
1088 if ( mImpl->boundTextures.Count() > 0u && mImpl->textureDependencyList.Count() > 0u )
1090 for ( auto textureId : mImpl->textureDependencyList )
1093 textureFound = std::find_if( mImpl->boundTextures.Begin(), mImpl->boundTextures.End(),
1094 [textureId]( GLuint id )
1096 return textureId == id;
1097 } ) != mImpl->boundTextures.End();
1103 if ( instruction.mFrameBuffer )
1105 // For off-screen buffer
1107 // Wait until all rendering calls for the currently context are executed
1108 mImpl->glContextHelperAbstraction.WaitClient();
1110 // Clear the dependency list
1111 mImpl->textureDependencyList.Clear();
1115 // Worker thread lambda function
1116 auto& glContextHelperAbstraction = mImpl->glContextHelperAbstraction;
1117 auto workerFunction = [&glContextHelperAbstraction]( int workerThread )
1119 // Switch to the shared context in the worker thread
1120 glContextHelperAbstraction.MakeSurfacelessContextCurrent();
1122 // Wait until all rendering calls for the shared context are executed
1123 glContextHelperAbstraction.WaitClient();
1125 // Must clear the context in the worker thread
1126 // Otherwise the shared context cannot be switched to from the render thread
1127 glContextHelperAbstraction.MakeContextNull();
1130 auto future = mImpl->threadPool->SubmitTask( 0u, workerFunction );
1133 mImpl->threadPool->Wait();
1135 // Clear the dependency list
1136 mImpl->textureDependencyList.Clear();
1142 if( instruction.mRenderTracker && instruction.mFrameBuffer )
1144 // This will create a sync object every frame this render tracker
1145 // is alive (though it should be now be created only for
1146 // render-once render tasks)
1147 instruction.mRenderTracker->CreateSyncObject( mImpl->glSyncAbstraction );
1148 instruction.mRenderTracker = nullptr; // Only create once.
1153 mImpl->currentContext->Flush();
1157 GLenum attachments[] = { GL_DEPTH, GL_STENCIL };
1158 mImpl->currentContext->InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
1161 void RenderManager::PostRender( bool uploadOnly )
1165 if ( mImpl->currentContext->IsSurfacelessContextSupported() )
1167 mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
1170 GLenum attachments[] = { GL_DEPTH, GL_STENCIL };
1171 mImpl->context.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
1174 //Notify RenderGeometries that rendering has finished
1175 for ( auto&& iter : mImpl->geometryContainer )
1177 iter->OnRenderFinished();
1180 mImpl->UpdateTrackers();
1183 uint32_t count = 0u;
1184 for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
1186 count += mImpl->sceneContainer[i]->GetRenderInstructions().Count( mImpl->renderBufferIndex );
1189 const bool haveInstructions = count > 0u;
1191 // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
1192 mImpl->lastFrameWasRendered = haveInstructions;
1195 * The rendering has finished; swap to the next buffer.
1196 * Ideally the update has just finished using this buffer; otherwise the render thread
1197 * should block until the update has finished.
1199 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1201 DALI_PRINT_RENDER_END();
1204 } // namespace SceneGraph
1206 } // namespace Internal