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>
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>
41 #if defined(DEBUG_ENABLED)
44 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_MANAGER");
45 } // unnamed namespace
49 * Structure to contain internal data
51 struct RenderManager::Impl
53 Impl(Graphics::Controller& graphicsController,
54 Integration::DepthBufferAvailable depthBufferAvailableParam,
55 Integration::StencilBufferAvailable stencilBufferAvailableParam,
56 Integration::PartialUpdateAvailable partialUpdateAvailableParam)
57 : context(graphicsController.GetGlAbstraction(), &sceneContextContainer),
58 currentContext(&context),
59 graphicsController(graphicsController),
63 renderBufferIndex(SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX),
68 frameBufferContainer(),
69 lastFrameWasRendered(false),
70 programController(graphicsController),
71 depthBufferAvailable(depthBufferAvailableParam),
72 stencilBufferAvailable(stencilBufferAvailableParam),
73 partialUpdateAvailable(partialUpdateAvailableParam),
74 defaultSurfaceOrientation(0)
76 // Create thread pool with just one thread ( there may be a need to create more threads in the future ).
77 threadPool = std::unique_ptr<Dali::ThreadPool>(new Dali::ThreadPool());
78 threadPool->Initialize(1u);
83 threadPool.reset(nullptr); // reset now to maintain correct destruction order
86 void AddRenderTracker(Render::RenderTracker* renderTracker)
88 DALI_ASSERT_DEBUG(renderTracker != NULL);
89 mRenderTrackers.PushBack(renderTracker);
92 void RemoveRenderTracker(Render::RenderTracker* renderTracker)
94 mRenderTrackers.EraseObject(renderTracker);
97 Context* CreateSceneContext()
99 Context* context = new Context(graphicsController.GetGlAbstraction());
100 sceneContextContainer.PushBack(context);
104 void DestroySceneContext(Context* sceneContext)
106 auto iter = std::find(sceneContextContainer.Begin(), sceneContextContainer.End(), sceneContext);
107 if(iter != sceneContextContainer.End())
109 (*iter)->GlContextDestroyed();
110 sceneContextContainer.Erase(iter);
114 Context* ReplaceSceneContext(Context* oldSceneContext)
116 Context* newContext = new Context(graphicsController.GetGlAbstraction());
118 oldSceneContext->GlContextDestroyed();
120 std::replace(sceneContextContainer.begin(), sceneContextContainer.end(), oldSceneContext, newContext);
124 void UpdateTrackers()
126 for(auto&& iter : mRenderTrackers)
128 iter->PollSyncObject();
132 // the order is important for destruction,
133 // programs are owned by context at the moment.
134 Context context; ///< Holds the GL state of the share resource context
135 Context* currentContext; ///< Holds the GL state of the current context for rendering
136 OwnerContainer<Context*> sceneContextContainer; ///< List of owned contexts holding the GL state per scene
137 Graphics::Controller& graphicsController;
138 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
140 std::vector<SceneGraph::Scene*> sceneContainer; ///< List of pointers to the scene graph objects of the scenes
142 Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
144 uint32_t frameCount; ///< The current frame count
145 BufferIndex renderBufferIndex; ///< The index of the buffer to read from; this is opposite of the "update" buffer
147 Rect<int32_t> defaultSurfaceRect; ///< Rectangle for the default surface we are rendering to
149 OwnerContainer<Render::Renderer*> rendererContainer; ///< List of owned renderers
150 OwnerContainer<Render::Sampler*> samplerContainer; ///< List of owned samplers
151 OwnerContainer<Render::Texture*> textureContainer; ///< List of owned textures
152 OwnerContainer<Render::FrameBuffer*> frameBufferContainer; ///< List of owned framebuffers
153 OwnerContainer<Render::VertexBuffer*> vertexBufferContainer; ///< List of owned vertex buffers
154 OwnerContainer<Render::Geometry*> geometryContainer; ///< List of owned Geometries
156 bool lastFrameWasRendered; ///< Keeps track of the last frame being rendered due to having render instructions
158 OwnerContainer<Render::RenderTracker*> mRenderTrackers; ///< List of render trackers
160 ProgramController programController; ///< Owner of the GL programs
162 Integration::DepthBufferAvailable depthBufferAvailable; ///< Whether the depth buffer is available
163 Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
164 Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
166 std::unique_ptr<Dali::ThreadPool> threadPool; ///< The thread pool
167 Vector<GLuint> boundTextures; ///< The textures bound for rendering
168 Vector<GLuint> textureDependencyList; ///< The dependency list of binded textures
170 int defaultSurfaceOrientation; ///< defaultSurfaceOrientation for the default surface we are rendering to
173 RenderManager* RenderManager::New(Graphics::Controller& graphicsController,
174 Integration::DepthBufferAvailable depthBufferAvailable,
175 Integration::StencilBufferAvailable stencilBufferAvailable,
176 Integration::PartialUpdateAvailable partialUpdateAvailable)
178 RenderManager* manager = new RenderManager;
179 manager->mImpl = new Impl(graphicsController,
180 depthBufferAvailable,
181 stencilBufferAvailable,
182 partialUpdateAvailable);
186 RenderManager::RenderManager()
191 RenderManager::~RenderManager()
196 RenderQueue& RenderManager::GetRenderQueue()
198 return mImpl->renderQueue;
201 void RenderManager::ContextCreated()
203 mImpl->context.GlContextCreated();
204 mImpl->programController.GlContextCreated();
206 // renderers, textures and gpu buffers cannot reinitialize themselves
207 // so they rely on someone reloading the data for them
210 void RenderManager::ContextDestroyed()
212 mImpl->context.GlContextDestroyed();
213 mImpl->programController.GlContextDestroyed();
216 for(auto&& texture : mImpl->textureContainer)
218 texture->GlContextDestroyed();
221 //Inform framebuffers
222 for(auto&& framebuffer : mImpl->frameBufferContainer)
224 framebuffer->GlContextDestroyed();
228 for(auto&& renderer : mImpl->rendererContainer)
230 renderer->GlContextDestroyed();
234 for(auto&& context : mImpl->sceneContextContainer)
236 context->GlContextDestroyed();
240 void RenderManager::SetShaderSaver(ShaderSaver& upstream)
242 mImpl->programController.SetShaderSaver(upstream);
245 void RenderManager::SetDefaultSurfaceRect(const Rect<int32_t>& rect)
247 mImpl->defaultSurfaceRect = rect;
250 void RenderManager::SetDefaultSurfaceOrientation(int orientation)
252 mImpl->defaultSurfaceOrientation = orientation;
255 void RenderManager::AddRenderer(OwnerPointer<Render::Renderer>& renderer)
257 // Initialize the renderer as we are now in render thread
258 renderer->Initialize(mImpl->context);
260 mImpl->rendererContainer.PushBack(renderer.Release());
263 void RenderManager::RemoveRenderer(Render::Renderer* renderer)
265 mImpl->rendererContainer.EraseObject(renderer);
268 void RenderManager::AddSampler(OwnerPointer<Render::Sampler>& sampler)
270 mImpl->samplerContainer.PushBack(sampler.Release());
273 void RenderManager::RemoveSampler(Render::Sampler* sampler)
275 mImpl->samplerContainer.EraseObject(sampler);
278 void RenderManager::AddTexture(OwnerPointer<Render::Texture>& texture)
280 texture->Initialize(mImpl->context);
281 mImpl->textureContainer.PushBack(texture.Release());
284 void RenderManager::RemoveTexture(Render::Texture* texture)
286 DALI_ASSERT_DEBUG(NULL != texture);
288 // Find the texture, use reference to pointer so we can do the erase safely
289 for(auto&& iter : mImpl->textureContainer)
293 texture->Destroy(mImpl->context);
294 mImpl->textureContainer.Erase(&iter); // Texture found; now destroy it
300 void RenderManager::UploadTexture(Render::Texture* texture, PixelDataPtr pixelData, const Texture::UploadParams& params)
302 texture->Upload(mImpl->context, pixelData, params);
305 void RenderManager::GenerateMipmaps(Render::Texture* texture)
307 texture->GenerateMipmaps(mImpl->context);
310 void RenderManager::SetFilterMode(Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode)
312 sampler->mMinificationFilter = static_cast<Dali::FilterMode::Type>(minFilterMode);
313 sampler->mMagnificationFilter = static_cast<Dali::FilterMode::Type>(magFilterMode);
316 void RenderManager::SetWrapMode(Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode)
318 sampler->mRWrapMode = static_cast<Dali::WrapMode::Type>(rWrapMode);
319 sampler->mSWrapMode = static_cast<Dali::WrapMode::Type>(sWrapMode);
320 sampler->mTWrapMode = static_cast<Dali::WrapMode::Type>(tWrapMode);
323 void RenderManager::AddFrameBuffer(OwnerPointer<Render::FrameBuffer>& frameBuffer)
325 Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
326 mImpl->frameBufferContainer.PushBack(frameBufferPtr);
327 frameBufferPtr->Initialize(mImpl->context);
330 void RenderManager::RemoveFrameBuffer(Render::FrameBuffer* frameBuffer)
332 DALI_ASSERT_DEBUG(NULL != frameBuffer);
334 // Find the sampler, use reference so we can safely do the erase
335 for(auto&& iter : mImpl->frameBufferContainer)
337 if(iter == frameBuffer)
339 frameBuffer->Destroy(mImpl->context);
340 mImpl->frameBufferContainer.Erase(&iter); // frameBuffer found; now destroy it
346 void RenderManager::InitializeScene(SceneGraph::Scene* scene)
348 scene->Initialize(*mImpl->CreateSceneContext());
349 mImpl->sceneContainer.push_back(scene);
352 void RenderManager::UninitializeScene(SceneGraph::Scene* scene)
354 mImpl->DestroySceneContext(scene->GetContext());
356 auto iter = std::find(mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene);
357 if(iter != mImpl->sceneContainer.end())
359 mImpl->sceneContainer.erase(iter);
363 void RenderManager::SurfaceReplaced(SceneGraph::Scene* scene)
365 Context* newContext = mImpl->ReplaceSceneContext(scene->GetContext());
366 scene->Initialize(*newContext);
369 void RenderManager::AttachColorTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer)
371 frameBuffer->AttachColorTexture(mImpl->context, texture, mipmapLevel, layer);
374 void RenderManager::AttachDepthTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
376 frameBuffer->AttachDepthTexture(mImpl->context, texture, mipmapLevel);
379 void RenderManager::AttachDepthStencilTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
381 frameBuffer->AttachDepthStencilTexture(mImpl->context, texture, mipmapLevel);
384 void RenderManager::AddVertexBuffer(OwnerPointer<Render::VertexBuffer>& vertexBuffer)
386 mImpl->vertexBufferContainer.PushBack(vertexBuffer.Release());
389 void RenderManager::RemoveVertexBuffer(Render::VertexBuffer* vertexBuffer)
391 mImpl->vertexBufferContainer.EraseObject(vertexBuffer);
394 void RenderManager::SetVertexBufferFormat(Render::VertexBuffer* vertexBuffer, OwnerPointer<Render::VertexBuffer::Format>& format)
396 vertexBuffer->SetFormat(format.Release());
399 void RenderManager::SetVertexBufferData(Render::VertexBuffer* vertexBuffer, OwnerPointer<Vector<uint8_t>>& data, uint32_t size)
401 vertexBuffer->SetData(data.Release(), size);
404 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Dali::Vector<uint16_t>& indices)
406 geometry->SetIndexBuffer(indices);
409 void RenderManager::AddGeometry(OwnerPointer<Render::Geometry>& geometry)
411 mImpl->geometryContainer.PushBack(geometry.Release());
414 void RenderManager::RemoveGeometry(Render::Geometry* geometry)
416 mImpl->geometryContainer.EraseObject(geometry);
419 void RenderManager::AttachVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
421 DALI_ASSERT_DEBUG(NULL != geometry);
424 for(auto&& iter : mImpl->geometryContainer)
428 iter->AddVertexBuffer(vertexBuffer);
434 void RenderManager::RemoveVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
436 DALI_ASSERT_DEBUG(NULL != geometry);
439 for(auto&& iter : mImpl->geometryContainer)
443 iter->RemoveVertexBuffer(vertexBuffer);
449 void RenderManager::SetGeometryType(Render::Geometry* geometry, uint32_t geometryType)
451 geometry->SetType(Render::Geometry::Type(geometryType));
454 void RenderManager::AddRenderTracker(Render::RenderTracker* renderTracker)
456 mImpl->AddRenderTracker(renderTracker);
459 void RenderManager::RemoveRenderTracker(Render::RenderTracker* renderTracker)
461 mImpl->RemoveRenderTracker(renderTracker);
464 ProgramCache* RenderManager::GetProgramCache()
466 return &(mImpl->programController);
469 void RenderManager::PreRender(Integration::RenderStatus& status, bool forceClear, bool uploadOnly)
471 DALI_PRINT_RENDER_START(mImpl->renderBufferIndex);
473 // Core::Render documents that GL context must be current before calling Render
474 DALI_ASSERT_DEBUG(mImpl->context.IsGlContextCreated());
476 // Increment the frame count at the beginning of each frame
479 // Process messages queued during previous update
480 mImpl->renderQueue.ProcessMessages(mImpl->renderBufferIndex);
483 for(uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i)
485 count += mImpl->sceneContainer[i]->GetRenderInstructions().Count(mImpl->renderBufferIndex);
488 const bool haveInstructions = count > 0u;
490 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");
492 // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
493 if(haveInstructions || mImpl->lastFrameWasRendered || forceClear)
495 DALI_LOG_INFO(gLogFilter, Debug::General, "Render: Processing\n");
497 // Switch to the shared context
498 if(mImpl->currentContext != &mImpl->context)
500 mImpl->currentContext = &mImpl->context;
502 if(mImpl->currentContext->IsSurfacelessContextSupported())
504 mImpl->graphicsController.GetGlContextHelperAbstraction().MakeSurfacelessContextCurrent();
507 // Clear the current cached program when the context is switched
508 mImpl->programController.ClearCurrentProgram();
511 // Upload the geometries
512 for(uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i)
514 RenderInstructionContainer& instructions = mImpl->sceneContainer[i]->GetRenderInstructions();
515 for(uint32_t j = 0; j < instructions.Count(mImpl->renderBufferIndex); ++j)
517 RenderInstruction& instruction = instructions.At(mImpl->renderBufferIndex, j);
519 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
520 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
522 DALI_ASSERT_DEBUG(viewMatrix);
523 DALI_ASSERT_DEBUG(projectionMatrix);
525 if(viewMatrix && projectionMatrix)
527 const RenderListContainer::SizeType renderListCount = instruction.RenderListCount();
529 // Iterate through each render list.
530 for(RenderListContainer::SizeType index = 0; index < renderListCount; ++index)
532 const RenderList* renderList = instruction.GetRenderList(index);
534 if(renderList && !renderList->IsEmpty())
536 const std::size_t itemCount = renderList->Count();
537 for(uint32_t itemIndex = 0u; itemIndex < itemCount; ++itemIndex)
539 const RenderItem& item = renderList->GetItem(itemIndex);
540 if(DALI_LIKELY(item.mRenderer))
542 item.mRenderer->Upload(*mImpl->currentContext);
553 void RenderManager::PreRender(Integration::Scene& scene, std::vector<Rect<int>>& damagedRects)
555 if(mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
560 Internal::Scene& sceneInternal = GetImplementation(scene);
561 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
563 if(sceneObject->IsRenderingSkipped())
565 // We don't need to calculate dirty rects
569 // @TODO We need to do partial rendering rotation.
570 if( mImpl->defaultSurfaceOrientation != 0 )
575 class DamagedRectsCleaner
578 DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects)
579 : mDamagedRects(damagedRects),
584 void SetCleanOnReturn(bool cleanOnReturn)
586 mCleanOnReturn = cleanOnReturn;
589 ~DamagedRectsCleaner()
593 mDamagedRects.clear();
598 std::vector<Rect<int>>& mDamagedRects;
602 Rect<int32_t> surfaceRect = Rect<int32_t>(0, 0, static_cast<int32_t>(scene.GetSize().width), static_cast<int32_t>(scene.GetSize().height));
604 // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
605 DamagedRectsCleaner damagedRectCleaner(damagedRects);
607 // Mark previous dirty rects in the sorted array. The array is already sorted by node and renderer, frame number.
608 // so you don't need to sort: std::stable_sort(itemsDirtyRects.begin(), itemsDirtyRects.end());
609 std::vector<DirtyRect>& itemsDirtyRects = sceneInternal.GetItemsDirtyRects();
610 for(DirtyRect& dirtyRect : itemsDirtyRects)
612 dirtyRect.visited = false;
615 uint32_t count = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
616 for(uint32_t i = 0; i < count; ++i)
618 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
620 if(instruction.mFrameBuffer)
622 return; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
625 const Camera* camera = instruction.GetCamera();
626 if(camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
628 const Node* node = instruction.GetCamera()->GetNode();
633 Quaternion orientation;
634 node->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
636 Vector3 orientationAxis;
637 Radian orientationAngle;
638 orientation.ToAxisAngle(orientationAxis, orientationAngle);
640 if(position.x > Math::MACHINE_EPSILON_10000 ||
641 position.y > Math::MACHINE_EPSILON_10000 ||
642 orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
643 orientationAngle != ANGLE_180 ||
644 scale != Vector3(1.0f, 1.0f, 1.0f))
655 Rect<int32_t> viewportRect;
656 if(instruction.mIsViewportSet)
658 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
659 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
660 if(viewportRect.IsEmpty() || !viewportRect.IsValid())
662 return; // just skip funny use cases for now, empty viewport means it is set somewhere else
667 viewportRect = surfaceRect;
670 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
671 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
672 if(viewMatrix && projectionMatrix)
674 const RenderListContainer::SizeType count = instruction.RenderListCount();
675 for(RenderListContainer::SizeType index = 0u; index < count; ++index)
677 const RenderList* renderList = instruction.GetRenderList(index);
678 if(renderList && !renderList->IsEmpty())
680 const std::size_t count = renderList->Count();
681 for(uint32_t index = 0u; index < count; ++index)
683 RenderItem& item = renderList->GetItem(index);
684 // If the item does 3D transformation, do early exit and clean the damaged rect array
685 if(item.mUpdateSize == Vector3::ZERO)
691 DirtyRect dirtyRect(item.mNode, item.mRenderer, mImpl->frameCount, rect);
692 // If the item refers to updated node or renderer.
693 if(item.mIsUpdated ||
695 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex, item.mNode)))))
697 item.mIsUpdated = false;
698 item.mNode->SetUpdated(false);
700 rect = item.CalculateViewportSpaceAABB(item.mUpdateSize, viewportRect.width, viewportRect.height);
701 if(rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
703 const int left = rect.x;
704 const int top = rect.y;
705 const int right = rect.x + rect.width;
706 const int bottom = rect.y + rect.height;
707 rect.x = (left / 16) * 16;
708 rect.y = (top / 16) * 16;
709 rect.width = ((right + 16) / 16) * 16 - rect.x;
710 rect.height = ((bottom + 16) / 16) * 16 - rect.y;
712 // Found valid dirty rect.
713 // 1. Insert it in the sorted array of the dirty rects.
714 // 2. Mark the related dirty rects as visited so they will not be removed below.
715 // 3. Keep only last 3 dirty rects for the same node and renderer (Tizen uses 3 back buffers, Ubuntu 1).
716 dirtyRect.rect = rect;
717 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
718 dirtyRectPos = itemsDirtyRects.insert(dirtyRectPos, dirtyRect);
721 while(++dirtyRectPos != itemsDirtyRects.end())
723 if(dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
728 dirtyRectPos->visited = true;
729 Rect<int>& dirtRect = dirtyRectPos->rect;
730 rect.Merge(dirtRect);
733 if(c > 3) // no more then 3 previous rects
735 itemsDirtyRects.erase(dirtyRectPos);
740 damagedRects.push_back(rect);
745 // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
746 // 2. Mark the related dirty rects as visited so they will not be removed below.
747 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
748 while(dirtyRectPos != itemsDirtyRects.end())
750 if(dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
755 dirtyRectPos->visited = true;
765 // Check removed nodes or removed renderers dirty rects
766 auto i = itemsDirtyRects.begin();
767 auto j = itemsDirtyRects.begin();
768 while(i != itemsDirtyRects.end())
776 Rect<int>& dirtRect = i->rect;
777 damagedRects.push_back(dirtRect);
782 itemsDirtyRects.resize(j - itemsDirtyRects.begin());
783 damagedRectCleaner.SetCleanOnReturn(false);
786 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo)
788 Rect<int> clippingRect;
789 RenderScene(status, scene, renderToFbo, clippingRect);
792 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
794 Internal::Scene& sceneInternal = GetImplementation(scene);
795 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
797 uint32_t count = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
799 for(uint32_t i = 0; i < count; ++i)
801 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
803 if((renderToFbo && !instruction.mFrameBuffer) || (!renderToFbo && instruction.mFrameBuffer))
808 // Mark that we will require a post-render step to be performed (includes swap-buffers).
809 status.SetNeedsPostRender(true);
811 Rect<int32_t> viewportRect;
814 if(instruction.mIsClearColorSet)
816 clearColor = instruction.mClearColor;
820 clearColor = Dali::RenderTask::DEFAULT_CLEAR_COLOR;
823 Rect<int32_t> surfaceRect = mImpl->defaultSurfaceRect;
824 Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
825 Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
826 int surfaceOrientation = sceneInternal.GetSurfaceOrientation();
828 if(instruction.mFrameBuffer)
831 if(mImpl->currentContext != &mImpl->context)
833 // Switch to shared context for off-screen buffer
834 mImpl->currentContext = &mImpl->context;
836 if(mImpl->currentContext->IsSurfacelessContextSupported())
838 mImpl->graphicsController.GetGlContextHelperAbstraction().MakeSurfacelessContextCurrent();
841 // Clear the current cached program when the context is switched
842 mImpl->programController.ClearCurrentProgram();
847 if(mImpl->currentContext->IsSurfacelessContextSupported())
849 if(mImpl->currentContext != sceneObject->GetContext())
851 // Switch the correct context if rendering to a surface
852 mImpl->currentContext = sceneObject->GetContext();
854 // Clear the current cached program when the context is switched
855 mImpl->programController.ClearCurrentProgram();
859 surfaceRect = Rect<int32_t>(0, 0, static_cast<int32_t>(scene.GetSize().width), static_cast<int32_t>(scene.GetSize().height));
862 // Make sure that GL context must be created
863 mImpl->currentContext->GlContextCreated();
865 // reset the program matrices for all programs once per frame
866 // this ensures we will set view and projection matrix once per program per camera
867 mImpl->programController.ResetProgramMatrices();
869 if(instruction.mFrameBuffer)
871 instruction.mFrameBuffer->Bind(*mImpl->currentContext);
873 // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
874 for(unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
876 mImpl->textureDependencyList.PushBack(instruction.mFrameBuffer->GetTextureId(i0));
881 mImpl->currentContext->BindFramebuffer(GL_FRAMEBUFFER, 0u);
884 if(!instruction.mFrameBuffer)
886 mImpl->currentContext->Viewport(surfaceRect.x,
892 // Clear the entire color, depth and stencil buffers for the default framebuffer, if required.
893 // It is important to clear all 3 buffers when they are being used, for performance on deferred renderers
894 // e.g. previously when the depth & stencil buffers were NOT cleared, it caused the DDK to exceed a "vertex count limit",
895 // and then stall. That problem is only noticeable when rendering a large number of vertices per frame.
896 GLbitfield clearMask = GL_COLOR_BUFFER_BIT;
898 mImpl->currentContext->ColorMask(true);
900 if(depthBufferAvailable == Integration::DepthBufferAvailable::TRUE)
902 mImpl->currentContext->DepthMask(true);
903 clearMask |= GL_DEPTH_BUFFER_BIT;
906 if(stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE)
908 mImpl->currentContext->ClearStencil(0);
909 mImpl->currentContext->StencilMask(0xFF); // 8 bit stencil mask, all 1's
910 clearMask |= GL_STENCIL_BUFFER_BIT;
913 if(!instruction.mIgnoreRenderToFbo && (instruction.mFrameBuffer != nullptr))
915 // Offscreen buffer rendering
916 if(instruction.mIsViewportSet)
918 // For glViewport the lower-left corner is (0,0)
919 const int32_t y = (instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height) - instruction.mViewport.y;
920 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
924 viewportRect.Set(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
926 surfaceOrientation = 0;
928 else // No Offscreen frame buffer rendering
930 // Check whether a viewport is specified, otherwise the full surface size is used
931 if(instruction.mIsViewportSet)
933 // For glViewport the lower-left corner is (0,0)
934 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
935 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
939 viewportRect = surfaceRect;
943 // Set surface orientation
944 mImpl->currentContext->SetSurfaceOrientation(surfaceOrientation);
946 bool clearFullFrameRect = true;
947 if(instruction.mFrameBuffer != nullptr)
949 Viewport frameRect(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
950 clearFullFrameRect = (frameRect == viewportRect);
954 clearFullFrameRect = (surfaceRect == viewportRect);
957 if(!clippingRect.IsEmpty())
959 if(!clippingRect.Intersect(viewportRect))
961 DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
962 clippingRect = Rect<int>();
964 clearFullFrameRect = false;
967 mImpl->currentContext->Viewport(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
969 if(instruction.mIsClearColorSet)
971 mImpl->currentContext->ClearColor(clearColor.r,
975 if(!clearFullFrameRect)
977 if(!clippingRect.IsEmpty())
979 mImpl->currentContext->SetScissorTest(true);
980 mImpl->currentContext->Scissor(clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
981 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
982 mImpl->currentContext->SetScissorTest(false);
986 mImpl->currentContext->SetScissorTest(true);
987 mImpl->currentContext->Scissor(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
988 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
989 mImpl->currentContext->SetScissorTest(false);
994 mImpl->currentContext->SetScissorTest(false);
995 mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
999 // Clear the list of bound textures
1000 mImpl->boundTextures.Clear();
1002 mImpl->renderAlgorithms.ProcessRenderInstruction(
1004 *mImpl->currentContext,
1005 mImpl->renderBufferIndex,
1006 depthBufferAvailable,
1007 stencilBufferAvailable,
1008 mImpl->boundTextures,
1011 // Synchronise the FBO/Texture access when there are multiple contexts
1012 if(mImpl->currentContext->IsSurfacelessContextSupported())
1014 // Check whether any binded texture is in the dependency list
1015 bool textureFound = false;
1017 if(mImpl->boundTextures.Count() > 0u && mImpl->textureDependencyList.Count() > 0u)
1019 for(auto textureId : mImpl->textureDependencyList)
1021 textureFound = std::find_if(mImpl->boundTextures.Begin(), mImpl->boundTextures.End(), [textureId](GLuint id) {
1022 return textureId == id;
1023 }) != mImpl->boundTextures.End();
1029 if(instruction.mFrameBuffer)
1031 // For off-screen buffer
1033 // Wait until all rendering calls for the currently context are executed
1034 mImpl->graphicsController.GetGlContextHelperAbstraction().WaitClient();
1036 // Clear the dependency list
1037 mImpl->textureDependencyList.Clear();
1041 // Worker thread lambda function
1042 auto& glContextHelperAbstraction = mImpl->graphicsController.GetGlContextHelperAbstraction();
1043 auto workerFunction = [&glContextHelperAbstraction](int workerThread) {
1044 // Switch to the shared context in the worker thread
1045 glContextHelperAbstraction.MakeSurfacelessContextCurrent();
1047 // Wait until all rendering calls for the shared context are executed
1048 glContextHelperAbstraction.WaitClient();
1050 // Must clear the context in the worker thread
1051 // Otherwise the shared context cannot be switched to from the render thread
1052 glContextHelperAbstraction.MakeContextNull();
1055 auto future = mImpl->threadPool->SubmitTask(0u, workerFunction);
1058 mImpl->threadPool->Wait();
1060 // Clear the dependency list
1061 mImpl->textureDependencyList.Clear();
1067 if(instruction.mRenderTracker && instruction.mFrameBuffer)
1069 // This will create a sync object every frame this render tracker
1070 // is alive (though it should be now be created only for
1071 // render-once render tasks)
1072 instruction.mRenderTracker->CreateSyncObject(mImpl->graphicsController.GetGlSyncAbstraction());
1073 instruction.mRenderTracker = nullptr; // Only create once.
1078 mImpl->currentContext->Flush();
1082 GLenum attachments[] = {GL_DEPTH, GL_STENCIL};
1083 mImpl->currentContext->InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
1086 void RenderManager::PostRender(bool uploadOnly)
1090 if(mImpl->currentContext->IsSurfacelessContextSupported())
1092 mImpl->graphicsController.GetGlContextHelperAbstraction().MakeSurfacelessContextCurrent();
1095 GLenum attachments[] = {GL_DEPTH, GL_STENCIL};
1096 mImpl->context.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
1099 //Notify RenderGeometries that rendering has finished
1100 for(auto&& iter : mImpl->geometryContainer)
1102 iter->OnRenderFinished();
1105 mImpl->UpdateTrackers();
1107 uint32_t count = 0u;
1108 for(uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i)
1110 count += mImpl->sceneContainer[i]->GetRenderInstructions().Count(mImpl->renderBufferIndex);
1113 const bool haveInstructions = count > 0u;
1115 // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
1116 mImpl->lastFrameWasRendered = haveInstructions;
1119 * The rendering has finished; swap to the next buffer.
1120 * Ideally the update has just finished using this buffer; otherwise the render thread
1121 * should block until the update has finished.
1123 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1125 DALI_PRINT_RENDER_END();
1128 } // namespace SceneGraph
1130 } // namespace Internal