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.
16 #ifndef OpenGl_Context_HeaderFile
17 #define OpenGl_Context_HeaderFile
19 #include <Aspect_Handle.hxx>
20 #include <Aspect_HatchStyle.hxx>
21 #include <Aspect_Drawable.hxx>
22 #include <Aspect_Display.hxx>
23 #include <Aspect_GraphicsLibrary.hxx>
24 #include <Aspect_RenderingContext.hxx>
25 #include <Aspect_TypeOfLine.hxx>
26 #include <NCollection_DataMap.hxx>
27 #include <Graphic3d_DiagnosticInfo.hxx>
28 #include <Graphic3d_TextureUnit.hxx>
29 #include <NCollection_Map.hxx>
30 #include <NCollection_Handle.hxx>
31 #include <NCollection_List.hxx>
32 #include <NCollection_SparseArray.hxx>
33 #include <Message.hxx>
34 #include <OpenGl_Caps.hxx>
35 #include <OpenGl_LineAttributes.hxx>
36 #include <OpenGl_Material.hxx>
37 #include <OpenGl_MatrixState.hxx>
38 #include <OpenGl_Vec.hxx>
39 #include <OpenGl_Resource.hxx>
40 #include <OpenGl_TextureSet.hxx>
41 #include <Standard_Transient.hxx>
42 #include <TColStd_IndexedDataMapOfStringString.hxx>
43 #include <TColStd_PackedMapOfInteger.hxx>
44 #include <OpenGl_Clipping.hxx>
45 #include <OpenGl_GlCore11.hxx>
47 #include <NCollection_Shared.hxx>
49 //! Forward declarations
50 #if defined(__APPLE__)
51 #import <TargetConditionals.h>
52 #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
60 @class NSOpenGLContext;
62 struct NSOpenGLContext;
67 struct OpenGl_GlFunctions;
72 struct OpenGl_ArbFBOBlit;
73 struct OpenGl_ArbSamplerObject;
74 struct OpenGl_ArbTexBindless;
77 struct OpenGl_GlCore12;
78 struct OpenGl_GlCore13;
79 struct OpenGl_GlCore14;
80 struct OpenGl_GlCore15;
81 struct OpenGl_GlCore20;
82 struct OpenGl_GlCore21;
83 struct OpenGl_GlCore30;
84 struct OpenGl_GlCore31;
85 struct OpenGl_GlCore32;
86 struct OpenGl_GlCore33;
87 struct OpenGl_GlCore40;
88 struct OpenGl_GlCore41;
89 struct OpenGl_GlCore42;
90 struct OpenGl_GlCore43;
91 struct OpenGl_GlCore44;
92 struct OpenGl_GlCore45;
93 struct OpenGl_GlCore46;
95 class Graphic3d_Camera;
96 class Graphic3d_PresentationAttributes;
98 class OpenGl_FrameBuffer;
100 class OpenGl_ShaderProgram;
101 class OpenGl_ShaderManager;
102 class OpenGl_FrameStats;
104 enum OpenGl_FeatureFlag
106 OpenGl_FeatureNotAvailable = 0, //!< Feature is not supported by OpenGl implementation.
107 OpenGl_FeatureInExtensions = 1, //!< Feature is supported as extension.
108 OpenGl_FeatureInCore = 2 //!< Feature is supported as part of core profile.
111 DEFINE_STANDARD_HANDLE(OpenGl_Context, Standard_Transient)
113 //! This class generalize access to the GL context and available extensions.
115 //! Functions related to specific OpenGL version or extension are grouped into structures which can be accessed as fields of this class.
116 //! The most simple way to check that required functionality is available - is NULL check for the group:
118 //! if (myContext->core20 != NULL)
120 //! myGlProgram = myContext->core20->glCreateProgram();
121 //! .. do more stuff ..
125 //! .. compatibility with outdated configurations ..
129 //! Current implementation provide access to OpenGL core functionality up to 4.6 version (core12, core13, core14, etc.)
130 //! as well as several extensions (arbTBO, arbFBO, etc.).
132 //! OpenGL context might be initialized in Core Profile. In this case deprecated functionality become unavailable.
133 //! To select which core** function set should be used in specific case:
134 //! - Determine the minimal OpenGL version required for implemented functionality and use it to access all functions.
135 //! For example, if algorithm requires OpenGL 2.1+, it is better to write core20fwd->glEnable() rather than core11fwd->glEnable() for uniformity.
136 //! - Validate minimal requirements at initialization/creation time and omit checks within code where algorithm should be already initialized.
137 //! Properly escape code incompatible with Core Profile. The simplest way to check Core Profile is "if (core11ffp == NULL)".
139 //! Simplified extensions classification:
140 //! - prefixed with NV, AMD, ATI are vendor-specific (however may be provided by other vendors in some cases);
141 //! - prefixed with EXT are accepted by 2+ vendors;
142 //! - prefixed with ARB are accepted by Architecture Review Board and are candidates
143 //! for inclusion into GL core functionality.
144 //! Some functionality can be represented in several extensions simultaneously.
145 //! In this case developer should be careful because different specification may differ
146 //! in aspects (like enumeration values and error-handling).
148 //! Notice that some systems provide mechanisms to simultaneously incorporate with GL contexts with different capabilities.
149 //! For this reason OpenGl_Context should be initialized and used for each GL context independently.
151 //! Matrices of OpenGl transformations:
152 //! model -> world -> view -> projection
153 //! These matrices might be changed for local transformation, transform persistent using direct access to
154 //! current matrix of ModelWorldState, WorldViewState and ProjectionState
155 //! After, these matrices should be applied using ApplyModelWorldMatrix, ApplyWorldViewMatrix,
156 //! ApplyModelViewMatrix or ApplyProjectionMatrix.
157 class OpenGl_Context : public Standard_Transient
159 DEFINE_STANDARD_RTTIEXT(OpenGl_Context, Standard_Transient)
160 friend class OpenGl_Window;
161 friend struct OpenGl_GlFunctions;
164 typedef NCollection_Shared< NCollection_DataMap<TCollection_AsciiString, Handle(OpenGl_Resource)> > OpenGl_ResourcesMap;
166 //! Function for getting power of to number larger or equal to input number.
167 //! @param theNumber number to 'power of two'
168 //! @param theThreshold upper threshold
169 //! @return power of two number
170 inline static Standard_Integer GetPowerOfTwo (const Standard_Integer theNumber,
171 const Standard_Integer theThreshold)
173 for (Standard_Integer p2 = 2; p2 <= theThreshold; p2 <<= 1)
183 //! Format GL constant as hex value 0xABCD.
184 Standard_EXPORT static TCollection_AsciiString FormatGlEnumHex (int theGlEnum);
186 //! Format pointer as hex value 0xABCD.
187 Standard_EXPORT static TCollection_AsciiString FormatPointer (const void* thePtr);
189 //! Format size value.
190 Standard_EXPORT static TCollection_AsciiString FormatSize (Standard_Size theSize);
192 //! Return text description of GL error.
193 Standard_EXPORT static TCollection_AsciiString FormatGlError (int theGlError);
197 //! Empty constructor. You should call Init() to perform initialization with bound GL context.
198 Standard_EXPORT OpenGl_Context (const Handle(OpenGl_Caps)& theCaps = NULL);
201 Standard_EXPORT virtual ~OpenGl_Context();
203 //! Release all resources, including shared ones
204 Standard_EXPORT void forcedRelease();
206 //! Share GL context resources.
207 //! theShareCtx - handle to context to retrieve handles to shared resources.
208 Standard_EXPORT void Share (const Handle(OpenGl_Context)& theShareCtx);
210 //! Initialize class from currently bound OpenGL context. Method should be called only once.
211 //! @return false if no GL context is bound to the current thread
212 Standard_EXPORT Standard_Boolean Init (const Standard_Boolean theIsCoreProfile = Standard_False);
214 //! @return true if this context is valid (has been initialized)
215 inline Standard_Boolean IsValid() const
217 return myIsInitialized;
220 //! Initialize class from specified surface and rendering context. Method should be called only once.
221 //! The meaning of parameters is platform-specific.
225 //! Handle(Aspect_Window) theAspWin;
226 //! EGLSurface theEglSurf = eglCreateWindowSurface (theEglDisp, anEglConfig, (EGLNativeWindowType )theAspWin->NativeHandle(), NULL);
227 //! EGLDisplay theEglDisp = eglGetDisplay (EGL_DEFAULT_DISPLAY);
228 //! EGLContext theEglCtx = eglCreateContext ((EGLDisplay )theEglDisp, anEglConfig, EGL_NO_CONTEXT, anEglCtxAttribs);
229 //! Handle(OpenGl_Context) aGlCtx = new OpenGl_Context();
230 //! aGlCtx->Init ((Aspect_Drawable )theEglSurf, (Aspect_Display )theEglDisp, (Aspect_RenderingContext )theEglCtx);
235 //! Handle(WNT_Window) theAspWin;
236 //! HWND theWindow = (HWND )theAspWin->NativeHandle();
237 //! HDC theDevCtx = GetDC(theWindow);
238 //! HGLRC theGContext = wglCreateContext (theDevCtx);
239 //! Handle(OpenGl_Context) aGlCtx = new OpenGl_Context();
240 //! aGlCtx->Init ((Aspect_Drawable )theWindow, (Aspect_Display )theDevCtx, (Aspect_RenderingContext )theGContext);
245 //! Handle(Xw_Window) theAspWin;
246 //! Window theXWindow = (Window )theAspWin->NativeHandle();
247 //! Display* theXDisp = (Display* )theAspWin->DisplayConnection()->GetDisplayAspect();
248 //! GLXContext theGlxCtx = glXCreateContext (theXDisp, aVis.get(), NULL, GL_TRUE);
249 //! Handle(OpenGl_Context) aGlCtx = new OpenGl_Context();
250 //! aGlCtx->Init ((Aspect_Drawable )theXWindow, (Aspect_Display )theXDisp, (Aspect_RenderingContext )theGlxCtx);
253 //! @param theSurface [in] surface / window (EGLSurface | HWND | GLXDrawable/Window)
254 //! @param theDisplay [in] display or device context (EGLDisplay | HDC | Display*)
255 //! @param theContext [in] rendering context (EGLContext | HGLRC | GLXContext | EAGLContext* | NSOpenGLContext*)
256 //! @param theIsCoreProfile [in] flag indicating that passed GL rendering context has been created with Core Profile
257 //! @return false if OpenGL context can not be bound to specified surface
258 Standard_EXPORT Standard_Boolean Init (const Aspect_Drawable theSurface,
259 const Aspect_Display theDisplay,
260 const Aspect_RenderingContext theContext,
261 const Standard_Boolean theIsCoreProfile = Standard_False);
263 //! Return window handle currently bound to this OpenGL context (EGLSurface | HWND | GLXDrawable).
264 Aspect_Drawable Window() const { return myWindow; }
266 //! Return display / window device context (EGLDisplay | HDC | Display*).
267 Aspect_Display GetDisplay() const { return myDisplay; }
269 //! Return rendering context (EGLContext | HGLRC | GLXContext | EAGLContext* | NSOpenGLContext*).
270 Aspect_RenderingContext RenderingContext() const { return myGContext; }
272 #if defined(__APPLE__) && !defined(HAVE_XLIB)
273 #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
275 //! Initialize class from specified OpenGL ES context (EAGLContext). Method should be called only once.
276 Standard_Boolean Init (EAGLContext* theGContext,
277 const Standard_Boolean theIsCoreProfile = Standard_False)
279 return Init ((Aspect_Drawable )0, (Aspect_Display )0, (Aspect_RenderingContext )theGContext, theIsCoreProfile);
282 //! Initialize class from specified OpenGL context (NSOpenGLContext). Method should be called only once.
283 Standard_Boolean Init (NSOpenGLContext* theGContext,
284 const Standard_Boolean theIsCoreProfile = Standard_False)
286 return Init ((Aspect_Drawable )0, (Aspect_Display )0, (Aspect_RenderingContext )theGContext, theIsCoreProfile);
291 //! Read OpenGL version information from active context.
292 Standard_EXPORT static void ReadGlVersion (Standard_Integer& theGlVerMajor,
293 Standard_Integer& theGlVerMinor);
295 //! Check if theExtName extension is supported by active GL context.
296 Standard_EXPORT Standard_Boolean CheckExtension (const char* theExtName) const;
298 //! Check if theExtName extension is in extensions string.
299 Standard_EXPORT static Standard_Boolean CheckExtension (const char* theExtString,
300 const char* theExtName);
302 //! Auxiliary template to retrieve GL function pointer.
303 //! Pointer to function retrieved from library is statically casted
304 //! to requested type - there no way to check real signature of exported function.
305 //! The context should be bound before call.
306 //! @param theLastFailFuncName [out] set to theFuncName in case of failure, unmodified on success
307 //! @param theFuncName [in] function name to find
308 //! @param theFuncPtr [out] retrieved function pointer
309 //! @return TRUE on success
310 template <typename FuncType_t>
311 Standard_Boolean FindProcVerbose (const char*& theLastFailFuncName,
312 const char* theFuncName,
313 FuncType_t& theFuncPtr)
315 theFuncPtr = (FuncType_t )findProc (theFuncName);
316 if (theFuncPtr == NULL)
318 theLastFailFuncName = theFuncName;
319 return Standard_False;
321 return Standard_True;
324 //! Auxiliary template to retrieve GL function pointer.
325 //! Same as FindProcVerbose() but without auxiliary last function name argument.
326 template <typename FuncType_t>
327 Standard_Boolean FindProc (const char* theFuncName,
328 FuncType_t& theFuncPtr)
330 theFuncPtr = (FuncType_t )findProc (theFuncName);
331 return (theFuncPtr != NULL);
334 //! Return active graphics library.
335 Aspect_GraphicsLibrary GraphicsLibrary() const { return myGapi; }
337 //! @return true if detected GL version is greater or equal to requested one.
338 inline Standard_Boolean IsGlGreaterEqual (const Standard_Integer theVerMajor,
339 const Standard_Integer theVerMinor) const
341 return (myGlVerMajor > theVerMajor)
342 || (myGlVerMajor == theVerMajor && myGlVerMinor >= theVerMinor);
345 //! Return cached GL version major number.
346 Standard_Integer VersionMajor() const { return myGlVerMajor; }
348 //! Return cached GL version minor number.
349 Standard_Integer VersionMinor() const { return myGlVerMinor; }
351 //! Access entire map of loaded OpenGL functions.
352 const OpenGl_GlFunctions* Functions() const { return myFuncs.operator->(); }
354 //! Clean up errors stack for this GL context (glGetError() in loop).
355 //! @return true if some error has been cleared
356 Standard_EXPORT bool ResetErrors (const bool theToPrintErrors = false);
358 //! This method uses system-dependent API to retrieve information
359 //! about GL context bound to the current thread.
360 //! @return true if current thread is bound to this GL context
361 Standard_EXPORT Standard_Boolean IsCurrent() const;
363 //! Activates current context.
364 //! Class should be initialized with appropriate info.
365 Standard_EXPORT Standard_Boolean MakeCurrent();
367 //! Swap front/back buffers for this GL context (should be activated before!).
368 Standard_EXPORT void SwapBuffers();
370 //! Setup swap interval (VSync).
371 Standard_EXPORT Standard_Boolean SetSwapInterval (const Standard_Integer theInterval);
373 //! Return true if active mode is GL_RENDER (cached state)
374 Standard_EXPORT Standard_Boolean IsRender() const;
376 //! Return true if active mode is GL_FEEDBACK (cached state)
377 Standard_EXPORT Standard_Boolean IsFeedback() const;
379 //! This function retrieves information from GL about free GPU memory that is:
380 //! - OS-dependent. On some OS it is per-process and on others - for entire system.
381 //! - Vendor-dependent. Currently available only on NVIDIA and AMD/ATi drivers only.
382 //! - Numbers meaning may vary.
383 //! You should use this info only for diagnostics purposes.
384 //! @return free GPU dedicated memory in bytes.
385 Standard_EXPORT Standard_Size AvailableMemory() const;
387 //! This function retrieves information from GL about GPU memory
388 //! and contains more vendor-specific values than AvailableMemory().
389 Standard_EXPORT TCollection_AsciiString MemoryInfo() const;
391 //! This function retrieves information from GL about GPU memory.
392 Standard_EXPORT void MemoryInfo (TColStd_IndexedDataMapOfStringString& theDict) const;
394 //! Fill in the dictionary with OpenGL info.
395 //! Should be called with bound context.
396 Standard_EXPORT void DiagnosticInformation (TColStd_IndexedDataMapOfStringString& theDict,
397 Graphic3d_DiagnosticInfo theFlags) const;
399 //! Access shared resource by its name.
400 //! @param theKey - unique identifier;
401 //! @return handle to shared resource or NULL.
402 Standard_EXPORT const Handle(OpenGl_Resource)& GetResource (const TCollection_AsciiString& theKey) const;
404 //! Access shared resource by its name.
405 //! @param theKey - unique identifier;
406 //! @param theValue - handle to fill;
407 //! @return true if resource was shared.
408 template<typename TheHandleType>
409 Standard_Boolean GetResource (const TCollection_AsciiString& theKey,
410 TheHandleType& theValue) const
412 const Handle(OpenGl_Resource)& aResource = GetResource (theKey);
413 if (aResource.IsNull())
415 return Standard_False;
418 theValue = TheHandleType::DownCast (aResource);
419 return !theValue.IsNull();
422 //! Register shared resource.
423 //! Notice that after registration caller shouldn't release it by himself -
424 //! it will be automatically released on context destruction.
425 //! @param theKey - unique identifier, shouldn't be empty;
426 //! @param theResource - new resource to register, shouldn't be NULL.
427 Standard_EXPORT Standard_Boolean ShareResource (const TCollection_AsciiString& theKey,
428 const Handle(OpenGl_Resource)& theResource);
430 //! Release shared resource.
431 //! If there are more than one reference to this resource
432 //! (also used by some other existing object) then call will be ignored.
433 //! This means that current object itself should nullify handle before this call.
434 //! Notice that this is unrecommended operation at all and should be used
435 //! only in case of fat resources to release memory for other needs.
436 //! @param theKey unique identifier
437 //! @param theToDelay postpone release until next redraw call
438 Standard_EXPORT void ReleaseResource (const TCollection_AsciiString& theKey,
439 const Standard_Boolean theToDelay = Standard_False);
441 //! Append resource to queue for delayed clean up.
442 //! Resources in this queue will be released at next redraw call.
444 void DelayedRelease (Handle(T)& theResource)
446 myUnusedResources->Prepend (theResource);
447 theResource.Nullify();
450 //! Clean up the delayed release queue.
451 Standard_EXPORT void ReleaseDelayed();
453 //! Return map of shared resources.
454 const OpenGl_ResourcesMap& SharedResources() const { return *mySharedResources; }
456 //! @return tool for management of clippings within this context.
457 inline OpenGl_Clipping& ChangeClipping() { return myClippingState; }
459 //! @return tool for management of clippings within this context.
460 inline const OpenGl_Clipping& Clipping() const { return myClippingState; }
462 //! @return tool for management of shader programs within this context.
463 inline const Handle(OpenGl_ShaderManager)& ShaderManager() const { return myShaderManager; }
467 //! Either GL_CLAMP_TO_EDGE (1.2+) or GL_CLAMP (1.1).
468 Standard_Integer TextureWrapClamp() const { return myTexClamp; }
470 //! @return true if texture parameters GL_TEXTURE_BASE_LEVEL/GL_TEXTURE_MAX_LEVEL are supported.
471 Standard_Boolean HasTextureBaseLevel() const
473 return myGapi == Aspect_GraphicsLibrary_OpenGLES
474 ? IsGlGreaterEqual (3, 0)
475 : IsGlGreaterEqual (1, 2);
478 //! Return map of supported texture formats.
479 const Handle(Image_SupportedFormats)& SupportedTextureFormats() const { return mySupportedFormats; }
481 //! @return maximum degree of anisotropy texture filter
482 Standard_Integer MaxDegreeOfAnisotropy() const { return myAnisoMax; }
484 //! @return value for GL_MAX_TEXTURE_SIZE
485 Standard_Integer MaxTextureSize() const { return myMaxTexDim; }
487 //! @return value for GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS
488 Standard_Integer MaxCombinedTextureUnits() const { return myMaxTexCombined; }
490 //! This method returns the multi-texture limit for obsolete fixed-function pipeline.
491 //! Use MaxCombinedTextureUnits() instead for limits for using programmable pipeline.
492 //! @return value for GL_MAX_TEXTURE_UNITS
493 Standard_Integer MaxTextureUnitsFFP() const { return myMaxTexUnitsFFP; }
495 //! Return texture unit to be used for sprites (Graphic3d_TextureUnit_PointSprite by default).
496 Graphic3d_TextureUnit SpriteTextureUnit() const { return mySpriteTexUnit; }
498 //! @return true if MSAA textures are supported.
499 Standard_Boolean HasTextureMultisampling() const { return myHasMsaaTextures; }
501 //! @return value for GL_MAX_SAMPLES
502 Standard_Integer MaxMsaaSamples() const { return myMaxMsaaSamples; }
504 //! @return maximum FBO width for image dump
505 Standard_Integer MaxDumpSizeX() const { return myMaxDumpSizeX; }
507 //! @return maximum FBO height for image dump
508 Standard_Integer MaxDumpSizeY() const { return myMaxDumpSizeY; }
510 //! @return value for GL_MAX_DRAW_BUFFERS
511 Standard_Integer MaxDrawBuffers() const { return myMaxDrawBuffers; }
513 //! @return value for GL_MAX_COLOR_ATTACHMENTS
514 Standard_Integer MaxColorAttachments() const { return myMaxColorAttachments; }
516 //! Get maximum number of clip planes supported by OpenGl.
517 //! This value is implementation dependent. At least 6
518 //! planes should be supported by OpenGl (see specs).
519 //! @return value for GL_MAX_CLIP_PLANES
520 Standard_Integer MaxClipPlanes() const { return myMaxClipPlanes; }
522 //! @return TRUE if ray tracing mode is supported
523 Standard_Boolean HasRayTracing() const { return myHasRayTracing; }
525 //! @return TRUE if textures in ray tracing mode are supported
526 Standard_Boolean HasRayTracingTextures() const { return myHasRayTracingTextures; }
528 //! @return TRUE if adaptive screen sampling in ray tracing mode is supported
529 Standard_Boolean HasRayTracingAdaptiveSampling() const { return myHasRayTracingAdaptiveSampling; }
531 //! @return TRUE if atomic adaptive screen sampling in ray tracing mode is supported
532 Standard_Boolean HasRayTracingAdaptiveSamplingAtomic() const { return myHasRayTracingAdaptiveSamplingAtomic; }
534 //! Returns TRUE if sRGB rendering is supported.
541 //! Returns TRUE if sRGB rendering is supported and permitted.
542 bool ToRenderSRGB() const
545 && !caps->sRGBDisable
549 //! Returns TRUE if window/surface buffer is sRGB-ready.
551 //! When offscreen FBOs are created in sRGB, but window is not sRGB-ready,
552 //! blitting into window should be done with manual gamma correction.
554 //! In desktop OpenGL, window buffer can be considered as sRGB-ready by default,
555 //! even when application has NOT requested sRGB-ready pixel format,
556 //! and rendering is managed via GL_FRAMEBUFFER_SRGB state.
558 //! In OpenGL ES, sRGB-ready window surface should be explicitly requested on construction,
559 //! and cannot be disabled/enabled without GL_EXT_sRGB_write_control extension afterwards
560 //! (GL_FRAMEBUFFER_SRGB can be considered as always tuned ON).
561 bool IsWindowSRGB() const { return myIsSRgbWindow; }
563 //! Overrides if window/surface buffer is sRGB-ready or not (initialized with the context).
564 void SetWindowSRGB (bool theIsSRgb) { myIsSRgbWindow = theIsSRgb; }
566 //! Convert Quantity_ColorRGBA into vec4
567 //! with conversion or no conversion into non-linear sRGB
568 //! basing on ToRenderSRGB() flag.
569 OpenGl_Vec4 Vec4FromQuantityColor (const OpenGl_Vec4& theColor) const
571 return myIsSRgbActive
572 ? Vec4LinearFromQuantityColor(theColor)
573 : Vec4sRGBFromQuantityColor (theColor);
576 //! Convert Quantity_ColorRGBA into vec4.
577 //! Quantity_Color is expected to be linear RGB, hence conversion is NOT required
578 const OpenGl_Vec4& Vec4LinearFromQuantityColor (const OpenGl_Vec4& theColor) const { return theColor; }
580 //! Convert Quantity_ColorRGBA (linear RGB) into non-linear sRGB vec4.
581 OpenGl_Vec4 Vec4sRGBFromQuantityColor (const OpenGl_Vec4& theColor) const
583 return Quantity_ColorRGBA::Convert_LinearRGB_To_sRGB (theColor);
586 //! Returns TRUE if PBR shading model is supported.
587 //! Basically, feature requires OpenGL 3.0+ / OpenGL ES 3.0+ hardware; more precisely:
588 //! - Graphics hardware with moderate capabilities for compiling long enough GLSL program.
589 //! - FBO (e.g. for baking environment).
590 //! - Multi-texturing with >= 4 units (LUT and IBL textures).
591 //! - GL_RG32F texture format (arbTexRG + arbTexFloat)
592 //! - Cubemap texture lookup textureCubeLod()/textureLod() with LOD index within Fragment Shader,
593 //! which requires GLSL OpenGL 3.0+ / OpenGL ES 3.0+ or OpenGL 2.1 + GL_EXT_gpu_shader4 extension.
594 Standard_Boolean HasPBR() const { return myHasPBR; }
596 //! Returns texture unit where Environment Lookup Table is expected to be bound, or 0 if PBR is unavailable.
597 Graphic3d_TextureUnit PBREnvLUTTexUnit() const { return myPBREnvLUTTexUnit; }
599 //! Returns texture unit where Diffuse (irradiance) IBL map's spherical harmonics coefficients is expected to be bound, or 0 if PBR is unavailable.
600 Graphic3d_TextureUnit PBRDiffIBLMapSHTexUnit() const { return myPBRDiffIBLMapSHTexUnit; }
602 //! Returns texture unit where Specular IBL map is expected to be bound, or 0 if PBR is unavailable.
603 Graphic3d_TextureUnit PBRSpecIBLMapTexUnit() const { return myPBRSpecIBLMapTexUnit; }
605 //! Returns texture unit where shadow map is expected to be bound, or 0 if unavailable.
606 Graphic3d_TextureUnit ShadowMapTexUnit() const { return myShadowMapTexUnit; }
608 //! Returns texture unit for occDepthPeelingDepth within enabled Depth Peeling.
609 Graphic3d_TextureUnit DepthPeelingDepthTexUnit() const { return myDepthPeelingDepthTexUnit; }
611 //! Returns texture unit for occDepthPeelingFrontColor within enabled Depth Peeling.
612 Graphic3d_TextureUnit DepthPeelingFrontColorTexUnit() const { return myDepthPeelingFrontColorTexUnit; }
614 //! Returns true if VBO is supported and permitted.
615 inline bool ToUseVbo() const
617 return core15fwd != NULL
618 && !caps->vboDisable;
621 //! @return cached state of GL_NORMALIZE.
622 Standard_Boolean IsGlNormalizeEnabled() const { return myIsGlNormalizeEnabled; }
624 //! Sets GL_NORMALIZE enabled or disabled.
625 //! @return old value of the flag
626 Standard_EXPORT Standard_Boolean SetGlNormalizeEnabled (Standard_Boolean isEnabled);
628 //! @return cached state of polygon rasterization mode (glPolygonMode()).
629 Standard_Integer PolygonMode() const { return myPolygonMode; }
631 //! Sets polygon rasterization mode (glPolygonMode() function).
632 //! @return old value of the rasterization mode.
633 Standard_EXPORT Standard_Integer SetPolygonMode (const Standard_Integer theMode);
635 //! @return cached enabled state of polygon hatching rasterization.
636 bool IsPolygonHatchEnabled() const { return myHatchIsEnabled; }
638 //! Sets enabled state of polygon hatching rasterization
639 //! without affecting currently selected hatching pattern.
640 //! @return previous state of polygon hatching mode.
641 Standard_EXPORT bool SetPolygonHatchEnabled (const bool theIsEnabled);
643 //! @return cached state of polygon hatch type.
644 Standard_Integer PolygonHatchStyle() const { return myActiveHatchType; }
646 //! Sets polygon hatch pattern.
647 //! Zero-index value is a default alias for solid filling.
648 //! @param the type of hatch supported by base implementation of
649 //! OpenGl_LineAttributes (Aspect_HatchStyle) or the type supported by custom
650 //! implementation derived from OpenGl_LineAttributes class.
651 //! @return old type of hatch.
652 Standard_EXPORT Standard_Integer SetPolygonHatchStyle (const Handle(Graphic3d_HatchStyle)& theStyle);
654 //! Sets and applies current polygon offset.
655 Standard_EXPORT void SetPolygonOffset (const Graphic3d_PolygonOffset& theOffset);
657 //! Returns currently applied polygon offset parameters.
658 const Graphic3d_PolygonOffset& PolygonOffset() const { return myPolygonOffset; }
660 //! Returns camera object.
661 const Handle(Graphic3d_Camera)& Camera() const { return myCamera; }
663 //! Sets camera object to the context and update matrices.
664 Standard_EXPORT void SetCamera (const Handle(Graphic3d_Camera)& theCamera);
666 //! Applies matrix into shader manager stored in ModelWorldState to OpenGl.
667 //! In "model -> world -> view -> projection" it performs:
669 Standard_EXPORT void ApplyModelWorldMatrix();
671 //! Applies matrix stored in WorldViewState to OpenGl.
672 //! In "model -> world -> view -> projection" it performs:
673 //! model -> world -> view,
674 //! where model -> world is identical matrix
675 Standard_EXPORT void ApplyWorldViewMatrix();
677 //! Applies combination of matrices stored in ModelWorldState and WorldViewState to OpenGl.
678 //! In "model -> world -> view -> projection" it performs:
679 //! model -> world -> view
680 Standard_EXPORT void ApplyModelViewMatrix();
682 //! Applies matrix stored in ProjectionState to OpenGl.
683 //! In "model -> world -> view -> projection" it performs:
684 //! view -> projection
685 Standard_EXPORT void ApplyProjectionMatrix();
689 //! @return messenger instance
690 inline const Handle(Message_Messenger)& Messenger() const
692 return ::Message::DefaultMessenger();
695 //! Callback for GL_ARB_debug_output extension
696 //! @param theSource message source within GL_DEBUG_SOURCE_ enumeration
697 //! @param theType message type within GL_DEBUG_TYPE_ enumeration
698 //! @param theId message ID within source
699 //! @param theSeverity message severity within GL_DEBUG_SEVERITY_ enumeration
700 //! @param theMessage the message itself
701 Standard_EXPORT void PushMessage (const unsigned int theSource,
702 const unsigned int theType,
703 const unsigned int theId,
704 const unsigned int theSeverity,
705 const TCollection_ExtendedString& theMessage);
707 //! Adds a filter for messages with theId and theSource (GL_DEBUG_SOURCE_)
708 Standard_EXPORT Standard_Boolean ExcludeMessage (const unsigned int theSource,
709 const unsigned int theId);
711 //! Removes a filter for messages with theId and theSource (GL_DEBUG_SOURCE_)
712 Standard_EXPORT Standard_Boolean IncludeMessage (const unsigned int theSource,
713 const unsigned int theId);
715 //! @return true if OpenGl context supports left and right rendering buffers.
716 Standard_Boolean HasStereoBuffers() const { return myIsStereoBuffers; }
718 public: //! @name methods to alter or retrieve current state
720 //! Return structure holding frame statistics.
721 const Handle(OpenGl_FrameStats)& FrameStats() const { return myFrameStats; }
723 //! Set structure holding frame statistics.
724 //! This call makes sense only if application defines OpenGl_FrameStats sub-class.
725 void SetFrameStats (const Handle(OpenGl_FrameStats)& theStats) { myFrameStats = theStats; }
727 //! Return cached viewport definition (x, y, width, height).
728 const Standard_Integer* Viewport() const { return myViewport; }
730 //! Resize the viewport (alias for glViewport).
731 //! @param theRect viewport definition (x, y, width, height)
732 Standard_EXPORT void ResizeViewport (const Standard_Integer theRect[4]);
734 //! Return virtual viewport definition (x, y, width, height).
735 const Standard_Integer* VirtualViewport() const { return myViewportVirt; }
737 //! Return active read buffer.
738 Standard_Integer ReadBuffer() { return myReadBuffer; }
740 //! Switch read buffer, wrapper for ::glReadBuffer().
741 Standard_EXPORT void SetReadBuffer (const Standard_Integer theReadBuffer);
743 //! Return active draw buffer attached to a render target referred by index (layout location).
744 Standard_Integer DrawBuffer (Standard_Integer theIndex = 0) const
746 return theIndex >= myDrawBuffers.Lower()
747 && theIndex <= myDrawBuffers.Upper()
748 ? myDrawBuffers.Value (theIndex)
752 //! Switch draw buffer, wrapper for ::glDrawBuffer().
753 Standard_EXPORT void SetDrawBuffer (const Standard_Integer theDrawBuffer);
755 //! Switch draw buffer, wrapper for ::glDrawBuffers (GLsizei, const GLenum*).
756 Standard_EXPORT void SetDrawBuffers (const Standard_Integer theNb, const Standard_Integer* theDrawBuffers);
758 //! Switch read/draw buffers.
759 void SetReadDrawBuffer (const Standard_Integer theBuffer)
761 SetReadBuffer (theBuffer);
762 SetDrawBuffer (theBuffer);
765 //! Returns cached GL_FRAMEBUFFER_SRGB state.
766 //! If TRUE, GLSL program is expected to write linear RGB color.
767 //! Otherwise, GLSL program might need manually converting result color into sRGB color space.
768 bool IsFrameBufferSRGB() const { return myIsSRgbActive; }
770 //! Enables/disables GL_FRAMEBUFFER_SRGB flag.
771 //! This flag can be set to:
772 //! - TRUE when writing into offscreen FBO (always expected to be in sRGB or RGBF formats).
773 //! - TRUE when writing into sRGB-ready window buffer (might require choosing proper pixel format on window creation).
774 //! - FALSE if sRGB rendering is not supported or sRGB-not-ready window buffer is used for drawing.
775 //! @param theIsFbo [in] flag indicating writing into offscreen FBO (always expected sRGB-ready when sRGB FBO is supported)
776 //! or into window buffer (FALSE, sRGB-readiness might vary).
777 //! @param theIsSRgb [in] flag indicating off-screen FBO is sRGB-ready
778 Standard_EXPORT void SetFrameBufferSRGB (bool theIsFbo, bool theIsFboSRgb = true);
780 //! Return cached flag indicating writing into color buffer is enabled or disabled (glColorMask).
781 const NCollection_Vec4<bool>& ColorMaskRGBA() const { return myColorMask; }
783 //! Enable/disable writing into color buffer (wrapper for glColorMask).
784 Standard_EXPORT void SetColorMaskRGBA (const NCollection_Vec4<bool>& theToWriteColor);
786 //! Return cached flag indicating writing into color buffer is enabled or disabled (glColorMask).
787 bool ColorMask() const { return myColorMask.r(); }
789 //! Enable/disable writing into color buffer (wrapper for glColorMask).
790 //! Alpha component writes will be disabled unconditionally in case of caps->buffersOpaqueAlpha.
791 Standard_EXPORT bool SetColorMask (bool theToWriteColor);
793 //! Return TRUE if GL_SAMPLE_ALPHA_TO_COVERAGE usage is allowed.
794 bool AllowSampleAlphaToCoverage() const { return myAllowAlphaToCov; }
796 //! Allow GL_SAMPLE_ALPHA_TO_COVERAGE usage.
797 void SetAllowSampleAlphaToCoverage (bool theToEnable) { myAllowAlphaToCov = theToEnable; }
799 //! Return GL_SAMPLE_ALPHA_TO_COVERAGE state.
800 bool SampleAlphaToCoverage() const { return myAlphaToCoverage; }
802 //! Enable/disable GL_SAMPLE_ALPHA_TO_COVERAGE.
803 Standard_EXPORT bool SetSampleAlphaToCoverage (bool theToEnable);
805 //! Return back face culling state.
806 bool ToCullBackFaces() const { return myToCullBackFaces; }
808 //! Enable or disable back face culling (glEnable (GL_CULL_FACE)).
809 Standard_EXPORT void SetCullBackFaces (bool theToEnable);
811 //! Fetch OpenGl context state. This class tracks value of several OpenGl
812 //! state variables. Consulting the cached values is quicker than
813 //! doing the same via OpenGl API. Call this method if any of the controlled
814 //! OpenGl state variables has a possibility of being out-of-date.
815 Standard_EXPORT void FetchState();
817 //! @return active textures
818 const Handle(OpenGl_TextureSet)& ActiveTextures() const { return myActiveTextures; }
820 //! Bind specified texture set to current context taking into account active GLSL program.
821 Standard_DEPRECATED("BindTextures() with explicit GLSL program should be used instead")
822 Handle(OpenGl_TextureSet) BindTextures (const Handle(OpenGl_TextureSet)& theTextures)
824 return BindTextures (theTextures, myActiveProgram);
827 //! Bind specified texture set to current context, or unbind previous one when NULL specified.
828 //! @param theTextures [in] texture set to bind
829 //! @param theProgram [in] program attributes; when not NULL,
830 //! mock textures will be bound to texture units expected by GLSL program, but undefined by texture set
831 //! @return previous texture set
832 Standard_EXPORT Handle(OpenGl_TextureSet) BindTextures (const Handle(OpenGl_TextureSet)& theTextures,
833 const Handle(OpenGl_ShaderProgram)& theProgram);
835 //! @return active GLSL program
836 const Handle(OpenGl_ShaderProgram)& ActiveProgram() const
838 return myActiveProgram;
841 //! Bind specified program to current context,
842 //! or unbind previous one when NULL specified.
843 //! @return true if some program is bound to context
844 Standard_EXPORT Standard_Boolean BindProgram (const Handle(OpenGl_ShaderProgram)& theProgram);
846 //! Setup current shading material.
847 Standard_EXPORT void SetShadingMaterial (const OpenGl_Aspects* theAspect,
848 const Handle(Graphic3d_PresentationAttributes)& theHighlight);
850 //! Checks if transparency is required for the given aspect and highlight style.
851 Standard_EXPORT static Standard_Boolean CheckIsTransparent (const OpenGl_Aspects* theAspect,
852 const Handle(Graphic3d_PresentationAttributes)& theHighlight,
853 Standard_ShortReal& theAlphaFront,
854 Standard_ShortReal& theAlphaBack);
856 //! Checks if transparency is required for the given aspect and highlight style.
857 static Standard_Boolean CheckIsTransparent (const OpenGl_Aspects* theAspect,
858 const Handle(Graphic3d_PresentationAttributes)& theHighlight)
860 Standard_ShortReal anAlphaFront = 1.0f, anAlphaBack = 1.0f;
861 return CheckIsTransparent (theAspect, theHighlight, anAlphaFront, anAlphaBack);
864 //! Setup current color.
865 Standard_EXPORT void SetColor4fv (const OpenGl_Vec4& theColor);
867 //! Setup type of line.
868 Standard_EXPORT void SetTypeOfLine (const Aspect_TypeOfLine theType,
869 const Standard_ShortReal theFactor = 1.0f);
871 //! Setup stipple line pattern with 1.0f factor; wrapper for glLineStipple().
872 void SetLineStipple (const uint16_t thePattern) { SetLineStipple (1.0f, thePattern); }
874 //! Setup type of line; wrapper for glLineStipple().
875 Standard_EXPORT void SetLineStipple (const Standard_ShortReal theFactor,
876 const uint16_t thePattern);
878 //! Setup width of line.
879 Standard_EXPORT void SetLineWidth (const Standard_ShortReal theWidth);
881 //! Setup point size.
882 Standard_EXPORT void SetPointSize (const Standard_ShortReal theSize);
884 //! Setup point sprite origin using GL_POINT_SPRITE_COORD_ORIGIN state:
885 //! - GL_UPPER_LEFT when GLSL program is active;
886 //! flipping should be handled in GLSL program for compatibility with OpenGL ES
887 //! - GL_LOWER_LEFT for FFP
888 Standard_EXPORT void SetPointSpriteOrigin();
890 //! Setup texture matrix to active GLSL program or to FFP global state using glMatrixMode (GL_TEXTURE).
891 //! @param theParams [in] texture parameters
892 //! @param theIsTopDown [in] texture top-down flag
893 Standard_EXPORT void SetTextureMatrix (const Handle(Graphic3d_TextureParams)& theParams,
894 const Standard_Boolean theIsTopDown);
896 //! Bind default Vertex Array Object
897 Standard_EXPORT void BindDefaultVao();
899 //! Default Frame Buffer Object.
900 const Handle(OpenGl_FrameBuffer)& DefaultFrameBuffer() const
905 //! Setup new Default Frame Buffer Object and return previously set.
906 //! This call doesn't change Active FBO!
907 Standard_EXPORT Handle(OpenGl_FrameBuffer) SetDefaultFrameBuffer (const Handle(OpenGl_FrameBuffer)& theFbo);
909 //! Return debug context initialization state.
910 Standard_Boolean IsDebugContext() const
912 return myIsGlDebugCtx;
915 Standard_EXPORT void EnableFeatures() const;
917 Standard_EXPORT void DisableFeatures() const;
919 //! Return resolution for rendering text.
920 unsigned int Resolution() const { return myResolution; }
922 //! Resolution scale factor (rendered resolution to standard resolution).
923 //! This scaling factor for parameters like text size to be properly displayed on device (screen / printer).
924 Standard_ShortReal ResolutionRatio() const { return myResolutionRatio; }
926 //! Rendering scale factor (rendering viewport height to real window buffer height).
927 Standard_ShortReal RenderScale() const { return myRenderScale; }
929 //! Return TRUE if rendering scale factor is not 1.
930 Standard_Boolean HasRenderScale() const { return Abs (myRenderScale - 1.0f) > 0.0001f; }
932 //! Rendering scale factor (inverted value).
933 Standard_ShortReal RenderScaleInv() const { return myRenderScaleInv; }
935 //! Return scale factor for line width.
936 Standard_ShortReal LineWidthScale() const { return myLineWidthScale; }
938 //! Set resolution ratio.
939 //! Note that this method rounds @theRatio to nearest integer.
940 void SetResolution (unsigned int theResolution,
941 Standard_ShortReal theRatio,
942 Standard_ShortReal theScale)
944 myResolution = (unsigned int )(theScale * theResolution + 0.5f);
945 myRenderScale = theScale;
946 myRenderScaleInv = 1.0f / theScale;
947 SetResolutionRatio (theRatio * theScale);
950 //! Set resolution ratio.
951 //! Note that this method rounds @theRatio to nearest integer.
952 void SetResolutionRatio (const Standard_ShortReal theRatio)
954 myResolutionRatio = theRatio;
955 myLineWidthScale = Max (1.0f, std::floor (theRatio + 0.5f));
958 //! Return line feater width in pixels.
959 Standard_ShortReal LineFeather() const { return myLineFeather; }
961 //! Set line feater width.
962 void SetLineFeather(Standard_ShortReal theValue) { myLineFeather = theValue; }
964 //! Wrapper over glGetBufferSubData(), implemented as:
965 //! - OpenGL 1.5+ (desktop) via glGetBufferSubData();
966 //! - OpenGL ES 3.0+ via glMapBufferRange();
967 //! - WebGL 2.0+ via gl.getBufferSubData().
968 //! @param theTarget [in] target buffer to map
969 //! @param theOffset [in] offset to the beginning of sub-data
970 //! @param theSize [in] number of bytes to read
971 //! @param theData [out] destination pointer to fill
972 //! @return FALSE if functionality is unavailable
973 Standard_EXPORT bool GetBufferSubData (GLenum theTarget, GLintptr theOffset, GLsizeiptr theSize, void* theData);
975 //! Return Graphics Driver's vendor.
976 const TCollection_AsciiString& Vendor() const { return myVendor; }
978 //! Dumps the content of me into the stream
979 Standard_EXPORT void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const;
981 //! Dumps the content of openGL state into the stream
982 Standard_EXPORT static void DumpJsonOpenGlState (Standard_OStream& theOStream, Standard_Integer theDepth = -1);
984 //! Set GL_SHADE_MODEL value.
985 Standard_EXPORT void SetShadeModel (Graphic3d_TypeOfShadingModel theModel);
989 //! Wrapper to system function to retrieve GL function pointer by name.
990 Standard_EXPORT void* findProc (const char* theFuncName);
992 //! Print error if not all functions have been exported by context for reported version.
993 //! Note that this will never happen when using GLX, since returned functions can not be validated.
994 //! @param theGlVerMajor the OpenGL major version with missing functions
995 //! @param theGlVerMinor the OpenGL minor version with missing functions
996 //! @param theLastFailedProc function name which cannot be found
997 Standard_EXPORT void checkWrongVersion (Standard_Integer theGlVerMajor, Standard_Integer theGlVerMinor,
998 const char* theLastFailedProc);
1000 //! Private initialization function that should be called only once.
1001 Standard_EXPORT void init (const Standard_Boolean theIsCoreProfile);
1003 public: //! @name core profiles
1005 OpenGl_GlCore11* core11ffp; //!< OpenGL 1.1 core functionality
1006 OpenGl_GlCore11Fwd* core11fwd; //!< OpenGL 1.1 without deprecated entry points
1007 OpenGl_GlCore15* core15; //!< OpenGL 1.5 without deprecated entry points
1008 OpenGl_GlCore20* core20; //!< OpenGL 2.0 without deprecated entry points
1009 OpenGl_GlCore30* core30; //!< OpenGL 3.0 without deprecated entry points
1010 OpenGl_GlCore32* core32; //!< OpenGL 3.2 core profile
1011 OpenGl_GlCore33* core33; //!< OpenGL 3.3 core profile
1012 OpenGl_GlCore41* core41; //!< OpenGL 4.1 core profile
1013 OpenGl_GlCore42* core42; //!< OpenGL 4.2 core profile
1014 OpenGl_GlCore43* core43; //!< OpenGL 4.3 core profile
1015 OpenGl_GlCore44* core44; //!< OpenGL 4.4 core profile
1016 OpenGl_GlCore45* core45; //!< OpenGL 4.5 core profile
1017 OpenGl_GlCore46* core46; //!< OpenGL 4.6 core profile
1019 OpenGl_GlCore15* core15fwd; //!< obsolete entry left for code portability; core15 should be used instead
1020 OpenGl_GlCore20* core20fwd; //!< obsolete entry left for code portability; core20 should be used instead
1022 Handle(OpenGl_Caps) caps; //!< context options
1024 public: //! @name extensions
1026 Standard_Boolean hasGetBufferData; //!< flag indicating if GetBufferSubData() is supported
1027 Standard_Boolean hasPackRowLength; //!< supporting of GL_PACK_ROW_LENGTH parameters (any desktop OpenGL; OpenGL ES 3.0)
1028 Standard_Boolean hasUnpackRowLength; //!< supporting of GL_UNPACK_ROW_LENGTH parameters (any desktop OpenGL; OpenGL ES 3.0)
1029 Standard_Boolean hasHighp; //!< highp in GLSL ES fragment shader is supported
1030 Standard_Boolean hasUintIndex; //!< GLuint for index buffer is supported (always available on desktop; on OpenGL ES - since 3.0 or as extension GL_OES_element_index_uint)
1031 Standard_Boolean hasTexRGBA8; //!< always available on desktop; on OpenGL ES - since 3.0 or as extension GL_OES_rgb8_rgba8
1032 Standard_Boolean hasTexFloatLinear; //!< texture-filterable state for 32-bit floating texture formats (always on desktop, GL_OES_texture_float_linear within OpenGL ES)
1033 Standard_Boolean hasTexSRGB; //!< sRGB texture formats (desktop OpenGL 2.1, OpenGL ES 3.0 or OpenGL ES 2.0 + GL_EXT_sRGB)
1034 Standard_Boolean hasFboSRGB; //!< sRGB FBO render targets (desktop OpenGL 2.1, OpenGL ES 3.0)
1035 Standard_Boolean hasSRGBControl; //!< sRGB write control (any desktop OpenGL, OpenGL ES + GL_EXT_sRGB_write_control extension)
1036 Standard_Boolean hasFboRenderMipmap; //!< FBO render target could be non-zero mipmap level of texture
1037 OpenGl_FeatureFlag hasFlatShading; //!< Complex flag indicating support of Flat shading (Graphic3d_TypeOfShadingModel_Phong) (always available on desktop; on OpenGL ES - since 3.0 or as extension GL_OES_standard_derivatives)
1038 OpenGl_FeatureFlag hasGlslBitwiseOps; //!< GLSL supports bitwise operations; OpenGL 3.0 / OpenGL ES 3.0 (GLSL 130 / GLSL ES 300) or OpenGL 2.1 + GL_EXT_gpu_shader4
1039 OpenGl_FeatureFlag hasDrawBuffers; //!< Complex flag indicating support of multiple draw buffers (desktop OpenGL 2.0, OpenGL ES 3.0, GL_ARB_draw_buffers, GL_EXT_draw_buffers)
1040 OpenGl_FeatureFlag hasFloatBuffer; //!< Complex flag indicating support of float color buffer format (desktop OpenGL 3.0, GL_ARB_color_buffer_float, GL_EXT_color_buffer_float)
1041 OpenGl_FeatureFlag hasHalfFloatBuffer; //!< Complex flag indicating support of half-float color buffer format (desktop OpenGL 3.0, GL_ARB_color_buffer_float, GL_EXT_color_buffer_half_float)
1042 OpenGl_FeatureFlag hasSampleVariables; //!< Complex flag indicating support of MSAA variables in GLSL shader (desktop OpenGL 4.0, GL_ARB_sample_shading)
1043 OpenGl_FeatureFlag hasGeometryStage; //!< Complex flag indicating support of Geometry shader (desktop OpenGL 3.2, OpenGL ES 3.2, GL_EXT_geometry_shader)
1044 Standard_Boolean arbDrawBuffers; //!< GL_ARB_draw_buffers
1045 Standard_Boolean arbNPTW; //!< GL_ARB_texture_non_power_of_two
1046 Standard_Boolean arbTexRG; //!< GL_ARB_texture_rg
1047 Standard_Boolean arbTexFloat; //!< GL_ARB_texture_float (on desktop OpenGL - since 3.0 or as extension GL_ARB_texture_float; on OpenGL ES - since 3.0); @sa hasTexFloatLinear for linear filtering support
1048 OpenGl_ArbSamplerObject* arbSamplerObject; //!< GL_ARB_sampler_objects (on desktop OpenGL - since 3.3 or as extension GL_ARB_sampler_objects; on OpenGL ES - since 3.0)
1049 OpenGl_ArbTexBindless* arbTexBindless; //!< GL_ARB_bindless_texture
1050 OpenGl_ArbTBO* arbTBO; //!< GL_ARB_texture_buffer_object (on desktop OpenGL - since 3.1 or as extension GL_ARB_texture_buffer_object; on OpenGL ES - since 3.2)
1051 Standard_Boolean arbTboRGB32; //!< GL_ARB_texture_buffer_object_rgb32 (3-component TBO), in core since 4.0 (on OpenGL ES - since 3.2)
1052 Standard_Boolean arbClipControl; //!< GL_ARB_clip_control, in core since 4.5
1053 OpenGl_ArbIns* arbIns; //!< GL_ARB_draw_instanced (on desktop OpenGL - since 3.1 or as extension GL_ARB_draw_instanced; on OpenGL ES - since 3.0 or as extension GL_ANGLE_instanced_arrays to WebGL 1.0)
1054 OpenGl_ArbDbg* arbDbg; //!< GL_ARB_debug_output (on desktop OpenGL - since 4.3 or as extension GL_ARB_debug_output; on OpenGL ES - since 3.2 or as extension GL_KHR_debug)
1055 OpenGl_ArbFBO* arbFBO; //!< GL_ARB_framebuffer_object
1056 OpenGl_ArbFBOBlit* arbFBOBlit; //!< glBlitFramebuffer function, moved out from OpenGl_ArbFBO structure for compatibility with OpenGL ES 2.0
1057 Standard_Boolean arbSampleShading; //!< GL_ARB_sample_shading
1058 Standard_Boolean arbDepthClamp; //!< GL_ARB_depth_clamp (on desktop OpenGL - since 3.2 or as extensions GL_ARB_depth_clamp,NV_depth_clamp; unavailable on OpenGL ES)
1059 Standard_Boolean extFragDepth; //!< GL_EXT_frag_depth on OpenGL ES 2.0 (gl_FragDepthEXT built-in variable, before OpenGL ES 3.0)
1060 Standard_Boolean extDrawBuffers; //!< GL_EXT_draw_buffers
1061 OpenGl_ExtGS* extGS; //!< GL_EXT_geometry_shader4
1062 Standard_Boolean extBgra; //!< GL_EXT_bgra or GL_EXT_texture_format_BGRA8888 on OpenGL ES
1063 Standard_Boolean extAnis; //!< GL_EXT_texture_filter_anisotropic
1064 Standard_Boolean extPDS; //!< GL_EXT_packed_depth_stencil
1065 Standard_Boolean atiMem; //!< GL_ATI_meminfo
1066 Standard_Boolean nvxMem; //!< GL_NVX_gpu_memory_info
1067 Standard_Boolean oesSampleVariables; //!< GL_OES_sample_variables
1068 Standard_Boolean oesStdDerivatives; //!< GL_OES_standard_derivatives
1070 public: //! @name public properties tracking current state
1072 OpenGl_MatrixState<Standard_ShortReal> ModelWorldState; //!< state of orientation matrix
1073 OpenGl_MatrixState<Standard_ShortReal> WorldViewState; //!< state of orientation matrix
1074 OpenGl_MatrixState<Standard_ShortReal> ProjectionState; //!< state of projection matrix
1076 private: // system-dependent fields
1078 Aspect_Drawable myWindow; //!< surface EGLSurface | HWND | GLXDrawable
1079 Aspect_Display myDisplay; //!< display EGLDisplay | HDC | Display*
1080 Aspect_RenderingContext myGContext; //!< rendering context EGLContext | HGLRC | GLXContext | EAGLContext* | NSOpenGLContext*
1082 private: // context info
1084 typedef NCollection_Shared< NCollection_DataMap<TCollection_AsciiString, Standard_Integer> > OpenGl_DelayReleaseMap;
1085 typedef NCollection_Shared< NCollection_List<Handle(OpenGl_Resource)> > OpenGl_ResourcesStack;
1087 Handle(OpenGl_ResourcesMap) mySharedResources; //!< shared resources with unique identification key
1088 Handle(OpenGl_DelayReleaseMap) myDelayed; //!< shared resources for delayed release
1089 Handle(OpenGl_ResourcesStack) myUnusedResources; //!< stack of resources for delayed clean up
1091 OpenGl_Clipping myClippingState; //!< state of clip planes
1093 void* myGlLibHandle; //!< optional handle to GL library
1094 NCollection_Handle<OpenGl_GlFunctions>
1095 myFuncs; //!< mega structure for all GL functions
1096 Aspect_GraphicsLibrary myGapi; //!< GAPI name
1097 Handle(Image_SupportedFormats)
1098 mySupportedFormats; //!< map of supported texture formats
1099 Standard_Integer myAnisoMax; //!< maximum level of anisotropy texture filter
1100 Standard_Integer myTexClamp; //!< either GL_CLAMP_TO_EDGE (1.2+) or GL_CLAMP (1.1)
1101 Standard_Integer myMaxTexDim; //!< value for GL_MAX_TEXTURE_SIZE
1102 Standard_Integer myMaxTexCombined; //!< value for GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS
1103 Standard_Integer myMaxTexUnitsFFP; //!< value for GL_MAX_TEXTURE_UNITS (fixed-function pipeline only)
1104 Standard_Integer myMaxDumpSizeX; //!< maximum FBO width for image dump
1105 Standard_Integer myMaxDumpSizeY; //!< maximum FBO height for image dump
1106 Standard_Integer myMaxClipPlanes; //!< value for GL_MAX_CLIP_PLANES
1107 Standard_Integer myMaxMsaaSamples; //!< value for GL_MAX_SAMPLES
1108 Standard_Integer myMaxDrawBuffers; //!< value for GL_MAX_DRAW_BUFFERS
1109 Standard_Integer myMaxColorAttachments; //!< value for GL_MAX_COLOR_ATTACHMENTS
1110 Standard_Integer myGlVerMajor; //!< cached GL version major number
1111 Standard_Integer myGlVerMinor; //!< cached GL version minor number
1112 Standard_Boolean myIsInitialized; //!< flag indicates initialization state
1113 Standard_Boolean myIsStereoBuffers; //!< context supports stereo buffering
1114 Standard_Boolean myHasMsaaTextures; //!< context supports MSAA textures
1115 Standard_Boolean myIsGlNormalizeEnabled; //!< GL_NORMALIZE flag
1116 //!< Used to tell OpenGl that normals should be normalized
1117 Graphic3d_TextureUnit mySpriteTexUnit; //!< sampler2D occSamplerPointSprite, texture unit for point sprite texture
1119 Standard_Boolean myHasRayTracing; //! indicates whether ray tracing mode is supported
1120 Standard_Boolean myHasRayTracingTextures; //! indicates whether textures in ray tracing mode are supported
1121 Standard_Boolean myHasRayTracingAdaptiveSampling; //! indicates whether adaptive screen sampling in ray tracing mode is supported
1122 Standard_Boolean myHasRayTracingAdaptiveSamplingAtomic; //! indicates whether atomic adaptive screen sampling in ray tracing mode is supported
1124 Standard_Boolean myHasPBR; //!< indicates whether PBR shading model is supported
1125 Graphic3d_TextureUnit myPBREnvLUTTexUnit; //!< sampler2D occEnvLUT, texture unit where environment lookup table is expected to be binded (0 if PBR is not supported)
1126 Graphic3d_TextureUnit myPBRDiffIBLMapSHTexUnit; //!< sampler2D occDiffIBLMapSHCoeffs, texture unit where diffuse (irradiance) IBL map's spherical harmonics coefficients is expected to be binded
1127 //! (0 if PBR is not supported)
1128 Graphic3d_TextureUnit myPBRSpecIBLMapTexUnit; //!< samplerCube occSpecIBLMap, texture unit where specular IBL map is expected to be binded (0 if PBR is not supported)
1129 Graphic3d_TextureUnit myShadowMapTexUnit; //!< sampler2D occShadowMapSampler
1131 Graphic3d_TextureUnit myDepthPeelingDepthTexUnit; //!< sampler2D occDepthPeelingDepth, texture unit for Depth Peeling lookups
1132 Graphic3d_TextureUnit myDepthPeelingFrontColorTexUnit; //!< sampler2D occDepthPeelingFrontColor, texture unit for Depth Peeling lookups
1134 Handle(OpenGl_ShaderManager) myShaderManager; //! support object for managing shader programs
1136 private: //! @name fields tracking current state
1138 Handle(Graphic3d_Camera) myCamera; //!< active camera object
1139 Handle(OpenGl_FrameStats) myFrameStats; //!< structure accumulating frame statistics
1140 Handle(OpenGl_ShaderProgram) myActiveProgram; //!< currently active GLSL program
1141 Handle(OpenGl_TextureSet) myActiveTextures; //!< currently bound textures
1142 //!< currently active sampler objects
1143 Standard_Integer myActiveMockTextures; //!< currently active mock sampler objects
1144 Handle(OpenGl_FrameBuffer) myDefaultFbo; //!< default Frame Buffer Object
1145 Handle(OpenGl_LineAttributes) myHatchStyles; //!< resource holding predefined hatch styles patterns
1146 Standard_Integer myActiveHatchType; //!< currently activated type of polygon hatch
1147 Standard_Boolean myHatchIsEnabled; //!< current enabled state of polygon hatching rasterization
1148 Handle(OpenGl_Texture) myTextureRgbaBlack;//!< mock black texture returning (0, 0, 0, 0)
1149 Handle(OpenGl_Texture) myTextureRgbaWhite;//!< mock white texture returning (1, 1, 1, 1)
1150 Standard_Integer myViewport[4]; //!< current viewport
1151 Standard_Integer myViewportVirt[4]; //!< virtual viewport
1152 Standard_Integer myPointSpriteOrig; //!< GL_POINT_SPRITE_COORD_ORIGIN state (GL_UPPER_LEFT by default)
1153 Standard_Integer myRenderMode; //!< value for active rendering mode
1154 Standard_Integer myShadeModel; //!< currently used shade model (glShadeModel)
1155 Standard_Integer myPolygonMode; //!< currently used polygon rasterization mode (glPolygonMode)
1156 Graphic3d_PolygonOffset myPolygonOffset; //!< currently applied polygon offset
1157 bool myToCullBackFaces; //!< back face culling mode enabled state (glIsEnabled (GL_CULL_FACE))
1158 Standard_Integer myReadBuffer; //!< current read buffer
1159 NCollection_Array1<Standard_Integer>
1160 myDrawBuffers; //!< current draw buffers
1161 unsigned int myDefaultVao; //!< default Vertex Array Object
1162 NCollection_Vec4<bool> myColorMask; //!< flag indicating writing into color buffer is enabled or disabled (glColorMask)
1163 Standard_Boolean myAllowAlphaToCov; //!< flag allowing GL_SAMPLE_ALPHA_TO_COVERAGE usage
1164 Standard_Boolean myAlphaToCoverage; //!< flag indicating GL_SAMPLE_ALPHA_TO_COVERAGE state
1165 Standard_Boolean myIsGlDebugCtx; //!< debug context initialization state
1166 Standard_Boolean myIsSRgbWindow; //!< indicates that window buffer is sRGB-ready
1167 Standard_Boolean myIsSRgbActive; //!< flag indicating GL_FRAMEBUFFER_SRGB state
1168 TCollection_AsciiString myVendor; //!< Graphics Driver's vendor
1169 TColStd_PackedMapOfInteger myFilters[6]; //!< messages suppressing filter (for sources from GL_DEBUG_SOURCE_API_ARB to GL_DEBUG_SOURCE_OTHER_ARB)
1170 unsigned int myResolution; //!< Pixels density (PPI), defines scaling factor for parameters like text size
1171 Standard_ShortReal myResolutionRatio; //!< scaling factor for parameters like text size
1172 //! to be properly displayed on device (screen / printer)
1173 Standard_ShortReal myLineWidthScale; //!< scaling factor for line width
1174 Standard_ShortReal myLineFeather; //!< line feater width in pixels
1175 Standard_ShortReal myRenderScale; //!< scaling factor for rendering resolution
1176 Standard_ShortReal myRenderScaleInv; //!< scaling factor for rendering resolution (inverted value)
1177 OpenGl_Material myMaterial; //!< current front/back material state (cached to reduce GL context updates)
1181 //! Copying allowed only within Handles
1182 OpenGl_Context (const OpenGl_Context& );
1183 OpenGl_Context& operator= (const OpenGl_Context& );
1187 #endif // _OpenGl_Context_H__