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