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