1 // Created on: 2012-01-26
2 // Created by: Kirill GAVRILOV
3 // Copyright (c) 2012-2014 OPEN CASCADE SAS
5 // This file is part of Open CASCADE Technology software library.
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
20 #include <OpenGl_Context.hxx>
22 #include <OpenGl_ArbTBO.hxx>
23 #include <OpenGl_ArbIns.hxx>
24 #include <OpenGl_ArbDbg.hxx>
25 #include <OpenGl_ArbFBO.hxx>
26 #include <OpenGl_ExtGS.hxx>
27 #include <OpenGl_ArbSamplerObject.hxx>
28 #include <OpenGl_ArbTexBindless.hxx>
29 #include <OpenGl_GlCore46.hxx>
30 #include <OpenGl_FrameBuffer.hxx>
31 #include <OpenGl_FrameStats.hxx>
32 #include <OpenGl_Sampler.hxx>
33 #include <OpenGl_ShaderManager.hxx>
34 #include <OpenGl_TextureSetPairIterator.hxx>
35 #include <OpenGl_Workspace.hxx>
36 #include <OpenGl_Aspects.hxx>
38 #include <Graphic3d_TransformUtils.hxx>
39 #include <Graphic3d_RenderingParams.hxx>
40 #include <Image_SupportedFormats.hxx>
41 #include <Message_Messenger.hxx>
42 #include <NCollection_Vector.hxx>
43 #include <Standard_ProgramError.hxx>
44 #include <Standard_WarningDisableFunctionCast.hxx>
46 #if defined(_WIN32) && defined(max)
51 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Context,Standard_Transient)
56 #pragma comment(lib, "libEGL.lib")
60 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
62 #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
65 #include <OpenGL/OpenGL.h>
66 #include <CoreGraphics/CoreGraphics.h>
69 #include <GL/glx.h> // glXGetProcAddress()
73 #include <emscripten.h>
74 #include <emscripten/html5.h>
76 //! Check if WebGL extension is available and activate it
77 //! (usage of extension without activation will generate errors).
78 static bool checkEnableWebGlExtension (const OpenGl_Context& theCtx,
79 const char* theExtName)
81 if (!theCtx.CheckExtension (theExtName))
85 if (EMSCRIPTEN_WEBGL_CONTEXT_HANDLE aWebGlCtx = emscripten_webgl_get_current_context())
87 if (emscripten_webgl_enable_extension (aWebGlCtx, theExtName))
98 static const Handle(OpenGl_Resource) NULL_GL_RESOURCE;
99 static const OpenGl_Mat4 THE_IDENTITY_MATRIX;
101 //! Add key-value pair to the dictionary.
102 static void addInfo (TColStd_IndexedDataMapOfStringString& theDict,
103 const TCollection_AsciiString& theKey,
104 const TCollection_AsciiString& theValue)
106 theDict.ChangeFromIndex (theDict.Add (theKey, theValue)) = theValue;
109 //! Add key-value pair to the dictionary.
110 static void addInfo (TColStd_IndexedDataMapOfStringString& theDict,
111 const TCollection_AsciiString& theKey,
112 const char* theValue)
114 TCollection_AsciiString aValue (theValue != NULL ? theValue : "");
115 theDict.ChangeFromIndex (theDict.Add (theKey, aValue)) = aValue;
119 // =======================================================================
120 // function : OpenGl_Context
122 // =======================================================================
123 OpenGl_Context::OpenGl_Context (const Handle(OpenGl_Caps)& theCaps)
139 caps (!theCaps.IsNull() ? theCaps : new OpenGl_Caps()),
140 hasGetBufferData (Standard_False),
141 #if defined(GL_ES_VERSION_2_0)
142 hasPackRowLength (Standard_False),
143 hasUnpackRowLength (Standard_False),
144 hasHighp (Standard_False),
145 hasUintIndex(Standard_False),
146 hasTexRGBA8(Standard_False),
148 hasPackRowLength (Standard_True),
149 hasUnpackRowLength (Standard_True),
150 hasHighp (Standard_True),
151 hasUintIndex(Standard_True),
152 hasTexRGBA8(Standard_True),
154 hasTexFloatLinear (Standard_False),
155 hasTexSRGB (Standard_False),
156 hasFboSRGB (Standard_False),
157 hasSRGBControl (Standard_False),
158 hasFboRenderMipmap (Standard_False),
159 #if defined(GL_ES_VERSION_2_0)
160 hasFlatShading (OpenGl_FeatureNotAvailable),
162 hasFlatShading (OpenGl_FeatureInCore),
164 hasGlslBitwiseOps (OpenGl_FeatureNotAvailable),
165 hasDrawBuffers (OpenGl_FeatureNotAvailable),
166 hasFloatBuffer (OpenGl_FeatureNotAvailable),
167 hasHalfFloatBuffer (OpenGl_FeatureNotAvailable),
168 hasSampleVariables (OpenGl_FeatureNotAvailable),
169 hasGeometryStage (OpenGl_FeatureNotAvailable),
170 arbDrawBuffers (Standard_False),
171 arbNPTW (Standard_False),
172 arbTexRG (Standard_False),
173 arbTexFloat (Standard_False),
174 arbSamplerObject (NULL),
175 arbTexBindless (NULL),
177 arbTboRGB32 (Standard_False),
178 arbClipControl (Standard_False),
183 arbSampleShading (Standard_False),
184 arbDepthClamp (Standard_False),
185 extFragDepth (Standard_False),
186 extDrawBuffers (Standard_False),
188 extBgra(Standard_False),
189 extAnis(Standard_False),
190 extPDS (Standard_False),
191 atiMem (Standard_False),
192 nvxMem (Standard_False),
193 oesSampleVariables (Standard_False),
194 oesStdDerivatives (Standard_False),
195 mySharedResources (new OpenGl_ResourcesMap()),
196 myDelayed (new OpenGl_DelayReleaseMap()),
197 myUnusedResources (new OpenGl_ResourcesStack()),
199 myGlLibHandle (NULL),
200 myFuncs (new OpenGl_GlFunctions()),
201 mySupportedFormats (new Image_SupportedFormats()),
203 myTexClamp (GL_CLAMP_TO_EDGE),
205 myMaxTexCombined (1),
206 myMaxTexUnitsFFP (1),
207 myMaxDumpSizeX (1024),
208 myMaxDumpSizeY (1024),
211 myMaxDrawBuffers (1),
212 myMaxColorAttachments (1),
215 myIsInitialized (Standard_False),
216 myIsStereoBuffers (Standard_False),
217 myIsGlNormalizeEnabled (Standard_False),
218 mySpriteTexUnit (Graphic3d_TextureUnit_PointSprite),
219 myHasRayTracing (Standard_False),
220 myHasRayTracingTextures (Standard_False),
221 myHasRayTracingAdaptiveSampling (Standard_False),
222 myHasRayTracingAdaptiveSamplingAtomic (Standard_False),
223 myHasPBR (Standard_False),
224 myPBREnvLUTTexUnit (Graphic3d_TextureUnit_PbrEnvironmentLUT),
225 myPBRDiffIBLMapSHTexUnit (Graphic3d_TextureUnit_PbrIblDiffuseSH),
226 myPBRSpecIBLMapTexUnit (Graphic3d_TextureUnit_PbrIblSpecular),
227 myShadowMapTexUnit (Graphic3d_TextureUnit_ShadowMap),
228 myDepthPeelingDepthTexUnit (Graphic3d_TextureUnit_DepthPeelingDepth),
229 myDepthPeelingFrontColorTexUnit (Graphic3d_TextureUnit_DepthPeelingFrontColor),
230 myFrameStats (new OpenGl_FrameStats()),
231 myActiveMockTextures (0),
232 myActiveHatchType (Aspect_HS_SOLID),
233 myHatchIsEnabled (false),
234 #if !defined(GL_ES_VERSION_2_0)
235 myPointSpriteOrig (GL_UPPER_LEFT),
236 myRenderMode (GL_RENDER),
237 myShadeModel (GL_SMOOTH),
238 myPolygonMode (GL_FILL),
240 myPointSpriteOrig (0),
245 myToCullBackFaces (false),
247 myDrawBuffers (0, 7),
250 myAlphaToCoverage (false),
251 myIsGlDebugCtx (false),
252 myIsSRgbWindow (false),
253 myResolution (Graphic3d_RenderingParams::THE_DEFAULT_RESOLUTION),
254 myResolutionRatio (1.0f),
255 myLineWidthScale (1.0f),
256 myLineFeather (1.0f),
257 myRenderScale (1.0f),
258 myRenderScaleInv (1.0f)
264 myViewportVirt[0] = 0;
265 myViewportVirt[1] = 0;
266 myViewportVirt[2] = 0;
267 myViewportVirt[3] = 0;
269 myPolygonOffset.Mode = Aspect_POM_Off;
270 myPolygonOffset.Factor = 0.0f;
271 myPolygonOffset.Units = 0.0f;
273 // system-dependent fields
274 #if defined(HAVE_EGL)
275 myDisplay = (Aspect_Display )EGL_NO_DISPLAY;
276 myWindow = (Aspect_Drawable )EGL_NO_SURFACE;
277 myGContext = (Aspect_RenderingContext )EGL_NO_CONTEXT;
278 #elif defined(_WIN32)
282 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
283 // Vendors can not extend functionality on this system
284 // and developers are limited to OpenGL support provided by Mac OS X SDK.
285 // We retrieve function pointers from system library
286 // to generalize extensions support on all platforms.
287 // In this way we also reach binary compatibility benefit between OS releases
288 // if some newest functionality is optionally used.
289 // Notice that GL version / extension availability checks are required
290 // because function pointers may be available but not functionality itself
291 // (depends on renderer).
292 #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
294 myGlLibHandle = dlopen ("/System/Library/Frameworks/OpenGLES.framework/OpenGLES", RTLD_LAZY);
297 myGlLibHandle = dlopen ("/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL", RTLD_LAZY);
305 memset (myFuncs.operator->(), 0, sizeof(OpenGl_GlFunctions));
306 myShaderManager = new OpenGl_ShaderManager (this);
309 // =======================================================================
310 // function : ~OpenGl_Context
312 // =======================================================================
313 OpenGl_Context::~OpenGl_Context()
315 // release clean up queue
318 #if !defined(GL_ES_VERSION_2_0)
319 // release default VAO
320 if (myDefaultVao != 0
324 core32->glDeleteVertexArrays (1, &myDefaultVao);
329 // release mock textures
330 if (!myTextureRgbaBlack.IsNull())
332 myTextureRgbaBlack->Release (this);
333 myTextureRgbaBlack.Nullify();
335 if (!myTextureRgbaWhite.IsNull())
337 myTextureRgbaWhite->Release (this);
338 myTextureRgbaWhite.Nullify();
341 // release default FBO
342 if (!myDefaultFbo.IsNull())
344 myDefaultFbo->Release (this);
345 myDefaultFbo.Nullify();
348 // release shared resources if any
349 if (mySharedResources->GetRefCount() <= 1)
351 myShaderManager.Nullify();
352 for (NCollection_DataMap<TCollection_AsciiString, Handle(OpenGl_Resource)>::Iterator anIter (*mySharedResources);
353 anIter.More(); anIter.Next())
355 anIter.Value()->Release (this);
358 // release delayed resources added during deletion of shared resources
359 while (!myUnusedResources->IsEmpty())
361 myUnusedResources->First()->Release (this);
362 myUnusedResources->RemoveFirst();
365 else if (myShaderManager->IsSameContext (this))
367 myShaderManager->SetContext (NULL);
369 mySharedResources.Nullify();
377 #if !defined(GL_ES_VERSION_2_0)
379 glGetPointerv (GL_DEBUG_CALLBACK_USER_PARAM, &aPtr);
383 arbDbg->glDebugMessageCallback (NULL, NULL);
385 myIsGlDebugCtx = Standard_False;
389 // =======================================================================
390 // function : forcedRelease
392 // =======================================================================
393 void OpenGl_Context::forcedRelease()
396 for (NCollection_DataMap<TCollection_AsciiString, Handle(OpenGl_Resource)>::Iterator anIter (*mySharedResources);
397 anIter.More(); anIter.Next())
399 anIter.Value()->Release (this);
401 mySharedResources->Clear();
402 myShaderManager->clear();
403 myShaderManager->SetContext (NULL);
405 // release delayed resources added during deletion of shared resources
406 while (!myUnusedResources->IsEmpty())
408 myUnusedResources->First()->Release (this);
409 myUnusedResources->RemoveFirst();
413 // =======================================================================
414 // function : ResizeViewport
416 // =======================================================================
417 void OpenGl_Context::ResizeViewport (const Standard_Integer* theRect)
419 core11fwd->glViewport (theRect[0], theRect[1], theRect[2], theRect[3]);
420 myViewport[0] = theRect[0];
421 myViewport[1] = theRect[1];
422 myViewport[2] = theRect[2];
423 myViewport[3] = theRect[3];
424 if (HasRenderScale())
426 myViewportVirt[0] = Standard_Integer(theRect[0] * myRenderScaleInv);
427 myViewportVirt[1] = Standard_Integer(theRect[1] * myRenderScaleInv);
428 myViewportVirt[2] = Standard_Integer(theRect[2] * myRenderScaleInv);
429 myViewportVirt[3] = Standard_Integer(theRect[3] * myRenderScaleInv);
433 myViewportVirt[0] = theRect[0];
434 myViewportVirt[1] = theRect[1];
435 myViewportVirt[2] = theRect[2];
436 myViewportVirt[3] = theRect[3];
440 #if !defined(GL_ES_VERSION_2_0)
441 inline Standard_Integer stereoToMonoBuffer (const Standard_Integer theBuffer)
457 // =======================================================================
458 // function : SetReadBuffer
460 // =======================================================================
461 void OpenGl_Context::SetReadBuffer (const Standard_Integer theReadBuffer)
463 #if !defined(GL_ES_VERSION_2_0)
464 myReadBuffer = !myIsStereoBuffers ? stereoToMonoBuffer (theReadBuffer) : theReadBuffer;
465 if (myReadBuffer < GL_COLOR_ATTACHMENT0
468 arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
470 ::glReadBuffer (myReadBuffer);
472 (void )theReadBuffer;
476 // =======================================================================
477 // function : SetDrawBuffer
479 // =======================================================================
480 void OpenGl_Context::SetDrawBuffer (const Standard_Integer theDrawBuffer)
482 #if !defined(GL_ES_VERSION_2_0)
483 const Standard_Integer aDrawBuffer = !myIsStereoBuffers ? stereoToMonoBuffer (theDrawBuffer) : theDrawBuffer;
484 if (aDrawBuffer < GL_COLOR_ATTACHMENT0
487 arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
489 ::glDrawBuffer (aDrawBuffer);
491 myDrawBuffers.Init (GL_NONE);
492 myDrawBuffers.SetValue (0, aDrawBuffer);
494 (void )theDrawBuffer;
498 // =======================================================================
499 // function : SetDrawBuffers
501 // =======================================================================
502 void OpenGl_Context::SetDrawBuffers (const Standard_Integer theNb, const Standard_Integer* theDrawBuffers)
504 Standard_ASSERT_RETURN (hasDrawBuffers, "Multiple draw buffers feature is not supported by the context", Standard_ASSERT_DO_NOTHING());
506 if (myDrawBuffers.Length() < theNb)
508 // should actually never happen here
509 myDrawBuffers.Resize (0, theNb - 1, false);
511 myDrawBuffers.Init (GL_NONE);
513 Standard_Boolean useDefaultFbo = Standard_False;
514 for (Standard_Integer anI = 0; anI < theNb; ++anI)
516 if (theDrawBuffers[anI] < GL_COLOR_ATTACHMENT0 && theDrawBuffers[anI] != GL_NONE)
518 useDefaultFbo = Standard_True;
522 myDrawBuffers.SetValue (anI, theDrawBuffers[anI]);
525 if (arbFBO != NULL && useDefaultFbo)
527 arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
530 myFuncs->glDrawBuffers (theNb, (const GLenum*)theDrawBuffers);
533 // =======================================================================
534 // function : SetFrameBufferSRGB
536 // =======================================================================
537 void OpenGl_Context::SetFrameBufferSRGB (bool theIsFbo, bool theIsFboSRgb)
541 myIsSRgbActive = false;
544 myIsSRgbActive = ToRenderSRGB()
545 && (theIsFbo || myIsSRgbWindow)
554 core11fwd->glEnable (GL_FRAMEBUFFER_SRGB);
558 core11fwd->glDisable (GL_FRAMEBUFFER_SRGB);
562 // =======================================================================
563 // function : SetCullBackFaces
565 // =======================================================================
566 void OpenGl_Context::SetCullBackFaces (bool theToEnable)
568 if (myToCullBackFaces == theToEnable)
573 myToCullBackFaces = theToEnable;
576 //glCullFace (GL_BACK); GL_BACK by default
577 core11fwd->glEnable (GL_CULL_FACE);
581 core11fwd->glDisable (GL_CULL_FACE);
585 // =======================================================================
586 // function : FetchState
588 // =======================================================================
589 void OpenGl_Context::FetchState()
591 #if !defined(GL_ES_VERSION_2_0)
592 // cache feedback mode state
593 if (core11ffp != NULL)
595 ::glGetIntegerv (GL_RENDER_MODE, &myRenderMode);
596 ::glGetIntegerv (GL_SHADE_MODEL, &myShadeModel);
599 // cache read buffers state
600 ::glGetIntegerv (GL_READ_BUFFER, &myReadBuffer);
602 // cache draw buffers state
603 if (myDrawBuffers.Length() < myMaxDrawBuffers)
605 myDrawBuffers.Resize (0, myMaxDrawBuffers - 1, false);
607 myDrawBuffers.Init (GL_NONE);
609 Standard_Integer aDrawBuffer = GL_NONE;
610 if (myMaxDrawBuffers == 1)
612 ::glGetIntegerv (GL_DRAW_BUFFER, &aDrawBuffer);
613 myDrawBuffers.SetValue (0, aDrawBuffer);
617 for (Standard_Integer anI = 0; anI < myMaxDrawBuffers; ++anI)
619 ::glGetIntegerv (GL_DRAW_BUFFER0 + anI, &aDrawBuffer);
620 myDrawBuffers.SetValue (anI, aDrawBuffer);
626 // =======================================================================
629 // =======================================================================
630 void OpenGl_Context::Share (const Handle(OpenGl_Context)& theShareCtx)
632 if (!theShareCtx.IsNull())
634 mySharedResources = theShareCtx->mySharedResources;
635 myDelayed = theShareCtx->myDelayed;
636 myUnusedResources = theShareCtx->myUnusedResources;
637 myShaderManager = theShareCtx->myShaderManager;
641 #if !defined(__APPLE__) || defined(MACOSX_USE_GLX)
643 // =======================================================================
644 // function : IsCurrent
646 // =======================================================================
647 Standard_Boolean OpenGl_Context::IsCurrent() const
649 #if defined(HAVE_EGL)
650 if ((EGLDisplay )myDisplay == EGL_NO_DISPLAY
651 || (EGLContext )myGContext == EGL_NO_CONTEXT)
653 return Standard_False;
656 return (((EGLDisplay )myDisplay == eglGetCurrentDisplay())
657 && ((EGLContext )myGContext == eglGetCurrentContext())
658 && ((EGLSurface )myWindow == eglGetCurrentSurface (EGL_DRAW)));
659 #elif defined(_WIN32)
660 if (myWindowDC == NULL || myGContext == NULL)
662 return Standard_False;
664 return (( (HDC )myWindowDC == wglGetCurrentDC())
665 && ((HGLRC )myGContext == wglGetCurrentContext()));
667 if (myDisplay == NULL || myWindow == 0 || myGContext == 0)
669 return Standard_False;
672 return ( ((Display* )myDisplay == glXGetCurrentDisplay())
673 && ((GLXContext )myGContext == glXGetCurrentContext())
674 && ((GLXDrawable )myWindow == glXGetCurrentDrawable()));
678 // =======================================================================
679 // function : MakeCurrent
681 // =======================================================================
682 Standard_Boolean OpenGl_Context::MakeCurrent()
684 #if defined(HAVE_EGL)
685 if ((EGLDisplay )myDisplay == EGL_NO_DISPLAY
686 || (EGLContext )myGContext == EGL_NO_CONTEXT)
688 Standard_ProgramError_Raise_if (myIsInitialized, "OpenGl_Context::Init() should be called before!");
689 return Standard_False;
692 if (eglMakeCurrent ((EGLDisplay )myDisplay, (EGLSurface )myWindow, (EGLSurface )myWindow, (EGLContext )myGContext) != EGL_TRUE)
694 // if there is no current context it might be impossible to use glGetError() correctly
695 PushMessage (GL_DEBUG_SOURCE_WINDOW_SYSTEM, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
696 "eglMakeCurrent() has failed!");
697 myIsInitialized = Standard_False;
698 return Standard_False;
700 #elif defined(_WIN32)
701 if (myWindowDC == NULL || myGContext == NULL)
703 Standard_ProgramError_Raise_if (myIsInitialized, "OpenGl_Context::Init() should be called before!");
704 return Standard_False;
707 // technically it should be safe to activate already bound GL context
708 // however some drivers (Intel etc.) may FAIL doing this for unknown reason
711 myShaderManager->SetContext (this);
712 return Standard_True;
714 else if (wglMakeCurrent ((HDC )myWindowDC, (HGLRC )myGContext) != TRUE)
716 // notice that glGetError() couldn't be used here!
717 wchar_t* aMsgBuff = NULL;
718 DWORD anErrorCode = GetLastError();
719 FormatMessageW (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
720 NULL, anErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (wchar_t* )&aMsgBuff, 0, NULL);
721 TCollection_ExtendedString aMsg ("wglMakeCurrent() has failed. ");
722 if (aMsgBuff != NULL)
724 aMsg += (Standard_ExtString )aMsgBuff;
725 LocalFree (aMsgBuff);
727 PushMessage (GL_DEBUG_SOURCE_WINDOW_SYSTEM, GL_DEBUG_TYPE_ERROR, (unsigned int )anErrorCode, GL_DEBUG_SEVERITY_HIGH, aMsg);
728 myIsInitialized = Standard_False;
729 return Standard_False;
732 if (myDisplay == NULL || myWindow == 0 || myGContext == 0)
734 Standard_ProgramError_Raise_if (myIsInitialized, "OpenGl_Context::Init() should be called before!");
735 return Standard_False;
738 if (!glXMakeCurrent ((Display* )myDisplay, (GLXDrawable )myWindow, (GLXContext )myGContext))
740 // if there is no current context it might be impossible to use glGetError() correctly
741 PushMessage (GL_DEBUG_SOURCE_WINDOW_SYSTEM, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
742 "glXMakeCurrent() has failed!");
743 myIsInitialized = Standard_False;
744 return Standard_False;
747 myShaderManager->SetContext (this);
748 return Standard_True;
751 // =======================================================================
752 // function : SwapBuffers
754 // =======================================================================
755 void OpenGl_Context::SwapBuffers()
757 #if defined(HAVE_EGL)
758 if ((EGLSurface )myWindow != EGL_NO_SURFACE)
760 eglSwapBuffers ((EGLDisplay )myDisplay, (EGLSurface )myWindow);
762 #elif defined(_WIN32)
763 if ((HDC )myWindowDC != NULL)
765 ::SwapBuffers ((HDC )myWindowDC);
769 if ((Display* )myDisplay != NULL)
771 glXSwapBuffers ((Display* )myDisplay, (GLXDrawable )myWindow);
778 // =======================================================================
779 // function : SetSwapInterval
781 // =======================================================================
782 Standard_Boolean OpenGl_Context::SetSwapInterval (const Standard_Integer theInterval)
784 #if defined(HAVE_EGL)
785 if (::eglSwapInterval ((EGLDisplay )myDisplay, theInterval) == EGL_TRUE)
787 return Standard_True;
789 #elif defined(_WIN32)
790 if (myFuncs->wglSwapIntervalEXT != NULL)
792 myFuncs->wglSwapIntervalEXT (theInterval);
793 return Standard_True;
795 #elif defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
796 (void )theInterval; // vsync cannot be turned OFF on iOS
797 #elif defined(__APPLE__)
798 if (::CGLSetParameter (CGLGetCurrentContext(), kCGLCPSwapInterval, &theInterval) == kCGLNoError)
800 return Standard_True;
803 if (theInterval == -1
804 && myFuncs->glXSwapIntervalEXT != NULL)
806 typedef int (*glXSwapIntervalEXT_t_x)(Display* theDisplay, GLXDrawable theDrawable, int theInterval);
807 glXSwapIntervalEXT_t_x aFuncPtr = (glXSwapIntervalEXT_t_x )myFuncs->glXSwapIntervalEXT;
808 aFuncPtr ((Display* )myDisplay, (GLXDrawable )myWindow, theInterval);
809 return Standard_True;
811 else if (myFuncs->glXSwapIntervalSGI != NULL)
813 myFuncs->glXSwapIntervalSGI (theInterval);
814 return Standard_True;
817 return Standard_False;
820 // =======================================================================
821 // function : findProc
823 // =======================================================================
824 void* OpenGl_Context::findProc (const char* theFuncName)
826 #if defined(HAVE_EGL)
827 return (void* )eglGetProcAddress (theFuncName);
828 #elif defined(_WIN32)
829 return (void* )wglGetProcAddress (theFuncName);
830 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
831 return (myGlLibHandle != NULL) ? dlsym (myGlLibHandle, theFuncName) : NULL;
833 return (void* )glXGetProcAddress ((const GLubyte* )theFuncName);
837 // =======================================================================
838 // function : CheckExtension
840 // =======================================================================
841 Standard_Boolean OpenGl_Context::CheckExtension (const char* theExtName) const
843 if (theExtName == NULL)
846 std::cerr << "CheckExtension called with NULL string!\n";
848 return Standard_False;
850 else if (caps->contextNoExtensions)
852 return Standard_False;
855 #if !defined(GL_ES_VERSION_2_0)
856 // available since OpenGL 3.0
857 // and the ONLY way to check extensions with OpenGL 3.1+ core profile
858 if (IsGlGreaterEqual (3, 0)
859 && myFuncs->glGetStringi != NULL)
862 ::glGetIntegerv (GL_NUM_EXTENSIONS, &anExtNb);
863 const size_t anExtNameLen = strlen (theExtName);
864 for (GLint anIter = 0; anIter < anExtNb; ++anIter)
866 const char* anExtension = (const char* )myFuncs->glGetStringi (GL_EXTENSIONS, (GLuint )anIter);
867 const size_t aTestExtNameLen = strlen (anExtension);
868 if (aTestExtNameLen == anExtNameLen
869 && strncmp (anExtension, theExtName, anExtNameLen) == 0)
871 return Standard_True;
874 return Standard_False;
878 // use old way with huge string for all extensions
879 const char* anExtString = (const char* )glGetString (GL_EXTENSIONS);
880 if (anExtString == NULL)
882 Messenger()->Send ("TKOpenGL: glGetString (GL_EXTENSIONS) has returned NULL! No GL context?", Message_Warning);
883 return Standard_False;
885 return CheckExtension (anExtString, theExtName);
888 // =======================================================================
889 // function : CheckExtension
891 // =======================================================================
892 Standard_Boolean OpenGl_Context::CheckExtension (const char* theExtString,
893 const char* theExtName)
895 if (theExtString == NULL)
897 return Standard_False;
900 // Search for theExtName in the extensions string.
901 // Use of strstr() is not sufficient because extension names can be prefixes of other extension names.
902 char* aPtrIter = (char* )theExtString;
903 const char* aPtrEnd = aPtrIter + strlen (theExtString);
904 const size_t anExtNameLen = strlen (theExtName);
905 while (aPtrIter < aPtrEnd)
907 const size_t n = strcspn (aPtrIter, " ");
908 if ((n == anExtNameLen) && (strncmp (aPtrIter, theExtName, anExtNameLen) == 0))
910 return Standard_True;
914 return Standard_False;
917 #if !defined(__APPLE__) || defined(MACOSX_USE_GLX)
919 // =======================================================================
922 // =======================================================================
923 Standard_Boolean OpenGl_Context::Init (const Standard_Boolean theIsCoreProfile)
927 return Standard_True;
930 #if defined(HAVE_EGL)
931 myDisplay = (Aspect_Display )eglGetCurrentDisplay();
932 myGContext = (Aspect_RenderingContext )eglGetCurrentContext();
933 myWindow = (Aspect_Drawable )eglGetCurrentSurface(EGL_DRAW);
934 #elif defined(_WIN32)
935 myWindowDC = (Aspect_Handle )wglGetCurrentDC();
936 myGContext = (Aspect_RenderingContext )wglGetCurrentContext();
938 myDisplay = (Aspect_Display )glXGetCurrentDisplay();
939 myGContext = (Aspect_RenderingContext )glXGetCurrentContext();
940 myWindow = (Aspect_Drawable )glXGetCurrentDrawable();
942 if (myGContext == NULL)
944 return Standard_False;
947 init (theIsCoreProfile);
948 myIsInitialized = Standard_True;
949 return Standard_True;
954 // =======================================================================
957 // =======================================================================
958 #if defined(HAVE_EGL)
959 Standard_Boolean OpenGl_Context::Init (const Aspect_Drawable theEglSurface,
960 const Aspect_Display theEglDisplay,
961 const Aspect_RenderingContext theEglContext,
962 const Standard_Boolean theIsCoreProfile)
963 #elif defined(_WIN32)
964 Standard_Boolean OpenGl_Context::Init (const Aspect_Handle theWindow,
965 const Aspect_Handle theWindowDC,
966 const Aspect_RenderingContext theGContext,
967 const Standard_Boolean theIsCoreProfile)
968 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
970 #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
971 Standard_Boolean OpenGl_Context::Init (EAGLContext* theGContext,
972 const Standard_Boolean theIsCoreProfile)
974 Standard_Boolean OpenGl_Context::Init (NSOpenGLContext* theGContext,
975 const Standard_Boolean theIsCoreProfile)
979 Standard_Boolean OpenGl_Context::Init (const Aspect_Drawable theWindow,
980 const Aspect_Display theDisplay,
981 const Aspect_RenderingContext theGContext,
982 const Standard_Boolean theIsCoreProfile)
985 Standard_ProgramError_Raise_if (myIsInitialized, "OpenGl_Context::Init() should be called only once!");
986 #if defined(HAVE_EGL)
987 myWindow = theEglSurface;
988 myGContext = theEglContext;
989 myDisplay = theEglDisplay;
990 #elif defined(_WIN32)
991 myWindow = theWindow;
992 myGContext = theGContext;
993 myWindowDC = theWindowDC;
994 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
995 myGContext = theGContext;
997 myWindow = theWindow;
998 myGContext = theGContext;
999 myDisplay = theDisplay;
1001 if (myGContext == NULL || !MakeCurrent())
1003 return Standard_False;
1006 init (theIsCoreProfile);
1007 myIsInitialized = Standard_True;
1008 return Standard_True;
1011 // =======================================================================
1012 // function : FormatGlEnumHex
1014 // =======================================================================
1015 TCollection_AsciiString OpenGl_Context::FormatGlEnumHex (int theGlEnum)
1018 Sprintf (aBuff, theGlEnum < (int )std::numeric_limits<uint16_t>::max()
1020 : "0x%08X", theGlEnum);
1024 // =======================================================================
1025 // function : FormatSize
1027 // =======================================================================
1028 TCollection_AsciiString OpenGl_Context::FormatSize (Standard_Size theSize)
1031 Sprintf (aBuff, "%" PRIu64, (uint64_t )theSize);
1035 // =======================================================================
1036 // function : FormatPointer
1038 // =======================================================================
1039 TCollection_AsciiString OpenGl_Context::FormatPointer (const void* thePtr)
1042 Sprintf (aBuff, "0x%" PRIXPTR, (uintptr_t )thePtr);
1046 // =======================================================================
1047 // function : FormatGlError
1049 // =======================================================================
1050 TCollection_AsciiString OpenGl_Context::FormatGlError (int theGlError)
1054 case GL_INVALID_ENUM: return "GL_INVALID_ENUM";
1055 case GL_INVALID_VALUE: return "GL_INVALID_VALUE";
1056 case GL_INVALID_OPERATION: return "GL_INVALID_OPERATION";
1057 #ifdef GL_STACK_OVERFLOW
1058 case GL_STACK_OVERFLOW: return "GL_STACK_OVERFLOW";
1059 case GL_STACK_UNDERFLOW: return "GL_STACK_UNDERFLOW";
1061 case GL_OUT_OF_MEMORY: return "GL_OUT_OF_MEMORY";
1062 case GL_INVALID_FRAMEBUFFER_OPERATION: return "GL_INVALID_FRAMEBUFFER_OPERATION";
1064 return FormatGlEnumHex (theGlError);
1067 // =======================================================================
1068 // function : ResetErrors
1070 // =======================================================================
1071 bool OpenGl_Context::ResetErrors (const bool theToPrintErrors)
1074 int anErr = ::glGetError();
1075 const bool hasError = anErr != GL_NO_ERROR;
1076 if (!theToPrintErrors)
1078 for (; anErr != GL_NO_ERROR && aPrevErr != anErr; aPrevErr = anErr, anErr = ::glGetError())
1085 for (; anErr != GL_NO_ERROR && aPrevErr != anErr; aPrevErr = anErr, anErr = ::glGetError())
1087 const TCollection_ExtendedString aMsg = TCollection_ExtendedString ("Unhandled GL error: ") + FormatGlError (anErr);
1088 PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_OTHER, 0, GL_DEBUG_SEVERITY_LOW, aMsg);
1093 // =======================================================================
1094 // function : debugPrintError
1096 // =======================================================================
1097 bool OpenGl_GlFunctions::debugPrintError (const char* theName) const
1099 const int anErr = ::glGetError();
1100 if (anErr != GL_NO_ERROR)
1102 Message::SendFail() << theName << "(), unhandled GL error: " << OpenGl_Context::FormatGlError (anErr);
1103 // there is no glSetError(), just emulate non-clear state
1106 case GL_INVALID_VALUE:
1108 ::glLineWidth(-1.0f);
1109 ::glLineWidth( 1.0f);
1113 case GL_INVALID_ENUM:
1115 ::glEnable (0xFFFF);
1120 return anErr != GL_NO_ERROR;
1123 // =======================================================================
1124 // function : ReadGlVersion
1126 // =======================================================================
1127 void OpenGl_Context::ReadGlVersion (Standard_Integer& theGlVerMajor,
1128 Standard_Integer& theGlVerMinor)
1134 bool toCheckVer3 = true;
1135 #if defined(__EMSCRIPTEN__)
1136 // WebGL 1.0 prints annoying invalid enumeration warnings to console.
1137 toCheckVer3 = false;
1138 if (EMSCRIPTEN_WEBGL_CONTEXT_HANDLE aWebGlCtx = emscripten_webgl_get_current_context())
1140 EmscriptenWebGLContextAttributes anAttribs = {};
1141 if (emscripten_webgl_get_context_attributes (aWebGlCtx, &anAttribs) == EMSCRIPTEN_RESULT_SUCCESS)
1143 toCheckVer3 = anAttribs.majorVersion >= 2;
1148 // Available since OpenGL 3.0 and OpenGL ES 3.0.
1151 GLint aMajor = 0, aMinor = 0;
1152 glGetIntegerv (GL_MAJOR_VERSION, &aMajor);
1153 glGetIntegerv (GL_MINOR_VERSION, &aMinor);
1154 // glGetError() sometimes does not report an error here even if
1155 // GL does not know GL_MAJOR_VERSION and GL_MINOR_VERSION constants.
1156 // This happens on some renderers like e.g. Cygwin MESA.
1157 // Thus checking additionally if GL has put anything to
1158 // the output variables.
1159 if (::glGetError() == GL_NO_ERROR && aMajor != 0 && aMinor != 0)
1161 theGlVerMajor = aMajor;
1162 theGlVerMinor = aMinor;
1165 for (GLenum anErr = ::glGetError(), aPrevErr = GL_NO_ERROR;; aPrevErr = anErr, anErr = ::glGetError())
1167 if (anErr == GL_NO_ERROR
1168 || anErr == aPrevErr)
1175 // Read version string.
1176 // Notice that only first two numbers split by point '2.1 XXXXX' are significant.
1177 // Following trash (after space) is vendor-specific.
1178 // New drivers also returns micro version of GL like '3.3.0' which has no meaning
1179 // and should be considered as vendor-specific too.
1180 const char* aVerStr = (const char* )glGetString (GL_VERSION);
1181 if (aVerStr == NULL || *aVerStr == '\0')
1183 // invalid GL context
1187 //#if defined(GL_ES_VERSION_2_0)
1188 // skip "OpenGL ES-** " section
1189 for (; *aVerStr != '\0'; ++aVerStr)
1191 if (*aVerStr >= '0' && *aVerStr <= '9')
1198 // parse string for major number
1201 size_t aMajIter = 0;
1202 while (aVerStr[aMajIter] >= '0' && aVerStr[aMajIter] <= '9')
1206 if (aMajIter == 0 || aMajIter >= sizeof(aMajorStr))
1210 memcpy (aMajorStr, aVerStr, aMajIter);
1211 aMajorStr[aMajIter] = '\0';
1213 // parse string for minor number
1214 aVerStr += aMajIter + 1;
1215 size_t aMinIter = 0;
1216 while (aVerStr[aMinIter] >= '0' && aVerStr[aMinIter] <= '9')
1220 if (aMinIter == 0 || aMinIter >= sizeof(aMinorStr))
1224 memcpy (aMinorStr, aVerStr, aMinIter);
1225 aMinorStr[aMinIter] = '\0';
1228 theGlVerMajor = atoi (aMajorStr);
1229 theGlVerMinor = atoi (aMinorStr);
1230 #if defined(__EMSCRIPTEN__)
1231 if (theGlVerMajor >= 3)
1234 || ::strstr (aVerStr, "WebGL 1.0") != NULL)
1236 Message::SendWarning() << "Warning! OpenGL context reports version " << theGlVerMajor << "." << theGlVerMinor
1237 << " but WebGL 2.0 was unavailable\n"
1238 << "Fallback to OpenGL ES 2.0 will be used instead of reported version";
1245 if (theGlVerMajor <= 0)
1252 static Standard_CString THE_DBGMSG_UNKNOWN = "UNKNOWN";
1253 static Standard_CString THE_DBGMSG_SOURCES[] =
1255 ".OpenGL", // GL_DEBUG_SOURCE_API
1256 ".WinSystem", // GL_DEBUG_SOURCE_WINDOW_SYSTEM
1257 ".GLSL", // GL_DEBUG_SOURCE_SHADER_COMPILER
1258 ".3rdParty", // GL_DEBUG_SOURCE_THIRD_PARTY
1259 "", // GL_DEBUG_SOURCE_APPLICATION
1260 ".Other" // GL_DEBUG_SOURCE_OTHER
1263 static Standard_CString THE_DBGMSG_TYPES[] =
1265 "Error", // GL_DEBUG_TYPE_ERROR
1266 "Deprecated", // GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR
1267 "Undef. behavior", // GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR
1268 "Portability", // GL_DEBUG_TYPE_PORTABILITY
1269 "Performance", // GL_DEBUG_TYPE_PERFORMANCE
1270 "Other" // GL_DEBUG_TYPE_OTHER
1273 static Standard_CString THE_DBGMSG_SEV_HIGH = "High"; // GL_DEBUG_SEVERITY_HIGH
1274 static Standard_CString THE_DBGMSG_SEV_MEDIUM = "Medium"; // GL_DEBUG_SEVERITY_MEDIUM
1275 static Standard_CString THE_DBGMSG_SEV_LOW = "Low"; // GL_DEBUG_SEVERITY_LOW
1277 //! Callback for GL_ARB_debug_output extension
1278 static void APIENTRY debugCallbackWrap(unsigned int theSource,
1279 unsigned int theType,
1281 unsigned int theSeverity,
1283 const char* theMessage,
1284 const void* theUserParam)
1286 OpenGl_Context* aCtx = (OpenGl_Context* )theUserParam;
1287 aCtx->PushMessage (theSource, theType, theId, theSeverity, theMessage);
1290 // =======================================================================
1291 // function : PushMessage
1293 // =======================================================================
1294 void OpenGl_Context::PushMessage (const unsigned int theSource,
1295 const unsigned int theType,
1296 const unsigned int theId,
1297 const unsigned int theSeverity,
1298 const TCollection_ExtendedString& theMessage)
1300 if (caps->suppressExtraMsg
1301 && theSource >= GL_DEBUG_SOURCE_API
1302 && theSource <= GL_DEBUG_SOURCE_OTHER
1303 && myFilters[theSource - GL_DEBUG_SOURCE_API].Contains (theId))
1308 Standard_CString& aSrc = (theSource >= GL_DEBUG_SOURCE_API
1309 && theSource <= GL_DEBUG_SOURCE_OTHER)
1310 ? THE_DBGMSG_SOURCES[theSource - GL_DEBUG_SOURCE_API]
1311 : THE_DBGMSG_UNKNOWN;
1312 Standard_CString& aType = (theType >= GL_DEBUG_TYPE_ERROR
1313 && theType <= GL_DEBUG_TYPE_OTHER)
1314 ? THE_DBGMSG_TYPES[theType - GL_DEBUG_TYPE_ERROR]
1315 : THE_DBGMSG_UNKNOWN;
1316 Standard_CString& aSev = theSeverity == GL_DEBUG_SEVERITY_HIGH
1317 ? THE_DBGMSG_SEV_HIGH
1318 : (theSeverity == GL_DEBUG_SEVERITY_MEDIUM
1319 ? THE_DBGMSG_SEV_MEDIUM
1320 : THE_DBGMSG_SEV_LOW);
1321 Message_Gravity aGrav = theSeverity == GL_DEBUG_SEVERITY_HIGH
1323 : (theSeverity == GL_DEBUG_SEVERITY_MEDIUM
1327 TCollection_ExtendedString aMsg;
1328 aMsg += "TKOpenGl"; aMsg += aSrc;
1329 aMsg += " | Type: "; aMsg += aType;
1330 aMsg += " | ID: "; aMsg += (Standard_Integer )theId;
1331 aMsg += " | Severity: "; aMsg += aSev;
1332 aMsg += " | Message:\n ";
1334 Messenger()->Send (aMsg, aGrav);
1337 // =======================================================================
1338 // function : ExcludeMessage
1340 // ======================================================================
1341 Standard_Boolean OpenGl_Context::ExcludeMessage (const unsigned int theSource,
1342 const unsigned int theId)
1344 return theSource >= GL_DEBUG_SOURCE_API
1345 && theSource <= GL_DEBUG_SOURCE_OTHER
1346 && myFilters[theSource - GL_DEBUG_SOURCE_API].Add (theId);
1349 // =======================================================================
1350 // function : IncludeMessage
1352 // ======================================================================
1353 Standard_Boolean OpenGl_Context::IncludeMessage (const unsigned int theSource,
1354 const unsigned int theId)
1356 return theSource >= GL_DEBUG_SOURCE_API
1357 && theSource <= GL_DEBUG_SOURCE_OTHER
1358 && myFilters[theSource - GL_DEBUG_SOURCE_API].Remove (theId);
1361 // =======================================================================
1362 // function : checkWrongVersion
1364 // ======================================================================
1365 void OpenGl_Context::checkWrongVersion (Standard_Integer theGlVerMajor, Standard_Integer theGlVerMinor,
1366 const char* theLastFailedProc)
1368 if (!IsGlGreaterEqual (theGlVerMajor, theGlVerMinor))
1373 PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
1374 TCollection_AsciiString()
1375 + "Error! OpenGL context reports version "
1376 + myGlVerMajor + "." + myGlVerMinor
1377 + " but does not export required functions for " + theGlVerMajor + "." + theGlVerMinor
1378 + " (" + (theLastFailedProc != NULL ? theLastFailedProc : "") + ")\n"
1379 + "Please report this issue to OpenGL driver vendor '" + myVendor + "'");
1381 // lower internal version
1382 if (theGlVerMinor > 0)
1384 myGlVerMajor = theGlVerMajor;
1385 myGlVerMinor = theGlVerMinor - 1;
1388 #if defined(GL_ES_VERSION_2_0)
1389 switch (theGlVerMajor)
1391 case 3: myGlVerMajor = 2; myGlVerMinor = 0; return;
1394 switch (theGlVerMajor)
1396 case 2: myGlVerMajor = 1; myGlVerMinor = 5; return;
1397 case 3: myGlVerMajor = 2; myGlVerMinor = 1; return;
1398 case 4: myGlVerMajor = 3; myGlVerMinor = 3; return;
1403 // =======================================================================
1406 // =======================================================================
1407 void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
1412 myMaxMsaaSamples = 0;
1413 myMaxDrawBuffers = 1;
1414 myMaxColorAttachments = 1;
1416 ReadGlVersion (myGlVerMajor, myGlVerMinor);
1417 myVendor = (const char* )::glGetString (GL_VENDOR);
1418 myVendor.LowerCase();
1419 mySupportedFormats->Clear();
1421 if (caps->contextMajorVersionUpper != -1)
1423 // synthetically restrict OpenGL version for testing
1424 Standard_Integer aCtxVer[2] = { myGlVerMajor, myGlVerMinor };
1425 bool isLowered = false;
1426 if (myGlVerMajor > caps->contextMajorVersionUpper)
1429 myGlVerMajor = caps->contextMajorVersionUpper;
1430 #if defined(GL_ES_VERSION_2_0)
1431 switch (myGlVerMajor)
1433 case 2: myGlVerMinor = 0; break;
1436 switch (myGlVerMajor)
1438 case 1: myGlVerMinor = 5; break;
1439 case 2: myGlVerMinor = 1; break;
1440 case 3: myGlVerMinor = 3; break;
1444 if (caps->contextMinorVersionUpper != -1
1445 && myGlVerMinor > caps->contextMinorVersionUpper)
1448 myGlVerMinor = caps->contextMinorVersionUpper;
1452 PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_MEDIUM,
1453 TCollection_AsciiString ("OpenGL version ") + aCtxVer[0] + "." + aCtxVer[1]
1454 + " has been lowered to " + myGlVerMajor + "." + myGlVerMinor);
1458 if (!caps->ffpEnable
1459 && !IsGlGreaterEqual (2, 0))
1461 caps->ffpEnable = true;
1462 TCollection_ExtendedString aMsg =
1463 TCollection_ExtendedString("OpenGL driver is too old! Context info:\n")
1464 + " Vendor: " + (const char* )::glGetString (GL_VENDOR) + "\n"
1465 + " Renderer: " + (const char* )::glGetString (GL_RENDERER) + "\n"
1466 + " Version: " + (const char* )::glGetString (GL_VERSION) + "\n"
1467 + " Fallback using deprecated fixed-function pipeline.\n"
1468 + " Visualization might work incorrectly.\n"
1469 " Consider upgrading the graphics driver.";
1470 PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
1473 #if defined(GL_ES_VERSION_2_0)
1474 (void )theIsCoreProfile;
1475 const bool isCoreProfile = false;
1478 if (myVendor.Search ("nvidia") != -1)
1480 // Buffer detailed info: Buffer object 1 (bound to GL_ARRAY_BUFFER_ARB, usage hint is GL_STATIC_DRAW)
1481 // will use VIDEO memory as the source for buffer object operations.
1482 ExcludeMessage (GL_DEBUG_SOURCE_API, 131185);
1484 if (IsGlGreaterEqual (3, 0))
1486 // retrieve auxiliary function in advance
1487 FindProc ("glGetStringi", myFuncs->glGetStringi);
1490 bool isCoreProfile = false;
1491 if (IsGlGreaterEqual (3, 2))
1493 isCoreProfile = (theIsCoreProfile == Standard_True);
1495 // detect Core profile
1499 ::glGetIntegerv (GL_CONTEXT_PROFILE_MASK, &aProfile);
1500 isCoreProfile = (aProfile & GL_CONTEXT_CORE_PROFILE_BIT) != 0;
1505 myFuncs->load (*this, isCoreProfile);
1507 // setup shader generator
1508 myShaderManager->SetGapiVersion (myGlVerMajor, myGlVerMinor);
1509 myShaderManager->SetEmulateDepthClamp (!arbDepthClamp);
1511 bool toReverseDFdxSign = false;
1512 #if defined(GL_ES_VERSION_2_0)
1513 // workaround Adreno driver bug computing reversed normal using dFdx/dFdy
1514 toReverseDFdxSign = myVendor.Search("qualcomm") != -1;
1516 myShaderManager->SetFlatShading (hasFlatShading != OpenGl_FeatureNotAvailable, toReverseDFdxSign);
1517 #if defined(GL_ES_VERSION_2_0)
1518 myShaderManager->SetUseRedAlpha (false);
1520 myShaderManager->SetUseRedAlpha (core11ffp == NULL);
1522 #define checkGlslExtensionShort(theName) myShaderManager->EnableGlslExtension (Graphic3d_GlslExtension_ ## theName, CheckExtension (#theName))
1523 #if defined(GL_ES_VERSION_2_0)
1524 checkGlslExtensionShort(GL_OES_standard_derivatives);
1525 checkGlslExtensionShort(GL_EXT_shader_texture_lod);
1526 checkGlslExtensionShort(GL_EXT_frag_depth);
1528 checkGlslExtensionShort(GL_EXT_gpu_shader4);
1531 // initialize debug context extension
1533 && caps->contextDebug)
1535 // setup default callback
1536 myIsGlDebugCtx = Standard_True;
1537 arbDbg->glDebugMessageCallback (debugCallbackWrap, this);
1538 #if defined(GL_ES_VERSION_2_0)
1539 ::glEnable (GL_DEBUG_OUTPUT);
1543 ::glEnable (GL_DEBUG_OUTPUT);
1546 if (caps->contextSyncDebug)
1548 // note that some broken implementations (e.g. simulators) might generate error message on this call
1549 ::glEnable (GL_DEBUG_OUTPUT_SYNCHRONOUS);
1555 glGetIntegerv (GL_MAX_DRAW_BUFFERS, &myMaxDrawBuffers);
1556 glGetIntegerv (GL_MAX_COLOR_ATTACHMENTS, &myMaxColorAttachments);
1557 if (myDrawBuffers.Length() < myMaxDrawBuffers)
1559 myDrawBuffers.Resize (0, myMaxDrawBuffers - 1, false);
1563 glGetIntegerv (GL_MAX_TEXTURE_SIZE, &myMaxTexDim);
1564 #if !defined(GL_ES_VERSION_2_0)
1565 if (IsGlGreaterEqual (1, 3) && core11ffp != NULL)
1567 // this is a maximum of texture units for FFP functionality,
1568 // usually smaller than combined texture units available for GLSL
1569 glGetIntegerv (GL_MAX_TEXTURE_UNITS, &myMaxTexUnitsFFP);
1570 myMaxTexCombined = myMaxTexUnitsFFP;
1573 if (IsGlGreaterEqual (2, 0))
1575 glGetIntegerv (GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &myMaxTexCombined);
1577 mySpriteTexUnit = myMaxTexCombined >= 2
1578 ? Graphic3d_TextureUnit_PointSprite
1579 : Graphic3d_TextureUnit_0;
1581 GLint aMaxVPortSize[2] = {0, 0};
1582 glGetIntegerv (GL_MAX_VIEWPORT_DIMS, aMaxVPortSize);
1583 myMaxDumpSizeX = Min (aMaxVPortSize[0], myMaxTexDim);
1584 myMaxDumpSizeY = Min (aMaxVPortSize[1], myMaxTexDim);
1585 if (myVendor == "intel")
1587 // Intel drivers have known bug with empty dump for images with width>=5462
1588 myMaxDumpSizeX = Min (myMaxDumpSizeX, 4096);
1593 glGetIntegerv (GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &myAnisoMax);
1596 myClippingState.Init();
1598 #if defined(GL_ES_VERSION_2_0)
1599 if (IsGlGreaterEqual (3, 1)
1600 && myFuncs->glTexStorage2DMultisample != NULL)
1602 // MSAA RenderBuffers have been defined in OpenGL ES 3.0,
1603 // but MSAA Textures - only in OpenGL ES 3.1+
1604 ::glGetIntegerv (GL_MAX_SAMPLES, &myMaxMsaaSamples);
1609 // MSAA RenderBuffers have been defined in OpenGL 3.0,
1610 // but MSAA Textures - only in OpenGL 3.2+
1613 ::glGetIntegerv (GL_MAX_SAMPLES, &myMaxMsaaSamples);
1615 else if (CheckExtension ("GL_ARB_texture_multisample")
1616 && myFuncs->glTexImage2DMultisample != NULL)
1618 GLint aNbColorSamples = 0, aNbDepthSamples = 0;
1619 ::glGetIntegerv (GL_MAX_COLOR_TEXTURE_SAMPLES, &aNbColorSamples);
1620 ::glGetIntegerv (GL_MAX_DEPTH_TEXTURE_SAMPLES, &aNbDepthSamples);
1621 myMaxMsaaSamples = Min (aNbColorSamples, aNbDepthSamples);
1626 #if !defined(GL_ES_VERSION_2_0)
1627 if (core32 != NULL && isCoreProfile)
1629 core32->glGenVertexArrays (1, &myDefaultVao);
1632 myTexClamp = IsGlGreaterEqual (1, 2) ? GL_CLAMP_TO_EDGE : GL_CLAMP;
1634 GLint aStereo = GL_FALSE;
1635 glGetIntegerv (GL_STEREO, &aStereo);
1636 myIsStereoBuffers = aStereo == 1;
1638 // get number of maximum clipping planes
1639 glGetIntegerv (GL_MAX_CLIP_PLANES, &myMaxClipPlanes);
1642 #if defined(GL_ES_VERSION_2_0)
1643 // check whether ray tracing mode is supported
1644 myHasRayTracing = IsGlGreaterEqual (3, 2);
1645 myHasRayTracingTextures = myHasRayTracingAdaptiveSampling = myHasRayTracingAdaptiveSamplingAtomic = false;
1647 // check whether ray tracing mode is supported
1648 myHasRayTracing = IsGlGreaterEqual (3, 1)
1650 && arbFBOBlit != NULL;
1652 // check whether textures in ray tracing mode are supported
1653 myHasRayTracingTextures = myHasRayTracing
1654 && arbTexBindless != NULL;
1656 // check whether adaptive screen sampling in ray tracing mode is supported
1657 myHasRayTracingAdaptiveSampling = myHasRayTracing
1659 myHasRayTracingAdaptiveSamplingAtomic = myHasRayTracingAdaptiveSampling
1660 && CheckExtension ("GL_NV_shader_atomic_float");
1666 // Detect if window buffer is considered by OpenGL as sRGB-ready
1667 // (linear RGB color written by shader is automatically converted into sRGB)
1668 // or not (offscreen FBO should be blit into window buffer with gamma correction).
1669 const GLenum aDefWinBuffer =
1670 #if !defined(GL_ES_VERSION_2_0)
1675 GLint aWinColorEncoding = 0; // GL_LINEAR
1676 arbFBO->glGetFramebufferAttachmentParameteriv (GL_FRAMEBUFFER, aDefWinBuffer, GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, &aWinColorEncoding);
1678 myIsSRgbWindow = aWinColorEncoding == GL_SRGB;
1680 // On desktop OpenGL, pixel formats are almost always sRGB-ready, even when not requested;
1681 // it is safe behavior on desktop where GL_FRAMEBUFFER_SRGB is disabled by default
1682 // (contrary to OpenGL ES, where it is enabled by default).
1683 // NVIDIA drivers, however, always return GL_LINEAR even for sRGB-ready pixel formats on Windows platform,
1684 // while AMD and Intel report GL_SRGB as expected.
1685 // macOS drivers seems to be also report GL_LINEAR even for [NSColorSpace sRGBColorSpace].
1686 #if !defined(GL_ES_VERSION_2_0)
1688 myIsSRgbWindow = true;
1691 && myVendor.Search ("nvidia") != -1)
1693 myIsSRgbWindow = true;
1697 if (!myIsSRgbWindow)
1699 Message::SendTrace ("OpenGl_Context, warning: window buffer is not sRGB-ready.\n"
1700 "Check OpenGL window creation parameters for optimal performance.");
1705 mySupportedFormats->Add (Image_Format_Gray);
1706 mySupportedFormats->Add (Image_Format_Alpha);
1707 mySupportedFormats->Add (Image_Format_RGB);
1708 mySupportedFormats->Add (Image_Format_RGB32);
1709 mySupportedFormats->Add (Image_Format_RGBA);
1712 #if !defined(GL_ES_VERSION_2_0)
1713 // no BGR on OpenGL ES - only BGRA as extension
1714 mySupportedFormats->Add (Image_Format_BGR);
1716 mySupportedFormats->Add (Image_Format_BGR32);
1717 mySupportedFormats->Add (Image_Format_BGRA);
1721 mySupportedFormats->Add (Image_Format_GrayF);
1722 mySupportedFormats->Add (Image_Format_AlphaF);
1723 mySupportedFormats->Add (Image_Format_RGBF);
1724 mySupportedFormats->Add (Image_Format_RGBAF);
1725 if (hasHalfFloatBuffer)
1727 mySupportedFormats->Add (Image_Format_RGBAF_half);
1731 mySupportedFormats->Add (Image_Format_RGF);
1732 if (hasHalfFloatBuffer)
1734 mySupportedFormats->Add (Image_Format_RGF_half);
1739 #if !defined(GL_ES_VERSION_2_0)
1740 mySupportedFormats->Add (Image_Format_BGRF);
1742 mySupportedFormats->Add (Image_Format_BGRAF);
1746 #ifdef __EMSCRIPTEN__
1747 if (checkEnableWebGlExtension (*this, "GL_WEBGL_compressed_texture_s3tc")) // GL_WEBGL_compressed_texture_s3tc_srgb for sRGB formats
1749 mySupportedFormats->Add (Image_CompressedFormat_RGB_S3TC_DXT1);
1750 mySupportedFormats->Add (Image_CompressedFormat_RGBA_S3TC_DXT1);
1751 mySupportedFormats->Add (Image_CompressedFormat_RGBA_S3TC_DXT3);
1752 mySupportedFormats->Add (Image_CompressedFormat_RGBA_S3TC_DXT5);
1755 && checkEnableWebGlExtension (*this, "GL_WEBGL_depth_texture"))
1757 extPDS = true; // WebGL 1.0 extension (in WebGL 2.0 core)
1760 if (CheckExtension ("GL_EXT_texture_compression_s3tc")) // GL_EXT_texture_sRGB for sRGB formats
1762 mySupportedFormats->Add (Image_CompressedFormat_RGB_S3TC_DXT1);
1763 mySupportedFormats->Add (Image_CompressedFormat_RGBA_S3TC_DXT1);
1764 mySupportedFormats->Add (Image_CompressedFormat_RGBA_S3TC_DXT3);
1765 mySupportedFormats->Add (Image_CompressedFormat_RGBA_S3TC_DXT5);
1769 if (CheckExtension ("GL_EXT_texture_compression_dxt1"))
1771 mySupportedFormats->Add (Image_CompressedFormat_RGB_S3TC_DXT1);
1772 mySupportedFormats->Add (Image_CompressedFormat_RGBA_S3TC_DXT1);
1774 if (CheckExtension ("GL_ANGLE_texture_compression_dxt3"))
1776 mySupportedFormats->Add (Image_CompressedFormat_RGBA_S3TC_DXT3);
1778 if (CheckExtension ("GL_ANGLE_texture_compression_dxt5"))
1780 mySupportedFormats->Add (Image_CompressedFormat_RGBA_S3TC_DXT5);
1785 // check whether PBR shading model is supported
1786 myHasPBR = arbFBO != NULL
1787 && myMaxTexCombined >= 4
1789 && (IsGlGreaterEqual (3, 0)
1790 #if defined(GL_ES_VERSION_2_0)
1792 // || CheckExtension ("GL_EXT_shader_texture_lod") fallback is used when extension is unavailable
1794 || (IsGlGreaterEqual (2, 1) && CheckExtension ("GL_EXT_gpu_shader4"))
1798 myDepthPeelingDepthTexUnit = static_cast<Graphic3d_TextureUnit>(myMaxTexCombined + Graphic3d_TextureUnit_DepthPeelingDepth); // -6
1799 myDepthPeelingFrontColorTexUnit = static_cast<Graphic3d_TextureUnit>(myMaxTexCombined + Graphic3d_TextureUnit_DepthPeelingFrontColor); // -5
1800 myShadowMapTexUnit = static_cast<Graphic3d_TextureUnit>(myMaxTexCombined + Graphic3d_TextureUnit_ShadowMap); // -4
1801 myPBREnvLUTTexUnit = static_cast<Graphic3d_TextureUnit>(myMaxTexCombined + Graphic3d_TextureUnit_PbrEnvironmentLUT); // -3
1802 myPBRDiffIBLMapSHTexUnit = static_cast<Graphic3d_TextureUnit>(myMaxTexCombined + Graphic3d_TextureUnit_PbrIblDiffuseSH); // -2
1803 myPBRSpecIBLMapTexUnit = static_cast<Graphic3d_TextureUnit>(myMaxTexCombined + Graphic3d_TextureUnit_PbrIblSpecular); // -1
1806 myDepthPeelingDepthTexUnit = static_cast<Graphic3d_TextureUnit>(myDepthPeelingDepthTexUnit + 3);
1807 myDepthPeelingFrontColorTexUnit = static_cast<Graphic3d_TextureUnit>(myDepthPeelingFrontColorTexUnit + 3);
1808 myShadowMapTexUnit = static_cast<Graphic3d_TextureUnit>(myShadowMapTexUnit + 3);
1812 // =======================================================================
1813 // function : MemoryInfo
1815 // =======================================================================
1816 Standard_Size OpenGl_Context::AvailableMemory() const
1818 #if !defined(GL_ES_VERSION_2_0)
1821 // this is actually information for VBO pool
1822 // however because pools are mostly shared
1823 // it can be used for total GPU memory estimations
1826 glGetIntegerv (GL_VBO_FREE_MEMORY_ATI, aMemInfo);
1827 // returned value is in KiB, however this maybe changed in future
1828 return Standard_Size(aMemInfo[0]) * 1024;
1832 // current available dedicated video memory (in KiB), currently unused GPU memory
1834 glGetIntegerv (GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &aMemInfo);
1835 return Standard_Size(aMemInfo) * 1024;
1841 // =======================================================================
1842 // function : MemoryInfo
1844 // =======================================================================
1845 TCollection_AsciiString OpenGl_Context::MemoryInfo() const
1847 TColStd_IndexedDataMapOfStringString aDict;
1850 TCollection_AsciiString aText;
1851 for (TColStd_IndexedDataMapOfStringString::Iterator anIter (aDict); anIter.More(); anIter.Next())
1853 if (!aText.IsEmpty())
1857 aText += TCollection_AsciiString(" ") + anIter.Key() + ": " + anIter.Value();
1862 // =======================================================================
1863 // function : MemoryInfo
1865 // =======================================================================
1866 void OpenGl_Context::MemoryInfo (TColStd_IndexedDataMapOfStringString& theDict) const
1868 #if defined(GL_ES_VERSION_2_0)
1870 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
1871 GLint aGlRendId = 0;
1872 CGLGetParameter (CGLGetCurrentContext(), kCGLCPCurrentRendererID, &aGlRendId);
1874 CGLRendererInfoObj aRendObj = NULL;
1875 CGOpenGLDisplayMask aDispMask = CGDisplayIDToOpenGLDisplayMask (kCGDirectMainDisplay);
1877 CGLQueryRendererInfo (aDispMask, &aRendObj, &aRendNb);
1878 for (GLint aRendIter = 0; aRendIter < aRendNb; ++aRendIter)
1881 if (CGLDescribeRenderer (aRendObj, aRendIter, kCGLRPRendererID, &aRendId) != kCGLNoError
1882 || aRendId != aGlRendId)
1887 //kCGLRPVideoMemoryMegabytes = 131;
1888 //kCGLRPTextureMemoryMegabytes = 132;
1890 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
1891 if (CGLDescribeRenderer(aRendObj, aRendIter, kCGLRPVideoMemoryMegabytes, &aVMem) == kCGLNoError)
1893 addInfo (theDict, "GPU memory", TCollection_AsciiString() + aVMem + " MiB");
1895 if (CGLDescribeRenderer(aRendObj, aRendIter, kCGLRPTextureMemoryMegabytes, &aVMem) == kCGLNoError)
1897 addInfo (theDict, "GPU Texture memory", TCollection_AsciiString() + aVMem + " MiB");
1900 if (CGLDescribeRenderer(aRendObj, aRendIter, kCGLRPVideoMemory, &aVMem) == kCGLNoError)
1902 addInfo (theDict, "GPU memory", TCollection_AsciiString() + (aVMem / (1024 * 1024)) + " MiB");
1904 if (CGLDescribeRenderer(aRendObj, aRendIter, kCGLRPTextureMemory, &aVMem) == kCGLNoError)
1906 addInfo (theDict, "GPU Texture memory", TCollection_AsciiString() + (aVMem / (1024 * 1024)) + " MiB");
1912 #if !defined(GL_ES_VERSION_2_0)
1916 memset (aValues, 0, sizeof(aValues));
1917 glGetIntegerv (GL_VBO_FREE_MEMORY_ATI, aValues);
1919 // total memory free in the pool
1920 addInfo (theDict, "GPU free memory", TCollection_AsciiString() + (aValues[0] / 1024) + " MiB");
1922 if (aValues[1] != aValues[0])
1924 // largest available free block in the pool
1925 addInfo (theDict, "Largest free block", TCollection_AsciiString() + (aValues[1] / 1024) + " MiB");
1927 if (aValues[2] != aValues[0])
1929 // total auxiliary memory free
1930 addInfo (theDict, "Free auxiliary memory", TCollection_AsciiString() + (aValues[2] / 1024) + " MiB");
1935 //current available dedicated video memory (in KiB), currently unused GPU memory
1937 glGetIntegerv (GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &aValue);
1938 addInfo (theDict, "GPU free memory", TCollection_AsciiString() + (aValue / 1024) + " MiB");
1940 // dedicated video memory, total size (in KiB) of the GPU memory
1941 GLint aDedicated = 0;
1942 glGetIntegerv (GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX, &aDedicated);
1943 addInfo (theDict, "GPU memory", TCollection_AsciiString() + (aDedicated / 1024) + " MiB");
1945 // total available memory, total size (in KiB) of the memory available for allocations
1946 glGetIntegerv (GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &aValue);
1947 if (aValue != aDedicated)
1949 // different only for special configurations
1950 addInfo (theDict, "Total memory", TCollection_AsciiString() + (aValue / 1024) + " MiB");
1954 else if (myFuncs->wglGetGPUInfoAMD != NULL
1955 && myFuncs->wglGetContextGPUIDAMD != NULL)
1957 GLuint aTotalMemMiB = 0;
1958 UINT anAmdId = myFuncs->wglGetContextGPUIDAMD ((HGLRC )myGContext);
1961 if (myFuncs->wglGetGPUInfoAMD (anAmdId, WGL_GPU_RAM_AMD, GL_UNSIGNED_INT, sizeof(aTotalMemMiB), &aTotalMemMiB) > 0)
1963 addInfo (theDict, "GPU memory", TCollection_AsciiString() + (int )aTotalMemMiB + " MiB");
1970 #if !defined(GL_ES_VERSION_2_0) && !defined(__APPLE__) && !defined(_WIN32)
1971 // GLX_RENDERER_VENDOR_ID_MESA
1972 if (myFuncs->glXQueryCurrentRendererIntegerMESA != NULL)
1974 unsigned int aVMemMiB = 0;
1975 if (myFuncs->glXQueryCurrentRendererIntegerMESA (GLX_RENDERER_VIDEO_MEMORY_MESA, &aVMemMiB) != False)
1977 addInfo (theDict, "GPU memory", TCollection_AsciiString() + int(aVMemMiB) + " MiB");
1983 // =======================================================================
1984 // function : DiagnosticInfo
1986 // =======================================================================
1987 void OpenGl_Context::DiagnosticInformation (TColStd_IndexedDataMapOfStringString& theDict,
1988 Graphic3d_DiagnosticInfo theFlags) const
1990 if ((theFlags & Graphic3d_DiagnosticInfo_NativePlatform) != 0)
1992 #if defined(HAVE_EGL)
1993 addInfo (theDict, "EGLVersion", ::eglQueryString ((EGLDisplay )myDisplay, EGL_VERSION));
1994 addInfo (theDict, "EGLVendor", ::eglQueryString ((EGLDisplay )myDisplay, EGL_VENDOR));
1995 addInfo (theDict, "EGLClientAPIs", ::eglQueryString ((EGLDisplay )myDisplay, EGL_CLIENT_APIS));
1996 if ((theFlags & Graphic3d_DiagnosticInfo_Extensions) != 0)
1998 addInfo (theDict, "EGLExtensions", ::eglQueryString ((EGLDisplay )myDisplay, EGL_EXTENSIONS));
2000 #elif defined(_WIN32)
2001 if ((theFlags & Graphic3d_DiagnosticInfo_Extensions) != 0
2002 && myFuncs->wglGetExtensionsStringARB != NULL)
2004 const char* aWglExts = myFuncs->wglGetExtensionsStringARB ((HDC )myWindowDC);
2005 addInfo (theDict, "WGLExtensions", aWglExts);
2007 #elif defined(__APPLE__)
2010 Display* aDisplay = (Display*)myDisplay;
2011 const int aScreen = DefaultScreen(aDisplay);
2012 addInfo (theDict, "GLXDirectRendering", ::glXIsDirect (aDisplay, (GLXContext )myGContext) ? "Yes" : "No");
2013 addInfo (theDict, "GLXVendor", ::glXQueryServerString (aDisplay, aScreen, GLX_VENDOR));
2014 addInfo (theDict, "GLXVersion", ::glXQueryServerString (aDisplay, aScreen, GLX_VERSION));
2015 if ((theFlags & Graphic3d_DiagnosticInfo_Extensions) != 0)
2017 const char* aGlxExts = ::glXQueryExtensionsString (aDisplay, aScreen);
2018 addInfo(theDict, "GLXExtensions", aGlxExts);
2021 addInfo (theDict, "GLXClientVendor", ::glXGetClientString (aDisplay, GLX_VENDOR));
2022 addInfo (theDict, "GLXClientVersion", ::glXGetClientString (aDisplay, GLX_VERSION));
2023 if ((theFlags & Graphic3d_DiagnosticInfo_Extensions) != 0)
2025 addInfo (theDict, "GLXClientExtensions", ::glXGetClientString (aDisplay, GLX_EXTENSIONS));
2030 if ((theFlags & Graphic3d_DiagnosticInfo_Device) != 0)
2032 Standard_Integer aDriverVer[2] = {};
2033 ReadGlVersion (aDriverVer[0], aDriverVer[1]);
2034 addInfo (theDict, "GLvendor", (const char*)::glGetString (GL_VENDOR));
2035 addInfo (theDict, "GLdevice", (const char*)::glGetString (GL_RENDERER));
2036 #ifdef __EMSCRIPTEN__
2037 if (checkEnableWebGlExtension (*this, "GL_WEBGL_debug_renderer_info"))
2039 if (const char* aVendor = (const char*)::glGetString (0x9245))
2041 addInfo (theDict, "GLunmaskedVendor", aVendor);
2043 if (const char* aDevice = (const char*)::glGetString (0x9246))
2045 addInfo (theDict, "GLunmaskedDevice", aDevice);
2050 addInfo (theDict, "GLversion", (const char*)::glGetString (GL_VERSION));
2051 if (myGlVerMajor != aDriverVer[0]
2052 || myGlVerMinor != aDriverVer[1])
2054 addInfo (theDict, "GLversionOcct", TCollection_AsciiString (myGlVerMajor) + "." + TCollection_AsciiString (myGlVerMinor));
2056 if (IsGlGreaterEqual (2, 0))
2058 addInfo (theDict, "GLSLversion", (const char*)::glGetString (GL_SHADING_LANGUAGE_VERSION));
2062 addInfo (theDict, "GLdebug", "ON");
2066 if ((theFlags & Graphic3d_DiagnosticInfo_Limits) != 0)
2068 addInfo (theDict, "Max texture size", TCollection_AsciiString(myMaxTexDim));
2069 addInfo (theDict, "Max FBO dump size", TCollection_AsciiString() + myMaxDumpSizeX + "x" + myMaxDumpSizeY);
2070 addInfo (theDict, "Max combined texture units", TCollection_AsciiString(myMaxTexCombined));
2071 addInfo (theDict, "Max MSAA samples", TCollection_AsciiString(myMaxMsaaSamples));
2074 if ((theFlags & Graphic3d_DiagnosticInfo_FrameBuffer) != 0)
2076 GLint aViewport[4] = {};
2077 ::glGetIntegerv (GL_VIEWPORT, aViewport);
2078 addInfo (theDict, "Viewport", TCollection_AsciiString() + aViewport[2] + "x" + aViewport[3]);
2081 if ((theFlags & Graphic3d_DiagnosticInfo_Memory) != 0)
2083 MemoryInfo (theDict);
2086 if ((theFlags & Graphic3d_DiagnosticInfo_Extensions) != 0)
2088 #if !defined(GL_ES_VERSION_2_0)
2089 if (IsGlGreaterEqual (3, 0)
2090 && myFuncs->glGetStringi != NULL)
2092 TCollection_AsciiString anExtList;
2094 ::glGetIntegerv (GL_NUM_EXTENSIONS, &anExtNb);
2095 for (GLint anIter = 0; anIter < anExtNb; ++anIter)
2097 const char* anExtension = (const char*)myFuncs->glGetStringi (GL_EXTENSIONS, (GLuint)anIter);
2098 if (!anExtList.IsEmpty())
2102 anExtList += anExtension;
2104 addInfo(theDict, "GLextensions", anExtList);
2109 addInfo (theDict, "GLextensions", (const char*)::glGetString (GL_EXTENSIONS));
2114 // =======================================================================
2115 // function : GetResource
2117 // =======================================================================
2118 const Handle(OpenGl_Resource)& OpenGl_Context::GetResource (const TCollection_AsciiString& theKey) const
2120 return mySharedResources->IsBound (theKey) ? mySharedResources->Find (theKey) : NULL_GL_RESOURCE;
2123 // =======================================================================
2124 // function : ShareResource
2126 // =======================================================================
2127 Standard_Boolean OpenGl_Context::ShareResource (const TCollection_AsciiString& theKey,
2128 const Handle(OpenGl_Resource)& theResource)
2130 if (theKey.IsEmpty() || theResource.IsNull())
2132 return Standard_False;
2134 return mySharedResources->Bind (theKey, theResource);
2137 // =======================================================================
2138 // function : ReleaseResource
2140 // =======================================================================
2141 void OpenGl_Context::ReleaseResource (const TCollection_AsciiString& theKey,
2142 const Standard_Boolean theToDelay)
2144 if (!mySharedResources->IsBound (theKey))
2148 const Handle(OpenGl_Resource)& aRes = mySharedResources->Find (theKey);
2149 if (aRes->GetRefCount() > 1)
2156 myDelayed->Bind (theKey, 1);
2160 aRes->Release (this);
2161 mySharedResources->UnBind (theKey);
2165 // =======================================================================
2166 // function : ReleaseDelayed
2168 // =======================================================================
2169 void OpenGl_Context::ReleaseDelayed()
2171 // release queued elements
2172 while (!myUnusedResources->IsEmpty())
2174 myUnusedResources->First()->Release (this);
2175 myUnusedResources->RemoveFirst();
2178 // release delayed shared resources
2179 NCollection_Vector<TCollection_AsciiString> aDeadList;
2180 for (NCollection_DataMap<TCollection_AsciiString, Standard_Integer>::Iterator anIter (*myDelayed);
2181 anIter.More(); anIter.Next())
2183 if (++anIter.ChangeValue() <= 2)
2185 continue; // postpone release one more frame to ensure noone use it periodically
2188 const TCollection_AsciiString& aKey = anIter.Key();
2189 if (!mySharedResources->IsBound (aKey))
2191 // mixed unshared strategy delayed/undelayed was used!
2192 aDeadList.Append (aKey);
2196 const Handle(OpenGl_Resource)& aRes = mySharedResources->ChangeFind (aKey);
2197 if (aRes->GetRefCount() > 1)
2199 // should be only 1 instance in mySharedResources
2200 // if not - resource was reused again
2201 aDeadList.Append (aKey);
2205 // release resource if no one requested it more than 2 redraw calls
2206 aRes->Release (this);
2207 mySharedResources->UnBind (aKey);
2208 aDeadList.Append (aKey);
2211 for (Standard_Integer anIter = 0; anIter < aDeadList.Length(); ++anIter)
2213 myDelayed->UnBind (aDeadList.Value (anIter));
2217 // =======================================================================
2218 // function : BindTextures
2220 // =======================================================================
2221 Handle(OpenGl_TextureSet) OpenGl_Context::BindTextures (const Handle(OpenGl_TextureSet)& theTextures,
2222 const Handle(OpenGl_ShaderProgram)& theProgram)
2224 const Standard_Integer aTextureSetBits = !theTextures.IsNull() ? theTextures->TextureSetBits() : 0;
2225 const Standard_Integer aProgramBits = !theProgram.IsNull() ? theProgram->TextureSetBits() : 0;
2226 Standard_Integer aMissingBits = aProgramBits & ~aTextureSetBits;
2227 if (aMissingBits != 0
2228 && myTextureRgbaBlack.IsNull())
2230 // allocate mock textures
2231 myTextureRgbaBlack = new OpenGl_Texture();
2232 myTextureRgbaWhite = new OpenGl_Texture();
2233 Image_PixMap anImage;
2234 anImage.InitZero (Image_Format_RGBA, 2, 2, 0, (Standard_Byte )0);
2235 if (!myTextureRgbaBlack->Init (this, OpenGl_TextureFormat::Create<GLubyte, 4>(), Graphic3d_Vec2i (2, 2), Graphic3d_TOT_2D, &anImage))
2237 PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH,
2238 "Error: unable to create unit mock PBR texture map.");
2240 anImage.InitZero (Image_Format_RGBA, 2, 2, 0, (Standard_Byte )255);
2241 if (!myTextureRgbaWhite->Init (this, OpenGl_TextureFormat::Create<GLubyte, 4>(), Graphic3d_Vec2i (2, 2), Graphic3d_TOT_2D, &anImage))
2243 PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH,
2244 "Error: unable to create normal mock PBR texture map.");
2248 Handle(OpenGl_TextureSet) anOldTextures = myActiveTextures;
2249 if (myActiveTextures != theTextures)
2251 Handle(OpenGl_Context) aThisCtx (this);
2252 for (OpenGl_TextureSetPairIterator aSlotIter (myActiveTextures, theTextures); aSlotIter.More(); aSlotIter.Next())
2254 const Graphic3d_TextureUnit aTexUnit = aSlotIter.Unit();
2255 const OpenGl_Texture* aTextureOld = aSlotIter.Texture1();
2256 const OpenGl_Texture* aTextureNew = aSlotIter.Texture2();
2257 if (aTextureNew == aTextureOld)
2262 if (aTextureNew != NULL
2263 && aTextureNew->IsValid())
2265 if (aTexUnit >= myMaxTexCombined)
2267 PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
2268 TCollection_AsciiString("Texture unit ") + aTexUnit + " for " + aTextureNew->ResourceId() + " exceeds hardware limit " + myMaxTexCombined);
2272 aTextureNew->Bind (aThisCtx, aTexUnit);
2273 if (aTextureNew->Sampler()->ToUpdateParameters())
2275 if (aTextureNew->Sampler()->IsImmutable())
2277 aTextureNew->Sampler()->Init (aThisCtx, *aTextureNew);
2281 OpenGl_Sampler::applySamplerParams (aThisCtx, aTextureNew->Sampler()->Parameters(), aTextureNew->Sampler().get(), aTextureNew->GetTarget(), aTextureNew->MaxMipmapLevel());
2284 #if !defined(GL_ES_VERSION_2_0)
2285 if (core11ffp != NULL)
2287 OpenGl_Sampler::applyGlobalTextureParams (aThisCtx, *aTextureNew, aTextureNew->Sampler()->Parameters());
2291 else if (aTextureOld != NULL
2292 && aTextureOld->IsValid())
2294 aTextureOld->Unbind (aThisCtx, aTexUnit);
2295 #if !defined(GL_ES_VERSION_2_0)
2296 if (core11ffp != NULL)
2298 OpenGl_Sampler::resetGlobalTextureParams (aThisCtx, *aTextureOld, aTextureOld->Sampler()->Parameters());
2303 myActiveTextures = theTextures;
2306 if (myActiveMockTextures != aMissingBits)
2308 myActiveMockTextures = aMissingBits;
2309 for (Standard_Integer aBitIter = 0; aMissingBits != 0; ++aBitIter)
2311 Standard_Integer aUnitMask = 1 << aBitIter;
2312 if ((aUnitMask & aMissingBits) != 0)
2314 aMissingBits = aMissingBits & ~aUnitMask;
2315 if (aBitIter == Graphic3d_TextureUnit_Normal)
2317 myTextureRgbaBlack->Bind (this, static_cast<Graphic3d_TextureUnit>(aBitIter));
2321 myTextureRgbaWhite->Bind (this, static_cast<Graphic3d_TextureUnit>(aBitIter));
2327 return anOldTextures;
2330 // =======================================================================
2331 // function : BindProgram
2333 // =======================================================================
2334 Standard_Boolean OpenGl_Context::BindProgram (const Handle(OpenGl_ShaderProgram)& theProgram)
2336 if (core20fwd == NULL)
2338 return Standard_False;
2340 else if (myActiveProgram == theProgram)
2342 return Standard_True;
2345 if (theProgram.IsNull()
2346 || !theProgram->IsValid())
2348 if (!myActiveProgram.IsNull())
2350 core20fwd->glUseProgram (OpenGl_ShaderProgram::NO_PROGRAM);
2351 myActiveProgram.Nullify();
2353 return Standard_False;
2356 myActiveProgram = theProgram;
2357 core20fwd->glUseProgram (theProgram->ProgramId());
2358 return Standard_True;
2361 // =======================================================================
2362 // function : BindDefaultVao
2364 // =======================================================================
2365 void OpenGl_Context::BindDefaultVao()
2367 #if !defined(GL_ES_VERSION_2_0)
2368 if (myDefaultVao == 0
2374 core32->glBindVertexArray (myDefaultVao);
2378 // =======================================================================
2379 // function : SetDefaultFrameBuffer
2381 // =======================================================================
2382 Handle(OpenGl_FrameBuffer) OpenGl_Context::SetDefaultFrameBuffer (const Handle(OpenGl_FrameBuffer)& theFbo)
2384 Handle(OpenGl_FrameBuffer) aFbo = myDefaultFbo;
2385 myDefaultFbo = theFbo;
2389 // =======================================================================
2390 // function : SetShadingMaterial
2392 // =======================================================================
2393 void OpenGl_Context::SetShadingMaterial (const OpenGl_Aspects* theAspect,
2394 const Handle(Graphic3d_PresentationAttributes)& theHighlight)
2396 const Handle(Graphic3d_Aspects)& anAspect = (!theHighlight.IsNull() && !theHighlight->BasicFillAreaAspect().IsNull())
2397 ? (const Handle(Graphic3d_Aspects)& )theHighlight->BasicFillAreaAspect()
2398 : theAspect->Aspect();
2400 const bool toDistinguish = anAspect->Distinguish();
2401 const bool toMapTexture = anAspect->ToMapTexture();
2402 const Graphic3d_MaterialAspect& aMatFrontSrc = anAspect->FrontMaterial();
2403 const Graphic3d_MaterialAspect& aMatBackSrc = toDistinguish
2404 ? anAspect->BackMaterial()
2406 const Quantity_Color& aFrontIntColor = anAspect->InteriorColor();
2407 const Quantity_Color& aBackIntColor = toDistinguish
2408 ? anAspect->BackInteriorColor()
2411 myMaterial.Init (*this, aMatFrontSrc, aFrontIntColor, aMatBackSrc, aBackIntColor);
2412 if (!theHighlight.IsNull()
2413 && theHighlight->BasicFillAreaAspect().IsNull())
2415 myMaterial.SetColor (theHighlight->ColorRGBA().GetRGB());
2416 myMaterial.SetColor (theHighlight->ColorRGBA().GetRGB());
2419 float anAlphaFront = 1.0f, anAlphaBack = 1.0f;
2420 if (CheckIsTransparent (theAspect, theHighlight, anAlphaFront, anAlphaBack))
2422 myMaterial.Common[0].Diffuse.a() = anAlphaFront;
2423 myMaterial.Common[1].Diffuse.a() = anAlphaBack;
2425 myMaterial.Pbr[0].BaseColor.a() = anAlphaFront;
2426 myMaterial.Pbr[1].BaseColor.a() = anAlphaBack;
2429 // do not update material properties in case of zero reflection mode,
2430 // because GL lighting will be disabled by OpenGl_PrimitiveArray::DrawArray() anyway.
2431 const OpenGl_MaterialState& aMatState = myShaderManager->MaterialState();
2432 float anAlphaCutoff = (anAspect->AlphaMode() == Graphic3d_AlphaMode_Mask
2433 || anAspect->AlphaMode() == Graphic3d_AlphaMode_MaskBlend)
2434 ? anAspect->AlphaCutoff()
2436 if (anAspect->ToDrawEdges())
2438 if (anAspect->InteriorStyle() == Aspect_IS_EMPTY
2439 || (anAspect->InteriorStyle() == Aspect_IS_SOLID
2440 && anAspect->EdgeColorRGBA().Alpha() < 1.0f))
2442 anAlphaCutoff = 0.285f;
2445 if (theAspect->ShadingModel() == Graphic3d_TOSM_UNLIT)
2447 if (anAlphaCutoff == aMatState.AlphaCutoff())
2452 else if (myMaterial.IsEqual (aMatState.Material())
2453 && toDistinguish == aMatState.ToDistinguish()
2454 && toMapTexture == aMatState.ToMapTexture()
2455 && anAlphaCutoff == aMatState.AlphaCutoff())
2460 myShaderManager->UpdateMaterialStateTo (myMaterial, anAlphaCutoff, toDistinguish, toMapTexture);
2463 // =======================================================================
2464 // function : CheckIsTransparent
2466 // =======================================================================
2467 Standard_Boolean OpenGl_Context::CheckIsTransparent (const OpenGl_Aspects* theAspect,
2468 const Handle(Graphic3d_PresentationAttributes)& theHighlight,
2469 Standard_ShortReal& theAlphaFront,
2470 Standard_ShortReal& theAlphaBack)
2472 const Handle(Graphic3d_Aspects)& anAspect = (!theHighlight.IsNull() && !theHighlight->BasicFillAreaAspect().IsNull())
2473 ? (const Handle(Graphic3d_Aspects)& )theHighlight->BasicFillAreaAspect()
2474 : theAspect->Aspect();
2476 const bool toDistinguish = anAspect->Distinguish();
2477 const Graphic3d_MaterialAspect& aMatFrontSrc = anAspect->FrontMaterial();
2478 const Graphic3d_MaterialAspect& aMatBackSrc = toDistinguish
2479 ? anAspect->BackMaterial()
2482 // handling transparency
2483 if (!theHighlight.IsNull()
2484 && theHighlight->BasicFillAreaAspect().IsNull())
2486 theAlphaFront = theHighlight->ColorRGBA().Alpha();
2487 theAlphaBack = theHighlight->ColorRGBA().Alpha();
2491 theAlphaFront = aMatFrontSrc.Alpha();
2492 theAlphaBack = aMatBackSrc .Alpha();
2495 if (anAspect->AlphaMode() == Graphic3d_AlphaMode_BlendAuto)
2497 return theAlphaFront < 1.0f
2498 || theAlphaBack < 1.0f;
2500 // Graphic3d_AlphaMode_Mask and Graphic3d_AlphaMode_MaskBlend are not considered transparent here
2501 return anAspect->AlphaMode() == Graphic3d_AlphaMode_Blend;
2504 // =======================================================================
2505 // function : SetColor4fv
2507 // =======================================================================
2508 void OpenGl_Context::SetColor4fv (const OpenGl_Vec4& theColor)
2510 if (!myActiveProgram.IsNull())
2512 if (const OpenGl_ShaderUniformLocation& aLoc = myActiveProgram->GetStateLocation (OpenGl_OCCT_COLOR))
2514 myActiveProgram->SetUniform (this, aLoc, Vec4FromQuantityColor (theColor));
2517 #if !defined(GL_ES_VERSION_2_0)
2518 else if (core11ffp != NULL)
2520 core11ffp->glColor4fv (theColor.GetData());
2525 // =======================================================================
2526 // function : SetTypeOfLine
2528 // =======================================================================
2529 void OpenGl_Context::SetTypeOfLine (const Aspect_TypeOfLine theType,
2530 const Standard_ShortReal theFactor)
2532 SetLineStipple (theFactor, Graphic3d_Aspects::DefaultLinePatternForType (theType));
2535 // =======================================================================
2536 // function : SetLineStipple
2538 // =======================================================================
2539 void OpenGl_Context::SetLineStipple (const Standard_ShortReal theFactor,
2540 const uint16_t thePattern)
2542 if (!myActiveProgram.IsNull())
2544 if (const OpenGl_ShaderUniformLocation aPatternLoc = myActiveProgram->GetStateLocation (OpenGl_OCCT_LINE_STIPPLE_PATTERN))
2546 if (hasGlslBitwiseOps != OpenGl_FeatureNotAvailable)
2548 myActiveProgram->SetUniform (this, aPatternLoc, (Standard_Integer )thePattern);
2552 Standard_Integer aPatArr[16] = {};
2553 for (unsigned int aBit = 0; aBit < 16; ++aBit)
2555 aPatArr[aBit] = ((unsigned int)(thePattern) & (1U << aBit)) != 0 ? 1 : 0;
2557 myActiveProgram->SetUniform (this, aPatternLoc, 16, aPatArr);
2559 myActiveProgram->SetUniform (this, myActiveProgram->GetStateLocation (OpenGl_OCCT_LINE_STIPPLE_FACTOR), theFactor);
2564 #if !defined(GL_ES_VERSION_2_0)
2565 if (thePattern != 0xFFFF)
2567 if (core11ffp != NULL)
2569 core11fwd->glEnable (GL_LINE_STIPPLE);
2571 core11ffp->glLineStipple (static_cast<GLint> (theFactor),
2572 static_cast<GLushort> (thePattern));
2577 if (core11ffp != NULL)
2579 core11fwd->glDisable (GL_LINE_STIPPLE);
2585 // =======================================================================
2586 // function : SetLineWidth
2588 // =======================================================================
2589 void OpenGl_Context::SetLineWidth (const Standard_ShortReal theWidth)
2591 #if !defined(GL_ES_VERSION_2_0)
2592 if (core11ffp != NULL)
2595 // glLineWidth() is still defined within Core Profile, but has no effect with values != 1.0f
2596 core11fwd->glLineWidth (theWidth * myLineWidthScale);
2600 // =======================================================================
2601 // function : SetTextureMatrix
2603 // =======================================================================
2604 void OpenGl_Context::SetTextureMatrix (const Handle(Graphic3d_TextureParams)& theParams,
2605 const Standard_Boolean theIsTopDown)
2607 if (theParams.IsNull())
2612 const Graphic3d_Vec2& aScale = theParams->Scale();
2613 const Graphic3d_Vec2& aTrans = theParams->Translation();
2614 if (!myActiveProgram.IsNull())
2616 const GLint aUniLoc = myActiveProgram->GetStateLocation (OpenGl_OCCT_TEXTURE_TRSF2D);
2617 if (aUniLoc == OpenGl_ShaderProgram::INVALID_LOCATION)
2622 // pack transformation parameters
2623 OpenGl_Vec4 aTrsf[2] =
2625 OpenGl_Vec4 (-aTrans.x(), -aTrans.y(), aScale.x(), aScale.y()),
2626 OpenGl_Vec4 (static_cast<float> (std::sin (-theParams->Rotation() * M_PI / 180.0)),
2627 static_cast<float> (std::cos (-theParams->Rotation() * M_PI / 180.0)),
2630 if (caps->isTopDownTextureUV != theIsTopDown)
2633 aTrsf[0].y() = -aTrans.y() + 1.0f / aScale.y();
2634 aTrsf[0].w() = -aScale.y();
2636 myActiveProgram->SetUniform (this, aUniLoc, 2, aTrsf);
2640 #if !defined(GL_ES_VERSION_2_0)
2641 if (core11ffp != NULL)
2643 GLint aMatrixMode = GL_TEXTURE;
2644 ::glGetIntegerv (GL_MATRIX_MODE, &aMatrixMode);
2646 core11ffp->glMatrixMode (GL_TEXTURE);
2647 OpenGl_Mat4 aTextureMat;
2648 if (caps->isTopDownTextureUV != theIsTopDown)
2651 Graphic3d_TransformUtils::Scale (aTextureMat, aScale.x(), -aScale.y(), 1.0f);
2652 Graphic3d_TransformUtils::Translate (aTextureMat, -aTrans.x(), -aTrans.y() + 1.0f / aScale.y(), 0.0f);
2656 Graphic3d_TransformUtils::Scale (aTextureMat, aScale.x(), aScale.y(), 1.0f);
2657 Graphic3d_TransformUtils::Translate (aTextureMat, -aTrans.x(), -aTrans.y(), 0.0f);
2659 Graphic3d_TransformUtils::Rotate (aTextureMat, -theParams->Rotation(), 0.0f, 0.0f, 1.0f);
2660 core11ffp->glLoadMatrixf (aTextureMat);
2661 core11ffp->glMatrixMode (aMatrixMode);
2666 // =======================================================================
2667 // function : SetPointSize
2669 // =======================================================================
2670 void OpenGl_Context::SetPointSize (const Standard_ShortReal theSize)
2672 if (!myActiveProgram.IsNull())
2674 myActiveProgram->SetUniform (this, myActiveProgram->GetStateLocation (OpenGl_OCCT_POINT_SIZE), theSize);
2675 #if !defined(GL_ES_VERSION_2_0)
2676 //myContext->core11fwd->glEnable (GL_VERTEX_PROGRAM_POINT_SIZE);
2679 #if !defined(GL_ES_VERSION_2_0)
2682 core11fwd->glPointSize (theSize);
2683 if (core20fwd != NULL)
2685 //myContext->core11fwd->glDisable (GL_VERTEX_PROGRAM_POINT_SIZE);
2691 // =======================================================================
2692 // function : SetPointSpriteOrigin
2694 // =======================================================================
2695 void OpenGl_Context::SetPointSpriteOrigin()
2697 #if !defined(GL_ES_VERSION_2_0)
2698 if (core15fwd == NULL)
2703 const int aNewState = !myActiveProgram.IsNull() ? GL_UPPER_LEFT : GL_LOWER_LEFT;
2704 if (myPointSpriteOrig != aNewState)
2706 myPointSpriteOrig = aNewState;
2707 core15fwd->glPointParameteri (GL_POINT_SPRITE_COORD_ORIGIN, aNewState);
2712 // =======================================================================
2713 // function : SetGlNormalizeEnabled
2715 // =======================================================================
2716 Standard_Boolean OpenGl_Context::SetGlNormalizeEnabled (Standard_Boolean isEnabled)
2718 if (isEnabled == myIsGlNormalizeEnabled)
2720 return myIsGlNormalizeEnabled;
2723 Standard_Boolean anOldGlNormalize = myIsGlNormalizeEnabled;
2724 myIsGlNormalizeEnabled = isEnabled;
2725 #if !defined(GL_ES_VERSION_2_0)
2726 if (core11ffp != NULL)
2730 core11fwd->glEnable (GL_NORMALIZE);
2734 core11fwd->glDisable (GL_NORMALIZE);
2739 return anOldGlNormalize;
2742 // =======================================================================
2743 // function : SetShadeModel
2745 // =======================================================================
2746 void OpenGl_Context::SetShadeModel (Graphic3d_TypeOfShadingModel theModel)
2748 #if !defined(GL_ES_VERSION_2_0)
2749 if (core11ffp != NULL)
2751 const Standard_Integer aModel = theModel == Graphic3d_TOSM_FACET
2752 || theModel == Graphic3d_TOSM_PBR_FACET ? GL_FLAT : GL_SMOOTH;
2753 if (myShadeModel == aModel)
2757 myShadeModel = aModel;
2758 core11ffp->glShadeModel (aModel);
2765 // =======================================================================
2766 // function : SetPolygonMode
2768 // =======================================================================
2769 Standard_Integer OpenGl_Context::SetPolygonMode (const Standard_Integer theMode)
2771 if (myPolygonMode == theMode)
2773 return myPolygonMode;
2776 const Standard_Integer anOldPolygonMode = myPolygonMode;
2778 myPolygonMode = theMode;
2780 #if !defined(GL_ES_VERSION_2_0)
2781 ::glPolygonMode (GL_FRONT_AND_BACK, (GLenum)theMode);
2784 return anOldPolygonMode;
2787 // =======================================================================
2788 // function : SetPolygonHatchEnabled
2790 // =======================================================================
2791 bool OpenGl_Context::SetPolygonHatchEnabled (const bool theIsEnabled)
2793 if (core11ffp == NULL)
2797 else if (myHatchIsEnabled == theIsEnabled)
2799 return theIsEnabled;
2802 const bool anOldIsEnabled = myHatchIsEnabled;
2803 #if !defined(GL_ES_VERSION_2_0)
2805 && myActiveHatchType != Aspect_HS_SOLID)
2807 core11fwd->glEnable (GL_POLYGON_STIPPLE);
2811 core11fwd->glDisable (GL_POLYGON_STIPPLE);
2814 myHatchIsEnabled = theIsEnabled;
2815 return anOldIsEnabled;
2818 // =======================================================================
2819 // function : SetPolygonHatchStyle
2821 // =======================================================================
2822 Standard_Integer OpenGl_Context::SetPolygonHatchStyle (const Handle(Graphic3d_HatchStyle)& theStyle)
2824 const Standard_Integer aNewStyle = !theStyle.IsNull() ? theStyle->HatchType() : Aspect_HS_SOLID;
2825 if (myActiveHatchType == aNewStyle
2826 || core11ffp == NULL)
2828 return myActiveHatchType;
2831 #if !defined(GL_ES_VERSION_2_0)
2832 if (aNewStyle == Aspect_HS_SOLID)
2834 if (myHatchIsEnabled)
2836 core11fwd->glDisable (GL_POLYGON_STIPPLE);
2838 return myActiveHatchType;
2841 if (myHatchStyles.IsNull()
2842 && !GetResource ("OpenGl_LineAttributes", myHatchStyles))
2844 // share and register for release once the resource is no longer used
2845 myHatchStyles = new OpenGl_LineAttributes();
2846 ShareResource ("OpenGl_LineAttributes", myHatchStyles);
2849 const Standard_Integer anOldType = myActiveHatchType;
2850 myActiveHatchType = aNewStyle;
2851 myHatchStyles->SetTypeOfHatch (this, theStyle);
2852 if (myHatchIsEnabled
2853 && anOldType == Aspect_HS_SOLID)
2855 core11fwd->glEnable (GL_POLYGON_STIPPLE);
2859 return myActiveHatchType;
2863 // =======================================================================
2864 // function : SetPolygonOffset
2866 // =======================================================================
2867 void OpenGl_Context::SetPolygonOffset (const Graphic3d_PolygonOffset& theOffset)
2869 const bool toFillOld = (myPolygonOffset.Mode & Aspect_POM_Fill) == Aspect_POM_Fill;
2870 const bool toFillNew = (theOffset.Mode & Aspect_POM_Fill) == Aspect_POM_Fill;
2871 if (toFillNew != toFillOld)
2875 core11fwd->glEnable (GL_POLYGON_OFFSET_FILL);
2879 core11fwd->glDisable (GL_POLYGON_OFFSET_FILL);
2883 #if !defined(GL_ES_VERSION_2_0)
2884 const bool toLineOld = (myPolygonOffset.Mode & Aspect_POM_Line) == Aspect_POM_Line;
2885 const bool toLineNew = (theOffset.Mode & Aspect_POM_Line) == Aspect_POM_Line;
2886 if (toLineNew != toLineOld)
2890 core11fwd->glEnable (GL_POLYGON_OFFSET_LINE);
2894 core11fwd->glDisable (GL_POLYGON_OFFSET_LINE);
2898 const bool toPointOld = (myPolygonOffset.Mode & Aspect_POM_Point) == Aspect_POM_Point;
2899 const bool toPointNew = (theOffset.Mode & Aspect_POM_Point) == Aspect_POM_Point;
2900 if (toPointNew != toPointOld)
2904 core11fwd->glEnable (GL_POLYGON_OFFSET_POINT);
2908 core11fwd->glDisable (GL_POLYGON_OFFSET_POINT);
2913 if (myPolygonOffset.Factor != theOffset.Factor
2914 || myPolygonOffset.Units != theOffset.Units)
2916 core11fwd->glPolygonOffset (theOffset.Factor, theOffset.Units);
2918 myPolygonOffset = theOffset;
2921 // =======================================================================
2922 // function : SetCamera
2924 // =======================================================================
2925 void OpenGl_Context::SetCamera (const Handle(Graphic3d_Camera)& theCamera)
2927 myCamera = theCamera;
2928 if (!theCamera.IsNull())
2930 ProjectionState.SetCurrent (theCamera->ProjectionMatrixF());
2931 WorldViewState .SetCurrent (theCamera->OrientationMatrixF());
2932 ApplyProjectionMatrix();
2933 ApplyWorldViewMatrix();
2937 // =======================================================================
2938 // function : ApplyModelWorldMatrix
2940 // =======================================================================
2941 void OpenGl_Context::ApplyModelWorldMatrix()
2943 if (myShaderManager->ModelWorldState().ModelWorldMatrix() != ModelWorldState.Current())
2945 myShaderManager->UpdateModelWorldStateTo (ModelWorldState.Current());
2949 // =======================================================================
2950 // function : ApplyWorldViewMatrix
2952 // =======================================================================
2953 void OpenGl_Context::ApplyWorldViewMatrix()
2955 if (myShaderManager->ModelWorldState().ModelWorldMatrix() != THE_IDENTITY_MATRIX)
2957 myShaderManager->UpdateModelWorldStateTo (THE_IDENTITY_MATRIX);
2959 if (myShaderManager->WorldViewState().WorldViewMatrix() != WorldViewState.Current())
2961 myShaderManager->UpdateWorldViewStateTo (WorldViewState.Current());
2965 // =======================================================================
2966 // function : ApplyModelViewMatrix
2968 // =======================================================================
2969 void OpenGl_Context::ApplyModelViewMatrix()
2971 if (myShaderManager->ModelWorldState().ModelWorldMatrix() != ModelWorldState.Current())
2973 myShaderManager->UpdateModelWorldStateTo (ModelWorldState.Current());
2975 if (myShaderManager->WorldViewState().WorldViewMatrix() != WorldViewState.Current())
2977 myShaderManager->UpdateWorldViewStateTo (WorldViewState.Current());
2981 // =======================================================================
2982 // function : ApplyProjectionMatrix
2984 // =======================================================================
2985 void OpenGl_Context::ApplyProjectionMatrix()
2987 if (myShaderManager->ProjectionState().ProjectionMatrix() != ProjectionState.Current())
2989 myShaderManager->UpdateProjectionStateTo (ProjectionState.Current());
2993 // =======================================================================
2994 // function : EnableFeatures
2996 // =======================================================================
2997 void OpenGl_Context::EnableFeatures() const
3002 // =======================================================================
3003 // function : DisableFeatures
3005 // =======================================================================
3006 void OpenGl_Context::DisableFeatures() const
3008 // Disable stuff that's likely to slow down glDrawPixels.
3009 core11fwd->glDisable(GL_DITHER);
3010 core11fwd->glDisable(GL_BLEND);
3011 core11fwd->glDisable(GL_DEPTH_TEST);
3012 core11fwd->glDisable(GL_STENCIL_TEST);
3014 #if !defined(GL_ES_VERSION_2_0)
3015 if (core11ffp == NULL)
3020 core11fwd->glDisable(GL_TEXTURE_1D);
3021 core11fwd->glDisable(GL_TEXTURE_2D);
3023 core11fwd->glDisable(GL_LIGHTING);
3024 core11fwd->glDisable(GL_ALPHA_TEST);
3025 core11fwd->glDisable(GL_FOG);
3026 core11fwd->glDisable(GL_LOGIC_OP);
3028 glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
3029 glPixelTransferi(GL_RED_SCALE, 1);
3030 glPixelTransferi(GL_RED_BIAS, 0);
3031 glPixelTransferi(GL_GREEN_SCALE, 1);
3032 glPixelTransferi(GL_GREEN_BIAS, 0);
3033 glPixelTransferi(GL_BLUE_SCALE, 1);
3034 glPixelTransferi(GL_BLUE_BIAS, 0);
3035 glPixelTransferi(GL_ALPHA_SCALE, 1);
3036 glPixelTransferi(GL_ALPHA_BIAS, 0);
3038 if ((myGlVerMajor >= 1) && (myGlVerMinor >= 2))
3040 if (CheckExtension ("GL_CONVOLUTION_1D_EXT"))
3041 core11fwd->glDisable(GL_CONVOLUTION_1D_EXT);
3043 if (CheckExtension ("GL_CONVOLUTION_2D_EXT"))
3044 core11fwd->glDisable(GL_CONVOLUTION_2D_EXT);
3046 if (CheckExtension ("GL_SEPARABLE_2D_EXT"))
3047 core11fwd->glDisable(GL_SEPARABLE_2D_EXT);
3049 if (CheckExtension ("GL_SEPARABLE_2D_EXT"))
3050 core11fwd->glDisable(GL_HISTOGRAM_EXT);
3052 if (CheckExtension ("GL_MINMAX_EXT"))
3053 core11fwd->glDisable(GL_MINMAX_EXT);
3055 if (CheckExtension ("GL_TEXTURE_3D_EXT"))
3056 core11fwd->glDisable(GL_TEXTURE_3D_EXT);
3061 // =======================================================================
3062 // function : SetColorMaskRGBA
3064 // =======================================================================
3065 void OpenGl_Context::SetColorMaskRGBA (const NCollection_Vec4<bool>& theVal)
3067 core11fwd->glColorMask (theVal.r() ? GL_TRUE : GL_FALSE,
3068 theVal.g() ? GL_TRUE : GL_FALSE,
3069 theVal.b() ? GL_TRUE : GL_FALSE,
3070 theVal.a() ? GL_TRUE : GL_FALSE);
3071 myColorMask = theVal;
3074 // =======================================================================
3075 // function : SetColorMask
3077 // =======================================================================
3078 bool OpenGl_Context::SetColorMask (bool theToWriteColor)
3080 const bool anOldValue = myColorMask.r();
3081 myColorMask.SetValues (theToWriteColor, theToWriteColor, theToWriteColor, caps->buffersOpaqueAlpha ? false : theToWriteColor);
3082 const GLboolean toWrite = theToWriteColor ? GL_TRUE : GL_FALSE;
3083 core11fwd->glColorMask (toWrite, toWrite, toWrite, myColorMask.a() ? GL_TRUE : GL_FALSE);
3087 // =======================================================================
3088 // function : SetSampleAlphaToCoverage
3090 // =======================================================================
3091 bool OpenGl_Context::SetSampleAlphaToCoverage (bool theToEnable)
3093 bool toEnable = myAllowAlphaToCov && theToEnable;
3094 if (myAlphaToCoverage == toEnable)
3096 return myAlphaToCoverage;
3099 if (core15fwd != NULL)
3103 //core15fwd->core15fwd->glSampleCoverage (1.0f, GL_FALSE);
3104 core15fwd->glEnable (GL_SAMPLE_ALPHA_TO_COVERAGE);
3108 core15fwd->glDisable (GL_SAMPLE_ALPHA_TO_COVERAGE);
3112 const bool anOldValue = myAlphaToCoverage;
3113 myAlphaToCoverage = toEnable;
3117 // =======================================================================
3118 // function : GetBufferSubData
3120 // =======================================================================
3121 bool OpenGl_Context::GetBufferSubData (GLenum theTarget, GLintptr theOffset, GLsizeiptr theSize, void* theData)
3123 if (!hasGetBufferData)
3127 #ifdef __EMSCRIPTEN__
3130 Module.ctx.getBufferSubData($0, $1, HEAPU8.subarray($2, $2 + $3));
3131 }, theTarget, theOffset, theData, theSize);
3133 #elif defined(GL_ES_VERSION_2_0)
3134 if (void* aData = core30->glMapBufferRange (theTarget, theOffset, theSize, GL_MAP_READ_BIT))
3136 memcpy (theData, aData, theSize);
3137 core30->glUnmapBuffer (theTarget);
3142 core15fwd->glGetBufferSubData (theTarget, theOffset, theSize, theData);
3147 // =======================================================================
3148 // function : DumpJson
3150 // =======================================================================
3151 void OpenGl_Context::DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth) const
3153 OCCT_DUMP_TRANSIENT_CLASS_BEGIN (theOStream)
3155 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myAnisoMax)
3156 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myTexClamp)
3157 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myMaxTexDim)
3158 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myMaxTexCombined)
3159 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myMaxDumpSizeX)
3160 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myMaxDumpSizeY)
3161 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myMaxClipPlanes)
3162 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myMaxMsaaSamples)
3163 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myMaxDrawBuffers)
3164 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myMaxColorAttachments)
3165 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myGlVerMajor)
3166 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myGlVerMinor)
3167 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myIsInitialized)
3168 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myIsStereoBuffers)
3169 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myIsGlNormalizeEnabled)
3171 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myHasRayTracing)
3172 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myHasRayTracingTextures)
3173 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myHasRayTracingAdaptiveSampling)
3174 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myHasRayTracingAdaptiveSamplingAtomic)
3176 for (int i = 0; i < 4; i++)
3178 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myViewport[i])
3181 for (int i = 0; i < 4; i++)
3183 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myViewportVirt[i])
3186 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myPointSpriteOrig)
3187 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myRenderMode)
3188 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myPolygonMode)
3189 OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, &myPolygonOffset)
3190 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myToCullBackFaces)
3191 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myReadBuffer)
3193 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myDefaultVao)
3194 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myColorMask)
3195 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myAllowAlphaToCov)
3196 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myAlphaToCoverage)
3197 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myIsGlDebugCtx)
3199 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myResolution)
3200 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myResolutionRatio)
3202 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myLineWidthScale)
3203 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myLineFeather)
3204 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myRenderScale)
3205 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myRenderScaleInv)
3207 OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, &ModelWorldState)
3208 OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, &WorldViewState)
3209 OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, &ProjectionState)
3212 // =======================================================================
3213 // function : DumpJsonOpenGlState
3215 // =======================================================================
3216 void OpenGl_Context::DumpJsonOpenGlState (Standard_OStream& theOStream, Standard_Integer)
3218 GLboolean isEnableBlend = glIsEnabled (GL_BLEND);
3219 GLboolean isEnableCullFace = glIsEnabled (GL_CULL_FACE);
3220 GLboolean isEnableDepthTest = glIsEnabled (GL_DEPTH_TEST);
3222 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, isEnableBlend)
3223 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, isEnableCullFace)
3224 OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, isEnableDepthTest)