0030748: Visualization - Marker displayed in immediate layer ruins QT Quick view...
[occt.git] / src / OpenGl / OpenGl_Window.cxx
index fa7f10a..c812775 100644 (file)
@@ -1,44 +1,48 @@
 // 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.
+// Alternatively, this file may be used under the terms of Open CASCADE
+// commercial license or contractual agreement.
 
-#include <OpenGl_GlCore11.hxx>
-
-#include <InterfaceGraphic.hxx>
-
-#include <OpenGl_Window.hxx>
+#include <OpenGl_GlCore12.hxx>
 
 #include <OpenGl_Context.hxx>
-#include <OpenGl_Display.hxx>
+#include <OpenGl_GraphicDriver.hxx>
+#include <OpenGl_Window.hxx>
+#include <OpenGl_FrameBuffer.hxx>
 
 #include <Aspect_GraphicDeviceDefinitionError.hxx>
+#include <Graphic3d_TransformUtils.hxx>
 #include <TCollection_AsciiString.hxx>
+#include <TCollection_ExtendedString.hxx>
+#include <Graphic3d_GraphicDriver.hxx>
+
+#include <memory>
+
+IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Window,Standard_Transient)
+
+#if defined(HAVE_EGL)
+  #include <EGL/egl.h>
+#endif
 
-IMPLEMENT_STANDARD_HANDLE(OpenGl_Window,MMgt_TShared)
-IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Window,MMgt_TShared)
 
 #if !defined(__APPLE__) || defined(MACOSX_USE_GLX)
 
 namespace
 {
-  static const TEL_COLOUR THE_DEFAULT_BG_COLOR = { { 0.F, 0.F, 0.F, 1.F } };
 
-#if defined(_WIN32)
+#if defined(HAVE_EGL)
+  //
+#elif defined(_WIN32)
 
   // WGL_ARB_pixel_format
 #ifndef WGL_NUMBER_PIXEL_FORMATS_ARB
@@ -118,41 +122,122 @@ namespace
     return DefWindowProcW (theWin, theMsg, theParamW, theParamL);
   }
 #else
-  static Bool WaitForNotify (Display* theDisp, XEvent* theEv, char* theArg)
+
+  // GLX_ARB_create_context
+#ifndef GLX_CONTEXT_MAJOR_VERSION_ARB
+  #define GLX_CONTEXT_DEBUG_BIT_ARB         0x00000001
+  #define GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002
+  #define GLX_CONTEXT_MAJOR_VERSION_ARB     0x2091
+  #define GLX_CONTEXT_MINOR_VERSION_ARB     0x2092
+  #define GLX_CONTEXT_FLAGS_ARB             0x2094
+
+  // GLX_ARB_create_context_profile
+  #define GLX_CONTEXT_CORE_PROFILE_BIT_ARB  0x00000001
+  #define GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
+  #define GLX_CONTEXT_PROFILE_MASK_ARB      0x9126
+#endif
+
+  //! Dummy XError handler which just skips errors
+  static int xErrorDummyHandler (Display*     /*theDisplay*/,
+                                 XErrorEvent* /*theErrorEvent*/)
+  {
+    return 0;
+  }
+
+  //! Auxiliary method to format list.
+  static void addMsgToList (TCollection_ExtendedString&       theList,
+                            const TCollection_ExtendedString& theMsg)
   {
-    return (theEv->type == MapNotify) && (theEv->xmap.window == (Window )theArg);
+    if (!theList.IsEmpty())
+    {
+      theList += ", ";
+    }
+    theList += theMsg;
   }
 #endif
 
-};
+}
 
 // =======================================================================
 // function : OpenGl_Window
 // purpose  :
 // =======================================================================
-OpenGl_Window::OpenGl_Window (const Handle(OpenGl_Display)& theDisplay,
-                              const CALL_DEF_WINDOW&        theCWindow,
+OpenGl_Window::OpenGl_Window (const Handle(OpenGl_GraphicDriver)& theDriver,
+                              const Handle(Aspect_Window)&  thePlatformWindow,
                               Aspect_RenderingContext       theGContext,
                               const Handle(OpenGl_Caps)&    theCaps,
                               const Handle(OpenGl_Context)& theShareCtx)
-: myDisplay (theDisplay),
-  myGlContext (new OpenGl_Context (theCaps)),
+: myGlContext (new OpenGl_Context (theCaps)),
   myOwnGContext (theGContext == 0),
-#if defined(_WIN32)
-  mySysPalInUse (FALSE),
-#endif
-  myWidth ((Standard_Integer )theCWindow.dx),
-  myHeight ((Standard_Integer )theCWindow.dy),
-  myBgColor (THE_DEFAULT_BG_COLOR),
-  myDither (theDisplay->Dither()),
-  myBackDither (theDisplay->BackDither())
+  myPlatformWindow (thePlatformWindow),
+  mySwapInterval (theCaps->swapInterval)
 {
-  myBgColor.rgb[0] = theCWindow.Background.r;
-  myBgColor.rgb[1] = theCWindow.Background.g;
-  myBgColor.rgb[2] = theCWindow.Background.b;
+  myPlatformWindow->Size (myWidth, myHeight);
+
+  Standard_Boolean isCoreProfile = Standard_False;
+
+#if defined(HAVE_EGL)
+  EGLDisplay anEglDisplay = (EGLDisplay )theDriver->getRawGlDisplay();
+  EGLContext anEglContext = (EGLContext )theDriver->getRawGlContext();
+  EGLConfig  anEglConfig  = (EGLConfig  )theDriver->getRawGlConfig();
+  if (anEglDisplay == EGL_NO_DISPLAY
+   || anEglContext == EGL_NO_CONTEXT
+   || (anEglConfig == NULL
+    && (EGLContext )theGContext == EGL_NO_CONTEXT))
+  {
+    throw Aspect_GraphicDeviceDefinitionError("OpenGl_Window, EGL does not provide compatible configurations!");
+    return;
+  }
 
-#if defined(_WIN32)
-  HWND  aWindow   = (HWND )theCWindow.XWindow;
+  EGLSurface anEglSurf = EGL_NO_SURFACE;
+  if ((EGLContext )theGContext == EGL_NO_CONTEXT)
+  {
+    // create new surface
+    anEglSurf = eglCreateWindowSurface (anEglDisplay,
+                                        anEglConfig,
+                                        (EGLNativeWindowType )myPlatformWindow->NativeHandle(),
+                                        NULL);
+    if (anEglSurf == EGL_NO_SURFACE)
+    {
+      throw Aspect_GraphicDeviceDefinitionError("OpenGl_Window, EGL is unable to create surface for window!");
+      return;
+    }
+  }
+  else if (theGContext != anEglContext)
+  {
+    throw Aspect_GraphicDeviceDefinitionError("OpenGl_Window, EGL is used in unsupported combination!");
+    return;
+  }
+  else
+  {
+    anEglSurf = eglGetCurrentSurface(EGL_DRAW);
+    if (anEglSurf == EGL_NO_SURFACE)
+    {
+      // window-less EGL context (off-screen)
+      //throw Aspect_GraphicDeviceDefinitionError("OpenGl_Window, EGL is unable to retrieve current surface!");
+      if (anEglConfig != NULL)
+      {
+        const int aSurfAttribs[] =
+        {
+          EGL_WIDTH,  myWidth,
+          EGL_HEIGHT, myHeight,
+          EGL_NONE
+        };
+        anEglSurf = eglCreatePbufferSurface (anEglDisplay, anEglConfig, aSurfAttribs);
+        if (anEglSurf == EGL_NO_SURFACE)
+        {
+          throw Aspect_GraphicDeviceDefinitionError("OpenGl_Window, EGL is unable to create off-screen surface!");
+        }
+      }
+      myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
+                                "OpenGl_Window::CreateWindow: WARNING, a Window is created without a EGL Surface!");
+    }
+  }
+
+  myGlContext->Init ((Aspect_Drawable )anEglSurf, (Aspect_Display )anEglDisplay, (Aspect_RenderingContext )anEglContext, isCoreProfile);
+#elif defined(_WIN32)
+  (void )theDriver;
+  HWND  aWindow   = (HWND )myPlatformWindow->NativeHandle();
   HDC   aWindowDC = GetDC (aWindow);
   HGLRC aGContext = (HGLRC )theGContext;
 
@@ -172,34 +257,33 @@ OpenGl_Window::OpenGl_Window (const Handle(OpenGl_Display)& theDisplay,
   }
 
   int aPixelFrmtId = ChoosePixelFormat (aWindowDC, &aPixelFrmt);
+
+  // in case of failure try without stereo if any
+  const Standard_Boolean hasStereo = aPixelFrmtId != 0 && theCaps->contextStereo;
+  if (aPixelFrmtId == 0 && theCaps->contextStereo)
+  {
+    TCollection_ExtendedString aMsg ("OpenGl_Window::CreateWindow: "
+                                     "ChoosePixelFormat is unable to find stereo supported pixel format. "
+                                     "Choosing similar non stereo format.");
+    myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
+                              GL_DEBUG_TYPE_OTHER,
+                              0, GL_DEBUG_SEVERITY_HIGH, aMsg);
+
+    aPixelFrmt.dwFlags &= ~PFD_STEREO;
+    aPixelFrmtId = ChoosePixelFormat (aWindowDC, &aPixelFrmt);
+  }
+
   if (aPixelFrmtId == 0)
   {
     ReleaseDC (aWindow, aWindowDC);
 
     TCollection_AsciiString aMsg ("OpenGl_Window::CreateWindow: ChoosePixelFormat failed. Error code: ");
     aMsg += (int )GetLastError();
-    Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
+    throw Aspect_GraphicDeviceDefinitionError(aMsg.ToCString());
     return;
   }
 
   DescribePixelFormat (aWindowDC, aPixelFrmtId, sizeof(aPixelFrmt), &aPixelFrmt);
-  if (aPixelFrmt.dwFlags & PFD_NEED_PALETTE)
-  {
-    WINDOW_DATA* aWndData = (WINDOW_DATA* )GetWindowLongPtr (aWindow, GWLP_USERDATA);
-
-    mySysPalInUse = (aPixelFrmt.dwFlags & PFD_NEED_SYSTEM_PALETTE) ? TRUE : FALSE;
-    InterfaceGraphic_RealizePalette (aWindowDC, aWndData->hPal, FALSE, mySysPalInUse);
-  }
-
-  if (myDither)
-  {
-    myDither = (aPixelFrmt.cColorBits <= 8);
-  }
-
-  if (myBackDither)
-  {
-    myBackDither = (aPixelFrmt.cColorBits <= 8);
-  }
 
   HGLRC aSlaveCtx = !theShareCtx.IsNull() ? (HGLRC )theShareCtx->myGContext : NULL;
   if (aGContext == NULL)
@@ -214,14 +298,18 @@ OpenGl_Window::OpenGl_Window (const Handle(OpenGl_Display)& theDisplay,
     HWND  aWinTmp     = NULL;
     HDC   aDevCtxTmp  = NULL;
     HGLRC aRendCtxTmp = NULL;
-    if ((!theCaps->contextDebug && !theCaps->contextNoAccel)
+    if ((!theCaps->contextDebug && !theCaps->contextNoAccel && theCaps->contextCompatible)
      || RegisterClassW (&aClass) == 0)
     {
       aClass.lpszClassName = NULL;
     }
     if (aClass.lpszClassName != NULL)
     {
-      aWinTmp = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_WINDOWEDGE | WS_EX_NOACTIVATE,
+      DWORD anExStyle = WS_EX_TOOLWINDOW | WS_EX_WINDOWEDGE;
+    #if (_WIN32_WINNT >= 0x0500)
+      anExStyle |= WS_EX_NOACTIVATE;
+    #endif
+      aWinTmp = CreateWindowExW(anExStyle,
                                 aClass.lpszClassName, L"OpenGl_WindowTmp",
                                 WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_DISABLED,
                                 2, 2, 4, 4,
@@ -270,7 +358,7 @@ OpenGl_Window::OpenGl_Window (const Handle(OpenGl_Display)& theDisplay,
         WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
         WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
         WGL_DOUBLE_BUFFER_ARB,  GL_TRUE,
-        WGL_STEREO_ARB,         theCaps->contextStereo ? GL_TRUE : GL_FALSE,
+        WGL_STEREO_ARB,         hasStereo ? GL_TRUE : GL_FALSE,
         WGL_PIXEL_TYPE_ARB,     WGL_TYPE_RGBA_ARB,
         //WGL_SAMPLE_BUFFERS_ARB, 1,
         //WGL_SAMPLES_ARB,        8,
@@ -291,25 +379,63 @@ OpenGl_Window::OpenGl_Window (const Handle(OpenGl_Display)& theDisplay,
 
       TCollection_AsciiString aMsg("OpenGl_Window::CreateWindow: SetPixelFormat failed. Error code: ");
       aMsg += (int )GetLastError();
-      Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
+      throw Aspect_GraphicDeviceDefinitionError(aMsg.ToCString());
       return;
     }
 
     // create GL context with extra options
     if (aCreateCtxProc != NULL)
     {
-      // Beware! NVIDIA drivers reject context creation when WGL_CONTEXT_PROFILE_MASK_ARB are specified
-      // but not WGL_CONTEXT_MAJOR_VERSION_ARB/WGL_CONTEXT_MINOR_VERSION_ARB.
-      int aCtxAttribs[] =
+      if (!theCaps->contextCompatible)
       {
-        //WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
-        //WGL_CONTEXT_MINOR_VERSION_ARB, 2,
-        //WGL_CONTEXT_PROFILE_MASK_ARB,  WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, //WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
-        WGL_CONTEXT_FLAGS_ARB,         theCaps->contextDebug ? WGL_CONTEXT_DEBUG_BIT_ARB : 0,
-        0, 0
-      };
+        int aCoreCtxAttribs[] =
+        {
+          WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
+          WGL_CONTEXT_MINOR_VERSION_ARB, 2,
+          WGL_CONTEXT_PROFILE_MASK_ARB,  WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
+          WGL_CONTEXT_FLAGS_ARB,         theCaps->contextDebug ? WGL_CONTEXT_DEBUG_BIT_ARB : 0,
+          0, 0
+        };
+
+        // Try to create the core profile of highest OpenGL version supported by OCCT
+        // (this will be done automatically by some drivers when requesting 3.2,
+        //  but some will not (e.g. AMD Catalyst) since WGL_ARB_create_context_profile specification allows both implementations).
+        for (int aLowVer4 = 5; aLowVer4 >= 0 && aGContext == NULL; --aLowVer4)
+        {
+          aCoreCtxAttribs[1] = 4;
+          aCoreCtxAttribs[3] = aLowVer4;
+          aGContext = aCreateCtxProc (aWindowDC, aSlaveCtx, aCoreCtxAttribs);
+        }
+        for (int aLowVer3 = 3; aLowVer3 >= 2 && aGContext == NULL; --aLowVer3)
+        {
+          aCoreCtxAttribs[1] = 3;
+          aCoreCtxAttribs[3] = aLowVer3;
+          aGContext = aCreateCtxProc (aWindowDC, aSlaveCtx, aCoreCtxAttribs);
+        }
+        isCoreProfile = aGContext != NULL;
+      }
+
+      if (aGContext == NULL)
+      {
+        int aCtxAttribs[] =
+        {
+          // Beware! NVIDIA drivers reject context creation when WGL_CONTEXT_PROFILE_MASK_ARB are specified
+          // but not WGL_CONTEXT_MAJOR_VERSION_ARB/WGL_CONTEXT_MINOR_VERSION_ARB.
+          //WGL_CONTEXT_PROFILE_MASK_ARB,  WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
+          WGL_CONTEXT_FLAGS_ARB,         theCaps->contextDebug ? WGL_CONTEXT_DEBUG_BIT_ARB : 0,
+          0, 0
+        };
+        isCoreProfile = Standard_False;
+        aGContext = aCreateCtxProc (aWindowDC, aSlaveCtx, aCtxAttribs);
+
+        if (aGContext != NULL
+        && !theCaps->contextCompatible)
+        {
+          TCollection_ExtendedString aMsg("OpenGl_Window::CreateWindow: core profile creation failed.");
+          myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMsg);
+        }
+      }
 
-      aGContext = aCreateCtxProc (aWindowDC, aSlaveCtx, aCtxAttribs);
       if (aGContext != NULL)
       {
         aSlaveCtx = NULL;
@@ -344,7 +470,7 @@ OpenGl_Window::OpenGl_Window (const Handle(OpenGl_Display)& theDisplay,
 
       TCollection_AsciiString aMsg ("OpenGl_Window::CreateWindow: wglCreateContext failed. Error code: ");
       aMsg += (int )GetLastError();
-      Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
+      throw Aspect_GraphicDeviceDefinitionError(aMsg.ToCString());
       return;
     }
   }
@@ -354,186 +480,143 @@ OpenGl_Window::OpenGl_Window (const Handle(OpenGl_Display)& theDisplay,
   {
     TCollection_AsciiString aMsg ("OpenGl_Window::CreateWindow: wglShareLists failed. Error code: ");
     aMsg += (int )GetLastError();
-    Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
+    throw Aspect_GraphicDeviceDefinitionError(aMsg.ToCString());
     return;
   }
 
-  myGlContext->Init ((Aspect_Handle )aWindow, (Aspect_Handle )aWindowDC, (Aspect_RenderingContext )aGContext);
+  myGlContext->Init ((Aspect_Handle )aWindow, (Aspect_Handle )aWindowDC, (Aspect_RenderingContext )aGContext, isCoreProfile);
 #else
-  WINDOW aParent = (WINDOW )theCWindow.XWindow;
-  WINDOW aWindow = 0;
-  DISPLAY* aDisp = (DISPLAY* )myDisplay->GetDisplay();
+  Window     aWindow   = (Window )myPlatformWindow->NativeHandle();
+  Display*   aDisp     = theDriver->GetDisplayConnection()->GetDisplay();
   GLXContext aGContext = (GLXContext )theGContext;
-
-  XWindowAttributes wattr;
-  XGetWindowAttributes (aDisp, aParent, &wattr);
-  const int scr = DefaultScreen (aDisp);
-
-  XVisualInfo* aVis = NULL;
+  GLXContext aSlaveCtx = !theShareCtx.IsNull() ? (GLXContext )theShareCtx->myGContext : NULL;
+
+  XWindowAttributes aWinAttribs;
+  XGetWindowAttributes (aDisp, aWindow, &aWinAttribs);
+  XVisualInfo aVisInfo;
+  aVisInfo.visualid = aWinAttribs.visual->visualid;
+  aVisInfo.screen   = DefaultScreen (aDisp);
+  int aNbItems;
+  std::unique_ptr<XVisualInfo, int(*)(void*)> aVis (XGetVisualInfo (aDisp, VisualIDMask | VisualScreenMask, &aVisInfo, &aNbItems), &XFree);
+  int isGl = 0;
+  if (aVis.get() == NULL)
   {
-    unsigned long aVisInfoMask = VisualIDMask | VisualScreenMask;
-    XVisualInfo aVisInfo;
-    aVisInfo.visualid = wattr.visual->visualid;
-    aVisInfo.screen   = scr;
-    int aNbItems;
-    aVis = XGetVisualInfo (aDisp, aVisInfoMask, &aVisInfo, &aNbItems);
+    throw Aspect_GraphicDeviceDefinitionError("OpenGl_Window::CreateWindow: XGetVisualInfo is unable to choose needed configuration in existing OpenGL context. ");
+    return;
   }
-
-  if (!myOwnGContext)
+  else if (glXGetConfig (aDisp, aVis.get(), GLX_USE_GL, &isGl) != 0 || !isGl)
   {
-    if (aVis != NULL)
-    {
-      Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: XGetVisualInfo failed.");
-      return;
-    }
-
-    aWindow = aParent;
+    throw Aspect_GraphicDeviceDefinitionError("OpenGl_Window::CreateWindow: window Visual does not support GL rendering!");
+    return;
   }
-  else
+
+  // create new context
+  GLXFBConfig anFBConfig = myPlatformWindow->NativeFBConfig();
+  const char* aGlxExts   = glXQueryExtensionsString (aDisp, aVisInfo.screen);
+  if (myOwnGContext
+   && anFBConfig != NULL
+   && OpenGl_Context::CheckExtension (aGlxExts, "GLX_ARB_create_context_profile"))
   {
-  #if defined(__linux) || defined(Linux) || defined(__APPLE__)
-    if (aVis != NULL)
+    // Replace default XError handler to ignore errors.
+    // Warning - this is global for all threads!
+    typedef int (*xerrorhandler_t)(Display* , XErrorEvent* );
+    xerrorhandler_t anOldHandler = XSetErrorHandler(xErrorDummyHandler);
+
+    typedef GLXContext (*glXCreateContextAttribsARB_t)(Display* dpy, GLXFBConfig config,
+                                                       GLXContext share_context, Bool direct,
+                                                       const int* attrib_list);
+    glXCreateContextAttribsARB_t aCreateCtxProc = (glXCreateContextAttribsARB_t )glXGetProcAddress((const GLubyte* )"glXCreateContextAttribsARB");
+    if (!theCaps->contextCompatible)
     {
-      // check Visual for OpenGl context's parameters compability
-      int isGl = 0, isDoubleBuffer = 0, isRGBA = 0, aDepthSize = 0, aStencilSize = 0;
-
-      if (glXGetConfig (aDisp, aVis, GLX_USE_GL, &isGl) != 0)
-        isGl = 0;
-
-      if (glXGetConfig (aDisp, aVis, GLX_RGBA, &isRGBA) != 0)
-        isRGBA = 0;
-
-      if (glXGetConfig (aDisp, aVis, GLX_DOUBLEBUFFER, &isDoubleBuffer) != 0)
-        isDoubleBuffer = 0;
-
-      if (glXGetConfig (aDisp, aVis, GLX_DEPTH_SIZE, &aDepthSize) != 0)
-        aDepthSize = 0;
-
-      if (glXGetConfig (aDisp, aVis, GLX_STENCIL_SIZE, &aStencilSize) != 0)
-        aStencilSize = 0;
+      int aCoreCtxAttribs[] =
+      {
+        GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
+        GLX_CONTEXT_MINOR_VERSION_ARB, 2,
+        GLX_CONTEXT_PROFILE_MASK_ARB,  GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
+        GLX_CONTEXT_FLAGS_ARB,         theCaps->contextDebug ? GLX_CONTEXT_DEBUG_BIT_ARB : 0,
+        0, 0
+      };
 
-      if (!isGl || !aDepthSize || !isRGBA  || (isDoubleBuffer ? 1 : 0) != (myDisplay->DBuffer()? 1 : 0))
+      // try to create the core profile of highest OpenGL version supported by OCCT
+      for (int aLowVer4 = 5; aLowVer4 >= 0 && aGContext == NULL; --aLowVer4)
       {
-        XFree (aVis);
-        aVis = NULL;
+        aCoreCtxAttribs[1] = 4;
+        aCoreCtxAttribs[3] = aLowVer4;
+        aGContext = aCreateCtxProc (aDisp, anFBConfig, aSlaveCtx, True, aCoreCtxAttribs);
       }
+      for (int aLowVer3 = 3; aLowVer3 >= 2 && aGContext == NULL; --aLowVer3)
+      {
+        aCoreCtxAttribs[1] = 3;
+        aCoreCtxAttribs[3] = aLowVer3;
+        aGContext = aCreateCtxProc (aDisp, anFBConfig, aSlaveCtx, True, aCoreCtxAttribs);
+      }
+      isCoreProfile = aGContext != NULL;
     }
-  #endif
 
-    if (aVis == NULL)
+    if (aGContext == NULL)
     {
-      int anIter = 0;
-      int anAttribs[13];
-      anAttribs[anIter++] = GLX_RGBA;
-
-      anAttribs[anIter++] = GLX_DEPTH_SIZE;
-      anAttribs[anIter++] = 1;
-
-      anAttribs[anIter++] = GLX_STENCIL_SIZE;
-      anAttribs[anIter++] = 1;
-
-      anAttribs[anIter++] = GLX_RED_SIZE;
-      anAttribs[anIter++] = (wattr.depth <= 8) ? 0 : 1;
-
-      anAttribs[anIter++] = GLX_GREEN_SIZE;
-      anAttribs[anIter++] = (wattr.depth <= 8) ? 0 : 1;
-
-      anAttribs[anIter++] = GLX_BLUE_SIZE;
-      anAttribs[anIter++] = (wattr.depth <= 8) ? 0 : 1;
-
-      if (myDisplay->DBuffer())
-        anAttribs[anIter++] = GLX_DOUBLEBUFFER;
-
-      anAttribs[anIter++] = None;
+      int aCtxAttribs[] =
+      {
+        GLX_CONTEXT_FLAGS_ARB, theCaps->contextDebug ? GLX_CONTEXT_DEBUG_BIT_ARB : 0,
+        0, 0
+      };
+      isCoreProfile = Standard_False;
+      aGContext = aCreateCtxProc (aDisp, anFBConfig, aSlaveCtx, True, aCtxAttribs);
 
-      aVis = glXChooseVisual (aDisp, scr, anAttribs);
-      if (aVis == NULL)
+      if (aGContext != NULL
+      && !theCaps->contextCompatible)
       {
-        Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: glXChooseVisual failed.");
-        return;
+        TCollection_ExtendedString aMsg("OpenGl_Window::CreateWindow: core profile creation failed.");
+        myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMsg);
       }
     }
+    XSetErrorHandler(anOldHandler);
+  }
 
-    if (!theShareCtx.IsNull())
-    {
-      // ctx est une copie du previous
-      aGContext = glXCreateContext (aDisp, aVis, (GLXContext )theShareCtx->myGContext, GL_TRUE);
-    }
-    else
-    {
-      aGContext = glXCreateContext (aDisp, aVis, NULL, GL_TRUE);
-    }
-
-    if (!aGContext)
+  if (myOwnGContext
+   && aGContext == NULL)
+  {
+    aGContext = glXCreateContext (aDisp, aVis.get(), aSlaveCtx, GL_TRUE);
+    if (aGContext == NULL)
     {
-      Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: glXCreateContext failed.");
+      throw Aspect_GraphicDeviceDefinitionError("OpenGl_Window::CreateWindow: glXCreateContext failed.");
       return;
     }
-
-    Colormap cmap = XCreateColormap (aDisp, aParent, aVis->visual, AllocNone);
-
-    XColor color;
-    color.red   = (unsigned short) (myBgColor.rgb[0] * 0xFFFF);
-    color.green = (unsigned short) (myBgColor.rgb[1] * 0xFFFF);
-    color.blue  = (unsigned short) (myBgColor.rgb[2] * 0xFFFF);
-    color.flags = DoRed | DoGreen | DoBlue;
-    XAllocColor (aDisp, cmap, &color);
-
-    XSetWindowAttributes cwa;
-    cwa.colormap         = cmap;
-    cwa.event_mask       = StructureNotifyMask;
-    cwa.border_pixel     = color.pixel;
-    cwa.background_pixel = color.pixel;
-
-    if (aVis->visualid == wattr.visual->visualid)
-    {
-      aWindow = aParent;
-    }
-    else
-    {
-      unsigned long mask = CWBackPixel | CWColormap | CWBorderPixel | CWEventMask;
-      aWindow = XCreateWindow (aDisp, aParent, 0, 0, myWidth, myHeight, 0/*bw*/, aVis->depth, InputOutput, aVis->visual, mask, &cwa);
-    }
-
-    XSetWindowBackground (aDisp, aWindow, cwa.background_pixel);
-    XClearWindow (aDisp, aWindow);
-
-    if (aWindow != aParent)
-    {
-      XEvent anEvent;
-      XMapWindow (aDisp, aWindow);
-      XIfEvent (aDisp, &anEvent, WaitForNotify, (char* )aWindow);
-    }
   }
 
-  /*
-  * Le BackDitherProp est utilise pour le clear du background
-  * Pour eviter une difference de couleurs avec la couleur choisie
-  * par l'application (XWindow) il faut desactiver le dithering
-  * au dessus de 8 plans.
-  *
-  * Pour le DitherProp:
-  * On cherchera a activer le Dithering que si le Visual a au moins
-  * 8 plans pour le GLX_RED_SIZE. Le test est plus sur car on peut
-  * avoir une profondeur superieure a 12 mais avoir besoin du dithering.
-  * (Carte Impact avec GLX_RED_SIZE a 5 par exemple)
-  */
-
-  int aValue;
-  glXGetConfig (aDisp, aVis, GLX_RED_SIZE, &aValue);
-
-  if (myDither)
-    myDither = (aValue < 8);
-
-  if (myBackDither)
-    myBackDither = (aVis->depth <= 8);
-
-  XFree ((char* )aVis);
+  // check Visual for OpenGl context's parameters compatibility
+  TCollection_ExtendedString aList;
+  int isDoubleBuffer = 0, isRGBA = 0, isStereo = 0;
+  int aDepthSize = 0, aStencilSize = 0;
+  glXGetConfig (aDisp, aVis.get(), GLX_RGBA,         &isRGBA);
+  glXGetConfig (aDisp, aVis.get(), GLX_DOUBLEBUFFER, &isDoubleBuffer);
+  glXGetConfig (aDisp, aVis.get(), GLX_STEREO,       &isStereo);
+  glXGetConfig (aDisp, aVis.get(), GLX_DEPTH_SIZE,   &aDepthSize);
+  glXGetConfig (aDisp, aVis.get(), GLX_STENCIL_SIZE, &aStencilSize);
+  if (aDepthSize < 1)      addMsgToList (aList, "no depth buffer");
+  if (aStencilSize < 1)    addMsgToList (aList, "no stencil buffer");
+  if (isRGBA == 0)         addMsgToList (aList, "no RGBA color buffer");
+  if (isDoubleBuffer == 0) addMsgToList (aList, "no Double Buffer");
+  if (theCaps->contextStereo && isStereo == 0)
+  {
+    addMsgToList (aList, "no Quad Buffer");
+  }
+  else if (!theCaps->contextStereo && isStereo == 1)
+  {
+    addMsgToList (aList, "extra Quad Buffer");
+  }
+  if (!aList.IsEmpty())
+  {
+    TCollection_ExtendedString aMsg = TCollection_ExtendedString ("OpenGl_Window::CreateWindow: window Visual is incomplete: ") + aList;
+    myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
+                              GL_DEBUG_TYPE_OTHER,
+                              0, GL_DEBUG_SEVERITY_MEDIUM, aMsg);
+  }
 
-  myGlContext->Init ((Aspect_Drawable )aWindow, (Aspect_Display )myDisplay->GetDisplay(), (Aspect_RenderingContext )aGContext);
+  myGlContext->Init ((Aspect_Drawable )aWindow, (Aspect_Display )aDisp, (Aspect_RenderingContext )aGContext, isCoreProfile);
 #endif
   myGlContext->Share (theShareCtx);
-
+  myGlContext->SetSwapInterval (mySwapInterval);
   Init();
 }
 
@@ -543,30 +626,55 @@ OpenGl_Window::OpenGl_Window (const Handle(OpenGl_Display)& theDisplay,
 // =======================================================================
 OpenGl_Window::~OpenGl_Window()
 {
-#if defined(_WIN32)
-  HWND  aWindow   = (HWND  )myGlContext->myWindow;
-  HDC   aWindowDC = (HDC   )myGlContext->myWindowDC;
-  HGLRC aGContext = (HGLRC )myGlContext->myGContext;
+  if (!myOwnGContext
+   ||  myGlContext.IsNull())
+  {
+    myGlContext.Nullify();
+    return;
+  }
+
+  // release "GL" context if it is owned by window
+  // Mesa implementation can fail to destroy GL context if it set for current thread.
+  // It should be safer to unset thread GL context before its destruction.
+#if defined(HAVE_EGL)
+  if ((EGLSurface )myGlContext->myWindow != EGL_NO_SURFACE)
+  {
+    eglDestroySurface ((EGLDisplay )myGlContext->myDisplay,
+                       (EGLSurface )myGlContext->myWindow);
+  }
+#elif defined(_WIN32)
+  HWND  aWindow          = (HWND  )myGlContext->myWindow;
+  HDC   aWindowDC        = (HDC   )myGlContext->myWindowDC;
+  HGLRC aWindowGContext  = (HGLRC )myGlContext->myGContext;
+  HGLRC aThreadGContext  = wglGetCurrentContext();
   myGlContext.Nullify();
 
-  if (myOwnGContext)
+  if (aThreadGContext != NULL)
   {
-    if (wglGetCurrentContext() != NULL)
+    if (aThreadGContext == aWindowGContext)
     {
-      wglDeleteContext (aGContext);
+      wglMakeCurrent (NULL, NULL);
     }
-    ReleaseDC (aWindow, aWindowDC);
+
+    wglDeleteContext (aWindowGContext);
   }
+  ReleaseDC (aWindow, aWindowDC);
 #else
-  Display*    aDisplay  = (Display*    )myGlContext->myDisplay;
-  GLXContext  aGContext = (GLXContext  )myGlContext->myGContext;
+  Display*    aDisplay        = (Display*    )myGlContext->myDisplay;
+  GLXContext  aWindowGContext = (GLXContext  )myGlContext->myGContext;
+  GLXContext  aThreadGContext = glXGetCurrentContext();
   myGlContext.Nullify();
 
-  if (aDisplay != NULL && myOwnGContext)
+  if (aDisplay != NULL)
   {
+    if (aThreadGContext == aWindowGContext)
+    {
+      glXMakeCurrent (aDisplay, None, NULL);
+    }
+
     // FSXXX sync necessary if non-direct rendering
     glXWaitGL();
-    glXDestroyContext (aDisplay, aGContext);
+    glXDestroyContext (aDisplay, aWindowGContext);
   }
 #endif
 }
@@ -588,20 +696,26 @@ Standard_Boolean OpenGl_Window::Activate()
 // function : Resize
 // purpose  : call_subr_resize
 // =======================================================================
-void OpenGl_Window::Resize (const CALL_DEF_WINDOW& theCWindow)
+void OpenGl_Window::Resize()
 {
-  DISPLAY* aDisp = (DISPLAY* )myDisplay->GetDisplay();
+#if !defined(_WIN32) && !defined(HAVE_EGL)
+  Display* aDisp = (Display* )myGlContext->myDisplay;
   if (aDisp == NULL)
     return;
+#endif
+
+  Standard_Integer aWidth  = 0;
+  Standard_Integer aHeight = 0;
+  myPlatformWindow->Size (aWidth, aHeight);
 
   // If the size is not changed - do nothing
-  if ((myWidth == theCWindow.dx) && (myHeight == theCWindow.dy))
+  if ((myWidth == aWidth) && (myHeight == aHeight))
     return;
 
-  myWidth  = (Standard_Integer )theCWindow.dx;
-  myHeight = (Standard_Integer )theCWindow.dy;
+  myWidth  = aWidth;
+  myHeight = aHeight;
 
-#if !defined(_WIN32)
+#if !defined(_WIN32) && !defined(HAVE_EGL)
   XResizeWindow (aDisp, myGlContext->myWindow, (unsigned int )myWidth, (unsigned int )myHeight);
   XSync (aDisp, False);
 #endif
@@ -609,46 +723,6 @@ void OpenGl_Window::Resize (const CALL_DEF_WINDOW& theCWindow)
   Init();
 }
 
-#endif // !__APPLE__
-
-// =======================================================================
-// function : ReadDepths
-// purpose  : TelReadDepths
-// =======================================================================
-void OpenGl_Window::ReadDepths (const Standard_Integer theX,     const Standard_Integer theY,
-                                const Standard_Integer theWidth, const Standard_Integer theHeight,
-                                float* theDepths)
-{
-  if (theDepths == NULL || !Activate())
-    return;
-
-  glMatrixMode (GL_PROJECTION);
-  glLoadIdentity();
-  gluOrtho2D (0.0, (GLdouble )myWidth, 0.0, (GLdouble )myHeight);
-  glMatrixMode (GL_MODELVIEW);
-  glLoadIdentity();
-
-  glRasterPos2i (theX, theY);
-  DisableFeatures();
-  glReadPixels (theX, theY, theWidth, theHeight, GL_DEPTH_COMPONENT, GL_FLOAT, theDepths);
-  EnableFeatures();
-}
-
-// =======================================================================
-// function : SetBackgroundColor
-// purpose  : call_subr_set_background
-// =======================================================================
-void OpenGl_Window::SetBackgroundColor (const Standard_ShortReal theR,
-                                        const Standard_ShortReal theG,
-                                        const Standard_ShortReal theB)
-{
-  myBgColor.rgb[0] = theR;
-  myBgColor.rgb[1] = theG;
-  myBgColor.rgb[2] = theB;
-}
-
-#if !defined(__APPLE__) || defined(MACOSX_USE_GLX)
-
 // =======================================================================
 // function : Init
 // purpose  :
@@ -658,156 +732,73 @@ void OpenGl_Window::Init()
   if (!Activate())
     return;
 
-#if defined(_WIN32)
-  RECT cr;
-  GetClientRect ((HWND )myGlContext->myWindow, &cr);
-  myWidth  = cr.right - cr.left;
-  myHeight = cr.bottom - cr.top;
+#if defined(HAVE_EGL)
+  if ((EGLSurface )myGlContext->myWindow == EGL_NO_SURFACE)
+  {
+    // define an offscreen default FBO to avoid rendering into EGL_NO_SURFACE;
+    // note that this code is currently never called, since eglCreatePbufferSurface() is used instead as more robust solution
+    // for offscreen rendering on bugged OpenGL ES drivers
+    Handle(OpenGl_FrameBuffer) aDefFbo = myGlContext->SetDefaultFrameBuffer (Handle(OpenGl_FrameBuffer)());
+    if (!aDefFbo.IsNull())
+    {
+      aDefFbo->Release (myGlContext.operator->());
+    }
+    else
+    {
+      aDefFbo = new OpenGl_FrameBuffer();
+    }
+
+    if (!aDefFbo->InitWithRB (myGlContext, myWidth, myHeight, GL_RGBA8, GL_DEPTH24_STENCIL8))
+    {
+      TCollection_AsciiString aMsg ("OpenGl_Window::CreateWindow: default FBO creation failed");
+      throw Aspect_GraphicDeviceDefinitionError(aMsg.ToCString());
+    }
+    myGlContext->SetDefaultFrameBuffer (aDefFbo);
+    aDefFbo->BindBuffer (myGlContext);
+  }
+  else if (!myPlatformWindow->IsVirtual())
+  {
+    eglQuerySurface ((EGLDisplay )myGlContext->myDisplay, (EGLSurface )myGlContext->myWindow, EGL_WIDTH,  &myWidth);
+    eglQuerySurface ((EGLDisplay )myGlContext->myDisplay, (EGLSurface )myGlContext->myWindow, EGL_HEIGHT, &myHeight);
+  }
+#elif defined(_WIN32)
+  //
 #else
   Window aRootWin;
   int aDummy;
   unsigned int aDummyU;
   unsigned int aNewWidth  = 0;
   unsigned int aNewHeight = 0;
-  DISPLAY* aDisp = (DISPLAY* )myDisplay->GetDisplay();
+  Display* aDisp = (Display* )myGlContext->myDisplay;
   XGetGeometry (aDisp, myGlContext->myWindow, &aRootWin, &aDummy, &aDummy, &aNewWidth, &aNewHeight, &aDummyU, &aDummyU);
   myWidth  = aNewWidth;
   myHeight = aNewHeight;
 #endif
 
-  glMatrixMode (GL_MODELVIEW);
-  glViewport (0, 0, myWidth, myHeight);
-
-  glDisable (GL_SCISSOR_TEST);
-  glDrawBuffer (GL_BACK);
-}
-
-#endif // !__APPLE__
-
-// =======================================================================
-// function : EnablePolygonOffset
-// purpose  : call_subr_enable_polygon_offset
-// =======================================================================
-void OpenGl_Window::EnablePolygonOffset() const
-{
-  Standard_ShortReal aFactor, aUnits;
-  myDisplay->PolygonOffset (aFactor, aUnits);
-  glPolygonOffset (aFactor, aUnits);
-  glEnable (GL_POLYGON_OFFSET_FILL);
-}
-
-// =======================================================================
-// function : DisablePolygonOffset
-// purpose  : call_subr_disable_polygon_offset
-// =======================================================================
-void OpenGl_Window::DisablePolygonOffset() const
-{
-  glDisable (GL_POLYGON_OFFSET_FILL);
-}
-
-// =======================================================================
-// function : EnableFeatures
-// purpose  :
-// =======================================================================
-void OpenGl_Window::EnableFeatures() const
-{
-  /*glPixelTransferi (GL_MAP_COLOR, GL_TRUE);*/
-
-  if (myDither)
-    glEnable (GL_DITHER);
-  else
-    glDisable (GL_DITHER);
-}
-
-// =======================================================================
-// function : DisableFeatures
-// purpose  :
-// =======================================================================
-void OpenGl_Window::DisableFeatures() const
-{
   glDisable (GL_DITHER);
-  glPixelTransferi (GL_MAP_COLOR, GL_FALSE);
-
-  /*
-  * Disable stuff that's likely to slow down glDrawPixels.
-  * (Omit as much of this as possible, when you know in advance
-  * that the OpenGL state will already be set correctly.)
-  */
-  glDisable(GL_ALPHA_TEST);
-  glDisable(GL_BLEND);
-  glDisable(GL_DEPTH_TEST);
-  glDisable(GL_FOG);
-  glDisable(GL_LIGHTING);
-
-  glDisable(GL_LOGIC_OP);
-  glDisable(GL_STENCIL_TEST);
-  glDisable(GL_TEXTURE_1D);
-  glDisable(GL_TEXTURE_2D);
-  glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
-  glPixelTransferi(GL_RED_SCALE, 1);
-  glPixelTransferi(GL_RED_BIAS, 0);
-  glPixelTransferi(GL_GREEN_SCALE, 1);
-  glPixelTransferi(GL_GREEN_BIAS, 0);
-  glPixelTransferi(GL_BLUE_SCALE, 1);
-  glPixelTransferi(GL_BLUE_BIAS, 0);
-  glPixelTransferi(GL_ALPHA_SCALE, 1);
-  glPixelTransferi(GL_ALPHA_BIAS, 0);
-
-  /*
-  * Disable extensions that could slow down glDrawPixels.
-  * (Actually, you should check for the presence of the proper
-  * extension before making these calls.  I've omitted that
-  * code for simplicity.)
-  */
-
-#ifdef GL_EXT_convolution
-  glDisable(GL_CONVOLUTION_1D_EXT);
-  glDisable(GL_CONVOLUTION_2D_EXT);
-  glDisable(GL_SEPARABLE_2D_EXT);
-#endif
-
-#ifdef GL_EXT_histogram
-  glDisable(GL_HISTOGRAM_EXT);
-  glDisable(GL_MINMAX_EXT);
-#endif
-
-#ifdef GL_EXT_texture3D
-  glDisable(GL_TEXTURE_3D_EXT);
+  glDisable (GL_SCISSOR_TEST);
+  const Standard_Integer aViewport[4] = { 0, 0, myWidth, myHeight };
+  myGlContext->ResizeViewport (aViewport);
+#if !defined(GL_ES_VERSION_2_0)
+  myGlContext->SetDrawBuffer (GL_BACK);
+  if (myGlContext->core11 != NULL)
+  {
+    glMatrixMode (GL_MODELVIEW);
+  }
 #endif
 }
 
 // =======================================================================
-// function : MakeFrontBufCurrent
-// purpose  : TelMakeFrontBufCurrent
-// =======================================================================
-void OpenGl_Window::MakeFrontBufCurrent() const
-{
-  glDrawBuffer (GL_FRONT);
-}
-
-// =======================================================================
-// function : MakeBackBufCurrent
-// purpose  : TelMakeBackBufCurrent
-// =======================================================================
-void OpenGl_Window::MakeBackBufCurrent() const
-{
-  glDrawBuffer (GL_BACK);
-}
-
-// =======================================================================
-// function : MakeFrontAndBackBufCurrent
-// purpose  : TelMakeFrontAndBackBufCurrent
-// =======================================================================
-void OpenGl_Window::MakeFrontAndBackBufCurrent() const
-{
-  glDrawBuffer (GL_FRONT_AND_BACK);
-}
-
-// =======================================================================
-// function : GetGContext
+// function : SetSwapInterval
 // purpose  :
 // =======================================================================
-GLCONTEXT OpenGl_Window::GetGContext() const
+void OpenGl_Window::SetSwapInterval()
 {
-  return (GLCONTEXT )myGlContext->myGContext;
+  if (mySwapInterval != myGlContext->caps->swapInterval)
+  {
+    mySwapInterval = myGlContext->caps->swapInterval;
+    myGlContext->SetSwapInterval (mySwapInterval);
+  }
 }
+
+#endif // !__APPLE__