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