2 * Copyright (c) 2024 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/integration-api/core.h>
26 #include <dali/internal/common/ordered-set.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/common/owner-key-container.h>
36 #include <dali/internal/render/common/render-algorithms.h>
37 #include <dali/internal/render/common/render-debug.h>
38 #include <dali/internal/render/common/render-instruction.h>
39 #include <dali/internal/render/common/render-tracker.h>
40 #include <dali/internal/render/queue/render-queue.h>
41 #include <dali/internal/render/renderers/pipeline-cache.h>
42 #include <dali/internal/render/renderers/render-frame-buffer.h>
43 #include <dali/internal/render/renderers/render-texture.h>
44 #include <dali/internal/render/renderers/uniform-buffer-manager.h>
45 #include <dali/internal/render/renderers/uniform-buffer.h>
46 #include <dali/internal/render/shaders/program-controller.h>
56 #if defined(DEBUG_ENABLED)
59 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_MANAGER");
60 } // unnamed namespace
65 // TODO : Cache clean logic have some problem now. Just block it until bug resolved
66 //constexpr uint32_t CACHE_CLEAN_FRAME_COUNT = 600u; // 60fps * 10sec
68 inline Graphics::Rect2D RecalculateScissorArea(const Graphics::Rect2D& scissorArea, int orientation, const Rect<int32_t>& viewportRect)
70 Graphics::Rect2D newScissorArea;
74 newScissorArea.x = viewportRect.height - (scissorArea.y + scissorArea.height);
75 newScissorArea.y = scissorArea.x;
76 newScissorArea.width = scissorArea.height;
77 newScissorArea.height = scissorArea.width;
79 else if(orientation == 180)
81 newScissorArea.x = viewportRect.width - (scissorArea.x + scissorArea.width);
82 newScissorArea.y = viewportRect.height - (scissorArea.y + scissorArea.height);
83 newScissorArea.width = scissorArea.width;
84 newScissorArea.height = scissorArea.height;
86 else if(orientation == 270)
88 newScissorArea.x = scissorArea.y;
89 newScissorArea.y = viewportRect.width - (scissorArea.x + scissorArea.width);
90 newScissorArea.width = scissorArea.height;
91 newScissorArea.height = scissorArea.width;
95 newScissorArea.x = scissorArea.x;
96 newScissorArea.y = scissorArea.y;
97 newScissorArea.width = scissorArea.width;
98 newScissorArea.height = scissorArea.height;
100 return newScissorArea;
103 inline Rect<int32_t> CalculateUpdateArea(RenderItem& item, BufferIndex renderBufferIndex, const Rect<int32_t>& viewportRect)
106 if(item.mNode && item.mNode->IsTextureUpdateAreaUsed() && item.mRenderer)
108 updateArea = item.mRenderer->GetTextureUpdateArea();
112 updateArea = item.mRenderer ? item.mRenderer->GetVisualTransformedUpdateArea(renderBufferIndex, item.mUpdateArea) : item.mUpdateArea;
115 return RenderItem::CalculateViewportSpaceAABB(item.mModelViewMatrix, Vector3(updateArea.x, updateArea.y, 0.0f), Vector3(updateArea.z, updateArea.w, 0.0f), viewportRect.width, viewportRect.height);
118 inline void AlignDamagedRect(Rect<int32_t>& rect)
120 const int left = rect.x;
121 const int top = rect.y;
122 const int right = rect.x + rect.width;
123 const int bottom = rect.y + rect.height;
124 rect.x = (left / 16) * 16;
125 rect.y = (top / 16) * 16;
126 rect.width = ((right + 16) / 16) * 16 - rect.x;
127 rect.height = ((bottom + 16) / 16) * 16 - rect.y;
132 * Structure to contain internal data
134 struct RenderManager::Impl
136 Impl(Graphics::Controller& graphicsController,
137 Integration::DepthBufferAvailable depthBufferAvailableParam,
138 Integration::StencilBufferAvailable stencilBufferAvailableParam,
139 Integration::PartialUpdateAvailable partialUpdateAvailableParam)
140 : graphicsController(graphicsController),
141 renderAlgorithms(graphicsController),
142 programController(graphicsController),
143 depthBufferAvailable(depthBufferAvailableParam),
144 stencilBufferAvailable(stencilBufferAvailableParam),
145 partialUpdateAvailable(partialUpdateAvailableParam)
147 uniformBufferManager = std::make_unique<Render::UniformBufferManager>(&graphicsController);
148 pipelineCache = std::make_unique<Render::PipelineCache>(graphicsController);
153 rendererContainer.Clear(); // clear now before the pipeline cache is deleted
156 void AddRenderTracker(Render::RenderTracker* renderTracker)
158 DALI_ASSERT_DEBUG(renderTracker != nullptr);
159 mRenderTrackers.PushBack(renderTracker);
162 void RemoveRenderTracker(Render::RenderTracker* renderTracker)
164 mRenderTrackers.EraseObject(renderTracker);
167 void UpdateTrackers()
169 for(auto&& iter : mRenderTrackers)
171 iter->PollSyncObject();
175 // the order is important for destruction,
176 Graphics::Controller& graphicsController;
177 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
178 std::vector<SceneGraph::Scene*> sceneContainer; ///< List of pointers to the scene graph objects of the scenes
179 Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
181 OrderedSet<Render::Sampler> samplerContainer; ///< List of owned samplers
182 OrderedSet<Render::FrameBuffer> frameBufferContainer; ///< List of owned framebuffers
183 OrderedSet<Render::VertexBuffer> vertexBufferContainer; ///< List of owned vertex buffers
184 OrderedSet<Render::Geometry> geometryContainer; ///< List of owned Geometries
185 OwnerKeyContainer<Render::Renderer> rendererContainer; ///< List of owned renderers
186 OwnerKeyContainer<Render::Texture> textureContainer; ///< List of owned textures
188 OrderedSet<Render::RenderTracker> mRenderTrackers; ///< List of owned render trackers
190 OwnerKeyContainer<Render::Texture> textureDiscardQueue; ///< Discarded textures
192 ProgramController programController; ///< Owner of the programs
194 std::unique_ptr<Render::UniformBufferManager> uniformBufferManager; ///< The uniform buffer manager
195 std::unique_ptr<Render::PipelineCache> pipelineCache;
197 Integration::DepthBufferAvailable depthBufferAvailable; ///< Whether the depth buffer is available
198 Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
199 Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
201 Vector<Render::TextureKey> updatedTextures{}; ///< The updated texture list
203 uint32_t frameCount{0u}; ///< The current frame count
204 BufferIndex renderBufferIndex{SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX}; ///< The index of the buffer to read from;
206 bool lastFrameWasRendered{false}; ///< Keeps track of the last frame being rendered due to having render instructions
207 bool commandBufferSubmitted{false};
210 RenderManager* RenderManager::New(Graphics::Controller& graphicsController,
211 Integration::DepthBufferAvailable depthBufferAvailable,
212 Integration::StencilBufferAvailable stencilBufferAvailable,
213 Integration::PartialUpdateAvailable partialUpdateAvailable)
215 auto* manager = new RenderManager;
216 manager->mImpl = new Impl(graphicsController,
217 depthBufferAvailable,
218 stencilBufferAvailable,
219 partialUpdateAvailable);
223 RenderManager::RenderManager()
228 RenderManager::~RenderManager()
233 void RenderManager::ContextDestroyed()
235 mImpl->uniformBufferManager->ContextDestroyed();
238 RenderQueue& RenderManager::GetRenderQueue()
240 return mImpl->renderQueue;
243 void RenderManager::SetShaderSaver(ShaderSaver& upstream)
247 void RenderManager::AddRenderer(const Render::RendererKey& renderer)
249 // Initialize the renderer as we are now in render thread
250 renderer->Initialize(mImpl->graphicsController, mImpl->programController, *(mImpl->uniformBufferManager.get()), *(mImpl->pipelineCache.get()));
252 mImpl->rendererContainer.PushBack(renderer);
255 void RenderManager::RemoveRenderer(const Render::RendererKey& renderer)
257 mImpl->rendererContainer.EraseKey(renderer);
260 void RenderManager::AddSampler(OwnerPointer<Render::Sampler>& sampler)
262 sampler->Initialize(mImpl->graphicsController);
263 mImpl->samplerContainer.PushBack(sampler.Release());
266 void RenderManager::RemoveSampler(Render::Sampler* sampler)
268 mImpl->samplerContainer.EraseObject(sampler);
271 void RenderManager::AddTexture(const Render::TextureKey& textureKey)
273 DALI_ASSERT_DEBUG(textureKey && "Trying to add empty texture key");
275 textureKey->Initialize(mImpl->graphicsController, *this);
276 mImpl->textureContainer.PushBack(textureKey);
277 mImpl->updatedTextures.PushBack(textureKey);
280 void RenderManager::RemoveTexture(const Render::TextureKey& textureKey)
282 DALI_ASSERT_DEBUG(textureKey && "Trying to remove empty texture key");
284 // Find the texture, use std::find so we can do the erase by iterator safely
285 auto iter = std::find(mImpl->textureContainer.Begin(), mImpl->textureContainer.End(), textureKey);
287 if(iter != mImpl->textureContainer.End())
290 textureKey->Destroy();
292 // Transfer ownership to the discard queue, this keeps the object alive, until the render-thread has finished with it
293 mImpl->textureDiscardQueue.PushBack(mImpl->textureContainer.Release(iter));
297 void RenderManager::UploadTexture(const Render::TextureKey& textureKey, PixelDataPtr pixelData, const Graphics::UploadParams& params)
299 DALI_ASSERT_DEBUG(textureKey && "Trying to upload to empty texture key");
300 textureKey->Upload(pixelData, params);
302 mImpl->updatedTextures.PushBack(textureKey);
305 void RenderManager::GenerateMipmaps(const Render::TextureKey& textureKey)
307 DALI_ASSERT_DEBUG(textureKey && "Trying to generate mipmaps on empty texture key");
308 textureKey->GenerateMipmaps();
310 mImpl->updatedTextures.PushBack(textureKey);
313 void RenderManager::SetTextureSize(const Render::TextureKey& textureKey, const Dali::ImageDimensions& size)
315 DALI_ASSERT_DEBUG(textureKey && "Trying to set size on empty texture key");
316 textureKey->SetWidth(size.GetWidth());
317 textureKey->SetHeight(size.GetHeight());
320 void RenderManager::SetTextureFormat(const Render::TextureKey& textureKey, Dali::Pixel::Format pixelFormat)
322 DALI_ASSERT_DEBUG(textureKey && "Trying to set pixel format on empty texture key");
323 textureKey->SetPixelFormat(pixelFormat);
326 void RenderManager::SetTextureUpdated(const Render::TextureKey& textureKey)
328 DALI_ASSERT_DEBUG(textureKey && "Trying to set updated on empty texture key");
329 textureKey->SetUpdated(true);
331 mImpl->updatedTextures.PushBack(textureKey);
334 void RenderManager::SetFilterMode(Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode)
336 sampler->SetFilterMode(static_cast<Dali::FilterMode::Type>(minFilterMode),
337 static_cast<Dali::FilterMode::Type>(magFilterMode));
340 void RenderManager::SetWrapMode(Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode)
342 sampler->SetWrapMode(static_cast<Dali::WrapMode::Type>(rWrapMode),
343 static_cast<Dali::WrapMode::Type>(sWrapMode),
344 static_cast<Dali::WrapMode::Type>(tWrapMode));
347 void RenderManager::AddFrameBuffer(OwnerPointer<Render::FrameBuffer>& frameBuffer)
349 Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
350 mImpl->frameBufferContainer.PushBack(frameBufferPtr);
351 frameBufferPtr->Initialize(mImpl->graphicsController);
354 void RenderManager::RemoveFrameBuffer(Render::FrameBuffer* frameBuffer)
356 DALI_ASSERT_DEBUG(nullptr != frameBuffer);
358 // Find the framebuffer, use OrderedSet.Find so we can safely do the erase
359 auto iter = mImpl->frameBufferContainer.Find(frameBuffer);
361 if(iter != mImpl->frameBufferContainer.End())
363 frameBuffer->Destroy();
364 mImpl->frameBufferContainer.Erase(iter); // frameBuffer found; now destroy it
368 void RenderManager::InitializeScene(SceneGraph::Scene* scene)
370 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
371 mImpl->sceneContainer.push_back(scene);
372 mImpl->uniformBufferManager->RegisterScene(scene);
375 void RenderManager::UninitializeScene(SceneGraph::Scene* scene)
377 mImpl->uniformBufferManager->UnregisterScene(scene);
378 auto iter = std::find(mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene);
379 if(iter != mImpl->sceneContainer.end())
381 mImpl->sceneContainer.erase(iter);
385 void RenderManager::SurfaceReplaced(SceneGraph::Scene* scene)
387 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
390 void RenderManager::AttachColorTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer)
392 frameBuffer->AttachColorTexture(texture, mipmapLevel, layer);
395 void RenderManager::AttachDepthTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
397 frameBuffer->AttachDepthTexture(texture, mipmapLevel);
400 void RenderManager::AttachDepthStencilTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
402 frameBuffer->AttachDepthStencilTexture(texture, mipmapLevel);
405 void RenderManager::SetMultiSamplingLevelToFrameBuffer(Render::FrameBuffer* frameBuffer, uint8_t multiSamplingLevel)
407 frameBuffer->SetMultiSamplingLevel(multiSamplingLevel);
410 void RenderManager::AddVertexBuffer(OwnerPointer<Render::VertexBuffer>& vertexBuffer)
412 mImpl->vertexBufferContainer.PushBack(vertexBuffer.Release());
415 void RenderManager::RemoveVertexBuffer(Render::VertexBuffer* vertexBuffer)
417 mImpl->vertexBufferContainer.EraseObject(vertexBuffer);
420 void RenderManager::SetVertexBufferFormat(Render::VertexBuffer* vertexBuffer, OwnerPointer<Render::VertexBuffer::Format>& format)
422 vertexBuffer->SetFormat(format.Release());
425 void RenderManager::SetVertexBufferData(Render::VertexBuffer* vertexBuffer, OwnerPointer<Vector<uint8_t>>& data, uint32_t size)
427 vertexBuffer->SetData(data.Release(), size);
430 void RenderManager::SetVertexBufferUpdateCallback(Render::VertexBuffer* vertexBuffer, Dali::VertexBufferUpdateCallback* callback)
432 vertexBuffer->SetVertexBufferUpdateCallback(callback);
435 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Render::Geometry::Uint16ContainerType& indices)
437 geometry->SetIndexBuffer(indices);
440 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Render::Geometry::Uint32ContainerType& indices)
442 geometry->SetIndexBuffer(indices);
445 void RenderManager::AddGeometry(OwnerPointer<Render::Geometry>& geometry)
447 mImpl->geometryContainer.PushBack(geometry.Release());
450 void RenderManager::RemoveGeometry(Render::Geometry* geometry)
452 mImpl->geometryContainer.EraseObject(geometry);
455 void RenderManager::AttachVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
457 geometry->AddVertexBuffer(vertexBuffer);
460 void RenderManager::RemoveVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
462 geometry->RemoveVertexBuffer(vertexBuffer);
465 void RenderManager::SetGeometryType(Render::Geometry* geometry, uint32_t geometryType)
467 geometry->SetType(Render::Geometry::Type(geometryType));
470 void RenderManager::AddRenderTracker(Render::RenderTracker* renderTracker)
472 mImpl->AddRenderTracker(renderTracker);
475 void RenderManager::RemoveRenderTracker(Render::RenderTracker* renderTracker)
477 mImpl->RemoveRenderTracker(renderTracker);
480 void RenderManager::PreRender(Integration::RenderStatus& status, bool forceClear)
482 DALI_PRINT_RENDER_START(mImpl->renderBufferIndex);
483 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "\n\nNewFrame %d\n", mImpl->frameCount);
485 // Increment the frame count at the beginning of each frame
488 // Process messages queued during previous update
489 mImpl->renderQueue.ProcessMessages(mImpl->renderBufferIndex);
491 uint32_t totalInstructionCount = 0u;
492 for(auto& i : mImpl->sceneContainer)
494 totalInstructionCount += i->GetRenderInstructions().Count(mImpl->renderBufferIndex);
497 const bool haveInstructions = totalInstructionCount > 0u;
499 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");
501 // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
502 if(haveInstructions || mImpl->lastFrameWasRendered || forceClear)
504 DALI_LOG_INFO(gLogFilter, Debug::General, "Render: Processing\n");
506 // Upload the geometries
507 for(auto&& geom : mImpl->geometryContainer)
509 geom->Upload(mImpl->graphicsController);
513 // Reset pipeline cache before rendering
514 mImpl->pipelineCache->PreRender();
516 // Let we collect reference counts during CACHE_CLEAN_FRAME_COUNT frames.
517 // TODO : Cache clean logic have some problem now. Just block it until bug resolved
519 if(mImpl->frameCount % CACHE_CLEAN_FRAME_COUNT == 1)
521 mImpl->programController.ResetReferenceCount();
525 mImpl->commandBufferSubmitted = false;
528 void RenderManager::PreRender(Integration::Scene& scene, std::vector<Rect<int>>& damagedRects)
530 if(mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
535 Internal::Scene& sceneInternal = GetImplementation(scene);
536 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
538 if(!sceneObject || sceneObject->IsRenderingSkipped())
540 // We don't need to calculate dirty rects
544 class DamagedRectsCleaner
547 explicit DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects, Rect<int>& surfaceRect)
548 : mDamagedRects(damagedRects),
549 mSurfaceRect(surfaceRect),
554 void SetCleanOnReturn(bool cleanOnReturn)
556 mCleanOnReturn = cleanOnReturn;
559 ~DamagedRectsCleaner()
563 mDamagedRects.clear();
564 mDamagedRects.push_back(mSurfaceRect);
569 std::vector<Rect<int>>& mDamagedRects;
570 Rect<int> mSurfaceRect;
574 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
576 // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
577 DamagedRectsCleaner damagedRectCleaner(damagedRects, surfaceRect);
578 bool cleanDamagedRect = false;
580 Scene::ItemsDirtyRectsContainer& itemsDirtyRects = sceneObject->GetItemsDirtyRects();
582 if(!sceneObject->IsPartialUpdateEnabled())
584 // Clear all dirty rects
585 // The rects will be added when partial updated is enabled again
586 itemsDirtyRects.clear();
590 // Mark previous dirty rects in the std::unordered_map.
591 for(auto& dirtyRectPair : itemsDirtyRects)
593 dirtyRectPair.second.visited = false;
596 uint32_t instructionCount = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
597 for(uint32_t i = 0; i < instructionCount; ++i)
599 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
601 if(instruction.mFrameBuffer)
603 cleanDamagedRect = true;
604 continue; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
607 const Camera* camera = instruction.GetCamera();
608 if(camera && camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
612 Quaternion orientation;
613 camera->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
615 Vector3 orientationAxis;
616 Radian orientationAngle;
617 orientation.ToAxisAngle(orientationAxis, orientationAngle);
619 if(position.x > Math::MACHINE_EPSILON_10000 ||
620 position.y > Math::MACHINE_EPSILON_10000 ||
621 orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
622 orientationAngle != ANGLE_180 ||
623 scale != Vector3(1.0f, 1.0f, 1.0f))
625 cleanDamagedRect = true;
631 cleanDamagedRect = true;
635 Rect<int32_t> viewportRect;
636 if(instruction.mIsViewportSet)
638 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
639 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
640 if(viewportRect.IsEmpty() || !viewportRect.IsValid())
642 cleanDamagedRect = true;
643 continue; // just skip funny use cases for now, empty viewport means it is set somewhere else
648 viewportRect = surfaceRect;
651 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
652 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
653 if(viewMatrix && projectionMatrix)
655 const RenderListContainer::SizeType count = instruction.RenderListCount();
656 for(RenderListContainer::SizeType index = 0u; index < count; ++index)
658 const RenderList* renderList = instruction.GetRenderList(index);
661 if(!renderList->IsEmpty())
663 const std::size_t listCount = renderList->Count();
664 for(uint32_t listIndex = 0u; listIndex < listCount; ++listIndex)
666 RenderItem& item = renderList->GetItem(listIndex);
667 // If the item does 3D transformation, make full update
668 if(item.mUpdateArea == Vector4::ZERO)
670 cleanDamagedRect = true;
672 // Save the full rect in the damaged list. We need it when this item is removed
673 DirtyRectKey dirtyRectKey(item.mNode, item.mRenderer);
674 auto dirtyRectPos = itemsDirtyRects.find(dirtyRectKey);
675 if(dirtyRectPos != itemsDirtyRects.end())
678 dirtyRectPos->second.visited = true;
679 dirtyRectPos->second.rect = surfaceRect;
683 // Else, just insert the new dirtyrect
684 itemsDirtyRects.insert({dirtyRectKey, surfaceRect});
690 DirtyRectKey dirtyRectKey(item.mNode, item.mRenderer);
691 // If the item refers to updated node or renderer.
692 if(item.mIsUpdated ||
694 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated()))))
696 item.mIsUpdated = false;
698 rect = CalculateUpdateArea(item, mImpl->renderBufferIndex, viewportRect);
699 if(rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
701 AlignDamagedRect(rect);
703 // Found valid dirty rect.
704 auto dirtyRectPos = itemsDirtyRects.find(dirtyRectKey);
705 if(dirtyRectPos != itemsDirtyRects.end())
707 Rect<int> currentRect = rect;
709 // Same item, merge it with the previous rect
710 rect.Merge(dirtyRectPos->second.rect);
712 // Replace the rect as current
713 dirtyRectPos->second.visited = true;
714 dirtyRectPos->second.rect = currentRect;
718 // Else, just insert the new dirtyrect
719 itemsDirtyRects.insert({dirtyRectKey, rect});
722 damagedRects.push_back(rect);
727 // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
728 // 2. Mark the related dirty rects as visited so they will not be removed below.
729 auto dirtyRectPos = itemsDirtyRects.find(dirtyRectKey);
730 if(dirtyRectPos != itemsDirtyRects.end())
732 dirtyRectPos->second.visited = true;
736 // The item is not in the list for some reason. Add the current rect!
737 rect = CalculateUpdateArea(item, mImpl->renderBufferIndex, viewportRect);
738 if(rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
740 AlignDamagedRect(rect);
742 itemsDirtyRects.insert({dirtyRectKey, rect});
744 cleanDamagedRect = true; // And make full update at this frame
754 // Check removed nodes or removed renderers dirty rects
755 // Note, std::unordered_map end iterator is validate if we call erase.
756 for(auto iter = itemsDirtyRects.cbegin(), iterEnd = itemsDirtyRects.cend(); iter != iterEnd;)
758 if(!iter->second.visited)
760 damagedRects.push_back(iter->second.rect);
761 iter = itemsDirtyRects.erase(iter);
769 if(sceneObject->IsNeededFullUpdate())
771 cleanDamagedRect = true; // And make full update at this frame
774 if(!cleanDamagedRect)
776 damagedRectCleaner.SetCleanOnReturn(false);
780 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo)
782 SceneGraph::Scene* sceneObject = GetImplementation(scene).GetSceneObject();
788 Rect<int> clippingRect = sceneObject->GetSurfaceRect();
789 RenderScene(status, scene, renderToFbo, clippingRect);
792 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
794 if(mImpl->partialUpdateAvailable == Integration::PartialUpdateAvailable::TRUE && !renderToFbo && clippingRect.IsEmpty())
796 // ClippingRect is empty. Skip rendering
800 // Reset main algorithms command buffer
801 mImpl->renderAlgorithms.ResetCommandBuffer();
803 auto mainCommandBuffer = mImpl->renderAlgorithms.GetMainCommandBuffer();
805 Internal::Scene& sceneInternal = GetImplementation(scene);
806 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
812 uint32_t instructionCount = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
814 std::vector<Graphics::RenderTarget*> targetstoPresent;
816 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
817 if(clippingRect == surfaceRect)
819 // Full rendering case
820 // Make clippingRect empty because we're doing full rendering now if the clippingRect is empty.
821 // To reduce side effects, keep this logic now.
822 clippingRect = Rect<int>();
825 // Prefetch programs before we start rendering so reflection is
826 // ready, and we can pull exact size of UBO needed (no need to resize during drawing)
827 auto totalSizeCPU = 0u;
828 auto totalSizeGPU = 0u;
830 for(uint32_t i = 0; i < instructionCount; ++i)
832 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
834 if((instruction.mFrameBuffer != nullptr && renderToFbo) ||
835 (instruction.mFrameBuffer == nullptr && !renderToFbo))
837 for(auto j = 0u; j < instruction.RenderListCount(); ++j)
839 const auto& renderList = instruction.GetRenderList(j);
840 for(auto k = 0u; k < renderList->Count(); ++k)
842 auto& item = renderList->GetItem(k);
843 if(item.mRenderer && item.mRenderer->NeedsProgram())
845 // Prepare and store used programs for further processing
846 auto program = item.mRenderer->PrepareProgram(instruction);
849 const auto& memoryRequirements = program->GetUniformBlocksMemoryRequirements();
851 totalSizeCPU += memoryRequirements.totalCpuSizeRequired;
852 totalSizeGPU += memoryRequirements.totalGpuSizeRequired;
860 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Render scene (%s), CPU:%d GPU:%d\n", renderToFbo ? "Offscreen" : "Onscreen", totalSizeCPU, totalSizeGPU);
862 auto& uboManager = mImpl->uniformBufferManager;
864 uboManager->SetCurrentSceneRenderInfo(sceneObject, renderToFbo);
865 uboManager->Rollback(sceneObject, renderToFbo);
867 // Respec UBOs for this frame (orphan buffers or double buffer in the GPU)
870 uboManager->GetUniformBufferForScene(sceneObject, renderToFbo, true)->ReSpecify(totalSizeCPU);
871 uboManager->GetUniformBufferForScene(sceneObject, renderToFbo, false)->ReSpecify(totalSizeGPU);
874 #if defined(DEBUG_ENABLED)
875 auto uniformBuffer1 = uboManager->GetUniformBufferForScene(sceneObject, renderToFbo, true);
876 auto uniformBuffer2 = uboManager->GetUniformBufferForScene(sceneObject, renderToFbo, false);
879 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "CPU buffer: Offset(%d), Cap(%d)\n", uniformBuffer1->GetCurrentOffset(), uniformBuffer1->GetCurrentCapacity());
883 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "CPU buffer: nil\n");
887 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "GPU buffer: Offset(%d), Cap(%d)\n", uniformBuffer2->GetCurrentOffset(), uniformBuffer2->GetCurrentCapacity());
891 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "GPU buffer: nil\n");
895 for(uint32_t i = 0; i < instructionCount; ++i)
897 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
899 if((renderToFbo && !instruction.mFrameBuffer) || (!renderToFbo && instruction.mFrameBuffer))
904 // Mark that we will require a post-render step to be performed (includes swap-buffers).
905 status.SetNeedsPostRender(true);
907 Rect<int32_t> viewportRect;
909 int32_t surfaceOrientation = sceneObject->GetSurfaceOrientation() + sceneObject->GetScreenOrientation();
910 if(surfaceOrientation >= 360)
912 surfaceOrientation -= 360;
915 // @todo Should these be part of scene?
916 Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
917 Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
919 Graphics::RenderTarget* currentRenderTarget = nullptr;
920 Graphics::RenderPass* currentRenderPass = nullptr;
921 std::vector<Graphics::ClearValue> currentClearValues{};
923 if(instruction.mFrameBuffer)
925 // Ensure graphics framebuffer is created, bind attachments and create render passes
926 // Only happens once per framebuffer. If the create fails, e.g. no attachments yet,
927 // then don't render to this framebuffer.
928 if(!instruction.mFrameBuffer->GetGraphicsObject())
930 const bool created = instruction.mFrameBuffer->CreateGraphicsObjects();
937 auto& clearValues = instruction.mFrameBuffer->GetGraphicsRenderPassClearValues();
939 // Set the clear color for first color attachment
940 if(instruction.mIsClearColorSet && !clearValues.empty())
942 clearValues[0].color = {
943 instruction.mClearColor.r,
944 instruction.mClearColor.g,
945 instruction.mClearColor.b,
946 instruction.mClearColor.a};
949 currentClearValues = clearValues;
951 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
954 currentRenderTarget = instruction.mFrameBuffer->GetGraphicsRenderTarget();
955 currentRenderPass = instruction.mFrameBuffer->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
957 else // no framebuffer
960 auto& clearValues = sceneObject->GetGraphicsRenderPassClearValues();
962 if(instruction.mIsClearColorSet)
964 clearValues[0].color = {
965 instruction.mClearColor.r,
966 instruction.mClearColor.g,
967 instruction.mClearColor.b,
968 instruction.mClearColor.a};
971 currentClearValues = clearValues;
973 // @todo SceneObject should already have the depth clear / stencil clear in the clearValues array.
974 // if the window has a depth/stencil buffer.
975 if((depthBufferAvailable == Integration::DepthBufferAvailable::TRUE ||
976 stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE) &&
977 (currentClearValues.size() <= 1))
979 currentClearValues.emplace_back();
980 currentClearValues.back().depthStencil.depth = 0;
981 currentClearValues.back().depthStencil.stencil = 0;
984 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
986 currentRenderTarget = sceneObject->GetSurfaceRenderTarget();
987 currentRenderPass = sceneObject->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
990 targetstoPresent.emplace_back(currentRenderTarget);
992 if(!instruction.mIgnoreRenderToFbo && (instruction.mFrameBuffer != nullptr))
994 // Offscreen buffer rendering
995 if(instruction.mIsViewportSet)
997 // For Viewport the lower-left corner is (0,0)
998 const int32_t y = (instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height) - instruction.mViewport.y;
999 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
1003 viewportRect.Set(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
1005 surfaceOrientation = 0;
1007 else // No Offscreen frame buffer rendering
1009 // Check whether a viewport is specified, otherwise the full surface size is used
1010 if(instruction.mIsViewportSet)
1012 // For Viewport the lower-left corner is (0,0)
1013 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
1014 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
1018 viewportRect = surfaceRect;
1022 // Set surface orientation
1023 // @todo Inform graphics impl by another route.
1024 // was: mImpl->currentContext->SetSurfaceOrientation(surfaceOrientation);
1026 /*** Clear region of framebuffer or surface before drawing ***/
1027 bool clearFullFrameRect = (surfaceRect == viewportRect);
1028 if(instruction.mFrameBuffer != nullptr)
1030 Viewport frameRect(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
1031 clearFullFrameRect = (frameRect == viewportRect);
1034 if(!clippingRect.IsEmpty())
1036 if(!clippingRect.Intersect(viewportRect))
1038 DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
1039 clippingRect = Rect<int>();
1041 clearFullFrameRect = false;
1044 Graphics::Rect2D scissorArea{viewportRect.x, viewportRect.y, uint32_t(viewportRect.width), uint32_t(viewportRect.height)};
1045 if(instruction.mIsClearColorSet)
1047 if(!clearFullFrameRect)
1049 if(!clippingRect.IsEmpty())
1051 scissorArea = {clippingRect.x, clippingRect.y, uint32_t(clippingRect.width), uint32_t(clippingRect.height)};
1056 // Scissor's value should be set based on the default system coordinates.
1057 // When the surface is rotated, the input values already were set with the rotated angle.
1058 // So, re-calculation is needed.
1059 scissorArea = RecalculateScissorArea(scissorArea, surfaceOrientation, surfaceRect);
1061 // Begin render pass
1062 mainCommandBuffer->BeginRenderPass(
1064 currentRenderTarget,
1066 currentClearValues);
1068 mainCommandBuffer->SetViewport({float(viewportRect.x),
1069 float(viewportRect.y),
1070 float(viewportRect.width),
1071 float(viewportRect.height)});
1073 mImpl->renderAlgorithms.ProcessRenderInstruction(
1075 mImpl->renderBufferIndex,
1076 depthBufferAvailable,
1077 stencilBufferAvailable,
1081 Uint16Pair(surfaceRect.width, surfaceRect.height));
1083 Graphics::SyncObject* syncObject{nullptr};
1084 // If the render instruction has an associated render tracker (owned separately)
1085 // and framebuffer, create a one shot sync object, and use it to determine when
1086 // the render pass has finished executing on GPU.
1087 if(instruction.mRenderTracker && instruction.mFrameBuffer)
1089 syncObject = instruction.mRenderTracker->CreateSyncObject(mImpl->graphicsController);
1090 instruction.mRenderTracker = nullptr;
1092 mainCommandBuffer->EndRenderPass(syncObject);
1096 mImpl->uniformBufferManager->Flush(sceneObject, renderToFbo);
1097 mImpl->renderAlgorithms.SubmitCommandBuffer();
1098 mImpl->commandBufferSubmitted = true;
1100 std::sort(targetstoPresent.begin(), targetstoPresent.end());
1102 Graphics::RenderTarget* rt = nullptr;
1103 for(auto& target : targetstoPresent)
1107 mImpl->graphicsController.PresentRenderTarget(target);
1113 void RenderManager::PostRender()
1115 if(!mImpl->commandBufferSubmitted)
1117 // Rendering is skipped but there may be pending tasks. Flush them.
1118 Graphics::SubmitInfo submitInfo;
1119 submitInfo.cmdBuffer.clear(); // Only flush
1120 submitInfo.flags = 0 | Graphics::SubmitFlagBits::FLUSH;
1121 mImpl->graphicsController.SubmitCommandBuffers(submitInfo);
1123 mImpl->commandBufferSubmitted = true;
1126 // Notify RenderGeometries that rendering has finished
1127 for(auto&& iter : mImpl->geometryContainer)
1129 iter->OnRenderFinished();
1132 // Notify updated RenderTexture that rendering has finished
1133 for(auto&& iter : mImpl->updatedTextures)
1135 iter->OnRenderFinished();
1137 mImpl->updatedTextures.Clear();
1139 // Remove discarded textures after OnRenderFinished called
1140 mImpl->textureDiscardQueue.Clear();
1142 mImpl->UpdateTrackers();
1144 uint32_t count = 0u;
1145 for(auto& scene : mImpl->sceneContainer)
1147 count += scene->GetRenderInstructions().Count(mImpl->renderBufferIndex);
1150 // Remove unused shader and programs during CACHE_CLEAN_FRAME_COUNT frames.
1151 // TODO : Cache clean logic have some problem now. Just block it until bug resolved
1153 if(mImpl->frameCount % CACHE_CLEAN_FRAME_COUNT == 0)
1155 mImpl->programController.ClearUnusedCache();
1159 const bool haveInstructions = count > 0u;
1161 // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
1162 mImpl->lastFrameWasRendered = haveInstructions;
1165 * The rendering has finished; swap to the next buffer.
1166 * Ideally the update has just finished using this buffer; otherwise the render thread
1167 * should block until the update has finished.
1169 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1171 DALI_PRINT_RENDER_END();
1174 } // namespace SceneGraph
1176 } // namespace Internal