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/renderers/shader-cache.h>
42 #include <dali/internal/render/renderers/uniform-buffer-manager.h>
43 #include <dali/internal/render/renderers/uniform-buffer-view-pool.h>
44 #include <dali/internal/render/shaders/program-controller.h>
46 #include <dali/internal/render/renderers/uniform-buffer-manager.h>
54 #if defined(DEBUG_ENABLED)
57 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_MANAGER");
58 } // unnamed namespace
63 inline Graphics::Rect2D RecalculateScissorArea(Graphics::Rect2D scissorArea, int orientation, Rect<int32_t> viewportRect)
65 Graphics::Rect2D newScissorArea;
69 newScissorArea.x = viewportRect.height - (scissorArea.y + scissorArea.height);
70 newScissorArea.y = scissorArea.x;
71 newScissorArea.width = scissorArea.height;
72 newScissorArea.height = scissorArea.width;
74 else if(orientation == 180)
76 newScissorArea.x = viewportRect.width - (scissorArea.x + scissorArea.width);
77 newScissorArea.y = viewportRect.height - (scissorArea.y + scissorArea.height);
78 newScissorArea.width = scissorArea.width;
79 newScissorArea.height = scissorArea.height;
81 else if(orientation == 270)
83 newScissorArea.x = scissorArea.y;
84 newScissorArea.y = viewportRect.width - (scissorArea.x + scissorArea.width);
85 newScissorArea.width = scissorArea.height;
86 newScissorArea.height = scissorArea.width;
90 newScissorArea.x = scissorArea.x;
91 newScissorArea.y = scissorArea.y;
92 newScissorArea.width = scissorArea.width;
93 newScissorArea.height = scissorArea.height;
95 return newScissorArea;
99 * Structure to contain internal data
101 struct RenderManager::Impl
103 Impl(Graphics::Controller& graphicsController,
104 Integration::DepthBufferAvailable depthBufferAvailableParam,
105 Integration::StencilBufferAvailable stencilBufferAvailableParam,
106 Integration::PartialUpdateAvailable partialUpdateAvailableParam)
107 : graphicsController(graphicsController),
109 renderAlgorithms(graphicsController),
111 renderBufferIndex(SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX),
115 frameBufferContainer(),
116 lastFrameWasRendered(false),
117 programController(graphicsController),
118 shaderCache(graphicsController),
119 depthBufferAvailable(depthBufferAvailableParam),
120 stencilBufferAvailable(stencilBufferAvailableParam),
121 partialUpdateAvailable(partialUpdateAvailableParam)
123 // Create thread pool with just one thread ( there may be a need to create more threads in the future ).
124 threadPool = std::unique_ptr<Dali::ThreadPool>(new Dali::ThreadPool());
125 threadPool->Initialize(1u);
127 uniformBufferManager.reset(new Render::UniformBufferManager(&graphicsController));
132 threadPool.reset(nullptr); // reset now to maintain correct destruction order
135 void AddRenderTracker(Render::RenderTracker* renderTracker)
137 DALI_ASSERT_DEBUG(renderTracker != nullptr);
138 mRenderTrackers.PushBack(renderTracker);
141 void RemoveRenderTracker(Render::RenderTracker* renderTracker)
143 mRenderTrackers.EraseObject(renderTracker);
146 void UpdateTrackers()
148 for(auto&& iter : mRenderTrackers)
150 iter->PollSyncObject();
154 // the order is important for destruction,
155 Graphics::Controller& graphicsController;
156 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
158 std::vector<SceneGraph::Scene*> sceneContainer; ///< List of pointers to the scene graph objects of the scenes
160 Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
162 uint32_t frameCount; ///< The current frame count
163 BufferIndex renderBufferIndex; ///< The index of the buffer to read from; this is opposite of the "update" buffer
165 OwnerContainer<Render::Renderer*> rendererContainer; ///< List of owned renderers
166 OwnerContainer<Render::Sampler*> samplerContainer; ///< List of owned samplers
167 OwnerContainer<Render::Texture*> textureContainer; ///< List of owned textures
168 OwnerContainer<Render::FrameBuffer*> frameBufferContainer; ///< List of owned framebuffers
169 OwnerContainer<Render::VertexBuffer*> vertexBufferContainer; ///< List of owned vertex buffers
170 OwnerContainer<Render::Geometry*> geometryContainer; ///< List of owned Geometries
172 bool lastFrameWasRendered; ///< Keeps track of the last frame being rendered due to having render instructions
174 OwnerContainer<Render::RenderTracker*> mRenderTrackers; ///< List of render trackers
176 ProgramController programController; ///< Owner of the GL programs
177 Render::ShaderCache shaderCache; ///< The cache for the graphics shaders
179 std::unique_ptr<Render::UniformBufferManager> uniformBufferManager; ///< The uniform buffer manager
181 Integration::DepthBufferAvailable depthBufferAvailable; ///< Whether the depth buffer is available
182 Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
183 Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
185 std::unique_ptr<Dali::ThreadPool> threadPool; ///< The thread pool
186 Vector<Graphics::Texture*> boundTextures; ///< The textures bound for rendering
187 Vector<Graphics::Texture*> textureDependencyList; ///< The dependency list of bound textures
190 RenderManager* RenderManager::New(Graphics::Controller& graphicsController,
191 Integration::DepthBufferAvailable depthBufferAvailable,
192 Integration::StencilBufferAvailable stencilBufferAvailable,
193 Integration::PartialUpdateAvailable partialUpdateAvailable)
195 auto* manager = new RenderManager;
196 manager->mImpl = new Impl(graphicsController,
197 depthBufferAvailable,
198 stencilBufferAvailable,
199 partialUpdateAvailable);
203 RenderManager::RenderManager()
208 RenderManager::~RenderManager()
213 RenderQueue& RenderManager::GetRenderQueue()
215 return mImpl->renderQueue;
218 void RenderManager::SetShaderSaver(ShaderSaver& upstream)
222 void RenderManager::AddRenderer(OwnerPointer<Render::Renderer>& renderer)
224 // Initialize the renderer as we are now in render thread
225 renderer->Initialize(mImpl->graphicsController, mImpl->programController, mImpl->shaderCache, *(mImpl->uniformBufferManager.get()));
227 mImpl->rendererContainer.PushBack(renderer.Release());
230 void RenderManager::RemoveRenderer(Render::Renderer* renderer)
232 mImpl->rendererContainer.EraseObject(renderer);
235 void RenderManager::AddSampler(OwnerPointer<Render::Sampler>& sampler)
237 sampler->Initialize(mImpl->graphicsController);
238 mImpl->samplerContainer.PushBack(sampler.Release());
241 void RenderManager::RemoveSampler(Render::Sampler* sampler)
243 mImpl->samplerContainer.EraseObject(sampler);
246 void RenderManager::AddTexture(OwnerPointer<Render::Texture>& texture)
248 texture->Initialize(mImpl->graphicsController);
249 mImpl->textureContainer.PushBack(texture.Release());
252 void RenderManager::RemoveTexture(Render::Texture* texture)
254 DALI_ASSERT_DEBUG(NULL != texture);
256 // Find the texture, use reference to pointer so we can do the erase safely
257 for(auto&& iter : mImpl->textureContainer)
262 mImpl->textureContainer.Erase(&iter); // Texture found; now destroy it
268 void RenderManager::UploadTexture(Render::Texture* texture, PixelDataPtr pixelData, const Texture::UploadParams& params)
270 texture->Upload(pixelData, params);
273 void RenderManager::GenerateMipmaps(Render::Texture* texture)
275 texture->GenerateMipmaps();
278 void RenderManager::SetFilterMode(Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode)
280 sampler->SetFilterMode(static_cast<Dali::FilterMode::Type>(minFilterMode),
281 static_cast<Dali::FilterMode::Type>(magFilterMode));
284 void RenderManager::SetWrapMode(Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode)
286 sampler->SetWrapMode(static_cast<Dali::WrapMode::Type>(rWrapMode),
287 static_cast<Dali::WrapMode::Type>(sWrapMode),
288 static_cast<Dali::WrapMode::Type>(tWrapMode));
291 void RenderManager::AddFrameBuffer(OwnerPointer<Render::FrameBuffer>& frameBuffer)
293 Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
294 mImpl->frameBufferContainer.PushBack(frameBufferPtr);
295 frameBufferPtr->Initialize(mImpl->graphicsController);
298 void RenderManager::RemoveFrameBuffer(Render::FrameBuffer* frameBuffer)
300 DALI_ASSERT_DEBUG(nullptr != frameBuffer);
302 // Find the sampler, use reference so we can safely do the erase
303 for(auto&& iter : mImpl->frameBufferContainer)
305 if(iter == frameBuffer)
307 frameBuffer->Destroy();
308 mImpl->frameBufferContainer.Erase(&iter); // frameBuffer found; now destroy it
315 void RenderManager::InitializeScene(SceneGraph::Scene* scene)
317 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
318 mImpl->sceneContainer.push_back(scene);
321 void RenderManager::UninitializeScene(SceneGraph::Scene* scene)
323 auto iter = std::find(mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene);
324 if(iter != mImpl->sceneContainer.end())
326 mImpl->sceneContainer.erase(iter);
330 void RenderManager::SurfaceReplaced(SceneGraph::Scene* scene)
332 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
335 void RenderManager::AttachColorTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer)
337 frameBuffer->AttachColorTexture(texture, mipmapLevel, layer);
340 void RenderManager::AttachDepthTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
342 frameBuffer->AttachDepthTexture(texture, mipmapLevel);
345 void RenderManager::AttachDepthStencilTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
347 frameBuffer->AttachDepthStencilTexture(texture, mipmapLevel);
350 void RenderManager::AddVertexBuffer(OwnerPointer<Render::VertexBuffer>& vertexBuffer)
352 mImpl->vertexBufferContainer.PushBack(vertexBuffer.Release());
355 void RenderManager::RemoveVertexBuffer(Render::VertexBuffer* vertexBuffer)
357 mImpl->vertexBufferContainer.EraseObject(vertexBuffer);
360 void RenderManager::SetVertexBufferFormat(Render::VertexBuffer* vertexBuffer, OwnerPointer<Render::VertexBuffer::Format>& format)
362 vertexBuffer->SetFormat(format.Release());
365 void RenderManager::SetVertexBufferData(Render::VertexBuffer* vertexBuffer, OwnerPointer<Vector<uint8_t>>& data, uint32_t size)
367 vertexBuffer->SetData(data.Release(), size);
370 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Dali::Vector<uint16_t>& indices)
372 geometry->SetIndexBuffer(indices);
375 void RenderManager::AddGeometry(OwnerPointer<Render::Geometry>& geometry)
377 mImpl->geometryContainer.PushBack(geometry.Release());
380 void RenderManager::RemoveGeometry(Render::Geometry* geometry)
382 mImpl->geometryContainer.EraseObject(geometry);
385 void RenderManager::AttachVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
387 DALI_ASSERT_DEBUG(nullptr != geometry);
390 for(auto&& iter : mImpl->geometryContainer)
394 iter->AddVertexBuffer(vertexBuffer);
400 void RenderManager::RemoveVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
402 DALI_ASSERT_DEBUG(nullptr != geometry);
405 for(auto&& iter : mImpl->geometryContainer)
409 iter->RemoveVertexBuffer(vertexBuffer);
415 void RenderManager::SetGeometryType(Render::Geometry* geometry, uint32_t geometryType)
417 geometry->SetType(Render::Geometry::Type(geometryType));
420 void RenderManager::AddRenderTracker(Render::RenderTracker* renderTracker)
422 mImpl->AddRenderTracker(renderTracker);
425 void RenderManager::RemoveRenderTracker(Render::RenderTracker* renderTracker)
427 mImpl->RemoveRenderTracker(renderTracker);
430 void RenderManager::PreRender(Integration::RenderStatus& status, bool forceClear, bool uploadOnly)
432 DALI_PRINT_RENDER_START(mImpl->renderBufferIndex);
435 mImpl->uniformBufferManager->GetUniformBufferViewPool(mImpl->renderBufferIndex)->Rollback();
437 // Increment the frame count at the beginning of each frame
440 // Process messages queued during previous update
441 mImpl->renderQueue.ProcessMessages(mImpl->renderBufferIndex);
444 for(auto& i : mImpl->sceneContainer)
446 count += i->GetRenderInstructions().Count(mImpl->renderBufferIndex);
449 const bool haveInstructions = count > 0u;
451 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");
453 // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
454 if(haveInstructions || mImpl->lastFrameWasRendered || forceClear)
456 DALI_LOG_INFO(gLogFilter, Debug::General, "Render: Processing\n");
458 // Upload the geometries
459 for(auto& i : mImpl->sceneContainer)
461 RenderInstructionContainer& instructions = i->GetRenderInstructions();
462 for(uint32_t j = 0; j < instructions.Count(mImpl->renderBufferIndex); ++j)
464 RenderInstruction& instruction = instructions.At(mImpl->renderBufferIndex, j);
466 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
467 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
469 DALI_ASSERT_DEBUG(viewMatrix);
470 DALI_ASSERT_DEBUG(projectionMatrix);
472 if(viewMatrix && projectionMatrix)
474 const RenderListContainer::SizeType renderListCount = instruction.RenderListCount();
476 // Iterate through each render list.
477 for(RenderListContainer::SizeType index = 0; index < renderListCount; ++index)
479 const RenderList* renderList = instruction.GetRenderList(index);
481 if(renderList && !renderList->IsEmpty())
483 const std::size_t itemCount = renderList->Count();
484 for(uint32_t itemIndex = 0u; itemIndex < itemCount; ++itemIndex)
486 const RenderItem& item = renderList->GetItem(itemIndex);
487 if(DALI_LIKELY(item.mRenderer))
489 item.mRenderer->Upload();
500 void RenderManager::PreRender(Integration::Scene& scene, std::vector<Rect<int>>& damagedRects)
502 if(mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
507 Internal::Scene& sceneInternal = GetImplementation(scene);
508 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
510 if(sceneObject->IsRenderingSkipped())
512 // We don't need to calculate dirty rects
516 class DamagedRectsCleaner
519 explicit DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects)
520 : mDamagedRects(damagedRects),
525 void SetCleanOnReturn(bool cleanOnReturn)
527 mCleanOnReturn = cleanOnReturn;
530 ~DamagedRectsCleaner()
534 mDamagedRects.clear();
539 std::vector<Rect<int>>& mDamagedRects;
543 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
545 // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
546 DamagedRectsCleaner damagedRectCleaner(damagedRects);
548 // Mark previous dirty rects in the sorted array. The array is already sorted by node and renderer, frame number.
549 // so you don't need to sort: std::stable_sort(itemsDirtyRects.begin(), itemsDirtyRects.end());
550 std::vector<DirtyRect>& itemsDirtyRects = sceneInternal.GetItemsDirtyRects();
551 for(DirtyRect& dirtyRect : itemsDirtyRects)
553 dirtyRect.visited = false;
556 uint32_t instructionCount = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
557 for(uint32_t i = 0; i < instructionCount; ++i)
559 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
561 if(instruction.mFrameBuffer)
563 return; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
566 const Camera* camera = instruction.GetCamera();
567 if(camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
569 const Node* node = instruction.GetCamera()->GetNode();
574 Quaternion orientation;
575 node->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
577 Vector3 orientationAxis;
578 Radian orientationAngle;
579 orientation.ToAxisAngle(orientationAxis, orientationAngle);
581 if(position.x > Math::MACHINE_EPSILON_10000 ||
582 position.y > Math::MACHINE_EPSILON_10000 ||
583 orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
584 orientationAngle != ANGLE_180 ||
585 scale != Vector3(1.0f, 1.0f, 1.0f))
596 Rect<int32_t> viewportRect;
597 if(instruction.mIsViewportSet)
599 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
600 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
601 if(viewportRect.IsEmpty() || !viewportRect.IsValid())
603 return; // just skip funny use cases for now, empty viewport means it is set somewhere else
608 viewportRect = surfaceRect;
611 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
612 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
613 if(viewMatrix && projectionMatrix)
615 const RenderListContainer::SizeType count = instruction.RenderListCount();
616 for(RenderListContainer::SizeType index = 0u; index < count; ++index)
618 const RenderList* renderList = instruction.GetRenderList(index);
619 if(renderList && !renderList->IsEmpty())
621 const std::size_t listCount = renderList->Count();
622 for(uint32_t listIndex = 0u; listIndex < listCount; ++listIndex)
624 RenderItem& item = renderList->GetItem(listIndex);
625 // If the item does 3D transformation, do early exit and clean the damaged rect array
626 if(item.mUpdateSize == Vector3::ZERO)
632 DirtyRect dirtyRect(item.mNode, item.mRenderer, mImpl->frameCount, rect);
633 // If the item refers to updated node or renderer.
634 if(item.mIsUpdated ||
636 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex, item.mNode)))))
638 item.mIsUpdated = false;
639 item.mNode->SetUpdated(false);
641 rect = item.CalculateViewportSpaceAABB(item.mUpdateSize, viewportRect.width, viewportRect.height);
642 if(rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
644 const int left = rect.x;
645 const int top = rect.y;
646 const int right = rect.x + rect.width;
647 const int bottom = rect.y + rect.height;
648 rect.x = (left / 16) * 16;
649 rect.y = (top / 16) * 16;
650 rect.width = ((right + 16) / 16) * 16 - rect.x;
651 rect.height = ((bottom + 16) / 16) * 16 - rect.y;
653 // Found valid dirty rect.
654 // 1. Insert it in the sorted array of the dirty rects.
655 // 2. Mark the related dirty rects as visited so they will not be removed below.
656 // 3. Keep only last 3 dirty rects for the same node and renderer (Tizen uses 3 back buffers, Ubuntu 1).
657 dirtyRect.rect = rect;
658 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
659 dirtyRectPos = itemsDirtyRects.insert(dirtyRectPos, dirtyRect);
662 while(++dirtyRectPos != itemsDirtyRects.end())
664 if(dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
669 dirtyRectPos->visited = true;
670 Rect<int>& dirtRect = dirtyRectPos->rect;
671 rect.Merge(dirtRect);
674 if(c > 3) // no more then 3 previous rects
676 itemsDirtyRects.erase(dirtyRectPos);
681 damagedRects.push_back(rect);
686 // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
687 // 2. Mark the related dirty rects as visited so they will not be removed below.
688 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
689 while(dirtyRectPos != itemsDirtyRects.end())
691 if(dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
696 dirtyRectPos->visited = true;
706 // Check removed nodes or removed renderers dirty rects
707 auto i = itemsDirtyRects.begin();
708 auto j = itemsDirtyRects.begin();
709 while(i != itemsDirtyRects.end())
717 Rect<int>& dirtRect = i->rect;
718 damagedRects.push_back(dirtRect);
723 itemsDirtyRects.resize(j - itemsDirtyRects.begin());
724 damagedRectCleaner.SetCleanOnReturn(false);
727 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo)
729 Rect<int> clippingRect;
730 RenderScene(status, scene, renderToFbo, clippingRect);
733 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
735 // Reset main algorithms command buffer
736 mImpl->renderAlgorithms.ResetCommandBuffer();
738 auto mainCommandBuffer = mImpl->renderAlgorithms.GetMainCommandBuffer();
740 Internal::Scene& sceneInternal = GetImplementation(scene);
741 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
743 uint32_t count = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
745 std::vector<Graphics::RenderTarget*> targetstoPresent;
747 for(uint32_t i = 0; i < count; ++i)
749 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
751 if((renderToFbo && !instruction.mFrameBuffer) || (!renderToFbo && instruction.mFrameBuffer))
756 // Mark that we will require a post-render step to be performed (includes swap-buffers).
757 status.SetNeedsPostRender(true);
759 Rect<int32_t> viewportRect;
761 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
762 int32_t surfaceOrientation = sceneObject->GetSurfaceOrientation();
764 // @todo Should these be part of scene?
765 Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
766 Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
768 Graphics::RenderTarget* currentRenderTarget = nullptr;
769 Graphics::RenderPass* currentRenderPass = nullptr;
770 std::vector<Graphics::ClearValue> currentClearValues{};
772 if(instruction.mFrameBuffer)
774 // Ensure graphics framebuffer is created, bind attachments and create render passes
775 // Only happens once per framebuffer. If the create fails, e.g. no attachments yet,
776 // then don't render to this framebuffer.
777 if(!instruction.mFrameBuffer->GetGraphicsObject())
779 const bool created = instruction.mFrameBuffer->CreateGraphicsObjects();
786 auto& clearValues = instruction.mFrameBuffer->GetGraphicsRenderPassClearValues();
788 // Set the clear color for first color attachment
789 if(instruction.mIsClearColorSet && !clearValues.empty())
791 clearValues[0].color = {
792 instruction.mClearColor.r,
793 instruction.mClearColor.g,
794 instruction.mClearColor.b,
795 instruction.mClearColor.a};
798 currentClearValues = clearValues;
800 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
803 currentRenderTarget = instruction.mFrameBuffer->GetGraphicsRenderTarget();
804 currentRenderPass = instruction.mFrameBuffer->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
806 else // no framebuffer
809 auto& clearValues = sceneObject->GetGraphicsRenderPassClearValues();
811 if(instruction.mIsClearColorSet)
813 clearValues[0].color = {
814 instruction.mClearColor.r,
815 instruction.mClearColor.g,
816 instruction.mClearColor.b,
817 instruction.mClearColor.a};
820 currentClearValues = clearValues;
822 // @todo SceneObject should already have the depth clear / stencil clear in the clearValues array.
823 // if the window has a depth/stencil buffer.
824 if((depthBufferAvailable == Integration::DepthBufferAvailable::TRUE ||
825 stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE) &&
826 (currentClearValues.size() <= 1))
828 currentClearValues.emplace_back();
829 currentClearValues.back().depthStencil.depth = 0;
830 currentClearValues.back().depthStencil.stencil = 0;
833 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
835 currentRenderTarget = sceneObject->GetSurfaceRenderTarget();
836 currentRenderPass = sceneObject->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
839 targetstoPresent.emplace_back(currentRenderTarget);
841 // reset the program matrices for all programs once per frame
842 // this ensures we will set view and projection matrix once per program per camera
843 mImpl->programController.ResetProgramMatrices();
845 if(instruction.mFrameBuffer)
847 // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
848 for(unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
850 mImpl->textureDependencyList.PushBack(instruction.mFrameBuffer->GetTexture(i0));
854 if(!instruction.mIgnoreRenderToFbo && (instruction.mFrameBuffer != nullptr))
856 // Offscreen buffer rendering
857 if(instruction.mIsViewportSet)
859 // For glViewport the lower-left corner is (0,0)
860 const int32_t y = (instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height) - instruction.mViewport.y;
861 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
865 viewportRect.Set(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
867 surfaceOrientation = 0;
869 else // No Offscreen frame buffer rendering
871 // Check whether a viewport is specified, otherwise the full surface size is used
872 if(instruction.mIsViewportSet)
874 // For glViewport the lower-left corner is (0,0)
875 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
876 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
880 viewportRect = surfaceRect;
884 // Set surface orientation
885 // @todo Inform graphics impl by another route.
886 // was: mImpl->currentContext->SetSurfaceOrientation(surfaceOrientation);
888 /*** Clear region of framebuffer or surface before drawing ***/
889 bool clearFullFrameRect = (surfaceRect == viewportRect);
890 if(instruction.mFrameBuffer != nullptr)
892 Viewport frameRect(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
893 clearFullFrameRect = (frameRect == viewportRect);
896 if(!clippingRect.IsEmpty())
898 if(!clippingRect.Intersect(viewportRect))
900 DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
901 clippingRect = Rect<int>();
903 clearFullFrameRect = false;
906 Graphics::Rect2D scissorArea{viewportRect.x, viewportRect.y, uint32_t(viewportRect.width), uint32_t(viewportRect.height)};
907 if(instruction.mIsClearColorSet)
909 if(!clearFullFrameRect)
911 if(!clippingRect.IsEmpty())
913 scissorArea = {clippingRect.x, clippingRect.y, uint32_t(clippingRect.width), uint32_t(clippingRect.height)};
918 // Scissor's value should be set based on the default system coordinates.
919 // When the surface is rotated, the input values already were set with the rotated angle.
920 // So, re-calculation is needed.
921 scissorArea = RecalculateScissorArea(scissorArea, surfaceOrientation, viewportRect);
924 mainCommandBuffer->BeginRenderPass(
930 mainCommandBuffer->SetViewport({float(viewportRect.x),
931 float(viewportRect.y),
932 float(viewportRect.width),
933 float(viewportRect.height)});
935 // Clear the list of bound textures
936 mImpl->boundTextures.Clear();
938 mImpl->renderAlgorithms.ProcessRenderInstruction(
940 mImpl->renderBufferIndex,
941 depthBufferAvailable,
942 stencilBufferAvailable,
943 mImpl->boundTextures,
948 // Synchronise the FBO/Texture access
950 // Check whether any bound texture is in the dependency list
951 bool textureFound = false;
953 if(mImpl->boundTextures.Count() > 0u && mImpl->textureDependencyList.Count() > 0u)
955 for(auto texture : mImpl->textureDependencyList)
957 textureFound = std::find_if(mImpl->boundTextures.Begin(), mImpl->boundTextures.End(), [texture](Graphics::Texture* graphicsTexture) {
958 return texture == graphicsTexture;
959 }) != mImpl->boundTextures.End();
965 if(instruction.mFrameBuffer)
967 // For off-screen buffer
969 // Clear the dependency list
970 mImpl->textureDependencyList.Clear();
974 // Worker thread lambda function
975 auto& glContextHelperAbstraction = mImpl->graphicsController.GetGlContextHelperAbstraction();
976 auto workerFunction = [&glContextHelperAbstraction](int workerThread) {
977 // Switch to the shared context in the worker thread
978 glContextHelperAbstraction.MakeSurfacelessContextCurrent();
980 // Wait until all rendering calls for the shared context are executed
981 glContextHelperAbstraction.WaitClient();
983 // Must clear the context in the worker thread
984 // Otherwise the shared context cannot be switched to from the render thread
985 glContextHelperAbstraction.MakeContextNull();
988 auto future = mImpl->threadPool->SubmitTask(0u, workerFunction);
991 mImpl->threadPool->Wait();
993 // Clear the dependency list
994 mImpl->textureDependencyList.Clear();
999 Graphics::SyncObject* syncObject{nullptr};
1000 // If the render instruction has an associated render tracker (owned separately)
1001 // and framebuffer, create a one shot sync object, and use it to determine when
1002 // the render pass has finished executing on GPU.
1003 if(instruction.mRenderTracker && instruction.mFrameBuffer)
1005 syncObject = instruction.mRenderTracker->CreateSyncObject(mImpl->graphicsController);
1006 instruction.mRenderTracker = nullptr;
1008 mainCommandBuffer->EndRenderPass(syncObject);
1010 mImpl->renderAlgorithms.SubmitCommandBuffer();
1012 std::sort(targetstoPresent.begin(), targetstoPresent.end());
1014 Graphics::RenderTarget* rt = nullptr;
1015 for(auto& target : targetstoPresent)
1019 mImpl->graphicsController.PresentRenderTarget(target);
1025 void RenderManager::PostRender(bool uploadOnly)
1027 // Notify RenderGeometries that rendering has finished
1028 for(auto&& iter : mImpl->geometryContainer)
1030 iter->OnRenderFinished();
1033 mImpl->UpdateTrackers();
1035 uint32_t count = 0u;
1036 for(auto& scene : mImpl->sceneContainer)
1038 count += scene->GetRenderInstructions().Count(mImpl->renderBufferIndex);
1041 const bool haveInstructions = count > 0u;
1043 // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
1044 mImpl->lastFrameWasRendered = haveInstructions;
1047 * The rendering has finished; swap to the next buffer.
1048 * Ideally the update has just finished using this buffer; otherwise the render thread
1049 * should block until the update has finished.
1051 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1053 DALI_PRINT_RENDER_END();
1056 } // namespace SceneGraph
1058 } // namespace Internal