Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-18 10:04:21

0001 // Created on: 2012-01-26
0002 // Created by: Kirill GAVRILOV
0003 // Copyright (c) 2012-2014 OPEN CASCADE SAS
0004 //
0005 // This file is part of Open CASCADE Technology software library.
0006 //
0007 // This library is free software; you can redistribute it and/or modify it under
0008 // the terms of the GNU Lesser General Public License version 2.1 as published
0009 // by the Free Software Foundation, with special exception defined in the file
0010 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
0011 // distribution for complete text of the license and disclaimer of any warranty.
0012 //
0013 // Alternatively, this file may be used under the terms of Open CASCADE
0014 // commercial license or contractual agreement.
0015 
0016 #ifndef OpenGl_Context_HeaderFile
0017 #define OpenGl_Context_HeaderFile
0018 
0019 #include <Aspect_Drawable.hxx>
0020 #include <Aspect_Display.hxx>
0021 #include <Aspect_GraphicsLibrary.hxx>
0022 #include <Aspect_RenderingContext.hxx>
0023 #include <Graphic3d_DiagnosticInfo.hxx>
0024 #include <Message.hxx>
0025 #include <OpenGl_Caps.hxx>
0026 #include <OpenGl_LineAttributes.hxx>
0027 #include <OpenGl_Material.hxx>
0028 #include <OpenGl_MatrixState.hxx>
0029 #include <OpenGl_Vec.hxx>
0030 #include <OpenGl_Resource.hxx>
0031 #include <OpenGl_TextureSet.hxx>
0032 #include <Standard_Transient.hxx>
0033 #include <TColStd_IndexedDataMapOfStringString.hxx>
0034 #include <TColStd_PackedMapOfInteger.hxx>
0035 #include <OpenGl_Clipping.hxx>
0036 
0037 #include <NCollection_Shared.hxx>
0038 
0039 #include <memory>
0040 
0041 //! Forward declarations
0042 #if defined(__APPLE__)
0043   #import <TargetConditionals.h>
0044   #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
0045     #ifdef __OBJC__
0046       @class EAGLContext;
0047     #else
0048       struct EAGLContext;
0049     #endif
0050   #else
0051     #ifdef __OBJC__
0052       @class NSOpenGLContext;
0053     #else
0054       struct NSOpenGLContext;
0055     #endif
0056   #endif
0057 #endif
0058 
0059 struct OpenGl_GlFunctions;
0060 struct OpenGl_ArbTBO;
0061 struct OpenGl_ArbIns;
0062 struct OpenGl_ArbDbg;
0063 struct OpenGl_ArbFBO;
0064 struct OpenGl_ArbFBOBlit;
0065 struct OpenGl_ArbSamplerObject;
0066 struct OpenGl_ArbTexBindless;
0067 struct OpenGl_ExtGS;
0068 
0069 struct OpenGl_GlCore11Fwd;
0070 struct OpenGl_GlCore11;
0071 struct OpenGl_GlCore12;
0072 struct OpenGl_GlCore13;
0073 struct OpenGl_GlCore14;
0074 struct OpenGl_GlCore15;
0075 struct OpenGl_GlCore20;
0076 struct OpenGl_GlCore21;
0077 struct OpenGl_GlCore30;
0078 struct OpenGl_GlCore31;
0079 struct OpenGl_GlCore32;
0080 struct OpenGl_GlCore33;
0081 struct OpenGl_GlCore40;
0082 struct OpenGl_GlCore41;
0083 struct OpenGl_GlCore42;
0084 struct OpenGl_GlCore43;
0085 struct OpenGl_GlCore44;
0086 struct OpenGl_GlCore45;
0087 struct OpenGl_GlCore46;
0088 
0089 class Graphic3d_Camera;
0090 class Graphic3d_PresentationAttributes;
0091 class OpenGl_Aspects;
0092 class OpenGl_FrameBuffer;
0093 class OpenGl_ShaderProgram;
0094 class OpenGl_ShaderManager;
0095 class OpenGl_FrameStats;
0096 
0097 enum OpenGl_FeatureFlag
0098 {
0099   OpenGl_FeatureNotAvailable = 0, //!< Feature is not supported by OpenGl implementation.
0100   OpenGl_FeatureInExtensions = 1, //!< Feature is supported as extension.
0101   OpenGl_FeatureInCore       = 2  //!< Feature is supported as part of core profile.
0102 };
0103 
0104 DEFINE_STANDARD_HANDLE(OpenGl_Context, Standard_Transient)
0105 
0106 //! This class generalize access to the GL context and available extensions.
0107 //!
0108 //! Functions related to specific OpenGL version or extension are grouped into structures which can be accessed as fields of this class.
0109 //! The most simple way to check that required functionality is available - is NULL check for the group:
0110 //! @code
0111 //!   if (myContext->core20 != NULL)
0112 //!   {
0113 //!     myGlProgram = myContext->core20->glCreateProgram();
0114 //!     .. do more stuff ..
0115 //!   }
0116 //!   else
0117 //!   {
0118 //!     .. compatibility with outdated configurations ..
0119 //!   }
0120 //! @endcode
0121 //!
0122 //! Current implementation provide access to OpenGL core functionality up to 4.6 version (core12, core13, core14, etc.)
0123 //! as well as several extensions (arbTBO, arbFBO, etc.).
0124 //!
0125 //! OpenGL context might be initialized in Core Profile. In this case deprecated functionality become unavailable.
0126 //! To select which core** function set should be used in specific case:
0127 //!  - Determine the minimal OpenGL version required for implemented functionality and use it to access all functions.
0128 //!    For example, if algorithm requires OpenGL 2.1+, it is better to write core20fwd->glEnable() rather than core11fwd->glEnable() for uniformity.
0129 //!  - Validate minimal requirements at initialization/creation time and omit checks within code where algorithm should be already initialized.
0130 //!    Properly escape code incompatible with Core Profile. The simplest way to check Core Profile is "if (core11ffp == NULL)".
0131 //!
0132 //! Simplified extensions classification:
0133 //!  - prefixed with NV, AMD, ATI are vendor-specific (however may be provided by other vendors in some cases);
0134 //!  - prefixed with EXT are accepted by 2+ vendors;
0135 //!  - prefixed with ARB are accepted by Architecture Review Board and are candidates
0136 //!    for inclusion into GL core functionality.
0137 //! Some functionality can be represented in several extensions simultaneously.
0138 //! In this case developer should be careful because different specification may differ
0139 //! in aspects (like enumeration values and error-handling).
0140 //!
0141 //! Notice that some systems provide mechanisms to simultaneously incorporate with GL contexts with different capabilities.
0142 //! For this reason OpenGl_Context should be initialized and used for each GL context independently.
0143 //!
0144 //! Matrices of OpenGl transformations:
0145 //! model -> world -> view -> projection
0146 //! These matrices might be changed for local transformation, transform persistent using direct access to
0147 //! current matrix of ModelWorldState, WorldViewState and ProjectionState
0148 //! After, these matrices should be applied using ApplyModelWorldMatrix, ApplyWorldViewMatrix,
0149 //! ApplyModelViewMatrix or ApplyProjectionMatrix.
0150 class OpenGl_Context : public Standard_Transient
0151 {
0152   DEFINE_STANDARD_RTTIEXT(OpenGl_Context, Standard_Transient)
0153   friend class OpenGl_Window;
0154   friend struct OpenGl_GlFunctions;
0155 public:
0156 
0157   typedef NCollection_Shared< NCollection_DataMap<TCollection_AsciiString, Handle(OpenGl_Resource)> > OpenGl_ResourcesMap;
0158 
0159   //! Function for getting power of to number larger or equal to input number.
0160   //! @param theNumber    number to 'power of two'
0161   //! @param theThreshold upper threshold
0162   //! @return power of two number
0163   inline static Standard_Integer GetPowerOfTwo (const Standard_Integer theNumber,
0164                                                 const Standard_Integer theThreshold)
0165   {
0166     for (Standard_Integer p2 = 2; p2 <= theThreshold; p2 <<= 1)
0167     {
0168       if (theNumber <= p2)
0169       {
0170         return p2;
0171       }
0172     }
0173     return theThreshold;
0174   }
0175 
0176   //! Format GL constant as hex value 0xABCD.
0177   Standard_EXPORT static TCollection_AsciiString FormatGlEnumHex (int theGlEnum);
0178 
0179   //! Format pointer as hex value 0xABCD.
0180   Standard_EXPORT static TCollection_AsciiString FormatPointer (const void* thePtr);
0181 
0182   //! Format size value.
0183   Standard_EXPORT static TCollection_AsciiString FormatSize (Standard_Size theSize);
0184 
0185   //! Return text description of GL error.
0186   Standard_EXPORT static TCollection_AsciiString FormatGlError (int theGlError);
0187 
0188 public:
0189 
0190   //! Empty constructor. You should call Init() to perform initialization with bound GL context.
0191   Standard_EXPORT OpenGl_Context (const Handle(OpenGl_Caps)& theCaps = NULL);
0192 
0193   //! Destructor.
0194   Standard_EXPORT virtual ~OpenGl_Context();
0195 
0196   //! Release all resources, including shared ones
0197   Standard_EXPORT void forcedRelease();
0198 
0199   //! Share GL context resources.
0200   //! theShareCtx - handle to context to retrieve handles to shared resources.
0201   Standard_EXPORT void Share (const Handle(OpenGl_Context)& theShareCtx);
0202 
0203   //! Initialize class from currently bound OpenGL context. Method should be called only once.
0204   //! @return false if no GL context is bound to the current thread
0205   Standard_EXPORT Standard_Boolean Init (const Standard_Boolean theIsCoreProfile = Standard_False);
0206 
0207   //! @return true if this context is valid (has been initialized)
0208   inline Standard_Boolean IsValid() const
0209   {
0210     return myIsInitialized;
0211   }
0212 
0213   //! Initialize class from specified surface and rendering context. Method should be called only once.
0214   //! The meaning of parameters is platform-specific.
0215   //!
0216   //! EGL:
0217   //! @code
0218   //!   Handle(Aspect_Window) theAspWin;
0219   //!   EGLSurface theEglSurf = eglCreateWindowSurface (theEglDisp, anEglConfig, (EGLNativeWindowType )theAspWin->NativeHandle(), NULL);
0220   //!   EGLDisplay theEglDisp = eglGetDisplay (EGL_DEFAULT_DISPLAY);
0221   //!   EGLContext theEglCtx  = eglCreateContext ((EGLDisplay )theEglDisp, anEglConfig, EGL_NO_CONTEXT, anEglCtxAttribs);
0222   //!   Handle(OpenGl_Context) aGlCtx = new OpenGl_Context();
0223   //!   aGlCtx->Init ((Aspect_Drawable )theEglSurf, (Aspect_Display )theEglDisp,  (Aspect_RenderingContext )theEglCtx);
0224   //! @endcode
0225   //!
0226   //! Windows (Win32):
0227   //! @code
0228   //!   Handle(WNT_Window) theAspWin;
0229   //!   HWND  theWindow   = (HWND )theAspWin->NativeHandle();
0230   //!   HDC   theDevCtx   = GetDC(theWindow);
0231   //!   HGLRC theGContext = wglCreateContext (theDevCtx);
0232   //!   Handle(OpenGl_Context) aGlCtx = new OpenGl_Context();
0233   //!   aGlCtx->Init ((Aspect_Drawable )theWindow, (Aspect_Display )theDevCtx, (Aspect_RenderingContext )theGContext);
0234   //! @endcode
0235   //!
0236   //! Linux (Xlib):
0237   //! @code
0238   //!   Handle(Xw_Window) theAspWin;
0239   //!   Window     theXWindow = (Window )theAspWin->NativeHandle();
0240   //!   Display*   theXDisp   = (Display* )theAspWin->DisplayConnection()->GetDisplayAspect();
0241   //!   GLXContext theGlxCtx  = glXCreateContext (theXDisp, aVis.get(), NULL, GL_TRUE);
0242   //!   Handle(OpenGl_Context) aGlCtx = new OpenGl_Context();
0243   //!   aGlCtx->Init ((Aspect_Drawable )theXWindow, (Aspect_Display )theXDisp,  (Aspect_RenderingContext )theGlxCtx);
0244   //! @endcode
0245   //!
0246   //! @param theSurface [in] surface / window          (EGLSurface | HWND  | GLXDrawable/Window)
0247   //! @param theDisplay [in] display or device context (EGLDisplay | HDC   | Display*)
0248   //! @param theContext [in] rendering context         (EGLContext | HGLRC | GLXContext | EAGLContext* | NSOpenGLContext*)
0249   //! @param theIsCoreProfile [in] flag indicating that passed GL rendering context has been created with Core Profile
0250   //! @return false if OpenGL context can not be bound to specified surface
0251   Standard_EXPORT Standard_Boolean Init (const Aspect_Drawable         theSurface,
0252                                          const Aspect_Display          theDisplay,
0253                                          const Aspect_RenderingContext theContext,
0254                                          const Standard_Boolean        theIsCoreProfile = Standard_False);
0255 
0256   //! Return window handle currently bound to this OpenGL context (EGLSurface | HWND | GLXDrawable).
0257   Aspect_Drawable Window() const { return myWindow; }
0258 
0259   //! Return display / window device context (EGLDisplay | HDC | Display*).
0260   Aspect_Display GetDisplay() const { return myDisplay; }
0261 
0262   //! Return rendering context (EGLContext | HGLRC | GLXContext | EAGLContext* | NSOpenGLContext*).
0263   Aspect_RenderingContext RenderingContext() const { return myGContext; }
0264 
0265 #if defined(__APPLE__) && !defined(HAVE_XLIB)
0266   #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
0267 
0268   //! Initialize class from specified OpenGL ES context (EAGLContext). Method should be called only once.
0269   Standard_Boolean Init (EAGLContext*           theGContext,
0270                          const Standard_Boolean theIsCoreProfile = Standard_False)
0271   {
0272     return Init ((Aspect_Drawable )0, (Aspect_Display )0, (Aspect_RenderingContext )theGContext, theIsCoreProfile);
0273   }
0274   #else
0275   //! Initialize class from specified OpenGL context (NSOpenGLContext). Method should be called only once.
0276   Standard_Boolean Init (NSOpenGLContext*       theGContext,
0277                          const Standard_Boolean theIsCoreProfile = Standard_False)
0278   {
0279     return Init ((Aspect_Drawable )0, (Aspect_Display )0, (Aspect_RenderingContext )theGContext, theIsCoreProfile);
0280   }
0281   #endif
0282 #endif
0283 
0284   //! Read OpenGL version information from active context.
0285   Standard_EXPORT static void ReadGlVersion (Standard_Integer& theGlVerMajor,
0286                                              Standard_Integer& theGlVerMinor);
0287 
0288   //! Check if theExtName extension is supported by active GL context.
0289   Standard_EXPORT Standard_Boolean CheckExtension (const char* theExtName) const;
0290 
0291   //! Check if theExtName extension is in extensions string.
0292   Standard_EXPORT static Standard_Boolean CheckExtension (const char* theExtString,
0293                                                           const char* theExtName);
0294 
0295   //! Auxiliary template to retrieve GL function pointer.
0296   //! Pointer to function retrieved from library is statically casted
0297   //! to requested type - there no way to check real signature of exported function.
0298   //! The context should be bound before call.
0299   //! @param theLastFailFuncName [out] set to theFuncName in case of failure, unmodified on success
0300   //! @param theFuncName [in] function name to find
0301   //! @param theFuncPtr [out] retrieved function pointer
0302   //! @return TRUE on success
0303   template <typename FuncType_t>
0304   Standard_Boolean FindProcVerbose (const char*& theLastFailFuncName,
0305                                     const char* theFuncName,
0306                                     FuncType_t& theFuncPtr)
0307   {
0308     theFuncPtr = (FuncType_t )findProc (theFuncName);
0309     if (theFuncPtr == NULL)
0310     {
0311       theLastFailFuncName = theFuncName;
0312       return Standard_False;
0313     }
0314     return Standard_True;
0315   }
0316 
0317   //! Auxiliary template to retrieve GL function pointer.
0318   //! Same as FindProcVerbose() but without auxiliary last function name argument.
0319   template <typename FuncType_t>
0320   Standard_Boolean FindProc (const char* theFuncName,
0321                              FuncType_t& theFuncPtr)
0322   {
0323     theFuncPtr = (FuncType_t )findProc (theFuncName);
0324     return (theFuncPtr != NULL);
0325   }
0326 
0327   //! Return active graphics library.
0328   Aspect_GraphicsLibrary GraphicsLibrary() const { return myGapi; }
0329 
0330   //! @return true if detected GL version is greater or equal to requested one.
0331   inline Standard_Boolean IsGlGreaterEqual (const Standard_Integer theVerMajor,
0332                                             const Standard_Integer theVerMinor) const
0333   {
0334     return (myGlVerMajor >  theVerMajor)
0335         || (myGlVerMajor == theVerMajor && myGlVerMinor >= theVerMinor);
0336   }
0337 
0338   //! Return cached GL version major number.
0339   Standard_Integer VersionMajor() const { return myGlVerMajor; }
0340 
0341   //! Return cached GL version minor number.
0342   Standard_Integer VersionMinor() const { return myGlVerMinor; }
0343 
0344   //! Access entire map of loaded OpenGL functions.
0345   const OpenGl_GlFunctions* Functions() const { return myFuncs.get(); }
0346 
0347   //! Clean up errors stack for this GL context (glGetError() in loop).
0348   //! @return true if some error has been cleared
0349   Standard_EXPORT bool ResetErrors (const bool theToPrintErrors = false);
0350 
0351   //! This method uses system-dependent API to retrieve information
0352   //! about GL context bound to the current thread.
0353   //! @return true if current thread is bound to this GL context
0354   Standard_EXPORT Standard_Boolean IsCurrent() const;
0355 
0356   //! Activates current context.
0357   //! Class should be initialized with appropriate info.
0358   Standard_EXPORT Standard_Boolean MakeCurrent();
0359 
0360   //! Swap front/back buffers for this GL context (should be activated before!).
0361   Standard_EXPORT void SwapBuffers();
0362 
0363   //! Setup swap interval (VSync).
0364   Standard_EXPORT Standard_Boolean SetSwapInterval (const Standard_Integer theInterval);
0365 
0366   //! Return true if active mode is GL_RENDER (cached state)
0367   Standard_EXPORT Standard_Boolean IsRender() const;
0368 
0369   //! Return true if active mode is GL_FEEDBACK (cached state)
0370   Standard_EXPORT Standard_Boolean IsFeedback() const;
0371 
0372   //! This function retrieves information from GL about free GPU memory that is:
0373   //!  - OS-dependent. On some OS it is per-process and on others - for entire system.
0374   //!  - Vendor-dependent. Currently available only on NVIDIA and AMD/ATi drivers only.
0375   //!  - Numbers meaning may vary.
0376   //! You should use this info only for diagnostics purposes.
0377   //! @return free GPU dedicated memory in bytes.
0378   Standard_EXPORT Standard_Size AvailableMemory() const;
0379 
0380   //! This function retrieves information from GL about GPU memory
0381   //! and contains more vendor-specific values than AvailableMemory().
0382   Standard_EXPORT TCollection_AsciiString MemoryInfo() const;
0383 
0384   //! This function retrieves information from GL about GPU memory.
0385   Standard_EXPORT void MemoryInfo (TColStd_IndexedDataMapOfStringString& theDict) const;
0386 
0387   //! Fill in the dictionary with OpenGL info.
0388   //! Should be called with bound context.
0389   Standard_EXPORT void DiagnosticInformation (TColStd_IndexedDataMapOfStringString& theDict,
0390                                               Graphic3d_DiagnosticInfo theFlags) const;
0391 
0392   //! Fetches information about window buffer pixel format.
0393   Standard_EXPORT void WindowBufferBits (Graphic3d_Vec4i& theColorBits,
0394                                          Graphic3d_Vec2i& theDepthStencilBits) const;
0395 
0396   //! Access shared resource by its name.
0397   //! @param  theKey - unique identifier;
0398   //! @return handle to shared resource or NULL.
0399   Standard_EXPORT const Handle(OpenGl_Resource)& GetResource (const TCollection_AsciiString& theKey) const;
0400 
0401   //! Access shared resource by its name.
0402   //! @param  theKey   - unique identifier;
0403   //! @param  theValue - handle to fill;
0404   //! @return true if resource was shared.
0405   template<typename TheHandleType>
0406   Standard_Boolean GetResource (const TCollection_AsciiString& theKey,
0407                                 TheHandleType&                 theValue) const
0408   {
0409     const Handle(OpenGl_Resource)& aResource = GetResource (theKey);
0410     if (aResource.IsNull())
0411     {
0412       return Standard_False;
0413     }
0414 
0415     theValue = TheHandleType::DownCast (aResource);
0416     return !theValue.IsNull();
0417   }
0418 
0419   //! Register shared resource.
0420   //! Notice that after registration caller shouldn't release it by himself -
0421   //! it will be automatically released on context destruction.
0422   //! @param theKey      - unique identifier, shouldn't be empty;
0423   //! @param theResource - new resource to register, shouldn't be NULL.
0424   Standard_EXPORT Standard_Boolean ShareResource (const TCollection_AsciiString& theKey,
0425                                                   const Handle(OpenGl_Resource)& theResource);
0426 
0427   //! Release shared resource.
0428   //! If there are more than one reference to this resource
0429   //! (also used by some other existing object) then call will be ignored.
0430   //! This means that current object itself should nullify handle before this call.
0431   //! Notice that this is unrecommended operation at all and should be used
0432   //! only in case of fat resources to release memory for other needs.
0433   //! @param theKey     unique identifier
0434   //! @param theToDelay postpone release until next redraw call
0435   Standard_EXPORT void ReleaseResource (const TCollection_AsciiString& theKey,
0436                                         const Standard_Boolean         theToDelay = Standard_False);
0437 
0438   //! Append resource to queue for delayed clean up.
0439   //! Resources in this queue will be released at next redraw call.
0440   template <class T>
0441   void DelayedRelease (Handle(T)& theResource)
0442   {
0443     myUnusedResources->Prepend (theResource);
0444     theResource.Nullify();
0445   }
0446 
0447   //! Clean up the delayed release queue.
0448   Standard_EXPORT void ReleaseDelayed();
0449 
0450   //! Return map of shared resources.
0451   const OpenGl_ResourcesMap& SharedResources() const { return *mySharedResources; }
0452 
0453   //! @return tool for management of clippings within this context.
0454   inline OpenGl_Clipping& ChangeClipping() { return myClippingState; }
0455 
0456   //! @return tool for management of clippings within this context.
0457   inline const OpenGl_Clipping& Clipping() const { return myClippingState; }
0458 
0459   //! @return tool for management of shader programs within this context.
0460   inline const Handle(OpenGl_ShaderManager)& ShaderManager() const { return myShaderManager; }
0461 
0462 public:
0463 
0464   //! Either GL_CLAMP_TO_EDGE (1.2+) or GL_CLAMP (1.1).
0465   Standard_Integer TextureWrapClamp() const { return myTexClamp; }
0466 
0467   //! @return true if texture parameters GL_TEXTURE_BASE_LEVEL/GL_TEXTURE_MAX_LEVEL are supported.
0468   Standard_Boolean HasTextureBaseLevel() const
0469   {
0470     return myGapi == Aspect_GraphicsLibrary_OpenGLES
0471          ? IsGlGreaterEqual (3, 0)
0472          : IsGlGreaterEqual (1, 2);
0473   }
0474 
0475   //! Return map of supported texture formats.
0476   const Handle(Image_SupportedFormats)& SupportedTextureFormats() const { return mySupportedFormats; }
0477 
0478   //! @return maximum degree of anisotropy texture filter
0479   Standard_Integer MaxDegreeOfAnisotropy() const { return myAnisoMax; }
0480 
0481   //! @return value for GL_MAX_TEXTURE_SIZE
0482   Standard_Integer MaxTextureSize() const { return myMaxTexDim; }
0483 
0484   //! @return value for GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS
0485   Standard_Integer MaxCombinedTextureUnits() const { return myMaxTexCombined; }
0486 
0487   //! This method returns the multi-texture limit for obsolete fixed-function pipeline.
0488   //! Use MaxCombinedTextureUnits() instead for limits for using programmable pipeline.
0489   //! @return value for GL_MAX_TEXTURE_UNITS
0490   Standard_Integer MaxTextureUnitsFFP() const { return myMaxTexUnitsFFP; }
0491 
0492   //! Return texture unit to be used for sprites (Graphic3d_TextureUnit_PointSprite by default).
0493   Graphic3d_TextureUnit SpriteTextureUnit() const { return mySpriteTexUnit; }
0494 
0495   //! @return true if MSAA textures are supported.
0496   Standard_Boolean HasTextureMultisampling() const { return myHasMsaaTextures; }
0497 
0498   //! @return value for GL_MAX_SAMPLES
0499   Standard_Integer MaxMsaaSamples() const { return myMaxMsaaSamples; }
0500 
0501   //! @return maximum FBO width for image dump
0502   Standard_Integer MaxDumpSizeX() const { return myMaxDumpSizeX; }
0503 
0504   //! @return maximum FBO height for image dump
0505   Standard_Integer MaxDumpSizeY() const { return myMaxDumpSizeY; }
0506 
0507   //! @return value for GL_MAX_DRAW_BUFFERS
0508   Standard_Integer MaxDrawBuffers() const { return myMaxDrawBuffers; }
0509 
0510   //! @return value for GL_MAX_COLOR_ATTACHMENTS
0511   Standard_Integer MaxColorAttachments() const { return myMaxColorAttachments; }
0512 
0513   //! Get maximum number of clip planes supported by OpenGl.
0514   //! This value is implementation dependent. At least 6
0515   //! planes should be supported by OpenGl (see specs).
0516   //! @return value for GL_MAX_CLIP_PLANES
0517   Standard_Integer MaxClipPlanes() const { return myMaxClipPlanes; }
0518 
0519   //! @return TRUE if ray tracing mode is supported
0520   Standard_Boolean HasRayTracing() const { return myHasRayTracing; }
0521 
0522   //! @return TRUE if textures in ray tracing mode are supported
0523   Standard_Boolean HasRayTracingTextures() const { return myHasRayTracingTextures; }
0524 
0525   //! @return TRUE if adaptive screen sampling in ray tracing mode is supported
0526   Standard_Boolean HasRayTracingAdaptiveSampling() const { return myHasRayTracingAdaptiveSampling; }
0527 
0528   //! @return TRUE if atomic adaptive screen sampling in ray tracing mode is supported
0529   Standard_Boolean HasRayTracingAdaptiveSamplingAtomic() const { return myHasRayTracingAdaptiveSamplingAtomic; }
0530 
0531   //! Returns TRUE if sRGB rendering is supported.
0532   bool HasSRGB() const
0533   {
0534     return hasTexSRGB
0535        &&  hasFboSRGB;
0536   }
0537 
0538   //! Returns TRUE if sRGB rendering is supported and permitted.
0539   bool ToRenderSRGB() const
0540   {
0541     return HasSRGB()
0542        && !caps->sRGBDisable
0543        && !caps->ffpEnable;
0544   }
0545 
0546   //! Returns TRUE if window/surface buffer is sRGB-ready.
0547   //!
0548   //! When offscreen FBOs are created in sRGB, but window is not sRGB-ready,
0549   //! blitting into window should be done with manual gamma correction.
0550   //!
0551   //! In desktop OpenGL, window buffer can be considered as sRGB-ready by default,
0552   //! even when application has NOT requested sRGB-ready pixel format,
0553   //! and rendering is managed via GL_FRAMEBUFFER_SRGB state.
0554   //!
0555   //! In OpenGL ES, sRGB-ready window surface should be explicitly requested on construction,
0556   //! and cannot be disabled/enabled without GL_EXT_sRGB_write_control extension afterwards
0557   //! (GL_FRAMEBUFFER_SRGB can be considered as always tuned ON).
0558   bool IsWindowSRGB() const { return myIsSRgbWindow; }
0559 
0560   //! Overrides if window/surface buffer is sRGB-ready or not (initialized with the context).
0561   void SetWindowSRGB (bool theIsSRgb) { myIsSRgbWindow = theIsSRgb; }
0562 
0563   //! Returns TRUE if window/surface buffer has deep color (10bit per component / 30bit RGB) or better precision.
0564   bool IsWindowDeepColor() const { return myIsWindowDeepColor; }
0565 
0566   //! Convert Quantity_ColorRGBA into vec4
0567   //! with conversion or no conversion into non-linear sRGB
0568   //! basing on ToRenderSRGB() flag.
0569   OpenGl_Vec4 Vec4FromQuantityColor (const OpenGl_Vec4& theColor) const
0570   {
0571     return myIsSRgbActive
0572          ? Vec4LinearFromQuantityColor(theColor)
0573          : Vec4sRGBFromQuantityColor  (theColor);
0574   }
0575 
0576   //! Convert Quantity_ColorRGBA into vec4.
0577   //! Quantity_Color is expected to be linear RGB, hence conversion is NOT required
0578   const OpenGl_Vec4& Vec4LinearFromQuantityColor (const OpenGl_Vec4& theColor) const { return theColor; }
0579 
0580   //! Convert Quantity_ColorRGBA (linear RGB) into non-linear sRGB vec4.
0581   OpenGl_Vec4 Vec4sRGBFromQuantityColor (const OpenGl_Vec4& theColor) const
0582   {
0583     return Quantity_ColorRGBA::Convert_LinearRGB_To_sRGB (theColor);
0584   }
0585 
0586   //! Returns TRUE if PBR shading model is supported.
0587   //! Basically, feature requires OpenGL 3.0+ / OpenGL ES 3.0+ hardware; more precisely:
0588   //! - Graphics hardware with moderate capabilities for compiling long enough GLSL program.
0589   //! - FBO (e.g. for baking environment).
0590   //! - Multi-texturing with >= 4 units (LUT and IBL textures).
0591   //! - GL_RG32F texture format (arbTexRG + arbTexFloat)
0592   //! - Cubemap texture lookup textureCubeLod()/textureLod() with LOD index within Fragment Shader,
0593   //!   which requires GLSL OpenGL 3.0+ / OpenGL ES 3.0+ or OpenGL 2.1 + GL_EXT_gpu_shader4 extension.
0594   Standard_Boolean HasPBR() const { return myHasPBR; }
0595 
0596   //! Returns texture unit where Environment Lookup Table is expected to be bound, or 0 if PBR is unavailable.
0597   Graphic3d_TextureUnit PBREnvLUTTexUnit() const { return myPBREnvLUTTexUnit; }
0598 
0599   //! Returns texture unit where Diffuse (irradiance) IBL map's spherical harmonics coefficients is expected to be bound, or 0 if PBR is unavailable.
0600   Graphic3d_TextureUnit PBRDiffIBLMapSHTexUnit() const { return myPBRDiffIBLMapSHTexUnit; }
0601 
0602   //! Returns texture unit where Specular IBL map is expected to be bound, or 0 if PBR is unavailable.
0603   Graphic3d_TextureUnit PBRSpecIBLMapTexUnit() const { return myPBRSpecIBLMapTexUnit; }
0604 
0605   //! Returns texture unit where shadow map is expected to be bound, or 0 if unavailable.
0606   Graphic3d_TextureUnit ShadowMapTexUnit() const { return myShadowMapTexUnit; }
0607 
0608   //! Returns texture unit for occDepthPeelingDepth within enabled Depth Peeling.
0609   Graphic3d_TextureUnit DepthPeelingDepthTexUnit() const { return myDepthPeelingDepthTexUnit; }
0610 
0611   //! Returns texture unit for occDepthPeelingFrontColor within enabled Depth Peeling.
0612   Graphic3d_TextureUnit DepthPeelingFrontColorTexUnit() const { return myDepthPeelingFrontColorTexUnit; }
0613 
0614   //! Returns true if VBO is supported and permitted.
0615   inline bool ToUseVbo() const
0616   {
0617     return core15fwd != NULL
0618        && !caps->vboDisable;
0619   }
0620 
0621   //! @return cached state of GL_NORMALIZE.
0622   Standard_Boolean IsGlNormalizeEnabled() const { return myIsGlNormalizeEnabled; }
0623 
0624   //! Sets GL_NORMALIZE enabled or disabled.
0625   //! @return old value of the flag
0626   Standard_EXPORT Standard_Boolean SetGlNormalizeEnabled (Standard_Boolean isEnabled);
0627 
0628   //! @return cached state of polygon rasterization mode (glPolygonMode()).
0629   Standard_Integer PolygonMode() const { return myPolygonMode; }
0630 
0631   //! Sets polygon rasterization mode (glPolygonMode() function).
0632   //! @return old value of the rasterization mode.
0633   Standard_EXPORT Standard_Integer SetPolygonMode (const Standard_Integer theMode);
0634 
0635   //! @return cached enabled state of polygon hatching rasterization.
0636   bool IsPolygonHatchEnabled() const { return myHatchIsEnabled; }
0637 
0638   //! Sets enabled state of polygon hatching rasterization
0639   //! without affecting currently selected hatching pattern.
0640   //! @return previous state of polygon hatching mode.
0641   Standard_EXPORT bool SetPolygonHatchEnabled (const bool theIsEnabled);
0642 
0643   //! @return cached state of polygon hatch type.
0644   Standard_Integer PolygonHatchStyle() const { return myActiveHatchType; }
0645 
0646   //! Sets polygon hatch pattern.
0647   //! Zero-index value is a default alias for solid filling.
0648   //! @param theStyle type of hatch supported by base implementation of
0649   //! OpenGl_LineAttributes (Aspect_HatchStyle) or the type supported by custom
0650   //! implementation derived from OpenGl_LineAttributes class.
0651   //! @return old type of hatch.
0652   Standard_EXPORT Standard_Integer SetPolygonHatchStyle (const Handle(Graphic3d_HatchStyle)& theStyle);
0653 
0654   //! Sets and applies current polygon offset.
0655   Standard_EXPORT void SetPolygonOffset (const Graphic3d_PolygonOffset& theOffset);
0656 
0657   //! Returns currently applied polygon offset parameters.
0658   const Graphic3d_PolygonOffset& PolygonOffset() const { return myPolygonOffset; }
0659 
0660   //! Returns camera object.
0661   const Handle(Graphic3d_Camera)& Camera() const { return myCamera; }
0662 
0663   //! Sets camera object to the context and update matrices.
0664   Standard_EXPORT void SetCamera (const Handle(Graphic3d_Camera)& theCamera);
0665 
0666   //! Applies matrix into shader manager stored in ModelWorldState to OpenGl.
0667   //! In "model -> world -> view -> projection" it performs:
0668   //!     model -> world
0669   Standard_EXPORT void ApplyModelWorldMatrix();
0670 
0671   //! Applies matrix stored in WorldViewState to OpenGl.
0672   //! In "model -> world -> view -> projection" it performs:
0673   //!     model -> world -> view,
0674   //! where model -> world is identical matrix
0675   Standard_EXPORT void ApplyWorldViewMatrix();
0676 
0677   //! Applies combination of matrices stored in ModelWorldState and WorldViewState to OpenGl.
0678   //! In "model -> world -> view -> projection" it performs:
0679   //!     model -> world -> view
0680   Standard_EXPORT void ApplyModelViewMatrix();
0681 
0682   //! Applies matrix stored in ProjectionState to OpenGl.
0683   //! In "model -> world -> view -> projection" it performs:
0684   //!                       view -> projection
0685   Standard_EXPORT void ApplyProjectionMatrix();
0686 
0687 public:
0688 
0689   //! @return messenger instance
0690   inline const Handle(Message_Messenger)& Messenger() const
0691   {
0692     return ::Message::DefaultMessenger();
0693   }
0694 
0695   //! Callback for GL_ARB_debug_output extension
0696   //! @param theSource   message source   within GL_DEBUG_SOURCE_   enumeration
0697   //! @param theType     message type     within GL_DEBUG_TYPE_     enumeration
0698   //! @param theId       message ID       within source
0699   //! @param theSeverity message severity within GL_DEBUG_SEVERITY_ enumeration
0700   //! @param theMessage  the message itself
0701   Standard_EXPORT void PushMessage (const unsigned int theSource,
0702                                     const unsigned int theType,
0703                                     const unsigned int theId,
0704                                     const unsigned int theSeverity,
0705                                     const TCollection_ExtendedString& theMessage);
0706 
0707   //! Adds a filter for messages with theId and theSource (GL_DEBUG_SOURCE_)
0708   Standard_EXPORT Standard_Boolean ExcludeMessage (const unsigned int theSource,
0709                                                    const unsigned int theId);
0710 
0711   //! Removes a filter for messages with theId and theSource (GL_DEBUG_SOURCE_)
0712   Standard_EXPORT Standard_Boolean IncludeMessage (const unsigned int theSource,
0713                                                    const unsigned int theId);
0714 
0715   //! @return true if OpenGl context supports left and right rendering buffers.
0716   Standard_Boolean HasStereoBuffers() const { return myIsStereoBuffers; }
0717 
0718 public: //! @name methods to alter or retrieve current state
0719 
0720   //! Return structure holding frame statistics.
0721   const Handle(OpenGl_FrameStats)& FrameStats() const { return myFrameStats; }
0722 
0723   //! Set structure holding frame statistics.
0724   //! This call makes sense only if application defines OpenGl_FrameStats sub-class.
0725   void SetFrameStats (const Handle(OpenGl_FrameStats)& theStats) { myFrameStats = theStats; }
0726 
0727   //! Return cached viewport definition (x, y, width, height).
0728   const Standard_Integer* Viewport() const { return myViewport; }
0729 
0730   //! Resize the viewport (alias for glViewport).
0731   //! @param theRect viewport definition (x, y, width, height)
0732   Standard_EXPORT void ResizeViewport (const Standard_Integer theRect[4]);
0733 
0734   //! Return virtual viewport definition (x, y, width, height).
0735   const Standard_Integer* VirtualViewport() const { return myViewportVirt; }
0736 
0737   //! Return active read buffer.
0738   Standard_Integer ReadBuffer() { return myReadBuffer; }
0739 
0740   //! Switch read buffer, wrapper for ::glReadBuffer().
0741   Standard_EXPORT void SetReadBuffer (const Standard_Integer theReadBuffer);
0742 
0743   //! Return active draw buffer attached to a render target referred by index (layout location).
0744   Standard_Integer DrawBuffer (Standard_Integer theIndex = 0) const
0745   {
0746     return theIndex >= myDrawBuffers.Lower()
0747         && theIndex <= myDrawBuffers.Upper()
0748          ? myDrawBuffers.Value (theIndex)
0749          : 0; // GL_NONE
0750   }
0751 
0752   //! Switch draw buffer, wrapper for ::glDrawBuffer().
0753   Standard_EXPORT void SetDrawBuffer (const Standard_Integer theDrawBuffer);
0754 
0755   //! Switch draw buffer, wrapper for ::glDrawBuffers (GLsizei, const GLenum*).
0756   Standard_EXPORT void SetDrawBuffers (const Standard_Integer theNb, const Standard_Integer* theDrawBuffers);
0757 
0758   //! Switch read/draw buffers.
0759   void SetReadDrawBuffer (const Standard_Integer theBuffer)
0760   {
0761     SetReadBuffer (theBuffer);
0762     SetDrawBuffer (theBuffer);
0763   }
0764 
0765   //! Returns cached GL_FRAMEBUFFER_SRGB state.
0766   //! If TRUE, GLSL program is expected to write linear RGB color.
0767   //! Otherwise, GLSL program might need manually converting result color into sRGB color space.
0768   bool IsFrameBufferSRGB() const { return myIsSRgbActive; }
0769 
0770   //! Enables/disables GL_FRAMEBUFFER_SRGB flag.
0771   //! This flag can be set to:
0772   //! - TRUE when writing into offscreen FBO (always expected to be in sRGB or RGBF formats).
0773   //! - TRUE when writing into sRGB-ready window buffer (might require choosing proper pixel format on window creation).
0774   //! - FALSE if sRGB rendering is not supported or sRGB-not-ready window buffer is used for drawing.
0775   //! @param[in] theIsFbo flag indicating writing into offscreen FBO (always expected sRGB-ready when sRGB FBO is supported)
0776   //!                     or into window buffer (FALSE, sRGB-readiness might vary).
0777   //! @param[in] theIsFboSRgb flag indicating off-screen FBO is sRGB-ready
0778   Standard_EXPORT void SetFrameBufferSRGB (bool theIsFbo, bool theIsFboSRgb = true);
0779 
0780   //! Return cached flag indicating writing into color buffer is enabled or disabled (glColorMask).
0781   const NCollection_Vec4<bool>& ColorMaskRGBA() const { return myColorMask; }
0782 
0783   //! Enable/disable writing into color buffer (wrapper for glColorMask).
0784   Standard_EXPORT void SetColorMaskRGBA (const NCollection_Vec4<bool>& theToWriteColor);
0785 
0786   //! Return cached flag indicating writing into color buffer is enabled or disabled (glColorMask).
0787   bool ColorMask() const { return myColorMask.r(); }
0788 
0789   //! Enable/disable writing into color buffer (wrapper for glColorMask).
0790   //! Alpha component writes will be disabled unconditionally in case of caps->buffersOpaqueAlpha.
0791   Standard_EXPORT bool SetColorMask (bool theToWriteColor);
0792 
0793   //! Return TRUE if GL_SAMPLE_ALPHA_TO_COVERAGE usage is allowed.
0794   bool AllowSampleAlphaToCoverage() const { return myAllowAlphaToCov; }
0795 
0796   //! Allow GL_SAMPLE_ALPHA_TO_COVERAGE usage.
0797   void SetAllowSampleAlphaToCoverage (bool theToEnable) { myAllowAlphaToCov = theToEnable; }
0798 
0799   //! Return GL_SAMPLE_ALPHA_TO_COVERAGE state.
0800   bool SampleAlphaToCoverage() const { return myAlphaToCoverage; }
0801 
0802   //! Enable/disable GL_SAMPLE_ALPHA_TO_COVERAGE.
0803   Standard_EXPORT bool SetSampleAlphaToCoverage (bool theToEnable);
0804 
0805   //! Return back face culling state.
0806   Graphic3d_TypeOfBackfacingModel FaceCulling() const { return myFaceCulling; }
0807 
0808   //! Enable or disable back face culling (glEnable (GL_CULL_FACE)).
0809   Standard_EXPORT void SetFaceCulling (Graphic3d_TypeOfBackfacingModel theMode);
0810 
0811   //! Return back face culling state.
0812   bool ToCullBackFaces() const { return myFaceCulling == Graphic3d_TypeOfBackfacingModel_BackCulled; }
0813 
0814   //! Enable or disable back face culling (glCullFace() + glEnable(GL_CULL_FACE)).
0815   void SetCullBackFaces (bool theToEnable)
0816   {
0817     SetFaceCulling (theToEnable ? Graphic3d_TypeOfBackfacingModel_BackCulled : Graphic3d_TypeOfBackfacingModel_DoubleSided);
0818   }
0819 
0820   //! Fetch OpenGl context state. This class tracks value of several OpenGl
0821   //! state variables. Consulting the cached values is quicker than
0822   //! doing the same via OpenGl API. Call this method if any of the controlled
0823   //! OpenGl state variables has a possibility of being out-of-date.
0824   Standard_EXPORT void FetchState();
0825 
0826   //! @return active textures
0827   const Handle(OpenGl_TextureSet)& ActiveTextures() const { return myActiveTextures; }
0828 
0829   //! Bind specified texture set to current context taking into account active GLSL program.
0830   Standard_DEPRECATED("BindTextures() with explicit GLSL program should be used instead")
0831   Handle(OpenGl_TextureSet) BindTextures (const Handle(OpenGl_TextureSet)& theTextures)
0832   {
0833     return BindTextures (theTextures, myActiveProgram);
0834   }
0835 
0836   //! Bind specified texture set to current context, or unbind previous one when NULL specified.
0837   //! @param theTextures [in] texture set to bind
0838   //! @param theProgram  [in] program attributes; when not NULL,
0839   //!                         mock textures will be bound to texture units expected by GLSL program, but undefined by texture set
0840   //! @return previous texture set
0841   Standard_EXPORT Handle(OpenGl_TextureSet) BindTextures (const Handle(OpenGl_TextureSet)& theTextures,
0842                                                           const Handle(OpenGl_ShaderProgram)& theProgram);
0843 
0844   //! @return active GLSL program
0845   const Handle(OpenGl_ShaderProgram)& ActiveProgram() const
0846   {
0847     return myActiveProgram;
0848   }
0849 
0850   //! Bind specified program to current context,
0851   //! or unbind previous one when NULL specified.
0852   //! @return true if some program is bound to context
0853   Standard_EXPORT Standard_Boolean BindProgram (const Handle(OpenGl_ShaderProgram)& theProgram);
0854 
0855   //! Setup current shading material.
0856   Standard_EXPORT void SetShadingMaterial (const OpenGl_Aspects* theAspect,
0857                                            const Handle(Graphic3d_PresentationAttributes)& theHighlight);
0858 
0859   //! Checks if transparency is required for the given aspect and highlight style.
0860   Standard_EXPORT static Standard_Boolean CheckIsTransparent (const OpenGl_Aspects* theAspect,
0861                                                               const Handle(Graphic3d_PresentationAttributes)& theHighlight,
0862                                                               Standard_ShortReal& theAlphaFront,
0863                                                               Standard_ShortReal& theAlphaBack);
0864 
0865   //! Checks if transparency is required for the given aspect and highlight style.
0866   static Standard_Boolean CheckIsTransparent (const OpenGl_Aspects* theAspect,
0867                                               const Handle(Graphic3d_PresentationAttributes)& theHighlight)
0868   {
0869     Standard_ShortReal anAlphaFront = 1.0f, anAlphaBack = 1.0f;
0870     return CheckIsTransparent (theAspect, theHighlight, anAlphaFront, anAlphaBack);
0871   }
0872 
0873   //! Setup current color.
0874   Standard_EXPORT void SetColor4fv (const OpenGl_Vec4& theColor);
0875 
0876   //! Setup type of line.
0877   Standard_EXPORT void SetTypeOfLine (const Aspect_TypeOfLine  theType,
0878                                       const Standard_ShortReal theFactor = 1.0f);
0879 
0880   //! Setup stipple line pattern with 1.0f factor; wrapper for glLineStipple().
0881   void SetLineStipple (const uint16_t thePattern) { SetLineStipple (1.0f, thePattern); }
0882 
0883   //! Setup type of line; wrapper for glLineStipple().
0884   Standard_EXPORT void SetLineStipple (const Standard_ShortReal theFactor,
0885                                        const uint16_t thePattern);
0886 
0887   //! Setup width of line.
0888   Standard_EXPORT void SetLineWidth (const Standard_ShortReal theWidth);
0889 
0890   //! Setup point size.
0891   Standard_EXPORT void SetPointSize (const Standard_ShortReal theSize);
0892 
0893   //! Setup point sprite origin using GL_POINT_SPRITE_COORD_ORIGIN state:
0894   //! - GL_UPPER_LEFT when GLSL program is active;
0895   //!   flipping should be handled in GLSL program for compatibility with OpenGL ES
0896   //! - GL_LOWER_LEFT for FFP
0897   Standard_EXPORT void SetPointSpriteOrigin();
0898 
0899   //! Setup texture matrix to active GLSL program or to FFP global state using glMatrixMode (GL_TEXTURE).
0900   //! @param theParams    [in] texture parameters
0901   //! @param theIsTopDown [in] texture top-down flag
0902   Standard_EXPORT void SetTextureMatrix (const Handle(Graphic3d_TextureParams)& theParams,
0903                                          const Standard_Boolean theIsTopDown);
0904 
0905   //! Bind default Vertex Array Object
0906   Standard_EXPORT void BindDefaultVao();
0907 
0908   //! Default Frame Buffer Object.
0909   const Handle(OpenGl_FrameBuffer)& DefaultFrameBuffer() const
0910   {
0911     return myDefaultFbo;
0912   }
0913 
0914   //! Setup new Default Frame Buffer Object and return previously set.
0915   //! This call doesn't change Active FBO!
0916   Standard_EXPORT Handle(OpenGl_FrameBuffer) SetDefaultFrameBuffer (const Handle(OpenGl_FrameBuffer)& theFbo);
0917 
0918   //! Return debug context initialization state.
0919   Standard_Boolean IsDebugContext() const
0920   {
0921     return myIsGlDebugCtx;
0922   }
0923 
0924   Standard_EXPORT void EnableFeatures() const;
0925 
0926   Standard_EXPORT void DisableFeatures() const;
0927 
0928   //! Return resolution for rendering text.
0929   unsigned int Resolution() const { return myResolution; }
0930 
0931   //! Resolution scale factor (rendered resolution to standard resolution).
0932   //! This scaling factor for parameters like text size to be properly displayed on device (screen / printer).
0933   Standard_ShortReal ResolutionRatio() const { return myResolutionRatio; }
0934 
0935   //! Rendering scale factor (rendering viewport height to real window buffer height).
0936   Standard_ShortReal RenderScale() const { return myRenderScale; }
0937 
0938   //! Return TRUE if rendering scale factor is not 1.
0939   Standard_Boolean HasRenderScale() const { return Abs (myRenderScale - 1.0f) > 0.0001f; }
0940 
0941   //! Rendering scale factor (inverted value).
0942   Standard_ShortReal RenderScaleInv() const { return myRenderScaleInv; }
0943 
0944   //! Return scale factor for line width.
0945   Standard_ShortReal LineWidthScale() const { return myLineWidthScale; }
0946 
0947   //! Set resolution ratio.
0948   //! Note that this method rounds @theRatio to nearest integer.
0949   void SetResolution (unsigned int theResolution,
0950                       Standard_ShortReal theRatio,
0951                       Standard_ShortReal theScale)
0952   {
0953     myResolution      = (unsigned int )(theScale * theResolution + 0.5f);
0954     myRenderScale     = theScale;
0955     myRenderScaleInv  = 1.0f / theScale;
0956     SetResolutionRatio (theRatio * theScale);
0957   }
0958 
0959   //! Set resolution ratio.
0960   //! Note that this method rounds @theRatio to nearest integer.
0961   void SetResolutionRatio (const Standard_ShortReal theRatio)
0962   {
0963     myResolutionRatio = theRatio;
0964     myLineWidthScale  = Max (1.0f, std::floor (theRatio + 0.5f));
0965   }
0966 
0967   //! Return line feater width in pixels.
0968   Standard_ShortReal LineFeather() const { return myLineFeather; }
0969 
0970   //! Set line feater width.
0971   void SetLineFeather(Standard_ShortReal theValue) { myLineFeather = theValue; }
0972 
0973   //! Wrapper over glGetBufferSubData(), implemented as:
0974   //! - OpenGL 1.5+ (desktop) via glGetBufferSubData();
0975   //! - OpenGL ES 3.0+ via glMapBufferRange();
0976   //! - WebGL 2.0+ via gl.getBufferSubData().
0977   //! @param[in]  theTarget target buffer to map {GLenum}
0978   //! @param[in]  theOffset offset to the beginning of sub-data {GLintptr}
0979   //! @param[in]  theSize   number of bytes to read {GLsizeiptr}
0980   //! @param[out] theData   destination pointer to fill
0981   //! @return FALSE if functionality is unavailable
0982   Standard_EXPORT bool GetBufferSubData (unsigned int theTarget, intptr_t theOffset, intptr_t theSize, void* theData);
0983 
0984   //! Return Graphics Driver's vendor.
0985   const TCollection_AsciiString& Vendor() const { return myVendor; }
0986 
0987   //! Dumps the content of me into the stream
0988   Standard_EXPORT void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const;
0989     
0990   //! Dumps the content of openGL state into the stream
0991   Standard_EXPORT void DumpJsonOpenGlState (Standard_OStream& theOStream, Standard_Integer theDepth = -1);
0992 
0993   //! Set GL_SHADE_MODEL value.
0994   Standard_EXPORT void SetShadeModel (Graphic3d_TypeOfShadingModel theModel);
0995 
0996 private:
0997 
0998   //! Wrapper to system function to retrieve GL function pointer by name.
0999   Standard_EXPORT void* findProc (const char* theFuncName);
1000 
1001   //! Print error if not all functions have been exported by context for reported version.
1002   //! Note that this will never happen when using GLX, since returned functions can not be validated.
1003   //! @param theGlVerMajor the OpenGL major version with missing functions
1004   //! @param theGlVerMinor the OpenGL minor version with missing functions
1005   //! @param theLastFailedProc function name which cannot be found
1006   Standard_EXPORT void checkWrongVersion (Standard_Integer theGlVerMajor, Standard_Integer theGlVerMinor,
1007                                           const char* theLastFailedProc);
1008 
1009   //! Private initialization function that should be called only once.
1010   Standard_EXPORT void init (const Standard_Boolean theIsCoreProfile);
1011 
1012 public: //! @name core profiles
1013 
1014   OpenGl_GlCore11*     core11ffp;  //!< OpenGL 1.1 core functionality
1015   OpenGl_GlCore11Fwd*  core11fwd;  //!< OpenGL 1.1 without deprecated entry points
1016   OpenGl_GlCore15*     core15;     //!< OpenGL 1.5 without deprecated entry points
1017   OpenGl_GlCore20*     core20;     //!< OpenGL 2.0 without deprecated entry points
1018   OpenGl_GlCore30*     core30;     //!< OpenGL 3.0 without deprecated entry points
1019   OpenGl_GlCore32*     core32;     //!< OpenGL 3.2 core profile
1020   OpenGl_GlCore33*     core33;     //!< OpenGL 3.3 core profile
1021   OpenGl_GlCore41*     core41;     //!< OpenGL 4.1 core profile
1022   OpenGl_GlCore42*     core42;     //!< OpenGL 4.2 core profile
1023   OpenGl_GlCore43*     core43;     //!< OpenGL 4.3 core profile
1024   OpenGl_GlCore44*     core44;     //!< OpenGL 4.4 core profile
1025   OpenGl_GlCore45*     core45;     //!< OpenGL 4.5 core profile
1026   OpenGl_GlCore46*     core46;     //!< OpenGL 4.6 core profile
1027 
1028   OpenGl_GlCore15*     core15fwd;  //!< obsolete entry left for code portability; core15 should be used instead
1029   OpenGl_GlCore20*     core20fwd;  //!< obsolete entry left for code portability; core20 should be used instead
1030 
1031   Handle(OpenGl_Caps) caps; //!< context options
1032 
1033 public: //! @name extensions
1034 
1035   Standard_Boolean       hasGetBufferData;   //!< flag indicating if GetBufferSubData() is supported
1036   Standard_Boolean       hasPackRowLength;   //!< supporting of GL_PACK_ROW_LENGTH   parameters (any desktop OpenGL; OpenGL ES 3.0)
1037   Standard_Boolean       hasUnpackRowLength; //!< supporting of GL_UNPACK_ROW_LENGTH parameters (any desktop OpenGL; OpenGL ES 3.0)
1038   Standard_Boolean       hasHighp;           //!< highp in GLSL ES fragment shader is supported
1039   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)
1040   Standard_Boolean       hasTexRGBA8;        //!< always available on desktop; on OpenGL ES - since 3.0 or as extension GL_OES_rgb8_rgba8
1041   Standard_Boolean       hasTexFloatLinear;  //!< texture-filterable state for 32-bit floating texture formats (always on desktop, GL_OES_texture_float_linear within OpenGL ES)
1042   Standard_Boolean       hasTexSRGB;         //!< sRGB texture    formats (desktop OpenGL 2.1, OpenGL ES 3.0 or OpenGL ES 2.0 + GL_EXT_sRGB)
1043   Standard_Boolean       hasFboSRGB;         //!< sRGB FBO render targets (desktop OpenGL 2.1, OpenGL ES 3.0)
1044   Standard_Boolean       hasSRGBControl;     //!< sRGB write control (any desktop OpenGL, OpenGL ES + GL_EXT_sRGB_write_control extension)
1045   Standard_Boolean       hasFboRenderMipmap; //!< FBO render target could be non-zero mipmap level of texture
1046   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)
1047   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
1048   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)
1049   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)
1050   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)
1051   OpenGl_FeatureFlag     hasSampleVariables; //!< Complex flag indicating support of MSAA variables in GLSL shader (desktop OpenGL 4.0, GL_ARB_sample_shading)
1052   OpenGl_FeatureFlag     hasGeometryStage;   //!< Complex flag indicating support of Geometry shader (desktop OpenGL 3.2, OpenGL ES 3.2, GL_EXT_geometry_shader)
1053   Standard_Boolean       arbDrawBuffers;     //!< GL_ARB_draw_buffers
1054   Standard_Boolean       arbNPTW;            //!< GL_ARB_texture_non_power_of_two
1055   Standard_Boolean       arbTexRG;           //!< GL_ARB_texture_rg
1056   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
1057   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)
1058   OpenGl_ArbTexBindless* arbTexBindless;     //!< GL_ARB_bindless_texture
1059   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)
1060   Standard_Boolean       arbTboRGB32;        //!< GL_ARB_texture_buffer_object_rgb32 (3-component TBO), in core since 4.0 (on OpenGL ES - since 3.2)
1061   Standard_Boolean       arbClipControl;     //!< GL_ARB_clip_control, in core since 4.5
1062   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)
1063   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)
1064   OpenGl_ArbFBO*         arbFBO;             //!< GL_ARB_framebuffer_object
1065   OpenGl_ArbFBOBlit*     arbFBOBlit;         //!< glBlitFramebuffer function, moved out from OpenGl_ArbFBO structure for compatibility with OpenGL ES 2.0
1066   Standard_Boolean       arbSampleShading;   //!< GL_ARB_sample_shading
1067   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)
1068   Standard_Boolean       extFragDepth;       //!< GL_EXT_frag_depth on OpenGL ES 2.0 (gl_FragDepthEXT built-in variable, before OpenGL ES 3.0)
1069   Standard_Boolean       extDrawBuffers;     //!< GL_EXT_draw_buffers
1070   OpenGl_ExtGS*          extGS;              //!< GL_EXT_geometry_shader4
1071   Standard_Boolean       extBgra;            //!< GL_EXT_bgra or GL_EXT_texture_format_BGRA8888 on OpenGL ES
1072   Standard_Boolean       extTexR16;          //!< GL_EXT_texture_norm16 on OpenGL ES; always available on desktop
1073   Standard_Boolean       extAnis;            //!< GL_EXT_texture_filter_anisotropic
1074   Standard_Boolean       extPDS;             //!< GL_EXT_packed_depth_stencil
1075   Standard_Boolean       atiMem;             //!< GL_ATI_meminfo
1076   Standard_Boolean       nvxMem;             //!< GL_NVX_gpu_memory_info
1077   Standard_Boolean       oesSampleVariables; //!< GL_OES_sample_variables
1078   Standard_Boolean       oesStdDerivatives;  //!< GL_OES_standard_derivatives
1079 
1080 public: //! @name public properties tracking current state
1081 
1082   OpenGl_MatrixState<Standard_ShortReal> ModelWorldState; //!< state of orientation matrix
1083   OpenGl_MatrixState<Standard_ShortReal> WorldViewState;  //!< state of orientation matrix
1084   OpenGl_MatrixState<Standard_ShortReal> ProjectionState; //!< state of projection  matrix
1085 
1086 private: // system-dependent fields
1087 
1088   Aspect_Drawable         myWindow;   //!< surface           EGLSurface | HWND  | GLXDrawable
1089   Aspect_Display          myDisplay;  //!< display           EGLDisplay | HDC   | Display*
1090   Aspect_RenderingContext myGContext; //!< rendering context EGLContext | HGLRC | GLXContext | EAGLContext* | NSOpenGLContext*
1091 
1092 private: // context info
1093 
1094   typedef NCollection_Shared< NCollection_DataMap<TCollection_AsciiString, Standard_Integer> > OpenGl_DelayReleaseMap;
1095   typedef NCollection_Shared< NCollection_List<Handle(OpenGl_Resource)> > OpenGl_ResourcesStack;
1096 
1097   Handle(OpenGl_ResourcesMap)    mySharedResources; //!< shared resources with unique identification key
1098   Handle(OpenGl_DelayReleaseMap) myDelayed;         //!< shared resources for delayed release
1099   Handle(OpenGl_ResourcesStack)  myUnusedResources; //!< stack of resources for delayed clean up
1100 
1101   OpenGl_Clipping myClippingState; //!< state of clip planes
1102 
1103   void*            myGlLibHandle;          //!< optional handle to GL library
1104   std::unique_ptr<OpenGl_GlFunctions>
1105                    myFuncs;                //!< mega structure for all GL functions
1106   Aspect_GraphicsLibrary myGapi;           //!< GAPI name
1107   Handle(Image_SupportedFormats)
1108                    mySupportedFormats;     //!< map of supported texture formats
1109   Standard_Integer myAnisoMax;             //!< maximum level of anisotropy texture filter
1110   Standard_Integer myTexClamp;             //!< either GL_CLAMP_TO_EDGE (1.2+) or GL_CLAMP (1.1)
1111   Standard_Integer myMaxTexDim;            //!< value for GL_MAX_TEXTURE_SIZE
1112   Standard_Integer myMaxTexCombined;       //!< value for GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS
1113   Standard_Integer myMaxTexUnitsFFP;       //!< value for GL_MAX_TEXTURE_UNITS (fixed-function pipeline only)
1114   Standard_Integer myMaxDumpSizeX;         //!< maximum FBO width  for image dump
1115   Standard_Integer myMaxDumpSizeY;         //!< maximum FBO height for image dump
1116   Standard_Integer myMaxClipPlanes;        //!< value for GL_MAX_CLIP_PLANES
1117   Standard_Integer myMaxMsaaSamples;       //!< value for GL_MAX_SAMPLES
1118   Standard_Integer myMaxDrawBuffers;       //!< value for GL_MAX_DRAW_BUFFERS
1119   Standard_Integer myMaxColorAttachments;  //!< value for GL_MAX_COLOR_ATTACHMENTS
1120   Standard_Integer myGlVerMajor;           //!< cached GL version major number
1121   Standard_Integer myGlVerMinor;           //!< cached GL version minor number
1122   Standard_Boolean myIsInitialized;        //!< flag indicates initialization state
1123   Standard_Boolean myIsStereoBuffers;      //!< context supports stereo buffering
1124   Standard_Boolean myHasMsaaTextures;      //!< context supports MSAA textures
1125   Standard_Boolean myIsGlNormalizeEnabled; //!< GL_NORMALIZE flag
1126                                            //!< Used to tell OpenGl that normals should be normalized
1127   Graphic3d_TextureUnit mySpriteTexUnit;   //!< sampler2D occSamplerPointSprite, texture unit for point sprite texture
1128 
1129   Standard_Boolean myHasRayTracing;                 //! indicates whether ray tracing mode is supported
1130   Standard_Boolean myHasRayTracingTextures;         //! indicates whether textures in ray tracing mode are supported
1131   Standard_Boolean myHasRayTracingAdaptiveSampling; //! indicates whether adaptive screen sampling in ray tracing mode is supported
1132   Standard_Boolean myHasRayTracingAdaptiveSamplingAtomic; //! indicates whether atomic adaptive screen sampling in ray tracing mode is supported
1133 
1134   Standard_Boolean myHasPBR;                      //!< indicates whether PBR shading model is supported
1135   Graphic3d_TextureUnit myPBREnvLUTTexUnit;       //!< sampler2D occEnvLUT, texture unit where environment lookup table is expected to be binded (0 if PBR is not supported)
1136   Graphic3d_TextureUnit myPBRDiffIBLMapSHTexUnit; //!< sampler2D occDiffIBLMapSHCoeffs, texture unit where diffuse (irradiance) IBL map's spherical harmonics coefficients is expected to  be binded
1137                                                   //!  (0 if PBR is not supported)
1138   Graphic3d_TextureUnit myPBRSpecIBLMapTexUnit;   //!< samplerCube occSpecIBLMap, texture unit where specular IBL map is expected to  be binded (0 if PBR is not supported)
1139   Graphic3d_TextureUnit myShadowMapTexUnit;       //!< sampler2D occShadowMapSampler
1140 
1141   Graphic3d_TextureUnit myDepthPeelingDepthTexUnit;      //!< sampler2D occDepthPeelingDepth, texture unit for Depth Peeling lookups
1142   Graphic3d_TextureUnit myDepthPeelingFrontColorTexUnit; //!< sampler2D occDepthPeelingFrontColor, texture unit for Depth Peeling lookups
1143 
1144   Handle(OpenGl_ShaderManager) myShaderManager; //! support object for managing shader programs
1145 
1146 private: //! @name fields tracking current state
1147 
1148   Handle(Graphic3d_Camera)      myCamera;          //!< active camera object
1149   Handle(OpenGl_FrameStats)     myFrameStats;      //!< structure accumulating frame statistics
1150   Handle(OpenGl_ShaderProgram)  myActiveProgram;   //!< currently active GLSL program
1151   Handle(OpenGl_TextureSet)     myActiveTextures;  //!< currently bound textures
1152                                                    //!< currently active sampler objects
1153   Standard_Integer              myActiveMockTextures; //!< currently active mock sampler objects
1154   Handle(OpenGl_FrameBuffer)    myDefaultFbo;      //!< default Frame Buffer Object
1155   Handle(OpenGl_LineAttributes) myHatchStyles;     //!< resource holding predefined hatch styles patterns
1156   Standard_Integer              myActiveHatchType; //!< currently activated type of polygon hatch
1157   Standard_Boolean              myHatchIsEnabled;  //!< current enabled state of polygon hatching rasterization
1158   Handle(OpenGl_Texture)        myTextureRgbaBlack;//!< mock black texture returning (0, 0, 0, 0)
1159   Handle(OpenGl_Texture)        myTextureRgbaWhite;//!< mock white texture returning (1, 1, 1, 1)
1160   Standard_Integer              myViewport[4];     //!< current viewport
1161   Standard_Integer              myViewportVirt[4]; //!< virtual viewport
1162   Standard_Integer              myPointSpriteOrig; //!< GL_POINT_SPRITE_COORD_ORIGIN state (GL_UPPER_LEFT by default)
1163   Standard_Integer              myRenderMode;      //!< value for active rendering mode
1164   Standard_Integer              myShadeModel;      //!< currently used shade model (glShadeModel)
1165   Standard_Integer              myPolygonMode;     //!< currently used polygon rasterization mode (glPolygonMode)
1166   Graphic3d_PolygonOffset       myPolygonOffset;   //!< currently applied polygon offset
1167   Graphic3d_TypeOfBackfacingModel myFaceCulling;   //!< back face culling mode enabled state (glIsEnabled (GL_CULL_FACE))
1168   Standard_Integer              myReadBuffer;      //!< current read buffer
1169   NCollection_Array1<Standard_Integer>
1170                                 myDrawBuffers;     //!< current draw buffers
1171   unsigned int                  myDefaultVao;      //!< default Vertex Array Object
1172   NCollection_Vec4<bool>        myColorMask;       //!< flag indicating writing into color buffer is enabled or disabled (glColorMask)
1173   Standard_Boolean              myAllowAlphaToCov; //!< flag allowing   GL_SAMPLE_ALPHA_TO_COVERAGE usage
1174   Standard_Boolean              myAlphaToCoverage; //!< flag indicating GL_SAMPLE_ALPHA_TO_COVERAGE state
1175   Standard_Boolean              myIsGlDebugCtx;    //!< debug context initialization state
1176   Standard_Boolean              myIsWindowDeepColor; //!< indicates that window buffer is has deep color pixel format
1177   Standard_Boolean              myIsSRgbWindow;    //!< indicates that window buffer is sRGB-ready
1178   Standard_Boolean              myIsSRgbActive;    //!< flag indicating GL_FRAMEBUFFER_SRGB state
1179   TCollection_AsciiString       myVendor;          //!< Graphics Driver's vendor
1180   TColStd_PackedMapOfInteger    myFilters[6];      //!< messages suppressing filter (for sources from GL_DEBUG_SOURCE_API_ARB to GL_DEBUG_SOURCE_OTHER_ARB)
1181   unsigned int                  myResolution;      //!< Pixels density (PPI), defines scaling factor for parameters like text size
1182   Standard_ShortReal            myResolutionRatio; //!< scaling factor for parameters like text size
1183                                                    //!  to be properly displayed on device (screen / printer)
1184   Standard_ShortReal            myLineWidthScale;  //!< scaling factor for line width
1185   Standard_ShortReal            myLineFeather;     //!< line feater width in pixels
1186   Standard_ShortReal            myRenderScale;     //!< scaling factor for rendering resolution
1187   Standard_ShortReal            myRenderScaleInv;  //!< scaling factor for rendering resolution (inverted value)
1188   OpenGl_Material               myMaterial;        //!< current front/back material state (cached to reduce GL context updates)
1189 
1190 private:
1191 
1192   //! Copying allowed only within Handles
1193   OpenGl_Context            (const OpenGl_Context& );
1194   OpenGl_Context& operator= (const OpenGl_Context& );
1195 
1196 };
1197 
1198 #endif // _OpenGl_Context_H__