2 * Copyright (c) 2021 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>
29 #include <dali/internal/event/common/scene-impl.h>
31 #include <dali/internal/update/common/scene-graph-scene.h>
32 #include <dali/internal/update/render-tasks/scene-graph-camera.h>
34 #include <dali/internal/render/common/render-algorithms.h>
35 #include <dali/internal/render/common/render-debug.h>
36 #include <dali/internal/render/common/render-instruction.h>
37 #include <dali/internal/render/common/render-tracker.h>
38 #include <dali/internal/render/queue/render-queue.h>
39 #include <dali/internal/render/renderers/render-frame-buffer.h>
40 #include <dali/internal/render/renderers/render-texture.h>
41 #include <dali/internal/render/shaders/program-controller.h>
49 #if defined(DEBUG_ENABLED)
52 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_MANAGER");
53 } // unnamed namespace
57 * Structure to contain internal data
59 struct RenderManager::Impl
61 Impl(Graphics::Controller& graphicsController,
62 Integration::DepthBufferAvailable depthBufferAvailableParam,
63 Integration::StencilBufferAvailable stencilBufferAvailableParam,
64 Integration::PartialUpdateAvailable partialUpdateAvailableParam)
65 : context(graphicsController.GetGlAbstraction(), &sceneContextContainer),
66 currentContext(&context),
67 graphicsController(graphicsController),
71 renderBufferIndex(SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX),
75 frameBufferContainer(),
76 lastFrameWasRendered(false),
77 programController(graphicsController),
78 depthBufferAvailable(depthBufferAvailableParam),
79 stencilBufferAvailable(stencilBufferAvailableParam),
80 partialUpdateAvailable(partialUpdateAvailableParam)
82 // Create thread pool with just one thread ( there may be a need to create more threads in the future ).
83 threadPool = std::unique_ptr<Dali::ThreadPool>(new Dali::ThreadPool());
84 threadPool->Initialize(1u);
89 threadPool.reset(nullptr); // reset now to maintain correct destruction order
92 void AddRenderTracker(Render::RenderTracker* renderTracker)
94 DALI_ASSERT_DEBUG(renderTracker != NULL);
95 mRenderTrackers.PushBack(renderTracker);
98 void RemoveRenderTracker(Render::RenderTracker* renderTracker)
100 mRenderTrackers.EraseObject(renderTracker);
103 Context* CreateSceneContext()
105 Context* context = new Context(graphicsController.GetGlAbstraction());
106 sceneContextContainer.PushBack(context);
110 void DestroySceneContext(Context* sceneContext)
112 auto iter = std::find(sceneContextContainer.Begin(), sceneContextContainer.End(), sceneContext);
113 if(iter != sceneContextContainer.End())
115 (*iter)->GlContextDestroyed();
116 sceneContextContainer.Erase(iter);
120 Context* ReplaceSceneContext(Context* oldSceneContext)
122 Context* newContext = new Context(graphicsController.GetGlAbstraction());
124 oldSceneContext->GlContextDestroyed();
126 std::replace(sceneContextContainer.begin(), sceneContextContainer.end(), oldSceneContext, newContext);
130 void UpdateTrackers()
132 for(auto&& iter : mRenderTrackers)
134 iter->PollSyncObject();
138 // the order is important for destruction,
139 // programs are owned by context at the moment.
140 Context context; ///< Holds the GL state of the share resource context
141 Context* currentContext; ///< Holds the GL state of the current context for rendering
142 OwnerContainer<Context*> sceneContextContainer; ///< List of owned contexts holding the GL state per scene
143 Graphics::Controller& graphicsController;
144 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
146 std::vector<SceneGraph::Scene*> sceneContainer; ///< List of pointers to the scene graph objects of the scenes
148 Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
150 uint32_t frameCount; ///< The current frame count
151 BufferIndex renderBufferIndex; ///< The index of the buffer to read from; this is opposite of the "update" buffer
153 OwnerContainer<Render::Renderer*> rendererContainer; ///< List of owned renderers
154 OwnerContainer<Render::Sampler*> samplerContainer; ///< List of owned samplers
155 OwnerContainer<Render::Texture*> textureContainer; ///< List of owned textures
156 OwnerContainer<Render::FrameBuffer*> frameBufferContainer; ///< List of owned framebuffers
157 OwnerContainer<Render::VertexBuffer*> vertexBufferContainer; ///< List of owned vertex buffers
158 OwnerContainer<Render::Geometry*> geometryContainer; ///< List of owned Geometries
160 bool lastFrameWasRendered; ///< Keeps track of the last frame being rendered due to having render instructions
162 OwnerContainer<Render::RenderTracker*> mRenderTrackers; ///< List of render trackers
164 ProgramController programController; ///< Owner of the GL programs
166 Integration::DepthBufferAvailable depthBufferAvailable; ///< Whether the depth buffer is available
167 Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
168 Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
170 std::unique_ptr<Dali::ThreadPool> threadPool; ///< The thread pool
171 Vector<GLuint> boundTextures; ///< The textures bound for rendering
172 Vector<GLuint> textureDependencyList; ///< The dependency list of binded textures
175 RenderManager* RenderManager::New(Graphics::Controller& graphicsController,
176 Integration::DepthBufferAvailable depthBufferAvailable,
177 Integration::StencilBufferAvailable stencilBufferAvailable,
178 Integration::PartialUpdateAvailable partialUpdateAvailable)
180 RenderManager* manager = new RenderManager;
181 manager->mImpl = new Impl(graphicsController,
182 depthBufferAvailable,
183 stencilBufferAvailable,
184 partialUpdateAvailable);
188 RenderManager::RenderManager()
193 RenderManager::~RenderManager()
198 RenderQueue& RenderManager::GetRenderQueue()
200 return mImpl->renderQueue;
203 void RenderManager::ContextCreated()
205 mImpl->context.GlContextCreated();
206 mImpl->programController.GlContextCreated();
208 // renderers, textures and gpu buffers cannot reinitialize themselves
209 // so they rely on someone reloading the data for them
212 void RenderManager::ContextDestroyed()
214 mImpl->context.GlContextDestroyed();
215 mImpl->programController.GlContextDestroyed();
218 for(auto&& texture : mImpl->textureContainer)
220 texture->GlContextDestroyed();
223 //Inform framebuffers
224 for(auto&& framebuffer : mImpl->frameBufferContainer)
226 framebuffer->GlContextDestroyed();
230 for(auto&& renderer : mImpl->rendererContainer)
232 renderer->GlContextDestroyed();
236 for(auto&& context : mImpl->sceneContextContainer)
238 context->GlContextDestroyed();
242 void RenderManager::SetShaderSaver(ShaderSaver& upstream)
244 mImpl->programController.SetShaderSaver(upstream);
247 void RenderManager::AddRenderer(OwnerPointer<Render::Renderer>& renderer)
249 // Initialize the renderer as we are now in render thread
250 renderer->Initialize(mImpl->context, mImpl->programController);
252 mImpl->rendererContainer.PushBack(renderer.Release());
255 void RenderManager::RemoveRenderer(Render::Renderer* renderer)
257 mImpl->rendererContainer.EraseObject(renderer);
260 void RenderManager::AddSampler(OwnerPointer<Render::Sampler>& sampler)
262 mImpl->samplerContainer.PushBack(sampler.Release());
265 void RenderManager::RemoveSampler(Render::Sampler* sampler)
267 mImpl->samplerContainer.EraseObject(sampler);
270 void RenderManager::AddTexture(OwnerPointer<Render::Texture>& texture)
272 texture->Initialize(mImpl->context);
273 mImpl->textureContainer.PushBack(texture.Release());
276 void RenderManager::RemoveTexture(Render::Texture* texture)
278 DALI_ASSERT_DEBUG(NULL != texture);
280 // Find the texture, use reference to pointer so we can do the erase safely
281 for(auto&& iter : mImpl->textureContainer)
285 texture->Destroy(mImpl->context);
286 mImpl->textureContainer.Erase(&iter); // Texture found; now destroy it
292 void RenderManager::UploadTexture(Render::Texture* texture, PixelDataPtr pixelData, const Texture::UploadParams& params)
294 texture->Upload(mImpl->context, pixelData, params);
297 void RenderManager::GenerateMipmaps(Render::Texture* texture)
299 texture->GenerateMipmaps(mImpl->context);
302 void RenderManager::SetFilterMode(Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode)
304 sampler->mMinificationFilter = static_cast<Dali::FilterMode::Type>(minFilterMode);
305 sampler->mMagnificationFilter = static_cast<Dali::FilterMode::Type>(magFilterMode);
308 void RenderManager::SetWrapMode(Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode)
310 sampler->mRWrapMode = static_cast<Dali::WrapMode::Type>(rWrapMode);
311 sampler->mSWrapMode = static_cast<Dali::WrapMode::Type>(sWrapMode);
312 sampler->mTWrapMode = static_cast<Dali::WrapMode::Type>(tWrapMode);
315 void RenderManager::AddFrameBuffer(OwnerPointer<Render::FrameBuffer>& frameBuffer)
317 Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
318 mImpl->frameBufferContainer.PushBack(frameBufferPtr);
319 frameBufferPtr->Initialize(mImpl->context);
322 void RenderManager::RemoveFrameBuffer(Render::FrameBuffer* frameBuffer)
324 DALI_ASSERT_DEBUG(NULL != frameBuffer);
326 // Find the sampler, use reference so we can safely do the erase
327 for(auto&& iter : mImpl->frameBufferContainer)
329 if(iter == frameBuffer)
331 frameBuffer->Destroy(mImpl->context);
332 mImpl->frameBufferContainer.Erase(&iter); // frameBuffer found; now destroy it
339 void RenderManager::InitializeScene(SceneGraph::Scene* scene)
341 scene->Initialize(*mImpl->CreateSceneContext());
342 mImpl->sceneContainer.push_back(scene);
345 void RenderManager::UninitializeScene(SceneGraph::Scene* scene)
347 mImpl->DestroySceneContext(scene->GetContext());
349 auto iter = std::find(mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene);
350 if(iter != mImpl->sceneContainer.end())
352 mImpl->sceneContainer.erase(iter);
356 void RenderManager::SurfaceReplaced(SceneGraph::Scene* scene)
358 Context* newContext = mImpl->ReplaceSceneContext(scene->GetContext());
359 scene->Initialize(*newContext);
362 void RenderManager::AttachColorTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer)
364 frameBuffer->AttachColorTexture(mImpl->context, texture, mipmapLevel, layer);
367 void RenderManager::AttachDepthTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
369 frameBuffer->AttachDepthTexture(mImpl->context, texture, mipmapLevel);
372 void RenderManager::AttachDepthStencilTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
374 frameBuffer->AttachDepthStencilTexture(mImpl->context, texture, mipmapLevel);
377 void RenderManager::AddVertexBuffer(OwnerPointer<Render::VertexBuffer>& vertexBuffer)
379 mImpl->vertexBufferContainer.PushBack(vertexBuffer.Release());
382 void RenderManager::RemoveVertexBuffer(Render::VertexBuffer* vertexBuffer)
384 mImpl->vertexBufferContainer.EraseObject(vertexBuffer);
387 void RenderManager::SetVertexBufferFormat(Render::VertexBuffer* vertexBuffer, OwnerPointer<Render::VertexBuffer::Format>& format)
389 vertexBuffer->SetFormat(format.Release());
392 void RenderManager::SetVertexBufferData(Render::VertexBuffer* vertexBuffer, OwnerPointer<Vector<uint8_t>>& data, uint32_t size)
394 vertexBuffer->SetData(data.Release(), size);
397 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Dali::Vector<uint16_t>& indices)
399 geometry->SetIndexBuffer(indices);
402 void RenderManager::AddGeometry(OwnerPointer<Render::Geometry>& geometry)
404 mImpl->geometryContainer.PushBack(geometry.Release());
407 void RenderManager::RemoveGeometry(Render::Geometry* geometry)
409 mImpl->geometryContainer.EraseObject(geometry);
412 void RenderManager::AttachVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
414 DALI_ASSERT_DEBUG(NULL != geometry);
417 for(auto&& iter : mImpl->geometryContainer)
421 iter->AddVertexBuffer(vertexBuffer);
427 void RenderManager::RemoveVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
429 DALI_ASSERT_DEBUG(NULL != geometry);
432 for(auto&& iter : mImpl->geometryContainer)
436 iter->RemoveVertexBuffer(vertexBuffer);
442 void RenderManager::SetGeometryType(Render::Geometry* geometry, uint32_t geometryType)
444 geometry->SetType(Render::Geometry::Type(geometryType));
447 void RenderManager::AddRenderTracker(Render::RenderTracker* renderTracker)
449 mImpl->AddRenderTracker(renderTracker);
452 void RenderManager::RemoveRenderTracker(Render::RenderTracker* renderTracker)
454 mImpl->RemoveRenderTracker(renderTracker);
457 ProgramCache* RenderManager::GetProgramCache()
459 return &(mImpl->programController);
462 void RenderManager::PreRender(Integration::RenderStatus& status, bool forceClear, bool uploadOnly)
464 DALI_PRINT_RENDER_START(mImpl->renderBufferIndex);
466 // Core::Render documents that GL context must be current before calling Render
467 DALI_ASSERT_DEBUG(mImpl->context.IsGlContextCreated());
469 // Increment the frame count at the beginning of each frame
472 // Process messages queued during previous update
473 mImpl->renderQueue.ProcessMessages(mImpl->renderBufferIndex);
476 for(uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i)
478 count += mImpl->sceneContainer[i]->GetRenderInstructions().Count(mImpl->renderBufferIndex);
481 const bool haveInstructions = count > 0u;
483 DALI_LOG_INFO(gLogFilter, Debug::General, "Render: haveInstructions(%s) || mImpl->lastFrameWasRendered(%s) || forceClear(%s)\n", haveInstructions ? "true" : "false", mImpl->lastFrameWasRendered ? "true" : "false", forceClear ? "true" : "false");
485 // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
486 if(haveInstructions || mImpl->lastFrameWasRendered || forceClear)
488 DALI_LOG_INFO(gLogFilter, Debug::General, "Render: Processing\n");
490 // Switch to the shared context
491 if(mImpl->currentContext != &mImpl->context)
493 mImpl->currentContext = &mImpl->context;
495 if(mImpl->currentContext->IsSurfacelessContextSupported())
497 mImpl->graphicsController.GetGlContextHelperAbstraction().MakeSurfacelessContextCurrent();
500 // Clear the current cached program when the context is switched
501 mImpl->programController.ClearCurrentProgram();
504 // Upload the geometries
505 for(uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i)
507 RenderInstructionContainer& instructions = mImpl->sceneContainer[i]->GetRenderInstructions();
508 for(uint32_t j = 0; j < instructions.Count(mImpl->renderBufferIndex); ++j)
510 RenderInstruction& instruction = instructions.At(mImpl->renderBufferIndex, j);
512 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
513 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
515 DALI_ASSERT_DEBUG(viewMatrix);
516 DALI_ASSERT_DEBUG(projectionMatrix);
518 if(viewMatrix && projectionMatrix)
520 const RenderListContainer::SizeType renderListCount = instruction.RenderListCount();
522 // Iterate through each render list.
523 for(RenderListContainer::SizeType index = 0; index < renderListCount; ++index)
525 const RenderList* renderList = instruction.GetRenderList(index);
527 if(renderList && !renderList->IsEmpty())
529 const std::size_t itemCount = renderList->Count();
530 for(uint32_t itemIndex = 0u; itemIndex < itemCount; ++itemIndex)
532 const RenderItem& item = renderList->GetItem(itemIndex);
533 if(DALI_LIKELY(item.mRenderer))
535 item.mRenderer->Upload(*mImpl->currentContext);
546 void RenderManager::PreRender(Integration::Scene& scene, std::vector<Rect<int>>& damagedRects)
548 if(mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
553 Internal::Scene& sceneInternal = GetImplementation(scene);
554 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
556 if(sceneObject->IsRenderingSkipped())
558 // We don't need to calculate dirty rects
562 class DamagedRectsCleaner
565 DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects)
566 : mDamagedRects(damagedRects),
571 void SetCleanOnReturn(bool cleanOnReturn)
573 mCleanOnReturn = cleanOnReturn;
576 ~DamagedRectsCleaner()
580 mDamagedRects.clear();
585 std::vector<Rect<int>>& mDamagedRects;
589 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
591 // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
592 DamagedRectsCleaner damagedRectCleaner(damagedRects);
594 // Mark previous dirty rects in the sorted array. The array is already sorted by node and renderer, frame number.
595 // so you don't need to sort: std::stable_sort(itemsDirtyRects.begin(), itemsDirtyRects.end());
596 std::vector<DirtyRect>& itemsDirtyRects = sceneInternal.GetItemsDirtyRects();
597 for(DirtyRect& dirtyRect : itemsDirtyRects)
599 dirtyRect.visited = false;
602 uint32_t count = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
603 for(uint32_t i = 0; i < count; ++i)
605 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
607 if(instruction.mFrameBuffer)
609 return; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
612 const Camera* camera = instruction.GetCamera();
613 if(camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
615 const Node* node = instruction.GetCamera()->GetNode();
620 Quaternion orientation;
621 node->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
623 Vector3 orientationAxis;
624 Radian orientationAngle;
625 orientation.ToAxisAngle(orientationAxis, orientationAngle);
627 if(position.x > Math::MACHINE_EPSILON_10000 ||
628 position.y > Math::MACHINE_EPSILON_10000 ||
629 orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
630 orientationAngle != ANGLE_180 ||
631 scale != Vector3(1.0f, 1.0f, 1.0f))
642 Rect<int32_t> viewportRect;
643 if(instruction.mIsViewportSet)
645 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
646 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
647 if(viewportRect.IsEmpty() || !viewportRect.IsValid())
649 return; // just skip funny use cases for now, empty viewport means it is set somewhere else
654 viewportRect = surfaceRect;
657 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
658 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
659 if(viewMatrix && projectionMatrix)
661 const RenderListContainer::SizeType count = instruction.RenderListCount();
662 for(RenderListContainer::SizeType index = 0u; index < count; ++index)
664 const RenderList* renderList = instruction.GetRenderList(index);
665 if(renderList && !renderList->IsEmpty())
667 const std::size_t count = renderList->Count();
668 for(uint32_t index = 0u; index < count; ++index)
670 RenderItem& item = renderList->GetItem(index);
671 // If the item does 3D transformation, do early exit and clean the damaged rect array
672 if(item.mUpdateSize == Vector3::ZERO)
678 DirtyRect dirtyRect(item.mNode, item.mRenderer, mImpl->frameCount, rect);
679 // If the item refers to updated node or renderer.
680 if(item.mIsUpdated ||
682 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex, item.mNode)))))
684 item.mIsUpdated = false;
685 item.mNode->SetUpdated(false);
687 rect = item.CalculateViewportSpaceAABB(item.mUpdateSize, viewportRect.width, viewportRect.height);
688 if(rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
690 const int left = rect.x;
691 const int top = rect.y;
692 const int right = rect.x + rect.width;
693 const int bottom = rect.y + rect.height;
694 rect.x = (left / 16) * 16;
695 rect.y = (top / 16) * 16;
696 rect.width = ((right + 16) / 16) * 16 - rect.x;
697 rect.height = ((bottom + 16) / 16) * 16 - rect.y;
699 // Found valid dirty rect.
700 // 1. Insert it in the sorted array of the dirty rects.
701 // 2. Mark the related dirty rects as visited so they will not be removed below.
702 // 3. Keep only last 3 dirty rects for the same node and renderer (Tizen uses 3 back buffers, Ubuntu 1).
703 dirtyRect.rect = rect;
704 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
705 dirtyRectPos = itemsDirtyRects.insert(dirtyRectPos, dirtyRect);
708 while(++dirtyRectPos != itemsDirtyRects.end())
710 if(dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
715 dirtyRectPos->visited = true;
716 Rect<int>& dirtRect = dirtyRectPos->rect;
717 rect.Merge(dirtRect);
720 if(c > 3) // no more then 3 previous rects
722 itemsDirtyRects.erase(dirtyRectPos);
727 damagedRects.push_back(rect);
732 // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
733 // 2. Mark the related dirty rects as visited so they will not be removed below.
734 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
735 while(dirtyRectPos != itemsDirtyRects.end())
737 if(dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
742 dirtyRectPos->visited = true;
752 // Check removed nodes or removed renderers dirty rects
753 auto i = itemsDirtyRects.begin();
754 auto j = itemsDirtyRects.begin();
755 while(i != itemsDirtyRects.end())
763 Rect<int>& dirtRect = i->rect;
764 damagedRects.push_back(dirtRect);
769 itemsDirtyRects.resize(j - itemsDirtyRects.begin());
770 damagedRectCleaner.SetCleanOnReturn(false);
773 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo)
775 Rect<int> clippingRect;
776 RenderScene(status, scene, renderToFbo, clippingRect);
779 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
781 Internal::Scene& sceneInternal = GetImplementation(scene);
782 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
784 uint32_t count = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
786 for(uint32_t i = 0; i < count; ++i)
788 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
790 if((renderToFbo && !instruction.mFrameBuffer) || (!renderToFbo && instruction.mFrameBuffer))
795 // Mark that we will require a post-render step to be performed (includes swap-buffers).
796 status.SetNeedsPostRender(true);
798 Rect<int32_t> viewportRect;
801 if(instruction.mIsClearColorSet)
803 clearColor = instruction.mClearColor;
807 clearColor = Dali::RenderTask::DEFAULT_CLEAR_COLOR;
810 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
811 int32_t surfaceOrientation = sceneObject->GetSurfaceOrientation();
813 Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
814 Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
816 if(instruction.mFrameBuffer)
819 if(mImpl->currentContext != &mImpl->context)
821 // Switch to shared context for off-screen buffer
822 mImpl->currentContext = &mImpl->context;
824 if(mImpl->currentContext->IsSurfacelessContextSupported())
826 mImpl->graphicsController.GetGlContextHelperAbstraction().MakeSurfacelessContextCurrent();
829 // Clear the current cached program when the context is switched
830 mImpl->programController.ClearCurrentProgram();
835 if(mImpl->currentContext->IsSurfacelessContextSupported())
837 if(mImpl->currentContext != sceneObject->GetContext())
839 // Switch the correct context if rendering to a surface
840 mImpl->currentContext = sceneObject->GetContext();
842 // Clear the current cached program when the context is switched
843 mImpl->programController.ClearCurrentProgram();
848 // Make sure that GL context must be created
849 mImpl->currentContext->GlContextCreated();
851 // reset the program matrices for all programs once per frame
852 // this ensures we will set view and projection matrix once per program per camera
853 mImpl->programController.ResetProgramMatrices();
855 if(instruction.mFrameBuffer)
857 instruction.mFrameBuffer->Bind(*mImpl->currentContext);
859 // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
860 for(unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
862 mImpl->textureDependencyList.PushBack(instruction.mFrameBuffer->GetTextureId(i0));
867 mImpl->currentContext->BindFramebuffer(GL_FRAMEBUFFER, 0u);
870 if(!instruction.mFrameBuffer)
872 mImpl->currentContext->Viewport(surfaceRect.x,
878 // Clear the entire color, depth and stencil buffers for the default framebuffer, if required.
879 // It is important to clear all 3 buffers when they are being used, for performance on deferred renderers
880 // e.g. previously when the depth & stencil buffers were NOT cleared, it caused the DDK to exceed a "vertex count limit",
881 // and then stall. That problem is only noticeable when rendering a large number of vertices per frame.
882 GLbitfield clearMask = GL_COLOR_BUFFER_BIT;
884 mImpl->currentContext->ColorMask(true);
886 if(depthBufferAvailable == Integration::DepthBufferAvailable::TRUE)
888 mImpl->currentContext->DepthMask(true);
889 clearMask |= GL_DEPTH_BUFFER_BIT;
892 if(stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE)
894 mImpl->currentContext->ClearStencil(0);
895 mImpl->currentContext->StencilMask(0xFF); // 8 bit stencil mask, all 1's
896 clearMask |= GL_STENCIL_BUFFER_BIT;
899 if(!instruction.mIgnoreRenderToFbo && (instruction.mFrameBuffer != nullptr))
901 // Offscreen buffer rendering
902 if(instruction.mIsViewportSet)
904 // For glViewport the lower-left corner is (0,0)
905 const int32_t y = (instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height) - instruction.mViewport.y;
906 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
910 viewportRect.Set(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
912 surfaceOrientation = 0;
914 else // No Offscreen frame buffer rendering
916 // Check whether a viewport is specified, otherwise the full surface size is used
917 if(instruction.mIsViewportSet)
919 // For glViewport the lower-left corner is (0,0)
920 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
921 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
925 viewportRect = surfaceRect;
929 // Set surface orientation
930 mImpl->currentContext->SetSurfaceOrientation(surfaceOrientation);
932 bool clearFullFrameRect = true;
933 if(instruction.mFrameBuffer != nullptr)
935 Viewport frameRect(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
936 clearFullFrameRect = (frameRect == viewportRect);
940 clearFullFrameRect = (surfaceRect == viewportRect);
943 if(!clippingRect.IsEmpty())
945 if(!clippingRect.Intersect(viewportRect))
947 DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
948 clippingRect = Rect<int>();
950 clearFullFrameRect = false;
953 mImpl->currentContext->Viewport(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
955 if(instruction.mIsClearColorSet)
957 mImpl->currentContext->ClearColor(clearColor.r,
961 if(!clearFullFrameRect)
963 if(!clippingRect.IsEmpty())
965 mImpl->currentContext->SetScissorTest(true);
966 mImpl->currentContext->Scissor(clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
967 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
968 mImpl->currentContext->SetScissorTest(false);
972 mImpl->currentContext->SetScissorTest(true);
973 mImpl->currentContext->Scissor(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
974 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
975 mImpl->currentContext->SetScissorTest(false);
980 mImpl->currentContext->SetScissorTest(false);
981 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
985 // Clear the list of bound textures
986 mImpl->boundTextures.Clear();
988 mImpl->renderAlgorithms.ProcessRenderInstruction(
990 *mImpl->currentContext,
991 mImpl->renderBufferIndex,
992 depthBufferAvailable,
993 stencilBufferAvailable,
994 mImpl->boundTextures,
997 // Synchronise the FBO/Texture access when there are multiple contexts
998 if(mImpl->currentContext->IsSurfacelessContextSupported())
1000 // Check whether any binded texture is in the dependency list
1001 bool textureFound = false;
1003 if(mImpl->boundTextures.Count() > 0u && mImpl->textureDependencyList.Count() > 0u)
1005 for(auto textureId : mImpl->textureDependencyList)
1007 textureFound = std::find_if(mImpl->boundTextures.Begin(), mImpl->boundTextures.End(), [textureId](GLuint id) {
1008 return textureId == id;
1009 }) != mImpl->boundTextures.End();
1015 if(instruction.mFrameBuffer)
1017 // For off-screen buffer
1019 // Wait until all rendering calls for the currently context are executed
1020 mImpl->graphicsController.GetGlContextHelperAbstraction().WaitClient();
1022 // Clear the dependency list
1023 mImpl->textureDependencyList.Clear();
1027 // Worker thread lambda function
1028 auto& glContextHelperAbstraction = mImpl->graphicsController.GetGlContextHelperAbstraction();
1029 auto workerFunction = [&glContextHelperAbstraction](int workerThread) {
1030 // Switch to the shared context in the worker thread
1031 glContextHelperAbstraction.MakeSurfacelessContextCurrent();
1033 // Wait until all rendering calls for the shared context are executed
1034 glContextHelperAbstraction.WaitClient();
1036 // Must clear the context in the worker thread
1037 // Otherwise the shared context cannot be switched to from the render thread
1038 glContextHelperAbstraction.MakeContextNull();
1041 auto future = mImpl->threadPool->SubmitTask(0u, workerFunction);
1044 mImpl->threadPool->Wait();
1046 // Clear the dependency list
1047 mImpl->textureDependencyList.Clear();
1053 if(instruction.mRenderTracker && instruction.mFrameBuffer)
1055 // This will create a sync object every frame this render tracker
1056 // is alive (though it should be now be created only for
1057 // render-once render tasks)
1058 instruction.mRenderTracker->CreateSyncObject(mImpl->graphicsController.GetGlSyncAbstraction());
1059 instruction.mRenderTracker = nullptr; // Only create once.
1064 mImpl->currentContext->Flush();
1068 GLenum attachments[] = {GL_DEPTH, GL_STENCIL};
1069 mImpl->currentContext->InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
1072 void RenderManager::PostRender(bool uploadOnly)
1076 if(mImpl->currentContext->IsSurfacelessContextSupported())
1078 mImpl->graphicsController.GetGlContextHelperAbstraction().MakeSurfacelessContextCurrent();
1081 GLenum attachments[] = {GL_DEPTH, GL_STENCIL};
1082 mImpl->context.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
1085 //Notify RenderGeometries that rendering has finished
1086 for(auto&& iter : mImpl->geometryContainer)
1088 iter->OnRenderFinished();
1091 mImpl->UpdateTrackers();
1093 uint32_t count = 0u;
1094 for(uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i)
1096 count += mImpl->sceneContainer[i]->GetRenderInstructions().Count(mImpl->renderBufferIndex);
1099 const bool haveInstructions = count > 0u;
1101 // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
1102 mImpl->lastFrameWasRendered = haveInstructions;
1105 * The rendering has finished; swap to the next buffer.
1106 * Ideally the update has just finished using this buffer; otherwise the render thread
1107 * should block until the update has finished.
1109 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1111 DALI_PRINT_RENDER_END();
1114 } // namespace SceneGraph
1116 } // namespace Internal