Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-09-09 09:16:12

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