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.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 // TODO : Cache clean logic have some problem now. Just block it until bug resolved
68 //constexpr uint32_t CACHE_CLEAN_FRAME_COUNT = 600u; // 60fps * 10sec
70 inline Graphics::Rect2D RecalculateScissorArea(const Graphics::Rect2D& scissorArea, int orientation, const Rect<int32_t>& viewportRect)
72 Graphics::Rect2D newScissorArea;
76 newScissorArea.x = viewportRect.height - (scissorArea.y + scissorArea.height);
77 newScissorArea.y = scissorArea.x;
78 newScissorArea.width = scissorArea.height;
79 newScissorArea.height = scissorArea.width;
81 else if(orientation == 180)
83 newScissorArea.x = viewportRect.width - (scissorArea.x + scissorArea.width);
84 newScissorArea.y = viewportRect.height - (scissorArea.y + scissorArea.height);
85 newScissorArea.width = scissorArea.width;
86 newScissorArea.height = scissorArea.height;
88 else if(orientation == 270)
90 newScissorArea.x = scissorArea.y;
91 newScissorArea.y = viewportRect.width - (scissorArea.x + scissorArea.width);
92 newScissorArea.width = scissorArea.height;
93 newScissorArea.height = scissorArea.width;
97 newScissorArea.x = scissorArea.x;
98 newScissorArea.y = scissorArea.y;
99 newScissorArea.width = scissorArea.width;
100 newScissorArea.height = scissorArea.height;
102 return newScissorArea;
105 inline Rect<int32_t> CalculateUpdateArea(RenderItem& item, BufferIndex renderBufferIndex, const Rect<int32_t>& viewportRect)
108 if(item.mNode && item.mNode->IsTextureUpdateAreaUsed() && item.mRenderer)
110 updateArea = item.mRenderer->GetTextureUpdateArea();
114 updateArea = item.mRenderer ? item.mRenderer->GetVisualTransformedUpdateArea(renderBufferIndex, item.mUpdateArea) : item.mUpdateArea;
117 return RenderItem::CalculateViewportSpaceAABB(item.mModelViewMatrix, Vector3(updateArea.x, updateArea.y, 0.0f), Vector3(updateArea.z, updateArea.w, 0.0f), viewportRect.width, viewportRect.height);
120 inline void AlignDamagedRect(Rect<int32_t>& rect)
122 const int left = rect.x;
123 const int top = rect.y;
124 const int right = rect.x + rect.width;
125 const int bottom = rect.y + rect.height;
126 rect.x = (left / 16) * 16;
127 rect.y = (top / 16) * 16;
128 rect.width = ((right + 16) / 16) * 16 - rect.x;
129 rect.height = ((bottom + 16) / 16) * 16 - rect.y;
134 * Structure to contain internal data
136 struct RenderManager::Impl
138 Impl(Graphics::Controller& graphicsController,
139 Integration::DepthBufferAvailable depthBufferAvailableParam,
140 Integration::StencilBufferAvailable stencilBufferAvailableParam,
141 Integration::PartialUpdateAvailable partialUpdateAvailableParam)
142 : graphicsController(graphicsController),
143 renderAlgorithms(graphicsController),
144 programController(graphicsController),
145 shaderCache(graphicsController),
146 depthBufferAvailable(depthBufferAvailableParam),
147 stencilBufferAvailable(stencilBufferAvailableParam),
148 partialUpdateAvailable(partialUpdateAvailableParam)
150 // Create thread pool with just one thread ( there may be a need to create more threads in the future ).
151 threadPool = std::make_unique<Dali::ThreadPool>();
152 threadPool->Initialize(1u);
154 uniformBufferManager = std::make_unique<Render::UniformBufferManager>(&graphicsController);
155 pipelineCache = std::make_unique<Render::PipelineCache>(graphicsController);
160 threadPool.reset(nullptr); // reset now to maintain correct destruction order
161 rendererContainer.Clear(); // clear now before the pipeline cache is deleted
164 void AddRenderTracker(Render::RenderTracker* renderTracker)
166 DALI_ASSERT_DEBUG(renderTracker != nullptr);
167 mRenderTrackers.PushBack(renderTracker);
170 void RemoveRenderTracker(Render::RenderTracker* renderTracker)
172 mRenderTrackers.EraseObject(renderTracker);
175 void UpdateTrackers()
177 for(auto&& iter : mRenderTrackers)
179 iter->PollSyncObject();
183 // the order is important for destruction,
184 Graphics::Controller& graphicsController;
185 RenderQueue renderQueue; ///< A message queue for receiving messages from the update-thread.
186 std::vector<SceneGraph::Scene*> sceneContainer; ///< List of pointers to the scene graph objects of the scenes
187 Render::RenderAlgorithms renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
189 OrderedSet<Render::Sampler> samplerContainer; ///< List of owned samplers
190 OrderedSet<Render::FrameBuffer> frameBufferContainer; ///< List of owned framebuffers
191 OrderedSet<Render::VertexBuffer> vertexBufferContainer; ///< List of owned vertex buffers
192 OrderedSet<Render::Geometry> geometryContainer; ///< List of owned Geometries
193 OwnerKeyContainer<Render::Renderer> rendererContainer; ///< List of owned renderers
194 OwnerKeyContainer<Render::Texture> textureContainer; ///< List of owned textures
196 OrderedSet<Render::RenderTracker> mRenderTrackers; ///< List of owned render trackers
198 OwnerKeyContainer<Render::Texture> textureDiscardQueue; ///< Discarded textures
200 ProgramController programController; ///< Owner of the programs
201 Render::ShaderCache shaderCache; ///< The cache for the graphics shaders
203 std::unique_ptr<Render::UniformBufferManager> uniformBufferManager; ///< The uniform buffer manager
204 std::unique_ptr<Render::PipelineCache> pipelineCache;
206 Integration::DepthBufferAvailable depthBufferAvailable; ///< Whether the depth buffer is available
207 Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
208 Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
210 std::unique_ptr<Dali::ThreadPool> threadPool; ///< The thread pool
211 Vector<Render::TextureKey> updatedTextures{}; ///< The updated texture list
213 uint32_t frameCount{0u}; ///< The current frame count
214 BufferIndex renderBufferIndex{SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX}; ///< The index of the buffer to read from;
216 bool lastFrameWasRendered{false}; ///< Keeps track of the last frame being rendered due to having render instructions
217 bool commandBufferSubmitted{false};
220 RenderManager* RenderManager::New(Graphics::Controller& graphicsController,
221 Integration::DepthBufferAvailable depthBufferAvailable,
222 Integration::StencilBufferAvailable stencilBufferAvailable,
223 Integration::PartialUpdateAvailable partialUpdateAvailable)
225 auto* manager = new RenderManager;
226 manager->mImpl = new Impl(graphicsController,
227 depthBufferAvailable,
228 stencilBufferAvailable,
229 partialUpdateAvailable);
233 RenderManager::RenderManager()
238 RenderManager::~RenderManager()
243 RenderQueue& RenderManager::GetRenderQueue()
245 return mImpl->renderQueue;
248 void RenderManager::SetShaderSaver(ShaderSaver& upstream)
252 void RenderManager::AddRenderer(const Render::RendererKey& renderer)
254 // Initialize the renderer as we are now in render thread
255 renderer->Initialize(mImpl->graphicsController, mImpl->programController, mImpl->shaderCache, *(mImpl->uniformBufferManager.get()), *(mImpl->pipelineCache.get()));
257 mImpl->rendererContainer.PushBack(renderer);
260 void RenderManager::RemoveRenderer(const Render::RendererKey& renderer)
262 mImpl->rendererContainer.EraseKey(renderer);
265 void RenderManager::AddSampler(OwnerPointer<Render::Sampler>& sampler)
267 sampler->Initialize(mImpl->graphicsController);
268 mImpl->samplerContainer.PushBack(sampler.Release());
271 void RenderManager::RemoveSampler(Render::Sampler* sampler)
273 mImpl->samplerContainer.EraseObject(sampler);
276 void RenderManager::AddTexture(const Render::TextureKey& textureKey)
278 DALI_ASSERT_DEBUG(textureKey && "Trying to add empty texture key");
280 textureKey->Initialize(mImpl->graphicsController, *this);
281 mImpl->textureContainer.PushBack(textureKey);
282 mImpl->updatedTextures.PushBack(textureKey);
285 void RenderManager::RemoveTexture(const Render::TextureKey& textureKey)
287 DALI_ASSERT_DEBUG(textureKey && "Trying to remove empty texture key");
289 // Find the texture, use std::find so we can do the erase by iterator safely
290 auto iter = std::find(mImpl->textureContainer.Begin(), mImpl->textureContainer.End(), textureKey);
292 if(iter != mImpl->textureContainer.End())
295 textureKey->Destroy();
297 // Transfer ownership to the discard queue, this keeps the object alive, until the render-thread has finished with it
298 mImpl->textureDiscardQueue.PushBack(mImpl->textureContainer.Release(iter));
302 void RenderManager::UploadTexture(const Render::TextureKey& textureKey, PixelDataPtr pixelData, const Graphics::UploadParams& params)
304 DALI_ASSERT_DEBUG(textureKey && "Trying to upload to empty texture key");
305 textureKey->Upload(pixelData, params);
307 mImpl->updatedTextures.PushBack(textureKey);
310 void RenderManager::GenerateMipmaps(const Render::TextureKey& textureKey)
312 DALI_ASSERT_DEBUG(textureKey && "Trying to generate mipmaps on empty texture key");
313 textureKey->GenerateMipmaps();
315 mImpl->updatedTextures.PushBack(textureKey);
318 void RenderManager::SetTextureSize(const Render::TextureKey& textureKey, const Dali::ImageDimensions& size)
320 DALI_ASSERT_DEBUG(textureKey && "Trying to set size on empty texture key");
321 textureKey->SetWidth(size.GetWidth());
322 textureKey->SetHeight(size.GetHeight());
325 void RenderManager::SetTextureFormat(const Render::TextureKey& textureKey, Dali::Pixel::Format pixelFormat)
327 DALI_ASSERT_DEBUG(textureKey && "Trying to set pixel format on empty texture key");
328 textureKey->SetPixelFormat(pixelFormat);
331 void RenderManager::SetTextureUpdated(const Render::TextureKey& textureKey)
333 DALI_ASSERT_DEBUG(textureKey && "Trying to set updated on empty texture key");
334 textureKey->SetUpdated(true);
336 mImpl->updatedTextures.PushBack(textureKey);
339 void RenderManager::SetFilterMode(Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode)
341 sampler->SetFilterMode(static_cast<Dali::FilterMode::Type>(minFilterMode),
342 static_cast<Dali::FilterMode::Type>(magFilterMode));
345 void RenderManager::SetWrapMode(Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode)
347 sampler->SetWrapMode(static_cast<Dali::WrapMode::Type>(rWrapMode),
348 static_cast<Dali::WrapMode::Type>(sWrapMode),
349 static_cast<Dali::WrapMode::Type>(tWrapMode));
352 void RenderManager::AddFrameBuffer(OwnerPointer<Render::FrameBuffer>& frameBuffer)
354 Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
355 mImpl->frameBufferContainer.PushBack(frameBufferPtr);
356 frameBufferPtr->Initialize(mImpl->graphicsController);
359 void RenderManager::RemoveFrameBuffer(Render::FrameBuffer* frameBuffer)
361 DALI_ASSERT_DEBUG(nullptr != frameBuffer);
363 // Find the framebuffer, use OrderedSet.Find so we can safely do the erase
364 auto iter = mImpl->frameBufferContainer.Find(frameBuffer);
366 if(iter != mImpl->frameBufferContainer.End())
368 frameBuffer->Destroy();
369 mImpl->frameBufferContainer.Erase(iter); // frameBuffer found; now destroy it
373 void RenderManager::InitializeScene(SceneGraph::Scene* scene)
375 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
376 mImpl->sceneContainer.push_back(scene);
377 mImpl->uniformBufferManager->RegisterScene(scene);
380 void RenderManager::UninitializeScene(SceneGraph::Scene* scene)
382 mImpl->uniformBufferManager->UnregisterScene(scene);
383 auto iter = std::find(mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene);
384 if(iter != mImpl->sceneContainer.end())
386 mImpl->sceneContainer.erase(iter);
390 void RenderManager::SurfaceReplaced(SceneGraph::Scene* scene)
392 scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
395 void RenderManager::AttachColorTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer)
397 frameBuffer->AttachColorTexture(texture, mipmapLevel, layer);
400 void RenderManager::AttachDepthTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
402 frameBuffer->AttachDepthTexture(texture, mipmapLevel);
405 void RenderManager::AttachDepthStencilTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
407 frameBuffer->AttachDepthStencilTexture(texture, mipmapLevel);
410 void RenderManager::SetMultiSamplingLevelToFrameBuffer(Render::FrameBuffer* frameBuffer, uint8_t multiSamplingLevel)
412 frameBuffer->SetMultiSamplingLevel(multiSamplingLevel);
415 void RenderManager::AddVertexBuffer(OwnerPointer<Render::VertexBuffer>& vertexBuffer)
417 mImpl->vertexBufferContainer.PushBack(vertexBuffer.Release());
420 void RenderManager::RemoveVertexBuffer(Render::VertexBuffer* vertexBuffer)
422 mImpl->vertexBufferContainer.EraseObject(vertexBuffer);
425 void RenderManager::SetVertexBufferFormat(Render::VertexBuffer* vertexBuffer, OwnerPointer<Render::VertexBuffer::Format>& format)
427 vertexBuffer->SetFormat(format.Release());
430 void RenderManager::SetVertexBufferData(Render::VertexBuffer* vertexBuffer, OwnerPointer<Vector<uint8_t>>& data, uint32_t size)
432 vertexBuffer->SetData(data.Release(), size);
435 void RenderManager::SetVertexBufferUpdateCallback(Render::VertexBuffer* vertexBuffer, Dali::VertexBufferUpdateCallback* callback)
437 vertexBuffer->SetVertexBufferUpdateCallback(callback);
440 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Render::Geometry::Uint16ContainerType& indices)
442 geometry->SetIndexBuffer(indices);
445 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Render::Geometry::Uint32ContainerType& indices)
447 geometry->SetIndexBuffer(indices);
450 void RenderManager::AddGeometry(OwnerPointer<Render::Geometry>& geometry)
452 mImpl->geometryContainer.PushBack(geometry.Release());
455 void RenderManager::RemoveGeometry(Render::Geometry* geometry)
457 mImpl->geometryContainer.EraseObject(geometry);
460 void RenderManager::AttachVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
462 geometry->AddVertexBuffer(vertexBuffer);
465 void RenderManager::RemoveVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
467 geometry->RemoveVertexBuffer(vertexBuffer);
470 void RenderManager::SetGeometryType(Render::Geometry* geometry, uint32_t geometryType)
472 geometry->SetType(Render::Geometry::Type(geometryType));
475 void RenderManager::AddRenderTracker(Render::RenderTracker* renderTracker)
477 mImpl->AddRenderTracker(renderTracker);
480 void RenderManager::RemoveRenderTracker(Render::RenderTracker* renderTracker)
482 mImpl->RemoveRenderTracker(renderTracker);
485 void RenderManager::PreRender(Integration::RenderStatus& status, bool forceClear)
487 DALI_PRINT_RENDER_START(mImpl->renderBufferIndex);
488 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "\n\nNewFrame %d\n", mImpl->frameCount);
490 // Increment the frame count at the beginning of each frame
493 // Process messages queued during previous update
494 mImpl->renderQueue.ProcessMessages(mImpl->renderBufferIndex);
496 uint32_t totalInstructionCount = 0u;
497 for(auto& i : mImpl->sceneContainer)
499 totalInstructionCount += i->GetRenderInstructions().Count(mImpl->renderBufferIndex);
502 const bool haveInstructions = totalInstructionCount > 0u;
504 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");
506 // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
507 if(haveInstructions || mImpl->lastFrameWasRendered || forceClear)
509 DALI_LOG_INFO(gLogFilter, Debug::General, "Render: Processing\n");
511 // Upload the geometries
512 for(auto&& geom : mImpl->geometryContainer)
514 geom->Upload(mImpl->graphicsController);
518 // Reset pipeline cache before rendering
519 mImpl->pipelineCache->PreRender();
521 // Let we collect reference counts during CACHE_CLEAN_FRAME_COUNT frames.
522 // TODO : Cache clean logic have some problem now. Just block it until bug resolved
524 if(mImpl->frameCount % CACHE_CLEAN_FRAME_COUNT == 1)
526 mImpl->programController.ResetReferenceCount();
527 mImpl->shaderCache.ResetReferenceCount();
531 mImpl->commandBufferSubmitted = false;
534 void RenderManager::PreRender(Integration::Scene& scene, std::vector<Rect<int>>& damagedRects)
536 if(mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
541 Internal::Scene& sceneInternal = GetImplementation(scene);
542 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
544 if(!sceneObject || sceneObject->IsRenderingSkipped())
546 // We don't need to calculate dirty rects
550 class DamagedRectsCleaner
553 explicit DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects, Rect<int>& surfaceRect)
554 : mDamagedRects(damagedRects),
555 mSurfaceRect(surfaceRect),
560 void SetCleanOnReturn(bool cleanOnReturn)
562 mCleanOnReturn = cleanOnReturn;
565 ~DamagedRectsCleaner()
569 mDamagedRects.clear();
570 mDamagedRects.push_back(mSurfaceRect);
575 std::vector<Rect<int>>& mDamagedRects;
576 Rect<int> mSurfaceRect;
580 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
582 // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
583 DamagedRectsCleaner damagedRectCleaner(damagedRects, surfaceRect);
584 bool cleanDamagedRect = false;
586 Scene::ItemsDirtyRectsContainer& itemsDirtyRects = sceneObject->GetItemsDirtyRects();
588 if(!sceneObject->IsPartialUpdateEnabled())
590 // Clear all dirty rects
591 // The rects will be added when partial updated is enabled again
592 itemsDirtyRects.clear();
596 // Mark previous dirty rects in the std::unordered_map.
597 for(auto& dirtyRectPair : itemsDirtyRects)
599 dirtyRectPair.second.visited = false;
602 uint32_t instructionCount = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
603 for(uint32_t i = 0; i < instructionCount; ++i)
605 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
607 if(instruction.mFrameBuffer)
609 cleanDamagedRect = true;
610 continue; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
613 const Camera* camera = instruction.GetCamera();
614 if(camera && camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
618 Quaternion orientation;
619 camera->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
621 Vector3 orientationAxis;
622 Radian orientationAngle;
623 orientation.ToAxisAngle(orientationAxis, orientationAngle);
625 if(position.x > Math::MACHINE_EPSILON_10000 ||
626 position.y > Math::MACHINE_EPSILON_10000 ||
627 orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
628 orientationAngle != ANGLE_180 ||
629 scale != Vector3(1.0f, 1.0f, 1.0f))
631 cleanDamagedRect = true;
637 cleanDamagedRect = true;
641 Rect<int32_t> viewportRect;
642 if(instruction.mIsViewportSet)
644 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
645 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
646 if(viewportRect.IsEmpty() || !viewportRect.IsValid())
648 cleanDamagedRect = true;
649 continue; // just skip funny use cases for now, empty viewport means it is set somewhere else
654 viewportRect = surfaceRect;
657 const Matrix* viewMatrix = instruction.GetViewMatrix(mImpl->renderBufferIndex);
658 const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
659 if(viewMatrix && projectionMatrix)
661 const RenderListContainer::SizeType count = instruction.RenderListCount();
662 for(RenderListContainer::SizeType index = 0u; index < count; ++index)
664 const RenderList* renderList = instruction.GetRenderList(index);
667 if(!renderList->IsEmpty())
669 const std::size_t listCount = renderList->Count();
670 for(uint32_t listIndex = 0u; listIndex < listCount; ++listIndex)
672 RenderItem& item = renderList->GetItem(listIndex);
673 // If the item does 3D transformation, make full update
674 if(item.mUpdateArea == Vector4::ZERO)
676 cleanDamagedRect = true;
678 // Save the full rect in the damaged list. We need it when this item is removed
679 DirtyRectKey dirtyRectKey(item.mNode, item.mRenderer);
680 auto dirtyRectPos = itemsDirtyRects.find(dirtyRectKey);
681 if(dirtyRectPos != itemsDirtyRects.end())
684 dirtyRectPos->second.visited = true;
685 dirtyRectPos->second.rect = surfaceRect;
689 // Else, just insert the new dirtyrect
690 itemsDirtyRects.insert({dirtyRectKey, surfaceRect});
696 DirtyRectKey dirtyRectKey(item.mNode, item.mRenderer);
697 // If the item refers to updated node or renderer.
698 if(item.mIsUpdated ||
700 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated()))))
702 item.mIsUpdated = false;
704 rect = CalculateUpdateArea(item, mImpl->renderBufferIndex, viewportRect);
705 if(rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
707 AlignDamagedRect(rect);
709 // Found valid dirty rect.
710 auto dirtyRectPos = itemsDirtyRects.find(dirtyRectKey);
711 if(dirtyRectPos != itemsDirtyRects.end())
713 Rect<int> currentRect = rect;
715 // Same item, merge it with the previous rect
716 rect.Merge(dirtyRectPos->second.rect);
718 // Replace the rect as current
719 dirtyRectPos->second.visited = true;
720 dirtyRectPos->second.rect = currentRect;
724 // Else, just insert the new dirtyrect
725 itemsDirtyRects.insert({dirtyRectKey, rect});
728 damagedRects.push_back(rect);
733 // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
734 // 2. Mark the related dirty rects as visited so they will not be removed below.
735 auto dirtyRectPos = itemsDirtyRects.find(dirtyRectKey);
736 if(dirtyRectPos != itemsDirtyRects.end())
738 dirtyRectPos->second.visited = true;
742 // The item is not in the list for some reason. Add the current rect!
743 rect = CalculateUpdateArea(item, mImpl->renderBufferIndex, viewportRect);
744 if(rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
746 AlignDamagedRect(rect);
748 itemsDirtyRects.insert({dirtyRectKey, rect});
750 cleanDamagedRect = true; // And make full update at this frame
760 // Check removed nodes or removed renderers dirty rects
761 // Note, std::unordered_map end iterator is validate if we call erase.
762 for(auto iter = itemsDirtyRects.cbegin(), iterEnd = itemsDirtyRects.cend(); iter != iterEnd;)
764 if(!iter->second.visited)
766 damagedRects.push_back(iter->second.rect);
767 iter = itemsDirtyRects.erase(iter);
775 if(sceneObject->IsNeededFullUpdate())
777 cleanDamagedRect = true; // And make full update at this frame
780 if(!cleanDamagedRect)
782 damagedRectCleaner.SetCleanOnReturn(false);
786 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo)
788 SceneGraph::Scene* sceneObject = GetImplementation(scene).GetSceneObject();
794 Rect<int> clippingRect = sceneObject->GetSurfaceRect();
795 RenderScene(status, scene, renderToFbo, clippingRect);
798 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
800 if(mImpl->partialUpdateAvailable == Integration::PartialUpdateAvailable::TRUE && !renderToFbo && clippingRect.IsEmpty())
802 // ClippingRect is empty. Skip rendering
806 // Reset main algorithms command buffer
807 mImpl->renderAlgorithms.ResetCommandBuffer();
809 auto mainCommandBuffer = mImpl->renderAlgorithms.GetMainCommandBuffer();
811 Internal::Scene& sceneInternal = GetImplementation(scene);
812 SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
818 uint32_t instructionCount = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
820 std::vector<Graphics::RenderTarget*> targetstoPresent;
822 Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
823 if(clippingRect == surfaceRect)
825 // Full rendering case
826 // Make clippingRect empty because we're doing full rendering now if the clippingRect is empty.
827 // To reduce side effects, keep this logic now.
828 clippingRect = Rect<int>();
831 // Prefetch programs before we start rendering so reflection is
832 // ready, and we can pull exact size of UBO needed (no need to resize during drawing)
833 auto totalSizeCPU = 0u;
834 auto totalSizeGPU = 0u;
836 for(uint32_t i = 0; i < instructionCount; ++i)
838 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
840 if((instruction.mFrameBuffer != nullptr && renderToFbo) ||
841 (instruction.mFrameBuffer == nullptr && !renderToFbo))
843 for(auto j = 0u; j < instruction.RenderListCount(); ++j)
845 const auto& renderList = instruction.GetRenderList(j);
846 for(auto k = 0u; k < renderList->Count(); ++k)
848 auto& item = renderList->GetItem(k);
849 if(item.mRenderer && item.mRenderer->NeedsProgram())
851 // Prepare and store used programs for further processing
852 auto program = item.mRenderer->PrepareProgram(instruction);
855 auto memoryRequirements = program->GetUniformBlocksMemoryRequirements();
857 totalSizeCPU += memoryRequirements.totalCpuSizeRequired;
858 totalSizeGPU += memoryRequirements.totalGpuSizeRequired;
866 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Render scene (%s), CPU:%d GPU:%d\n", renderToFbo ? "Offscreen" : "Onscreen", totalSizeCPU, totalSizeGPU);
868 auto& uboManager = mImpl->uniformBufferManager;
870 uboManager->SetCurrentSceneRenderInfo(sceneObject, renderToFbo);
871 uboManager->Rollback(sceneObject, renderToFbo);
873 // Respec UBOs for this frame (orphan buffers or double buffer in the GPU)
876 uboManager->GetUniformBufferForScene(sceneObject, renderToFbo, true)->ReSpecify(totalSizeCPU);
877 uboManager->GetUniformBufferForScene(sceneObject, renderToFbo, false)->ReSpecify(totalSizeGPU);
880 #if defined(DEBUG_ENABLED)
881 auto uniformBuffer1 = uboManager->GetUniformBufferForScene(sceneObject, renderToFbo, true);
882 auto uniformBuffer2 = uboManager->GetUniformBufferForScene(sceneObject, renderToFbo, false);
885 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "CPU buffer: Offset(%d), Cap(%d)\n", uniformBuffer1->GetCurrentOffset(), uniformBuffer1->GetCurrentCapacity());
889 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "CPU buffer: nil\n");
893 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "GPU buffer: Offset(%d), Cap(%d)\n", uniformBuffer2->GetCurrentOffset(), uniformBuffer2->GetCurrentCapacity());
897 DALI_LOG_INFO(gLogFilter, Debug::Verbose, "GPU buffer: nil\n");
901 for(uint32_t i = 0; i < instructionCount; ++i)
903 RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
905 if((renderToFbo && !instruction.mFrameBuffer) || (!renderToFbo && instruction.mFrameBuffer))
910 // Mark that we will require a post-render step to be performed (includes swap-buffers).
911 status.SetNeedsPostRender(true);
913 Rect<int32_t> viewportRect;
915 int32_t surfaceOrientation = sceneObject->GetSurfaceOrientation() + sceneObject->GetScreenOrientation();
916 if(surfaceOrientation >= 360)
918 surfaceOrientation -= 360;
921 // @todo Should these be part of scene?
922 Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
923 Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
925 Graphics::RenderTarget* currentRenderTarget = nullptr;
926 Graphics::RenderPass* currentRenderPass = nullptr;
927 std::vector<Graphics::ClearValue> currentClearValues{};
929 if(instruction.mFrameBuffer)
931 // Ensure graphics framebuffer is created, bind attachments and create render passes
932 // Only happens once per framebuffer. If the create fails, e.g. no attachments yet,
933 // then don't render to this framebuffer.
934 if(!instruction.mFrameBuffer->GetGraphicsObject())
936 const bool created = instruction.mFrameBuffer->CreateGraphicsObjects();
943 auto& clearValues = instruction.mFrameBuffer->GetGraphicsRenderPassClearValues();
945 // Set the clear color for first color attachment
946 if(instruction.mIsClearColorSet && !clearValues.empty())
948 clearValues[0].color = {
949 instruction.mClearColor.r,
950 instruction.mClearColor.g,
951 instruction.mClearColor.b,
952 instruction.mClearColor.a};
955 currentClearValues = clearValues;
957 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
960 currentRenderTarget = instruction.mFrameBuffer->GetGraphicsRenderTarget();
961 currentRenderPass = instruction.mFrameBuffer->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
963 else // no framebuffer
966 auto& clearValues = sceneObject->GetGraphicsRenderPassClearValues();
968 if(instruction.mIsClearColorSet)
970 clearValues[0].color = {
971 instruction.mClearColor.r,
972 instruction.mClearColor.g,
973 instruction.mClearColor.b,
974 instruction.mClearColor.a};
977 currentClearValues = clearValues;
979 // @todo SceneObject should already have the depth clear / stencil clear in the clearValues array.
980 // if the window has a depth/stencil buffer.
981 if((depthBufferAvailable == Integration::DepthBufferAvailable::TRUE ||
982 stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE) &&
983 (currentClearValues.size() <= 1))
985 currentClearValues.emplace_back();
986 currentClearValues.back().depthStencil.depth = 0;
987 currentClearValues.back().depthStencil.stencil = 0;
990 auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
992 currentRenderTarget = sceneObject->GetSurfaceRenderTarget();
993 currentRenderPass = sceneObject->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
996 targetstoPresent.emplace_back(currentRenderTarget);
998 // reset the program matrices for all programs once per frame
999 // this ensures we will set view and projection matrix once per program per camera
1000 mImpl->programController.ResetProgramMatrices();
1002 if(!instruction.mIgnoreRenderToFbo && (instruction.mFrameBuffer != nullptr))
1004 // Offscreen buffer rendering
1005 if(instruction.mIsViewportSet)
1007 // For Viewport the lower-left corner is (0,0)
1008 const int32_t y = (instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height) - instruction.mViewport.y;
1009 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
1013 viewportRect.Set(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
1015 surfaceOrientation = 0;
1017 else // No Offscreen frame buffer rendering
1019 // Check whether a viewport is specified, otherwise the full surface size is used
1020 if(instruction.mIsViewportSet)
1022 // For Viewport the lower-left corner is (0,0)
1023 const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
1024 viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
1028 viewportRect = surfaceRect;
1032 // Set surface orientation
1033 // @todo Inform graphics impl by another route.
1034 // was: mImpl->currentContext->SetSurfaceOrientation(surfaceOrientation);
1036 /*** Clear region of framebuffer or surface before drawing ***/
1037 bool clearFullFrameRect = (surfaceRect == viewportRect);
1038 if(instruction.mFrameBuffer != nullptr)
1040 Viewport frameRect(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
1041 clearFullFrameRect = (frameRect == viewportRect);
1044 if(!clippingRect.IsEmpty())
1046 if(!clippingRect.Intersect(viewportRect))
1048 DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
1049 clippingRect = Rect<int>();
1051 clearFullFrameRect = false;
1054 Graphics::Rect2D scissorArea{viewportRect.x, viewportRect.y, uint32_t(viewportRect.width), uint32_t(viewportRect.height)};
1055 if(instruction.mIsClearColorSet)
1057 if(!clearFullFrameRect)
1059 if(!clippingRect.IsEmpty())
1061 scissorArea = {clippingRect.x, clippingRect.y, uint32_t(clippingRect.width), uint32_t(clippingRect.height)};
1066 // Scissor's value should be set based on the default system coordinates.
1067 // When the surface is rotated, the input values already were set with the rotated angle.
1068 // So, re-calculation is needed.
1069 scissorArea = RecalculateScissorArea(scissorArea, surfaceOrientation, surfaceRect);
1071 // Begin render pass
1072 mainCommandBuffer->BeginRenderPass(
1074 currentRenderTarget,
1076 currentClearValues);
1078 mainCommandBuffer->SetViewport({float(viewportRect.x),
1079 float(viewportRect.y),
1080 float(viewportRect.width),
1081 float(viewportRect.height)});
1083 mImpl->renderAlgorithms.ProcessRenderInstruction(
1085 mImpl->renderBufferIndex,
1086 depthBufferAvailable,
1087 stencilBufferAvailable,
1091 Uint16Pair(surfaceRect.width, surfaceRect.height));
1093 Graphics::SyncObject* syncObject{nullptr};
1094 // If the render instruction has an associated render tracker (owned separately)
1095 // and framebuffer, create a one shot sync object, and use it to determine when
1096 // the render pass has finished executing on GPU.
1097 if(instruction.mRenderTracker && instruction.mFrameBuffer)
1099 syncObject = instruction.mRenderTracker->CreateSyncObject(mImpl->graphicsController);
1100 instruction.mRenderTracker = nullptr;
1102 mainCommandBuffer->EndRenderPass(syncObject);
1106 mImpl->uniformBufferManager->Flush(sceneObject, renderToFbo);
1108 mImpl->renderAlgorithms.SubmitCommandBuffer();
1109 mImpl->commandBufferSubmitted = true;
1111 std::sort(targetstoPresent.begin(), targetstoPresent.end());
1113 Graphics::RenderTarget* rt = nullptr;
1114 for(auto& target : targetstoPresent)
1118 mImpl->graphicsController.PresentRenderTarget(target);
1124 void RenderManager::PostRender()
1126 if(!mImpl->commandBufferSubmitted)
1128 // Rendering is skipped but there may be pending tasks. Flush them.
1129 Graphics::SubmitInfo submitInfo;
1130 submitInfo.cmdBuffer.clear(); // Only flush
1131 submitInfo.flags = 0 | Graphics::SubmitFlagBits::FLUSH;
1132 mImpl->graphicsController.SubmitCommandBuffers(submitInfo);
1134 mImpl->commandBufferSubmitted = true;
1137 // Notify RenderGeometries that rendering has finished
1138 for(auto&& iter : mImpl->geometryContainer)
1140 iter->OnRenderFinished();
1143 // Notify updated RenderTexture that rendering has finished
1144 for(auto&& iter : mImpl->updatedTextures)
1146 iter->OnRenderFinished();
1148 mImpl->updatedTextures.Clear();
1150 // Remove discarded textures after OnRenderFinished called
1151 mImpl->textureDiscardQueue.Clear();
1153 mImpl->UpdateTrackers();
1155 uint32_t count = 0u;
1156 for(auto& scene : mImpl->sceneContainer)
1158 count += scene->GetRenderInstructions().Count(mImpl->renderBufferIndex);
1161 // Remove unused shader and programs during CACHE_CLEAN_FRAME_COUNT frames.
1162 // TODO : Cache clean logic have some problem now. Just block it until bug resolved
1164 if(mImpl->frameCount % CACHE_CLEAN_FRAME_COUNT == 0)
1166 mImpl->programController.ClearUnusedCache();
1167 mImpl->shaderCache.ClearUnusedCache();
1171 const bool haveInstructions = count > 0u;
1173 // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
1174 mImpl->lastFrameWasRendered = haveInstructions;
1177 * The rendering has finished; swap to the next buffer.
1178 * Ideally the update has just finished using this buffer; otherwise the render thread
1179 * should block until the update has finished.
1181 mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1183 DALI_PRINT_RENDER_END();
1186 } // namespace SceneGraph
1188 } // namespace Internal