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