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