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