[Tizen] Add screen and client rotation itself function
[platform/core/uifw/dali-core.git] / dali / internal / render / common / render-manager.cpp
old mode 100644 (file)
new mode 100755 (executable)
index 5a0d3c1..d819228
 #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>
-#include <dali/internal/render/common/render-instruction-container.h>
-#include <dali/internal/render/common/render-instruction.h>
-#include <dali/internal/render/gl-resources/context.h>
 #include <dali/internal/render/queue/render-queue.h>
-#include <dali/internal/render/renderers/render-frame-buffer.h>
-#include <dali/internal/render/renderers/render-geometry.h>
-#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
 {
@@ -71,7 +57,8 @@ struct RenderManager::Impl
         Integration::GlSyncAbstraction& glSyncAbstraction,
         Integration::GlContextHelperAbstraction& glContextHelperAbstraction,
         Integration::DepthBufferAvailable depthBufferAvailableParam,
-        Integration::StencilBufferAvailable stencilBufferAvailableParam )
+        Integration::StencilBufferAvailable stencilBufferAvailableParam,
+        Integration::PartialUpdateAvailable partialUpdateAvailableParam )
   : context( glAbstraction, &sceneContextContainer ),
     currentContext( &context ),
     glAbstraction( glAbstraction ),
@@ -89,7 +76,9 @@ struct RenderManager::Impl
     lastFrameWasRendered( false ),
     programController( glAbstraction ),
     depthBufferAvailable( depthBufferAvailableParam ),
-    stencilBufferAvailable( stencilBufferAvailableParam )
+    stencilBufferAvailable( stencilBufferAvailableParam ),
+    partialUpdateAvailable( partialUpdateAvailableParam ),
+    defaultSurfaceOrientation( 0 )
   {
      // 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() );
@@ -114,22 +103,27 @@ struct RenderManager::Impl
 
   Context* CreateSceneContext()
   {
-    sceneContextContainer.push_back( new Context( glAbstraction ) );
-    return sceneContextContainer[ sceneContextContainer.size() - 1 ];
+    Context* context = new Context( glAbstraction );
+    sceneContextContainer.PushBack( context );
+    return context;
   }
 
   void DestroySceneContext( Context* sceneContext )
   {
-    auto iter = std::find( sceneContextContainer.begin(), sceneContextContainer.end(), sceneContext );
-    if( iter != sceneContextContainer.end() )
+    auto iter = std::find( sceneContextContainer.Begin(), sceneContextContainer.End(), sceneContext );
+    if( iter != sceneContextContainer.End() )
     {
-      sceneContextContainer.erase( iter );
+      ( *iter )->GlContextDestroyed();
+      sceneContextContainer.Erase( iter );
     }
   }
 
   Context* ReplaceSceneContext( Context* oldSceneContext )
   {
     Context* newContext = new Context( glAbstraction );
+
+    oldSceneContext->GlContextDestroyed();
+
     std::replace( sceneContextContainer.begin(), sceneContextContainer.end(), oldSceneContext, newContext );
     return newContext;
   }
@@ -146,7 +140,7 @@ struct RenderManager::Impl
   // programs are owned by context at the moment.
   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
+  OwnerContainer< 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
@@ -165,7 +159,7 @@ struct RenderManager::Impl
   OwnerContainer< Render::Sampler* >        samplerContainer;        ///< List of owned samplers
   OwnerContainer< Render::Texture* >        textureContainer;        ///< List of owned textures
   OwnerContainer< Render::FrameBuffer* >    frameBufferContainer;    ///< List of owned framebuffers
-  OwnerContainer< Render::PropertyBuffer* > propertyBufferContainer; ///< List of owned property buffers
+  OwnerContainer< Render::VertexBuffer* >   vertexBufferContainer;   ///< List of owned vertex buffers
   OwnerContainer< Render::Geometry* >       geometryContainer;       ///< List of owned Geometries
 
   bool                                      lastFrameWasRendered;    ///< Keeps track of the last frame being rendered due to having render instructions
@@ -176,29 +170,33 @@ struct RenderManager::Impl
 
   Integration::DepthBufferAvailable         depthBufferAvailable;     ///< Whether the depth buffer is available
   Integration::StencilBufferAvailable       stencilBufferAvailable;   ///< Whether the stencil buffer is available
+  Integration::PartialUpdateAvailable       partialUpdateAvailable;   ///< Whether the partial update 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
+  int                                       defaultSurfaceOrientation; ///< defaultSurfaceOrientation for the default surface we are rendering to
 };
 
 RenderManager* RenderManager::New( Integration::GlAbstraction& glAbstraction,
                                    Integration::GlSyncAbstraction& glSyncAbstraction,
                                    Integration::GlContextHelperAbstraction& glContextHelperAbstraction,
                                    Integration::DepthBufferAvailable depthBufferAvailable,
-                                   Integration::StencilBufferAvailable stencilBufferAvailable )
+                                   Integration::StencilBufferAvailable stencilBufferAvailable,
+                                   Integration::PartialUpdateAvailable partialUpdateAvailable )
 {
   RenderManager* manager = new RenderManager;
   manager->mImpl = new Impl( glAbstraction,
                              glSyncAbstraction,
                              glContextHelperAbstraction,
                              depthBufferAvailable,
-                             stencilBufferAvailable );
+                             stencilBufferAvailable,
+                             partialUpdateAvailable );
   return manager;
 }
 
 RenderManager::RenderManager()
-: mImpl(NULL)
+: mImpl(nullptr)
 {
 }
 
@@ -244,10 +242,10 @@ void RenderManager::ContextDestroyed()
     renderer->GlContextDestroyed();
   }
 
-  // inform scenes
-  for( auto&& scene : mImpl->sceneContainer )
+  // inform context
+  for( auto&& context : mImpl->sceneContextContainer )
   {
-    scene->GlContextDestroyed();
+    context->GlContextDestroyed();
   }
 }
 
@@ -261,6 +259,11 @@ void RenderManager::SetDefaultSurfaceRect(const Rect<int32_t>& rect)
   mImpl->defaultSurfaceRect = rect;
 }
 
+void RenderManager::SetDefaultSurfaceOrientation( int orientation )
+{
+  mImpl->defaultSurfaceOrientation = orientation;
+}
+
 void RenderManager::AddRenderer( OwnerPointer< Render::Renderer >& renderer )
 {
   // Initialize the renderer as we are now in render thread
@@ -390,24 +393,24 @@ void RenderManager::AttachDepthStencilTextureToFrameBuffer( Render::FrameBuffer*
   frameBuffer->AttachDepthStencilTexture( mImpl->context, texture, mipmapLevel );
 }
 
-void RenderManager::AddPropertyBuffer( OwnerPointer< Render::PropertyBuffer >& propertyBuffer )
+void RenderManager::AddVertexBuffer( OwnerPointer< Render::VertexBuffer >& vertexBuffer )
 {
-  mImpl->propertyBufferContainer.PushBack( propertyBuffer.Release() );
+  mImpl->vertexBufferContainer.PushBack( vertexBuffer.Release() );
 }
 
-void RenderManager::RemovePropertyBuffer( Render::PropertyBuffer* propertyBuffer )
+void RenderManager::RemoveVertexBuffer( Render::VertexBuffer* vertexBuffer )
 {
-  mImpl->propertyBufferContainer.EraseObject( propertyBuffer );
+  mImpl->vertexBufferContainer.EraseObject( vertexBuffer );
 }
 
-void RenderManager::SetPropertyBufferFormat( Render::PropertyBuffer* propertyBuffer, OwnerPointer< Render::PropertyBuffer::Format>& format )
+void RenderManager::SetVertexBufferFormat( Render::VertexBuffer* vertexBuffer, OwnerPointer< Render::VertexBuffer::Format>& format )
 {
-  propertyBuffer->SetFormat( format.Release() );
+  vertexBuffer->SetFormat( format.Release() );
 }
 
-void RenderManager::SetPropertyBufferData( Render::PropertyBuffer* propertyBuffer, OwnerPointer< Vector<uint8_t> >& data, uint32_t size )
+void RenderManager::SetVertexBufferData( Render::VertexBuffer* vertexBuffer, OwnerPointer< Vector<uint8_t> >& data, uint32_t size )
 {
-  propertyBuffer->SetData( data.Release(), size );
+  vertexBuffer->SetData( data.Release(), size );
 }
 
 void RenderManager::SetIndexBuffer( Render::Geometry* geometry, Dali::Vector<uint16_t>& indices )
@@ -425,7 +428,7 @@ void RenderManager::RemoveGeometry( Render::Geometry* geometry )
   mImpl->geometryContainer.EraseObject( geometry );
 }
 
-void RenderManager::AttachVertexBuffer( Render::Geometry* geometry, Render::PropertyBuffer* propertyBuffer )
+void RenderManager::AttachVertexBuffer( Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer )
 {
   DALI_ASSERT_DEBUG( NULL != geometry );
 
@@ -434,13 +437,13 @@ void RenderManager::AttachVertexBuffer( Render::Geometry* geometry, Render::Prop
   {
     if ( iter == geometry )
     {
-      iter->AddPropertyBuffer( propertyBuffer );
+      iter->AddVertexBuffer( vertexBuffer );
       break;
     }
   }
 }
 
-void RenderManager::RemoveVertexBuffer( Render::Geometry* geometry, Render::PropertyBuffer* propertyBuffer )
+void RenderManager::RemoveVertexBuffer( Render::Geometry* geometry, Render::VertexBuffer* vertexBuffer )
 {
   DALI_ASSERT_DEBUG( NULL != geometry );
 
@@ -449,7 +452,7 @@ void RenderManager::RemoveVertexBuffer( Render::Geometry* geometry, Render::Prop
   {
     if ( iter == geometry )
     {
-      iter->RemovePropertyBuffer( propertyBuffer );
+      iter->RemoveVertexBuffer( vertexBuffer );
       break;
     }
   }
@@ -507,12 +510,6 @@ void RenderManager::PreRender( Integration::RenderStatus& status, bool forceClea
   {
     DALI_LOG_INFO( gLogFilter, Debug::General, "Render: Processing\n" );
 
-    if ( !uploadOnly )
-    {
-      // Mark that we will require a post-render step to be performed (includes swap-buffers).
-      status.SetNeedsPostRender( true );
-    }
-
     // Switch to the shared context
     if ( mImpl->currentContext != &mImpl->context )
     {
@@ -569,8 +566,236 @@ void RenderManager::PreRender( Integration::RenderStatus& status, bool forceClea
   }
 }
 
+void RenderManager::PreRender( Integration::Scene& scene, std::vector<Rect<int>>& damagedRects )
+{
+  if (mImpl->partialUpdateAvailable != Integration::PartialUpdateAvailable::TRUE)
+  {
+    return;
+  }
+
+  class DamagedRectsCleaner
+  {
+  public:
+    DamagedRectsCleaner(std::vector<Rect<int>>& damagedRects)
+    : mDamagedRects(damagedRects),
+      mCleanOnReturn(true)
+    {
+    }
+
+    void SetCleanOnReturn(bool cleanOnReturn)
+    {
+      mCleanOnReturn = cleanOnReturn;
+    }
+
+    ~DamagedRectsCleaner()
+    {
+      if (mCleanOnReturn)
+      {
+        mDamagedRects.clear();
+      }
+    }
+
+  private:
+    std::vector<Rect<int>>& mDamagedRects;
+    bool mCleanOnReturn;
+  };
+
+  Rect<int32_t> surfaceRect = Rect<int32_t>(0, 0, static_cast<int32_t>( scene.GetSize().width ), static_cast<int32_t>( scene.GetSize().height ));
+
+  // Clean collected dirty/damaged rects on exit if 3d layer or 3d node or other conditions.
+  DamagedRectsCleaner damagedRectCleaner(damagedRects);
+
+
+
+  Internal::Scene& sceneInternal = GetImplementation(scene);
+  SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
+
+  // Mark previous dirty rects in the sorted array. The array is already sorted by node and renderer, frame number.
+  // so you don't need to sort: std::stable_sort(itemsDirtyRects.begin(), itemsDirtyRects.end());
+  std::vector<DirtyRect>& itemsDirtyRects = sceneInternal.GetItemsDirtyRects();
+  for (DirtyRect& dirtyRect : itemsDirtyRects)
+  {
+    dirtyRect.visited = false;
+  }
+
+  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 (instruction.mFrameBuffer)
+    {
+      return; // TODO: reset, we don't deal with render tasks with framebuffers (for now)
+    }
+
+    const Camera* camera = instruction.GetCamera();
+    if (camera->mType == Camera::DEFAULT_TYPE && camera->mTargetPosition == Camera::DEFAULT_TARGET_POSITION)
+    {
+      const Node* node = instruction.GetCamera()->GetNode();
+      if (node)
+      {
+        Vector3 position;
+        Vector3 scale;
+        Quaternion orientation;
+        node->GetWorldMatrix(mImpl->renderBufferIndex).GetTransformComponents(position, orientation, scale);
+
+        Vector3 orientationAxis;
+        Radian orientationAngle;
+        orientation.ToAxisAngle( orientationAxis, orientationAngle );
+
+        if (position.x > Math::MACHINE_EPSILON_10000 ||
+            position.y > Math::MACHINE_EPSILON_10000 ||
+            orientationAxis != Vector3(0.0f, 1.0f, 0.0f) ||
+            orientationAngle != ANGLE_180 ||
+            scale != Vector3(1.0f, 1.0f, 1.0f))
+        {
+          return;
+        }
+      }
+    }
+    else
+    {
+      return;
+    }
+
+    Rect<int32_t> viewportRect;
+    if (instruction.mIsViewportSet)
+    {
+      const int32_t y = (surfaceRect.height - instruction.mViewport.height) - instruction.mViewport.y;
+      viewportRect.Set(instruction.mViewport.x,  y, instruction.mViewport.width, instruction.mViewport.height);
+      if (viewportRect.IsEmpty() || !viewportRect.IsValid())
+      {
+        return; // just skip funny use cases for now, empty viewport means it is set somewhere else
+      }
+    }
+    else
+    {
+      viewportRect = surfaceRect;
+    }
+
+    const Matrix* viewMatrix       = instruction.GetViewMatrix(mImpl->renderBufferIndex);
+    const Matrix* projectionMatrix = instruction.GetProjectionMatrix(mImpl->renderBufferIndex);
+    if (viewMatrix && projectionMatrix)
+    {
+      const RenderListContainer::SizeType count = instruction.RenderListCount();
+      for (RenderListContainer::SizeType index = 0u; index < count; ++index)
+      {
+        const RenderList* renderList = instruction.GetRenderList( index );
+        if (renderList && !renderList->IsEmpty())
+        {
+          const std::size_t count = renderList->Count();
+          for (uint32_t index = 0u; index < count; ++index)
+          {
+            RenderItem& item = renderList->GetItem( index );
+            // If the item does 3D transformation, do early exit and clean the damaged rect array
+            if (item.mUpdateSize == Vector3::ZERO)
+            {
+              return;
+            }
+
+            Rect<int> rect;
+            DirtyRect dirtyRect(item.mNode, item.mRenderer, mImpl->frameCount, rect);
+            // If the item refers to updated node or renderer.
+            if (item.mIsUpdated ||
+                (item.mNode &&
+                (item.mNode->Updated() || (item.mRenderer && item.mRenderer->Updated(mImpl->renderBufferIndex, item.mNode)))))
+            {
+              item.mIsUpdated = false;
+              item.mNode->SetUpdated(false);
+
+              rect = item.CalculateViewportSpaceAABB(item.mUpdateSize, viewportRect.width, viewportRect.height);
+              if (rect.IsValid() && rect.Intersect(viewportRect) && !rect.IsEmpty())
+              {
+                const int left = rect.x;
+                const int top = rect.y;
+                const int right = rect.x + rect.width;
+                const int bottom = rect.y + rect.height;
+                rect.x = (left / 16) * 16;
+                rect.y = (top / 16) * 16;
+                rect.width = ((right + 16) / 16) * 16 - rect.x;
+                rect.height = ((bottom + 16) / 16) * 16 - rect.y;
+
+                // Found valid dirty rect.
+                // 1. Insert it in the sorted array of the dirty rects.
+                // 2. Mark the related dirty rects as visited so they will not be removed below.
+                // 3. Keep only last 3 dirty rects for the same node and renderer (Tizen uses 3 back buffers, Ubuntu 1).
+                dirtyRect.rect = rect;
+                auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
+                dirtyRectPos = itemsDirtyRects.insert(dirtyRectPos, dirtyRect);
+
+                int c = 1;
+                while (++dirtyRectPos != itemsDirtyRects.end())
+                {
+                  if (dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
+                  {
+                    break;
+                  }
+
+                  dirtyRectPos->visited = true;
+                  Rect<int>& dirtRect = dirtyRectPos->rect;
+                  rect.Merge(dirtRect);
+
+                  c++;
+                  if (c > 3) // no more then 3 previous rects
+                  {
+                    itemsDirtyRects.erase(dirtyRectPos);
+                    break;
+                  }
+                }
+
+                damagedRects.push_back(rect);
+              }
+            }
+            else
+            {
+              // 1. The item is not dirty, the node and renderer referenced by the item are still exist.
+              // 2. Mark the related dirty rects as visited so they will not be removed below.
+              auto dirtyRectPos = std::lower_bound(itemsDirtyRects.begin(), itemsDirtyRects.end(), dirtyRect);
+              while (dirtyRectPos != itemsDirtyRects.end())
+              {
+                if (dirtyRectPos->node != item.mNode || dirtyRectPos->renderer != item.mRenderer)
+                {
+                  break;
+                }
+
+                dirtyRectPos->visited = true;
+                dirtyRectPos++;
+              }
+            }
+          }
+        }
+      }
+    }
+  }
+
+  // Check removed nodes or removed renderers dirty rects
+  auto i = itemsDirtyRects.begin();
+  auto j = itemsDirtyRects.begin();
+  while (i != itemsDirtyRects.end())
+  {
+    if (i->visited)
+    {
+      *j++ = *i;
+    }
+    else
+    {
+      Rect<int>& dirtRect = i->rect;
+      damagedRects.push_back(dirtRect);
+    }
+    i++;
+  }
+
+  itemsDirtyRects.resize(j - itemsDirtyRects.begin());
+  damagedRectCleaner.SetCleanOnReturn(false);
+}
+
+void RenderManager::RenderScene( Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo )
+{
+  Rect<int> clippingRect;
+  RenderScene( status, scene, renderToFbo, clippingRect);
+}
 
-void RenderManager::RenderScene( Integration::Scene& scene, bool renderToFbo )
+void RenderManager::RenderScene( Integration::RenderStatus& status, Integration::Scene& scene, bool renderToFbo, Rect<int>& clippingRect )
 {
   Internal::Scene& sceneInternal = GetImplementation( scene );
   SceneGraph::Scene* sceneObject = sceneInternal.GetSceneObject();
@@ -586,6 +811,9 @@ void RenderManager::RenderScene( Integration::Scene& scene, bool renderToFbo )
       continue; // skip
     }
 
+    // Mark that we will require a post-render step to be performed (includes swap-buffers).
+    status.SetNeedsPostRender( true );
+
     Rect<int32_t> viewportRect;
     Vector4   clearColor;
 
@@ -601,6 +829,7 @@ void RenderManager::RenderScene( Integration::Scene& scene, bool renderToFbo )
     Rect<int32_t> surfaceRect = mImpl->defaultSurfaceRect;
     Integration::DepthBufferAvailable depthBufferAvailable = mImpl->depthBufferAvailable;
     Integration::StencilBufferAvailable stencilBufferAvailable = mImpl->stencilBufferAvailable;
+    int surfaceOrientation = mImpl->defaultSurfaceOrientation;
 
     if ( instruction.mFrameBuffer )
     {
@@ -636,7 +865,8 @@ void RenderManager::RenderScene( Integration::Scene& scene, bool renderToFbo )
       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() );
+    // Make sure that GL context must be created
+     mImpl->currentContext->GlContextCreated();
 
     // reset the program matrices for all programs once per frame
     // this ensures we will set view and projection matrix once per program per camera
@@ -686,7 +916,7 @@ void RenderManager::RenderScene( Integration::Scene& scene, bool renderToFbo )
       clearMask |= GL_STENCIL_BUFFER_BIT;
     }
 
-    if( !instruction.mIgnoreRenderToFbo && ( instruction.mFrameBuffer != 0 ) )
+    if( !instruction.mIgnoreRenderToFbo && ( instruction.mFrameBuffer != nullptr ) )
     {
       // Offscreen buffer rendering
       if ( instruction.mIsViewportSet )
@@ -699,6 +929,7 @@ void RenderManager::RenderScene( Integration::Scene& scene, bool renderToFbo )
       {
         viewportRect.Set( 0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight() );
       }
+      surfaceOrientation = 0;
     }
     else // No Offscreen frame buffer rendering
     {
@@ -715,8 +946,15 @@ void RenderManager::RenderScene( Integration::Scene& scene, bool renderToFbo )
       }
     }
 
+    if( surfaceOrientation == 90 || surfaceOrientation == 270 )
+    {
+      int temp = viewportRect.width;
+      viewportRect.width = viewportRect.height;
+      viewportRect.height = temp;
+    }
+
     bool clearFullFrameRect = true;
-    if( instruction.mFrameBuffer != 0 )
+    if( instruction.mFrameBuffer != nullptr )
     {
       Viewport frameRect( 0, 0, instruction.mFrameBuffer->GetWidth(), instruction.mFrameBuffer->GetHeight() );
       clearFullFrameRect = ( frameRect == viewportRect );
@@ -726,26 +964,45 @@ void RenderManager::RenderScene( Integration::Scene& scene, bool renderToFbo )
       clearFullFrameRect = ( surfaceRect == viewportRect );
     }
 
+    if (!clippingRect.IsEmpty())
+    {
+      if (!clippingRect.Intersect(viewportRect))
+      {
+        DALI_LOG_ERROR("Invalid clipping rect %d %d %d %d\n", clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
+        clippingRect = Rect<int>();
+      }
+      clearFullFrameRect = false;
+    }
+
     mImpl->currentContext->Viewport(viewportRect.x, viewportRect.y, viewportRect.width, viewportRect.height);
 
-    if( instruction.mIsClearColorSet )
+    if (instruction.mIsClearColorSet)
     {
-      mImpl->currentContext->ClearColor( clearColor.r,
-                                         clearColor.g,
-                                         clearColor.b,
-                                         clearColor.a );
-
-      if( !clearFullFrameRect )
+      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 );
+        if (!clippingRect.IsEmpty())
+        {
+          mImpl->currentContext->SetScissorTest(true);
+          mImpl->currentContext->Scissor(clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height);
+          mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
+          mImpl->currentContext->SetScissorTest(false);
+        }
+        else
+        {
+          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 );
+        mImpl->currentContext->SetScissorTest(false);
+        mImpl->currentContext->Clear(clearMask, Context::FORCE_CLEAR);
       }
     }
 
@@ -758,7 +1015,9 @@ void RenderManager::RenderScene( Integration::Scene& scene, bool renderToFbo )
         mImpl->renderBufferIndex,
         depthBufferAvailable,
         stencilBufferAvailable,
-        mImpl->boundTextures );
+        mImpl->boundTextures,
+        clippingRect,
+        surfaceOrientation );
 
     // Synchronise the FBO/Texture access when there are multiple contexts
     if ( mImpl->currentContext->IsSurfacelessContextSupported() )