0024023: Revamp the OCCT Handle -- general
[occt.git] / src / OpenGl / OpenGl_Context.cxx
index fcbd347..f4f92b2 100644 (file)
 #include <OpenGl_ArbDbg.hxx>
 #include <OpenGl_ArbFBO.hxx>
 #include <OpenGl_ExtGS.hxx>
-#include <OpenGl_GlCore20.hxx>
+#include <OpenGl_ArbTexBindless.hxx>
+#include <OpenGl_GlCore44.hxx>
+#include <OpenGl_FrameBuffer.hxx>
+#include <OpenGl_Sampler.hxx>
 #include <OpenGl_ShaderManager.hxx>
 
 #include <Message_Messenger.hxx>
 
 #include <Standard_ProgramError.hxx>
 
-#if defined(_WIN32)
+#if defined(HAVE_EGL)
+  #include <EGL/egl.h>
+  #ifdef _MSC_VER
+    #pragma comment(lib, "libEGL.lib")
+  #endif
+#elif defined(_WIN32)
   //
 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
   #include <dlfcn.h>
+  #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
+    //
+  #else
+    #include <OpenGL/OpenGL.h>
+  #endif
 #else
   #include <GL/glx.h> // glXGetProcAddress()
 #endif
 
-// GL_NVX_gpu_memory_info
-#ifndef GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX
-  enum
-  {
-    GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX         = 0x9047,
-    GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX   = 0x9048,
-    GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX = 0x9049,
-    GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX           = 0x904A,
-    GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX           = 0x904B
-  };
+#ifdef HAVE_GL2PS
+  #include <gl2ps.h>
+  #ifdef _MSC_VER
+    #pragma comment (lib, "gl2ps.lib")
+  #endif
 #endif
 
-IMPLEMENT_STANDARD_HANDLE (OpenGl_Context, Standard_Transient)
-IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Context, Standard_Transient)
 
 namespace
 {
   static const Handle(OpenGl_Resource) NULL_GL_RESOURCE;
-  static const GLdouble OpenGl_DefaultPlaneEq[] = {0.0, 0.0, 0.0, 0.0};
 }
 
 // =======================================================================
@@ -75,6 +80,8 @@ OpenGl_Context::OpenGl_Context (const Handle(OpenGl_Caps)& theCaps)
   core20fwd  (NULL),
   core32     (NULL),
   core32back (NULL),
+  core33     (NULL),
+  core33back (NULL),
   core41     (NULL),
   core41back (NULL),
   core42     (NULL),
@@ -84,11 +91,24 @@ OpenGl_Context::OpenGl_Context (const Handle(OpenGl_Caps)& theCaps)
   core44     (NULL),
   core44back (NULL),
   caps   (!theCaps.IsNull() ? theCaps : new OpenGl_Caps()),
-  arbNPTW(Standard_False),
+#if defined(GL_ES_VERSION_2_0)
+  hasHighp   (Standard_False),
+  hasUintIndex(Standard_False),
+  hasTexRGBA8(Standard_False),
+#else
+  hasHighp   (Standard_True),
+  hasUintIndex(Standard_True),
+  hasTexRGBA8(Standard_True),
+#endif
+  arbNPTW  (Standard_False),
+  arbTexRG (Standard_False),
+  arbTexBindless (NULL),
   arbTBO (NULL),
+  arbTboRGB32 (Standard_False),
   arbIns (NULL),
   arbDbg (NULL),
   arbFBO (NULL),
+  arbFBOBlit (NULL),
   extGS  (NULL),
   extBgra(Standard_False),
   extAnis(Standard_False),
@@ -97,21 +117,39 @@ OpenGl_Context::OpenGl_Context (const Handle(OpenGl_Caps)& theCaps)
   nvxMem (Standard_False),
   mySharedResources (new OpenGl_ResourcesMap()),
   myDelayed         (new OpenGl_DelayReleaseMap()),
-  myReleaseQueue    (new OpenGl_ResourcesQueue()),
+  myUnusedResources (new OpenGl_ResourcesStack()),
   myClippingState (),
   myGlLibHandle (NULL),
   myFuncs (new OpenGl_GlFunctions()),
   myAnisoMax   (1),
+  myTexClamp   (GL_CLAMP_TO_EDGE),
   myMaxTexDim  (1024),
   myMaxClipPlanes (6),
   myGlVerMajor (0),
   myGlVerMinor (0),
-  myRenderMode (GL_RENDER),
   myIsInitialized (Standard_False),
   myIsStereoBuffers (Standard_False),
-  myDrawBuffer (0)
+  myIsGlNormalizeEnabled (Standard_False),
+#if !defined(GL_ES_VERSION_2_0)
+  myRenderMode (GL_RENDER),
+#else
+  myRenderMode (0),
+#endif
+  myReadBuffer (0),
+  myDrawBuffer (0),
+  myDefaultVao (0),
+  myIsGlDebugCtx (Standard_False)
 {
-#if defined(MAC_OS_X_VERSION_10_3) && !defined(MACOSX_USE_GLX)
+  // system-dependent fields
+#if defined(HAVE_EGL)
+  myDisplay  = (Aspect_Display          )EGL_NO_DISPLAY;
+  myWindow   = (Aspect_Drawable         )EGL_NO_SURFACE;
+  myGContext = (Aspect_RenderingContext )EGL_NO_CONTEXT;
+#elif defined(_WIN32)
+  myWindow   = NULL;
+  myWindowDC = NULL;
+  myGContext = NULL;
+#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
   // Vendors can not extend functionality on this system
   // and developers are limited to OpenGL support provided by Mac OS X SDK.
   // We retrieve function pointers from system library
@@ -121,8 +159,19 @@ OpenGl_Context::OpenGl_Context (const Handle(OpenGl_Caps)& theCaps)
   // Notice that GL version / extension availability checks are required
   // because function pointers may be available but not functionality itself
   // (depends on renderer).
+#if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
+  myGContext    = NULL;
+  myGlLibHandle = dlopen ("/System/Library/Frameworks/OpenGLES.framework/OpenGLES", RTLD_LAZY);
+#else
+  myGContext    = NULL;
   myGlLibHandle = dlopen ("/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL", RTLD_LAZY);
 #endif
+#else
+  myDisplay =  NULL;
+  myWindow   = 0;
+  myGContext = 0;
+#endif
+
   memset (myFuncs.operator->(), 0, sizeof(OpenGl_GlFunctions));
   myShaderManager = new OpenGl_ShaderManager (this);
 }
@@ -136,6 +185,24 @@ OpenGl_Context::~OpenGl_Context()
   // release clean up queue
   ReleaseDelayed();
 
+#if !defined(GL_ES_VERSION_2_0)
+  // release default VAO
+  if (myDefaultVao != 0
+   && IsValid()
+   && core32 != NULL)
+  {
+    core32->glDeleteVertexArrays (1, &myDefaultVao);
+  }
+  myDefaultVao = 0;
+#endif
+
+  // release default FBO
+  if (!myDefaultFbo.IsNull())
+  {
+    myDefaultFbo->Release (this);
+    myDefaultFbo.Nullify();
+  }
+
   // release shared resources if any
   if (((const Handle(Standard_Transient)& )mySharedResources)->GetRefCount() <= 1)
   {
@@ -145,6 +212,13 @@ OpenGl_Context::~OpenGl_Context()
     {
       anIter.Value()->Release (this);
     }
+
+    // release delayed resources added during deletion of shared resources
+    while (!myUnusedResources->IsEmpty())
+    {
+      myUnusedResources->First()->Release (this);
+      myUnusedResources->RemoveFirst();
+    }
   }
   else
   {
@@ -153,8 +227,15 @@ OpenGl_Context::~OpenGl_Context()
   mySharedResources.Nullify();
   myDelayed.Nullify();
 
+  // release sampler object
+  if (!myTexSampler.IsNull())
+  {
+    myTexSampler->Release (this);
+  }
+
+#if !defined(GL_ES_VERSION_2_0)
   if (arbDbg != NULL
-   && caps->contextDebug
+   && myIsGlDebugCtx
    && IsValid())
   {
     // reset callback
@@ -164,6 +245,32 @@ OpenGl_Context::~OpenGl_Context()
     {
       arbDbg->glDebugMessageCallbackARB (NULL, NULL);
     }
+    myIsGlDebugCtx = Standard_False;
+  }
+#endif
+}
+
+// =======================================================================
+// function : forcedRelease
+// purpose  :
+// =======================================================================
+void OpenGl_Context::forcedRelease()
+{
+  ReleaseDelayed();
+  for (NCollection_DataMap<TCollection_AsciiString, Handle(OpenGl_Resource)>::Iterator anIter (*mySharedResources);
+       anIter.More(); anIter.Next())
+  {
+    anIter.Value()->Release (this);
+  }
+  mySharedResources->Clear();
+  myShaderManager->clear();
+  myShaderManager->SetContext (NULL);
+
+  // release delayed resources added during deletion of shared resources
+  while (!myUnusedResources->IsEmpty())
+  {
+    myUnusedResources->First()->Release (this);
+    myUnusedResources->RemoveFirst();
   }
 }
 
@@ -194,88 +301,59 @@ Standard_Integer OpenGl_Context::MaxClipPlanes() const
   return myMaxClipPlanes;
 }
 
-// =======================================================================
-// function : SetDrawBufferLeft
-// purpose  :
-// =======================================================================
-void OpenGl_Context::SetDrawBufferLeft()
+#if !defined(GL_ES_VERSION_2_0)
+inline Standard_Integer stereoToMonoBuffer (const Standard_Integer theBuffer)
 {
-  switch (myDrawBuffer)
+  switch (theBuffer)
   {
-    case GL_BACK_RIGHT :
-    case GL_BACK :
-      glDrawBuffer (GL_BACK_LEFT);
-      myDrawBuffer = GL_BACK_LEFT;
-      break;
-
-    case GL_FRONT_RIGHT :
-    case GL_FRONT :
-      glDrawBuffer (GL_FRONT_LEFT);
-      myDrawBuffer = GL_FRONT_LEFT;
-      break;
-
-    case GL_FRONT_AND_BACK :
-    case GL_RIGHT :
-      glDrawBuffer (GL_LEFT);
-      myDrawBuffer = GL_LEFT;
-      break;
+    case GL_BACK_LEFT:
+    case GL_BACK_RIGHT:
+      return GL_BACK;
+    case GL_FRONT_LEFT:
+    case GL_FRONT_RIGHT:
+      return GL_FRONT;
+    default:
+      return theBuffer;
   }
 }
+#endif
 
 // =======================================================================
-// function : SetDrawBufferRight
+// function : SetReadBuffer
 // purpose  :
 // =======================================================================
-void OpenGl_Context::SetDrawBufferRight()
+void OpenGl_Context::SetReadBuffer (const Standard_Integer theReadBuffer)
 {
-  switch (myDrawBuffer)
+#if !defined(GL_ES_VERSION_2_0)
+  myReadBuffer = !myIsStereoBuffers ? stereoToMonoBuffer (theReadBuffer) : theReadBuffer;
+  if (myReadBuffer < GL_COLOR_ATTACHMENT0
+   && arbFBO != NULL)
   {
-    case GL_BACK_LEFT :
-    case GL_BACK :
-      glDrawBuffer (GL_BACK_RIGHT);
-      myDrawBuffer = GL_BACK_RIGHT;
-      break;
-
-    case GL_FRONT_LEFT :
-    case GL_FRONT :
-      glDrawBuffer (GL_FRONT_RIGHT);
-      myDrawBuffer = GL_FRONT_RIGHT;
-      break;
-
-    case GL_FRONT_AND_BACK :
-    case GL_LEFT :
-      glDrawBuffer (GL_RIGHT);
-      myDrawBuffer = GL_RIGHT;
-      break;
+    arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
   }
+  ::glReadBuffer (myReadBuffer);
+#else
+  (void )theReadBuffer;
+#endif
 }
 
 // =======================================================================
-// function : SetDrawBufferMono
+// function : SetDrawBuffer
 // purpose  :
 // =======================================================================
-void OpenGl_Context::SetDrawBufferMono()
+void OpenGl_Context::SetDrawBuffer (const Standard_Integer theDrawBuffer)
 {
-  switch (myDrawBuffer)
+#if !defined(GL_ES_VERSION_2_0)
+  myDrawBuffer = !myIsStereoBuffers ? stereoToMonoBuffer (theDrawBuffer) : theDrawBuffer;
+  if (myDrawBuffer < GL_COLOR_ATTACHMENT0
+   && arbFBO != NULL)
   {
-    case GL_BACK_LEFT :
-    case GL_BACK_RIGHT :
-      glDrawBuffer (GL_BACK);
-      myDrawBuffer = GL_BACK;
-      break;
-
-    case GL_FRONT_LEFT :
-    case GL_FRONT_RIGHT :
-      glDrawBuffer (GL_FRONT);
-      myDrawBuffer = GL_FRONT;
-      break;
-
-    case GL_LEFT :
-    case GL_RIGHT :
-      glDrawBuffer (GL_FRONT_AND_BACK);
-      myDrawBuffer = GL_FRONT_AND_BACK;
-      break;
+    arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
   }
+  ::glDrawBuffer (myDrawBuffer);
+#else
+  (void )theDrawBuffer;
+#endif
 }
 
 // =======================================================================
@@ -284,11 +362,17 @@ void OpenGl_Context::SetDrawBufferMono()
 // =======================================================================
 void OpenGl_Context::FetchState()
 {
+#if !defined(GL_ES_VERSION_2_0)
   // cache feedback mode state
-  glGetIntegerv (GL_RENDER_MODE, &myRenderMode);
+  if (core11 != NULL)
+  {
+    ::glGetIntegerv (GL_RENDER_MODE, &myRenderMode);
+  }
 
-  // cache draw buffer state
-  glGetIntegerv (GL_DRAW_BUFFER, &myDrawBuffer);
+  // cache buffers state
+  ::glGetIntegerv (GL_READ_BUFFER, &myReadBuffer);
+  ::glGetIntegerv (GL_DRAW_BUFFER, &myDrawBuffer);
+#endif
 }
 
 // =======================================================================
@@ -301,7 +385,7 @@ void OpenGl_Context::Share (const Handle(OpenGl_Context)& theShareCtx)
   {
     mySharedResources = theShareCtx->mySharedResources;
     myDelayed         = theShareCtx->myDelayed;
-    myReleaseQueue    = theShareCtx->myReleaseQueue;
+    myUnusedResources = theShareCtx->myUnusedResources;
     myShaderManager   = theShareCtx->myShaderManager;
   }
 }
@@ -314,7 +398,18 @@ void OpenGl_Context::Share (const Handle(OpenGl_Context)& theShareCtx)
 // =======================================================================
 Standard_Boolean OpenGl_Context::IsCurrent() const
 {
-#if defined(_WIN32)
+#if defined(HAVE_EGL)
+  if ((EGLDisplay )myDisplay  == EGL_NO_DISPLAY
+   || (EGLSurface )myWindow   == EGL_NO_SURFACE
+   || (EGLContext )myGContext == EGL_NO_CONTEXT)
+  {
+    return Standard_False;
+  }
+
+  return (((EGLDisplay )myDisplay  == eglGetCurrentDisplay())
+       && ((EGLContext )myGContext == eglGetCurrentContext())
+       && ((EGLSurface )myWindow   == eglGetCurrentSurface (EGL_DRAW)));
+#elif defined(_WIN32)
   if (myWindowDC == NULL || myGContext == NULL)
   {
     return Standard_False;
@@ -339,7 +434,24 @@ Standard_Boolean OpenGl_Context::IsCurrent() const
 // =======================================================================
 Standard_Boolean OpenGl_Context::MakeCurrent()
 {
-#if defined(_WIN32)
+#if defined(HAVE_EGL)
+  if ((EGLDisplay )myDisplay  == EGL_NO_DISPLAY
+   || (EGLSurface )myWindow   == EGL_NO_SURFACE
+   || (EGLContext )myGContext == EGL_NO_CONTEXT)
+  {
+    Standard_ProgramError_Raise_if (myIsInitialized, "OpenGl_Context::Init() should be called before!");
+    return Standard_False;
+  }
+
+  if (eglMakeCurrent ((EGLDisplay )myDisplay, (EGLSurface )myWindow, (EGLSurface )myWindow, (EGLContext )myGContext) != EGL_TRUE)
+  {
+    // if there is no current context it might be impossible to use glGetError() correctly
+    PushMessage (GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB, GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB,
+                 "eglMakeCurrent() has failed!");
+    myIsInitialized = Standard_False;
+    return Standard_False;
+  }
+#elif defined(_WIN32)
   if (myWindowDC == NULL || myGContext == NULL)
   {
     Standard_ProgramError_Raise_if (myIsInitialized, "OpenGl_Context::Init() should be called before!");
@@ -396,7 +508,12 @@ Standard_Boolean OpenGl_Context::MakeCurrent()
 // =======================================================================
 void OpenGl_Context::SwapBuffers()
 {
-#if defined(_WIN32)
+#if defined(HAVE_EGL)
+  if ((EGLSurface )myWindow != EGL_NO_SURFACE)
+  {
+    eglSwapBuffers ((EGLDisplay )myDisplay, (EGLSurface )myWindow);
+  }
+#elif defined(_WIN32)
   if ((HDC )myWindowDC != NULL)
   {
     ::SwapBuffers ((HDC )myWindowDC);
@@ -412,13 +529,57 @@ void OpenGl_Context::SwapBuffers()
 
 #endif // __APPLE__
 
+// =======================================================================
+// function : SetSwapInterval
+// purpose  :
+// =======================================================================
+Standard_Boolean OpenGl_Context::SetSwapInterval (const Standard_Integer theInterval)
+{
+#if defined(HAVE_EGL)
+  if (::eglSwapInterval ((EGLDisplay )myDisplay, theInterval) == EGL_TRUE)
+  {
+    return Standard_True;
+  }
+#elif defined(_WIN32)
+  if (myFuncs->wglSwapIntervalEXT != NULL)
+  {
+    myFuncs->wglSwapIntervalEXT (theInterval);
+    return Standard_True;
+  }
+#elif defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
+  //
+#elif defined(__APPLE__)
+  if (::CGLSetParameter (CGLGetCurrentContext(), kCGLCPSwapInterval, &theInterval) == kCGLNoError)
+  {
+    return Standard_True;
+  }
+#else
+  if (theInterval == -1
+   && myFuncs->glXSwapIntervalEXT != NULL)
+  {
+    typedef int (*glXSwapIntervalEXT_t_x)(Display* theDisplay, GLXDrawable theDrawable, int theInterval);
+    glXSwapIntervalEXT_t_x aFuncPtr = (glXSwapIntervalEXT_t_x )myFuncs->glXSwapIntervalEXT;
+    aFuncPtr ((Display* )myDisplay, (GLXDrawable )myWindow, theInterval);
+    return Standard_True;
+  }
+  else if (myFuncs->glXSwapIntervalSGI != NULL)
+  {
+    myFuncs->glXSwapIntervalSGI (theInterval);
+    return Standard_True;
+  }
+#endif
+  return Standard_False;
+}
+
 // =======================================================================
 // function : findProc
 // purpose  :
 // =======================================================================
 void* OpenGl_Context::findProc (const char* theFuncName)
 {
-#if defined(_WIN32)
+#if defined(HAVE_EGL)
+  return (void* )eglGetProcAddress (theFuncName);
+#elif defined(_WIN32)
   return wglGetProcAddress (theFuncName);
 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
   return (myGlLibHandle != NULL) ? dlsym (myGlLibHandle, theFuncName) : NULL;
@@ -435,27 +596,34 @@ Standard_Boolean OpenGl_Context::CheckExtension (const char* theExtName) const
 {
   if (theExtName  == NULL)
   {
+#ifdef OCCT_DEBUG
     std::cerr << "CheckExtension called with NULL string!\n";
+#endif
     return Standard_False;
   }
 
+#if !defined(GL_ES_VERSION_2_0)
   // available since OpenGL 3.0
   // and the ONLY way to check extensions with OpenGL 3.1+ core profile
-  /**if (IsGlGreaterEqual (3, 0))
+  if (IsGlGreaterEqual (3, 0)
+   && myFuncs->glGetStringi != NULL)
   {
     GLint anExtNb = 0;
-    glGetIntegerv (GL_NUM_EXTENSIONS, &anExtNb);
+    ::glGetIntegerv (GL_NUM_EXTENSIONS, &anExtNb);
+    const size_t anExtNameLen = strlen (theExtName);
     for (GLint anIter = 0; anIter < anExtNb; ++anIter)
     {
-      const char* anExtension = (const char* )core30->glGetStringi (GL_EXTENSIONS, (GLuint )anIter);
-      if (anExtension[anExtNameLen] == '\0' &&
-          strncmp (anExtension, theExtName, anExtNameLen) == 0)
+      const char* anExtension = (const char* )myFuncs->glGetStringi (GL_EXTENSIONS, (GLuint )anIter);
+      const size_t aTestExtNameLen = strlen (anExtension);
+      if (aTestExtNameLen == anExtNameLen
+       && strncmp (anExtension, theExtName, anExtNameLen) == 0)
       {
         return Standard_True;
       }
     }
     return Standard_False;
-  }*/
+  }
+#endif
 
   // use old way with huge string for all extensions
   const char* anExtString = (const char* )glGetString (GL_EXTENSIONS);
@@ -502,14 +670,18 @@ Standard_Boolean OpenGl_Context::CheckExtension (const char* theExtString,
 // function : Init
 // purpose  :
 // =======================================================================
-Standard_Boolean OpenGl_Context::Init()
+Standard_Boolean OpenGl_Context::Init (const Standard_Boolean theIsCoreProfile)
 {
   if (myIsInitialized)
   {
     return Standard_True;
   }
 
-#if defined(_WIN32)
+#if defined(HAVE_EGL)
+  myDisplay  = (Aspect_Display )eglGetCurrentDisplay();
+  myGContext = (Aspect_RenderingContext )eglGetCurrentContext();
+  myWindow   = (Aspect_Drawable )eglGetCurrentSurface(EGL_DRAW);
+#elif defined(_WIN32)
   myWindowDC = (Aspect_Handle )wglGetCurrentDC();
   myGContext = (Aspect_RenderingContext )wglGetCurrentContext();
 #else
@@ -522,7 +694,7 @@ Standard_Boolean OpenGl_Context::Init()
     return Standard_False;
   }
 
-  init();
+  init (theIsCoreProfile);
   myIsInitialized = Standard_True;
   return Standard_True;
 }
@@ -533,25 +705,44 @@ Standard_Boolean OpenGl_Context::Init()
 // function : Init
 // purpose  :
 // =======================================================================
-#if defined(_WIN32)
+#if defined(HAVE_EGL)
+Standard_Boolean OpenGl_Context::Init (const Aspect_Drawable         theEglSurface,
+                                       const Aspect_Display          theEglDisplay,
+                                       const Aspect_RenderingContext theEglContext,
+                                       const Standard_Boolean        theIsCoreProfile)
+#elif defined(_WIN32)
 Standard_Boolean OpenGl_Context::Init (const Aspect_Handle           theWindow,
                                        const Aspect_Handle           theWindowDC,
-                                       const Aspect_RenderingContext theGContext)
+                                       const Aspect_RenderingContext theGContext,
+                                       const Standard_Boolean        theIsCoreProfile)
 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
-Standard_Boolean OpenGl_Context::Init (const void*                   theGContext)
+
+#if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
+Standard_Boolean OpenGl_Context::Init (EAGLContext*                  theGContext,
+                                       const Standard_Boolean        theIsCoreProfile)
+#else
+Standard_Boolean OpenGl_Context::Init (NSOpenGLContext*              theGContext,
+                                       const Standard_Boolean        theIsCoreProfile)
+#endif
+
 #else
 Standard_Boolean OpenGl_Context::Init (const Aspect_Drawable         theWindow,
                                        const Aspect_Display          theDisplay,
-                                       const Aspect_RenderingContext theGContext)
+                                       const Aspect_RenderingContext theGContext,
+                                       const Standard_Boolean        theIsCoreProfile)
 #endif
 {
   Standard_ProgramError_Raise_if (myIsInitialized, "OpenGl_Context::Init() should be called only once!");
-#if defined(_WIN32)
+#if defined(HAVE_EGL)
+  myWindow   = theEglSurface;
+  myGContext = theEglContext;
+  myDisplay  = theEglDisplay;
+#elif defined(_WIN32)
   myWindow   = theWindow;
   myGContext = theGContext;
   myWindowDC = theWindowDC;
 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
-  myGContext = (void* )theGContext;
+  myGContext = theGContext;
 #else
   myWindow   = theWindow;
   myGContext = theGContext;
@@ -562,7 +753,7 @@ Standard_Boolean OpenGl_Context::Init (const Aspect_Drawable         theWindow,
     return Standard_False;
   }
 
-  init();
+  init (theIsCoreProfile);
   myIsInitialized = Standard_True;
   return Standard_True;
 }
@@ -580,34 +771,44 @@ void OpenGl_Context::ResetErrors()
 }
 
 // =======================================================================
-// function : readGlVersion
+// function : ReadGlVersion
 // purpose  :
 // =======================================================================
-void OpenGl_Context::readGlVersion()
+void OpenGl_Context::ReadGlVersion (Standard_Integer& theGlVerMajor,
+                                    Standard_Integer& theGlVerMinor)
 {
   // reset values
-  myGlVerMajor = 0;
-  myGlVerMinor = 0;
+  theGlVerMajor = 0;
+  theGlVerMinor = 0;
 
-  // available since OpenGL 3.0
+#ifdef GL_MAJOR_VERSION
+  // available since OpenGL 3.0 and OpenGL 3.0 ES
   GLint aMajor = 0, aMinor = 0;
   glGetIntegerv (GL_MAJOR_VERSION, &aMajor);
   glGetIntegerv (GL_MINOR_VERSION, &aMinor);
   // glGetError() sometimes does not report an error here even if
   // GL does not know GL_MAJOR_VERSION and GL_MINOR_VERSION constants.
-  // This happens on some rendereres like e.g. Cygwin MESA.
+  // This happens on some renderers like e.g. Cygwin MESA.
   // Thus checking additionally if GL has put anything to
   // the output variables.
-  if (glGetError() == GL_NO_ERROR && aMajor != 0 && aMinor != 0)
+  if (::glGetError() == GL_NO_ERROR && aMajor != 0 && aMinor != 0)
   {
-    myGlVerMajor = aMajor;
-    myGlVerMinor = aMinor;
+    theGlVerMajor = aMajor;
+    theGlVerMinor = aMinor;
     return;
   }
-  ResetErrors();
+  for (GLenum anErr = ::glGetError(), aPrevErr = GL_NO_ERROR;; aPrevErr = anErr, anErr = ::glGetError())
+  {
+    if (anErr == GL_NO_ERROR
+     || anErr == aPrevErr)
+    {
+      break;
+    }
+  }
+#endif
 
   // Read version string.
-  // Notice that only first two numbers splitted by point '2.1 XXXXX' are significant.
+  // Notice that only first two numbers split by point '2.1 XXXXX' are significant.
   // Following trash (after space) is vendor-specific.
   // New drivers also returns micro version of GL like '3.3.0' which has no meaning
   // and should be considered as vendor-specific too.
@@ -618,6 +819,17 @@ void OpenGl_Context::readGlVersion()
     return;
   }
 
+//#if defined(GL_ES_VERSION_2_0)
+  // skip "OpenGL ES-** " section
+  for (; *aVerStr != '\0'; ++aVerStr)
+  {
+    if (*aVerStr >= '0' && *aVerStr <= '9')
+    {
+      break;
+    }
+  }
+//#endif
+
   // parse string for major number
   char aMajorStr[32];
   char aMinorStr[32];
@@ -648,13 +860,13 @@ void OpenGl_Context::readGlVersion()
   aMinorStr[aMinIter] = '\0';
 
   // read numbers
-  myGlVerMajor = atoi (aMajorStr);
-  myGlVerMinor = atoi (aMinorStr);
+  theGlVerMajor = atoi (aMajorStr);
+  theGlVerMinor = atoi (aMinorStr);
 
-  if (myGlVerMajor <= 0)
+  if (theGlVerMajor <= 0)
   {
-    myGlVerMajor = 0;
-    myGlVerMinor = 0;
+    theGlVerMajor = 0;
+    theGlVerMinor = 0;
   }
 }
 
@@ -683,6 +895,7 @@ static Standard_CString THE_DBGMSG_SEV_HIGH   = "High";   // GL_DEBUG_SEVERITY_H
 static Standard_CString THE_DBGMSG_SEV_MEDIUM = "Medium"; // GL_DEBUG_SEVERITY_MEDIUM_ARB
 static Standard_CString THE_DBGMSG_SEV_LOW    = "Low";    // GL_DEBUG_SEVERITY_LOW_ARB
 
+#if !defined(GL_ES_VERSION_2_0)
 //! Callback for GL_ARB_debug_output extension
 static void APIENTRY debugCallbackWrap(unsigned int theSource,
                                        unsigned int theType,
@@ -695,6 +908,7 @@ static void APIENTRY debugCallbackWrap(unsigned int theSource,
   OpenGl_Context* aCtx = (OpenGl_Context* )theUserParam;
   aCtx->PushMessage (theSource, theType, theId, theSeverity, theMessage);
 }
+#endif
 
 // =======================================================================
 // function : PushMessage
@@ -706,7 +920,14 @@ void OpenGl_Context::PushMessage (const unsigned int theSource,
                                   const unsigned int theSeverity,
                                   const TCollection_ExtendedString& theMessage)
 {
-  //OpenGl_Context* aCtx = (OpenGl_Context* )theUserParam;
+  if (caps->suppressExtraMsg
+   && theSource >= GL_DEBUG_SOURCE_API_ARB
+   && theSource <= GL_DEBUG_SOURCE_OTHER_ARB
+   && myFilters[theSource - GL_DEBUG_SOURCE_API_ARB].Contains (theId))
+  {
+    return;
+  }
+
   Standard_CString& aSrc = (theSource >= GL_DEBUG_SOURCE_API_ARB
                         && theSource <= GL_DEBUG_SOURCE_OTHER_ARB)
                          ? THE_DBGMSG_SOURCES[theSource - GL_DEBUG_SOURCE_API_ARB]
@@ -733,20 +954,106 @@ void OpenGl_Context::PushMessage (const unsigned int theSource,
   aMsg += " | Severity: ";    aMsg += aSev;
   aMsg += " | Message:\n  ";
   aMsg += theMessage;
-
   Messenger()->Send (aMsg, aGrav);
 }
 
+// =======================================================================
+// function : ExcludeMessage
+// purpose  :
+// ======================================================================
+Standard_Boolean OpenGl_Context::ExcludeMessage (const unsigned int theSource,
+                                                 const unsigned int theId)
+{
+  return theSource >= GL_DEBUG_SOURCE_API_ARB
+      && theSource <= GL_DEBUG_SOURCE_OTHER_ARB
+      && myFilters[theSource - GL_DEBUG_SOURCE_API_ARB].Add (theId);
+}
+
+// =======================================================================
+// function : IncludeMessage
+// purpose  :
+// ======================================================================
+Standard_Boolean OpenGl_Context::IncludeMessage (const unsigned int theSource,
+                                                 const unsigned int theId)
+{
+  return theSource >= GL_DEBUG_SOURCE_API_ARB
+      && theSource <= GL_DEBUG_SOURCE_OTHER_ARB
+      && myFilters[theSource - GL_DEBUG_SOURCE_API_ARB].Remove (theId);
+}
+
+// =======================================================================
+// function : checkWrongVersion
+// purpose  :
+// ======================================================================
+void OpenGl_Context::checkWrongVersion (const Standard_Integer theGlVerMajor,
+                                        const Standard_Integer theGlVerMinor)
+{
+  if (!IsGlGreaterEqual (theGlVerMajor, theGlVerMinor))
+  {
+    return;
+  }
+
+  TCollection_ExtendedString aMsg = TCollection_ExtendedString()
+    + "Error! OpenGL context reports version "
+    + myGlVerMajor  + "." + myGlVerMinor
+    + " but does not export required functions for "
+    + theGlVerMajor + "." + theGlVerMinor;
+  PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
+               GL_DEBUG_TYPE_ERROR_ARB,
+               0,
+               GL_DEBUG_SEVERITY_HIGH_ARB,
+               aMsg);
+}
+
 // =======================================================================
 // function : init
 // purpose  :
 // =======================================================================
-void OpenGl_Context::init()
+void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
 {
   // read version
-  readGlVersion();
+  myGlVerMajor = 0;
+  myGlVerMinor = 0;
+  ReadGlVersion (myGlVerMajor, myGlVerMinor);
+  myVendor = (const char* )::glGetString (GL_VENDOR);
+
+#if defined(GL_ES_VERSION_2_0)
+  (void )theIsCoreProfile;
+  const bool isCoreProfile = false;
+#else
+
+  if (myVendor.Search ("NVIDIA") != -1)
+  {
+    // Buffer detailed info: Buffer object 1 (bound to GL_ARRAY_BUFFER_ARB, usage hint is GL_STATIC_DRAW)
+    // will use VIDEO memory as the source for buffer object operations.
+    ExcludeMessage (GL_DEBUG_SOURCE_API_ARB, 131185);
+  }
+  if (IsGlGreaterEqual (3, 0))
+  {
+    // retrieve auxiliary function in advance
+    FindProc ("glGetStringi", myFuncs->glGetStringi);
+  }
 
-  core11     = (OpenGl_GlCore11*    )(&(*myFuncs));
+  bool isCoreProfile = false;
+  if (IsGlGreaterEqual (3, 2))
+  {
+    isCoreProfile = (theIsCoreProfile == Standard_True);
+
+    // detect Core profile
+    if (isCoreProfile)
+    {
+      GLint aProfile = 0;
+      ::glGetIntegerv (GL_CONTEXT_PROFILE_MASK, &aProfile);
+      isCoreProfile = (aProfile & GL_CONTEXT_CORE_PROFILE_BIT) != 0;
+    }
+  }
+#endif
+
+  core11     = NULL;
+  if (!isCoreProfile)
+  {
+    core11 = (OpenGl_GlCore11* )(&(*myFuncs));
+  }
   core11fwd  = (OpenGl_GlCore11Fwd* )(&(*myFuncs));
   core15     = NULL;
   core15fwd  = NULL;
@@ -754,6 +1061,8 @@ void OpenGl_Context::init()
   core20fwd  = NULL;
   core32     = NULL;
   core32back = NULL;
+  core33     = NULL;
+  core33back = NULL;
   core41     = NULL;
   core41back = NULL;
   core42     = NULL;
@@ -763,11 +1072,60 @@ void OpenGl_Context::init()
   core44     = NULL;
   core44back = NULL;
   arbTBO     = NULL;
+  arbTboRGB32 = Standard_False;
   arbIns     = NULL;
   arbDbg     = NULL;
   arbFBO     = NULL;
+  arbFBOBlit = NULL;
   extGS      = NULL;
+  myDefaultVao = 0;
+
+#if defined(GL_ES_VERSION_2_0)
+
+  hasTexRGBA8 = IsGlGreaterEqual (3, 0)
+             || CheckExtension ("GL_OES_rgb8_rgba8");
+  // NPOT textures has limited support within OpenGL ES 2.0
+  // which are relaxed by OpenGL ES 3.0 or some extensions
+  //arbNPTW     = IsGlGreaterEqual (3, 0)
+  //           || CheckExtension ("GL_OES_texture_npot")
+  //           || CheckExtension ("GL_NV_texture_npot_2D_mipmap");
+  arbNPTW     = Standard_True;
+  arbTexRG    = IsGlGreaterEqual (3, 0)
+             || CheckExtension ("GL_EXT_texture_rg");
+  extBgra     = CheckExtension ("GL_EXT_texture_format_BGRA8888");
+  extAnis = CheckExtension ("GL_EXT_texture_filter_anisotropic");
+  extPDS  = CheckExtension ("GL_OES_packed_depth_stencil");
 
+  core11fwd = (OpenGl_GlCore11Fwd* )(&(*myFuncs));
+  if (IsGlGreaterEqual (2, 0))
+  {
+    // enable compatible functions
+    core20    = (OpenGl_GlCore20*    )(&(*myFuncs));
+    core20fwd = (OpenGl_GlCore20Fwd* )(&(*myFuncs));
+    core15fwd = (OpenGl_GlCore15Fwd* )(&(*myFuncs));
+    arbFBO    = (OpenGl_ArbFBO*      )(&(*myFuncs));
+  }
+  if (IsGlGreaterEqual (3, 0)
+   && FindProc ("glBlitFramebuffer", myFuncs->glBlitFramebuffer))
+  {
+    arbFBOBlit = (OpenGl_ArbFBOBlit* )(&(*myFuncs));
+  }
+
+  hasUintIndex = IsGlGreaterEqual (3, 0)
+              || CheckExtension ("GL_OES_element_index_uint");
+  hasHighp     = CheckExtension ("GL_OES_fragment_precision_high");
+  GLint aRange[2] = {0, 0};
+  GLint aPrec     = 0;
+  ::glGetShaderPrecisionFormat (GL_FRAGMENT_SHADER, GL_HIGH_FLOAT, aRange, &aPrec);
+  if (aPrec != 0)
+  {
+    hasHighp = Standard_True;
+  }
+#else
+
+  myTexClamp = IsGlGreaterEqual (1, 2) ? GL_CLAMP_TO_EDGE : GL_CLAMP;
+
+  hasTexRGBA8 = Standard_True;
   arbNPTW = CheckExtension ("GL_ARB_texture_non_power_of_two");
   extBgra = CheckExtension ("GL_EXT_bgra");
   extAnis = CheckExtension ("GL_EXT_texture_filter_anisotropic");
@@ -775,14 +1133,16 @@ void OpenGl_Context::init()
   atiMem  = CheckExtension ("GL_ATI_meminfo");
   nvxMem  = CheckExtension ("GL_NVX_gpu_memory_info");
 
-  // get number of maximum clipping planes
-  glGetIntegerv (GL_MAX_CLIP_PLANES, &myMaxClipPlanes);
-  glGetIntegerv (GL_MAX_TEXTURE_SIZE, &myMaxTexDim);
-
-  GLint aStereo;
+  GLint aStereo = GL_FALSE;
   glGetIntegerv (GL_STEREO, &aStereo);
   myIsStereoBuffers = aStereo == 1;
 
+  // get number of maximum clipping planes
+  glGetIntegerv (GL_MAX_CLIP_PLANES,  &myMaxClipPlanes);
+#endif
+
+  glGetIntegerv (GL_MAX_TEXTURE_SIZE, &myMaxTexDim);
+
   if (extAnis)
   {
     glGetIntegerv (GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &myAnisoMax);
@@ -790,6 +1150,8 @@ void OpenGl_Context::init()
 
   myClippingState.Init (myMaxClipPlanes);
 
+#if !defined(GL_ES_VERSION_2_0)
+
   bool has12 = false;
   bool has13 = false;
   bool has14 = false;
@@ -809,8 +1171,10 @@ void OpenGl_Context::init()
   //! Make record shorter to retrieve function pointer using variable with same name
   #define FindProcShort(theFunc) FindProc(#theFunc, myFuncs->theFunc)
 
-    // retrieve platform-dependent extensions
-#ifdef _WIN32
+  // retrieve platform-dependent extensions
+#if defined(HAVE_EGL)
+  //
+#elif defined(_WIN32)
   if (FindProcShort (wglGetExtensionsStringARB))
   {
     const char* aWglExts = myFuncs->wglGetExtensionsStringARB (wglGetCurrentDC());
@@ -838,6 +1202,19 @@ void OpenGl_Context::init()
       FindProcShort (wglDXUnlockObjectsNV);
     }
   }
+#elif defined(__APPLE__)
+    //
+#else
+    const char* aGlxExts = ::glXQueryExtensionsString ((Display* )myDisplay, DefaultScreen ((Display* )myDisplay));
+    if (CheckExtension (aGlxExts, "GLX_EXT_swap_control"))
+    {
+      FindProcShort (glXSwapIntervalEXT);
+    }
+    if (CheckExtension (aGlxExts, "GLX_SGI_swap_control"))
+    {
+      FindProcShort (glXSwapIntervalSGI);
+    }
+    //extSwapTear = CheckExtension (aGlxExts, "GLX_EXT_swap_control_tear");
 #endif
 
   // initialize debug context extension
@@ -855,10 +1232,12 @@ void OpenGl_Context::init()
      && caps->contextDebug)
     {
       // setup default callback
+      myIsGlDebugCtx = Standard_True;
       arbDbg->glDebugMessageCallbackARB (debugCallbackWrap, this);
-    #ifdef DEB
-      glEnable (GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
-    #endif
+      if (caps->contextSyncDebug)
+      {
+        ::glEnable (GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
+      }
     }
   }
 
@@ -881,7 +1260,11 @@ void OpenGl_Context::init()
        && FindProcShort (glCompressedTexSubImage3D)
        && FindProcShort (glCompressedTexSubImage2D)
        && FindProcShort (glCompressedTexSubImage1D)
-       && FindProcShort (glGetCompressedTexImage)
+       && FindProcShort (glGetCompressedTexImage);
+
+  if (!isCoreProfile)
+  {
+    has13 = has13
        && FindProcShort (glClientActiveTexture)
        && FindProcShort (glMultiTexCoord1d)
        && FindProcShort (glMultiTexCoord1dv)
@@ -919,6 +1302,7 @@ void OpenGl_Context::init()
        && FindProcShort (glLoadTransposeMatrixd)
        && FindProcShort (glMultTransposeMatrixf)
        && FindProcShort (glMultTransposeMatrixd);
+  }
 
   // load OpenGL 1.4 new functions
   has14 = IsGlGreaterEqual (1, 4)
@@ -1514,10 +1898,7 @@ void OpenGl_Context::init()
   const bool hasTextureStorage = (IsGlGreaterEqual (4, 2) || CheckExtension ("GL_ARB_texture_storage"))
        && FindProcShort (glTexStorage1D)
        && FindProcShort (glTexStorage2D)
-       && FindProcShort (glTexStorage3D)
-       && FindProcShort (glTextureStorage1DEXT)
-       && FindProcShort (glTextureStorage2DEXT)
-       && FindProcShort (glTextureStorage3DEXT);
+       && FindProcShort (glTexStorage3D);
 
   has42 = IsGlGreaterEqual (4, 2)
        && hasBaseInstance
@@ -1594,6 +1975,7 @@ void OpenGl_Context::init()
   {
     arbTBO = (OpenGl_ArbTBO* )(&(*myFuncs));
   }
+  arbTboRGB32 = CheckExtension ("GL_ARB_texture_buffer_object_rgb32");
 
   // initialize hardware instancing extension (ARB)
   if (!has31
@@ -1607,7 +1989,8 @@ void OpenGl_Context::init()
   // initialize FBO extension (ARB)
   if (hasFBO)
   {
-    arbFBO = (OpenGl_ArbFBO* )(&(*myFuncs));
+    arbFBO     = (OpenGl_ArbFBO*     )(&(*myFuncs));
+    arbFBOBlit = (OpenGl_ArbFBOBlit* )(&(*myFuncs));
     extPDS = Standard_True; // extension for EXT, but part of ARB
   }
 
@@ -1618,45 +2001,98 @@ void OpenGl_Context::init()
     extGS = (OpenGl_ExtGS* )(&(*myFuncs));
   }
 
+  // initialize bindless texture extension (ARB)
+  if (CheckExtension ("GL_ARB_bindless_texture")
+   && FindProcShort (glGetTextureHandleARB)
+   && FindProcShort (glGetTextureSamplerHandleARB)
+   && FindProcShort (glMakeTextureHandleResidentARB)
+   && FindProcShort (glMakeTextureHandleNonResidentARB)
+   && FindProcShort (glGetImageHandleARB)
+   && FindProcShort (glMakeImageHandleResidentARB)
+   && FindProcShort (glMakeImageHandleNonResidentARB)
+   && FindProcShort (glUniformHandleui64ARB)
+   && FindProcShort (glUniformHandleui64vARB)
+   && FindProcShort (glProgramUniformHandleui64ARB)
+   && FindProcShort (glProgramUniformHandleui64vARB)
+   && FindProcShort (glIsTextureHandleResidentARB)
+   && FindProcShort (glIsImageHandleResidentARB)
+   && FindProcShort (glVertexAttribL1ui64ARB)
+   && FindProcShort (glVertexAttribL1ui64vARB)
+   && FindProcShort (glGetVertexAttribLui64vARB))
+  {
+    arbTexBindless = (OpenGl_ArbTexBindless* )(&(*myFuncs));
+  }
+
   if (!has12)
   {
+    checkWrongVersion (1, 2);
     myGlVerMajor = 1;
     myGlVerMinor = 1;
     return;
   }
   else if (!has13)
   {
+    checkWrongVersion (1, 3);
     myGlVerMajor = 1;
     myGlVerMinor = 2;
     return;
   }
   else if (!has14)
   {
+    checkWrongVersion (1, 4);
     myGlVerMajor = 1;
     myGlVerMinor = 3;
     return;
   }
   else if (!has15)
   {
+    checkWrongVersion (1, 5);
     myGlVerMajor = 1;
     myGlVerMinor = 4;
     return;
   }
-  core15    = (OpenGl_GlCore15*    )(&(*myFuncs));
+  if (!isCoreProfile)
+  {
+    core15 = (OpenGl_GlCore15* )(&(*myFuncs));
+  }
   core15fwd = (OpenGl_GlCore15Fwd* )(&(*myFuncs));
 
   if (!has20)
   {
+    checkWrongVersion (2, 0);
+    myGlVerMajor = 1;
+    myGlVerMinor = 5;
+    return;
+  }
+
+  const char* aGlslVer = (const char* )::glGetString (GL_SHADING_LANGUAGE_VERSION);
+  if (aGlslVer == NULL
+  || *aGlslVer == '\0')
+  {
+    // broken context has been detected
+    TCollection_ExtendedString aMsg = TCollection_ExtendedString()
+      + "Error! OpenGL context reports version "
+      + myGlVerMajor  + "." + myGlVerMinor
+      + " but reports wrong GLSL version";
+    PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
+                 GL_DEBUG_TYPE_ERROR_ARB,
+                 0,
+                 GL_DEBUG_SEVERITY_HIGH_ARB,
+                 aMsg);
     myGlVerMajor = 1;
     myGlVerMinor = 5;
     return;
   }
 
-  core20    = (OpenGl_GlCore20*    )(&(*myFuncs));
+  if (!isCoreProfile)
+  {
+    core20  = (OpenGl_GlCore20*    )(&(*myFuncs));
+  }
   core20fwd = (OpenGl_GlCore20Fwd* )(&(*myFuncs));
 
   if (!has21)
   {
+    checkWrongVersion (2, 1);
     myGlVerMajor = 2;
     myGlVerMinor = 0;
     return;
@@ -1664,6 +2100,7 @@ void OpenGl_Context::init()
 
   if (!has30)
   {
+    checkWrongVersion (3, 0);
     myGlVerMajor = 2;
     myGlVerMinor = 1;
     return;
@@ -1671,6 +2108,7 @@ void OpenGl_Context::init()
 
   if (!has31)
   {
+    checkWrongVersion (3, 1);
     myGlVerMajor = 3;
     myGlVerMinor = 0;
     return;
@@ -1680,62 +2118,99 @@ void OpenGl_Context::init()
 
   if (!has32)
   {
+    checkWrongVersion (3, 2);
     myGlVerMajor = 3;
     myGlVerMinor = 1;
     return;
   }
-  core32     = (OpenGl_GlCore32*     )(&(*myFuncs));
-  core32back = (OpenGl_GlCore32Back* )(&(*myFuncs));
+  core32 = (OpenGl_GlCore32* )(&(*myFuncs));
+  if (isCoreProfile)
+  {
+    core32->glGenVertexArrays (1, &myDefaultVao);
+  }
+  else
+  {
+    core32back = (OpenGl_GlCore32Back* )(&(*myFuncs));
+  }
 
   if (!has33)
   {
+    checkWrongVersion (3, 3);
     myGlVerMajor = 3;
     myGlVerMinor = 2;
     return;
   }
+  core33 = (OpenGl_GlCore33* )(&(*myFuncs));
+  if (!isCoreProfile)
+  {
+    core33back = (OpenGl_GlCore33Back* )(&(*myFuncs));
+  }
+
+  // initialize sampler object
+  myTexSampler = new OpenGl_Sampler();
+  myTexSampler->Init (*this);
 
   if (!has40)
   {
+    checkWrongVersion (4, 0);
     myGlVerMajor = 3;
     myGlVerMinor = 3;
     return;
   }
+  arbTboRGB32 = Standard_True; // in core since OpenGL 4.0
 
   if (!has41)
   {
+    checkWrongVersion (4, 1);
     myGlVerMajor = 4;
     myGlVerMinor = 0;
     return;
   }
-  core41     = (OpenGl_GlCore41*     )(&(*myFuncs));
-  core41back = (OpenGl_GlCore41Back* )(&(*myFuncs));
+  core41 = (OpenGl_GlCore41* )(&(*myFuncs));
+  if (!isCoreProfile)
+  {
+    core41back = (OpenGl_GlCore41Back* )(&(*myFuncs));
+  }
 
   if(!has42)
   {
+    checkWrongVersion (4, 2);
     myGlVerMajor = 4;
     myGlVerMinor = 1;
     return;
   }
-  core42     = (OpenGl_GlCore42*     )(&(*myFuncs));
-  core42back = (OpenGl_GlCore42Back* )(&(*myFuncs));
+  core42 = (OpenGl_GlCore42* )(&(*myFuncs));
+  if (!isCoreProfile)
+  {
+    core42back = (OpenGl_GlCore42Back* )(&(*myFuncs));
+  }
 
-  if(!has43)
+  if (!has43)
   {
+    checkWrongVersion (4, 3);
     myGlVerMajor = 4;
     myGlVerMinor = 2;
     return;
   }
-  core43     = (OpenGl_GlCore43*     )(&(*myFuncs));
-  core43back = (OpenGl_GlCore43Back* )(&(*myFuncs));
+  core43 = (OpenGl_GlCore43* )(&(*myFuncs));
+  if (!isCoreProfile)
+  {
+    core43back = (OpenGl_GlCore43Back* )(&(*myFuncs));
+  }
 
   if (!has44)
   {
+    checkWrongVersion (4, 4);
     myGlVerMajor = 4;
     myGlVerMinor = 3;
     return;
   }
-  core44     = (OpenGl_GlCore44*     )(&(*myFuncs));
-  core44back = (OpenGl_GlCore44Back* )(&(*myFuncs));
+  core44 = (OpenGl_GlCore44* )(&(*myFuncs));
+  if (!isCoreProfile)
+  {
+    core44back = (OpenGl_GlCore44Back* )(&(*myFuncs));
+  }
+#endif
 }
 
 // =======================================================================
@@ -1744,6 +2219,7 @@ void OpenGl_Context::init()
 // =======================================================================
 Standard_Size OpenGl_Context::AvailableMemory() const
 {
+#if !defined(GL_ES_VERSION_2_0)
   if (atiMem)
   {
     // this is actually information for VBO pool
@@ -1762,6 +2238,7 @@ Standard_Size OpenGl_Context::AvailableMemory() const
     glGetIntegerv (GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &aMemInfo);
     return Standard_Size(aMemInfo) * 1024;
   }
+#endif
   return 0;
 }
 
@@ -1772,6 +2249,7 @@ Standard_Size OpenGl_Context::AvailableMemory() const
 TCollection_AsciiString OpenGl_Context::MemoryInfo() const
 {
   TCollection_AsciiString anInfo;
+#if !defined(GL_ES_VERSION_2_0)
   if (atiMem)
   {
     GLint aValues[4];
@@ -1809,6 +2287,7 @@ TCollection_AsciiString OpenGl_Context::MemoryInfo() const
       anInfo += TCollection_AsciiString ("  Total memory:       ") + (aValue / 1024) + " MiB\n";
     }
   }
+#endif
   return anInfo;
 }
 
@@ -1870,7 +2349,7 @@ void OpenGl_Context::ReleaseResource (const TCollection_AsciiString& theKey,
 // =======================================================================
 void OpenGl_Context::DelayedRelease (Handle(OpenGl_Resource)& theResource)
 {
-  myReleaseQueue->Push (theResource);
+  myUnusedResources->Prepend (theResource);
   theResource.Nullify();
 }
 
@@ -1881,10 +2360,10 @@ void OpenGl_Context::DelayedRelease (Handle(OpenGl_Resource)& theResource)
 void OpenGl_Context::ReleaseDelayed()
 {
   // release queued elements
-  while (!myReleaseQueue->IsEmpty())
+  while (!myUnusedResources->IsEmpty())
   {
-    myReleaseQueue->Front()->Release (this);
-    myReleaseQueue->Pop();
+    myUnusedResources->First()->Release (this);
+    myUnusedResources->RemoveFirst();
   }
 
   // release delayed shared resources
@@ -1925,3 +2404,310 @@ void OpenGl_Context::ReleaseDelayed()
     myDelayed->UnBind (aDeadList.Value (anIter));
   }
 }
+
+// =======================================================================
+// function : BindProgram
+// purpose  :
+// =======================================================================
+Standard_Boolean OpenGl_Context::BindProgram (const Handle(OpenGl_ShaderProgram)& theProgram)
+{
+  if (core20fwd == NULL)
+  {
+    return Standard_False;
+  }
+
+  if (theProgram.IsNull()
+  || !theProgram->IsValid())
+  {
+    if (!myActiveProgram.IsNull())
+    {
+      core20fwd->glUseProgram (OpenGl_ShaderProgram::NO_PROGRAM);
+      myActiveProgram.Nullify();
+    }
+    return Standard_False;
+  }
+
+  myActiveProgram = theProgram;
+  core20fwd->glUseProgram (theProgram->ProgramId());
+  return Standard_True;
+}
+
+// =======================================================================
+// function : BindDefaultVao
+// purpose  :
+// =======================================================================
+void OpenGl_Context::BindDefaultVao()
+{
+#if !defined(GL_ES_VERSION_2_0)
+  if (myDefaultVao == 0
+   || core32 == NULL)
+  {
+    return;
+  }
+
+  core32->glBindVertexArray (myDefaultVao);
+#endif
+}
+
+// =======================================================================
+// function : SetDefaultFrameBuffer
+// purpose  :
+// =======================================================================
+Handle(OpenGl_FrameBuffer) OpenGl_Context::SetDefaultFrameBuffer (const Handle(OpenGl_FrameBuffer)& theFbo)
+{
+  Handle(OpenGl_FrameBuffer) aFbo = myDefaultFbo;
+  myDefaultFbo = theFbo;
+  return aFbo;
+}
+
+// =======================================================================
+// function : SetColor4fv
+// purpose  :
+// =======================================================================
+void OpenGl_Context::SetColor4fv (const OpenGl_Vec4& theColor)
+{
+  if (!myActiveProgram.IsNull())
+  {
+    myActiveProgram->SetUniform (this, myActiveProgram->GetStateLocation (OpenGl_OCCT_COLOR), theColor);
+  }
+#if !defined(GL_ES_VERSION_2_0)
+  else if (core11 != NULL)
+  {
+    core11->glColor4fv (theColor.GetData());
+  }
+#endif
+}
+
+// =======================================================================
+// function : SetTypeOfLine
+// purpose  :
+// =======================================================================
+void OpenGl_Context::SetTypeOfLine (const Aspect_TypeOfLine  theType,
+                                    const Standard_ShortReal theFactor)
+{
+  Standard_Integer aPattern = 0xFFFF;
+  switch (theType)
+  {
+    case Aspect_TOL_DASH:
+    {
+      aPattern = 0xFFC0;
+      break;
+    }
+    case Aspect_TOL_DOT:
+    {
+      aPattern = 0xCCCC;
+      break;
+    }
+    case Aspect_TOL_DOTDASH:
+    {
+      aPattern = 0xFF18;
+      break;
+    }
+    case Aspect_TOL_SOLID:
+    {
+      aPattern = 0xFFFF;
+      break;
+    }
+    case Aspect_TOL_USERDEFINED:
+    {
+      aPattern = 0xFF24;
+      break;
+    }
+  }
+
+  if (!myActiveProgram.IsNull())
+  {
+    myActiveProgram->SetUniform (this, "uPattern", aPattern);
+    myActiveProgram->SetUniform (this, "uFactor",  theFactor);
+    return;
+  }
+
+#if !defined(GL_ES_VERSION_2_0)
+  if (theType != Aspect_TOL_SOLID)
+  {
+  #ifdef HAVE_GL2PS
+    if (IsFeedback())
+    {
+      gl2psEnable (GL2PS_LINE_STIPPLE);
+    }
+  #endif
+
+    if (core11 != NULL)
+    {
+      core11fwd->glEnable (GL_LINE_STIPPLE);
+
+      core11->glLineStipple (static_cast<GLint>    (theFactor),
+                             static_cast<GLushort> (aPattern));
+    }
+  }
+  else
+  {
+    if (core11 != NULL)
+    {
+      core11fwd->glDisable (GL_LINE_STIPPLE);
+    }
+
+  #ifdef HAVE_GL2PS
+    if (IsFeedback())
+    {
+      gl2psDisable (GL2PS_LINE_STIPPLE);
+    }
+  #endif
+  }
+#endif
+}
+
+// =======================================================================
+// function : SetLineWidth
+// purpose  :
+// =======================================================================
+void OpenGl_Context::SetLineWidth (const Standard_ShortReal theWidth)
+{
+  if (core11 != NULL)
+  {
+    // glLineWidth() is still defined within Core Profile, but has no effect with values != 1.0f
+    core11fwd->glLineWidth (theWidth);
+  }
+#ifdef HAVE_GL2PS
+  if (IsFeedback())
+  {
+    gl2psLineWidth (theWidth);
+  }
+#endif
+}
+
+// =======================================================================
+// function : SetPointSize
+// purpose  :
+// =======================================================================
+void OpenGl_Context::SetPointSize (const Standard_ShortReal theSize)
+{
+  if (!myActiveProgram.IsNull())
+  {
+    myActiveProgram->SetUniform (this, myActiveProgram->GetStateLocation (OpenGl_OCCT_POINT_SIZE), theSize);
+  #if !defined(GL_ES_VERSION_2_0)
+    //myContext->core11fwd->glEnable (GL_VERTEX_PROGRAM_POINT_SIZE);
+  #endif
+  }
+#if !defined(GL_ES_VERSION_2_0)
+  //else
+  {
+    core11fwd->glPointSize (theSize);
+    if (core20fwd != NULL)
+    {
+      //myContext->core11fwd->glDisable (GL_VERTEX_PROGRAM_POINT_SIZE);
+    }
+  }
+#endif
+}
+
+// =======================================================================
+// function : SetGlNormalizeEnabled
+// purpose  :
+// =======================================================================
+Standard_Boolean OpenGl_Context::SetGlNormalizeEnabled (Standard_Boolean isEnabled)
+{
+  if (isEnabled == myIsGlNormalizeEnabled)
+  {
+    return myIsGlNormalizeEnabled;
+  }
+
+  Standard_Boolean anOldGlNormalize = myIsGlNormalizeEnabled;
+
+  myIsGlNormalizeEnabled = isEnabled;
+
+#if !defined(GL_ES_VERSION_2_0)
+  if (isEnabled)
+  {
+    glEnable (GL_NORMALIZE);
+  }
+  else
+  {
+    glDisable (GL_NORMALIZE);
+  }
+#endif
+
+  return anOldGlNormalize;
+}
+
+// =======================================================================
+// function : ApplyModelWorldMatrix
+// purpose  :
+// =======================================================================
+void OpenGl_Context::ApplyModelWorldMatrix()
+{
+#if !defined(GL_ES_VERSION_2_0)
+  if (core11 != NULL)
+  {
+    core11->glMatrixMode (GL_MODELVIEW);
+    core11->glLoadMatrixf (ModelWorldState.Current());
+  }
+#endif
+
+  if (!myShaderManager->IsEmpty())
+  {
+    myShaderManager->UpdateModelWorldStateTo (ModelWorldState.Current());
+  }
+}
+
+// =======================================================================
+// function : ApplyWorldViewMatrix
+// purpose  :
+// =======================================================================
+void OpenGl_Context::ApplyWorldViewMatrix()
+{
+#if !defined(GL_ES_VERSION_2_0)
+  if (core11 != NULL)
+  {
+    core11->glMatrixMode (GL_MODELVIEW);
+    core11->glLoadMatrixf (WorldViewState.Current());
+  }
+#endif
+
+  if (!myShaderManager->IsEmpty())
+  {
+    myShaderManager->UpdateWorldViewStateTo (WorldViewState.Current());
+  }
+}
+
+// =======================================================================
+// function : ApplyModelViewMatrix
+// purpose  :
+// =======================================================================
+void OpenGl_Context::ApplyModelViewMatrix()
+{
+#if !defined(GL_ES_VERSION_2_0)
+  if (core11 != NULL)
+  {
+    OpenGl_Mat4 aModelView = WorldViewState.Current() * ModelWorldState.Current();
+    core11->glMatrixMode (GL_MODELVIEW);
+    core11->glLoadMatrixf (aModelView.GetData());
+  }
+#endif
+
+  if (!myShaderManager->IsEmpty())
+  {
+    myShaderManager->UpdateModelWorldStateTo (ModelWorldState.Current());
+    myShaderManager->UpdateWorldViewStateTo (WorldViewState.Current());
+  }
+}
+
+// =======================================================================
+// function : ApplyProjectionMatrix
+// purpose  :
+// =======================================================================
+void OpenGl_Context::ApplyProjectionMatrix()
+{
+#if !defined(GL_ES_VERSION_2_0)
+  if (core11 != NULL)
+  {
+    core11->glMatrixMode (GL_PROJECTION);
+    core11->glLoadMatrixf (ProjectionState.Current().GetData());
+  }
+#endif
+
+  if (!myShaderManager->IsEmpty())
+  {
+    myShaderManager->UpdateProjectionStateTo (ProjectionState.Current());
+  }
+}