0028306: Visualization - viewer crashes if style for shaded display is set to HATCH
[occt.git] / src / OpenGl / OpenGl_Context.cxx
index 0e5432b..43ae9fa 100644 (file)
@@ -54,6 +54,7 @@ IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Context,Standard_Transient)
     //
   #else
     #include <OpenGL/OpenGL.h>
+    #include <CoreGraphics/CoreGraphics.h>
   #endif
 #else
   #include <GL/glx.h> // glXGetProcAddress()
@@ -71,6 +72,23 @@ namespace
 {
   static const Handle(OpenGl_Resource) NULL_GL_RESOURCE;
   static const OpenGl_Mat4 THE_IDENTITY_MATRIX;
+
+  //! Add key-value pair to the dictionary.
+  static void addInfo (TColStd_IndexedDataMapOfStringString& theDict,
+                       const TCollection_AsciiString& theKey,
+                       const TCollection_AsciiString& theValue)
+  {
+    theDict.ChangeFromIndex (theDict.Add (theKey, theValue)) = theValue;
+  }
+
+  //! Add key-value pair to the dictionary.
+  static void addInfo (TColStd_IndexedDataMapOfStringString& theDict,
+                       const TCollection_AsciiString& theKey,
+                       const char* theValue)
+  {
+    TCollection_AsciiString aValue (theValue != NULL ? theValue : "");
+    theDict.ChangeFromIndex (theDict.Add (theKey, aValue)) = aValue;
+  }
 }
 
 // =======================================================================
@@ -116,6 +134,7 @@ OpenGl_Context::OpenGl_Context (const Handle(OpenGl_Caps)& theCaps)
   arbDbg (NULL),
   arbFBO (NULL),
   arbFBOBlit (NULL),
+  extFragDepth (Standard_False),
   extGS  (NULL),
   extBgra(Standard_False),
   extAnis(Standard_False),
@@ -138,12 +157,17 @@ OpenGl_Context::OpenGl_Context (const Handle(OpenGl_Caps)& theCaps)
   myIsInitialized (Standard_False),
   myIsStereoBuffers (Standard_False),
   myIsGlNormalizeEnabled (Standard_False),
+  myHasRayTracing (Standard_False),
+  myHasRayTracingTextures (Standard_False),
+  myHasRayTracingAdaptiveSampling (Standard_False),
 #if !defined(GL_ES_VERSION_2_0)
   myPointSpriteOrig (GL_UPPER_LEFT),
   myRenderMode (GL_RENDER),
+  myPolygonMode (GL_FILL),
 #else
   myPointSpriteOrig (0),
   myRenderMode (0),
+  myPolygonMode (0),
 #endif
   myToCullBackFaces (false),
   myReadBuffer (0),
@@ -152,6 +176,11 @@ OpenGl_Context::OpenGl_Context (const Handle(OpenGl_Caps)& theCaps)
   myIsGlDebugCtx (Standard_False),
   myResolutionRatio (1.0f)
 {
+  myViewport[0] = 0;
+  myViewport[1] = 0;
+  myViewport[2] = 0;
+  myViewport[3] = 0;
+
   // system-dependent fields
 #if defined(HAVE_EGL)
   myDisplay  = (Aspect_Display          )EGL_NO_DISPLAY;
@@ -245,21 +274,21 @@ OpenGl_Context::~OpenGl_Context()
     myTexSampler->Release (this);
   }
 
-#if !defined(GL_ES_VERSION_2_0)
   if (arbDbg != NULL
    && myIsGlDebugCtx
    && IsValid())
   {
     // reset callback
+  #if !defined(GL_ES_VERSION_2_0)
     void* aPtr = NULL;
     glGetPointerv (GL_DEBUG_CALLBACK_USER_PARAM, &aPtr);
     if (aPtr == this)
+  #endif
     {
-      arbDbg->glDebugMessageCallbackARB (NULL, NULL);
+      arbDbg->glDebugMessageCallback (NULL, NULL);
     }
     myIsGlDebugCtx = Standard_False;
   }
-#endif
 }
 
 // =======================================================================
@@ -286,6 +315,19 @@ void OpenGl_Context::forcedRelease()
   }
 }
 
+// =======================================================================
+// function : ResizeViewport
+// purpose  :
+// =======================================================================
+void OpenGl_Context::ResizeViewport (const Standard_Integer* theRect)
+{
+  core11fwd->glViewport (theRect[0], theRect[1], theRect[2], theRect[3]);
+  myViewport[0] = theRect[0];
+  myViewport[1] = theRect[1];
+  myViewport[2] = theRect[2];
+  myViewport[3] = theRect[3];
+}
+
 #if !defined(GL_ES_VERSION_2_0)
 inline Standard_Integer stereoToMonoBuffer (const Standard_Integer theBuffer)
 {
@@ -770,17 +812,18 @@ Standard_Boolean OpenGl_Context::Init (const Aspect_Drawable         theWindow,
 // function : ResetErrors
 // purpose  :
 // =======================================================================
-void OpenGl_Context::ResetErrors (const bool theToPrintErrors)
+bool OpenGl_Context::ResetErrors (const bool theToPrintErrors)
 {
   int aPrevErr = 0;
   int anErr    = ::glGetError();
+  const bool hasError = anErr != GL_NO_ERROR;
   if (!theToPrintErrors)
   {
     for (; anErr != GL_NO_ERROR && aPrevErr != anErr; aPrevErr = anErr, anErr = ::glGetError())
     {
       //
     }
-    return;
+    return hasError;
   }
 
   for (; anErr != GL_NO_ERROR && aPrevErr != anErr; aPrevErr = anErr, anErr = ::glGetError())
@@ -807,6 +850,7 @@ void OpenGl_Context::ResetErrors (const bool theToPrintErrors)
     const TCollection_ExtendedString aMsg = TCollection_ExtendedString ("Unhandled GL error: ") + anErrId;
     PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_OTHER, 0, GL_DEBUG_SEVERITY_LOW, aMsg);
   }
+  return hasError;
 }
 
 // =======================================================================
@@ -934,7 +978,6 @@ static Standard_CString THE_DBGMSG_SEV_HIGH   = "High";   // GL_DEBUG_SEVERITY_H
 static Standard_CString THE_DBGMSG_SEV_MEDIUM = "Medium"; // GL_DEBUG_SEVERITY_MEDIUM
 static Standard_CString THE_DBGMSG_SEV_LOW    = "Low";    // GL_DEBUG_SEVERITY_LOW
 
-#if !defined(GL_ES_VERSION_2_0)
 //! Callback for GL_ARB_debug_output extension
 static void APIENTRY debugCallbackWrap(unsigned int theSource,
                                        unsigned int theType,
@@ -947,7 +990,6 @@ static void APIENTRY debugCallbackWrap(unsigned int theSource,
   OpenGl_Context* aCtx = (OpenGl_Context* )theUserParam;
   aCtx->PushMessage (theSource, theType, theId, theSeverity, theMessage);
 }
-#endif
 
 // =======================================================================
 // function : PushMessage
@@ -1164,6 +1206,8 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
   {
     arbFBOBlit = (OpenGl_ArbFBOBlit* )(&(*myFuncs));
   }
+  extFragDepth = !IsGlGreaterEqual(3, 0)
+               && CheckExtension ("GL_EXT_frag_depth");
   if (IsGlGreaterEqual (3, 1)
    && FindProc ("glTexStorage2DMultisample", myFuncs->glTexStorage2DMultisample))
   {
@@ -1193,6 +1237,37 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
   {
     arbTBO = reinterpret_cast<OpenGl_ArbTBO*> (myFuncs.get());
   }
+
+  // initialize debug context extension
+  if (CheckExtension ("GL_KHR_debug"))
+  {
+    // this functionality become a part of OpenGL ES 3.2
+    arbDbg = NULL;
+    // According to GL_KHR_debug spec, all functions should have KHR suffix.
+    // However, some implementations can export these functions without suffix.
+    if (FindProc ("glDebugMessageControlKHR",  myFuncs->glDebugMessageControl)
+     && FindProc ("glDebugMessageInsertKHR",   myFuncs->glDebugMessageInsert)
+     && FindProc ("glDebugMessageCallbackKHR", myFuncs->glDebugMessageCallback)
+     && FindProc ("glGetDebugMessageLogKHR",   myFuncs->glGetDebugMessageLog))
+    {
+      arbDbg = (OpenGl_ArbDbg* )(&(*myFuncs));
+    }
+
+    if (arbDbg != NULL
+     && caps->contextDebug)
+    {
+      // setup default callback
+      myIsGlDebugCtx = Standard_True;
+      arbDbg->glDebugMessageCallback (debugCallbackWrap, this);
+      ::glEnable (GL_DEBUG_OUTPUT);
+      if (caps->contextSyncDebug)
+      {
+        // note that some broken implementations (e.g. simulators) might generate error message on this call
+        ::glEnable (GL_DEBUG_OUTPUT_SYNCHRONOUS);
+      }
+    }
+  }
+
 #else
 
   myTexClamp = IsGlGreaterEqual (1, 2) ? GL_CLAMP_TO_EDGE : GL_CLAMP;
@@ -1288,32 +1363,15 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
     {
       FindProcShort (glXSwapIntervalSGI);
     }
-    //extSwapTear = CheckExtension (aGlxExts, "GLX_EXT_swap_control_tear");
-#endif
-
-  // initialize debug context extension
-  if (CheckExtension ("GL_ARB_debug_output"))
-  {
-    arbDbg = NULL;
-    if (FindProcShort (glDebugMessageControlARB)
-     && FindProcShort (glDebugMessageInsertARB)
-     && FindProcShort (glDebugMessageCallbackARB)
-     && FindProcShort (glGetDebugMessageLogARB))
-    {
-      arbDbg = (OpenGl_ArbDbg* )(&(*myFuncs));
-    }
-    if (arbDbg != NULL
-     && caps->contextDebug)
+    if (CheckExtension (aGlxExts, "GLX_MESA_query_renderer"))
     {
-      // setup default callback
-      myIsGlDebugCtx = Standard_True;
-      arbDbg->glDebugMessageCallbackARB (debugCallbackWrap, this);
-      if (caps->contextSyncDebug)
-      {
-        ::glEnable (GL_DEBUG_OUTPUT_SYNCHRONOUS);
-      }
+      FindProcShort (glXQueryRendererIntegerMESA);
+      FindProcShort (glXQueryCurrentRendererIntegerMESA);
+      FindProcShort (glXQueryRendererStringMESA);
+      FindProcShort (glXQueryCurrentRendererStringMESA);
     }
-  }
+    //extSwapTear = CheckExtension (aGlxExts, "GLX_EXT_swap_control_tear");
+#endif
 
   // load OpenGL 1.2 new functions
   has12 = IsGlGreaterEqual (1, 2)
@@ -2050,6 +2108,39 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
        && FindProcShort (glBindImageTextures)
        && FindProcShort (glBindVertexBuffers);
 
+  // initialize debug context extension
+  if (CheckExtension ("GL_ARB_debug_output"))
+  {
+    arbDbg = NULL;
+    if (has43)
+    {
+      arbDbg = (OpenGl_ArbDbg* )(&(*myFuncs));
+    }
+    else if (FindProc ("glDebugMessageControlARB",  myFuncs->glDebugMessageControl)
+          && FindProc ("glDebugMessageInsertARB",   myFuncs->glDebugMessageInsert)
+          && FindProc ("glDebugMessageCallbackARB", myFuncs->glDebugMessageCallback)
+          && FindProc ("glGetDebugMessageLogARB",   myFuncs->glGetDebugMessageLog))
+    {
+      arbDbg = (OpenGl_ArbDbg* )(&(*myFuncs));
+    }
+
+    if (arbDbg != NULL
+     && caps->contextDebug)
+    {
+      // setup default callback
+      myIsGlDebugCtx = Standard_True;
+      arbDbg->glDebugMessageCallback (debugCallbackWrap, this);
+      if (has43)
+      {
+        ::glEnable (GL_DEBUG_OUTPUT);
+      }
+      if (caps->contextSyncDebug)
+      {
+        ::glEnable (GL_DEBUG_OUTPUT_SYNCHRONOUS);
+      }
+    }
+  }
+
   // initialize TBO extension (ARB)
   if (!has31
    && CheckExtension ("GL_ARB_texture_buffer_object")
@@ -2216,6 +2307,20 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
   arbTBO = (OpenGl_ArbTBO* )(&(*myFuncs));
   arbIns = (OpenGl_ArbIns* )(&(*myFuncs));
 
+  // check whether ray tracing mode is supported
+  myHasRayTracing = has31
+                 && arbTboRGB32
+                 && arbFBOBlit  != NULL;
+
+  // check whether textures in ray tracing mode are supported
+  myHasRayTracingTextures = myHasRayTracing
+                         && arbTexBindless != NULL;
+
+  // check whether adaptive screen sampling in ray tracing mode is supported
+  myHasRayTracingAdaptiveSampling = myHasRayTracing
+                                 && has44
+                                 && CheckExtension ("GL_NV_shader_atomic_float");
+
   if (!has32)
   {
     checkWrongVersion (3, 2);
@@ -2349,7 +2454,71 @@ Standard_Size OpenGl_Context::AvailableMemory() const
 // =======================================================================
 TCollection_AsciiString OpenGl_Context::MemoryInfo() const
 {
-  TCollection_AsciiString anInfo;
+  TColStd_IndexedDataMapOfStringString aDict;
+  MemoryInfo (aDict);
+
+  TCollection_AsciiString aText;
+  for (TColStd_IndexedDataMapOfStringString::Iterator anIter (aDict); anIter.More(); anIter.Next())
+  {
+    if (!aText.IsEmpty())
+    {
+      aText += "\n";
+    }
+    aText += TCollection_AsciiString("  ") + anIter.Key() + ": " + anIter.Value();
+  }
+  return aText;
+}
+
+// =======================================================================
+// function : MemoryInfo
+// purpose  :
+// =======================================================================
+void OpenGl_Context::MemoryInfo (TColStd_IndexedDataMapOfStringString& theDict) const
+{
+#if defined(GL_ES_VERSION_2_0)
+  (void )theDict;
+#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
+  GLint aGlRendId = 0;
+  CGLGetParameter (CGLGetCurrentContext(), kCGLCPCurrentRendererID, &aGlRendId);
+
+  CGLRendererInfoObj  aRendObj = NULL;
+  CGOpenGLDisplayMask aDispMask = CGDisplayIDToOpenGLDisplayMask (kCGDirectMainDisplay);
+  GLint aRendNb = 0;
+  CGLQueryRendererInfo (aDispMask, &aRendObj, &aRendNb);
+  for (GLint aRendIter = 0; aRendIter < aRendNb; ++aRendIter)
+  {
+    GLint aRendId = 0;
+    if (CGLDescribeRenderer (aRendObj, aRendIter, kCGLRPRendererID, &aRendId) != kCGLNoError
+     || aRendId != aGlRendId)
+    {
+      continue;
+    }
+
+    //kCGLRPVideoMemoryMegabytes   = 131;
+    //kCGLRPTextureMemoryMegabytes = 132;
+    GLint aVMem = 0;
+  #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
+    if (CGLDescribeRenderer(aRendObj, aRendIter, kCGLRPVideoMemoryMegabytes, &aVMem) == kCGLNoError)
+    {
+      addInfo (theDict, "GPU memory",         TCollection_AsciiString() + aVMem + " MiB");
+    }
+    if (CGLDescribeRenderer(aRendObj, aRendIter, kCGLRPTextureMemoryMegabytes, &aVMem) == kCGLNoError)
+    {
+      addInfo (theDict, "GPU Texture memory", TCollection_AsciiString() + aVMem + " MiB");
+    }
+  #else
+    if (CGLDescribeRenderer(aRendObj, aRendIter, kCGLRPVideoMemory, &aVMem) == kCGLNoError)
+    {
+      addInfo (theDict, "GPU memory",         TCollection_AsciiString() + (aVMem / (1024 * 1024)) + " MiB");
+    }
+    if (CGLDescribeRenderer(aRendObj, aRendIter, kCGLRPTextureMemory, &aVMem) == kCGLNoError)
+    {
+      addInfo (theDict, "GPU Texture memory", TCollection_AsciiString() + (aVMem / (1024 * 1024)) + " MiB");
+    }
+  #endif
+  }
+#endif
+
 #if !defined(GL_ES_VERSION_2_0)
   if (atiMem)
   {
@@ -2358,14 +2527,17 @@ TCollection_AsciiString OpenGl_Context::MemoryInfo() const
     glGetIntegerv (GL_VBO_FREE_MEMORY_ATI, aValues);
 
     // total memory free in the pool
-    anInfo += TCollection_AsciiString ("  GPU free memory:    ") + (aValues[0] / 1024) + " MiB\n";
+    addInfo (theDict, "GPU free memory",    TCollection_AsciiString() + (aValues[0] / 1024) + " MiB");
 
-    // largest available free block in the pool
-    anInfo += TCollection_AsciiString ("  Largest free block: ") + (aValues[1] / 1024) + " MiB\n";
+    if (aValues[1] != aValues[0])
+    {
+      // largest available free block in the pool
+      addInfo (theDict, "Largest free block", TCollection_AsciiString() + (aValues[1] / 1024) + " MiB");
+    }
     if (aValues[2] != aValues[0])
     {
       // total auxiliary memory free
-      anInfo += TCollection_AsciiString ("  Free memory:        ") + (aValues[2] / 1024) + " MiB\n";
+      addInfo (theDict, "Free auxiliary memory", TCollection_AsciiString() + (aValues[2] / 1024) + " MiB");
     }
   }
   else if (nvxMem)
@@ -2373,25 +2545,140 @@ TCollection_AsciiString OpenGl_Context::MemoryInfo() const
     //current available dedicated video memory (in KiB), currently unused GPU memory
     GLint aValue = 0;
     glGetIntegerv (GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &aValue);
-    anInfo += TCollection_AsciiString ("  GPU free memory:    ") + (aValue / 1024) + " MiB\n";
+    addInfo (theDict, "GPU free memory", TCollection_AsciiString() + (aValue / 1024) + " MiB");
 
     // dedicated video memory, total size (in KiB) of the GPU memory
     GLint aDedicated = 0;
     glGetIntegerv (GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX, &aDedicated);
-    anInfo += TCollection_AsciiString ("  GPU memory:         ") + (aDedicated / 1024) + " MiB\n";
+    addInfo (theDict, "GPU memory", TCollection_AsciiString() + (aDedicated / 1024) + " MiB");
 
     // total available memory, total size (in KiB) of the memory available for allocations
     glGetIntegerv (GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &aValue);
     if (aValue != aDedicated)
     {
       // different only for special configurations
-      anInfo += TCollection_AsciiString ("  Total memory:       ") + (aValue / 1024) + " MiB\n";
+      addInfo (theDict, "Total memory", TCollection_AsciiString() + (aValue / 1024) + " MiB");
+    }
+  }
+#endif
+
+#if !defined(GL_ES_VERSION_2_0) && !defined(__APPLE__) && !defined(_WIN32)
+  // GLX_RENDERER_VENDOR_ID_MESA
+  if (myFuncs->glXQueryCurrentRendererIntegerMESA != NULL)
+  {
+    unsigned int aVMemMiB = 0;
+    if (myFuncs->glXQueryCurrentRendererIntegerMESA (GLX_RENDERER_VIDEO_MEMORY_MESA, &aVMemMiB) != False)
+    {
+      addInfo (theDict, "GPU memory", TCollection_AsciiString() + int(aVMemMiB) + " MiB");
     }
   }
 #endif
-  return anInfo;
 }
 
+// =======================================================================
+// function : DiagnosticInfo
+// purpose  :
+// =======================================================================
+void OpenGl_Context::DiagnosticInformation (TColStd_IndexedDataMapOfStringString& theDict,
+                                            Graphic3d_DiagnosticInfo theFlags) const
+{
+  if ((theFlags & Graphic3d_DiagnosticInfo_NativePlatform) != 0)
+  {
+  #if defined(HAVE_EGL)
+    addInfo (theDict, "EGLVersion",    ::eglQueryString ((Aspect_Display)myDisplay, EGL_VERSION));
+    addInfo (theDict, "EGLVendor",     ::eglQueryString ((Aspect_Display)myDisplay, EGL_VENDOR));
+    addInfo (theDict, "EGLClientAPIs", ::eglQueryString ((Aspect_Display)myDisplay, EGL_CLIENT_APIS));
+    if ((theFlags & Graphic3d_DiagnosticInfo_Extensions) != 0)
+    {
+      addInfo (theDict, "EGLExtensions", ::eglQueryString ((Aspect_Display)myDisplay, EGL_EXTENSIONS));
+    }
+  #elif defined(_WIN32)
+    if ((theFlags & Graphic3d_DiagnosticInfo_Extensions) != 0
+     && myFuncs->wglGetExtensionsStringARB != NULL)
+    {
+      const char* aWglExts = myFuncs->wglGetExtensionsStringARB ((HDC )myWindowDC);
+      addInfo (theDict, "WGLExtensions", aWglExts);
+    }
+  #elif defined(__APPLE__)
+    //
+  #else
+    Display* aDisplay = (Display*)myDisplay;
+    const int aScreen = DefaultScreen(aDisplay);
+    addInfo (theDict, "GLXDirectRendering", ::glXIsDirect (aDisplay, (GLXContext )myGContext) ? "Yes" : "No");
+    addInfo (theDict, "GLXVendor",  ::glXQueryServerString (aDisplay, aScreen, GLX_VENDOR));
+    addInfo (theDict, "GLXVersion", ::glXQueryServerString (aDisplay, aScreen, GLX_VERSION));
+    if ((theFlags & Graphic3d_DiagnosticInfo_Extensions) != 0)
+    {
+      const char* aGlxExts = ::glXQueryExtensionsString (aDisplay, aScreen);
+      addInfo(theDict, "GLXExtensions", aGlxExts);
+    }
+
+    addInfo (theDict, "GLXClientVendor",  ::glXGetClientString (aDisplay, GLX_VENDOR));
+    addInfo (theDict, "GLXClientVersion", ::glXGetClientString (aDisplay, GLX_VERSION));
+    if ((theFlags & Graphic3d_DiagnosticInfo_Extensions) != 0)
+    {
+      addInfo (theDict, "GLXClientExtensions", ::glXGetClientString (aDisplay, GLX_EXTENSIONS));
+    }
+  #endif
+  }
+
+  if ((theFlags & Graphic3d_DiagnosticInfo_Device) != 0)
+  {
+    addInfo (theDict, "GLvendor",    (const char*)::glGetString (GL_VENDOR));
+    addInfo (theDict, "GLdevice",    (const char*)::glGetString (GL_RENDERER));
+    addInfo (theDict, "GLversion",   (const char*)::glGetString (GL_VERSION));
+    addInfo (theDict, "GLSLversion", (const char*)::glGetString (GL_SHADING_LANGUAGE_VERSION));
+    if (myIsGlDebugCtx)
+    {
+      addInfo (theDict, "GLdebug", "ON");
+    }
+  }
+
+  if ((theFlags & Graphic3d_DiagnosticInfo_Limits) != 0)
+  {
+    addInfo (theDict, "Max texture size", TCollection_AsciiString(myMaxTexDim));
+    addInfo (theDict, "Max MSAA samples", TCollection_AsciiString(myMaxMsaaSamples));
+  }
+
+  if ((theFlags & Graphic3d_DiagnosticInfo_FrameBuffer) != 0)
+  {
+    GLint aViewport[4] = {};
+    ::glGetIntegerv (GL_VIEWPORT, aViewport);
+    addInfo (theDict, "Viewport", TCollection_AsciiString() + aViewport[2] + "x" + aViewport[3]);
+  }
+
+  if ((theFlags & Graphic3d_DiagnosticInfo_Memory) != 0)
+  {
+    MemoryInfo (theDict);
+  }
+
+  if ((theFlags & Graphic3d_DiagnosticInfo_Extensions) != 0)
+  {
+  #if !defined(GL_ES_VERSION_2_0)
+    if (IsGlGreaterEqual (3, 0)
+     && myFuncs->glGetStringi != NULL)
+    {
+      TCollection_AsciiString anExtList;
+      GLint anExtNb = 0;
+      ::glGetIntegerv (GL_NUM_EXTENSIONS, &anExtNb);
+      for (GLint anIter = 0; anIter < anExtNb; ++anIter)
+      {
+        const char* anExtension = (const char*)myFuncs->glGetStringi (GL_EXTENSIONS, (GLuint)anIter);
+        if (!anExtList.IsEmpty())
+        {
+          anExtList += " ";
+        }
+        anExtList += anExtension;
+      }
+      addInfo(theDict, "GLextensions", anExtList);
+    }
+    else
+  #endif
+    {
+      addInfo (theDict, "GLextensions", (const char*)::glGetString (GL_EXTENSIONS));
+    }
+  }
+}
 
 // =======================================================================
 // function : GetResource
@@ -2506,6 +2793,10 @@ Standard_Boolean OpenGl_Context::BindProgram (const Handle(OpenGl_ShaderProgram)
   {
     return Standard_False;
   }
+  else if (myActiveProgram == theProgram)
+  {
+    return Standard_True;
+  }
 
   if (theProgram.IsNull()
   || !theProgram->IsValid())
@@ -2556,51 +2847,100 @@ Handle(OpenGl_FrameBuffer) OpenGl_Context::SetDefaultFrameBuffer (const Handle(O
 // purpose  :
 // =======================================================================
 void OpenGl_Context::SetShadingMaterial (const OpenGl_AspectFace* theAspect,
-                                         const OpenGl_Vec4* theHighlightColor)
+                                         const Handle(Graphic3d_PresentationAttributes)& theHighlight,
+                                         const Standard_Boolean theUseDepthWrite,
+                                         Standard_Integer& theRenderingPassFlags)
 {
-  if (!myActiveProgram.IsNull())
+  const Handle(Graphic3d_AspectFillArea3d)& anAspect = (!theHighlight.IsNull() && !theHighlight->BasicFillAreaAspect().IsNull())
+                                                      ?  theHighlight->BasicFillAreaAspect()
+                                                      :  theAspect->Aspect();
+
+  const bool toDistinguish = anAspect->Distinguish();
+  const bool toMapTexture  = anAspect->ToMapTexture();
+  const Graphic3d_MaterialAspect& aMatFrontSrc = anAspect->FrontMaterial();
+  const Graphic3d_MaterialAspect& aMatBackSrc  = toDistinguish
+                                               ? anAspect->BackMaterial()
+                                               : aMatFrontSrc;
+  const Quantity_Color& aFrontIntColor = anAspect->InteriorColor();
+  const Quantity_Color& aBackIntColor  = toDistinguish
+                                       ? anAspect->BackInteriorColor()
+                                       : aFrontIntColor;
+
+  myMatFront.Init (aMatFrontSrc, aFrontIntColor);
+  if (toDistinguish)
+  {
+    myMatBack.Init (aMatBackSrc, aBackIntColor);
+  }
+  else
   {
-    myActiveProgram->SetUniform (this,
-                                 myActiveProgram->GetStateLocation (OpenGl_OCCT_TEXTURE_ENABLE),
-                                 theAspect->Aspect()->ToMapTexture() ? 1 : 0);
-    myActiveProgram->SetUniform (this,
-                                 myActiveProgram->GetStateLocation (OpenGl_OCCT_DISTINGUISH_MODE),
-                                 theAspect->Aspect()->Distinguish() ? 1 : 0);
+    myMatBack = myMatFront;
+  }
 
-    OpenGl_Material aParams;
-    for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
+  // handling transparency
+  float aTranspFront = (float )aMatFrontSrc.Transparency();
+  float aTranspBack  = (float )aMatBackSrc .Transparency();
+  if (!theHighlight.IsNull()
+    && theHighlight->BasicFillAreaAspect().IsNull())
+  {
+    myMatFront.SetColor (theHighlight->ColorRGBA());
+    myMatBack .SetColor (theHighlight->ColorRGBA());
+    aTranspFront = theHighlight->Transparency();
+    aTranspBack  = theHighlight->Transparency();
+  }
+  if ((theRenderingPassFlags & OPENGL_NS_2NDPASSDO) != 0)
+  {
+    // second pass
+    myMatFront.Diffuse.a() = aMatFrontSrc.EnvReflexion();
+    myMatBack .Diffuse.a() = aMatBackSrc .EnvReflexion();
+  }
+  else
+  {
+    if (aMatFrontSrc.EnvReflexion() != 0.0f
+     || aMatBackSrc .EnvReflexion() != 0.0f)
     {
-      const GLint aLoc = myActiveProgram->GetStateLocation (anIndex == 0
-                                                          ? OpenGl_OCCT_FRONT_MATERIAL
-                                                          : OpenGl_OCCT_BACK_MATERIAL);
-      if (aLoc == OpenGl_ShaderProgram::INVALID_LOCATION)
-      {
-        continue;
-      }
-
-      if (anIndex == 0 || !theAspect->Aspect()->Distinguish())
-      {
-        const Graphic3d_MaterialAspect& aSrcMat      = theAspect->Aspect()->FrontMaterial();
-        const Quantity_Color&           aSrcIntColor = theAspect->Aspect()->InteriorColor();
-        aParams.Init (aSrcMat, aSrcIntColor);
-        aParams.Diffuse.a() = 1.0f - (float )aSrcMat.Transparency();
-      }
-      else
-      {
-        const Graphic3d_MaterialAspect& aSrcMat      = theAspect->Aspect()->BackMaterial();
-        const Quantity_Color&           aSrcIntColor = theAspect->Aspect()->BackInteriorColor();
-        aParams.Init (aSrcMat, aSrcIntColor);
-        aParams.Diffuse.a() = 1.0f - (float )aSrcMat.Transparency();
-      }
-      if (theHighlightColor != NULL)
-      {
-        aParams.SetColor (*theHighlightColor);
-      }
+      // if the material reflects the environment scene, the second pass is needed
+      theRenderingPassFlags |= OPENGL_NS_2NDPASSNEED;
+    }
 
-      myActiveProgram->SetUniform (this, aLoc, OpenGl_Material::NbOfVec4(),
-                                   aParams.Packed());
+    GLboolean aDepthMask = GL_TRUE;
+    if (aTranspFront != 0.0f
+     || aTranspBack  != 0.0f)
+    {
+      // render transparent
+      myMatFront.Diffuse.a() = 1.0f - aTranspFront;
+      myMatBack .Diffuse.a() = 1.0f - aTranspBack;
+      glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+      glEnable (GL_BLEND);
+      aDepthMask = GL_FALSE;
     }
+    else
+    {
+      // render opaque
+      glBlendFunc (GL_ONE, GL_ZERO);
+      glDisable (GL_BLEND);
+    }
+    if (theUseDepthWrite)
+    {
+      glDepthMask (aDepthMask);
+    }
+  }
+
+  // do not update material properties in case of zero reflection mode,
+  // because GL lighting will be disabled by OpenGl_PrimitiveArray::DrawArray() anyway.
+  if (theAspect->IsNoLighting())
+  {
+    return;
   }
+
+  if (myMatFront    == myShaderManager->MaterialState().FrontMaterial()
+   && myMatBack     == myShaderManager->MaterialState().BackMaterial()
+   && toDistinguish == myShaderManager->MaterialState().ToDistinguish()
+   && toMapTexture  == myShaderManager->MaterialState().ToMapTexture())
+  {
+    return;
+  }
+
+  myShaderManager->UpdateMaterialStateTo (myMatFront, myMatBack, toDistinguish, toMapTexture);
 }
 
 // =======================================================================
@@ -2646,6 +2986,7 @@ void OpenGl_Context::SetTypeOfLine (const Aspect_TypeOfLine  theType,
       aPattern = 0xFF18;
       break;
     }
+    case Aspect_TOL_EMPTY:
     case Aspect_TOL_SOLID:
     {
       aPattern = 0xFFFF;
@@ -2666,7 +3007,7 @@ void OpenGl_Context::SetTypeOfLine (const Aspect_TypeOfLine  theType,
   }
 
 #if !defined(GL_ES_VERSION_2_0)
-  if (theType != Aspect_TOL_SOLID)
+  if (aPattern != 0xFFFF)
   {
   #ifdef HAVE_GL2PS
     if (IsFeedback())
@@ -2845,20 +3186,80 @@ Standard_Boolean OpenGl_Context::SetGlNormalizeEnabled (Standard_Boolean isEnabl
 }
 
 // =======================================================================
-// function : ApplyModelWorldMatrix
+// function : SetPolygonMode
 // purpose  :
 // =======================================================================
-void OpenGl_Context::ApplyModelWorldMatrix()
+Standard_Integer OpenGl_Context::SetPolygonMode (const Standard_Integer theMode)
 {
-#if !defined(GL_ES_VERSION_2_0)
-  if (core11 != NULL)
+  if (myPolygonMode == theMode)
   {
-    core11->glMatrixMode (GL_MODELVIEW);
-    core11->glLoadMatrixf (ModelWorldState.Current());
+    return myPolygonMode;
   }
+
+  const Standard_Integer anOldPolygonMode = myPolygonMode;
+
+  myPolygonMode = theMode;
+
+#if !defined(GL_ES_VERSION_2_0)
+  ::glPolygonMode (GL_FRONT_AND_BACK, (GLenum)theMode);
 #endif
 
-  if (!myShaderManager->IsEmpty())
+  return anOldPolygonMode;
+}
+
+// =======================================================================
+// function : SetPolygonHatchEnabled
+// purpose  :
+// =======================================================================
+bool OpenGl_Context::SetPolygonHatchEnabled (const bool theIsEnabled)
+{
+  if (myHatchStyles.IsNull())
+  {
+    return false;
+  }
+  else if (myHatchStyles->IsEnabled() == theIsEnabled)
+  {
+    return theIsEnabled;
+  }
+
+  return myHatchStyles->SetEnabled (this, theIsEnabled);
+}
+
+// =======================================================================
+// function : SetPolygonHatchStyle
+// purpose  :
+// =======================================================================
+Standard_Integer OpenGl_Context::SetPolygonHatchStyle (const Handle(Graphic3d_HatchStyle)& theStyle)
+{
+  if (theStyle.IsNull())
+  {
+    return 0;
+  }
+
+  if (myHatchStyles.IsNull())
+  {
+    if (!GetResource ("OpenGl_LineAttributes", myHatchStyles))
+    {
+      // share and register for release once the resource is no longer used
+      myHatchStyles = new OpenGl_LineAttributes();
+      ShareResource ("OpenGl_LineAttributes", myHatchStyles);
+    }
+  }
+  if (myHatchStyles->TypeOfHatch() == theStyle->HatchType())
+  {
+    return theStyle->HatchType();
+  }
+
+  return myHatchStyles->SetTypeOfHatch (this, theStyle);
+}
+
+// =======================================================================
+// function : ApplyModelWorldMatrix
+// purpose  :
+// =======================================================================
+void OpenGl_Context::ApplyModelWorldMatrix()
+{
+  if (myShaderManager->ModelWorldState().ModelWorldMatrix() != ModelWorldState.Current())
   {
     myShaderManager->UpdateModelWorldStateTo (ModelWorldState.Current());
   }
@@ -2870,17 +3271,12 @@ void OpenGl_Context::ApplyModelWorldMatrix()
 // =======================================================================
 void OpenGl_Context::ApplyWorldViewMatrix()
 {
-#if !defined(GL_ES_VERSION_2_0)
-  if (core11 != NULL)
+  if (myShaderManager->ModelWorldState().ModelWorldMatrix() != THE_IDENTITY_MATRIX)
   {
-    core11->glMatrixMode (GL_MODELVIEW);
-    core11->glLoadMatrixf (WorldViewState.Current());
+    myShaderManager->UpdateModelWorldStateTo (THE_IDENTITY_MATRIX);
   }
-#endif
-
-  if (!myShaderManager->IsEmpty())
+  if (myShaderManager->WorldViewState().WorldViewMatrix() != WorldViewState.Current())
   {
-    myShaderManager->UpdateModelWorldStateTo (THE_IDENTITY_MATRIX);
     myShaderManager->UpdateWorldViewStateTo (WorldViewState.Current());
   }
 }
@@ -2891,19 +3287,13 @@ void OpenGl_Context::ApplyWorldViewMatrix()
 // =======================================================================
 void OpenGl_Context::ApplyModelViewMatrix()
 {
-#if !defined(GL_ES_VERSION_2_0)
-  if (core11 != NULL)
+  if (myShaderManager->ModelWorldState().ModelWorldMatrix() != ModelWorldState.Current())
   {
-    OpenGl_Mat4 aModelView = WorldViewState.Current() * ModelWorldState.Current();
-    core11->glMatrixMode (GL_MODELVIEW);
-    core11->glLoadMatrixf (aModelView.GetData());
+    myShaderManager->UpdateModelWorldStateTo (ModelWorldState.Current());
   }
-#endif
-
-  if (!myShaderManager->IsEmpty())
+  if (myShaderManager->WorldViewState().WorldViewMatrix() != WorldViewState.Current())
   {
-    myShaderManager->UpdateModelWorldStateTo (ModelWorldState.Current());
-    myShaderManager->UpdateWorldViewStateTo (WorldViewState.Current());
+    myShaderManager->UpdateWorldViewStateTo  (WorldViewState.Current());
   }
 }
 
@@ -2913,21 +3303,12 @@ void OpenGl_Context::ApplyModelViewMatrix()
 // =======================================================================
 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())
+  if (myShaderManager->ProjectionState().ProjectionMatrix() != ProjectionState.Current())
   {
     myShaderManager->UpdateProjectionStateTo (ProjectionState.Current());
   }
 }
 
-
 // =======================================================================
 // function : EnableFeatures
 // purpose  :