0030640: Visualization, Graphic3d_Camera - add option creating Projection matrix...
[occt.git] / src / OpenGl / OpenGl_Context.hxx
1 // Created on: 2012-01-26
2 // Created by: Kirill GAVRILOV
3 // Copyright (c) 2012-2014 OPEN CASCADE SAS
4 //
5 // This file is part of Open CASCADE Technology software library.
6 //
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
12 //
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
15
16 #ifndef _OpenGl_Context_H__
17 #define _OpenGl_Context_H__
18
19 #include <Aspect_Handle.hxx>
20 #include <Aspect_HatchStyle.hxx>
21 #include <Aspect_Drawable.hxx>
22 #include <Aspect_Display.hxx>
23 #include <Aspect_RenderingContext.hxx>
24 #include <Aspect_TypeOfLine.hxx>
25 #include <NCollection_DataMap.hxx>
26 #include <Graphic3d_DiagnosticInfo.hxx>
27 #include <Graphic3d_TextureUnit.hxx>
28 #include <NCollection_Map.hxx>
29 #include <NCollection_Handle.hxx>
30 #include <NCollection_List.hxx>
31 #include <NCollection_SparseArray.hxx>
32 #include <Message.hxx>
33 #include <OpenGl_Caps.hxx>
34 #include <OpenGl_LineAttributes.hxx>
35 #include <OpenGl_Material.hxx>
36 #include <OpenGl_MatrixState.hxx>
37 #include <OpenGl_Vec.hxx>
38 #include <OpenGl_Resource.hxx>
39 #include <OpenGl_TextureSet.hxx>
40 #include <Standard_Transient.hxx>
41 #include <TColStd_IndexedDataMapOfStringString.hxx>
42 #include <TColStd_PackedMapOfInteger.hxx>
43 #include <OpenGl_Clipping.hxx>
44 #include <OpenGl_GlCore11.hxx>
45
46 #include <NCollection_Shared.hxx>
47
48 //! Forward declarations
49 #if defined(__APPLE__)
50   #import <TargetConditionals.h>
51   #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
52     #ifdef __OBJC__
53       @class EAGLContext;
54     #else
55       struct EAGLContext;
56     #endif
57   #else
58     #ifdef __OBJC__
59       @class NSOpenGLContext;
60     #else
61       struct NSOpenGLContext;
62     #endif
63   #endif
64 #endif
65
66 struct OpenGl_GlFunctions;
67 struct OpenGl_ArbTBO;
68 struct OpenGl_ArbIns;
69 struct OpenGl_ArbDbg;
70 struct OpenGl_ArbFBO;
71 struct OpenGl_ArbFBOBlit;
72 struct OpenGl_ArbSamplerObject;
73 struct OpenGl_ArbTexBindless;
74 struct OpenGl_ExtGS;
75
76 template<typename theBaseClass_t> struct OpenGl_TmplCore12;
77 typedef OpenGl_TmplCore12<OpenGl_GlCore11>     OpenGl_GlCore12;
78 typedef OpenGl_TmplCore12<OpenGl_GlCore11Fwd>  OpenGl_GlCore12Fwd;
79
80 struct OpenGl_GlCore13;
81 struct OpenGl_GlCore13Fwd;
82
83 template<typename theBaseClass_t> struct OpenGl_TmplCore14;
84 typedef OpenGl_TmplCore14<OpenGl_GlCore13>     OpenGl_GlCore14;
85 typedef OpenGl_TmplCore14<OpenGl_GlCore13Fwd>  OpenGl_GlCore14Fwd;
86
87 template<typename theBaseClass_t> struct OpenGl_TmplCore15;
88 typedef OpenGl_TmplCore15<OpenGl_GlCore14>     OpenGl_GlCore15;
89 typedef OpenGl_TmplCore15<OpenGl_GlCore14Fwd>  OpenGl_GlCore15Fwd;
90
91 template<typename theBaseClass_t> struct OpenGl_TmplCore20;
92 typedef OpenGl_TmplCore20<OpenGl_GlCore15>     OpenGl_GlCore20;
93 typedef OpenGl_TmplCore20<OpenGl_GlCore15Fwd>  OpenGl_GlCore20Fwd;
94
95 template<typename theBaseClass_t> struct OpenGl_TmplCore21;
96 typedef OpenGl_TmplCore21<OpenGl_GlCore20>     OpenGl_GlCore21;
97 typedef OpenGl_TmplCore21<OpenGl_GlCore20Fwd>  OpenGl_GlCore21Fwd;
98
99 template<typename theBaseClass_t> struct OpenGl_TmplCore30;
100 typedef OpenGl_TmplCore30<OpenGl_GlCore21>     OpenGl_GlCore30;
101 typedef OpenGl_TmplCore30<OpenGl_GlCore21Fwd>  OpenGl_GlCore30Fwd;
102
103 template<typename theBaseClass_t> struct OpenGl_TmplCore31;
104 typedef OpenGl_TmplCore31<OpenGl_GlCore30>     OpenGl_GlCore31Back;
105 typedef OpenGl_TmplCore31<OpenGl_GlCore30Fwd>  OpenGl_GlCore31;
106
107 template<typename theBaseClass_t> struct OpenGl_TmplCore32;
108 typedef OpenGl_TmplCore32<OpenGl_GlCore31Back> OpenGl_GlCore32Back;
109 typedef OpenGl_TmplCore32<OpenGl_GlCore31>     OpenGl_GlCore32;
110
111 template<typename theBaseClass_t> struct OpenGl_TmplCore33;
112 typedef OpenGl_TmplCore33<OpenGl_GlCore32Back> OpenGl_GlCore33Back;
113 typedef OpenGl_TmplCore33<OpenGl_GlCore32>     OpenGl_GlCore33;
114
115 template<typename theBaseClass_t> struct OpenGl_TmplCore40;
116 typedef OpenGl_TmplCore40<OpenGl_GlCore33Back> OpenGl_GlCore40Back;
117 typedef OpenGl_TmplCore40<OpenGl_GlCore33>     OpenGl_GlCore40;
118
119 template<typename theBaseClass_t> struct OpenGl_TmplCore41;
120 typedef OpenGl_TmplCore41<OpenGl_GlCore40Back> OpenGl_GlCore41Back;
121 typedef OpenGl_TmplCore41<OpenGl_GlCore40>     OpenGl_GlCore41;
122
123 template<typename theBaseClass_t> struct OpenGl_TmplCore42;
124 typedef OpenGl_TmplCore42<OpenGl_GlCore41Back> OpenGl_GlCore42Back;
125 typedef OpenGl_TmplCore42<OpenGl_GlCore41>     OpenGl_GlCore42;
126
127 template<typename theBaseClass_t> struct OpenGl_TmplCore43;
128 typedef OpenGl_TmplCore43<OpenGl_GlCore42Back> OpenGl_GlCore43Back;
129 typedef OpenGl_TmplCore43<OpenGl_GlCore42>     OpenGl_GlCore43;
130
131 template<typename theBaseClass_t> struct OpenGl_TmplCore44;
132 typedef OpenGl_TmplCore44<OpenGl_GlCore43Back> OpenGl_GlCore44Back;
133 typedef OpenGl_TmplCore44<OpenGl_GlCore43>     OpenGl_GlCore44;
134
135 template<typename theBaseClass_t> struct OpenGl_TmplCore45;
136 typedef OpenGl_TmplCore45<OpenGl_GlCore44Back> OpenGl_GlCore45Back;
137 typedef OpenGl_TmplCore45<OpenGl_GlCore44>     OpenGl_GlCore45;
138
139 template<typename theBaseClass_t> struct OpenGl_TmplCore46;
140 typedef OpenGl_TmplCore46<OpenGl_GlCore45Back> OpenGl_GlCore46Back;
141 typedef OpenGl_TmplCore46<OpenGl_GlCore45>     OpenGl_GlCore46;
142
143 class Graphic3d_Camera;
144 class Graphic3d_PresentationAttributes;
145 class OpenGl_Aspects;
146 class OpenGl_FrameBuffer;
147 class OpenGl_Sampler;
148 class OpenGl_ShaderProgram;
149 class OpenGl_ShaderManager;
150 class OpenGl_FrameStats;
151
152 enum OpenGl_FeatureFlag
153 {
154   OpenGl_FeatureNotAvailable = 0, //!< Feature is not supported by OpenGl implementation.
155   OpenGl_FeatureInExtensions = 1, //!< Feature is supported as extension.
156   OpenGl_FeatureInCore       = 2  //!< Feature is supported as part of core profile.
157 };
158
159 DEFINE_STANDARD_HANDLE(OpenGl_Context, Standard_Transient)
160
161 //! This class generalize access to the GL context and available extensions.
162 //!
163 //! Functions related to specific OpenGL version or extension are grouped into structures which can be accessed as fields of this class.
164 //! The most simple way to check that required functionality is available - is NULL check for the group:
165 //! @code
166 //!   if (myContext->core20 != NULL)
167 //!   {
168 //!     myGlProgram = myContext->core20->glCreateProgram();
169 //!     .. do more stuff ..
170 //!   }
171 //!   else
172 //!   {
173 //!     .. compatibility with outdated configurations ..
174 //!   }
175 //! @endcode
176 //!
177 //! Current implementation provide access to OpenGL core functionality up to 4.4 version (core12, core13, core14, core15, fields core20)
178 //! as well as several extensions (arbTBO, arbFBO, etc.).
179 //!
180 //! OpenGL context might be initialized in Core Profile. In this case deprecated functionality become unavailable.
181 //! To make code easily adaptable to wide range of OpenGL versions, function sets related to each version has two kinds of suffixes:
182 //!  - "back" for version 3.2+.
183 //!     Represents function set for Backward-Compatible Profile.
184 //!     Function sets without this suffix represents core profile.
185 //!  - "fwd"  for version 3.0-.
186 //!     Represents non-deprecated function set of earlier OpenGL versions, which are still available within OpenGL 3.2 Core Profile.
187 //!     Function sets without this suffix represents complete list of functions related to specific OpenGL version.
188 //!
189 //! To select which core** function set should be used in specific case:
190 //!  - Determine the minimal OpenGL version required for implemented functionality and use it to access all functions.
191 //!    For example, if algorithm requires OpenGL 2.1+, it is better to write core20fwd->glEnable() rather than core11fwd->glEnable() for uniformity.
192 //!  - If functionality will work within Core Profile, use function sets with appropriate suffix.
193 //!  - Validate minimal requirements at initialization/creation time and omit checks within code where algorithm should be already initialized.
194 //!    Properly escape code incompatible with Core Profile. The simplest way to check Core Profile is "if (core11 == NULL)".
195 //!
196 //! Simplified extensions classification:
197 //!  - prefixed with NV, AMD, ATI are vendor-specific (however may be provided by other vendors in some cases);
198 //!  - prefixed with EXT are accepted by 2+ vendors;
199 //!  - prefixed with ARB are accepted by Architecture Review Board and are candidates
200 //!    for inclusion into GL core functionality.
201 //! Some functionality can be represented in several extensions simultaneously.
202 //! In this case developer should be careful because different specification may differ
203 //! in aspects (like enumeration values and error-handling).
204 //!
205 //! Notice that some systems provide mechanisms to simultaneously incorporate with GL contexts with different capabilities.
206 //! For this reason OpenGl_Context should be initialized and used for each GL context independently.
207 //!
208 //! Matrices of OpenGl transformations:
209 //! model -> world -> view -> projection
210 //! These matrices might be changed for local transformation, transform persistent using direct access to
211 //! current matrix of ModelWorldState, WorldViewState and ProjectionState
212 //! After, these matrices should be applyed using ApplyModelWorldMatrix, ApplyWorldViewMatrix,
213 //! ApplyModelViewMatrix or ApplyProjectionMatrix.
214 class OpenGl_Context : public Standard_Transient
215 {
216   DEFINE_STANDARD_RTTIEXT(OpenGl_Context, Standard_Transient)
217   friend class OpenGl_Window;
218   friend struct OpenGl_GlFunctions;
219 public:
220
221   typedef NCollection_Shared< NCollection_DataMap<TCollection_AsciiString, Handle(OpenGl_Resource)> > OpenGl_ResourcesMap;
222
223   //! Function for getting power of to number larger or equal to input number.
224   //! @param theNumber    number to 'power of two'
225   //! @param theThreshold upper threshold
226   //! @return power of two number
227   inline static Standard_Integer GetPowerOfTwo (const Standard_Integer theNumber,
228                                                 const Standard_Integer theThreshold)
229   {
230     for (Standard_Integer p2 = 2; p2 <= theThreshold; p2 <<= 1)
231     {
232       if (theNumber <= p2)
233       {
234         return p2;
235       }
236     }
237     return theThreshold;
238   }
239
240   //! Format GL constant as hex value 0xABCD.
241   Standard_EXPORT static TCollection_AsciiString FormatGlEnumHex (int theGlEnum);
242
243   //! Format pointer as hex value 0xABCD.
244   Standard_EXPORT static TCollection_AsciiString FormatPointer (const void* thePtr);
245
246   //! Format size value.
247   Standard_EXPORT static TCollection_AsciiString FormatSize (Standard_Size theSize);
248
249   //! Return text description of GL error.
250   Standard_EXPORT static TCollection_AsciiString FormatGlError (int theGlError);
251
252 public:
253
254   //! Empty constructor. You should call Init() to perform initialization with bound GL context.
255   Standard_EXPORT OpenGl_Context (const Handle(OpenGl_Caps)& theCaps = NULL);
256
257   //! Destructor.
258   Standard_EXPORT virtual ~OpenGl_Context();
259
260   //! Release all resources, including shared ones
261   Standard_EXPORT void forcedRelease();
262
263   //! Share GL context resources.
264   //! theShareCtx - handle to context to retrieve handles to shared resources.
265   Standard_EXPORT void Share (const Handle(OpenGl_Context)& theShareCtx);
266
267   //! Initialize class from currently bound OpenGL context. Method should be called only once.
268   //! @return false if no GL context is bound to the current thread
269   Standard_EXPORT Standard_Boolean Init (const Standard_Boolean theIsCoreProfile = Standard_False);
270
271   //! @return true if this context is valid (has been initialized)
272   inline Standard_Boolean IsValid() const
273   {
274     return myIsInitialized;
275   }
276
277 #if defined(HAVE_EGL)
278   //! Initialize class from specified surface and rendering context. Method should be called only once.
279   //! @return false if OpenGL context can not be bound to specified surface
280   Standard_EXPORT Standard_Boolean Init (const Aspect_Drawable         theEglSurface,
281                                          const Aspect_Display          theEglDisplay,
282                                          const Aspect_RenderingContext theEglContext,
283                                          const Standard_Boolean        theIsCoreProfile = Standard_False);
284 #elif defined(_WIN32)
285   //! Initialize class from specified window and rendering context. Method should be called only once.
286   //! @return false if OpenGL context can not be bound to specified window
287   Standard_EXPORT Standard_Boolean Init (const Aspect_Handle           theWindow,
288                                          const Aspect_Handle           theWindowDC,
289                                          const Aspect_RenderingContext theGContext,
290                                          const Standard_Boolean        theIsCoreProfile = Standard_False);
291
292   //! @return the window handle (HWND) currently bound to this OpenGL context
293   inline Aspect_Handle Window() const
294   {
295     return myWindow;
296   }
297
298 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
299   #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
300
301   //! Initialize class from specified OpenGL ES context (EAGLContext). Method should be called only once.
302   Standard_EXPORT Standard_Boolean Init (EAGLContext*                  theGContext,
303                                          const Standard_Boolean        theIsCoreProfile = Standard_False);
304   #else
305
306   //! Initialize class from specified OpenGL context (NSOpenGLContext). Method should be called only once.
307   Standard_EXPORT Standard_Boolean Init (NSOpenGLContext*              theGContext,
308                                          const Standard_Boolean        theIsCoreProfile = Standard_False);
309   #endif
310 #else
311
312   //! Initialize class from specified window and rendering context. Method should be called only once.
313   //! @return false if OpenGL context can not be bound to specified window
314   Standard_EXPORT Standard_Boolean Init (const Aspect_Drawable         theWindow,
315                                          const Aspect_Display          theDisplay,
316                                          const Aspect_RenderingContext theGContext,
317                                          const Standard_Boolean        theIsCoreProfile = Standard_False);
318
319   //! @return the window handle (GLXDrawable) currently bound to this OpenGL context
320   inline Aspect_Drawable Window() const
321   {
322     return myWindow;
323   }
324 #endif
325
326   //! Read OpenGL version information from active context.
327   Standard_EXPORT static void ReadGlVersion (Standard_Integer& theGlVerMajor,
328                                              Standard_Integer& theGlVerMinor);
329
330   //! Check if theExtName extension is supported by active GL context.
331   Standard_EXPORT Standard_Boolean CheckExtension (const char* theExtName) const;
332
333   //! Check if theExtName extension is in extensions string.
334   Standard_EXPORT static Standard_Boolean CheckExtension (const char* theExtString,
335                                                           const char* theExtName);
336
337   //! Auxiliary template to retrieve GL function pointer.
338   //! Pointer to function retrieved from library is statically casted
339   //! to requested type - there no way to check real signature of exported function.
340   //! The context should be bound before call.
341   //! @param theLastFailFuncName [out] set to theFuncName in case of failure, unmodified on success
342   //! @param theFuncName [in] function name to find
343   //! @param theFuncPtr [out] retrieved function pointer
344   //! @return TRUE on success
345   template <typename FuncType_t>
346   Standard_Boolean FindProcVerbose (const char*& theLastFailFuncName,
347                                     const char* theFuncName,
348                                     FuncType_t& theFuncPtr)
349   {
350     theFuncPtr = (FuncType_t )findProc (theFuncName);
351     if (theFuncPtr == NULL)
352     {
353       theLastFailFuncName = theFuncName;
354       return Standard_False;
355     }
356     return Standard_True;
357   }
358
359   //! Auxiliary template to retrieve GL function pointer.
360   //! Same as FindProcVerbose() but without auxiliary last function name argument.
361   template <typename FuncType_t>
362   Standard_Boolean FindProc (const char* theFuncName,
363                              FuncType_t& theFuncPtr)
364   {
365     theFuncPtr = (FuncType_t )findProc (theFuncName);
366     return (theFuncPtr != NULL);
367   }
368
369   //! @return true if detected GL version is greater or equal to requested one.
370   inline Standard_Boolean IsGlGreaterEqual (const Standard_Integer theVerMajor,
371                                             const Standard_Integer theVerMinor) const
372   {
373     return (myGlVerMajor >  theVerMajor)
374         || (myGlVerMajor == theVerMajor && myGlVerMinor >= theVerMinor);
375   }
376
377   //! Return cached GL version major number.
378   Standard_Integer VersionMajor() const { return myGlVerMajor; }
379
380   //! Return cached GL version minor number.
381   Standard_Integer VersionMinor() const { return myGlVerMinor; }
382
383   //! Access entire map of loaded OpenGL functions.
384   const OpenGl_GlFunctions* Functions() const { return myFuncs.operator->(); }
385
386   //! Clean up errors stack for this GL context (glGetError() in loop).
387   //! @return true if some error has been cleared
388   Standard_EXPORT bool ResetErrors (const bool theToPrintErrors = false);
389
390   //! This method uses system-dependent API to retrieve information
391   //! about GL context bound to the current thread.
392   //! @return true if current thread is bound to this GL context
393   Standard_EXPORT Standard_Boolean IsCurrent() const;
394
395   //! Activates current context.
396   //! Class should be initialized with appropriate info.
397   Standard_EXPORT Standard_Boolean MakeCurrent();
398
399   //! Swap front/back buffers for this GL context (should be activated before!).
400   Standard_EXPORT void SwapBuffers();
401
402   //! Setup swap interval (VSync).
403   Standard_EXPORT Standard_Boolean SetSwapInterval (const Standard_Integer theInterval);
404
405   //! Return true if active mode is GL_RENDER (cached state)
406   Standard_Boolean IsRender() const
407   {
408   #if !defined(GL_ES_VERSION_2_0)
409     return myRenderMode == GL_RENDER;
410   #else
411     return Standard_True;
412   #endif
413   }
414
415   //! Return true if active mode is GL_FEEDBACK (cached state)
416   Standard_Boolean IsFeedback() const
417   {
418   #if !defined(GL_ES_VERSION_2_0)
419     return myRenderMode == GL_FEEDBACK;
420   #else
421     return Standard_False;
422   #endif
423   }
424
425   //! This function retrieves information from GL about free GPU memory that is:
426   //!  - OS-dependent. On some OS it is per-process and on others - for entire system.
427   //!  - Vendor-dependent. Currently available only on NVIDIA and AMD/ATi drivers only.
428   //!  - Numbers meaning may vary.
429   //! You should use this info only for diagnostics purposes.
430   //! @return free GPU dedicated memory in bytes.
431   Standard_EXPORT Standard_Size AvailableMemory() const;
432
433   //! This function retrieves information from GL about GPU memory
434   //! and contains more vendor-specific values than AvailableMemory().
435   Standard_EXPORT TCollection_AsciiString MemoryInfo() const;
436
437   //! This function retrieves information from GL about GPU memory.
438   Standard_EXPORT void MemoryInfo (TColStd_IndexedDataMapOfStringString& theDict) const;
439
440   //! Fill in the dictionary with OpenGL info.
441   //! Should be called with bound context.
442   Standard_EXPORT void DiagnosticInformation (TColStd_IndexedDataMapOfStringString& theDict,
443                                               Graphic3d_DiagnosticInfo theFlags) const;
444
445   //! Access shared resource by its name.
446   //! @param  theKey - unique identifier;
447   //! @return handle to shared resource or NULL.
448   Standard_EXPORT const Handle(OpenGl_Resource)& GetResource (const TCollection_AsciiString& theKey) const;
449
450   //! Access shared resource by its name.
451   //! @param  theKey   - unique identifier;
452   //! @param  theValue - handle to fill;
453   //! @return true if resource was shared.
454   template<typename TheHandleType>
455   Standard_Boolean GetResource (const TCollection_AsciiString& theKey,
456                                 TheHandleType&                 theValue) const
457   {
458     const Handle(OpenGl_Resource)& aResource = GetResource (theKey);
459     if (aResource.IsNull())
460     {
461       return Standard_False;
462     }
463
464     theValue = TheHandleType::DownCast (aResource);
465     return !theValue.IsNull();
466   }
467
468   //! Register shared resource.
469   //! Notice that after registration caller shouldn't release it by himself -
470   //! it will be automatically released on context destruction.
471   //! @param theKey      - unique identifier, shouldn't be empty;
472   //! @param theResource - new resource to register, shouldn't be NULL.
473   Standard_EXPORT Standard_Boolean ShareResource (const TCollection_AsciiString& theKey,
474                                                   const Handle(OpenGl_Resource)& theResource);
475
476   //! Release shared resource.
477   //! If there are more than one reference to this resource
478   //! (also used by some other existing object) then call will be ignored.
479   //! This means that current object itself should nullify handle before this call.
480   //! Notice that this is unrecommended operation at all and should be used
481   //! only in case of fat resources to release memory for other needs.
482   //! @param theKey     unique identifier
483   //! @param theToDelay postpone release until next redraw call
484   Standard_EXPORT void ReleaseResource (const TCollection_AsciiString& theKey,
485                                         const Standard_Boolean         theToDelay = Standard_False);
486
487   //! Append resource to queue for delayed clean up.
488   //! Resources in this queue will be released at next redraw call.
489   template <class T>
490   void DelayedRelease (Handle(T)& theResource)
491   {
492     myUnusedResources->Prepend (theResource);
493     theResource.Nullify();
494   }
495
496   //! Clean up the delayed release queue.
497   Standard_EXPORT void ReleaseDelayed();
498
499   //! Return map of shared resources.
500   const OpenGl_ResourcesMap& SharedResources() const { return *mySharedResources; }
501
502   //! @return tool for management of clippings within this context.
503   inline OpenGl_Clipping& ChangeClipping() { return myClippingState; }
504
505   //! @return tool for management of clippings within this context.
506   inline const OpenGl_Clipping& Clipping() const { return myClippingState; }
507
508   //! @return tool for management of shader programs within this context.
509   inline const Handle(OpenGl_ShaderManager)& ShaderManager() const { return myShaderManager; }
510
511 public:
512
513   //! Either GL_CLAMP_TO_EDGE (1.2+) or GL_CLAMP (1.1).
514   Standard_Integer TextureWrapClamp() const { return myTexClamp; }
515
516   //! @return true if texture parameters GL_TEXTURE_BASE_LEVEL/GL_TEXTURE_MAX_LEVEL are supported.
517   Standard_Boolean HasTextureBaseLevel() const
518   {
519   #if !defined(GL_ES_VERSION_2_0)
520     return IsGlGreaterEqual (1, 2);
521   #else
522     return IsGlGreaterEqual (3, 0);
523   #endif
524   }
525
526   //! Return map of supported texture formats.
527   const Handle(Image_SupportedFormats)& SupportedTextureFormats() const { return mySupportedFormats; }
528
529   //! @return maximum degree of anisotropy texture filter
530   Standard_Integer MaxDegreeOfAnisotropy() const { return myAnisoMax; }
531
532   //! @return value for GL_MAX_TEXTURE_SIZE
533   Standard_Integer MaxTextureSize() const { return myMaxTexDim; }
534
535   //! @return value for GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS
536   Standard_Integer MaxCombinedTextureUnits() const { return myMaxTexCombined; }
537
538   //! This method returns the multi-texture limit for obsolete fixed-function pipeline.
539   //! Use MaxCombinedTextureUnits() instead for limits for using programmable pipeline.
540   //! @return value for GL_MAX_TEXTURE_UNITS
541   Standard_Integer MaxTextureUnitsFFP() const { return myMaxTexUnitsFFP; }
542
543   //! Return texture unit to be used for sprites (Graphic3d_TextureUnit_PointSprite by default).
544   Graphic3d_TextureUnit SpriteTextureUnit() const { return mySpriteTexUnit; }
545
546   //! @return value for GL_MAX_SAMPLES
547   Standard_Integer MaxMsaaSamples() const { return myMaxMsaaSamples; }
548
549   //! @return maximum FBO width for image dump
550   Standard_Integer MaxDumpSizeX() const { return myMaxDumpSizeX; }
551
552   //! @return maximum FBO height for image dump
553   Standard_Integer MaxDumpSizeY() const { return myMaxDumpSizeY; }
554
555   //! @return value for GL_MAX_DRAW_BUFFERS
556   Standard_Integer MaxDrawBuffers() const { return myMaxDrawBuffers; }
557
558   //! @return value for GL_MAX_COLOR_ATTACHMENTS
559   Standard_Integer MaxColorAttachments() const { return myMaxColorAttachments; }
560
561   //! Get maximum number of clip planes supported by OpenGl.
562   //! This value is implementation dependent. At least 6
563   //! planes should be supported by OpenGl (see specs).
564   //! @return value for GL_MAX_CLIP_PLANES
565   Standard_Integer MaxClipPlanes() const { return myMaxClipPlanes; }
566
567   //! @return TRUE if ray tracing mode is supported
568   Standard_Boolean HasRayTracing() const { return myHasRayTracing; }
569
570   //! @return TRUE if textures in ray tracing mode are supported
571   Standard_Boolean HasRayTracingTextures() const { return myHasRayTracingTextures; }
572
573   //! @return TRUE if adaptive screen sampling in ray tracing mode is supported
574   Standard_Boolean HasRayTracingAdaptiveSampling() const { return myHasRayTracingAdaptiveSampling; }
575
576   //! @return TRUE if atomic adaptive screen sampling in ray tracing mode is supported
577   Standard_Boolean HasRayTracingAdaptiveSamplingAtomic() const { return myHasRayTracingAdaptiveSamplingAtomic; }
578
579   //! Returns TRUE if sRGB rendering is supported.
580   bool HasSRGB() const
581   {
582     return hasTexSRGB
583        &&  hasFboSRGB;
584   }
585
586   //! Returns TRUE if sRGB rendering is supported and permitted.
587   bool ToRenderSRGB() const
588   {
589     return HasSRGB()
590        && !caps->sRGBDisable
591        && !caps->ffpEnable;
592   }
593
594   //! Returns TRUE if window/surface buffer is sRGB-ready.
595   //!
596   //! When offscreen FBOs are created in sRGB, but window is not sRGB-ready,
597   //! blitting into window should be done with manual gamma correction.
598   //!
599   //! In desktop OpenGL, window buffer can be considered as sRGB-ready by default,
600   //! even when application has NOT requested sRGB-ready pixel format,
601   //! and rendering is managed via GL_FRAMEBUFFER_SRGB state.
602   //!
603   //! In OpenGL ES, sRGB-ready window surface should be explicitly requested on construction,
604   //! and cannot be disabled/enabled without GL_EXT_sRGB_write_control extension afterwards
605   //! (GL_FRAMEBUFFER_SRGB can be considered as always tuned ON).
606   bool IsWindowSRGB() const { return myIsSRgbWindow; }
607
608   //! Overrides if window/surface buffer is sRGB-ready or not (initialized with the context).
609   void SetWindowSRGB (bool theIsSRgb) { myIsSRgbWindow = theIsSRgb; }
610
611   //! Convert Quantity_ColorRGBA into vec4
612   //! with conversion or no conversion into non-linear sRGB
613   //! basing on ToRenderSRGB() flag.
614   OpenGl_Vec4 Vec4FromQuantityColor (const OpenGl_Vec4& theColor) const
615   {
616     return myIsSRgbActive
617          ? Vec4LinearFromQuantityColor(theColor)
618          : Vec4sRGBFromQuantityColor  (theColor);
619   }
620
621   //! Convert Quantity_ColorRGBA into vec4.
622   //! Quantity_Color is expected to be linear RGB, hence conversion is NOT required
623   const OpenGl_Vec4& Vec4LinearFromQuantityColor (const OpenGl_Vec4& theColor) const { return theColor; }
624
625   //! Convert Quantity_ColorRGBA (linear RGB) into non-linear sRGB vec4.
626   OpenGl_Vec4 Vec4sRGBFromQuantityColor (const OpenGl_Vec4& theColor) const
627   {
628     return Quantity_ColorRGBA::Convert_LinearRGB_To_sRGB (theColor);
629   }
630
631   //! Returns TRUE if PBR shading model is supported.
632   //! Basically, feature requires OpenGL 3.0+ / OpenGL ES 3.0+ hardware; more precisely:
633   //! - Graphics hardware with moderate capabilities for compiling long enough GLSL program.
634   //! - FBO (e.g. for baking environment).
635   //! - Multi-texturing with >= 4 units (LUT and IBL textures).
636   //! - GL_RG32F texture format (arbTexRG + arbTexFloat)
637   //! - Cubemap texture lookup textureCubeLod()/textureLod() with LOD index within Fragment Shader,
638   //!   which requires GLSL OpenGL 3.0+ / OpenGL ES 3.0+ or OpenGL 2.1 + GL_EXT_gpu_shader4 extension.
639   Standard_Boolean HasPBR() const { return myHasPBR; }
640
641   //! Returns texture unit where Environment Lookup Table is expected to be bound, or 0 if PBR is unavailable.
642   Graphic3d_TextureUnit PBREnvLUTTexUnit() const { return myPBREnvLUTTexUnit; }
643
644   //! Returns texture unit where Diffuse (irradiance) IBL map's spherical harmonics coefficients is expected to be bound, or 0 if PBR is unavailable.
645   Graphic3d_TextureUnit PBRDiffIBLMapSHTexUnit() const { return myPBRDiffIBLMapSHTexUnit; }
646
647   //! Returns texture unit where Specular IBL map is expected to be bound, or 0 if PBR is unavailable.
648   Graphic3d_TextureUnit PBRSpecIBLMapTexUnit() const { return myPBRSpecIBLMapTexUnit; }
649
650   //! Returns texture unit where shadow map is expected to be bound, or 0 if unavailable.
651   Graphic3d_TextureUnit ShadowMapTexUnit() const { return myShadowMapTexUnit; }
652
653   //! Returns texture unit for occDepthPeelingDepth within enabled Depth Peeling.
654   Graphic3d_TextureUnit DepthPeelingDepthTexUnit() const { return myDepthPeelingDepthTexUnit; }
655
656   //! Returns texture unit for occDepthPeelingFrontColor within enabled Depth Peeling.
657   Graphic3d_TextureUnit DepthPeelingFrontColorTexUnit() const { return myDepthPeelingFrontColorTexUnit; }
658
659   //! Returns true if VBO is supported and permitted.
660   inline bool ToUseVbo() const
661   {
662     return core15fwd != NULL
663        && !caps->vboDisable;
664   }
665
666   //! @return cached state of GL_NORMALIZE.
667   Standard_Boolean IsGlNormalizeEnabled() const { return myIsGlNormalizeEnabled; }
668
669   //! Sets GL_NORMALIZE enabled or disabled.
670   //! @return old value of the flag
671   Standard_EXPORT Standard_Boolean SetGlNormalizeEnabled (Standard_Boolean isEnabled);
672
673   //! @return cached state of polygon rasterization mode (glPolygonMode()).
674   Standard_Integer PolygonMode() const { return myPolygonMode; }
675
676   //! Sets polygon rasterization mode (glPolygonMode() function).
677   //! @return old value of the rasterization mode.
678   Standard_EXPORT Standard_Integer SetPolygonMode (const Standard_Integer theMode);
679
680   //! @return cached enabled state of polygon hatching rasterization.
681   bool IsPolygonHatchEnabled() const { return myHatchIsEnabled; }
682
683   //! Sets enabled state of polygon hatching rasterization
684   //! without affecting currently selected hatching pattern.
685   //! @return previous state of polygon hatching mode.
686   Standard_EXPORT bool SetPolygonHatchEnabled (const bool theIsEnabled);
687
688   //! @return cached state of polygon hatch type.
689   Standard_Integer PolygonHatchStyle() const { return myActiveHatchType; }
690
691   //! Sets polygon hatch pattern.
692   //! Zero-index value is a default alias for solid filling.
693   //! @param the type of hatch supported by base implementation of
694   //! OpenGl_LineAttributes (Aspect_HatchStyle) or the type supported by custom
695   //! implementation derived from OpenGl_LineAttributes class.
696   //! @return old type of hatch.
697   Standard_EXPORT Standard_Integer SetPolygonHatchStyle (const Handle(Graphic3d_HatchStyle)& theStyle);
698
699   //! Sets and applies current polygon offset.
700   Standard_EXPORT void SetPolygonOffset (const Graphic3d_PolygonOffset& theOffset);
701
702   //! Returns currently applied polygon offset parameters.
703   const Graphic3d_PolygonOffset& PolygonOffset() const { return myPolygonOffset; }
704
705   //! Returns camera object.
706   const Handle(Graphic3d_Camera)& Camera() const { return myCamera; }
707
708   //! Sets camera object to the context and update matrices.
709   Standard_EXPORT void SetCamera (const Handle(Graphic3d_Camera)& theCamera);
710
711   //! Applies matrix into shader manager stored in ModelWorldState to OpenGl.
712   //! In "model -> world -> view -> projection" it performs:
713   //!     model -> world
714   Standard_EXPORT void ApplyModelWorldMatrix();
715
716   //! Applies matrix stored in WorldViewState to OpenGl.
717   //! In "model -> world -> view -> projection" it performs:
718   //!     model -> world -> view,
719   //! where model -> world is identical matrix
720   Standard_EXPORT void ApplyWorldViewMatrix();
721
722   //! Applies combination of matrices stored in ModelWorldState and WorldViewState to OpenGl.
723   //! In "model -> world -> view -> projection" it performs:
724   //!     model -> world -> view
725   Standard_EXPORT void ApplyModelViewMatrix();
726
727   //! Applies matrix stored in ProjectionState to OpenGl.
728   //! In "model -> world -> view -> projection" it performs:
729   //!                       view -> projection
730   Standard_EXPORT void ApplyProjectionMatrix();
731
732 public:
733
734   //! @return messenger instance
735   inline const Handle(Message_Messenger)& Messenger() const
736   {
737     return ::Message::DefaultMessenger();
738   }
739
740   //! Callback for GL_ARB_debug_output extension
741   //! @param theSource   message source   within GL_DEBUG_SOURCE_   enumeration
742   //! @param theType     message type     within GL_DEBUG_TYPE_     enumeration
743   //! @param theId       message ID       within source
744   //! @param theSeverity message severity within GL_DEBUG_SEVERITY_ enumeration
745   //! @param theMessage  the message itself
746   Standard_EXPORT void PushMessage (const unsigned int theSource,
747                                     const unsigned int theType,
748                                     const unsigned int theId,
749                                     const unsigned int theSeverity,
750                                     const TCollection_ExtendedString& theMessage);
751
752   //! Adds a filter for messages with theId and theSource (GL_DEBUG_SOURCE_)
753   Standard_EXPORT Standard_Boolean ExcludeMessage (const unsigned int theSource,
754                                                    const unsigned int theId);
755
756   //! Removes a filter for messages with theId and theSource (GL_DEBUG_SOURCE_)
757   Standard_EXPORT Standard_Boolean IncludeMessage (const unsigned int theSource,
758                                                    const unsigned int theId);
759
760   //! @return true if OpenGl context supports left and
761   //! right rendering buffers.
762   Standard_Boolean HasStereoBuffers() const
763   {
764   #if !defined(GL_ES_VERSION_2_0)
765     return myIsStereoBuffers;
766   #else
767     return Standard_False;
768   #endif
769   }
770
771 public: //! @name methods to alter or retrieve current state
772
773   //! Return structure holding frame statistics.
774   const Handle(OpenGl_FrameStats)& FrameStats() const { return myFrameStats; }
775
776   //! Set structure holding frame statistics.
777   //! This call makes sense only if application defines OpenGl_FrameStats sub-class.
778   void SetFrameStats (const Handle(OpenGl_FrameStats)& theStats) { myFrameStats = theStats; }
779
780   //! Return cached viewport definition (x, y, width, height).
781   const Standard_Integer* Viewport() const { return myViewport; }
782
783   //! Resize the viewport (alias for glViewport).
784   //! @param theRect viewport definition (x, y, width, height)
785   Standard_EXPORT void ResizeViewport (const Standard_Integer theRect[4]);
786
787   //! Return virtual viewport definition (x, y, width, height).
788   const Standard_Integer* VirtualViewport() const { return myViewportVirt; }
789
790   //! Return active read buffer.
791   Standard_Integer ReadBuffer() { return myReadBuffer; }
792
793   //! Switch read buffer, wrapper for ::glReadBuffer().
794   Standard_EXPORT void SetReadBuffer (const Standard_Integer theReadBuffer);
795
796   //! Return active draw buffer attached to a render target referred by index (layout location).
797   Standard_Integer DrawBuffer (Standard_Integer theIndex = 0) const
798   {
799     return theIndex >= myDrawBuffers.Lower()
800         && theIndex <= myDrawBuffers.Upper()
801          ? myDrawBuffers.Value (theIndex)
802          : GL_NONE;
803   }
804
805   //! Switch draw buffer, wrapper for ::glDrawBuffer().
806   Standard_EXPORT void SetDrawBuffer (const Standard_Integer theDrawBuffer);
807
808   //! Switch draw buffer, wrapper for ::glDrawBuffers (GLsizei, const GLenum*).
809   Standard_EXPORT void SetDrawBuffers (const Standard_Integer theNb, const Standard_Integer* theDrawBuffers);
810
811   //! Switch read/draw buffers.
812   void SetReadDrawBuffer (const Standard_Integer theBuffer)
813   {
814     SetReadBuffer (theBuffer);
815     SetDrawBuffer (theBuffer);
816   }
817
818   //! Returns cached GL_FRAMEBUFFER_SRGB state.
819   //! If TRUE, GLSL program is expected to write linear RGB color.
820   //! Otherwise, GLSL program might need manually converting result color into sRGB color space.
821   bool IsFrameBufferSRGB() const { return myIsSRgbActive; }
822
823   //! Enables/disables GL_FRAMEBUFFER_SRGB flag.
824   //! This flag can be set to:
825   //! - TRUE when writing into offscreen FBO (always expected to be in sRGB or RGBF formats).
826   //! - TRUE when writing into sRGB-ready window buffer (might require choosing proper pixel format on window creation).
827   //! - FALSE if sRGB rendering is not supported or sRGB-not-ready window buffer is used for drawing.
828   //! @param theIsFbo [in] flag indicating writing into offscreen FBO (always expected sRGB-ready when sRGB FBO is supported)
829   //!                      or into window buffer (FALSE, sRGB-readiness might vary).
830   //! @param theIsSRgb [in] flag indicating off-screen FBO is sRGB-ready
831   Standard_EXPORT void SetFrameBufferSRGB (bool theIsFbo, bool theIsFboSRgb = true);
832
833   //! Return cached flag indicating writing into color buffer is enabled or disabled (glColorMask).
834   const NCollection_Vec4<bool>& ColorMaskRGBA() const { return myColorMask; }
835
836   //! Enable/disable writing into color buffer (wrapper for glColorMask).
837   Standard_EXPORT void SetColorMaskRGBA (const NCollection_Vec4<bool>& theToWriteColor);
838
839   //! Return cached flag indicating writing into color buffer is enabled or disabled (glColorMask).
840   bool ColorMask() const { return myColorMask.r(); }
841
842   //! Enable/disable writing into color buffer (wrapper for glColorMask).
843   //! Alpha component writes will be disabled unconditionally in case of caps->buffersOpaqueAlpha.
844   Standard_EXPORT bool SetColorMask (bool theToWriteColor);
845
846   //! Return TRUE if GL_SAMPLE_ALPHA_TO_COVERAGE usage is allowed.
847   bool AllowSampleAlphaToCoverage() const { return myAllowAlphaToCov; }
848
849   //! Allow GL_SAMPLE_ALPHA_TO_COVERAGE usage.
850   void SetAllowSampleAlphaToCoverage (bool theToEnable) { myAllowAlphaToCov = theToEnable; }
851
852   //! Return GL_SAMPLE_ALPHA_TO_COVERAGE state.
853   bool SampleAlphaToCoverage() const { return myAlphaToCoverage; }
854
855   //! Enable/disable GL_SAMPLE_ALPHA_TO_COVERAGE.
856   Standard_EXPORT bool SetSampleAlphaToCoverage (bool theToEnable);
857
858   //! Return back face culling state.
859   bool ToCullBackFaces() const { return myToCullBackFaces; }
860
861   //! Enable or disable back face culling (glEnable (GL_CULL_FACE)).
862   Standard_EXPORT void SetCullBackFaces (bool theToEnable);
863
864   //! Fetch OpenGl context state. This class tracks value of several OpenGl
865   //! state variables. Consulting the cached values is quicker than
866   //! doing the same via OpenGl API. Call this method if any of the controlled
867   //! OpenGl state variables has a possibility of being out-of-date.
868   Standard_EXPORT void FetchState();
869
870   //! @return active textures
871   const Handle(OpenGl_TextureSet)& ActiveTextures() const { return myActiveTextures; }
872
873   //! Bind specified texture set to current context taking into account active GLSL program.
874   Standard_DEPRECATED("BindTextures() with explicit GLSL program should be used instead")
875   Handle(OpenGl_TextureSet) BindTextures (const Handle(OpenGl_TextureSet)& theTextures)
876   {
877     return BindTextures (theTextures, myActiveProgram);
878   }
879
880   //! Bind specified texture set to current context, or unbind previous one when NULL specified.
881   //! @param theTextures [in] texture set to bind
882   //! @param theProgram  [in] program attributes; when not NULL,
883   //!                         mock textures will be bound to texture units expected by GLSL program, but undefined by texture set
884   //! @return previous texture set
885   Standard_EXPORT Handle(OpenGl_TextureSet) BindTextures (const Handle(OpenGl_TextureSet)& theTextures,
886                                                           const Handle(OpenGl_ShaderProgram)& theProgram);
887
888   //! @return active GLSL program
889   const Handle(OpenGl_ShaderProgram)& ActiveProgram() const
890   {
891     return myActiveProgram;
892   }
893
894   //! Bind specified program to current context,
895   //! or unbind previous one when NULL specified.
896   //! @return true if some program is bound to context
897   Standard_EXPORT Standard_Boolean BindProgram (const Handle(OpenGl_ShaderProgram)& theProgram);
898
899   //! Setup current shading material.
900   Standard_EXPORT void SetShadingMaterial (const OpenGl_Aspects* theAspect,
901                                            const Handle(Graphic3d_PresentationAttributes)& theHighlight);
902
903   //! Checks if transparency is required for the given aspect and highlight style.
904   Standard_EXPORT static Standard_Boolean CheckIsTransparent (const OpenGl_Aspects* theAspect,
905                                                               const Handle(Graphic3d_PresentationAttributes)& theHighlight,
906                                                               Standard_ShortReal& theAlphaFront,
907                                                               Standard_ShortReal& theAlphaBack);
908
909   //! Checks if transparency is required for the given aspect and highlight style.
910   static Standard_Boolean CheckIsTransparent (const OpenGl_Aspects* theAspect,
911                                               const Handle(Graphic3d_PresentationAttributes)& theHighlight)
912   {
913     Standard_ShortReal anAlphaFront = 1.0f, anAlphaBack = 1.0f;
914     return CheckIsTransparent (theAspect, theHighlight, anAlphaFront, anAlphaBack);
915   }
916
917   //! Setup current color.
918   Standard_EXPORT void SetColor4fv (const OpenGl_Vec4& theColor);
919
920   //! Setup type of line.
921   Standard_EXPORT void SetTypeOfLine (const Aspect_TypeOfLine  theType,
922                                       const Standard_ShortReal theFactor = 1.0f);
923
924   //! Setup stipple line pattern with 1.0f factor; wrapper for glLineStipple().
925   void SetLineStipple (const uint16_t thePattern) { SetLineStipple (1.0f, thePattern); }
926
927   //! Setup type of line; wrapper for glLineStipple().
928   Standard_EXPORT void SetLineStipple (const Standard_ShortReal theFactor,
929                                        const uint16_t thePattern);
930
931   //! Setup width of line.
932   Standard_EXPORT void SetLineWidth (const Standard_ShortReal theWidth);
933
934   //! Setup point size.
935   Standard_EXPORT void SetPointSize (const Standard_ShortReal theSize);
936
937   //! Setup point sprite origin using GL_POINT_SPRITE_COORD_ORIGIN state:
938   //! - GL_UPPER_LEFT when GLSL program is active;
939   //!   flipping should be handled in GLSL program for compatibility with OpenGL ES
940   //! - GL_LOWER_LEFT for FFP
941   Standard_EXPORT void SetPointSpriteOrigin();
942
943   //! Setup texture matrix to active GLSL program or to FFP global state using glMatrixMode (GL_TEXTURE).
944   //! @param theParams    [in] texture parameters
945   //! @param theIsTopDown [in] texture top-down flag
946   Standard_EXPORT void SetTextureMatrix (const Handle(Graphic3d_TextureParams)& theParams,
947                                          const Standard_Boolean theIsTopDown);
948
949   //! Bind default Vertex Array Object
950   Standard_EXPORT void BindDefaultVao();
951
952   //! Default Frame Buffer Object.
953   const Handle(OpenGl_FrameBuffer)& DefaultFrameBuffer() const
954   {
955     return myDefaultFbo;
956   }
957
958   //! Setup new Default Frame Buffer Object and return previously set.
959   //! This call doesn't change Active FBO!
960   Standard_EXPORT Handle(OpenGl_FrameBuffer) SetDefaultFrameBuffer (const Handle(OpenGl_FrameBuffer)& theFbo);
961
962   //! Return debug context initialization state.
963   Standard_Boolean IsDebugContext() const
964   {
965     return myIsGlDebugCtx;
966   }
967
968   Standard_EXPORT void EnableFeatures() const;
969
970   Standard_EXPORT void DisableFeatures() const;
971
972   //! Return resolution for rendering text.
973   unsigned int Resolution() const { return myResolution; }
974
975   //! Resolution scale factor (rendered resolution to standard resolution).
976   //! This scaling factor for parameters like text size to be properly displayed on device (screen / printer).
977   Standard_ShortReal ResolutionRatio() const { return myResolutionRatio; }
978
979   //! Rendering scale factor (rendering viewport height to real window buffer height).
980   Standard_ShortReal RenderScale() const { return myRenderScale; }
981
982   //! Return TRUE if rendering scale factor is not 1.
983   Standard_Boolean HasRenderScale() const { return Abs (myRenderScale - 1.0f) > 0.0001f; }
984
985   //! Rendering scale factor (inverted value).
986   Standard_ShortReal RenderScaleInv() const { return myRenderScaleInv; }
987
988   //! Return scale factor for line width.
989   Standard_ShortReal LineWidthScale() const { return myLineWidthScale; }
990
991   //! Set resolution ratio.
992   //! Note that this method rounds @theRatio to nearest integer.
993   void SetResolution (unsigned int theResolution,
994                       Standard_ShortReal theRatio,
995                       Standard_ShortReal theScale)
996   {
997     myResolution      = (unsigned int )(theScale * theResolution + 0.5f);
998     myRenderScale     = theScale;
999     myRenderScaleInv  = 1.0f / theScale;
1000     SetResolutionRatio (theRatio * theScale);
1001   }
1002
1003   //! Set resolution ratio.
1004   //! Note that this method rounds @theRatio to nearest integer.
1005   void SetResolutionRatio (const Standard_ShortReal theRatio)
1006   {
1007     myResolutionRatio = theRatio;
1008     myLineWidthScale  = Max (1.0f, std::floor (theRatio + 0.5f));
1009   }
1010
1011   //! Return line feater width in pixels.
1012   Standard_ShortReal LineFeather() const { return myLineFeather; }
1013
1014   //! Set line feater width.
1015   void SetLineFeather(Standard_ShortReal theValue) { myLineFeather = theValue; }
1016
1017   //! Wrapper over glGetBufferSubData(), implemented as:
1018   //! - OpenGL 1.5+ (desktop) via glGetBufferSubData();
1019   //! - OpenGL ES 3.0+ via glMapBufferRange();
1020   //! - WebGL 2.0+ via gl.getBufferSubData().
1021   //! @param theTarget [in] target buffer to map
1022   //! @param theOffset [in] offset to the beginning of sub-data
1023   //! @param theSize   [in] number of bytes to read
1024   //! @param theData  [out] destination pointer to fill
1025   //! @return FALSE if functionality is unavailable
1026   Standard_EXPORT bool GetBufferSubData (GLenum theTarget, GLintptr theOffset, GLsizeiptr theSize, void* theData);
1027
1028   //! Return Graphics Driver's vendor.
1029   const TCollection_AsciiString& Vendor() const { return myVendor; }
1030
1031   //! Dumps the content of me into the stream
1032   Standard_EXPORT void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const;
1033     
1034   //! Dumps the content of openGL state into the stream
1035   Standard_EXPORT static void DumpJsonOpenGlState (Standard_OStream& theOStream, Standard_Integer theDepth = -1);
1036
1037   //! Set GL_SHADE_MODEL value.
1038   Standard_EXPORT void SetShadeModel (Graphic3d_TypeOfShadingModel theModel);
1039
1040 private:
1041
1042   //! Wrapper to system function to retrieve GL function pointer by name.
1043   Standard_EXPORT void* findProc (const char* theFuncName);
1044
1045   //! Print error if not all functions have been exported by context for reported version.
1046   //! Note that this will never happen when using GLX, since returned functions can not be validated.
1047   //! @param theGlVerMajor the OpenGL major version with missing functions
1048   //! @param theGlVerMinor the OpenGL minor version with missing functions
1049   //! @param theLastFailedProc function name which cannot be found
1050   Standard_EXPORT void checkWrongVersion (Standard_Integer theGlVerMajor, Standard_Integer theGlVerMinor,
1051                                           const char* theLastFailedProc);
1052
1053   //! Private initialization function that should be called only once.
1054   Standard_EXPORT void init (const Standard_Boolean theIsCoreProfile);
1055
1056 public: //! @name core profiles
1057
1058   OpenGl_GlCore11*     core11;     //!< OpenGL 1.1 core functionality
1059   OpenGl_GlCore11Fwd*  core11fwd;  //!< OpenGL 1.1 without deprecated entry points
1060   OpenGl_GlCore15*     core15;     //!< OpenGL 1.5 core functionality
1061   OpenGl_GlCore15Fwd*  core15fwd;  //!< OpenGL 1.5 without deprecated entry points
1062   OpenGl_GlCore20*     core20;     //!< OpenGL 2.0 core functionality (includes 1.5)
1063   OpenGl_GlCore20Fwd*  core20fwd;  //!< OpenGL 2.0 without deprecated entry points
1064   OpenGl_GlCore30*     core30;     //!< OpenGL 3.0 core functionality
1065   OpenGl_GlCore30Fwd*  core30fwd;  //!< OpenGL 3.0 without deprecated entry points
1066   OpenGl_GlCore32*     core32;     //!< OpenGL 3.2 core profile
1067   OpenGl_GlCore32Back* core32back; //!< OpenGL 3.2 backward compatibility profile
1068   OpenGl_GlCore33*     core33;     //!< OpenGL 3.3 core profile
1069   OpenGl_GlCore33Back* core33back; //!< OpenGL 3.3 backward compatibility profile
1070   OpenGl_GlCore41*     core41;     //!< OpenGL 4.1 core profile
1071   OpenGl_GlCore41Back* core41back; //!< OpenGL 4.1 backward compatibility profile
1072   OpenGl_GlCore42*     core42;     //!< OpenGL 4.2 core profile
1073   OpenGl_GlCore42Back* core42back; //!< OpenGL 4.2 backward compatibility profile
1074   OpenGl_GlCore43*     core43;     //!< OpenGL 4.3 core profile
1075   OpenGl_GlCore43Back* core43back; //!< OpenGL 4.3 backward compatibility profile
1076   OpenGl_GlCore44*     core44;     //!< OpenGL 4.4 core profile
1077   OpenGl_GlCore44Back* core44back; //!< OpenGL 4.4 backward compatibility profile
1078   OpenGl_GlCore45*     core45;     //!< OpenGL 4.5 core profile
1079   OpenGl_GlCore45Back* core45back; //!< OpenGL 4.5 backward compatibility profile
1080   OpenGl_GlCore46*     core46;     //!< OpenGL 4.6 core profile
1081   OpenGl_GlCore46Back* core46back; //!< OpenGL 4.6 backward compatibility profile
1082
1083   Handle(OpenGl_Caps) caps; //!< context options
1084
1085 public: //! @name extensions
1086
1087   Standard_Boolean       hasGetBufferData;   //!< flag indicating if GetBufferSubData() is supported
1088   Standard_Boolean       hasPackRowLength;   //!< supporting of GL_PACK_ROW_LENGTH   parameters (any desktop OpenGL; OpenGL ES 3.0)
1089   Standard_Boolean       hasUnpackRowLength; //!< supporting of GL_UNPACK_ROW_LENGTH parameters (any desktop OpenGL; OpenGL ES 3.0)
1090   Standard_Boolean       hasHighp;           //!< highp in GLSL ES fragment shader is supported
1091   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)
1092   Standard_Boolean       hasTexRGBA8;        //!< always available on desktop; on OpenGL ES - since 3.0 or as extension GL_OES_rgb8_rgba8
1093   Standard_Boolean       hasTexFloatLinear;  //!< texture-filterable state for 32-bit floating texture formats (always on desktop, GL_OES_texture_float_linear within OpenGL ES)
1094   Standard_Boolean       hasTexSRGB;         //!< sRGB texture    formats (desktop OpenGL 2.1, OpenGL ES 3.0 or GL_EXT_texture_sRGB)
1095   Standard_Boolean       hasFboSRGB;         //!< sRGB FBO render targets (desktop OpenGL 2.1, OpenGL ES 3.0)
1096   Standard_Boolean       hasSRGBControl;     //!< sRGB write control (any desktop OpenGL, OpenGL ES + GL_EXT_sRGB_write_control extension)
1097   Standard_Boolean       hasFboRenderMipmap; //!< FBO render target could be non-zero mipmap level of texture
1098   OpenGl_FeatureFlag     hasFlatShading;     //!< Complex flag indicating support of Flat shading (Graphic3d_TOSM_FACET) (always available on desktop; on OpenGL ES - since 3.0 or as extension GL_OES_standard_derivatives)
1099   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
1100   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)
1101   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)
1102   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)
1103   OpenGl_FeatureFlag     hasSampleVariables; //!< Complex flag indicating support of MSAA variables in GLSL shader (desktop OpenGL 4.0, GL_ARB_sample_shading)
1104   OpenGl_FeatureFlag     hasGeometryStage;   //!< Complex flag indicating support of Geometry shader (desktop OpenGL 3.2, OpenGL ES 3.2, GL_EXT_geometry_shader)
1105   Standard_Boolean       arbDrawBuffers;     //!< GL_ARB_draw_buffers
1106   Standard_Boolean       arbNPTW;            //!< GL_ARB_texture_non_power_of_two
1107   Standard_Boolean       arbTexRG;           //!< GL_ARB_texture_rg
1108   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
1109   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)
1110   OpenGl_ArbTexBindless* arbTexBindless;     //!< GL_ARB_bindless_texture
1111   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)
1112   Standard_Boolean       arbTboRGB32;        //!< GL_ARB_texture_buffer_object_rgb32 (3-component TBO), in core since 4.0 (on OpenGL ES - since 3.2)
1113   Standard_Boolean       arbClipControl;     //!< GL_ARB_clip_control, in core since 4.5
1114   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)
1115   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)
1116   OpenGl_ArbFBO*         arbFBO;             //!< GL_ARB_framebuffer_object
1117   OpenGl_ArbFBOBlit*     arbFBOBlit;         //!< glBlitFramebuffer function, moved out from OpenGl_ArbFBO structure for compatibility with OpenGL ES 2.0
1118   Standard_Boolean       arbSampleShading;   //!< GL_ARB_sample_shading
1119   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)
1120   Standard_Boolean       extFragDepth;       //!< GL_EXT_frag_depth on OpenGL ES 2.0 (gl_FragDepthEXT built-in variable, before OpenGL ES 3.0)
1121   Standard_Boolean       extDrawBuffers;     //!< GL_EXT_draw_buffers
1122   OpenGl_ExtGS*          extGS;              //!< GL_EXT_geometry_shader4
1123   Standard_Boolean       extBgra;            //!< GL_EXT_bgra or GL_EXT_texture_format_BGRA8888 on OpenGL ES
1124   Standard_Boolean       extAnis;            //!< GL_EXT_texture_filter_anisotropic
1125   Standard_Boolean       extPDS;             //!< GL_EXT_packed_depth_stencil
1126   Standard_Boolean       atiMem;             //!< GL_ATI_meminfo
1127   Standard_Boolean       nvxMem;             //!< GL_NVX_gpu_memory_info
1128   Standard_Boolean       oesSampleVariables; //!< GL_OES_sample_variables
1129   Standard_Boolean       oesStdDerivatives;  //!< GL_OES_standard_derivatives
1130
1131 public: //! @name public properties tracking current state
1132
1133   OpenGl_MatrixState<Standard_ShortReal> ModelWorldState; //!< state of orientation matrix
1134   OpenGl_MatrixState<Standard_ShortReal> WorldViewState;  //!< state of orientation matrix
1135   OpenGl_MatrixState<Standard_ShortReal> ProjectionState; //!< state of projection  matrix
1136
1137 private: // system-dependent fields
1138
1139 #if defined(HAVE_EGL)
1140   Aspect_Drawable         myWindow;   //!< EGL surface                   : EGLSurface
1141   Aspect_Display          myDisplay;  //!< EGL connection to the Display : EGLDisplay
1142   Aspect_RenderingContext myGContext; //!< EGL rendering context         : EGLContext
1143 #elif defined(_WIN32)
1144   Aspect_Handle           myWindow;   //!< window handle (owner of GL context) : HWND
1145   Aspect_Handle           myWindowDC; //!< Device Descriptor handle : HDC
1146   Aspect_RenderingContext myGContext; //!< Rendering Context handle : HGLRC
1147 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
1148   #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
1149   EAGLContext*            myGContext;    //!< Rendering Context handle
1150   #else
1151   NSOpenGLContext*        myGContext; //!< Rendering Context handle
1152   #endif
1153 #else
1154   Aspect_Drawable         myWindow;   //!< window handle (owner of GL context) : GLXDrawable
1155   Aspect_Display          myDisplay;  //!< connection to the X-server : Display*
1156   Aspect_RenderingContext myGContext; //!< X-GLX rendering context : GLXContext
1157 #endif
1158
1159 private: // context info
1160
1161   typedef NCollection_Shared< NCollection_DataMap<TCollection_AsciiString, Standard_Integer> > OpenGl_DelayReleaseMap;
1162   typedef NCollection_Shared< NCollection_List<Handle(OpenGl_Resource)> > OpenGl_ResourcesStack;
1163
1164   Handle(OpenGl_ResourcesMap)    mySharedResources; //!< shared resources with unique identification key
1165   Handle(OpenGl_DelayReleaseMap) myDelayed;         //!< shared resources for delayed release
1166   Handle(OpenGl_ResourcesStack)  myUnusedResources; //!< stack of resources for delayed clean up
1167
1168   OpenGl_Clipping myClippingState; //!< state of clip planes
1169
1170   void*            myGlLibHandle;          //!< optional handle to GL library
1171   NCollection_Handle<OpenGl_GlFunctions>
1172                    myFuncs;                //!< mega structure for all GL functions
1173   Handle(Image_SupportedFormats)
1174                    mySupportedFormats;     //!< map of supported texture formats
1175   Standard_Integer myAnisoMax;             //!< maximum level of anisotropy texture filter
1176   Standard_Integer myTexClamp;             //!< either GL_CLAMP_TO_EDGE (1.2+) or GL_CLAMP (1.1)
1177   Standard_Integer myMaxTexDim;            //!< value for GL_MAX_TEXTURE_SIZE
1178   Standard_Integer myMaxTexCombined;       //!< value for GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS
1179   Standard_Integer myMaxTexUnitsFFP;       //!< value for GL_MAX_TEXTURE_UNITS (fixed-function pipeline only)
1180   Standard_Integer myMaxDumpSizeX;         //!< maximum FBO width  for image dump
1181   Standard_Integer myMaxDumpSizeY;         //!< maximum FBO height for image dump
1182   Standard_Integer myMaxClipPlanes;        //!< value for GL_MAX_CLIP_PLANES
1183   Standard_Integer myMaxMsaaSamples;       //!< value for GL_MAX_SAMPLES
1184   Standard_Integer myMaxDrawBuffers;       //!< value for GL_MAX_DRAW_BUFFERS
1185   Standard_Integer myMaxColorAttachments;  //!< value for GL_MAX_COLOR_ATTACHMENTS
1186   Standard_Integer myGlVerMajor;           //!< cached GL version major number
1187   Standard_Integer myGlVerMinor;           //!< cached GL version minor number
1188   Standard_Boolean myIsInitialized;        //!< flag indicates initialization state
1189   Standard_Boolean myIsStereoBuffers;      //!< context supports stereo buffering
1190   Standard_Boolean myIsGlNormalizeEnabled; //!< GL_NORMALIZE flag
1191                                            //!< Used to tell OpenGl that normals should be normalized
1192   Graphic3d_TextureUnit mySpriteTexUnit;   //!< sampler2D occSamplerPointSprite, texture unit for point sprite texture
1193
1194   Standard_Boolean myHasRayTracing;                 //! indicates whether ray tracing mode is supported
1195   Standard_Boolean myHasRayTracingTextures;         //! indicates whether textures in ray tracing mode are supported
1196   Standard_Boolean myHasRayTracingAdaptiveSampling; //! indicates whether adaptive screen sampling in ray tracing mode is supported
1197   Standard_Boolean myHasRayTracingAdaptiveSamplingAtomic; //! indicates whether atomic adaptive screen sampling in ray tracing mode is supported
1198
1199   Standard_Boolean myHasPBR;                      //!< indicates whether PBR shading model is supported
1200   Graphic3d_TextureUnit myPBREnvLUTTexUnit;       //!< sampler2D occEnvLUT, texture unit where environment lookup table is expected to be binded (0 if PBR is not supported)
1201   Graphic3d_TextureUnit myPBRDiffIBLMapSHTexUnit; //!< sampler2D occDiffIBLMapSHCoeffs, texture unit where diffuse (irradiance) IBL map's spherical harmonics coefficients is expected to  be binded
1202                                                   //!  (0 if PBR is not supported)
1203   Graphic3d_TextureUnit myPBRSpecIBLMapTexUnit;   //!< samplerCube occSpecIBLMap, texture unit where specular IBL map is expected to  be binded (0 if PBR is not supported)
1204   Graphic3d_TextureUnit myShadowMapTexUnit;       //!< sampler2D occShadowMapSampler
1205
1206   Graphic3d_TextureUnit myDepthPeelingDepthTexUnit;      //!< sampler2D occDepthPeelingDepth, texture unit for Depth Peeling lookups
1207   Graphic3d_TextureUnit myDepthPeelingFrontColorTexUnit; //!< sampler2D occDepthPeelingFrontColor, texture unit for Depth Peeling lookups
1208
1209   Handle(OpenGl_ShaderManager) myShaderManager; //! support object for managing shader programs
1210
1211 private: //! @name fields tracking current state
1212
1213   Handle(Graphic3d_Camera)      myCamera;          //!< active camera object
1214   Handle(OpenGl_FrameStats)     myFrameStats;      //!< structure accumulating frame statistics
1215   Handle(OpenGl_ShaderProgram)  myActiveProgram;   //!< currently active GLSL program
1216   Handle(OpenGl_TextureSet)     myActiveTextures;  //!< currently bound textures
1217                                                    //!< currently active sampler objects
1218   Standard_Integer              myActiveMockTextures; //!< currently active mock sampler objects
1219   Handle(OpenGl_FrameBuffer)    myDefaultFbo;      //!< default Frame Buffer Object
1220   Handle(OpenGl_LineAttributes) myHatchStyles;     //!< resource holding predefined hatch styles patterns
1221   Standard_Integer              myActiveHatchType; //!< currently activated type of polygon hatch
1222   Standard_Boolean              myHatchIsEnabled;  //!< current enabled state of polygon hatching rasterization
1223   Handle(OpenGl_Texture)        myTextureRgbaBlack;//!< mock black texture returning (0, 0, 0, 0)
1224   Handle(OpenGl_Texture)        myTextureRgbaWhite;//!< mock white texture returning (1, 1, 1, 1)
1225   Standard_Integer              myViewport[4];     //!< current viewport
1226   Standard_Integer              myViewportVirt[4]; //!< virtual viewport
1227   Standard_Integer              myPointSpriteOrig; //!< GL_POINT_SPRITE_COORD_ORIGIN state (GL_UPPER_LEFT by default)
1228   Standard_Integer              myRenderMode;      //!< value for active rendering mode
1229   Standard_Integer              myShadeModel;      //!< currently used shade model (glShadeModel)
1230   Standard_Integer              myPolygonMode;     //!< currently used polygon rasterization mode (glPolygonMode)
1231   Graphic3d_PolygonOffset       myPolygonOffset;   //!< currently applied polygon offset
1232   bool                          myToCullBackFaces; //!< back face culling mode enabled state (glIsEnabled (GL_CULL_FACE))
1233   Standard_Integer              myReadBuffer;      //!< current read buffer
1234   NCollection_Array1<Standard_Integer>
1235                                 myDrawBuffers;     //!< current draw buffers
1236   unsigned int                  myDefaultVao;      //!< default Vertex Array Object
1237   NCollection_Vec4<bool>        myColorMask;       //!< flag indicating writing into color buffer is enabled or disabled (glColorMask)
1238   Standard_Boolean              myAllowAlphaToCov; //!< flag allowing   GL_SAMPLE_ALPHA_TO_COVERAGE usage
1239   Standard_Boolean              myAlphaToCoverage; //!< flag indicating GL_SAMPLE_ALPHA_TO_COVERAGE state
1240   Standard_Boolean              myIsGlDebugCtx;    //!< debug context initialization state
1241   Standard_Boolean              myIsSRgbWindow;    //!< indicates that window buffer is sRGB-ready
1242   Standard_Boolean              myIsSRgbActive;    //!< flag indicating GL_FRAMEBUFFER_SRGB state
1243   TCollection_AsciiString       myVendor;          //!< Graphics Driver's vendor
1244   TColStd_PackedMapOfInteger    myFilters[6];      //!< messages suppressing filter (for sources from GL_DEBUG_SOURCE_API_ARB to GL_DEBUG_SOURCE_OTHER_ARB)
1245   unsigned int                  myResolution;      //!< Pixels density (PPI), defines scaling factor for parameters like text size
1246   Standard_ShortReal            myResolutionRatio; //!< scaling factor for parameters like text size
1247                                                    //!  to be properly displayed on device (screen / printer)
1248   Standard_ShortReal            myLineWidthScale;  //!< scaling factor for line width
1249   Standard_ShortReal            myLineFeather;     //!< line feater width in pixels
1250   Standard_ShortReal            myRenderScale;     //!< scaling factor for rendering resolution
1251   Standard_ShortReal            myRenderScaleInv;  //!< scaling factor for rendering resolution (inverted value)
1252   OpenGl_Material               myMatFront;        //!< current front material state (cached to reduce GL context updates)
1253   OpenGl_Material               myMatBack;         //!< current back  material state
1254
1255 private:
1256
1257   //! Copying allowed only within Handles
1258   OpenGl_Context            (const OpenGl_Context& );
1259   OpenGl_Context& operator= (const OpenGl_Context& );
1260
1261 };
1262
1263 #endif // _OpenGl_Context_H__