2 * Copyright (c) 2023 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/internal/common/ordered-set.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/nodes/scene-graph-layer.h>
33 #include <dali/internal/update/render-tasks/scene-graph-camera.h>
35 #include <dali/internal/common/owner-key-container.h>
37 #include <dali/internal/render/common/render-algorithms.h>
38 #include <dali/internal/render/common/render-debug.h>
39 #include <dali/internal/render/common/render-instruction.h>
40 #include <dali/internal/render/common/render-tracker.h>
41 #include <dali/internal/render/queue/render-queue.h>
42 #include <dali/internal/render/renderers/pipeline-cache.h>
43 #include <dali/internal/render/renderers/render-frame-buffer.h>
44 #include <dali/internal/render/renderers/render-texture.h>
45 #include <dali/internal/render/renderers/shader-cache.h>
46 #include <dali/internal/render/renderers/uniform-buffer-manager.h>
47 #include <dali/internal/render/renderers/uniform-buffer-view-pool.h>
48 #include <dali/internal/render/shaders/program-controller.h>
58 #if defined(DEBUG_ENABLED)
61 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_MANAGER");
62 } // unnamed namespace
67 inline Graphics::Rect2D RecalculateScissorArea(Graphics::Rect2D scissorArea, int orientation, Rect<int32_t> viewportRect)
69 Graphics::Rect2D newScissorArea;
73 newScissorArea.x = viewportRect.height - (scissorArea.y + scissorArea.height);
74 newScissorArea.y = scissorArea.x;
75 newScissorArea.width = scissorArea.height;
76 newScissorArea.height = scissorArea.width;
78 else if(orientation == 180)
80 newScissorArea.x = viewportRect.width - (scissorArea.x + scissorArea.width);
81 newScissorArea.y = viewportRect.height - (scissorArea.y + scissorArea.height);
82 newScissorArea.width = scissorArea.width;
83 newScissorArea.height = scissorArea.height;
85 else if(orientation == 270)
87 newScissorArea.x = scissorArea.y;
88 newScissorArea.y = viewportRect.width - (scissorArea.x + scissorArea.width);
89 newScissorArea.width = scissorArea.height;
90 newScissorArea.height = scissorArea.width;
94 newScissorArea.x = scissorArea.x;
95 newScissorArea.y = scissorArea.y;
96 newScissorArea.width = scissorArea.width;
97 newScissorArea.height = scissorArea.height;
99 return newScissorArea;
104 * Structure to contain internal data
106 struct RenderManager::Impl
108 Impl(Graphics::Controller& graphicsController,
109 Integration::DepthBufferAvailable depthBufferAvailableParam,
110 Integration::StencilBufferAvailable stencilBufferAvailableParam,
111 Integration::PartialUpdateAvailable partialUpdateAvailableParam)
112 : graphicsController(graphicsController),
113 renderAlgorithms(graphicsController),
114 programController(graphicsController),
115 shaderCache(graphicsController),
116 depthBufferAvailable(depthBufferAvailableParam),
117 stencilBufferAvailable(stencilBufferAvailableParam),
118 partialUpdateAvailable(partialUpdateAvailableParam)
120 // Create thread pool with just one thread ( there may be a need to create more threads in the future ).
121 threadPool = std::make_unique<Dali::ThreadPool>();
122 threadPool->Initialize(1u);
124 uniformBufferManager = std::make_unique<Render::UniformBufferManager>(&graphicsController);
125 pipelineCache = std::make_unique<Render::PipelineCache>(graphicsController);
130 threadPool.reset(nullptr); // reset now to maintain correct destruction order
133 void AddRenderTracker(Render::RenderTracker* renderTracker)
135 DALI_ASSERT_DEBUG(renderTracker != nullptr);
136 mRenderTrackers.PushBack(renderTracker);
139 void RemoveRenderTracker(Render::RenderTracker* renderTracker)
141 mRenderTrackers.EraseObject(renderTracker);
144 void UpdateTrackers()
146 for(auto&& iter : mRenderTrackers)
148 iter->PollSyncObject();
152 // the order is important for destruction,
153 Graphics::Controller& graphicsController;
154 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
155 std::vector<SceneGraph::Scene*> sceneContainer; ///< List of pointers to the scene graph objects of the scenes
156 Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
158 OrderedSet<Render::Sampler> samplerContainer; ///< List of owned samplers
159 OrderedSet<Render::FrameBuffer> frameBufferContainer; ///< List of owned framebuffers
160 OrderedSet<Render::VertexBuffer> vertexBufferContainer; ///< List of owned vertex buffers
161 OrderedSet<Render::Geometry> geometryContainer; ///< List of owned Geometries
162 OwnerKeyContainer<Render::Renderer> rendererContainer; ///< List of owned renderers
163 OwnerKeyContainer<Render::Texture> textureContainer; ///< List of owned textures
165 OrderedSet<Render::RenderTracker> mRenderTrackers; ///< List of owned render trackers
167 ProgramController programController; ///< Owner of the programs
168 Render::ShaderCache shaderCache; ///< The cache for the graphics shaders
170 std::unique_ptr<Render::UniformBufferManager> uniformBufferManager; ///< The uniform buffer manager
171 std::unique_ptr<Render::PipelineCache> pipelineCache;
173 Integration::DepthBufferAvailable depthBufferAvailable; ///< Whether the depth buffer is available
174 Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
175 Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
177 std::unique_ptr<Dali::ThreadPool> threadPool; ///< The thread pool
178 Vector<Graphics::Texture*> boundTextures; ///< The textures bound for rendering
179 Vector<Graphics::Texture*> textureDependencyList; ///< The dependency list of bound textures
181 uint32_t frameCount{0u}; ///< The current frame count
182 BufferIndex renderBufferIndex{SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX}; ///< The index of the buffer to read from; this is opposite of the "update" buffer
184 bool lastFrameWasRendered{false}; ///< Keeps track of the last frame being rendered due to having render instructions
185 bool commandBufferSubmitted{false};
188 RenderManager* RenderManager::New(Graphics::Controller& graphicsController,
189 Integration::DepthBufferAvailable depthBufferAvailable,
190 Integration::StencilBufferAvailable stencilBufferAvailable,
191 Integration::PartialUpdateAvailable partialUpdateAvailable)
193 auto* manager = new RenderManager;
194 manager->mImpl = new Impl(graphicsController,
195 depthBufferAvailable,
196 stencilBufferAvailable,
197 partialUpdateAvailable);
201 RenderManager::RenderManager()
206 RenderManager::~RenderManager()
211 RenderQueue& RenderManager::GetRenderQueue()
213 return mImpl->renderQueue;
216 void RenderManager::SetShaderSaver(ShaderSaver& upstream)
220 void RenderManager::AddRenderer(const Render::RendererKey& renderer)
222 // Initialize the renderer as we are now in render thread
223 renderer->Initialize(mImpl->graphicsController, mImpl->programController, mImpl->shaderCache, *(mImpl->uniformBufferManager.get()), *(mImpl->pipelineCache.get()));
225 mImpl->rendererContainer.PushBack(renderer);
228 void RenderManager::RemoveRenderer(const Render::RendererKey& renderer)
230 mImpl->rendererContainer.EraseKey(renderer);
233 void RenderManager::AddSampler(OwnerPointer<Render::Sampler>& sampler)
235 sampler->Initialize(mImpl->graphicsController);
236 mImpl->samplerContainer.PushBack(sampler.Release());
239 void RenderManager::RemoveSampler(Render::Sampler* sampler)
241 mImpl->samplerContainer.EraseObject(sampler);
244 void RenderManager::AddTexture(const Render::TextureKey& textureKey)
246 DALI_ASSERT_DEBUG(textureKey && "Trying to add empty texture key");
248 textureKey->Initialize(mImpl->graphicsController);
249 mImpl->textureContainer.PushBack(textureKey);
252 void RenderManager::RemoveTexture(const Render::TextureKey& textureKey)
254 DALI_ASSERT_DEBUG(textureKey && "Trying to remove empty texture key");
256 // Find the texture, use std::find so we can do the erase by iterator safely
257 auto iter = std::find(mImpl->textureContainer.Begin(), mImpl->textureContainer.End(), textureKey);
259 if(iter != mImpl->textureContainer.End())
261 textureKey->Destroy();
262 mImpl->textureContainer.Erase(iter); // Texture found; now destroy it
266 void RenderManager::UploadTexture(const Render::TextureKey& textureKey, PixelDataPtr pixelData, const Texture::UploadParams& params)
268 DALI_ASSERT_DEBUG(textureKey && "Trying to upload to empty texture key");
269 textureKey->Upload(pixelData, params);
272 void RenderManager::GenerateMipmaps(const Render::TextureKey& textureKey)
274 DALI_ASSERT_DEBUG(textureKey && "Trying to generate mipmaps on empty texture key");
275 textureKey->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 framebuffer, use OrderedSet.Find so we can safely do the erase
303 auto iter = mImpl->frameBufferContainer.Find(frameBuffer);
305 if(iter != mImpl->frameBufferContainer.End())
307 frameBuffer->Destroy();
308 mImpl->frameBufferContainer.Erase(iter); // frameBuffer found; now destroy it
312 void RenderManager::InitializeScene(SceneGraph::Scene* scene)
314 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
315 mImpl->sceneContainer.push_back(scene);
318 void RenderManager::UninitializeScene(SceneGraph::Scene* scene)
320 auto iter = std::find(mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene);
321 if(iter != mImpl->sceneContainer.end())
323 mImpl->sceneContainer.erase(iter);
327 void RenderManager::SurfaceReplaced(SceneGraph::Scene* scene)
329 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
332 void RenderManager::AttachColorTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer)
334 frameBuffer->AttachColorTexture(texture, mipmapLevel, layer);
337 void RenderManager::AttachDepthTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
339 frameBuffer->AttachDepthTexture(texture, mipmapLevel);
342 void RenderManager::AttachDepthStencilTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
344 frameBuffer->AttachDepthStencilTexture(texture, mipmapLevel);
347 void RenderManager::SetMultiSamplingLevelToFrameBuffer(Render::FrameBuffer* frameBuffer, uint8_t multiSamplingLevel)
349 frameBuffer->SetMultiSamplingLevel(multiSamplingLevel);
352 void RenderManager::AddVertexBuffer(OwnerPointer<Render::VertexBuffer>& vertexBuffer)
354 mImpl->vertexBufferContainer.PushBack(vertexBuffer.Release());
357 void RenderManager::RemoveVertexBuffer(Render::VertexBuffer* vertexBuffer)
359 mImpl->vertexBufferContainer.EraseObject(vertexBuffer);
362 void RenderManager::SetVertexBufferFormat(Render::VertexBuffer* vertexBuffer, OwnerPointer<Render::VertexBuffer::Format>& format)
364 vertexBuffer->SetFormat(format.Release());
367 void RenderManager::SetVertexBufferData(Render::VertexBuffer* vertexBuffer, OwnerPointer<Vector<uint8_t>>& data, uint32_t size)
369 vertexBuffer->SetData(data.Release(), size);
372 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Render::Geometry::Uint16ContainerType& indices)
374 geometry->SetIndexBuffer(indices);
377 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Render::Geometry::Uint32ContainerType& indices)
379 geometry->SetIndexBuffer(indices);
382 void RenderManager::AddGeometry(OwnerPointer<Render::Geometry>& geometry)
384 mImpl->geometryContainer.PushBack(geometry.Release());
387 void RenderManager::RemoveGeometry(Render::Geometry* geometry)
389 mImpl->geometryContainer.EraseObject(geometry);
392 void RenderManager::AttachVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
394 geometry->AddVertexBuffer(vertexBuffer);
397 void RenderManager::RemoveVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
399 geometry->RemoveVertexBuffer(vertexBuffer);
402 void RenderManager::SetGeometryType(Render::Geometry* geometry, uint32_t geometryType)
404 geometry->SetType(Render::Geometry::Type(geometryType));
407 void RenderManager::AddRenderTracker(Render::RenderTracker* renderTracker)
409 mImpl->AddRenderTracker(renderTracker);
412 void RenderManager::RemoveRenderTracker(Render::RenderTracker* renderTracker)
414 mImpl->RemoveRenderTracker(renderTracker);
417 void RenderManager::PreRender(Integration::RenderStatus& status, bool forceClear)
419 DALI_PRINT_RENDER_START(mImpl->renderBufferIndex);
422 mImpl->uniformBufferManager->GetUniformBufferViewPool(mImpl->renderBufferIndex)->Rollback();
424 // Increment the frame count at the beginning of each frame
427 // Process messages queued during previous update
428 mImpl->renderQueue.ProcessMessages(mImpl->renderBufferIndex);
431 for(auto& i : mImpl->sceneContainer)
433 count += i->GetRenderInstructions().Count(mImpl->renderBufferIndex);
436 const bool haveInstructions = count > 0u;
438 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");
440 // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
441 if(haveInstructions || mImpl->lastFrameWasRendered || forceClear)
443 DALI_LOG_INFO(gLogFilter, Debug::General, "Render: Processing\n");
445 // Upload the geometries
446 for(auto&& geom : mImpl->geometryContainer)
448 geom->Upload(mImpl->graphicsController);
452 mImpl->commandBufferSubmitted = false;
455 void RenderManager::PreRender(Integration::Scene& scene, std::vector<Rect<int>>& damagedRects)
457 if(mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
462 Internal::Scene& sceneInternal = GetImplementation(scene);
463 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
465 if(!sceneObject || sceneObject->IsRenderingSkipped())
467 // We don't need to calculate dirty rects
471 class DamagedRectsCleaner
474 explicit DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects, Rect<int>& surfaceRect)
475 : mDamagedRects(damagedRects),
476 mSurfaceRect(surfaceRect),
481 void SetCleanOnReturn(bool cleanOnReturn)
483 mCleanOnReturn = cleanOnReturn;
486 ~DamagedRectsCleaner()
490 mDamagedRects.clear();
491 mDamagedRects.push_back(mSurfaceRect);
496 std::vector<Rect<int>>& mDamagedRects;
497 Rect<int> mSurfaceRect;
501 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
503 // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
504 DamagedRectsCleaner damagedRectCleaner(damagedRects, surfaceRect);
505 bool cleanDamagedRect = false;
507 // Mark previous dirty rects in the std::unordered_map.
508 Scene::ItemsDirtyRectsContainer& itemsDirtyRects = sceneObject->GetItemsDirtyRects();
509 for(auto& dirtyRectPair : itemsDirtyRects)
511 dirtyRectPair.second.visited = false;
514 uint32_t instructionCount = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
515 for(uint32_t i = 0; i < instructionCount; ++i)
517 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
519 if(instruction.mFrameBuffer)
521 cleanDamagedRect = true;
522 continue; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
525 const Camera* camera = instruction.GetCamera();
526 if(camera && camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
530 Quaternion orientation;
531 camera->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
533 Vector3 orientationAxis;
534 Radian orientationAngle;
535 orientation.ToAxisAngle(orientationAxis, orientationAngle);
537 if(position.x > Math::MACHINE_EPSILON_10000 ||
538 position.y > Math::MACHINE_EPSILON_10000 ||
539 orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
540 orientationAngle != ANGLE_180 ||
541 scale != Vector3(1.0f, 1.0f, 1.0f))
543 cleanDamagedRect = true;
549 cleanDamagedRect = true;
553 Rect<int32_t> viewportRect;
554 if(instruction.mIsViewportSet)
556 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
557 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
558 if(viewportRect.IsEmpty() || !viewportRect.IsValid())
560 cleanDamagedRect = true;
561 continue; // just skip funny use cases for now, empty viewport means it is set somewhere else
566 viewportRect = surfaceRect;
569 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
570 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
571 if(viewMatrix && projectionMatrix)
573 const RenderListContainer::SizeType count = instruction.RenderListCount();
574 for(RenderListContainer::SizeType index = 0u; index < count; ++index)
576 const RenderList* renderList = instruction.GetRenderList(index);
579 if(!renderList->IsEmpty())
581 const std::size_t listCount = renderList->Count();
582 for(uint32_t listIndex = 0u; listIndex < listCount; ++listIndex)
584 RenderItem& item = renderList->GetItem(listIndex);
585 // If the item does 3D transformation, make full update
586 if(item.mUpdateArea == Vector4::ZERO)
588 cleanDamagedRect = true;
590 // Save the full rect in the damaged list. We need it when this item is removed
591 DirtyRectKey dirtyRectKey(item.mNode, item.mRenderer);
592 auto dirtyRectPos = itemsDirtyRects.find(dirtyRectKey);
593 if(dirtyRectPos != itemsDirtyRects.end())
596 dirtyRectPos->second.visited = true;
597 dirtyRectPos->second.rect = surfaceRect;
601 // Else, just insert the new dirtyrect
602 itemsDirtyRects.insert({dirtyRectKey, surfaceRect});
608 DirtyRectKey dirtyRectKey(item.mNode, item.mRenderer);
609 // If the item refers to updated node or renderer.
610 if(item.mIsUpdated ||
612 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex)))))
614 item.mIsUpdated = false;
616 Vector4 updateArea = item.mRenderer ? item.mRenderer->GetVisualTransformedUpdateArea(mImpl->renderBufferIndex, item.mUpdateArea) : item.mUpdateArea;
618 rect = RenderItem::CalculateViewportSpaceAABB(item.mModelViewMatrix, Vector3(updateArea.x, updateArea.y, 0.0f), Vector3(updateArea.z, updateArea.w, 0.0f), viewportRect.width, viewportRect.height);
619 if(rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
621 const int left = rect.x;
622 const int top = rect.y;
623 const int right = rect.x + rect.width;
624 const int bottom = rect.y + rect.height;
625 rect.x = (left / 16) * 16;
626 rect.y = (top / 16) * 16;
627 rect.width = ((right + 16) / 16) * 16 - rect.x;
628 rect.height = ((bottom + 16) / 16) * 16 - rect.y;
630 // Found valid dirty rect.
631 auto dirtyRectPos = itemsDirtyRects.find(dirtyRectKey);
632 if(dirtyRectPos != itemsDirtyRects.end())
634 Rect<int> currentRect = rect;
636 // Same item, merge it with the previous rect
637 rect.Merge(dirtyRectPos->second.rect);
639 // Replace the rect as current
640 dirtyRectPos->second.visited = true;
641 dirtyRectPos->second.rect = currentRect;
645 // Else, just insert the new dirtyrect
646 itemsDirtyRects.insert({dirtyRectKey, rect});
649 damagedRects.push_back(rect);
654 // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
655 // 2. Mark the related dirty rects as visited so they will not be removed below.
656 auto dirtyRectPos = itemsDirtyRects.find(dirtyRectKey);
657 if(dirtyRectPos != itemsDirtyRects.end())
659 dirtyRectPos->second.visited = true;
663 // The item is not in the list for some reason. Add it!
664 itemsDirtyRects.insert({dirtyRectKey, surfaceRect});
665 cleanDamagedRect = true; // And make full update at this frame
675 // Check removed nodes or removed renderers dirty rects
676 // Note, std::unordered_map end iterator is validate if we call erase.
677 for(auto iter = itemsDirtyRects.cbegin(), iterEnd = itemsDirtyRects.cend(); iter != iterEnd;)
679 if(!iter->second.visited)
681 damagedRects.push_back(iter->second.rect);
682 iter = itemsDirtyRects.erase(iter);
690 if(!cleanDamagedRect)
692 damagedRectCleaner.SetCleanOnReturn(false);
696 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo)
698 SceneGraph::Scene* sceneObject = GetImplementation(scene).GetSceneObject();
704 Rect<int> clippingRect = sceneObject->GetSurfaceRect();
705 RenderScene(status, scene, renderToFbo, clippingRect);
708 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
710 if(mImpl->partialUpdateAvailable == Integration::PartialUpdateAvailable::TRUE && !renderToFbo && clippingRect.IsEmpty())
712 // ClippingRect is empty. Skip rendering
716 // Reset main algorithms command buffer
717 mImpl->renderAlgorithms.ResetCommandBuffer();
719 auto mainCommandBuffer = mImpl->renderAlgorithms.GetMainCommandBuffer();
721 Internal::Scene& sceneInternal = GetImplementation(scene);
722 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
728 uint32_t count = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
730 std::vector<Graphics::RenderTarget*> targetstoPresent;
732 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
733 if(clippingRect == surfaceRect)
735 // Full rendering case
736 // Make clippingRect empty because we're doing full rendering now if the clippingRect is empty.
737 // To reduce side effects, keep this logic now.
738 clippingRect = Rect<int>();
741 // Prepare to lock and map standalone uniform buffer.
742 mImpl->uniformBufferManager->ReadyToLockUniformBuffer(mImpl->renderBufferIndex);
744 for(uint32_t i = 0; i < count; ++i)
746 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
748 if((renderToFbo && !instruction.mFrameBuffer) || (!renderToFbo && instruction.mFrameBuffer))
753 // Mark that we will require a post-render step to be performed (includes swap-buffers).
754 status.SetNeedsPostRender(true);
756 Rect<int32_t> viewportRect;
758 int32_t surfaceOrientation = sceneObject->GetSurfaceOrientation() + sceneObject->GetScreenOrientation();
759 if(surfaceOrientation >= 360)
761 surfaceOrientation -= 360;
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 Viewport 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 Viewport 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, surfaceRect);
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,
947 Uint16Pair(surfaceRect.width, surfaceRect.height));
949 Graphics::SyncObject* syncObject{nullptr};
950 // If the render instruction has an associated render tracker (owned separately)
951 // and framebuffer, create a one shot sync object, and use it to determine when
952 // the render pass has finished executing on GPU.
953 if(instruction.mRenderTracker && instruction.mFrameBuffer)
955 syncObject = instruction.mRenderTracker->CreateSyncObject(mImpl->graphicsController);
956 instruction.mRenderTracker = nullptr;
958 mainCommandBuffer->EndRenderPass(syncObject);
961 // Unlock standalone uniform buffer.
962 mImpl->uniformBufferManager->UnlockUniformBuffer(mImpl->renderBufferIndex);
964 mImpl->renderAlgorithms.SubmitCommandBuffer();
965 mImpl->commandBufferSubmitted = true;
967 std::sort(targetstoPresent.begin(), targetstoPresent.end());
969 Graphics::RenderTarget* rt = nullptr;
970 for(auto& target : targetstoPresent)
974 mImpl->graphicsController.PresentRenderTarget(target);
980 void RenderManager::PostRender()
982 if(!mImpl->commandBufferSubmitted)
984 // Rendering is skipped but there may be pending tasks. Flush them.
985 Graphics::SubmitInfo submitInfo;
986 submitInfo.cmdBuffer.clear(); // Only flush
987 submitInfo.flags = 0 | Graphics::SubmitFlagBits::FLUSH;
988 mImpl->graphicsController.SubmitCommandBuffers(submitInfo);
990 mImpl->commandBufferSubmitted = true;
993 // Notify RenderGeometries that rendering has finished
994 for(auto&& iter : mImpl->geometryContainer)
996 iter->OnRenderFinished();
999 // Notify RenderTexture that rendering has finished
1000 for(auto&& iter : mImpl->textureContainer)
1002 iter->OnRenderFinished();
1005 mImpl->UpdateTrackers();
1007 uint32_t count = 0u;
1008 for(auto& scene : mImpl->sceneContainer)
1010 count += scene->GetRenderInstructions().Count(mImpl->renderBufferIndex);
1013 const bool haveInstructions = count > 0u;
1015 // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
1016 mImpl->lastFrameWasRendered = haveInstructions;
1019 * The rendering has finished; swap to the next buffer.
1020 * Ideally the update has just finished using this buffer; otherwise the render thread
1021 * should block until the update has finished.
1023 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1025 DALI_PRINT_RENDER_END();
1028 } // namespace SceneGraph
1030 } // namespace Internal