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