Merge "Added rotation support to frame-callback" into devel/master
[platform/core/uifw/dali-core.git] / dali / internal / render / common / render-manager.cpp
1 /*
2  * Copyright (c) 2023 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali/internal/render/common/render-manager.h>
20
21 // EXTERNAL INCLUDES
22 #include <memory.h>
23
24 // INTERNAL INCLUDES
25 #include <dali/devel-api/threading/thread-pool.h>
26 #include <dali/integration-api/core.h>
27
28 #include <dali/internal/event/common/scene-impl.h>
29
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>
33
34 #include <dali/internal/common/owner-key-container.h>
35
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/shader-cache.h>
45 #include <dali/internal/render/renderers/uniform-buffer-manager.h>
46 #include <dali/internal/render/renderers/uniform-buffer-view-pool.h>
47 #include <dali/internal/render/shaders/program-controller.h>
48
49 #include <memory>
50
51 namespace Dali
52 {
53 namespace Internal
54 {
55 namespace SceneGraph
56 {
57 #if defined(DEBUG_ENABLED)
58 namespace
59 {
60 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_MANAGER");
61 } // unnamed namespace
62 #endif
63
64 namespace
65 {
66 inline Graphics::Rect2D RecalculateScissorArea(Graphics::Rect2D scissorArea, int orientation, Rect<int32_t> viewportRect)
67 {
68   Graphics::Rect2D newScissorArea;
69
70   if(orientation == 90)
71   {
72     newScissorArea.x      = viewportRect.height - (scissorArea.y + scissorArea.height);
73     newScissorArea.y      = scissorArea.x;
74     newScissorArea.width  = scissorArea.height;
75     newScissorArea.height = scissorArea.width;
76   }
77   else if(orientation == 180)
78   {
79     newScissorArea.x      = viewportRect.width - (scissorArea.x + scissorArea.width);
80     newScissorArea.y      = viewportRect.height - (scissorArea.y + scissorArea.height);
81     newScissorArea.width  = scissorArea.width;
82     newScissorArea.height = scissorArea.height;
83   }
84   else if(orientation == 270)
85   {
86     newScissorArea.x      = scissorArea.y;
87     newScissorArea.y      = viewportRect.width - (scissorArea.x + scissorArea.width);
88     newScissorArea.width  = scissorArea.height;
89     newScissorArea.height = scissorArea.width;
90   }
91   else
92   {
93     newScissorArea.x      = scissorArea.x;
94     newScissorArea.y      = scissorArea.y;
95     newScissorArea.width  = scissorArea.width;
96     newScissorArea.height = scissorArea.height;
97   }
98   return newScissorArea;
99 }
100 } // namespace
101
102 /**
103  * Structure to contain internal data
104  */
105 struct RenderManager::Impl
106 {
107   Impl(Graphics::Controller&               graphicsController,
108        Integration::DepthBufferAvailable   depthBufferAvailableParam,
109        Integration::StencilBufferAvailable stencilBufferAvailableParam,
110        Integration::PartialUpdateAvailable partialUpdateAvailableParam)
111   : graphicsController(graphicsController),
112     renderAlgorithms(graphicsController),
113     programController(graphicsController),
114     shaderCache(graphicsController),
115     depthBufferAvailable(depthBufferAvailableParam),
116     stencilBufferAvailable(stencilBufferAvailableParam),
117     partialUpdateAvailable(partialUpdateAvailableParam)
118   {
119     // Create thread pool with just one thread ( there may be a need to create more threads in the future ).
120     threadPool = std::make_unique<Dali::ThreadPool>();
121     threadPool->Initialize(1u);
122
123     uniformBufferManager = std::make_unique<Render::UniformBufferManager>(&graphicsController);
124     pipelineCache        = std::make_unique<Render::PipelineCache>(graphicsController);
125   }
126
127   ~Impl()
128   {
129     threadPool.reset(nullptr); // reset now to maintain correct destruction order
130   }
131
132   void AddRenderTracker(Render::RenderTracker* renderTracker)
133   {
134     DALI_ASSERT_DEBUG(renderTracker != nullptr);
135     mRenderTrackers.PushBack(renderTracker);
136   }
137
138   void RemoveRenderTracker(Render::RenderTracker* renderTracker)
139   {
140     mRenderTrackers.EraseObject(renderTracker);
141   }
142
143   void UpdateTrackers()
144   {
145     for(auto&& iter : mRenderTrackers)
146     {
147       iter->PollSyncObject();
148     }
149   }
150
151   // the order is important for destruction,
152   Graphics::Controller&           graphicsController;
153   RenderQueue                     renderQueue;      ///< A message queue for receiving messages from the update-thread.
154   std::vector<SceneGraph::Scene*> sceneContainer;   ///< List of pointers to the scene graph objects of the scenes
155   Render::RenderAlgorithms        renderAlgorithms; ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
156
157   OwnerContainer<Render::Sampler*>       samplerContainer;      ///< List of owned samplers
158   OwnerContainer<Render::FrameBuffer*>   frameBufferContainer;  ///< List of owned framebuffers
159   OwnerContainer<Render::VertexBuffer*>  vertexBufferContainer; ///< List of owned vertex buffers
160   OwnerContainer<Render::Geometry*>      geometryContainer;     ///< List of owned Geometries
161   OwnerContainer<Render::RenderTracker*> mRenderTrackers;       ///< List of render trackers
162   OwnerKeyContainer<Render::Renderer>    rendererContainer;     ///< List of owned renderers
163   OwnerKeyContainer<Render::Texture>     textureContainer;      ///< List of owned textures
164
165   ProgramController   programController; ///< Owner of the programs
166   Render::ShaderCache shaderCache;       ///< The cache for the graphics shaders
167
168   std::unique_ptr<Render::UniformBufferManager> uniformBufferManager; ///< The uniform buffer manager
169   std::unique_ptr<Render::PipelineCache>        pipelineCache;
170
171   Integration::DepthBufferAvailable   depthBufferAvailable;   ///< Whether the depth buffer is available
172   Integration::StencilBufferAvailable stencilBufferAvailable; ///< Whether the stencil buffer is available
173   Integration::PartialUpdateAvailable partialUpdateAvailable; ///< Whether the partial update is available
174
175   std::unique_ptr<Dali::ThreadPool> threadPool;            ///< The thread pool
176   Vector<Graphics::Texture*>        boundTextures;         ///< The textures bound for rendering
177   Vector<Graphics::Texture*>        textureDependencyList; ///< The dependency list of bound textures
178
179   uint32_t    frameCount{0u};                                                    ///< The current frame count
180   BufferIndex renderBufferIndex{SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX}; ///< The index of the buffer to read from; this is opposite of the "update" buffer
181
182   bool lastFrameWasRendered{false}; ///< Keeps track of the last frame being rendered due to having render instructions
183   bool commandBufferSubmitted{false};
184 };
185
186 RenderManager* RenderManager::New(Graphics::Controller&               graphicsController,
187                                   Integration::DepthBufferAvailable   depthBufferAvailable,
188                                   Integration::StencilBufferAvailable stencilBufferAvailable,
189                                   Integration::PartialUpdateAvailable partialUpdateAvailable)
190 {
191   auto* manager  = new RenderManager;
192   manager->mImpl = new Impl(graphicsController,
193                             depthBufferAvailable,
194                             stencilBufferAvailable,
195                             partialUpdateAvailable);
196   return manager;
197 }
198
199 RenderManager::RenderManager()
200 : mImpl(nullptr)
201 {
202 }
203
204 RenderManager::~RenderManager()
205 {
206   delete mImpl;
207 }
208
209 RenderQueue& RenderManager::GetRenderQueue()
210 {
211   return mImpl->renderQueue;
212 }
213
214 void RenderManager::SetShaderSaver(ShaderSaver& upstream)
215 {
216 }
217
218 void RenderManager::AddRenderer(const Render::RendererKey& renderer)
219 {
220   // Initialize the renderer as we are now in render thread
221   renderer->Initialize(mImpl->graphicsController, mImpl->programController, mImpl->shaderCache, *(mImpl->uniformBufferManager.get()), *(mImpl->pipelineCache.get()));
222
223   mImpl->rendererContainer.PushBack(renderer);
224 }
225
226 void RenderManager::RemoveRenderer(const Render::RendererKey& renderer)
227 {
228   mImpl->rendererContainer.EraseKey(renderer);
229 }
230
231 void RenderManager::AddSampler(OwnerPointer<Render::Sampler>& sampler)
232 {
233   sampler->Initialize(mImpl->graphicsController);
234   mImpl->samplerContainer.PushBack(sampler.Release());
235 }
236
237 void RenderManager::RemoveSampler(Render::Sampler* sampler)
238 {
239   mImpl->samplerContainer.EraseObject(sampler);
240 }
241
242 void RenderManager::AddTexture(const Render::TextureKey& textureKey)
243 {
244   DALI_ASSERT_DEBUG(textureKey && "Trying to add empty texture key");
245
246   textureKey->Initialize(mImpl->graphicsController);
247   mImpl->textureContainer.PushBack(textureKey);
248 }
249
250 void RenderManager::RemoveTexture(const Render::TextureKey& textureKey)
251 {
252   DALI_ASSERT_DEBUG(textureKey && "Trying to remove empty texture key");
253
254   // Find the texture, use std::find so we can do the erase safely
255   auto iter = std::find(mImpl->textureContainer.begin(), mImpl->textureContainer.end(), textureKey);
256
257   if(iter != mImpl->textureContainer.end())
258   {
259     textureKey->Destroy();
260     mImpl->textureContainer.Erase(iter); // Texture found; now destroy it
261   }
262 }
263
264 void RenderManager::UploadTexture(const Render::TextureKey& textureKey, PixelDataPtr pixelData, const Texture::UploadParams& params)
265 {
266   DALI_ASSERT_DEBUG(textureKey && "Trying to upload to empty texture key");
267   textureKey->Upload(pixelData, params);
268 }
269
270 void RenderManager::GenerateMipmaps(const Render::TextureKey& textureKey)
271 {
272   DALI_ASSERT_DEBUG(textureKey && "Trying to generate mipmaps on empty texture key");
273   textureKey->GenerateMipmaps();
274 }
275
276 void RenderManager::SetFilterMode(Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode)
277 {
278   sampler->SetFilterMode(static_cast<Dali::FilterMode::Type>(minFilterMode),
279                          static_cast<Dali::FilterMode::Type>(magFilterMode));
280 }
281
282 void RenderManager::SetWrapMode(Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode)
283 {
284   sampler->SetWrapMode(static_cast<Dali::WrapMode::Type>(rWrapMode),
285                        static_cast<Dali::WrapMode::Type>(sWrapMode),
286                        static_cast<Dali::WrapMode::Type>(tWrapMode));
287 }
288
289 void RenderManager::AddFrameBuffer(OwnerPointer<Render::FrameBuffer>& frameBuffer)
290 {
291   Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
292   mImpl->frameBufferContainer.PushBack(frameBufferPtr);
293   frameBufferPtr->Initialize(mImpl->graphicsController);
294 }
295
296 void RenderManager::RemoveFrameBuffer(Render::FrameBuffer* frameBuffer)
297 {
298   DALI_ASSERT_DEBUG(nullptr != frameBuffer);
299
300   // Find the framebuffer, use std:find so we can safely do the erase
301   auto iter = std::find(mImpl->frameBufferContainer.begin(), mImpl->frameBufferContainer.end(), frameBuffer);
302
303   if(iter != mImpl->frameBufferContainer.end())
304   {
305     frameBuffer->Destroy();
306     mImpl->frameBufferContainer.Erase(iter); // frameBuffer found; now destroy it
307   }
308 }
309
310 void RenderManager::InitializeScene(SceneGraph::Scene* scene)
311 {
312   scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
313   mImpl->sceneContainer.push_back(scene);
314 }
315
316 void RenderManager::UninitializeScene(SceneGraph::Scene* scene)
317 {
318   auto iter = std::find(mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene);
319   if(iter != mImpl->sceneContainer.end())
320   {
321     mImpl->sceneContainer.erase(iter);
322   }
323 }
324
325 void RenderManager::SurfaceReplaced(SceneGraph::Scene* scene)
326 {
327   scene->Initialize(mImpl->graphicsController, mImpl->depthBufferAvailable, mImpl->stencilBufferAvailable);
328 }
329
330 void RenderManager::AttachColorTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer)
331 {
332   frameBuffer->AttachColorTexture(texture, mipmapLevel, layer);
333 }
334
335 void RenderManager::AttachDepthTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
336 {
337   frameBuffer->AttachDepthTexture(texture, mipmapLevel);
338 }
339
340 void RenderManager::AttachDepthStencilTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
341 {
342   frameBuffer->AttachDepthStencilTexture(texture, mipmapLevel);
343 }
344
345 void RenderManager::SetMultiSamplingLevelToFrameBuffer(Render::FrameBuffer* frameBuffer, uint8_t multiSamplingLevel)
346 {
347   frameBuffer->SetMultiSamplingLevel(multiSamplingLevel);
348 }
349
350 void RenderManager::AddVertexBuffer(OwnerPointer<Render::VertexBuffer>& vertexBuffer)
351 {
352   mImpl->vertexBufferContainer.PushBack(vertexBuffer.Release());
353 }
354
355 void RenderManager::RemoveVertexBuffer(Render::VertexBuffer* vertexBuffer)
356 {
357   mImpl->vertexBufferContainer.EraseObject(vertexBuffer);
358 }
359
360 void RenderManager::SetVertexBufferFormat(Render::VertexBuffer* vertexBuffer, OwnerPointer<Render::VertexBuffer::Format>& format)
361 {
362   vertexBuffer->SetFormat(format.Release());
363 }
364
365 void RenderManager::SetVertexBufferData(Render::VertexBuffer* vertexBuffer, OwnerPointer<Vector<uint8_t>>& data, uint32_t size)
366 {
367   vertexBuffer->SetData(data.Release(), size);
368 }
369
370 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Dali::Vector<uint16_t>& indices)
371 {
372   geometry->SetIndexBuffer(indices);
373 }
374
375 void RenderManager::AddGeometry(OwnerPointer<Render::Geometry>& geometry)
376 {
377   mImpl->geometryContainer.PushBack(geometry.Release());
378 }
379
380 void RenderManager::RemoveGeometry(Render::Geometry* geometry)
381 {
382   auto iter = std::find(mImpl->geometryContainer.begin(), mImpl->geometryContainer.end(), geometry);
383
384   if(iter != mImpl->geometryContainer.end())
385   {
386     mImpl->geometryContainer.Erase(iter);
387   }
388 }
389
390 void RenderManager::AttachVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
391 {
392   DALI_ASSERT_DEBUG(nullptr != geometry);
393
394   // Find the geometry
395   for(auto&& iter : mImpl->geometryContainer)
396   {
397     if(iter == geometry)
398     {
399       iter->AddVertexBuffer(vertexBuffer);
400       break;
401     }
402   }
403 }
404
405 void RenderManager::RemoveVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
406 {
407   DALI_ASSERT_DEBUG(nullptr != geometry);
408
409   // Find the geometry
410   for(auto&& iter : mImpl->geometryContainer)
411   {
412     if(iter == geometry)
413     {
414       iter->RemoveVertexBuffer(vertexBuffer);
415       break;
416     }
417   }
418 }
419
420 void RenderManager::SetGeometryType(Render::Geometry* geometry, uint32_t geometryType)
421 {
422   geometry->SetType(Render::Geometry::Type(geometryType));
423 }
424
425 void RenderManager::AddRenderTracker(Render::RenderTracker* renderTracker)
426 {
427   mImpl->AddRenderTracker(renderTracker);
428 }
429
430 void RenderManager::RemoveRenderTracker(Render::RenderTracker* renderTracker)
431 {
432   mImpl->RemoveRenderTracker(renderTracker);
433 }
434
435 void RenderManager::PreRender(Integration::RenderStatus& status, bool forceClear)
436 {
437   DALI_PRINT_RENDER_START(mImpl->renderBufferIndex);
438
439   // Rollback
440   mImpl->uniformBufferManager->GetUniformBufferViewPool(mImpl->renderBufferIndex)->Rollback();
441
442   // Increment the frame count at the beginning of each frame
443   ++mImpl->frameCount;
444
445   // Process messages queued during previous update
446   mImpl->renderQueue.ProcessMessages(mImpl->renderBufferIndex);
447
448   uint32_t count = 0u;
449   for(auto& i : mImpl->sceneContainer)
450   {
451     count += i->GetRenderInstructions().Count(mImpl->renderBufferIndex);
452   }
453
454   const bool haveInstructions = count > 0u;
455
456   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");
457
458   // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
459   if(haveInstructions || mImpl->lastFrameWasRendered || forceClear)
460   {
461     DALI_LOG_INFO(gLogFilter, Debug::General, "Render: Processing\n");
462
463     // Upload the geometries
464     for(auto&& geom : mImpl->geometryContainer)
465     {
466       geom->Upload(mImpl->graphicsController);
467     }
468   }
469
470   mImpl->commandBufferSubmitted = false;
471 }
472
473 void RenderManager::PreRender(Integration::Scene& scene, std::vector<Rect<int>>& damagedRects)
474 {
475   if(mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
476   {
477     return;
478   }
479
480   Internal::Scene&   sceneInternal = GetImplementation(scene);
481   SceneGraph::Scene* sceneObject   = sceneInternal.GetSceneObject();
482
483   if(sceneObject->IsRenderingSkipped())
484   {
485     // We don't need to calculate dirty rects
486     return;
487   }
488
489   class DamagedRectsCleaner
490   {
491   public:
492     explicit DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects, Rect<int>& surfaceRect)
493     : mDamagedRects(damagedRects),
494       mSurfaceRect(surfaceRect),
495       mCleanOnReturn(true)
496     {
497     }
498
499     void SetCleanOnReturn(bool cleanOnReturn)
500     {
501       mCleanOnReturn = cleanOnReturn;
502     }
503
504     ~DamagedRectsCleaner()
505     {
506       if(mCleanOnReturn)
507       {
508         mDamagedRects.clear();
509         mDamagedRects.push_back(mSurfaceRect);
510       }
511     }
512
513   private:
514     std::vector<Rect<int>>& mDamagedRects;
515     Rect<int>               mSurfaceRect;
516     bool                    mCleanOnReturn;
517   };
518
519   Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
520
521   // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
522   DamagedRectsCleaner damagedRectCleaner(damagedRects, surfaceRect);
523   bool                cleanDamagedRect = false;
524
525   // Mark previous dirty rects in the std::unordered_map.
526   Scene::ItemsDirtyRectsContainer& itemsDirtyRects = sceneObject->GetItemsDirtyRects();
527   for(auto& dirtyRectPair : itemsDirtyRects)
528   {
529     dirtyRectPair.second.visited = false;
530   }
531
532   uint32_t instructionCount = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
533   for(uint32_t i = 0; i < instructionCount; ++i)
534   {
535     RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
536
537     if(instruction.mFrameBuffer)
538     {
539       cleanDamagedRect = true;
540       continue; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
541     }
542
543     const Camera* camera = instruction.GetCamera();
544     if(camera && camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
545     {
546       Vector3    position;
547       Vector3    scale;
548       Quaternion orientation;
549       camera->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
550
551       Vector3 orientationAxis;
552       Radian  orientationAngle;
553       orientation.ToAxisAngle(orientationAxis, orientationAngle);
554
555       if(position.x > Math::MACHINE_EPSILON_10000 ||
556          position.y > Math::MACHINE_EPSILON_10000 ||
557          orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
558          orientationAngle != ANGLE_180 ||
559          scale != Vector3(1.0f, 1.0f, 1.0f))
560       {
561         cleanDamagedRect = true;
562         continue;
563       }
564     }
565     else
566     {
567       cleanDamagedRect = true;
568       continue;
569     }
570
571     Rect<int32_t> viewportRect;
572     if(instruction.mIsViewportSet)
573     {
574       const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
575       viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
576       if(viewportRect.IsEmpty() || !viewportRect.IsValid())
577       {
578         cleanDamagedRect = true;
579         continue; // just skip funny use cases for now, empty viewport means it is set somewhere else
580       }
581     }
582     else
583     {
584       viewportRect = surfaceRect;
585     }
586
587     const Matrix* viewMatrix       = instruction.GetViewMatrix(mImpl->renderBufferIndex);
588     const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
589     if(viewMatrix && projectionMatrix)
590     {
591       const RenderListContainer::SizeType count = instruction.RenderListCount();
592       for(RenderListContainer::SizeType index = 0u; index < count; ++index)
593       {
594         const RenderList* renderList = instruction.GetRenderList(index);
595         if(renderList)
596         {
597           if(!renderList->IsEmpty())
598           {
599             const std::size_t listCount = renderList->Count();
600             for(uint32_t listIndex = 0u; listIndex < listCount; ++listIndex)
601             {
602               RenderItem& item = renderList->GetItem(listIndex);
603               // If the item does 3D transformation, make full update
604               if(item.mUpdateArea == Vector4::ZERO)
605               {
606                 cleanDamagedRect = true;
607
608                 // Save the full rect in the damaged list. We need it when this item is removed
609                 DirtyRectKey dirtyRectKey(item.mNode, item.mRenderer);
610                 auto         dirtyRectPos = itemsDirtyRects.find(dirtyRectKey);
611                 if(dirtyRectPos != itemsDirtyRects.end())
612                 {
613                   // Replace the rect
614                   dirtyRectPos->second.visited = true;
615                   dirtyRectPos->second.rect    = surfaceRect;
616                 }
617                 else
618                 {
619                   // Else, just insert the new dirtyrect
620                   itemsDirtyRects.insert({dirtyRectKey, surfaceRect});
621                 }
622                 continue;
623               }
624
625               Rect<int>    rect;
626               DirtyRectKey dirtyRectKey(item.mNode, item.mRenderer);
627               // If the item refers to updated node or renderer.
628               if(item.mIsUpdated ||
629                  (item.mNode &&
630                   (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex)))))
631               {
632                 item.mIsUpdated = false;
633
634                 Vector4 updateArea = item.mRenderer ? item.mRenderer->GetVisualTransformedUpdateArea(mImpl->renderBufferIndex, item.mUpdateArea) : item.mUpdateArea;
635
636                 rect = RenderItem::CalculateViewportSpaceAABB(item.mModelViewMatrix, Vector3(updateArea.x, updateArea.y, 0.0f), Vector3(updateArea.z, updateArea.w, 0.0f), viewportRect.width, viewportRect.height);
637                 if(rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
638                 {
639                   const int left   = rect.x;
640                   const int top    = rect.y;
641                   const int right  = rect.x + rect.width;
642                   const int bottom = rect.y + rect.height;
643                   rect.x           = (left / 16) * 16;
644                   rect.y           = (top / 16) * 16;
645                   rect.width       = ((right + 16) / 16) * 16 - rect.x;
646                   rect.height      = ((bottom + 16) / 16) * 16 - rect.y;
647
648                   // Found valid dirty rect.
649                   auto dirtyRectPos = itemsDirtyRects.find(dirtyRectKey);
650                   if(dirtyRectPos != itemsDirtyRects.end())
651                   {
652                     Rect<int> currentRect = rect;
653
654                     // Same item, merge it with the previous rect
655                     rect.Merge(dirtyRectPos->second.rect);
656
657                     // Replace the rect as current
658                     dirtyRectPos->second.visited = true;
659                     dirtyRectPos->second.rect    = currentRect;
660                   }
661                   else
662                   {
663                     // Else, just insert the new dirtyrect
664                     itemsDirtyRects.insert({dirtyRectKey, rect});
665                   }
666
667                   damagedRects.push_back(rect);
668                 }
669               }
670               else
671               {
672                 // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
673                 // 2. Mark the related dirty rects as visited so they will not be removed below.
674                 auto dirtyRectPos = itemsDirtyRects.find(dirtyRectKey);
675                 if(dirtyRectPos != itemsDirtyRects.end())
676                 {
677                   dirtyRectPos->second.visited = true;
678                 }
679                 else
680                 {
681                   // The item is not in the list for some reason. Add it!
682                   itemsDirtyRects.insert({dirtyRectKey, surfaceRect});
683                   cleanDamagedRect = true; // And make full update at this frame
684                 }
685               }
686             }
687           }
688         }
689       }
690     }
691   }
692
693   // Check removed nodes or removed renderers dirty rects
694   // Note, std::unordered_map end iterator is validate if we call erase.
695   for(auto iter = itemsDirtyRects.cbegin(), iterEnd = itemsDirtyRects.cend(); iter != iterEnd;)
696   {
697     if(!iter->second.visited)
698     {
699       damagedRects.push_back(iter->second.rect);
700       iter = itemsDirtyRects.erase(iter);
701     }
702     else
703     {
704       ++iter;
705     }
706   }
707
708   if(!cleanDamagedRect)
709   {
710     damagedRectCleaner.SetCleanOnReturn(false);
711   }
712 }
713
714 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo)
715 {
716   SceneGraph::Scene* sceneObject  = GetImplementation(scene).GetSceneObject();
717   Rect<int>          clippingRect = sceneObject->GetSurfaceRect();
718
719   RenderScene(status, scene, renderToFbo, clippingRect);
720 }
721
722 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
723 {
724   if(mImpl->partialUpdateAvailable == Integration::PartialUpdateAvailable::TRUE && !renderToFbo && clippingRect.IsEmpty())
725   {
726     // ClippingRect is empty. Skip rendering
727     return;
728   }
729
730   // Reset main algorithms command buffer
731   mImpl->renderAlgorithms.ResetCommandBuffer();
732
733   auto mainCommandBuffer = mImpl->renderAlgorithms.GetMainCommandBuffer();
734
735   Internal::Scene&   sceneInternal = GetImplementation(scene);
736   SceneGraph::Scene* sceneObject   = sceneInternal.GetSceneObject();
737
738   uint32_t count = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
739
740   std::vector<Graphics::RenderTarget*> targetstoPresent;
741
742   Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
743   if(clippingRect == surfaceRect)
744   {
745     // Full rendering case
746     // Make clippingRect empty because we're doing full rendering now if the clippingRect is empty.
747     // To reduce side effects, keep this logic now.
748     clippingRect = Rect<int>();
749   }
750
751   // Prepare to lock and map standalone uniform buffer.
752   mImpl->uniformBufferManager->ReadyToLockUniformBuffer(mImpl->renderBufferIndex);
753
754   for(uint32_t i = 0; i < count; ++i)
755   {
756     RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
757
758     if((renderToFbo && !instruction.mFrameBuffer) || (!renderToFbo && instruction.mFrameBuffer))
759     {
760       continue; // skip
761     }
762
763     // Mark that we will require a post-render step to be performed (includes swap-buffers).
764     status.SetNeedsPostRender(true);
765
766     Rect<int32_t> viewportRect;
767
768     int32_t surfaceOrientation = sceneObject->GetSurfaceOrientation() + sceneObject->GetScreenOrientation();
769     if(surfaceOrientation >= 360)
770     {
771       surfaceOrientation -= 360;
772     }
773
774     // @todo Should these be part of scene?
775     Integration::DepthBufferAvailable   depthBufferAvailable   = mImpl->depthBufferAvailable;
776     Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
777
778     Graphics::RenderTarget*           currentRenderTarget = nullptr;
779     Graphics::RenderPass*             currentRenderPass   = nullptr;
780     std::vector<Graphics::ClearValue> currentClearValues{};
781
782     if(instruction.mFrameBuffer)
783     {
784       // Ensure graphics framebuffer is created, bind attachments and create render passes
785       // Only happens once per framebuffer. If the create fails, e.g. no attachments yet,
786       // then don't render to this framebuffer.
787       if(!instruction.mFrameBuffer->GetGraphicsObject())
788       {
789         const bool created = instruction.mFrameBuffer->CreateGraphicsObjects();
790         if(!created)
791         {
792           continue;
793         }
794       }
795
796       auto& clearValues = instruction.mFrameBuffer->GetGraphicsRenderPassClearValues();
797
798       // Set the clear color for first color attachment
799       if(instruction.mIsClearColorSet && !clearValues.empty())
800       {
801         clearValues[0].color = {
802           instruction.mClearColor.r,
803           instruction.mClearColor.g,
804           instruction.mClearColor.b,
805           instruction.mClearColor.a};
806       }
807
808       currentClearValues = clearValues;
809
810       auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
811
812       // offscreen buffer
813       currentRenderTarget = instruction.mFrameBuffer->GetGraphicsRenderTarget();
814       currentRenderPass   = instruction.mFrameBuffer->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
815     }
816     else // no framebuffer
817     {
818       // surface
819       auto& clearValues = sceneObject->GetGraphicsRenderPassClearValues();
820
821       if(instruction.mIsClearColorSet)
822       {
823         clearValues[0].color = {
824           instruction.mClearColor.r,
825           instruction.mClearColor.g,
826           instruction.mClearColor.b,
827           instruction.mClearColor.a};
828       }
829
830       currentClearValues = clearValues;
831
832       // @todo SceneObject should already have the depth clear / stencil clear in the clearValues array.
833       // if the window has a depth/stencil buffer.
834       if((depthBufferAvailable == Integration::DepthBufferAvailable::TRUE ||
835           stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE) &&
836          (currentClearValues.size() <= 1))
837       {
838         currentClearValues.emplace_back();
839         currentClearValues.back().depthStencil.depth   = 0;
840         currentClearValues.back().depthStencil.stencil = 0;
841       }
842
843       auto loadOp = instruction.mIsClearColorSet ? Graphics::AttachmentLoadOp::CLEAR : Graphics::AttachmentLoadOp::LOAD;
844
845       currentRenderTarget = sceneObject->GetSurfaceRenderTarget();
846       currentRenderPass   = sceneObject->GetGraphicsRenderPass(loadOp, Graphics::AttachmentStoreOp::STORE);
847     }
848
849     targetstoPresent.emplace_back(currentRenderTarget);
850
851     // reset the program matrices for all programs once per frame
852     // this ensures we will set view and projection matrix once per program per camera
853     mImpl->programController.ResetProgramMatrices();
854
855     if(instruction.mFrameBuffer)
856     {
857       // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
858       for(unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
859       {
860         mImpl->textureDependencyList.PushBack(instruction.mFrameBuffer->GetTexture(i0));
861       }
862     }
863
864     if(!instruction.mIgnoreRenderToFbo && (instruction.mFrameBuffer != nullptr))
865     {
866       // Offscreen buffer rendering
867       if(instruction.mIsViewportSet)
868       {
869         // For Viewport the lower-left corner is (0,0)
870         const int32_t y = (instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height) - instruction.mViewport.y;
871         viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
872       }
873       else
874       {
875         viewportRect.Set(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
876       }
877       surfaceOrientation = 0;
878     }
879     else // No Offscreen frame buffer rendering
880     {
881       // Check whether a viewport is specified, otherwise the full surface size is used
882       if(instruction.mIsViewportSet)
883       {
884         // For Viewport the lower-left corner is (0,0)
885         const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
886         viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
887       }
888       else
889       {
890         viewportRect = surfaceRect;
891       }
892     }
893
894     // Set surface orientation
895     // @todo Inform graphics impl by another route.
896     // was: mImpl->currentContext->SetSurfaceOrientation(surfaceOrientation);
897
898     /*** Clear region of framebuffer or surface before drawing ***/
899     bool clearFullFrameRect = (surfaceRect == viewportRect);
900     if(instruction.mFrameBuffer != nullptr)
901     {
902       Viewport frameRect(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
903       clearFullFrameRect = (frameRect == viewportRect);
904     }
905
906     if(!clippingRect.IsEmpty())
907     {
908       if(!clippingRect.Intersect(viewportRect))
909       {
910         DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
911         clippingRect = Rect<int>();
912       }
913       clearFullFrameRect = false;
914     }
915
916     Graphics::Rect2D scissorArea{viewportRect.x, viewportRect.y, uint32_t(viewportRect.width), uint32_t(viewportRect.height)};
917     if(instruction.mIsClearColorSet)
918     {
919       if(!clearFullFrameRect)
920       {
921         if(!clippingRect.IsEmpty())
922         {
923           scissorArea = {clippingRect.x, clippingRect.y, uint32_t(clippingRect.width), uint32_t(clippingRect.height)};
924         }
925       }
926     }
927
928     // Scissor's value should be set based on the default system coordinates.
929     // When the surface is rotated, the input values already were set with the rotated angle.
930     // So, re-calculation is needed.
931     scissorArea = RecalculateScissorArea(scissorArea, surfaceOrientation, surfaceRect);
932
933     // Begin render pass
934     mainCommandBuffer->BeginRenderPass(
935       currentRenderPass,
936       currentRenderTarget,
937       scissorArea,
938       currentClearValues);
939
940     mainCommandBuffer->SetViewport({float(viewportRect.x),
941                                     float(viewportRect.y),
942                                     float(viewportRect.width),
943                                     float(viewportRect.height)});
944
945     // Clear the list of bound textures
946     mImpl->boundTextures.Clear();
947
948     mImpl->renderAlgorithms.ProcessRenderInstruction(
949       instruction,
950       mImpl->renderBufferIndex,
951       depthBufferAvailable,
952       stencilBufferAvailable,
953       mImpl->boundTextures,
954       viewportRect,
955       clippingRect,
956       surfaceOrientation,
957       Uint16Pair(surfaceRect.width, surfaceRect.height));
958
959     Graphics::SyncObject* syncObject{nullptr};
960     // If the render instruction has an associated render tracker (owned separately)
961     // and framebuffer, create a one shot sync object, and use it to determine when
962     // the render pass has finished executing on GPU.
963     if(instruction.mRenderTracker && instruction.mFrameBuffer)
964     {
965       syncObject                 = instruction.mRenderTracker->CreateSyncObject(mImpl->graphicsController);
966       instruction.mRenderTracker = nullptr;
967     }
968     mainCommandBuffer->EndRenderPass(syncObject);
969   }
970
971   // Unlock standalone uniform buffer.
972   mImpl->uniformBufferManager->UnlockUniformBuffer(mImpl->renderBufferIndex);
973
974   mImpl->renderAlgorithms.SubmitCommandBuffer();
975   mImpl->commandBufferSubmitted = true;
976
977   std::sort(targetstoPresent.begin(), targetstoPresent.end());
978
979   Graphics::RenderTarget* rt = nullptr;
980   for(auto& target : targetstoPresent)
981   {
982     if(target != rt)
983     {
984       mImpl->graphicsController.PresentRenderTarget(target);
985       rt = target;
986     }
987   }
988 }
989
990 void RenderManager::PostRender()
991 {
992   if(!mImpl->commandBufferSubmitted)
993   {
994     // Rendering is skipped but there may be pending tasks. Flush them.
995     Graphics::SubmitInfo submitInfo;
996     submitInfo.cmdBuffer.clear(); // Only flush
997     submitInfo.flags = 0 | Graphics::SubmitFlagBits::FLUSH;
998     mImpl->graphicsController.SubmitCommandBuffers(submitInfo);
999
1000     mImpl->commandBufferSubmitted = true;
1001   }
1002
1003   // Notify RenderGeometries that rendering has finished
1004   for(auto&& iter : mImpl->geometryContainer)
1005   {
1006     iter->OnRenderFinished();
1007   }
1008
1009   // Notify RenderTexture that rendering has finished
1010   for(auto&& iter : mImpl->textureContainer)
1011   {
1012     iter->OnRenderFinished();
1013   }
1014
1015   mImpl->UpdateTrackers();
1016
1017   uint32_t count = 0u;
1018   for(auto& scene : mImpl->sceneContainer)
1019   {
1020     count += scene->GetRenderInstructions().Count(mImpl->renderBufferIndex);
1021   }
1022
1023   const bool haveInstructions = count > 0u;
1024
1025   // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
1026   mImpl->lastFrameWasRendered = haveInstructions;
1027
1028   /**
1029    * The rendering has finished; swap to the next buffer.
1030    * Ideally the update has just finished using this buffer; otherwise the render thread
1031    * should block until the update has finished.
1032    */
1033   mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1034
1035   DALI_PRINT_RENDER_END();
1036 }
1037
1038 } // namespace SceneGraph
1039
1040 } // namespace Internal
1041
1042 } // namespace Dali