Remove RenderSurface from Core
[platform/core/uifw/dali-core.git] / dali / internal / render / common / render-manager.cpp
index e9e13e8..24c310f 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2018 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2020 Samsung Electronics Co., Ltd.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
 // CLASS HEADER
 #include <dali/internal/render/common/render-manager.h>
 
+// EXTERNAL INCLUDES
+#include <memory.h>
+
 // INTERNAL INCLUDES
 #include <dali/public-api/actors/sampling.h>
 #include <dali/public-api/common/dali-common.h>
 #include <dali/public-api/common/stage.h>
 #include <dali/public-api/render-tasks/render-task.h>
+#include <dali/devel-api/threading/thread-pool.h>
 #include <dali/integration-api/debug.h>
 #include <dali/integration-api/core.h>
+#include <dali/integration-api/gl-context-helper-abstraction.h>
 #include <dali/internal/common/owner-pointer.h>
+#include <dali/internal/event/common/scene-impl.h>
 #include <dali/internal/render/common/render-algorithms.h>
 #include <dali/internal/render/common/render-debug.h>
 #include <dali/internal/render/common/render-tracker.h>
@@ -38,6 +44,7 @@
 #include <dali/internal/render/renderers/render-renderer.h>
 #include <dali/internal/render/renderers/render-sampler.h>
 #include <dali/internal/render/shaders/program-controller.h>
+#include <dali/internal/update/common/scene-graph-scene.h>
 
 namespace Dali
 {
@@ -48,6 +55,13 @@ namespace Internal
 namespace SceneGraph
 {
 
+#if defined(DEBUG_ENABLED)
+namespace
+{
+Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_RENDER_MANAGER" );
+} // unnamed namespace
+#endif
+
 /**
  * Structure to contain internal data
  */
@@ -55,14 +69,16 @@ struct RenderManager::Impl
 {
   Impl( Integration::GlAbstraction& glAbstraction,
         Integration::GlSyncAbstraction& glSyncAbstraction,
+        Integration::GlContextHelperAbstraction& glContextHelperAbstraction,
         Integration::DepthBufferAvailable depthBufferAvailableParam,
         Integration::StencilBufferAvailable stencilBufferAvailableParam )
-  : context( glAbstraction ),
+  : context( glAbstraction, &sceneContextContainer ),
+    currentContext( &context ),
+    glAbstraction( glAbstraction ),
     glSyncAbstraction( glSyncAbstraction ),
+    glContextHelperAbstraction( glContextHelperAbstraction ),
     renderQueue(),
-    instructions(),
     renderAlgorithms(),
-    backgroundColor( Dali::Stage::DEFAULT_BACKGROUND_COLOR ),
     frameCount( 0u ),
     renderBufferIndex( SceneGraphBuffers::INITIAL_UPDATE_BUFFER_INDEX ),
     defaultSurfaceRect(),
@@ -75,10 +91,14 @@ struct RenderManager::Impl
     depthBufferAvailable( depthBufferAvailableParam ),
     stencilBufferAvailable( stencilBufferAvailableParam )
   {
+     // Create thread pool with just one thread ( there may be a need to create more threads in the future ).
+    threadPool = std::unique_ptr<Dali::ThreadPool>( new Dali::ThreadPool() );
+    threadPool->Initialize( 1u );
   }
 
   ~Impl()
   {
+    threadPool.reset( nullptr ); // reset now to maintain correct destruction order
   }
 
   void AddRenderTracker( Render::RenderTracker* renderTracker )
@@ -92,6 +112,28 @@ struct RenderManager::Impl
     mRenderTrackers.EraseObject( renderTracker );
   }
 
+  Context* CreateSceneContext()
+  {
+    sceneContextContainer.push_back( new Context( glAbstraction ) );
+    return sceneContextContainer[ sceneContextContainer.size() - 1 ];
+  }
+
+  void DestroySceneContext( Context* sceneContext )
+  {
+    auto iter = std::find( sceneContextContainer.begin(), sceneContextContainer.end(), sceneContext );
+    if( iter != sceneContextContainer.end() )
+    {
+      sceneContextContainer.erase( iter );
+    }
+  }
+
+  Context* ReplaceSceneContext( Context* oldSceneContext )
+  {
+    Context* newContext = new Context( glAbstraction );
+    std::replace( sceneContextContainer.begin(), sceneContextContainer.end(), oldSceneContext, newContext );
+    return newContext;
+  }
+
   void UpdateTrackers()
   {
     for( auto&& iter : mRenderTrackers )
@@ -102,16 +144,17 @@ struct RenderManager::Impl
 
   // the order is important for destruction,
   // programs are owned by context at the moment.
-  Context                                   context;                 ///< holds the GL state
+  Context                                   context;                 ///< Holds the GL state of the share resource context
+  Context*                                  currentContext;          ///< Holds the GL state of the current context for rendering
+  std::vector< Context* >                   sceneContextContainer;   ///< List of owned contexts holding the GL state per scene
+  Integration::GlAbstraction&               glAbstraction;           ///< GL abstraction
   Integration::GlSyncAbstraction&           glSyncAbstraction;       ///< GL sync abstraction
+  Integration::GlContextHelperAbstraction&  glContextHelperAbstraction; ///< GL context helper abstraction
   RenderQueue                               renderQueue;             ///< A message queue for receiving messages from the update-thread.
 
-  // Render instructions describe what should be rendered during RenderManager::Render()
-  // Owned by RenderManager. Update manager updates instructions for the next frame while we render the current one
-  RenderInstructionContainer                instructions;
-  Render::RenderAlgorithms                  renderAlgorithms;        ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
+  std::vector< SceneGraph::Scene* >         sceneContainer;          ///< List of pointers to the scene graph objects of the scenes
 
-  Vector4                                   backgroundColor;         ///< The glClear color used at the beginning of each frame.
+  Render::RenderAlgorithms                  renderAlgorithms;        ///< The RenderAlgorithms object is used to action the renders required by a RenderInstruction
 
   uint32_t                                  frameCount;              ///< The current frame count
   BufferIndex                               renderBufferIndex;       ///< The index of the buffer to read from; this is opposite of the "update" buffer
@@ -134,16 +177,21 @@ struct RenderManager::Impl
   Integration::DepthBufferAvailable         depthBufferAvailable;     ///< Whether the depth buffer is available
   Integration::StencilBufferAvailable       stencilBufferAvailable;   ///< Whether the stencil buffer is available
 
+  std::unique_ptr<Dali::ThreadPool>         threadPool;               ///< The thread pool
+  Vector<GLuint>                            boundTextures;            ///< The textures bound for rendering
+  Vector<GLuint>                            textureDependencyList;    ///< The dependency list of binded textures
 };
 
 RenderManager* RenderManager::New( Integration::GlAbstraction& glAbstraction,
                                    Integration::GlSyncAbstraction& glSyncAbstraction,
+                                   Integration::GlContextHelperAbstraction& glContextHelperAbstraction,
                                    Integration::DepthBufferAvailable depthBufferAvailable,
                                    Integration::StencilBufferAvailable stencilBufferAvailable )
 {
   RenderManager* manager = new RenderManager;
   manager->mImpl = new Impl( glAbstraction,
                              glSyncAbstraction,
+                             glContextHelperAbstraction,
                              depthBufferAvailable,
                              stencilBufferAvailable );
   return manager;
@@ -195,6 +243,12 @@ void RenderManager::ContextDestroyed()
   {
     renderer->GlContextDestroyed();
   }
+
+  // inform scenes
+  for( auto&& scene : mImpl->sceneContainer )
+  {
+    scene->GlContextDestroyed();
+  }
 }
 
 void RenderManager::SetShaderSaver( ShaderSaver& upstream )
@@ -202,16 +256,6 @@ void RenderManager::SetShaderSaver( ShaderSaver& upstream )
   mImpl->programController.SetShaderSaver( upstream );
 }
 
-RenderInstructionContainer& RenderManager::GetRenderInstructionContainer()
-{
-  return mImpl->instructions;
-}
-
-void RenderManager::SetBackgroundColor( const Vector4& color )
-{
-  mImpl->backgroundColor = color;
-}
-
 void RenderManager::SetDefaultSurfaceRect(const Rect<int32_t>& rect)
 {
   mImpl->defaultSurfaceRect = rect;
@@ -285,10 +329,11 @@ void RenderManager::SetWrapMode( Render::Sampler* sampler, uint32_t rWrapMode, u
   sampler->mTWrapMode = static_cast<Dali::WrapMode::Type>(tWrapMode);
 }
 
-void RenderManager::AddFrameBuffer( Render::FrameBuffer* frameBuffer )
+void RenderManager::AddFrameBuffer( OwnerPointer< Render::FrameBuffer >& frameBuffer )
 {
-  mImpl->frameBufferContainer.PushBack( frameBuffer );
-  frameBuffer->Initialize(mImpl->context);
+  Render::FrameBuffer* frameBufferPtr = frameBuffer.Release();
+  mImpl->frameBufferContainer.PushBack( frameBufferPtr );
+  frameBufferPtr->Initialize( mImpl->context );
 }
 
 void RenderManager::RemoveFrameBuffer( Render::FrameBuffer* frameBuffer )
@@ -302,10 +347,33 @@ void RenderManager::RemoveFrameBuffer( Render::FrameBuffer* frameBuffer )
     {
       frameBuffer->Destroy( mImpl->context );
       mImpl->frameBufferContainer.Erase( &iter ); // frameBuffer found; now destroy it
+
       break;
     }
   }
 }
+void RenderManager::InitializeScene( SceneGraph::Scene* scene )
+{
+  scene->Initialize( *mImpl->CreateSceneContext() );
+  mImpl->sceneContainer.push_back( scene );
+}
+
+void RenderManager::UninitializeScene( SceneGraph::Scene* scene )
+{
+  mImpl->DestroySceneContext( scene->GetContext() );
+
+  auto iter = std::find( mImpl->sceneContainer.begin(), mImpl->sceneContainer.end(), scene );
+  if( iter != mImpl->sceneContainer.end() )
+  {
+    mImpl->sceneContainer.erase( iter );
+  }
+}
+
+void RenderManager::SurfaceReplaced( SceneGraph::Scene* scene )
+{
+  Context* newContext = mImpl->ReplaceSceneContext( scene->GetContext() );
+  scene->Initialize( *newContext );
+}
 
 void RenderManager::AttachColorTextureToFrameBuffer( Render::FrameBuffer* frameBuffer, Render::Texture* texture, uint32_t mipmapLevel, uint32_t layer )
 {
@@ -397,7 +465,7 @@ ProgramCache* RenderManager::GetProgramCache()
   return &(mImpl->programController);
 }
 
-void RenderManager::Render( Integration::RenderStatus& status, bool forceClear )
+void RenderManager::PreRender( Integration::RenderStatus& status, bool forceClear, bool uploadOnly )
 {
   DALI_PRINT_RENDER_START( mImpl->renderBufferIndex );
 
@@ -410,168 +478,398 @@ void RenderManager::Render( Integration::RenderStatus& status, bool forceClear )
   // Process messages queued during previous update
   mImpl->renderQueue.ProcessMessages( mImpl->renderBufferIndex );
 
-  const uint32_t count = mImpl->instructions.Count( mImpl->renderBufferIndex );
+  uint32_t count = 0u;
+  for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
+  {
+    count += mImpl->sceneContainer[i]->GetRenderInstructions().Count( mImpl->renderBufferIndex );
+  }
+
   const bool haveInstructions = count > 0u;
 
+  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" );
+
   // Only render if we have instructions to render, or the last frame was rendered (and therefore a clear is required).
   if( haveInstructions || mImpl->lastFrameWasRendered || forceClear )
   {
-    // Mark that we will require a post-render step to be performed (includes swap-buffers).
-    status.SetNeedsPostRender( true );
+    DALI_LOG_INFO( gLogFilter, Debug::General, "Render: Processing\n" );
 
-    // switch rendering to adaptor provided (default) buffer
-    mImpl->context.BindFramebuffer( GL_FRAMEBUFFER, 0u );
+    if ( !uploadOnly )
+    {
+      // Mark that we will require a post-render step to be performed (includes swap-buffers).
+      status.SetNeedsPostRender( true );
+    }
 
-    mImpl->context.Viewport( mImpl->defaultSurfaceRect.x,
-                             mImpl->defaultSurfaceRect.y,
-                             mImpl->defaultSurfaceRect.width,
-                             mImpl->defaultSurfaceRect.height );
+    // Switch to the shared context
+    if ( mImpl->currentContext != &mImpl->context )
+    {
+      mImpl->currentContext = &mImpl->context;
 
-    mImpl->context.ClearColor( mImpl->backgroundColor.r,
-                               mImpl->backgroundColor.g,
-                               mImpl->backgroundColor.b,
-                               mImpl->backgroundColor.a );
+      if ( mImpl->currentContext->IsSurfacelessContextSupported() )
+      {
+        mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
+      }
 
-    // Clear the entire color, depth and stencil buffers for the default framebuffer, if required.
-    // It is important to clear all 3 buffers when they are being used, for performance on deferred renderers
-    // e.g. previously when the depth & stencil buffers were NOT cleared, it caused the DDK to exceed a "vertex count limit",
-    // and then stall. That problem is only noticeable when rendering a large number of vertices per frame.
+      // Clear the current cached program when the context is switched
+      mImpl->programController.ClearCurrentProgram();
+    }
 
-    mImpl->context.SetScissorTest( false );
+    // Upload the geometries
+    for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
+    {
+      RenderInstructionContainer& instructions = mImpl->sceneContainer[i]->GetRenderInstructions();
+      for ( uint32_t j = 0; j < instructions.Count( mImpl->renderBufferIndex ); ++j )
+      {
+        RenderInstruction& instruction = instructions.At( mImpl->renderBufferIndex, j );
+
+        const Matrix* viewMatrix       = instruction.GetViewMatrix( mImpl->renderBufferIndex );
+        const Matrix* projectionMatrix = instruction.GetProjectionMatrix( mImpl->renderBufferIndex );
+
+        DALI_ASSERT_DEBUG( viewMatrix );
+        DALI_ASSERT_DEBUG( projectionMatrix );
+
+        if( viewMatrix && projectionMatrix )
+        {
+          const RenderListContainer::SizeType renderListCount = instruction.RenderListCount();
+
+          // Iterate through each render list.
+          for( RenderListContainer::SizeType index = 0; index < renderListCount; ++index )
+          {
+            const RenderList* renderList = instruction.GetRenderList( index );
+
+            if( renderList && !renderList->IsEmpty() )
+            {
+              const std::size_t itemCount = renderList->Count();
+              for( uint32_t itemIndex = 0u; itemIndex < itemCount; ++itemIndex )
+              {
+                const RenderItem& item = renderList->GetItem( itemIndex );
+                if( DALI_LIKELY( item.mRenderer ) )
+                {
+                  item.mRenderer->Upload( *mImpl->currentContext );
+                }
+              }
+            }
+          }
+        }
+      }
+    }
+  }
+}
 
-    GLbitfield clearMask = GL_COLOR_BUFFER_BIT;
 
-    mImpl->context.ColorMask( true );
+void RenderManager::RenderScene( Integration::Scene& scene, bool renderToFbo )
+{
+  Internal::Scene& sceneInternal = GetImplementation( scene );
+  SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
+
+  uint32_t count = sceneObject->GetRenderInstructions().Count( mImpl->renderBufferIndex );
+
+  for( uint32_t i = 0; i < count; ++i )
+  {
+    RenderInstruction& instruction = sceneObject->GetRenderInstructions().At( mImpl->renderBufferIndex, i );
 
-    if( mImpl->depthBufferAvailable == Integration::DepthBufferAvailable::TRUE )
+    if ( ( renderToFbo && !instruction.mFrameBuffer ) || ( !renderToFbo && instruction.mFrameBuffer ) )
     {
-      mImpl->context.DepthMask( true );
-      clearMask |= GL_DEPTH_BUFFER_BIT;
+      continue; // skip
     }
 
-    if( mImpl->stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE)
+    Rect<int32_t> viewportRect;
+    Vector4   clearColor;
+
+    if ( instruction.mIsClearColorSet )
     {
-      mImpl->context.ClearStencil( 0 );
-      mImpl->context.StencilMask( 0xFF ); // 8 bit stencil mask, all 1's
-      clearMask |= GL_STENCIL_BUFFER_BIT;
+      clearColor = instruction.mClearColor;
+    }
+    else
+    {
+      clearColor = Dali::RenderTask::DEFAULT_CLEAR_COLOR;
     }
 
-    mImpl->context.Clear( clearMask, Context::FORCE_CLEAR );
+    Rect<int32_t> surfaceRect = mImpl->defaultSurfaceRect;
+    Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
+    Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
+
+    if ( instruction.mFrameBuffer )
+    {
+      // offscreen buffer
+      if ( mImpl->currentContext != &mImpl->context )
+      {
+        // Switch to shared context for off-screen buffer
+        mImpl->currentContext = &mImpl->context;
+
+        if ( mImpl->currentContext->IsSurfacelessContextSupported() )
+        {
+          mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
+        }
+
+        // Clear the current cached program when the context is switched
+        mImpl->programController.ClearCurrentProgram();
+      }
+    }
+    else
+    {
+      if ( mImpl->currentContext->IsSurfacelessContextSupported() )
+      {
+        if ( mImpl->currentContext != sceneObject->GetContext() )
+        {
+          // Switch the correct context if rendering to a surface
+          mImpl->currentContext = sceneObject->GetContext();
+
+          // Clear the current cached program when the context is switched
+          mImpl->programController.ClearCurrentProgram();
+        }
+      }
+
+      surfaceRect = Rect<int32_t>( 0, 0, static_cast<int32_t>( scene.GetSize().width ), static_cast<int32_t>( scene.GetSize().height ) );
+    }
+
+    DALI_ASSERT_DEBUG( mImpl->currentContext->IsGlContextCreated() );
 
     // reset the program matrices for all programs once per frame
     // this ensures we will set view and projection matrix once per program per camera
     mImpl->programController.ResetProgramMatrices();
 
-    for( uint32_t i = 0; i < count; ++i )
+    if( instruction.mFrameBuffer )
     {
-      RenderInstruction& instruction = mImpl->instructions.At( mImpl->renderBufferIndex, i );
+      instruction.mFrameBuffer->Bind( *mImpl->currentContext );
 
-      DoRender( instruction );
+      // For each offscreen buffer, update the dependency list with the new texture id used by this frame buffer.
+      for (unsigned int i0 = 0, i1 = instruction.mFrameBuffer->GetColorAttachmentCount(); i0 < i1; ++i0)
+      {
+        mImpl->textureDependencyList.PushBack( instruction.mFrameBuffer->GetTextureId(i0) );
+      }
     }
-
-    GLenum attachments[] = { GL_DEPTH, GL_STENCIL };
-    mImpl->context.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
-
-    //Notify RenderGeometries that rendering has finished
-    for ( auto&& iter : mImpl->geometryContainer )
+    else
     {
-      iter->OnRenderFinished();
+      mImpl->currentContext->BindFramebuffer( GL_FRAMEBUFFER, 0u );
     }
-  }
 
-  mImpl->UpdateTrackers();
+    if ( !instruction.mFrameBuffer )
+    {
+      mImpl->currentContext->Viewport( surfaceRect.x,
+                                       surfaceRect.y,
+                                       surfaceRect.width,
+                                       surfaceRect.height );
+    }
 
-  // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
-  mImpl->lastFrameWasRendered = haveInstructions;
+    // Clear the entire color, depth and stencil buffers for the default framebuffer, if required.
+    // It is important to clear all 3 buffers when they are being used, for performance on deferred renderers
+    // e.g. previously when the depth & stencil buffers were NOT cleared, it caused the DDK to exceed a "vertex count limit",
+    // and then stall. That problem is only noticeable when rendering a large number of vertices per frame.
+    GLbitfield clearMask = GL_COLOR_BUFFER_BIT;
 
-  /**
-   * The rendering has finished; swap to the next buffer.
-   * Ideally the update has just finished using this buffer; otherwise the render thread
-   * should block until the update has finished.
-   */
-  mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
+    mImpl->currentContext->ColorMask( true );
 
-  DALI_PRINT_RENDER_END();
-}
+    if( depthBufferAvailable == Integration::DepthBufferAvailable::TRUE )
+    {
+      mImpl->currentContext->DepthMask( true );
+      clearMask |= GL_DEPTH_BUFFER_BIT;
+    }
 
-void RenderManager::DoRender( RenderInstruction& instruction )
-{
-  Rect<int32_t> viewportRect;
-  Vector4   clearColor;
+    if( stencilBufferAvailable == Integration::StencilBufferAvailable::TRUE)
+    {
+      mImpl->currentContext->ClearStencil( 0 );
+      mImpl->currentContext->StencilMask( 0xFF ); // 8 bit stencil mask, all 1's
+      clearMask |= GL_STENCIL_BUFFER_BIT;
+    }
 
-  if ( instruction.mIsClearColorSet )
-  {
-    clearColor = instruction.mClearColor;
-  }
-  else
-  {
-    clearColor = Dali::RenderTask::DEFAULT_CLEAR_COLOR;
-  }
+    if( !instruction.mIgnoreRenderToFbo && ( instruction.mFrameBuffer != 0 ) )
+    {
+      // Offscreen buffer rendering
+      if ( instruction.mIsViewportSet )
+      {
+        // For glViewport the lower-left corner is (0,0)
+        const int32_t y = ( instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height ) - instruction.mViewport.y;
+        viewportRect.Set( instruction.mViewport.x,  y, instruction.mViewport.width, instruction.mViewport.height );
+      }
+      else
+      {
+        viewportRect.Set( 0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight() );
+      }
+    }
+    else // No Offscreen frame buffer rendering
+    {
+      // Check whether a viewport is specified, otherwise the full surface size is used
+      if ( instruction.mIsViewportSet )
+      {
+        // For glViewport the lower-left corner is (0,0)
+        const int32_t y = ( surfaceRect.height - instruction.mViewport.height ) - instruction.mViewport.y;
+        viewportRect.Set( instruction.mViewport.x,  y, instruction.mViewport.width, instruction.mViewport.height );
+      }
+      else
+      {
+        viewportRect = surfaceRect;
+      }
+    }
 
-  if( !instruction.mIgnoreRenderToFbo && ( instruction.mFrameBuffer != 0 ) )
-  {
-    instruction.mFrameBuffer->Bind( mImpl->context );
-    if ( instruction.mIsViewportSet )
+    bool clearFullFrameRect = true;
+    if( instruction.mFrameBuffer != 0 )
     {
-      // For glViewport the lower-left corner is (0,0)
-      const int32_t y = ( instruction.mFrameBuffer->GetHeight() - instruction.mViewport.height ) - instruction.mViewport.y;
-      viewportRect.Set( instruction.mViewport.x,  y, instruction.mViewport.width, instruction.mViewport.height );
+      Viewport frameRect( 0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight() );
+      clearFullFrameRect = ( frameRect == viewportRect );
     }
     else
     {
-      viewportRect.Set( 0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight() );
+      clearFullFrameRect = ( surfaceRect == viewportRect );
     }
-  }
-  else // !(instruction.mOffscreenTexture)
-  {
-    // switch rendering to adaptor provided (default) buffer
-    mImpl->context.BindFramebuffer( GL_FRAMEBUFFER, 0 );
 
-    // Check whether a viewport is specified, otherwise the full surface size is used
-    if ( instruction.mIsViewportSet )
+    mImpl->currentContext->Viewport(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
+
+    if( instruction.mIsClearColorSet )
     {
-      // For glViewport the lower-left corner is (0,0)
-      const int32_t y = ( mImpl->defaultSurfaceRect.height - instruction.mViewport.height ) - instruction.mViewport.y;
-      viewportRect.Set( instruction.mViewport.x,  y, instruction.mViewport.width, instruction.mViewport.height );
+      mImpl->currentContext->ClearColor( clearColor.r,
+                                         clearColor.g,
+                                         clearColor.b,
+                                         clearColor.a );
+
+      if( !clearFullFrameRect )
+      {
+        mImpl->currentContext->SetScissorTest( true );
+        mImpl->currentContext->Scissor( viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height );
+        mImpl->currentContext->Clear( clearMask, Context::FORCE_CLEAR );
+        mImpl->currentContext->SetScissorTest( false );
+      }
+      else
+      {
+        mImpl->currentContext->SetScissorTest( false );
+        mImpl->currentContext->Clear( clearMask, Context::FORCE_CLEAR );
+      }
     }
-    else
+
+    // Clear the list of bound textures
+    mImpl->boundTextures.Clear();
+
+    mImpl->renderAlgorithms.ProcessRenderInstruction(
+        instruction,
+        *mImpl->currentContext,
+        mImpl->renderBufferIndex,
+        depthBufferAvailable,
+        stencilBufferAvailable,
+        mImpl->boundTextures );
+
+    // Synchronise the FBO/Texture access when there are multiple contexts
+    if ( mImpl->currentContext->IsSurfacelessContextSupported() )
+    {
+      // Check whether any binded texture is in the dependency list
+      bool textureFound = false;
+
+      if ( mImpl->boundTextures.Count() > 0u && mImpl->textureDependencyList.Count() > 0u )
+      {
+        for ( auto textureId : mImpl->textureDependencyList )
+        {
+
+          textureFound = std::find_if( mImpl->boundTextures.Begin(), mImpl->boundTextures.End(),
+                                       [textureId]( GLuint id )
+                                       {
+                                         return textureId == id;
+                                       } ) != mImpl->boundTextures.End();
+        }
+      }
+
+      if ( textureFound )
+      {
+        if ( instruction.mFrameBuffer )
+        {
+          // For off-screen buffer
+
+          // Wait until all rendering calls for the currently context are executed
+          mImpl->glContextHelperAbstraction.WaitClient();
+
+          // Clear the dependency list
+          mImpl->textureDependencyList.Clear();
+        }
+        else
+        {
+          // Worker thread lambda function
+          auto& glContextHelperAbstraction = mImpl->glContextHelperAbstraction;
+          auto workerFunction = [&glContextHelperAbstraction]( int workerThread )
+          {
+            // Switch to the shared context in the worker thread
+            glContextHelperAbstraction.MakeSurfacelessContextCurrent();
+
+            // Wait until all rendering calls for the shared context are executed
+            glContextHelperAbstraction.WaitClient();
+
+            // Must clear the context in the worker thread
+            // Otherwise the shared context cannot be switched to from the render thread
+            glContextHelperAbstraction.MakeContextNull();
+          };
+
+          auto future = mImpl->threadPool->SubmitTask( 0u, workerFunction );
+          if ( future )
+          {
+            mImpl->threadPool->Wait();
+
+            // Clear the dependency list
+            mImpl->textureDependencyList.Clear();
+          }
+        }
+      }
+    }
+
+    if( instruction.mRenderTracker && instruction.mFrameBuffer )
+    {
+      // This will create a sync object every frame this render tracker
+      // is alive (though it should be now be created only for
+      // render-once render tasks)
+      instruction.mRenderTracker->CreateSyncObject( mImpl->glSyncAbstraction );
+      instruction.mRenderTracker = nullptr; // Only create once.
+    }
+
+    if ( renderToFbo )
     {
-      viewportRect = mImpl->defaultSurfaceRect;
+      mImpl->currentContext->Flush();
     }
   }
 
-  mImpl->context.Viewport(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
+  GLenum attachments[] = { GL_DEPTH, GL_STENCIL };
+  mImpl->currentContext->InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
+}
 
-  if ( instruction.mIsClearColorSet )
+void RenderManager::PostRender( bool uploadOnly )
+{
+  if ( !uploadOnly )
   {
-    mImpl->context.ClearColor( clearColor.r,
-                               clearColor.g,
-                               clearColor.b,
-                               clearColor.a );
-
-    // Clear the viewport area only
-    mImpl->context.SetScissorTest( true );
-    mImpl->context.Scissor( viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height );
-    mImpl->context.ColorMask( true );
-    mImpl->context.Clear( GL_COLOR_BUFFER_BIT , Context::CHECK_CACHED_VALUES );
-    mImpl->context.SetScissorTest( false );
+    if ( mImpl->currentContext->IsSurfacelessContextSupported() )
+    {
+      mImpl->glContextHelperAbstraction.MakeSurfacelessContextCurrent();
+    }
+
+    GLenum attachments[] = { GL_DEPTH, GL_STENCIL };
+    mImpl->context.InvalidateFramebuffer(GL_FRAMEBUFFER, 2, attachments);
   }
 
-  mImpl->renderAlgorithms.ProcessRenderInstruction(
-      instruction,
-      mImpl->context,
-      mImpl->renderBufferIndex,
-      mImpl->depthBufferAvailable,
-      mImpl->stencilBufferAvailable );
+  //Notify RenderGeometries that rendering has finished
+  for ( auto&& iter : mImpl->geometryContainer )
+  {
+    iter->OnRenderFinished();
+  }
+
+  mImpl->UpdateTrackers();
 
-  if( instruction.mRenderTracker && ( instruction.mFrameBuffer != NULL ) )
+
+  uint32_t count = 0u;
+  for( uint32_t i = 0; i < mImpl->sceneContainer.size(); ++i )
   {
-    // This will create a sync object every frame this render tracker
-    // is alive (though it should be now be created only for
-    // render-once render tasks)
-    instruction.mRenderTracker->CreateSyncObject( mImpl->glSyncAbstraction );
-    instruction.mRenderTracker = NULL; // Only create once.
+    count += mImpl->sceneContainer[i]->GetRenderInstructions().Count( mImpl->renderBufferIndex );
   }
+
+  const bool haveInstructions = count > 0u;
+
+  // If this frame was rendered due to instructions existing, we mark this so we know to clear the next frame.
+  mImpl->lastFrameWasRendered = haveInstructions;
+
+  /**
+   * The rendering has finished; swap to the next buffer.
+   * Ideally the update has just finished using this buffer; otherwise the render thread
+   * should block until the update has finished.
+   */
+  mImpl->renderBufferIndex = (0 != mImpl->renderBufferIndex) ? 0 : 1;
+
+  DALI_PRINT_RENDER_END();
 }
 
 } // namespace SceneGraph