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>
28 #include <dali/internal/event/common/scene-impl.h>
30 #include <dali/internal/update/common/scene-graph-scene.h>
31 #include <dali/internal/update/nodes/scene-graph-layer.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/pipeline-cache.h>
40 #include <dali/internal/render/renderers/render-frame-buffer.h>
41 #include <dali/internal/render/renderers/render-texture.h>
42 #include <dali/internal/render/renderers/shader-cache.h>
43 #include <dali/internal/render/renderers/uniform-buffer-manager.h>
44 #include <dali/internal/render/renderers/uniform-buffer-view-pool.h>
45 #include <dali/internal/render/shaders/program-controller.h>
55 #if defined(DEBUG_ENABLED)
58 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_MANAGER");
59 } // unnamed namespace
64 inline Graphics::Rect2D RecalculateScissorArea(Graphics::Rect2D scissorArea, int orientation, Rect<int32_t> viewportRect)
66 Graphics::Rect2D newScissorArea;
70 newScissorArea.x = viewportRect.height - (scissorArea.y + scissorArea.height);
71 newScissorArea.y = scissorArea.x;
72 newScissorArea.width = scissorArea.height;
73 newScissorArea.height = scissorArea.width;
75 else if(orientation == 180)
77 newScissorArea.x = viewportRect.width - (scissorArea.x + scissorArea.width);
78 newScissorArea.y = viewportRect.height - (scissorArea.y + scissorArea.height);
79 newScissorArea.width = scissorArea.width;
80 newScissorArea.height = scissorArea.height;
82 else if(orientation == 270)
84 newScissorArea.x = scissorArea.y;
85 newScissorArea.y = viewportRect.width - (scissorArea.x + scissorArea.width);
86 newScissorArea.width = scissorArea.height;
87 newScissorArea.height = scissorArea.width;
91 newScissorArea.x = scissorArea.x;
92 newScissorArea.y = scissorArea.y;
93 newScissorArea.width = scissorArea.width;
94 newScissorArea.height = scissorArea.height;
96 return newScissorArea;
100 * Structure to contain internal data
102 struct RenderManager::Impl
104 Impl(Graphics::Controller& graphicsController,
105 Integration::DepthBufferAvailable depthBufferAvailableParam,
106 Integration::StencilBufferAvailable stencilBufferAvailableParam,
107 Integration::PartialUpdateAvailable partialUpdateAvailableParam)
108 : graphicsController(graphicsController),
110 renderAlgorithms(graphicsController),
112 renderBufferIndex(SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX),
116 frameBufferContainer(),
117 lastFrameWasRendered(false),
118 programController(graphicsController),
119 shaderCache(graphicsController),
120 depthBufferAvailable(depthBufferAvailableParam),
121 stencilBufferAvailable(stencilBufferAvailableParam),
122 partialUpdateAvailable(partialUpdateAvailableParam)
124 // Create thread pool with just one thread ( there may be a need to create more threads in the future ).
125 threadPool = std::make_unique<Dali::ThreadPool>();
126 threadPool->Initialize(1u);
128 uniformBufferManager = std::make_unique<Render::UniformBufferManager>(&graphicsController);
129 pipelineCache = std::make_unique<Render::PipelineCache>(graphicsController);
134 threadPool.reset(nullptr); // reset now to maintain correct destruction order
137 void AddRenderTracker(Render::RenderTracker* renderTracker)
139 DALI_ASSERT_DEBUG(renderTracker != nullptr);
140 mRenderTrackers.PushBack(renderTracker);
143 void RemoveRenderTracker(Render::RenderTracker* renderTracker)
145 mRenderTrackers.EraseObject(renderTracker);
148 void UpdateTrackers()
150 for(auto&& iter : mRenderTrackers)
152 iter->PollSyncObject();
156 // the order is important for destruction,
157 Graphics::Controller& graphicsController;
158 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
160 std::vector<SceneGraph::Scene*> sceneContainer; ///< List of pointers to the scene graph objects of the scenes
162 Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
164 uint32_t frameCount; ///< The current frame count
165 BufferIndex renderBufferIndex; ///< The index of the buffer to read from; this is opposite of the "update" buffer
167 OwnerContainer<Render::Renderer*> rendererContainer; ///< List of owned renderers
168 OwnerContainer<Render::Sampler*> samplerContainer; ///< List of owned samplers
169 OwnerContainer<Render::Texture*> textureContainer; ///< List of owned textures
170 OwnerContainer<Render::FrameBuffer*> frameBufferContainer; ///< List of owned framebuffers
171 OwnerContainer<Render::VertexBuffer*> vertexBufferContainer; ///< List of owned vertex buffers
172 OwnerContainer<Render::Geometry*> geometryContainer; ///< List of owned Geometries
174 bool lastFrameWasRendered; ///< Keeps track of the last frame being rendered due to having render instructions
176 OwnerContainer<Render::RenderTracker*> mRenderTrackers; ///< List of render trackers
178 ProgramController programController; ///< Owner of the programs
179 Render::ShaderCache shaderCache; ///< The cache for the graphics shaders
181 std::unique_ptr<Render::UniformBufferManager> uniformBufferManager; ///< The uniform buffer manager
182 std::unique_ptr<Render::PipelineCache> pipelineCache;
184 Integration::DepthBufferAvailable depthBufferAvailable; ///< Whether the depth buffer is available
185 Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
186 Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
188 std::unique_ptr<Dali::ThreadPool> threadPool; ///< The thread pool
189 Vector<Graphics::Texture*> boundTextures; ///< The textures bound for rendering
190 Vector<Graphics::Texture*> textureDependencyList; ///< The dependency list of bound textures
193 RenderManager* RenderManager::New(Graphics::Controller& graphicsController,
194 Integration::DepthBufferAvailable depthBufferAvailable,
195 Integration::StencilBufferAvailable stencilBufferAvailable,
196 Integration::PartialUpdateAvailable partialUpdateAvailable)
198 auto* manager = new RenderManager;
199 manager->mImpl = new Impl(graphicsController,
200 depthBufferAvailable,
201 stencilBufferAvailable,
202 partialUpdateAvailable);
206 RenderManager::RenderManager()
211 RenderManager::~RenderManager()
216 RenderQueue& RenderManager::GetRenderQueue()
218 return mImpl->renderQueue;
221 void RenderManager::SetShaderSaver(ShaderSaver& upstream)
225 void RenderManager::AddRenderer(OwnerPointer<Render::Renderer>& renderer)
227 // Initialize the renderer as we are now in render thread
228 renderer->Initialize(mImpl->graphicsController, mImpl->programController, mImpl->shaderCache, *(mImpl->uniformBufferManager.get()), *(mImpl->pipelineCache.get()));
230 mImpl->rendererContainer.PushBack(renderer.Release());
233 void RenderManager::RemoveRenderer(Render::Renderer* renderer)
235 mImpl->rendererContainer.EraseObject(renderer);
238 void RenderManager::AddSampler(OwnerPointer<Render::Sampler>& sampler)
240 sampler->Initialize(mImpl->graphicsController);
241 mImpl->samplerContainer.PushBack(sampler.Release());
244 void RenderManager::RemoveSampler(Render::Sampler* sampler)
246 mImpl->samplerContainer.EraseObject(sampler);
249 void RenderManager::AddTexture(OwnerPointer<Render::Texture>& texture)
251 texture->Initialize(mImpl->graphicsController);
252 mImpl->textureContainer.PushBack(texture.Release());
255 void RenderManager::RemoveTexture(Render::Texture* texture)
257 DALI_ASSERT_DEBUG(NULL != texture);
259 // Find the texture, use reference to pointer so we can do the erase safely
260 for(auto&& iter : mImpl->textureContainer)
265 mImpl->textureContainer.Erase(&iter); // Texture found; now destroy it
271 void RenderManager::UploadTexture(Render::Texture* texture, PixelDataPtr pixelData, const Texture::UploadParams& params)
273 texture->Upload(pixelData, params);
276 void RenderManager::GenerateMipmaps(Render::Texture* texture)
278 texture->GenerateMipmaps();
281 void RenderManager::SetFilterMode(Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode)
283 sampler->SetFilterMode(static_cast<Dali::FilterMode::Type>(minFilterMode),
284 static_cast<Dali::FilterMode::Type>(magFilterMode));
287 void RenderManager::SetWrapMode(Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode)
289 sampler->SetWrapMode(static_cast<Dali::WrapMode::Type>(rWrapMode),
290 static_cast<Dali::WrapMode::Type>(sWrapMode),
291 static_cast<Dali::WrapMode::Type>(tWrapMode));
294 void RenderManager::AddFrameBuffer(OwnerPointer<Render::FrameBuffer>& frameBuffer)
296 Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
297 mImpl->frameBufferContainer.PushBack(frameBufferPtr);
298 frameBufferPtr->Initialize(mImpl->graphicsController);
301 void RenderManager::RemoveFrameBuffer(Render::FrameBuffer* frameBuffer)
303 DALI_ASSERT_DEBUG(nullptr != frameBuffer);
305 // Find the sampler, use reference so we can safely do the erase
306 for(auto&& iter : mImpl->frameBufferContainer)
308 if(iter == frameBuffer)
310 frameBuffer->Destroy();
311 mImpl->frameBufferContainer.Erase(&iter); // frameBuffer found; now destroy it
318 void RenderManager::InitializeScene(SceneGraph::Scene* scene)
320 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
321 mImpl->sceneContainer.push_back(scene);
324 void RenderManager::UninitializeScene(SceneGraph::Scene* scene)
326 auto iter = std::find(mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene);
327 if(iter != mImpl->sceneContainer.end())
329 mImpl->sceneContainer.erase(iter);
333 void RenderManager::SurfaceReplaced(SceneGraph::Scene* scene)
335 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
338 void RenderManager::AttachColorTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer)
340 frameBuffer->AttachColorTexture(texture, mipmapLevel, layer);
343 void RenderManager::AttachDepthTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
345 frameBuffer->AttachDepthTexture(texture, mipmapLevel);
348 void RenderManager::AttachDepthStencilTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
350 frameBuffer->AttachDepthStencilTexture(texture, mipmapLevel);
353 void RenderManager::AddVertexBuffer(OwnerPointer<Render::VertexBuffer>& vertexBuffer)
355 mImpl->vertexBufferContainer.PushBack(vertexBuffer.Release());
358 void RenderManager::RemoveVertexBuffer(Render::VertexBuffer* vertexBuffer)
360 mImpl->vertexBufferContainer.EraseObject(vertexBuffer);
363 void RenderManager::SetVertexBufferFormat(Render::VertexBuffer* vertexBuffer, OwnerPointer<Render::VertexBuffer::Format>& format)
365 vertexBuffer->SetFormat(format.Release());
368 void RenderManager::SetVertexBufferData(Render::VertexBuffer* vertexBuffer, OwnerPointer<Vector<uint8_t>>& data, uint32_t size)
370 vertexBuffer->SetData(data.Release(), size);
373 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Dali::Vector<uint16_t>& indices)
375 geometry->SetIndexBuffer(indices);
378 void RenderManager::AddGeometry(OwnerPointer<Render::Geometry>& geometry)
380 mImpl->geometryContainer.PushBack(geometry.Release());
383 void RenderManager::RemoveGeometry(Render::Geometry* geometry)
385 auto it = std::find_if(mImpl->geometryContainer.begin(), mImpl->geometryContainer.end(), [geometry](auto& item) {
386 return geometry == item;
389 if(it != mImpl->geometryContainer.end())
391 mImpl->geometryContainer.Erase(it);
395 void RenderManager::AttachVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
397 DALI_ASSERT_DEBUG(nullptr != geometry);
400 for(auto&& iter : mImpl->geometryContainer)
404 iter->AddVertexBuffer(vertexBuffer);
410 void RenderManager::RemoveVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
412 DALI_ASSERT_DEBUG(nullptr != geometry);
415 for(auto&& iter : mImpl->geometryContainer)
419 iter->RemoveVertexBuffer(vertexBuffer);
425 void RenderManager::SetGeometryType(Render::Geometry* geometry, uint32_t geometryType)
427 geometry->SetType(Render::Geometry::Type(geometryType));
430 void RenderManager::AddRenderTracker(Render::RenderTracker* renderTracker)
432 mImpl->AddRenderTracker(renderTracker);
435 void RenderManager::RemoveRenderTracker(Render::RenderTracker* renderTracker)
437 mImpl->RemoveRenderTracker(renderTracker);
440 void RenderManager::PreRender(Integration::RenderStatus& status, bool forceClear, bool uploadOnly)
442 DALI_PRINT_RENDER_START(mImpl->renderBufferIndex);
445 mImpl->uniformBufferManager->GetUniformBufferViewPool(mImpl->renderBufferIndex)->Rollback();
447 // Increment the frame count at the beginning of each frame
450 // Process messages queued during previous update
451 mImpl->renderQueue.ProcessMessages(mImpl->renderBufferIndex);
454 for(auto& i : mImpl->sceneContainer)
456 count += i->GetRenderInstructions().Count(mImpl->renderBufferIndex);
459 const bool haveInstructions = count > 0u;
461 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");
463 // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
464 if(haveInstructions || mImpl->lastFrameWasRendered || forceClear)
466 DALI_LOG_INFO(gLogFilter, Debug::General, "Render: Processing\n");
468 // Upload the geometries
469 for(auto&& geom : mImpl->geometryContainer)
471 geom->Upload(mImpl->graphicsController);
476 void RenderManager::PreRender(Integration::Scene& scene, std::vector<Rect<int>>& damagedRects)
478 if(mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
483 Internal::Scene& sceneInternal = GetImplementation(scene);
484 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
486 if(sceneObject->IsRenderingSkipped())
488 // We don't need to calculate dirty rects
492 class DamagedRectsCleaner
495 explicit DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects, Rect<int>& surfaceRect)
496 : mDamagedRects(damagedRects),
497 mSurfaceRect(surfaceRect),
502 void SetCleanOnReturn(bool cleanOnReturn)
504 mCleanOnReturn = cleanOnReturn;
507 ~DamagedRectsCleaner()
511 mDamagedRects.clear();
512 mDamagedRects.push_back(mSurfaceRect);
517 std::vector<Rect<int>>& mDamagedRects;
518 Rect<int> mSurfaceRect;
522 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
524 // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
525 DamagedRectsCleaner damagedRectCleaner(damagedRects, surfaceRect);
527 // Mark previous dirty rects in the sorted array. The array is already sorted by node and renderer, frame number.
528 // so you don't need to sort: std::stable_sort(itemsDirtyRects.begin(), itemsDirtyRects.end());
529 std::vector<DirtyRect>& itemsDirtyRects = sceneInternal.GetItemsDirtyRects();
530 for(DirtyRect& dirtyRect : itemsDirtyRects)
532 dirtyRect.visited = false;
535 uint32_t instructionCount = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
536 for(uint32_t i = 0; i < instructionCount; ++i)
538 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
540 if(instruction.mFrameBuffer)
542 return; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
545 const Camera* camera = instruction.GetCamera();
546 if(camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
548 const Node* node = instruction.GetCamera()->GetNode();
553 Quaternion orientation;
554 node->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
556 Vector3 orientationAxis;
557 Radian orientationAngle;
558 orientation.ToAxisAngle(orientationAxis, orientationAngle);
560 if(position.x > Math::MACHINE_EPSILON_10000 ||
561 position.y > Math::MACHINE_EPSILON_10000 ||
562 orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
563 orientationAngle != ANGLE_180 ||
564 scale != Vector3(1.0f, 1.0f, 1.0f))
575 Rect<int32_t> viewportRect;
576 if(instruction.mIsViewportSet)
578 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
579 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
580 if(viewportRect.IsEmpty() || !viewportRect.IsValid())
582 return; // just skip funny use cases for now, empty viewport means it is set somewhere else
587 viewportRect = surfaceRect;
590 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
591 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
592 if(viewMatrix && projectionMatrix)
594 const RenderListContainer::SizeType count = instruction.RenderListCount();
595 for(RenderListContainer::SizeType index = 0u; index < count; ++index)
597 const RenderList* renderList = instruction.GetRenderList(index);
600 if(!renderList->IsEmpty())
602 const std::size_t listCount = renderList->Count();
603 for(uint32_t listIndex = 0u; listIndex < listCount; ++listIndex)
605 RenderItem& item = renderList->GetItem(listIndex);
606 // If the item does 3D transformation, do early exit and clean the damaged rect array
607 if(item.mUpdateSize == Vector3::ZERO)
613 DirtyRect dirtyRect(item.mNode, item.mRenderer, mImpl->frameCount, rect);
614 // If the item refers to updated node or renderer.
615 if(item.mIsUpdated ||
617 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex, item.mNode)))))
619 item.mIsUpdated = false;
621 rect = RenderItem::CalculateViewportSpaceAABB(item.mModelViewMatrix, item.mUpdateSize, viewportRect.width, viewportRect.height);
622 if(rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
624 const int left = rect.x;
625 const int top = rect.y;
626 const int right = rect.x + rect.width;
627 const int bottom = rect.y + rect.height;
628 rect.x = (left / 16) * 16;
629 rect.y = (top / 16) * 16;
630 rect.width = ((right + 16) / 16) * 16 - rect.x;
631 rect.height = ((bottom + 16) / 16) * 16 - rect.y;
633 // Found valid dirty rect.
634 // 1. Insert it in the sorted array of the dirty rects.
635 // 2. Mark the related dirty rects as visited so they will not be removed below.
636 // 3. Keep only last 3 dirty rects for the same node and renderer (Tizen uses 3 back buffers, Ubuntu 1).
637 dirtyRect.rect = rect;
638 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
639 dirtyRectPos = itemsDirtyRects.insert(dirtyRectPos, dirtyRect);
642 while(++dirtyRectPos != itemsDirtyRects.end())
644 if(dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
649 dirtyRectPos->visited = true;
650 Rect<int>& dirtRect = dirtyRectPos->rect;
651 rect.Merge(dirtRect);
654 if(c > 3) // no more then 3 previous rects
656 itemsDirtyRects.erase(dirtyRectPos);
661 damagedRects.push_back(rect);
666 // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
667 // 2. Mark the related dirty rects as visited so they will not be removed below.
668 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
669 while(dirtyRectPos != itemsDirtyRects.end())
671 if(dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
676 dirtyRectPos->visited = true;
683 // Reset updated flag from the root
684 Layer* sourceLayer = renderList->GetSourceLayer();
687 sourceLayer->SetUpdatedTree(false);
694 // Check removed nodes or removed renderers dirty rects
695 auto i = itemsDirtyRects.begin();
696 auto j = itemsDirtyRects.begin();
697 while(i != itemsDirtyRects.end())
705 Rect<int>& dirtRect = i->rect;
706 damagedRects.push_back(dirtRect);
711 itemsDirtyRects.resize(j - itemsDirtyRects.begin());
712 damagedRectCleaner.SetCleanOnReturn(false);
715 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo)
717 Rect<int> clippingRect;
718 RenderScene(status, scene, renderToFbo, clippingRect);
721 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
723 if(mImpl->partialUpdateAvailable == Integration::PartialUpdateAvailable::TRUE && !renderToFbo && clippingRect.IsEmpty())
725 // ClippingRect is empty. Skip rendering
729 // Reset main algorithms command buffer
730 mImpl->renderAlgorithms.ResetCommandBuffer();
732 auto mainCommandBuffer = mImpl->renderAlgorithms.GetMainCommandBuffer();
734 Internal::Scene& sceneInternal = GetImplementation(scene);
735 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
737 uint32_t count = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
739 std::vector<Graphics::RenderTarget*> targetstoPresent;
741 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
742 if(clippingRect == surfaceRect)
744 // Full rendering case
745 // Make clippingRect empty because we're doing full rendering now if the clippingRect is empty.
746 // To reduce side effects, keep this logic now.
747 clippingRect = Rect<int>();
750 for(uint32_t i = 0; i < count; ++i)
752 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
754 if((renderToFbo && !instruction.mFrameBuffer) || (!renderToFbo && instruction.mFrameBuffer))
759 // Mark that we will require a post-render step to be performed (includes swap-buffers).
760 status.SetNeedsPostRender(true);
762 Rect<int32_t> viewportRect;
764 int32_t surfaceOrientation = sceneObject->GetSurfaceOrientation();
766 // @todo Should these be part of scene?
767 Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
768 Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
770 Graphics::RenderTarget* currentRenderTarget = nullptr;
771 Graphics::RenderPass* currentRenderPass = nullptr;
772 std::vector<Graphics::ClearValue> currentClearValues{};
774 if(instruction.mFrameBuffer)
776 // Ensure graphics framebuffer is created, bind attachments and create render passes
777 // Only happens once per framebuffer. If the create fails, e.g. no attachments yet,
778 // then don't render to this framebuffer.
779 if(!instruction.mFrameBuffer->GetGraphicsObject())
781 const bool created = instruction.mFrameBuffer->CreateGraphicsObjects();
788 auto& clearValues = instruction.mFrameBuffer->GetGraphicsRenderPassClearValues();
790 // Set the clear color for first color attachment
791 if(instruction.mIsClearColorSet && !clearValues.empty())
793 clearValues[0].color = {
794 instruction.mClearColor.r,
795 instruction.mClearColor.g,
796 instruction.mClearColor.b,
797 instruction.mClearColor.a};
800 currentClearValues = clearValues;
802 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
805 currentRenderTarget = instruction.mFrameBuffer->GetGraphicsRenderTarget();
806 currentRenderPass = instruction.mFrameBuffer->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
808 else // no framebuffer
811 auto& clearValues = sceneObject->GetGraphicsRenderPassClearValues();
813 if(instruction.mIsClearColorSet)
815 clearValues[0].color = {
816 instruction.mClearColor.r,
817 instruction.mClearColor.g,
818 instruction.mClearColor.b,
819 instruction.mClearColor.a};
822 currentClearValues = clearValues;
824 // @todo SceneObject should already have the depth clear / stencil clear in the clearValues array.
825 // if the window has a depth/stencil buffer.
826 if((depthBufferAvailable == Integration::DepthBufferAvailable::TRUE ||
827 stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE) &&
828 (currentClearValues.size() <= 1))
830 currentClearValues.emplace_back();
831 currentClearValues.back().depthStencil.depth = 0;
832 currentClearValues.back().depthStencil.stencil = 0;
835 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
837 currentRenderTarget = sceneObject->GetSurfaceRenderTarget();
838 currentRenderPass = sceneObject->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
841 targetstoPresent.emplace_back(currentRenderTarget);
843 // reset the program matrices for all programs once per frame
844 // this ensures we will set view and projection matrix once per program per camera
845 mImpl->programController.ResetProgramMatrices();
847 if(instruction.mFrameBuffer)
849 // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
850 for(unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
852 mImpl->textureDependencyList.PushBack(instruction.mFrameBuffer->GetTexture(i0));
856 if(!instruction.mIgnoreRenderToFbo && (instruction.mFrameBuffer != nullptr))
858 // Offscreen buffer rendering
859 if(instruction.mIsViewportSet)
861 // For Viewport the lower-left corner is (0,0)
862 const int32_t y = (instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height) - instruction.mViewport.y;
863 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
867 viewportRect.Set(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
869 surfaceOrientation = 0;
871 else // No Offscreen frame buffer rendering
873 // Check whether a viewport is specified, otherwise the full surface size is used
874 if(instruction.mIsViewportSet)
876 // For Viewport the lower-left corner is (0,0)
877 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
878 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
882 viewportRect = surfaceRect;
886 // Set surface orientation
887 // @todo Inform graphics impl by another route.
888 // was: mImpl->currentContext->SetSurfaceOrientation(surfaceOrientation);
890 /*** Clear region of framebuffer or surface before drawing ***/
891 bool clearFullFrameRect = (surfaceRect == viewportRect);
892 if(instruction.mFrameBuffer != nullptr)
894 Viewport frameRect(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
895 clearFullFrameRect = (frameRect == viewportRect);
898 if(!clippingRect.IsEmpty())
900 if(!clippingRect.Intersect(viewportRect))
902 DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
903 clippingRect = Rect<int>();
905 clearFullFrameRect = false;
908 Graphics::Rect2D scissorArea{viewportRect.x, viewportRect.y, uint32_t(viewportRect.width), uint32_t(viewportRect.height)};
909 if(instruction.mIsClearColorSet)
911 if(!clearFullFrameRect)
913 if(!clippingRect.IsEmpty())
915 scissorArea = {clippingRect.x, clippingRect.y, uint32_t(clippingRect.width), uint32_t(clippingRect.height)};
920 // Scissor's value should be set based on the default system coordinates.
921 // When the surface is rotated, the input values already were set with the rotated angle.
922 // So, re-calculation is needed.
923 scissorArea = RecalculateScissorArea(scissorArea, surfaceOrientation, viewportRect);
926 mainCommandBuffer->BeginRenderPass(
932 mainCommandBuffer->SetViewport({float(viewportRect.x),
933 float(viewportRect.y),
934 float(viewportRect.width),
935 float(viewportRect.height)});
937 // Clear the list of bound textures
938 mImpl->boundTextures.Clear();
940 mImpl->renderAlgorithms.ProcessRenderInstruction(
942 mImpl->renderBufferIndex,
943 depthBufferAvailable,
944 stencilBufferAvailable,
945 mImpl->boundTextures,
950 Graphics::SyncObject* syncObject{nullptr};
951 // If the render instruction has an associated render tracker (owned separately)
952 // and framebuffer, create a one shot sync object, and use it to determine when
953 // the render pass has finished executing on GPU.
954 if(instruction.mRenderTracker && instruction.mFrameBuffer)
956 syncObject = instruction.mRenderTracker->CreateSyncObject(mImpl->graphicsController);
957 instruction.mRenderTracker = nullptr;
959 mainCommandBuffer->EndRenderPass(syncObject);
961 mImpl->renderAlgorithms.SubmitCommandBuffer();
963 std::sort(targetstoPresent.begin(), targetstoPresent.end());
965 Graphics::RenderTarget* rt = nullptr;
966 for(auto& target : targetstoPresent)
970 mImpl->graphicsController.PresentRenderTarget(target);
976 void RenderManager::PostRender(bool uploadOnly)
978 // Notify RenderGeometries that rendering has finished
979 for(auto&& iter : mImpl->geometryContainer)
981 iter->OnRenderFinished();
984 mImpl->UpdateTrackers();
987 for(auto& scene : mImpl->sceneContainer)
989 count += scene->GetRenderInstructions().Count(mImpl->renderBufferIndex);
992 const bool haveInstructions = count > 0u;
994 // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
995 mImpl->lastFrameWasRendered = haveInstructions;
998 * The rendering has finished; swap to the next buffer.
999 * Ideally the update has just finished using this buffer; otherwise the render thread
1000 * should block until the update has finished.
1002 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1004 DALI_PRINT_RENDER_END();
1007 } // namespace SceneGraph
1009 } // namespace Internal