0024381: Visualization, TKOpenGl - revise matrices stack and usage of temporary matrices
[occt.git] / src / OpenGl / OpenGl_Workspace.cxx
index 13fd04f..fe150d3 100644 (file)
@@ -1,25 +1,17 @@
 // Created on: 2011-09-20
 // Created by: Sergey ZERCHANINOV
-// Copyright (c) 2011-2012 OPEN CASCADE SAS
+// Copyright (c) 2011-2014 OPEN CASCADE SAS
 //
-// The content of this file is subject to the Open CASCADE Technology Public
-// License Version 6.5 (the "License"). You may not use the content of this file
-// except in compliance with the License. Please obtain a copy of the License
-// at http://www.opencascade.org and read it completely before using this file.
+// This file is part of Open CASCADE Technology software library.
 //
-// The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
-// main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
+// This library is free software; you can redistribute it and/or modify it under
+// the terms of the GNU Lesser General Public License version 2.1 as published
+// by the Free Software Foundation, with special exception defined in the file
+// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
+// distribution for complete text of the license and disclaimer of any warranty.
 //
-// The Original Code and all software distributed under the License is
-// distributed on an "AS IS" basis, without warranty of any kind, and the
-// Initial Developer hereby disclaims all such warranties, including without
-// limitation, any warranties of merchantability, fitness for a particular
-// purpose or non-infringement. Please see the License for the specific terms
-// and conditions governing the rights and limitations under the License.
-
-#ifdef HAVE_CONFIG_H
-  #include <config.h>
-#endif
+// Alternatively, this file may be used under the terms of Open CASCADE
+// commercial license or contractual agreement.
 
 #include <OpenGl_GlCore15.hxx>
 
 #include <OpenGl_AspectMarker.hxx>
 #include <OpenGl_AspectText.hxx>
 #include <OpenGl_Context.hxx>
+#include <OpenGl_Element.hxx>
 #include <OpenGl_FrameBuffer.hxx>
+#include <OpenGl_Structure.hxx>
+#include <OpenGl_Sampler.hxx>
 #include <OpenGl_Texture.hxx>
+#include <OpenGl_Utils.hxx>
 #include <OpenGl_View.hxx>
 #include <OpenGl_Workspace.hxx>
-#include <OpenGl_Element.hxx>
 
 #include <Graphic3d_TextureParams.hxx>
 
@@ -140,23 +135,33 @@ void OpenGl_Material::Init (const OPENGL_SURF_PROP& theProp)
 // function : OpenGl_Workspace
 // purpose  :
 // =======================================================================
-OpenGl_Workspace::OpenGl_Workspace (const Handle(OpenGl_Display)& theDisplay,
+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 (theDisplay, theCWindow, theGContext, theCaps, theShareCtx),
+: OpenGl_Window (theDriver, theCWindow, theGContext, theCaps, theShareCtx),
   NamedStatus (0),
   HighlightColor (&THE_WHITE_COLOR),
   //
-  myIsTransientOpen (Standard_False),
-  myRetainMode (Standard_False),
+  myComputeInitStatus (OpenGl_RT_NONE),
+  myIsRaytraceDataValid (Standard_False),
+  myIsRaytraceWarnTextures (Standard_False),
+  myViewModificationStatus (0),
+  myLayersModificationStatus (0),
+  //
+  myRaytraceFilter       (new OpenGl_RaytraceFilter()),
+  myToRedrawGL           (Standard_True),
+  myAntiAliasingMode     (3),
   myTransientDrawToFront (Standard_True),
+  myBackBufferRestored   (Standard_False),
+  myIsImmediateDrawn     (Standard_False),
   myUseTransparency (Standard_False),
   myUseZBuffer (Standard_False),
   myUseDepthTest (Standard_True),
   myUseGLLight (Standard_True),
-  myBackBufferRestored (Standard_False),
+  myIsCullingEnabled (Standard_False),
+  myFrameCounter (0),
   //
   AspectLine_set (&myDefaultAspectLine),
   AspectLine_applied (NULL),
@@ -170,13 +175,23 @@ OpenGl_Workspace::OpenGl_Workspace (const Handle(OpenGl_Display)& theDisplay,
   TextParam_applied (NULL),
   ViewMatrix_applied (&myDefaultMatrix),
   StructureMatrix_applied (&myDefaultMatrix),
+  myCullingMode (TelCullUndefined),
   myModelViewMatrix (myDefaultMatrix),
-  PolygonOffset_applied (NULL)
+  PolygonOffset_applied (THE_DEFAULT_POFFSET)
 {
-  theDisplay->InitAttributes();
+  myGlContext->core11fwd->glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
+
+  if (!myGlContext->GetResource ("OpenGl_LineAttributes", myLineAttribs))
+  {
+    // share and register for release once the resource is no longer used
+    myLineAttribs = new OpenGl_LineAttributes();
+    myGlContext->ShareResource ("OpenGl_LineAttributes", myLineAttribs);
+    myLineAttribs->Init (myGlContext);
+  }
 
   // General initialization of the context
 
+#if !defined(GL_ES_VERSION_2_0)
   // 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);
@@ -186,24 +201,15 @@ OpenGl_Workspace::OpenGl_Workspace (const Handle(OpenGl_Display)& theDisplay,
   glHint (GL_POINT_SMOOTH_HINT,   GL_FASTEST);
   glHint (GL_LINE_SMOOTH_HINT,    GL_FASTEST);
   glHint (GL_POLYGON_SMOOTH_HINT, GL_FASTEST);
-
-  // Polygon Offset
-  EnablePolygonOffset();
-
-#ifdef HAVE_OPENCL
-
-  myComputeInitStatus = OpenGl_CLIS_NONE;
-
-  myViewModificationStatus = 0;
-  myLayersModificationStatus = 0;
-
-  myRaytraceOutputTexture[0] = 0;
-  myRaytraceOutputTexture[1] = 0;
-
-  myIsRaytraceDataValid = Standard_False;
-  myToUpdateRaytraceData = Standard_False;
-
 #endif
+
+  // AA mode
+  const char* anAaEnv = ::getenv ("CALL_OPENGL_ANTIALIASING_MODE");
+  if (anAaEnv != NULL)
+  {
+    int v;
+    if (sscanf (anAaEnv, "%d", &v) > 0) myAntiAliasingMode = v;
+  }
 }
 
 // =======================================================================
@@ -223,9 +229,13 @@ Standard_Boolean OpenGl_Workspace::SetImmediateModeDrawToFront (const Standard_B
 // =======================================================================
 OpenGl_Workspace::~OpenGl_Workspace()
 {
-#ifdef HAVE_OPENCL
-  ReleaseOpenCL();
-#endif
+  if (!myLineAttribs.IsNull())
+  {
+    myLineAttribs.Nullify();
+    myGlContext->ReleaseResource ("OpenGl_LineAttributes", Standard_True);
+  }
+
+  ReleaseRaytraceResources();
 }
 
 // =======================================================================
@@ -272,7 +282,8 @@ 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);
   AspectFace(Standard_True);
@@ -291,18 +302,22 @@ Handle(OpenGl_Texture) OpenGl_Workspace::DisableTexture()
     return myTextureBound;
   }
 
+#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);
+#endif
 
   myTextureBound->Unbind (myGlContext);
   switch (myTextureBound->GetTarget())
   {
+  #if !defined(GL_ES_VERSION_2_0)
     case GL_TEXTURE_1D:
     {
+
       if (myTextureBound->GetParams()->GenMode() != GL_NONE)
       {
         glDisable (GL_TEXTURE_GEN_S);
@@ -310,8 +325,10 @@ Handle(OpenGl_Texture) OpenGl_Workspace::DisableTexture()
       glDisable (GL_TEXTURE_1D);
       break;
     }
+  #endif
     case GL_TEXTURE_2D:
     {
+    #if !defined(GL_ES_VERSION_2_0)
       if (myTextureBound->GetParams()->GenMode() != GL_NONE)
       {
         glDisable (GL_TEXTURE_GEN_S);
@@ -322,6 +339,7 @@ Handle(OpenGl_Texture) OpenGl_Workspace::DisableTexture()
         }
       }
       glDisable (GL_TEXTURE_2D);
+    #endif
       break;
     }
     default: break;
@@ -345,17 +363,19 @@ 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();
+  OpenGl_Mat4 aTextureMat;
   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);
+  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);
 
   // setup generation of texture coordinates
   switch (aParams->GenMode())
@@ -382,9 +402,10 @@ void OpenGl_Workspace::setTextureParams (Handle(OpenGl_Texture)&
     }
     case Graphic3d_TOTM_EYE:
     {
-      glMatrixMode (GL_MODELVIEW);
-      glPushMatrix();
-      glLoadIdentity();
+      myGlContext->WorldViewState.Push();
+
+      myGlContext->WorldViewState.SetIdentity();
+      myGlContext->ApplyWorldViewMatrix();
 
       glTexGeni  (GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
       glTexGenfv (GL_S, GL_EYE_PLANE,        aParams->GenPlaneS().GetData());
@@ -394,7 +415,9 @@ void OpenGl_Workspace::setTextureParams (Handle(OpenGl_Texture)&
         glTexGeni  (GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
         glTexGenfv (GL_T, GL_EYE_PLANE,        aParams->GenPlaneT().GetData());
       }
-      glPopMatrix();
+
+      myGlContext->WorldViewState.Pop();
+
       break;
     }
     case Graphic3d_TOTM_SPRITE:
@@ -417,20 +440,36 @@ void OpenGl_Workspace::setTextureParams (Handle(OpenGl_Texture)&
   {
     glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, aParams->IsModulate() ? GL_MODULATE : GL_DECAL);
   }
+#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;
@@ -450,37 +489,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;
@@ -488,6 +548,7 @@ 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)
@@ -497,20 +558,25 @@ void OpenGl_Workspace::setTextureParams (Handle(OpenGl_Texture)&
       glEnable (GL_TEXTURE_1D);
       break;
     }
+  #endif
     case GL_TEXTURE_2D:
     {
+    #if !defined(GL_ES_VERSION_2_0)
       if (aParams->GenMode() != Graphic3d_TOTM_MANUAL)
       {
         glEnable (GL_TEXTURE_GEN_S);
         glEnable (GL_TEXTURE_GEN_T);
       }
       glEnable (GL_TEXTURE_2D);
+    #endif
       break;
     }
     default: break;
   }
 
+#if !defined(GL_ES_VERSION_2_0)
   glMatrixMode (aMatrixMode); // turn back active matrix
+#endif
   theTexture->SetParams (aParams);
 }
 
@@ -538,6 +604,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;
 }
 
@@ -554,49 +629,93 @@ void OpenGl_Workspace::Redraw (const Graphic3d_CView& theCView,
     return;
   }
 
+  ++myFrameCounter;
+  myIsCullingEnabled = theCView.IsCullingEnabled;
+
   // release pending GL resources
   Handle(OpenGl_Context) aGlCtx = GetGlContext();
   aGlCtx->ReleaseDelayed();
 
-  // cache render mode state
-  GLint aRendMode = GL_RENDER;
-  glGetIntegerv (GL_RENDER_MODE,  &aRendMode);
-  aGlCtx->SetFeedback (aRendMode == GL_FEEDBACK);
+  // fetch OpenGl context state
+  aGlCtx->FetchState();
 
-  Tint toSwap = (aRendMode == GL_RENDER); // swap buffers
+  Tint toSwap = (aGlCtx->IsRender() && !aGlCtx->caps->buffersNoSwap) ? 1 : 0; // 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
   }
 
-#ifdef HAVE_OPENCL
-  if (!theCView.IsRaytracing || myComputeInitStatus == OpenGl_CLIS_FAIL)
+  myToRedrawGL = Standard_True;
+  if (theCView.RenderParams.Method == Graphic3d_RM_RAYTRACING
+   && myComputeInitStatus != OpenGl_RT_FAIL)
   {
-#endif
-    Redraw1 (theCView, theCUnderLayer, theCOverLayer, toSwap);
-    if (aFrameBuffer == NULL || !myTransientDrawToFront)
+    if (UpdateRaytraceGeometry (OpenGl_GUM_CHECK) && myIsRaytraceDataValid)
     {
-      RedrawImmediatMode();
-    }
+      myToRedrawGL = Standard_False;
 
-    theCView.WasRedrawnGL = Standard_True;
-#ifdef HAVE_OPENCL
+      // Only non-raytracable structures should be rendered in OpenGL mode.
+      Handle(OpenGl_RenderFilter) aRenderFilter = GetRenderFilter();
+      myRaytraceFilter->SetPrevRenderFilter (aRenderFilter);
+      SetRenderFilter (myRaytraceFilter);
+
+      Standard_Integer aSizeX = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeX() : myWidth;
+      Standard_Integer aSizeY = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeY() : myHeight;
+
+      if (myOpenGlFBO.IsNull())
+      {
+        myOpenGlFBO = new OpenGl_FrameBuffer();
+      }
+      if (myOpenGlFBO->GetVPSizeX() != aSizeX
+       || myOpenGlFBO->GetVPSizeY() != aSizeY)
+      {
+        myOpenGlFBO->Init (aGlCtx, 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 (aGlCtx);
+      redraw1 (theCView, anEmptyCLayer, anEmptyCLayer, 0);
+      myOpenGlFBO->UnbindBuffer (aGlCtx);
+
+      const Standard_Boolean isImmediate = !myView->ImmediateStructures().IsEmpty();
+      Raytrace (theCView, aSizeX, aSizeY, isImmediate ? 0 : toSwap,
+                theCOverLayer, theCUnderLayer, aFrameBuffer);
+
+      if (isImmediate)
+      {
+        RedrawImmediate (theCView, theCUnderLayer, theCOverLayer, Standard_True);
+      }
+
+      SetRenderFilter (aRenderFilter);
+
+      theCView.WasRedrawnGL = Standard_False;
+    }
   }
-  else
+
+  if (myToRedrawGL)
   {
-    int aSizeX = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeX() : myWidth;
-    int aSizeY = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeY() : myHeight;
+    // draw entire frame using normal OpenGL pipeline
+    if (aFrameBuffer != NULL)
+    {
+      aFrameBuffer->BindBuffer (aGlCtx);
+    }
 
-    Raytrace (theCView, aSizeX, aSizeY, toSwap);
+    const Standard_Boolean isImmediate = !myView->ImmediateStructures().IsEmpty();
+    redraw1 (theCView, theCUnderLayer, theCOverLayer, isImmediate ? 0 : toSwap);
+    if (isImmediate)
+    {
+      RedrawImmediate (theCView, theCUnderLayer, theCOverLayer, Standard_True);
+    }
 
-    theCView.WasRedrawnGL = Standard_False;
+    theCView.WasRedrawnGL = Standard_True;
   }
-#endif
 
   if (aFrameBuffer != NULL)
   {
@@ -605,7 +724,7 @@ void OpenGl_Workspace::Redraw (const Graphic3d_CView& theCView,
     glViewport (aViewPortBack[0], aViewPortBack[1], aViewPortBack[2], aViewPortBack[3]);
   }
 
-#if (defined(_WIN32) || defined(__WIN32__)) && defined(HAVE_VIDEOCAPTURE)
+#if defined(_WIN32) && defined(HAVE_VIDEOCAPTURE)
   if (OpenGl_AVIWriter_AllowWriting (theCView.DefWindow.XWindow))
   {
     GLint params[4];
@@ -624,5 +743,224 @@ void OpenGl_Workspace::Redraw (const Graphic3d_CView& theCView,
 #endif
 
   // reset render mode state
-  aGlCtx->SetFeedback (Standard_False);
+  aGlCtx->FetchState();
+}
+
+// =======================================================================
+// function : redraw1
+// purpose  :
+// =======================================================================
+void OpenGl_Workspace::redraw1 (const Graphic3d_CView& theCView,
+                                const Aspect_CLayer2d& theCUnderLayer,
+                                const Aspect_CLayer2d& theCOverLayer,
+                                const int              theToSwap)
+{
+  if (myView.IsNull())
+  {
+    return;
+  }
+
+  // request reset of material
+  NamedStatus |= OPENGL_NS_RESMAT;
+
+  GLbitfield toClear = GL_COLOR_BUFFER_BIT;
+  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
+    toClear |= GL_DEPTH_BUFFER_BIT;
+  }
+  else
+  {
+    glDisable (GL_DEPTH_TEST);
+  }
+
+  if (!ToRedrawGL())
+  {
+    // set background to black
+    glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
+    toClear |= GL_DEPTH_BUFFER_BIT; //
+  }
+  else
+  {
+    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;//
+  }
+}
+
+// =======================================================================
+// function : copyBackToFront
+// purpose  :
+// =======================================================================
+void OpenGl_Workspace::copyBackToFront()
+{
+#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();
+
+  glDrawBuffer (GL_FRONT);
+  glReadBuffer (GL_BACK);
+
+  glRasterPos2i (0, 0);
+  glCopyPixels  (0, 0, myWidth + 1, myHeight + 1, GL_COLOR);
+
+  EnableFeatures();
+
+  myGlContext->WorldViewState.Pop();
+  myGlContext->ProjectionState.Pop();
+  myGlContext->ApplyProjectionMatrix();
+  glDrawBuffer (GL_BACK);
+
+#endif
+  myIsImmediateDrawn = Standard_False;
+}
+
+// =======================================================================
+// function : DisplayCallback
+// purpose  :
+// =======================================================================
+void OpenGl_Workspace::DisplayCallback (const Graphic3d_CView& theCView,
+                                        Standard_Integer       theReason)
+{
+  if (theCView.GDisplayCB == NULL)
+  {
+    return;
+  }
+
+  Aspect_GraphicCallbackStruct aCallData;
+  aCallData.reason    = theReason;
+  aCallData.glContext = GetGlContext();
+  aCallData.wsID      = theCView.WsId;
+  aCallData.viewID    = theCView.ViewId;
+  theCView.GDisplayCB (theCView.DefWindow.XWindow, theCView.GClientData, &aCallData);
+}
+
+// =======================================================================
+// function : RedrawImmediate
+// purpose  :
+// =======================================================================
+void OpenGl_Workspace::RedrawImmediate (const Graphic3d_CView& theCView,
+                                        const Aspect_CLayer2d& theCUnderLayer,
+                                        const Aspect_CLayer2d& theCOverLayer,
+                                        const Standard_Boolean theToForce)
+{
+  if (!Activate())
+  {
+    return;
+  }
+
+  GLboolean isDoubleBuffer = GL_FALSE;
+#if !defined(GL_ES_VERSION_2_0)
+  glGetBooleanv (GL_DOUBLEBUFFER, &isDoubleBuffer);
+#endif
+  if (myView->ImmediateStructures().IsEmpty())
+  {
+    if (theToForce
+     || !myIsImmediateDrawn)
+    {
+      myIsImmediateDrawn = Standard_False;
+      return;
+    }
+
+    if (myBackBufferRestored
+     && isDoubleBuffer)
+    {
+      copyBackToFront();
+      glFlush();
+    }
+    else
+    {
+      Redraw (theCView, theCUnderLayer, theCOverLayer);
+    }
+    return;
+  }
+
+  if (isDoubleBuffer && myTransientDrawToFront)
+  {
+    if (!myBackBufferRestored)
+    {
+      Redraw (theCView, theCUnderLayer, theCOverLayer);
+      return;
+    }
+    copyBackToFront();
+    MakeFrontBufCurrent();
+  }
+  else
+  {
+    myBackBufferRestored = Standard_False;
+  }
+  myIsImmediateDrawn = Standard_True;
+
+  NamedStatus |= OPENGL_NS_IMMEDIATE;
+  ///glDisable (GL_LIGHTING);
+  glDisable (GL_DEPTH_TEST);
+
+  Handle(OpenGl_Workspace) aWS (this);
+  for (OpenGl_SequenceOfStructure::Iterator anIter (myView->ImmediateStructures());
+       anIter.More(); anIter.Next())
+  {
+    const OpenGl_Structure* aStructure = anIter.Value();
+    aStructure->Render (aWS);
+  }
+
+  NamedStatus &= ~OPENGL_NS_IMMEDIATE;
+
+  if (isDoubleBuffer && myTransientDrawToFront)
+  {
+    glFlush();
+    MakeBackBufCurrent();
+  }
 }