[Tizen] Partial rendering rotation does not work
[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<GLuint>                    boundTextures;         ///< The textures bound for rendering
172   Vector<GLuint>                    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->GlContextDestroyed();
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->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   mImpl->samplerContainer.PushBack(sampler.Release());
263 }
264
265 void RenderManager::RemoveSampler(Render::Sampler* sampler)
266 {
267   mImpl->samplerContainer.EraseObject(sampler);
268 }
269
270 void RenderManager::AddTexture(OwnerPointer<Render::Texture>& texture)
271 {
272   texture->Initialize(mImpl->context);
273   mImpl->textureContainer.PushBack(texture.Release());
274 }
275
276 void RenderManager::RemoveTexture(Render::Texture* texture)
277 {
278   DALI_ASSERT_DEBUG(NULL != texture);
279
280   // Find the texture, use reference to pointer so we can do the erase safely
281   for(auto&& iter : mImpl->textureContainer)
282   {
283     if(iter == texture)
284     {
285       texture->Destroy(mImpl->context);
286       mImpl->textureContainer.Erase(&iter); // Texture found; now destroy it
287       return;
288     }
289   }
290 }
291
292 void RenderManager::UploadTexture(Render::Texture* texture, PixelDataPtr pixelData, const Texture::UploadParams& params)
293 {
294   texture->Upload(mImpl->context, pixelData, params);
295 }
296
297 void RenderManager::GenerateMipmaps(Render::Texture* texture)
298 {
299   texture->GenerateMipmaps(mImpl->context);
300 }
301
302 void RenderManager::SetFilterMode(Render::Sampler* sampler, uint32_t minFilterMode, uint32_t magFilterMode)
303 {
304   sampler->mMinificationFilter  = static_cast<Dali::FilterMode::Type>(minFilterMode);
305   sampler->mMagnificationFilter = static_cast<Dali::FilterMode::Type>(magFilterMode);
306 }
307
308 void RenderManager::SetWrapMode(Render::Sampler* sampler, uint32_t rWrapMode, uint32_t sWrapMode, uint32_t tWrapMode)
309 {
310   sampler->mRWrapMode = static_cast<Dali::WrapMode::Type>(rWrapMode);
311   sampler->mSWrapMode = static_cast<Dali::WrapMode::Type>(sWrapMode);
312   sampler->mTWrapMode = static_cast<Dali::WrapMode::Type>(tWrapMode);
313 }
314
315 void RenderManager::AddFrameBuffer(OwnerPointer<Render::FrameBuffer>& frameBuffer)
316 {
317   Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
318   mImpl->frameBufferContainer.PushBack(frameBufferPtr);
319   frameBufferPtr->Initialize(mImpl->context);
320 }
321
322 void RenderManager::RemoveFrameBuffer(Render::FrameBuffer* frameBuffer)
323 {
324   DALI_ASSERT_DEBUG(NULL != frameBuffer);
325
326   // Find the sampler, use reference so we can safely do the erase
327   for(auto&& iter : mImpl->frameBufferContainer)
328   {
329     if(iter == frameBuffer)
330     {
331       frameBuffer->Destroy(mImpl->context);
332       mImpl->frameBufferContainer.Erase(&iter); // frameBuffer found; now destroy it
333
334       break;
335     }
336   }
337 }
338
339 void RenderManager::InitializeScene(SceneGraph::Scene* scene)
340 {
341   scene->Initialize(*mImpl->CreateSceneContext());
342   mImpl->sceneContainer.push_back(scene);
343 }
344
345 void RenderManager::UninitializeScene(SceneGraph::Scene* scene)
346 {
347   mImpl->DestroySceneContext(scene->GetContext());
348
349   auto iter = std::find(mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene);
350   if(iter != mImpl->sceneContainer.end())
351   {
352     mImpl->sceneContainer.erase(iter);
353   }
354 }
355
356 void RenderManager::SurfaceReplaced(SceneGraph::Scene* scene)
357 {
358   Context* newContext = mImpl->ReplaceSceneContext(scene->GetContext());
359   scene->Initialize(*newContext);
360 }
361
362 void RenderManager::AttachColorTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer)
363 {
364   frameBuffer->AttachColorTexture(mImpl->context, texture, mipmapLevel, layer);
365 }
366
367 void RenderManager::AttachDepthTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
368 {
369   frameBuffer->AttachDepthTexture(mImpl->context, texture, mipmapLevel);
370 }
371
372 void RenderManager::AttachDepthStencilTextureToFrameBuffer(Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel)
373 {
374   frameBuffer->AttachDepthStencilTexture(mImpl->context, texture, mipmapLevel);
375 }
376
377 void RenderManager::AddVertexBuffer(OwnerPointer<Render::VertexBuffer>& vertexBuffer)
378 {
379   mImpl->vertexBufferContainer.PushBack(vertexBuffer.Release());
380 }
381
382 void RenderManager::RemoveVertexBuffer(Render::VertexBuffer* vertexBuffer)
383 {
384   mImpl->vertexBufferContainer.EraseObject(vertexBuffer);
385 }
386
387 void RenderManager::SetVertexBufferFormat(Render::VertexBuffer* vertexBuffer, OwnerPointer<Render::VertexBuffer::Format>& format)
388 {
389   vertexBuffer->SetFormat(format.Release());
390 }
391
392 void RenderManager::SetVertexBufferData(Render::VertexBuffer* vertexBuffer, OwnerPointer<Vector<uint8_t>>& data, uint32_t size)
393 {
394   vertexBuffer->SetData(data.Release(), size);
395 }
396
397 void RenderManager::SetIndexBuffer(Render::Geometry* geometry, Dali::Vector<uint16_t>& indices)
398 {
399   geometry->SetIndexBuffer(indices);
400 }
401
402 void RenderManager::AddGeometry(OwnerPointer<Render::Geometry>& geometry)
403 {
404   mImpl->geometryContainer.PushBack(geometry.Release());
405 }
406
407 void RenderManager::RemoveGeometry(Render::Geometry* geometry)
408 {
409   mImpl->geometryContainer.EraseObject(geometry);
410 }
411
412 void RenderManager::AttachVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
413 {
414   DALI_ASSERT_DEBUG(NULL != geometry);
415
416   // Find the geometry
417   for(auto&& iter : mImpl->geometryContainer)
418   {
419     if(iter == geometry)
420     {
421       iter->AddVertexBuffer(vertexBuffer);
422       break;
423     }
424   }
425 }
426
427 void RenderManager::RemoveVertexBuffer(Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer)
428 {
429   DALI_ASSERT_DEBUG(NULL != geometry);
430
431   // Find the geometry
432   for(auto&& iter : mImpl->geometryContainer)
433   {
434     if(iter == geometry)
435     {
436       iter->RemoveVertexBuffer(vertexBuffer);
437       break;
438     }
439   }
440 }
441
442 void RenderManager::SetGeometryType(Render::Geometry* geometry, uint32_t geometryType)
443 {
444   geometry->SetType(Render::Geometry::Type(geometryType));
445 }
446
447 void RenderManager::AddRenderTracker(Render::RenderTracker* renderTracker)
448 {
449   mImpl->AddRenderTracker(renderTracker);
450 }
451
452 void RenderManager::RemoveRenderTracker(Render::RenderTracker* renderTracker)
453 {
454   mImpl->RemoveRenderTracker(renderTracker);
455 }
456
457 ProgramCache* RenderManager::GetProgramCache()
458 {
459   return &(mImpl->programController);
460 }
461
462 void RenderManager::PreRender(Integration::RenderStatus& status, bool forceClear, bool uploadOnly)
463 {
464   DALI_PRINT_RENDER_START(mImpl->renderBufferIndex);
465
466   // Core::Render documents that GL context must be current before calling Render
467   DALI_ASSERT_DEBUG(mImpl->context.IsGlContextCreated());
468
469   // Increment the frame count at the beginning of each frame
470   ++mImpl->frameCount;
471
472   // Process messages queued during previous update
473   mImpl->renderQueue.ProcessMessages(mImpl->renderBufferIndex);
474
475   uint32_t count = 0u;
476   for(uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i)
477   {
478     count += mImpl->sceneContainer[i]->GetRenderInstructions().Count(mImpl->renderBufferIndex);
479   }
480
481   const bool haveInstructions = count > 0u;
482
483   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");
484
485   // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
486   if(haveInstructions || mImpl->lastFrameWasRendered || forceClear)
487   {
488     DALI_LOG_INFO(gLogFilter, Debug::General, "Render: Processing\n");
489
490     // Switch to the shared context
491     if(mImpl->currentContext != &mImpl->context)
492     {
493       mImpl->currentContext = &mImpl->context;
494
495       if(mImpl->currentContext->IsSurfacelessContextSupported())
496       {
497         mImpl->graphicsController.GetGlContextHelperAbstraction().MakeSurfacelessContextCurrent();
498       }
499
500       // Clear the current cached program when the context is switched
501       mImpl->programController.ClearCurrentProgram();
502     }
503
504     // Upload the geometries
505     for(uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i)
506     {
507       RenderInstructionContainer& instructions = mImpl->sceneContainer[i]->GetRenderInstructions();
508       for(uint32_t j = 0; j < instructions.Count(mImpl->renderBufferIndex); ++j)
509       {
510         RenderInstruction& instruction = instructions.At(mImpl->renderBufferIndex, j);
511
512         const Matrix* viewMatrix       = instruction.GetViewMatrix(mImpl->renderBufferIndex);
513         const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
514
515         DALI_ASSERT_DEBUG(viewMatrix);
516         DALI_ASSERT_DEBUG(projectionMatrix);
517
518         if(viewMatrix && projectionMatrix)
519         {
520           const RenderListContainer::SizeType renderListCount = instruction.RenderListCount();
521
522           // Iterate through each render list.
523           for(RenderListContainer::SizeType index = 0; index < renderListCount; ++index)
524           {
525             const RenderList* renderList = instruction.GetRenderList(index);
526
527             if(renderList && !renderList->IsEmpty())
528             {
529               const std::size_t itemCount = renderList->Count();
530               for(uint32_t itemIndex = 0u; itemIndex < itemCount; ++itemIndex)
531               {
532                 const RenderItem& item = renderList->GetItem(itemIndex);
533                 if(DALI_LIKELY(item.mRenderer))
534                 {
535                   item.mRenderer->Upload(*mImpl->currentContext);
536                 }
537               }
538             }
539           }
540         }
541       }
542     }
543   }
544 }
545
546 void RenderManager::PreRender(Integration::Scene& scene, std::vector<Rect<int>>& damagedRects)
547 {
548   if(mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
549   {
550     return;
551   }
552
553   Internal::Scene&   sceneInternal = GetImplementation(scene);
554   SceneGraph::Scene* sceneObject   = sceneInternal.GetSceneObject();
555
556   if(sceneObject->IsRenderingSkipped())
557   {
558     // We don't need to calculate dirty rects
559     return;
560   }
561
562   // @TODO We need to do partial rendering rotation.
563   if( sceneObject && sceneObject->GetSurfaceOrientation() != 0 )
564   {
565     return;
566   }
567
568   class DamagedRectsCleaner
569   {
570   public:
571     DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects)
572     : mDamagedRects(damagedRects),
573       mCleanOnReturn(true)
574     {
575     }
576
577     void SetCleanOnReturn(bool cleanOnReturn)
578     {
579       mCleanOnReturn = cleanOnReturn;
580     }
581
582     ~DamagedRectsCleaner()
583     {
584       if(mCleanOnReturn)
585       {
586         mDamagedRects.clear();
587       }
588     }
589
590   private:
591     std::vector<Rect<int>>& mDamagedRects;
592     bool                    mCleanOnReturn;
593   };
594
595   Rect<int32_t> surfaceRect = sceneObject->GetSurfaceRect();
596
597   // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
598   DamagedRectsCleaner damagedRectCleaner(damagedRects);
599
600   // Mark previous dirty rects in the sorted array. The array is already sorted by node and renderer, frame number.
601   // so you don't need to sort: std::stable_sort(itemsDirtyRects.begin(), itemsDirtyRects.end());
602   std::vector<DirtyRect>& itemsDirtyRects = sceneInternal.GetItemsDirtyRects();
603   for(DirtyRect& dirtyRect : itemsDirtyRects)
604   {
605     dirtyRect.visited = false;
606   }
607
608   uint32_t count = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
609   for(uint32_t i = 0; i < count; ++i)
610   {
611     RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
612
613     if(instruction.mFrameBuffer)
614     {
615       return; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
616     }
617
618     const Camera* camera = instruction.GetCamera();
619     if(camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
620     {
621       const Node* node = instruction.GetCamera()->GetNode();
622       if(node)
623       {
624         Vector3    position;
625         Vector3    scale;
626         Quaternion orientation;
627         node->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
628
629         Vector3 orientationAxis;
630         Radian  orientationAngle;
631         orientation.ToAxisAngle(orientationAxis, orientationAngle);
632
633         if(position.x > Math::MACHINE_EPSILON_10000 ||
634            position.y > Math::MACHINE_EPSILON_10000 ||
635            orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
636            orientationAngle != ANGLE_180 ||
637            scale != Vector3(1.0f, 1.0f, 1.0f))
638         {
639           return;
640         }
641       }
642     }
643     else
644     {
645       return;
646     }
647
648     Rect<int32_t> viewportRect;
649     if(instruction.mIsViewportSet)
650     {
651       const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
652       viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
653       if(viewportRect.IsEmpty() || !viewportRect.IsValid())
654       {
655         return; // just skip funny use cases for now, empty viewport means it is set somewhere else
656       }
657     }
658     else
659     {
660       viewportRect = surfaceRect;
661     }
662
663     const Matrix* viewMatrix       = instruction.GetViewMatrix(mImpl->renderBufferIndex);
664     const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
665     if(viewMatrix && projectionMatrix)
666     {
667       const RenderListContainer::SizeType count = instruction.RenderListCount();
668       for(RenderListContainer::SizeType index = 0u; index < count; ++index)
669       {
670         const RenderList* renderList = instruction.GetRenderList(index);
671         if(renderList && !renderList->IsEmpty())
672         {
673           const std::size_t count = renderList->Count();
674           for(uint32_t index = 0u; index < count; ++index)
675           {
676             RenderItem& item = renderList->GetItem(index);
677             // If the item does 3D transformation, do early exit and clean the damaged rect array
678             if(item.mUpdateSize == Vector3::ZERO)
679             {
680               return;
681             }
682
683             Rect<int> rect;
684             DirtyRect dirtyRect(item.mNode, item.mRenderer, mImpl->frameCount, rect);
685             // If the item refers to updated node or renderer.
686             if(item.mIsUpdated ||
687                (item.mNode &&
688                 (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex, item.mNode)))))
689             {
690               item.mIsUpdated = false;
691               item.mNode->SetUpdated(false);
692
693               rect = item.CalculateViewportSpaceAABB(item.mUpdateSize, viewportRect.width, viewportRect.height);
694               if(rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
695               {
696                 const int left   = rect.x;
697                 const int top    = rect.y;
698                 const int right  = rect.x + rect.width;
699                 const int bottom = rect.y + rect.height;
700                 rect.x           = (left / 16) * 16;
701                 rect.y           = (top / 16) * 16;
702                 rect.width       = ((right + 16) / 16) * 16 - rect.x;
703                 rect.height      = ((bottom + 16) / 16) * 16 - rect.y;
704
705                 // Found valid dirty rect.
706                 // 1. Insert it in the sorted array of the dirty rects.
707                 // 2. Mark the related dirty rects as visited so they will not be removed below.
708                 // 3. Keep only last 3 dirty rects for the same node and renderer (Tizen uses 3 back buffers, Ubuntu 1).
709                 dirtyRect.rect    = rect;
710                 auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
711                 dirtyRectPos      = itemsDirtyRects.insert(dirtyRectPos, dirtyRect);
712
713                 int c = 1;
714                 while(++dirtyRectPos != itemsDirtyRects.end())
715                 {
716                   if(dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
717                   {
718                     break;
719                   }
720
721                   dirtyRectPos->visited = true;
722                   Rect<int>& dirtRect   = dirtyRectPos->rect;
723                   rect.Merge(dirtRect);
724
725                   c++;
726                   if(c > 3) // no more then 3 previous rects
727                   {
728                     itemsDirtyRects.erase(dirtyRectPos);
729                     break;
730                   }
731                 }
732
733                 damagedRects.push_back(rect);
734               }
735             }
736             else
737             {
738               // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
739               // 2. Mark the related dirty rects as visited so they will not be removed below.
740               auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
741               while(dirtyRectPos != itemsDirtyRects.end())
742               {
743                 if(dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
744                 {
745                   break;
746                 }
747
748                 dirtyRectPos->visited = true;
749                 dirtyRectPos++;
750               }
751             }
752           }
753         }
754       }
755     }
756   }
757
758   // Check removed nodes or removed renderers dirty rects
759   auto i = itemsDirtyRects.begin();
760   auto j = itemsDirtyRects.begin();
761   while(i != itemsDirtyRects.end())
762   {
763     if(i->visited)
764     {
765       *j++ = *i;
766     }
767     else
768     {
769       Rect<int>& dirtRect = i->rect;
770       damagedRects.push_back(dirtRect);
771     }
772     i++;
773   }
774
775   itemsDirtyRects.resize(j - itemsDirtyRects.begin());
776   damagedRectCleaner.SetCleanOnReturn(false);
777 }
778
779 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo)
780 {
781   Rect<int> clippingRect;
782   RenderScene(status, scene, renderToFbo, clippingRect);
783 }
784
785 void RenderManager::RenderScene(Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect)
786 {
787   Internal::Scene&   sceneInternal = GetImplementation(scene);
788   SceneGraph::Scene* sceneObject   = sceneInternal.GetSceneObject();
789
790   uint32_t count = sceneObject->GetRenderInstructions().Count(mImpl->renderBufferIndex);
791
792   for(uint32_t i = 0; i < count; ++i)
793   {
794     RenderInstruction& instruction = sceneObject->GetRenderInstructions().At(mImpl->renderBufferIndex, i);
795
796     if((renderToFbo && !instruction.mFrameBuffer) || (!renderToFbo && instruction.mFrameBuffer))
797     {
798       continue; // skip
799     }
800
801     // Mark that we will require a post-render step to be performed (includes swap-buffers).
802     status.SetNeedsPostRender(true);
803
804     Rect<int32_t> viewportRect;
805     Vector4       clearColor;
806
807     if(instruction.mIsClearColorSet)
808     {
809       clearColor = instruction.mClearColor;
810     }
811     else
812     {
813       clearColor = Dali::RenderTask::DEFAULT_CLEAR_COLOR;
814     }
815
816     Rect<int32_t> surfaceRect        = sceneObject->GetSurfaceRect();
817     int32_t       surfaceOrientation = sceneObject->GetSurfaceOrientation();
818
819     Integration::DepthBufferAvailable   depthBufferAvailable   = mImpl->depthBufferAvailable;
820     Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
821
822     if(instruction.mFrameBuffer)
823     {
824       // offscreen buffer
825       if(mImpl->currentContext != &mImpl->context)
826       {
827         // Switch to shared context for off-screen buffer
828         mImpl->currentContext = &mImpl->context;
829
830         if(mImpl->currentContext->IsSurfacelessContextSupported())
831         {
832           mImpl->graphicsController.GetGlContextHelperAbstraction().MakeSurfacelessContextCurrent();
833         }
834
835         // Clear the current cached program when the context is switched
836         mImpl->programController.ClearCurrentProgram();
837       }
838     }
839     else
840     {
841       if(mImpl->currentContext->IsSurfacelessContextSupported())
842       {
843         if(mImpl->currentContext != sceneObject->GetContext())
844         {
845           // Switch the correct context if rendering to a surface
846           mImpl->currentContext = sceneObject->GetContext();
847
848           // Clear the current cached program when the context is switched
849           mImpl->programController.ClearCurrentProgram();
850         }
851       }
852     }
853
854     // Make sure that GL context must be created
855     mImpl->currentContext->GlContextCreated();
856
857     // reset the program matrices for all programs once per frame
858     // this ensures we will set view and projection matrix once per program per camera
859     mImpl->programController.ResetProgramMatrices();
860
861     if(instruction.mFrameBuffer)
862     {
863       instruction.mFrameBuffer->Bind(*mImpl->currentContext);
864
865       // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
866       for(unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
867       {
868         mImpl->textureDependencyList.PushBack(instruction.mFrameBuffer->GetTextureId(i0));
869       }
870     }
871     else
872     {
873       mImpl->currentContext->BindFramebuffer(GL_FRAMEBUFFER, 0u);
874     }
875
876     if(!instruction.mFrameBuffer)
877     {
878       mImpl->currentContext->Viewport(surfaceRect.x,
879                                       surfaceRect.y,
880                                       surfaceRect.width,
881                                       surfaceRect.height);
882     }
883
884     // Clear the entire color, depth and stencil buffers for the default framebuffer, if required.
885     // It is important to clear all 3 buffers when they are being used, for performance on deferred renderers
886     // e.g. previously when the depth & stencil buffers were NOT cleared, it caused the DDK to exceed a "vertex count limit",
887     // and then stall. That problem is only noticeable when rendering a large number of vertices per frame.
888     GLbitfield clearMask = GL_COLOR_BUFFER_BIT;
889
890     mImpl->currentContext->ColorMask(true);
891
892     if(depthBufferAvailable == Integration::DepthBufferAvailable::TRUE)
893     {
894       mImpl->currentContext->DepthMask(true);
895       clearMask |= GL_DEPTH_BUFFER_BIT;
896     }
897
898     if(stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE)
899     {
900       mImpl->currentContext->ClearStencil(0);
901       mImpl->currentContext->StencilMask(0xFF); // 8 bit stencil mask, all 1's
902       clearMask |= GL_STENCIL_BUFFER_BIT;
903     }
904
905     if(!instruction.mIgnoreRenderToFbo && (instruction.mFrameBuffer != nullptr))
906     {
907       // Offscreen buffer rendering
908       if(instruction.mIsViewportSet)
909       {
910         // For glViewport the lower-left corner is (0,0)
911         const int32_t y = (instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height) - instruction.mViewport.y;
912         viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
913       }
914       else
915       {
916         viewportRect.Set(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
917       }
918       surfaceOrientation = 0;
919     }
920     else // No Offscreen frame buffer rendering
921     {
922       // Check whether a viewport is specified, otherwise the full surface size is used
923       if(instruction.mIsViewportSet)
924       {
925         // For glViewport the lower-left corner is (0,0)
926         const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
927         viewportRect.Set(instruction.mViewport.x, y, instruction.mViewport.width, instruction.mViewport.height);
928       }
929       else
930       {
931         viewportRect = surfaceRect;
932       }
933     }
934
935     // Set surface orientation
936     mImpl->currentContext->SetSurfaceOrientation(surfaceOrientation);
937
938     bool clearFullFrameRect = true;
939     if(instruction.mFrameBuffer != nullptr)
940     {
941       Viewport frameRect(0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight());
942       clearFullFrameRect = (frameRect == viewportRect);
943     }
944     else
945     {
946       clearFullFrameRect = (surfaceRect == viewportRect);
947     }
948
949     if(!clippingRect.IsEmpty())
950     {
951       if(!clippingRect.Intersect(viewportRect))
952       {
953         DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
954         clippingRect = Rect<int>();
955       }
956       clearFullFrameRect = false;
957     }
958
959     mImpl->currentContext->Viewport(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
960
961     if(instruction.mIsClearColorSet)
962     {
963       mImpl->currentContext->ClearColor(clearColor.r,
964                                         clearColor.g,
965                                         clearColor.b,
966                                         clearColor.a);
967       if(!clearFullFrameRect)
968       {
969         if(!clippingRect.IsEmpty())
970         {
971           mImpl->currentContext->SetScissorTest(true);
972           mImpl->currentContext->Scissor(clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
973           mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
974           mImpl->currentContext->SetScissorTest(false);
975         }
976         else
977         {
978           mImpl->currentContext->SetScissorTest(true);
979           mImpl->currentContext->Scissor(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
980           mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
981           mImpl->currentContext->SetScissorTest(false);
982         }
983       }
984       else
985       {
986         mImpl->currentContext->SetScissorTest(false);
987         mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
988       }
989     }
990
991     // Clear the list of bound textures
992     mImpl->boundTextures.Clear();
993
994     mImpl->renderAlgorithms.ProcessRenderInstruction(
995       instruction,
996       *mImpl->currentContext,
997       mImpl->renderBufferIndex,
998       depthBufferAvailable,
999       stencilBufferAvailable,
1000       mImpl->boundTextures,
1001       clippingRect);
1002
1003     // Synchronise the FBO/Texture access when there are multiple contexts
1004     if(mImpl->currentContext->IsSurfacelessContextSupported())
1005     {
1006       // Check whether any binded texture is in the dependency list
1007       bool textureFound = false;
1008
1009       if(mImpl->boundTextures.Count() > 0u && mImpl->textureDependencyList.Count() > 0u)
1010       {
1011         for(auto textureId : mImpl->textureDependencyList)
1012         {
1013           textureFound = std::find_if(mImpl->boundTextures.Begin(), mImpl->boundTextures.End(), [textureId](GLuint id) {
1014                            return textureId == id;
1015                          }) != mImpl->boundTextures.End();
1016         }
1017       }
1018
1019       if(textureFound)
1020       {
1021         if(instruction.mFrameBuffer)
1022         {
1023           // For off-screen buffer
1024
1025           // Wait until all rendering calls for the currently context are executed
1026           mImpl->graphicsController.GetGlContextHelperAbstraction().WaitClient();
1027
1028           // Clear the dependency list
1029           mImpl->textureDependencyList.Clear();
1030         }
1031         else
1032         {
1033           // Worker thread lambda function
1034           auto& glContextHelperAbstraction = mImpl->graphicsController.GetGlContextHelperAbstraction();
1035           auto  workerFunction             = [&glContextHelperAbstraction](int workerThread) {
1036             // Switch to the shared context in the worker thread
1037             glContextHelperAbstraction.MakeSurfacelessContextCurrent();
1038
1039             // Wait until all rendering calls for the shared context are executed
1040             glContextHelperAbstraction.WaitClient();
1041
1042             // Must clear the context in the worker thread
1043             // Otherwise the shared context cannot be switched to from the render thread
1044             glContextHelperAbstraction.MakeContextNull();
1045           };
1046
1047           auto future = mImpl->threadPool->SubmitTask(0u, workerFunction);
1048           if(future)
1049           {
1050             mImpl->threadPool->Wait();
1051
1052             // Clear the dependency list
1053             mImpl->textureDependencyList.Clear();
1054           }
1055         }
1056       }
1057     }
1058
1059     if(instruction.mRenderTracker && instruction.mFrameBuffer)
1060     {
1061       // This will create a sync object every frame this render tracker
1062       // is alive (though it should be now be created only for
1063       // render-once render tasks)
1064       instruction.mRenderTracker->CreateSyncObject(mImpl->graphicsController.GetGlSyncAbstraction());
1065       instruction.mRenderTracker = nullptr; // Only create once.
1066     }
1067
1068     if(renderToFbo)
1069     {
1070       mImpl->currentContext->Flush();
1071     }
1072   }
1073
1074   GLenum attachments[] = {GL_DEPTH, GL_STENCIL};
1075   mImpl->currentContext->InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
1076 }
1077
1078 void RenderManager::PostRender(bool uploadOnly)
1079 {
1080   if(!uploadOnly)
1081   {
1082     if(mImpl->currentContext->IsSurfacelessContextSupported())
1083     {
1084       mImpl->graphicsController.GetGlContextHelperAbstraction().MakeSurfacelessContextCurrent();
1085     }
1086
1087     GLenum attachments[] = {GL_DEPTH, GL_STENCIL};
1088     mImpl->context.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
1089   }
1090
1091   //Notify RenderGeometries that rendering has finished
1092   for(auto&& iter : mImpl->geometryContainer)
1093   {
1094     iter->OnRenderFinished();
1095   }
1096
1097   mImpl->UpdateTrackers();
1098
1099   uint32_t count = 0u;
1100   for(uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i)
1101   {
1102     count += mImpl->sceneContainer[i]->GetRenderInstructions().Count(mImpl->renderBufferIndex);
1103   }
1104
1105   const bool haveInstructions = count > 0u;
1106
1107   // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
1108   mImpl->lastFrameWasRendered = haveInstructions;
1109
1110   /**
1111    * The rendering has finished; swap to the next buffer.
1112    * Ideally the update has just finished using this buffer; otherwise the render thread
1113    * should block until the update has finished.
1114    */
1115   mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
1116
1117   DALI_PRINT_RENDER_END();
1118 }
1119
1120 } // namespace SceneGraph
1121
1122 } // namespace Internal
1123
1124 } // namespace Dali