0025984: Visualization, OpenGl_Workspace::RedrawImmediate() - do not swap buffers...
[occt.git] / src / OpenGl / OpenGl_Workspace.cxx
index 825ac63..a911d0f 100644 (file)
 // Alternatively, this file may be used under the terms of Open CASCADE
 // commercial license or contractual agreement.
 
-#ifdef HAVE_CONFIG_H
-  #include <config.h>
-#endif
-
 #include <OpenGl_GlCore15.hxx>
+#include <OpenGl_ArbFBO.hxx>
 
 #include <InterfaceGraphic.hxx>
 
 #include <OpenGl_Element.hxx>
 #include <OpenGl_FrameBuffer.hxx>
 #include <OpenGl_Structure.hxx>
+#include <OpenGl_Sampler.hxx>
+#include <OpenGl_ShaderManager.hxx>
 #include <OpenGl_Texture.hxx>
+#include <OpenGl_Utils.hxx>
 #include <OpenGl_View.hxx>
 #include <OpenGl_Workspace.hxx>
 
@@ -137,29 +137,34 @@ void OpenGl_Material::Init (const OPENGL_SURF_PROP& theProp)
 // function : OpenGl_Workspace
 // purpose  :
 // =======================================================================
-OpenGl_Workspace::OpenGl_Workspace (const Handle(Aspect_DisplayConnection)& theDisplayConnection,
+OpenGl_Workspace::OpenGl_Workspace (const Handle(OpenGl_GraphicDriver)& theDriver,
                                     const CALL_DEF_WINDOW&        theCWindow,
                                     Aspect_RenderingContext       theGContext,
                                     const Handle(OpenGl_Caps)&    theCaps,
                                     const Handle(OpenGl_Context)& theShareCtx)
-: OpenGl_Window (theDisplayConnection, theCWindow, theGContext, theCaps, theShareCtx),
+: OpenGl_Window (theDriver, theCWindow, theGContext, theCaps, theShareCtx),
   NamedStatus (0),
   HighlightColor (&THE_WHITE_COLOR),
   //
   myComputeInitStatus (OpenGl_RT_NONE),
   myIsRaytraceDataValid (Standard_False),
-  myTraversalStackSize (THE_DEFAULT_STACK_SIZE),
+  myIsRaytraceWarnTextures (Standard_False),
+  myHasFboBlit (Standard_True),
   myViewModificationStatus (0),
   myLayersModificationStatus (0),
   //
+  myRaytraceFilter       (new OpenGl_RaytraceFilter()),
+  myToRedrawGL           (Standard_True),
+  myViewId               (-1),
   myAntiAliasingMode     (3),
   myTransientDrawToFront (Standard_True),
   myBackBufferRestored   (Standard_False),
   myIsImmediateDrawn     (Standard_False),
-  myUseTransparency (Standard_False),
   myUseZBuffer (Standard_False),
   myUseDepthTest (Standard_True),
   myUseGLLight (Standard_True),
+  myIsCullingEnabled (Standard_False),
+  myFrameCounter (0),
   //
   AspectLine_set (&myDefaultAspectLine),
   AspectLine_applied (NULL),
@@ -175,9 +180,10 @@ OpenGl_Workspace::OpenGl_Workspace (const Handle(Aspect_DisplayConnection)& theD
   StructureMatrix_applied (&myDefaultMatrix),
   myCullingMode (TelCullUndefined),
   myModelViewMatrix (myDefaultMatrix),
-  PolygonOffset_applied (NULL)
+  PolygonOffset_applied (THE_DEFAULT_POFFSET)
 {
   myGlContext->core11fwd->glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
+  myResultFBO = new OpenGl_FrameBuffer();
 
   if (!myGlContext->GetResource ("OpenGl_LineAttributes", myLineAttribs))
   {
@@ -189,15 +195,21 @@ OpenGl_Workspace::OpenGl_Workspace (const Handle(Aspect_DisplayConnection)& theD
 
   // General initialization of the context
 
-  // Eviter d'avoir les faces mal orientees en noir.
-  // Pourrait etre utiliser pour detecter les problemes d'orientation
-  glLightModeli ((GLenum )GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
+#if !defined(GL_ES_VERSION_2_0)
+  if (myGlContext->core11 != NULL)
+  {
+    // Eviter d'avoir les faces mal orientees en noir.
+    // Pourrait etre utiliser pour detecter les problemes d'orientation
+    glLightModeli ((GLenum )GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
+
+    // Optimisation pour le Fog et l'antialiasing
+    glHint (GL_FOG_HINT,            GL_FASTEST);
+    glHint (GL_POINT_SMOOTH_HINT,   GL_FASTEST);
+  }
 
-  // Optimisation pour le Fog et l'antialiasing
-  glHint (GL_FOG_HINT,            GL_FASTEST);
-  glHint (GL_POINT_SMOOTH_HINT,   GL_FASTEST);
   glHint (GL_LINE_SMOOTH_HINT,    GL_FASTEST);
   glHint (GL_POLYGON_SMOOTH_HINT, GL_FASTEST);
+#endif
 
   // AA mode
   const char* anAaEnv = ::getenv ("CALL_OPENGL_ANTIALIASING_MODE");
@@ -231,6 +243,16 @@ OpenGl_Workspace::~OpenGl_Workspace()
     myGlContext->ReleaseResource ("OpenGl_LineAttributes", Standard_True);
   }
 
+  if (!myResultFBO.IsNull())
+  {
+    myResultFBO->Release (myGlContext.operator->());
+    myResultFBO.Nullify();
+  }
+  if (myFullScreenQuad.IsValid())
+  {
+    myFullScreenQuad.Release (myGlContext.operator->());
+  }
+
   ReleaseRaytraceResources();
 }
 
@@ -251,21 +273,14 @@ Standard_Boolean OpenGl_Workspace::Activate()
   return Standard_True;
 }
 
-// =======================================================================
-// function : UseTransparency
-// purpose  : call_togl_transparency
-// =======================================================================
-void OpenGl_Workspace::UseTransparency (const Standard_Boolean theFlag)
-{
-  myUseTransparency = theFlag;
-}
-
 //=======================================================================
 //function : ResetAppliedAspect
 //purpose  : Sets default values of GL parameters in accordance with default aspects
 //=======================================================================
 void OpenGl_Workspace::ResetAppliedAspect()
 {
+  myGlContext->BindDefaultVao();
+
   NamedStatus           = !myTextureBound.IsNull() ? OPENGL_NS_TEXTURE : 0;
   HighlightColor        = &THE_WHITE_COLOR;
   AspectLine_set        = &myDefaultAspectLine;
@@ -278,7 +293,7 @@ void OpenGl_Workspace::ResetAppliedAspect()
   AspectText_applied    = NULL;
   TextParam_set         = &myDefaultTextParam;
   TextParam_applied     = NULL;
-  PolygonOffset_applied = NULL;
+  PolygonOffset_applied = THE_DEFAULT_POFFSET;
   myCullingMode         = TelCullUndefined;
 
   AspectLine(Standard_True);
@@ -298,37 +313,58 @@ Handle(OpenGl_Texture) OpenGl_Workspace::DisableTexture()
     return myTextureBound;
   }
 
+  const Handle(OpenGl_Sampler)& aSampler = myGlContext->TextureSampler();
+  if (!aSampler.IsNull())
+  {
+    aSampler->Unbind (*myGlContext);
+  }
+
+#if !defined(GL_ES_VERSION_2_0)
   // reset texture matrix because some code may expect it is identity
-  GLint aMatrixMode = GL_TEXTURE;
-  glGetIntegerv (GL_MATRIX_MODE, &aMatrixMode);
-  glMatrixMode (GL_TEXTURE);
-  glLoadIdentity();
-  glMatrixMode (aMatrixMode);
+  if (myGlContext->core11 != NULL)
+  {
+    GLint aMatrixMode = GL_TEXTURE;
+    glGetIntegerv (GL_MATRIX_MODE, &aMatrixMode);
+    glMatrixMode (GL_TEXTURE);
+    glLoadIdentity();
+    glMatrixMode (aMatrixMode);
+  }
+#endif
 
   myTextureBound->Unbind (myGlContext);
   switch (myTextureBound->GetTarget())
   {
+  #if !defined(GL_ES_VERSION_2_0)
     case GL_TEXTURE_1D:
     {
-      if (myTextureBound->GetParams()->GenMode() != GL_NONE)
+      if (myGlContext->core11 != NULL)
       {
-        glDisable (GL_TEXTURE_GEN_S);
+        if (myTextureBound->GetParams()->GenMode() != GL_NONE)
+        {
+          glDisable (GL_TEXTURE_GEN_S);
+        }
+        glDisable (GL_TEXTURE_1D);
       }
-      glDisable (GL_TEXTURE_1D);
       break;
     }
+  #endif
     case GL_TEXTURE_2D:
     {
-      if (myTextureBound->GetParams()->GenMode() != GL_NONE)
+    #if !defined(GL_ES_VERSION_2_0)
+      if (myGlContext->core11 != NULL)
       {
-        glDisable (GL_TEXTURE_GEN_S);
-        glDisable (GL_TEXTURE_GEN_T);
-        if (myTextureBound->GetParams()->GenMode() == Graphic3d_TOTM_SPRITE)
+        if (myTextureBound->GetParams()->GenMode() != GL_NONE)
         {
-          glDisable (GL_POINT_SPRITE);
+          glDisable (GL_TEXTURE_GEN_S);
+          glDisable (GL_TEXTURE_GEN_T);
+          if (myTextureBound->GetParams()->GenMode() == Graphic3d_TOTM_SPRITE)
+          {
+            glDisable (GL_POINT_SPRITE);
+          }
         }
+        glDisable (GL_TEXTURE_2D);
       }
-      glDisable (GL_TEXTURE_2D);
+    #endif
       break;
     }
     default: break;
@@ -352,92 +388,124 @@ void OpenGl_Workspace::setTextureParams (Handle(OpenGl_Texture)&
     return;
   }
 
+#if !defined(GL_ES_VERSION_2_0)
   GLint aMatrixMode = GL_TEXTURE;
-  glGetIntegerv (GL_MATRIX_MODE, &aMatrixMode);
-
-  // setup texture matrix
-  glMatrixMode (GL_TEXTURE);
-  glLoadIdentity();
-  const Graphic3d_Vec2& aScale = aParams->Scale();
-  const Graphic3d_Vec2& aTrans = aParams->Translation();
-  glScalef     ( aScale.x(),  aScale.y(), 1.0f);
-  glTranslatef (-aTrans.x(), -aTrans.y(), 0.0f);
-  glRotatef (-aParams->Rotation(), 0.0f, 0.0f, 1.0f);
-
-  // setup generation of texture coordinates
-  switch (aParams->GenMode())
+  if (myGlContext->core11 != NULL)
   {
-    case Graphic3d_TOTM_OBJECT:
+    glGetIntegerv (GL_MATRIX_MODE, &aMatrixMode);
+
+    // setup texture matrix
+    glMatrixMode (GL_TEXTURE);
+    OpenGl_Mat4 aTextureMat;
+    const Graphic3d_Vec2& aScale = aParams->Scale();
+    const Graphic3d_Vec2& aTrans = aParams->Translation();
+    OpenGl_Utils::Scale     (aTextureMat,  aScale.x(),  aScale.y(), 1.0f);
+    OpenGl_Utils::Translate (aTextureMat, -aTrans.x(), -aTrans.y(), 0.0f);
+    OpenGl_Utils::Rotate    (aTextureMat, -aParams->Rotation(), 0.0f, 0.0f, 1.0f);
+    glLoadMatrixf (aTextureMat);
+
+    GLint anEnvMode = GL_MODULATE; // lighting mode
+    if (!aParams->IsModulate())
     {
-      glTexGeni  (GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
-      glTexGenfv (GL_S, GL_OBJECT_PLANE,     aParams->GenPlaneS().GetData());
-      if (theTexture->GetTarget() != GL_TEXTURE_1D)
+      anEnvMode = GL_DECAL;
+      if (theTexture->GetFormat() == GL_ALPHA
+       || theTexture->GetFormat() == GL_LUMINANCE)
       {
-        glTexGeni  (GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
-        glTexGenfv (GL_T, GL_OBJECT_PLANE,     aParams->GenPlaneT().GetData());
+        anEnvMode = GL_REPLACE;
       }
-      break;
     }
-    case Graphic3d_TOTM_SPHERE:
+
+    // setup generation of texture coordinates
+    switch (aParams->GenMode())
     {
-      glTexGeni (GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
-      if (theTexture->GetTarget() != GL_TEXTURE_1D)
+      case Graphic3d_TOTM_OBJECT:
       {
-        glTexGeni (GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
+        glTexGeni  (GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
+        glTexGenfv (GL_S, GL_OBJECT_PLANE,     aParams->GenPlaneS().GetData());
+        if (theTexture->GetTarget() != GL_TEXTURE_1D)
+        {
+          glTexGeni  (GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
+          glTexGenfv (GL_T, GL_OBJECT_PLANE,     aParams->GenPlaneT().GetData());
+        }
+        break;
       }
-      break;
-    }
-    case Graphic3d_TOTM_EYE:
-    {
-      glMatrixMode (GL_MODELVIEW);
-      glPushMatrix();
-      glLoadIdentity();
+      case Graphic3d_TOTM_SPHERE:
+      {
+        glTexGeni (GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
+        if (theTexture->GetTarget() != GL_TEXTURE_1D)
+        {
+          glTexGeni (GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
+        }
+        break;
+      }
+      case Graphic3d_TOTM_EYE:
+      {
+        myGlContext->WorldViewState.Push();
 
-      glTexGeni  (GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
-      glTexGenfv (GL_S, GL_EYE_PLANE,        aParams->GenPlaneS().GetData());
+        myGlContext->WorldViewState.SetIdentity();
+        myGlContext->ApplyWorldViewMatrix();
 
-      if (theTexture->GetTarget() != GL_TEXTURE_1D)
-      {
-        glTexGeni  (GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
-        glTexGenfv (GL_T, GL_EYE_PLANE,        aParams->GenPlaneT().GetData());
+        glTexGeni  (GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
+        glTexGenfv (GL_S, GL_EYE_PLANE,        aParams->GenPlaneS().GetData());
+
+        if (theTexture->GetTarget() != GL_TEXTURE_1D)
+        {
+          glTexGeni  (GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
+          glTexGenfv (GL_T, GL_EYE_PLANE,        aParams->GenPlaneT().GetData());
+        }
+
+        myGlContext->WorldViewState.Pop();
+
+        break;
       }
-      glPopMatrix();
-      break;
-    }
-    case Graphic3d_TOTM_SPRITE:
-    {
-      if (GetGlContext()->core20 != NULL)
+      case Graphic3d_TOTM_SPRITE:
       {
-        glEnable  (GL_POINT_SPRITE);
-        glTexEnvi (GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
-        glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
-        GetGlContext()->core15->glPointParameteri (GL_POINT_SPRITE_COORD_ORIGIN, GL_LOWER_LEFT);
+        if (GetGlContext()->core20fwd != NULL)
+        {
+          glEnable  (GL_POINT_SPRITE);
+          glTexEnvi (GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
+          anEnvMode = GL_REPLACE;
+          GetGlContext()->core15->glPointParameteri (GL_POINT_SPRITE_COORD_ORIGIN, GL_LOWER_LEFT);
+        }
+        break;
       }
-      break;
+      case Graphic3d_TOTM_MANUAL:
+      default: break;
     }
-    case Graphic3d_TOTM_MANUAL:
-    default: break;
-  }
 
-  // setup lighting
-  if (aParams->GenMode() != Graphic3d_TOTM_SPRITE)
-  {
-    glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, aParams->IsModulate() ? GL_MODULATE : GL_DECAL);
+    // setup lighting
+    glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, anEnvMode);
   }
+#endif
+
+  // get active sampler object to override default texture parameters
+  const Handle(OpenGl_Sampler)& aSampler = myGlContext->TextureSampler();
 
   // setup texture filtering and wrapping
   //if (theTexture->GetParams() != theParams)
   const GLenum aFilter   = (aParams->Filter() == Graphic3d_TOTF_NEAREST) ? GL_NEAREST : GL_LINEAR;
-  const GLenum aWrapMode = aParams->IsRepeat() ? GL_REPEAT : GL_CLAMP;
+  const GLenum aWrapMode = aParams->IsRepeat() ? GL_REPEAT : myGlContext->TextureWrapClamp();
   switch (theTexture->GetTarget())
   {
+  #if !defined(GL_ES_VERSION_2_0)
     case GL_TEXTURE_1D:
     {
-      glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, aFilter);
-      glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, aFilter);
-      glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_WRAP_S,     aWrapMode);
+      if (aSampler.IsNull() || !aSampler->IsValid())
+      {
+        glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, aFilter);
+        glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, aFilter);
+        glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_WRAP_S,     aWrapMode);
+      }
+      else
+      {
+        aSampler->SetParameter (*myGlContext, GL_TEXTURE_MAG_FILTER, aFilter);
+        aSampler->SetParameter (*myGlContext, GL_TEXTURE_MIN_FILTER, aFilter);
+        aSampler->SetParameter (*myGlContext, GL_TEXTURE_WRAP_S,     aWrapMode);
+      }
+
       break;
     }
+  #endif
     case GL_TEXTURE_2D:
     {
       GLenum aFilterMin = aFilter;
@@ -457,37 +525,58 @@ void OpenGl_Workspace::setTextureParams (Handle(OpenGl_Texture)&
         {
           // setup degree of anisotropy filter
           const GLint aMaxDegree = myGlContext->MaxDegreeOfAnisotropy();
+          GLint aDegree;
           switch (aParams->AnisoFilter())
           {
             case Graphic3d_LOTA_QUALITY:
             {
-              glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, aMaxDegree);
+              aDegree = aMaxDegree;
               break;
             }
             case Graphic3d_LOTA_MIDDLE:
             {
-
-              glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, (aMaxDegree <= 4) ? 2 : (aMaxDegree / 2));
+              aDegree = (aMaxDegree <= 4) ? 2 : (aMaxDegree / 2);
               break;
             }
             case Graphic3d_LOTA_FAST:
             {
-              glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 2);
+              aDegree = 2;
               break;
             }
             case Graphic3d_LOTA_OFF:
             default:
             {
-              glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1);
+              aDegree = 1;
               break;
             }
           }
+
+          if (aSampler.IsNull() || !aSampler->IsValid())
+          {
+            glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, aDegree);
+          }
+          else
+          {
+            aSampler->SetParameter (*myGlContext, GL_TEXTURE_MAX_ANISOTROPY_EXT, aDegree);
+          }
         }
       }
-      glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, aFilterMin);
-      glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, aFilter);
-      glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,     aWrapMode);
-      glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,     aWrapMode);
+
+      if (aSampler.IsNull() || !aSampler->IsValid())
+      {
+        glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, aFilterMin);
+        glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, aFilter);
+        glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,     aWrapMode);
+        glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,     aWrapMode);
+      }
+      else
+      {
+        aSampler->SetParameter (*myGlContext, GL_TEXTURE_MIN_FILTER, aFilterMin);
+        aSampler->SetParameter (*myGlContext, GL_TEXTURE_MAG_FILTER, aFilter);
+        aSampler->SetParameter (*myGlContext, GL_TEXTURE_WRAP_S,     aWrapMode);
+        aSampler->SetParameter (*myGlContext, GL_TEXTURE_WRAP_T,     aWrapMode);
+      }
+
       break;
     }
     default: break;
@@ -495,29 +584,44 @@ void OpenGl_Workspace::setTextureParams (Handle(OpenGl_Texture)&
 
   switch (theTexture->GetTarget())
   {
+  #if !defined(GL_ES_VERSION_2_0)
     case GL_TEXTURE_1D:
     {
-      if (aParams->GenMode() != Graphic3d_TOTM_MANUAL)
+      if (myGlContext->core11 != NULL)
       {
-        glEnable (GL_TEXTURE_GEN_S);
+        if (aParams->GenMode() != Graphic3d_TOTM_MANUAL)
+        {
+          glEnable (GL_TEXTURE_GEN_S);
+        }
+        glEnable (GL_TEXTURE_1D);
       }
-      glEnable (GL_TEXTURE_1D);
       break;
     }
+  #endif
     case GL_TEXTURE_2D:
     {
-      if (aParams->GenMode() != Graphic3d_TOTM_MANUAL)
+    #if !defined(GL_ES_VERSION_2_0)
+      if (myGlContext->core11 != NULL)
       {
-        glEnable (GL_TEXTURE_GEN_S);
-        glEnable (GL_TEXTURE_GEN_T);
+        if (aParams->GenMode() != Graphic3d_TOTM_MANUAL)
+        {
+          glEnable (GL_TEXTURE_GEN_S);
+          glEnable (GL_TEXTURE_GEN_T);
+        }
+        glEnable (GL_TEXTURE_2D);
       }
-      glEnable (GL_TEXTURE_2D);
+    #endif
       break;
     }
     default: break;
   }
 
-  glMatrixMode (aMatrixMode); // turn back active matrix
+#if !defined(GL_ES_VERSION_2_0)
+  if (myGlContext->core11 != NULL)
+  {
+    glMatrixMode (aMatrixMode); // turn back active matrix
+  }
+#endif
   theTexture->SetParams (aParams);
 }
 
@@ -545,6 +649,15 @@ Handle(OpenGl_Texture) OpenGl_Workspace::EnableTexture (const Handle(OpenGl_Text
   myTextureBound->Bind (myGlContext);
   setTextureParams (myTextureBound, theParams);
 
+  // If custom sampler object is available it will be
+  // used for overriding default texture parameters
+  const Handle(OpenGl_Sampler)& aSampler = myGlContext->TextureSampler();
+
+  if (!aSampler.IsNull() && aSampler->IsValid())
+  {
+    aSampler->Bind (*myGlContext);
+  }
+
   return aPrevTexture;
 }
 
@@ -561,50 +674,131 @@ void OpenGl_Workspace::Redraw (const Graphic3d_CView& theCView,
     return;
   }
 
+  ++myFrameCounter;
+  myIsCullingEnabled = theCView.IsCullingEnabled;
+
   // release pending GL resources
-  Handle(OpenGl_Context) aGlCtx = GetGlContext();
-  aGlCtx->ReleaseDelayed();
+  myGlContext->ReleaseDelayed();
 
   // fetch OpenGl context state
-  aGlCtx->FetchState();
+  myGlContext->FetchState();
 
-  Tint toSwap = (aGlCtx->IsRender()); // swap buffers
-  GLint aViewPortBack[4];
   OpenGl_FrameBuffer* aFrameBuffer = (OpenGl_FrameBuffer* )theCView.ptrFBO;
   if (aFrameBuffer != NULL)
   {
-    glGetIntegerv (GL_VIEWPORT, aViewPortBack);
-    aFrameBuffer->SetupViewport (aGlCtx);
-    aFrameBuffer->BindBuffer    (aGlCtx);
-    toSwap = 0; // no need to swap buffers
+    aFrameBuffer->SetupViewport (myGlContext);
+  }
+  else
+  {
+    myGlContext->core11fwd->glViewport (0, 0, myWidth, myHeight);
   }
+  bool toSwap = myGlContext->IsRender()
+            && !myGlContext->caps->buffersNoSwap
+            &&  aFrameBuffer == NULL;
 
-  if (!theCView.IsRaytracing || myComputeInitStatus == OpenGl_RT_FAIL)
+  Standard_Integer aSizeX = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeX() : myWidth;
+  Standard_Integer aSizeY = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeY() : myHeight;
+
+  if (myHasFboBlit
+   && myTransientDrawToFront)
   {
-    const Standard_Boolean isImmediate = !myView->ImmediateStructures().IsEmpty();
-    redraw1 (theCView, theCUnderLayer, theCOverLayer, isImmediate ? 0 : toSwap);
-    if (isImmediate)
+    if (myResultFBO->GetVPSizeX() != aSizeX
+     || myResultFBO->GetVPSizeY() != aSizeY)
     {
-      RedrawImmediate (theCView, theCUnderLayer, theCOverLayer, Standard_True);
+      // prepare FBOs containing main scene
+      // for further blitting and rendering immediate presentations on top
+      if (myGlContext->core20fwd != NULL)
+      {
+        myResultFBO->Init (myGlContext, aSizeX, aSizeY);
+      }
     }
 
-    theCView.WasRedrawnGL = Standard_True;
+    if (myResultFBO->IsValid())
+    {
+      myResultFBO->SetupViewport (myGlContext);
+    }
   }
   else
   {
-    int aSizeX = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeX() : myWidth;
-    int aSizeY = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeY() : myHeight;
+    myResultFBO->Release (myGlContext.operator->());
+  }
+
+  myToRedrawGL = Standard_True;
+  if (theCView.RenderParams.Method == Graphic3d_RM_RAYTRACING
+   && myComputeInitStatus != OpenGl_RT_FAIL)
+  {
+    if (InitRaytraceResources (theCView) && UpdateRaytraceGeometry (OpenGl_GUM_CHECK) && myIsRaytraceDataValid)
+    {
+      myToRedrawGL = Standard_False;
+
+      // Only non-raytracable structures should be rendered in OpenGL mode.
+      Handle(OpenGl_RenderFilter) aRenderFilter = GetRenderFilter();
+      myRaytraceFilter->SetPrevRenderFilter (aRenderFilter);
+      SetRenderFilter (myRaytraceFilter);
+
+      if (myOpenGlFBO.IsNull())
+      {
+        myOpenGlFBO = new OpenGl_FrameBuffer();
+      }
+      if (myOpenGlFBO->GetVPSizeX() != aSizeX
+       || myOpenGlFBO->GetVPSizeY() != aSizeY)
+      {
+        myOpenGlFBO->Init (myGlContext, aSizeX, aSizeY);
+      }
+
+      // OverLayer and UnderLayer shouldn't be drawn by OpenGL.
+      // They will be drawn during ray-tracing.
+      Aspect_CLayer2d anEmptyCLayer;
+      anEmptyCLayer.ptrLayer = NULL;
+
+      myOpenGlFBO->BindBuffer (myGlContext);
+      redraw1 (theCView, anEmptyCLayer, anEmptyCLayer);
+      myOpenGlFBO->UnbindBuffer (myGlContext);
+
+      Raytrace (theCView, aSizeX, aSizeY,
+                theCOverLayer, theCUnderLayer,
+                myResultFBO->IsValid() ? myResultFBO.operator->() : aFrameBuffer);
+      myBackBufferRestored = Standard_True;
+      myIsImmediateDrawn   = Standard_False;
+      if (!redrawImmediate (theCView, theCOverLayer, theCUnderLayer, aFrameBuffer))
+      {
+        toSwap = false;
+      }
 
-    Raytrace (theCView, aSizeX, aSizeY, toSwap, aFrameBuffer);
+      SetRenderFilter (aRenderFilter);
 
-    theCView.WasRedrawnGL = Standard_False;
+      theCView.WasRedrawnGL = Standard_False;
+    }
+  }
+
+  if (myToRedrawGL)
+  {
+    // draw entire frame using normal OpenGL pipeline
+    if (myResultFBO->IsValid())
+    {
+      myResultFBO->BindBuffer (myGlContext);
+    }
+    else if (aFrameBuffer != NULL)
+    {
+      aFrameBuffer->BindBuffer (myGlContext);
+    }
+
+    redraw1 (theCView, theCUnderLayer, theCOverLayer);
+    myBackBufferRestored = Standard_True;
+    myIsImmediateDrawn   = Standard_False;
+    if (!redrawImmediate (theCView, theCOverLayer, theCUnderLayer, aFrameBuffer))
+    {
+      toSwap = false;
+    }
+
+    theCView.WasRedrawnGL = Standard_True;
   }
 
   if (aFrameBuffer != NULL)
   {
-    aFrameBuffer->UnbindBuffer (aGlCtx);
+    aFrameBuffer->UnbindBuffer (myGlContext);
     // move back original viewport
-    glViewport (aViewPortBack[0], aViewPortBack[1], aViewPortBack[2], aViewPortBack[3]);
+    myGlContext->core11fwd->glViewport (0, 0, myWidth, myHeight);
   }
 
 #if defined(_WIN32) && defined(HAVE_VIDEOCAPTURE)
@@ -625,8 +819,22 @@ void OpenGl_Workspace::Redraw (const Graphic3d_CView& theCView,
   }
 #endif
 
+  // Swap the buffers
+  if (toSwap)
+  {
+    GetGlContext()->SwapBuffers();
+    if (!myResultFBO->IsValid())
+    {
+      myBackBufferRestored = Standard_False;
+    }
+  }
+  else
+  {
+    myGlContext->core11fwd->glFlush();
+  }
+
   // reset render mode state
-  aGlCtx->FetchState();
+  myGlContext->FetchState();
 }
 
 // =======================================================================
@@ -635,8 +843,7 @@ void OpenGl_Workspace::Redraw (const Graphic3d_CView& theCView,
 // =======================================================================
 void OpenGl_Workspace::redraw1 (const Graphic3d_CView& theCView,
                                 const Aspect_CLayer2d& theCUnderLayer,
-                                const Aspect_CLayer2d& theCOverLayer,
-                                const int              theToSwap)
+                                const Aspect_CLayer2d& theCOverLayer)
 {
   if (myView.IsNull())
   {
@@ -660,7 +867,11 @@ void OpenGl_Workspace::redraw1 (const Graphic3d_CView& theCView,
       glDisable (GL_DEPTH_TEST);
     }
 
+  #if !defined(GL_ES_VERSION_2_0)
     glClearDepth (1.0);
+  #else
+    glClearDepthf (1.0f);
+  #endif
     toClear |= GL_DEPTH_BUFFER_BIT;
   }
   else
@@ -668,34 +879,29 @@ void OpenGl_Workspace::redraw1 (const Graphic3d_CView& theCView,
     glDisable (GL_DEPTH_TEST);
   }
 
-  if (NamedStatus & OPENGL_NS_WHITEBACK)
+  if (!ToRedrawGL())
   {
-    // set background to white
-    glClearColor (1.0f, 1.0f, 1.0f, 1.0f);
-    toClear |= GL_DEPTH_BUFFER_BIT;
+    // set background to black
+    glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
+    toClear |= GL_DEPTH_BUFFER_BIT; //
   }
   else
   {
-    glClearColor (myBgColor.rgb[0], myBgColor.rgb[1], myBgColor.rgb[2], 0.0f);
+    if (NamedStatus & OPENGL_NS_WHITEBACK)
+    {
+        // set background to white
+      glClearColor (1.0f, 1.0f, 1.0f, 1.0f);
+      toClear |= GL_DEPTH_BUFFER_BIT;
+    }
+    else
+    {
+      glClearColor (myBgColor.rgb[0], myBgColor.rgb[1], myBgColor.rgb[2], 0.0f);
+    }
   }
   glClear (toClear);
 
   Handle(OpenGl_Workspace) aWS (this);
-  myView->Render (myPrintContext, aWS, theCView, theCUnderLayer, theCOverLayer);
-
-  // swap the buffers
-  if (theToSwap)
-  {
-    GetGlContext()->SwapBuffers();
-    myBackBufferRestored = Standard_False;
-    myIsImmediateDrawn   = Standard_False;
-  }
-  else
-  {
-    glFlush();
-    myBackBufferRestored = Standard_True;
-    myIsImmediateDrawn   = Standard_False;
-  }
+  myView->Render (myPrintContext, aWS, theCView, theCUnderLayer, theCOverLayer, Standard_False);
 }
 
 // =======================================================================
@@ -704,13 +910,20 @@ void OpenGl_Workspace::redraw1 (const Graphic3d_CView& theCView,
 // =======================================================================
 void OpenGl_Workspace::copyBackToFront()
 {
-  glMatrixMode (GL_PROJECTION);
-  glPushMatrix();
-  glLoadIdentity();
-  gluOrtho2D (0.0, (GLdouble )myWidth, 0.0, (GLdouble )myHeight);
-  glMatrixMode (GL_MODELVIEW);
-  glPushMatrix();
-  glLoadIdentity();
+#if !defined(GL_ES_VERSION_2_0)
+
+  OpenGl_Mat4 aProjectMat;
+  OpenGl_Utils::Ortho2D<Standard_ShortReal> (aProjectMat,
+    0.f, static_cast<GLfloat> (myWidth), 0.f, static_cast<GLfloat> (myHeight));
+
+  myGlContext->WorldViewState.Push();
+  myGlContext->ProjectionState.Push();
+
+  myGlContext->WorldViewState.SetIdentity();
+  myGlContext->ProjectionState.SetCurrent (aProjectMat);
+
+  myGlContext->ApplyProjectionMatrix();
+  myGlContext->ApplyWorldViewMatrix();
 
   DisableFeatures();
 
@@ -719,16 +932,16 @@ void OpenGl_Workspace::copyBackToFront()
 
   glRasterPos2i (0, 0);
   glCopyPixels  (0, 0, myWidth + 1, myHeight + 1, GL_COLOR);
+  //glCopyPixels  (0, 0, myWidth + 1, myHeight + 1, GL_DEPTH);
 
   EnableFeatures();
 
-  glMatrixMode (GL_PROJECTION);
-  glPopMatrix();
-  glMatrixMode (GL_MODELVIEW);
-  glPopMatrix();
-
+  myGlContext->WorldViewState.Pop();
+  myGlContext->ProjectionState.Pop();
+  myGlContext->ApplyProjectionMatrix();
   glDrawBuffer (GL_BACK);
 
+#endif
   myIsImmediateDrawn = Standard_False;
 }
 
@@ -746,9 +959,10 @@ void OpenGl_Workspace::DisplayCallback (const Graphic3d_CView& theCView,
 
   Aspect_GraphicCallbackStruct aCallData;
   aCallData.reason    = theReason;
-  aCallData.glContext = GetGlContext();
+  aCallData.glContext = myGlContext;
   aCallData.wsID      = theCView.WsId;
   aCallData.viewID    = theCView.ViewId;
+  aCallData.IsCoreProfile = (myGlContext->core11 == NULL);
   theCView.GDisplayCB (theCView.DefWindow.XWindow, theCView.GClientData, &aCallData);
 }
 
@@ -758,47 +972,161 @@ void OpenGl_Workspace::DisplayCallback (const Graphic3d_CView& theCView,
 // =======================================================================
 void OpenGl_Workspace::RedrawImmediate (const Graphic3d_CView& theCView,
                                         const Aspect_CLayer2d& theCUnderLayer,
-                                        const Aspect_CLayer2d& theCOverLayer,
-                                        const Standard_Boolean theToForce)
+                                        const Aspect_CLayer2d& theCOverLayer)
 {
-  if (!Activate())
+  if (!myTransientDrawToFront
+   || !myBackBufferRestored
+   || (myGlContext->caps->buffersNoSwap && !myResultFBO->IsValid()))
   {
+    Redraw (theCView, theCUnderLayer, theCOverLayer);
     return;
   }
+  else if (!Activate())
+  {
+    return;
+  }
+
+  if (redrawImmediate (theCView, theCUnderLayer, theCOverLayer, NULL, Standard_True)
+  && !myGlContext->caps->buffersNoSwap)
+  {
+    myGlContext->SwapBuffers();
+  }
+  else
+  {
+    myGlContext->core11fwd->glFlush();
+    MakeBackBufCurrent();
+  }
+}
 
-  GLboolean isDoubleBuffer = GL_FALSE;
-  glGetBooleanv (GL_DOUBLEBUFFER, &isDoubleBuffer);
-  if (myView->ImmediateStructures().IsEmpty())
+// =======================================================================
+// function : redrawImmediate
+// purpose  :
+// =======================================================================
+bool OpenGl_Workspace::redrawImmediate (const Graphic3d_CView& theCView,
+                                        const Aspect_CLayer2d& theCUnderLayer,
+                                        const Aspect_CLayer2d& theCOverLayer,
+                                        OpenGl_FrameBuffer*    theTargetFBO,
+                                        const Standard_Boolean theIsPartialUpdate)
+{
+  GLboolean toCopyBackToFront = GL_FALSE;
+  if (!myTransientDrawToFront)
   {
-    if (theToForce
-     || !myIsImmediateDrawn)
+    myBackBufferRestored = Standard_False;
+  }
+  else if (myResultFBO->IsValid()
+        && myGlContext->IsRender())
+  {
+    // clear destination before blitting
+    if (theTargetFBO != NULL)
     {
-      myIsImmediateDrawn = Standard_False;
-      return;
+      theTargetFBO->BindBuffer (myGlContext);
     }
-
-    if (myBackBufferRestored
-     && isDoubleBuffer)
+    else
     {
-      copyBackToFront();
-      glFlush();
+      myGlContext->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
+    }
+  #if !defined(GL_ES_VERSION_2_0)
+    myGlContext->core20fwd->glClearDepth  (1.0);
+  #else
+    myGlContext->core20fwd->glClearDepthf (1.0f);
+  #endif
+    myGlContext->core20fwd->glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
+
+  /*#if !defined(GL_ES_VERSION_2_0)
+    if (myGlContext->arbFBOBlit != NULL)
+    {
+      myResultFBO->BindReadBuffer (myGlContext);
+      if (theTargetFBO != NULL)
+      {
+        theTargetFBO->BindDrawBuffer (myGlContext);
+      }
+      else
+      {
+        myGlContext->arbFBO->glBindFramebuffer (GL_DRAW_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
+      }
+      // we don't copy stencil buffer here... does it matter for performance?
+      myGlContext->arbFBOBlit->glBlitFramebuffer (0, 0, myResultFBO->GetVPSizeX(), myResultFBO->GetVPSizeY(),
+                                                  0, 0, myResultFBO->GetVPSizeX(), myResultFBO->GetVPSizeY(),
+                                                  GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST);
+
+      if (theTargetFBO != NULL)
+      {
+        theTargetFBO->BindBuffer (myGlContext);
+      }
+      else
+      {
+        myGlContext->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
+      }
     }
     else
+  #endif*/
     {
-      Redraw (theCView, theCUnderLayer, theCOverLayer);
+      myGlContext->core20fwd->glDepthFunc (GL_ALWAYS);
+      myGlContext->core20fwd->glDepthMask (GL_TRUE);
+      myGlContext->core20fwd->glEnable (GL_DEPTH_TEST);
+
+      DisableTexture();
+      if (!myFullScreenQuad.IsValid())
+      {
+        OpenGl_Vec4 aQuad[4] =
+        {
+          OpenGl_Vec4( 1.0f, -1.0f, 1.0f, 0.0f),
+          OpenGl_Vec4( 1.0f,  1.0f, 1.0f, 1.0f),
+          OpenGl_Vec4(-1.0f, -1.0f, 0.0f, 0.0f),
+          OpenGl_Vec4(-1.0f,  1.0f, 0.0f, 1.0f)
+        };
+        myFullScreenQuad.Init (myGlContext, 4, 4, aQuad[0].GetData());
+      }
+
+      const Handle(OpenGl_ShaderManager)& aManager = myGlContext->ShaderManager();
+      if (myFullScreenQuad.IsValid()
+       && aManager->BindFboBlitProgram())
+      {
+        myResultFBO->ColorTexture()       ->Bind   (myGlContext, GL_TEXTURE0 + 0);
+        myResultFBO->DepthStencilTexture()->Bind   (myGlContext, GL_TEXTURE0 + 1);
+        myFullScreenQuad.BindVertexAttrib (myGlContext, 0);
+
+        myGlContext->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
+
+        myFullScreenQuad.UnbindVertexAttrib (myGlContext, 0);
+        myResultFBO->DepthStencilTexture()->Unbind (myGlContext, GL_TEXTURE0 + 1);
+        myResultFBO->ColorTexture()       ->Unbind (myGlContext, GL_TEXTURE0 + 0);
+      }
+      else
+      {
+        TCollection_ExtendedString aMsg = TCollection_ExtendedString()
+          + "Error! FBO blitting has failed";
+        myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
+                                  GL_DEBUG_TYPE_ERROR_ARB,
+                                  0,
+                                  GL_DEBUG_SEVERITY_HIGH_ARB,
+                                  aMsg);
+        myHasFboBlit = Standard_False;
+        myResultFBO->Release (myGlContext.operator->());
+        return true;
+      }
     }
-    return;
   }
-
-  if (isDoubleBuffer && myTransientDrawToFront)
+  else if (theTargetFBO == NULL)
   {
-    if (!myBackBufferRestored)
+  #if !defined(GL_ES_VERSION_2_0)
+    myGlContext->core11fwd->glGetBooleanv (GL_DOUBLEBUFFER, &toCopyBackToFront);
+  #endif
+    if (toCopyBackToFront)
+    {
+      if (!myView->HasImmediateStructures()
+       && !theIsPartialUpdate)
+      {
+        // prefer Swap Buffers within Redraw in compatibility mode (without FBO)
+        return true;
+      }
+      copyBackToFront();
+      MakeFrontBufCurrent();
+    }
+    else
     {
-      Redraw (theCView, theCUnderLayer, theCOverLayer);
-      return;
+      myBackBufferRestored = Standard_False;
     }
-    copyBackToFront();
-    MakeFrontBufCurrent();
   }
   else
   {
@@ -806,23 +1134,53 @@ void OpenGl_Workspace::RedrawImmediate (const Graphic3d_CView& theCView,
   }
   myIsImmediateDrawn = Standard_True;
 
-  NamedStatus |= OPENGL_NS_IMMEDIATE;
-  ///glDisable (GL_LIGHTING);
-  glDisable (GL_DEPTH_TEST);
-
   Handle(OpenGl_Workspace) aWS (this);
+
+  if (myUseZBuffer)
+  {
+    glDepthFunc (GL_LEQUAL);
+    glDepthMask (GL_TRUE);
+    if (myUseDepthTest)
+    {
+      glEnable (GL_DEPTH_TEST);
+    }
+    else
+    {
+      glDisable (GL_DEPTH_TEST);
+    }
+
+  #if !defined(GL_ES_VERSION_2_0)
+    glClearDepth (1.0);
+  #else
+    glClearDepthf (1.0f);
+  #endif
+  }
+  else
+  {
+    glDisable (GL_DEPTH_TEST);
+  }
+
+  myView->Render (myPrintContext, aWS, theCView, theCUnderLayer, theCOverLayer, Standard_True);
+  if (!myView->ImmediateStructures().IsEmpty())
+  {
+    glDisable (GL_DEPTH_TEST);
+  }
   for (OpenGl_SequenceOfStructure::Iterator anIter (myView->ImmediateStructures());
        anIter.More(); anIter.Next())
   {
     const OpenGl_Structure* aStructure = anIter.Value();
+    if (!aStructure->IsVisible())
+    {
+      continue;
+    }
+
     aStructure->Render (aWS);
   }
 
-  NamedStatus &= ~OPENGL_NS_IMMEDIATE;
-
-  if (isDoubleBuffer && myTransientDrawToFront)
+  if (toCopyBackToFront)
   {
-    glFlush();
     MakeBackBufCurrent();
+    return false;
   }
+  return true;
 }