Debian Codegraph @

src/base_rendering/castleinternalcontextbase.pas

raw
1 {
2 Copyright 2013-2024 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Cross-platform OpenGL(ES) context types. }
17 unit CastleInternalContextBase;
18
19 {$i castleconf.inc}
20
21 interface
22
23 uses SysUtils, Classes, Generics.Collections,
24 CastleVectors, CastleRenderOptions;
25
26 type
27 EGLContextNotPossible = class(Exception);
28
29 { Required OpenGL(ES) context capabilities.
30 These context requirements are cross-platform,
31 i.e. they should make sense for all ways how one can create OpenGL context
32 (EGL, wgl, glX, etc.) }
33 TGLContextRequirements = class(TComponent)
34 strict private
35 FDoubleBuffer: Boolean;
36 FRedBits, FGreenBits, FBlueBits: Cardinal;
37 FDepthBits: Cardinal;
38 FAlphaBits: Cardinal;
39 FStencilBits: Cardinal;
40 FMultiSampling: Cardinal;
41 function GetColorBits: Cardinal;
42 procedure SetColorBits(const Value: Cardinal);
43 public
44 const
45 DefaultDepthBits = 24;
46
47 constructor Create(AOwner: TComponent); override;
48
49 { Check do given OpenGL buffers configuration satisfies the
50 requested configuration.
51
52 So it checks does
53
54 @preformatted(
55 ProvidedStencilBits >= StencilBits and
56 ProvidedDepthBits >= DepthBits ...
57 )
58
59 and so on. If not, EGLContextNotPossible is raised with detailed
60 description (which buffer constraint is not satisfied -- e.g. maybe
61 the stencil buffer is not available).
62
63 Note that ProvidedMultiSampling is not checked if MultiSampling is <= 1.
64 In other words, if multisampling was not required, ProvidedMultiSampling
65 doesn't matter --- it's Ok even ProvidedMultiSampling = 0 and
66 MultiSampling = 1, which happens commonly (since our MultiSampling = 1 means
67 "no multisampling" and is default, but most backends returns num_samples
68 (or something equivalent) as = 0 when multisampling not supported). }
69 procedure CheckRequestedBufferAttributes(const ProviderName: string;
70 ProvidedStencilBits, ProvidedDepthBits, ProvidedAlphaBits,
71 ProvidedMultiSampling: Cardinal);
72
73 { Current OpenGL buffers configuration required.
74 Stuff like DoubleBuffer, AlphaBits, DepthBits, StencilBits etc.
75 This simply returns a text description of these properties.
76
77 It does not describe the current OpenGL context parameters.
78 (It doesn't even need an OpenGL context open.)
79
80 Useful for constructing messages e.g. for EGLContextNotPossible exceptions. }
81 function RequestedBufferAttributes: String;
82 published
83 { Should we request and use the double buffer.
84 After every draw, we automatically swap buffers (if DoubleBuffer)
85 or call glFlush (if not DoubleBuffer). }
86 property DoubleBuffer: Boolean read FDoubleBuffer write FDoubleBuffer default true;
87
88 { Required red / green / blue color buffer precision for this window.
89 When 0, the default window system color precision will be used.
90
91 You can either set them by separate red / green / blue properties.
92 Or you can use ColorBits that reads / writes all three channels bits.
93 Reading ColorBits simply returns the sum of
94 @code(RedBits + GreenBits + BlueBits).
95 Writing ColorBits simply set RedBits and BlueBits to
96 @code(ColorBits div 3), and sets GreenBits to the remainder.
97 This way green channel has always the best resolution (as is usual,
98 since it's perceived most), and the sum is always as requested.
99 This way setting ColorBits to values like 16 or 24 works as expected.
100
101 @groupBegin }
102 property RedBits: Cardinal read FRedBits write FRedBits default 0;
103 property GreenBits: Cardinal read FGreenBits write FGreenBits default 0;
104 property BlueBits: Cardinal read FBlueBits write FBlueBits default 0;
105 property ColorBits: Cardinal read GetColorBits write SetColorBits stored false default 0;
106 { @groupEnd }
107
108 { Required depth buffer precision. Zero means that we don't need
109 depth buffer at all. We may get depth buffer with more precision
110 than requested (we may even get depth buffer when we set
111 DepthBits = 0), this all depends on graphic card.
112
113 Default value is @link(DefaultDepthBits),
114 which is non-zero and a reasonable default for 3D programs
115 that want to work with depth test enabled.
116
117 @italic(Design notes:) Why default value is not 0?
118
119 @orderedList(
120 @item(
121 Most programs using OpenGL use 3D and so use depth testing.
122 So many programs
123 would have to call something like @code(Window.DepthBits := DefaultDepthBits).
124 )
125
126 @item(
127 Often graphic cards / window systems / OSes give you an OpenGL
128 context with depth buffer @italic(even if you don't need depth buffer).
129 This makes it easy to forget about setting DepthBits to something
130 non-zero, because on @italic(your) system you may happen
131 to always get some depth buffer.
132 )
133 )
134
135 If you are writing a program that does not need depth buffer
136 you can set Window.DepthBits := 0, to inform OpenGL it doesn't need
137 to allocate any depth buffer.
138 }
139 property DepthBits: Cardinal read FDepthBits write FDepthBits default DefaultDepthBits;
140
141 { Required number of bits in alpha channel of color buffer.
142 Zero means that alpha channel is not needed.
143
144 Just like with other XxxBits property, we may get more
145 bits than we requested. But we will never get less --- if window system
146 will not be able to provide GL context with requested number of bits,
147 we will raise an error. }
148 property AlphaBits: Cardinal read FAlphaBits write FAlphaBits default 0;
149
150 { Required stencil buffer precision, zero means that stencil buffer is
151 not needed.
152
153 Just like with other XxxBits property, we may get more
154 bits than we requested. But we will never get less --- if window system
155 will not be able to provide GL context with requested number of bits,
156 we will raise an error.
157
158 Note that after initializing OpenGL context (when opening the window),
159 StencilBits is @italic(not) updated to the current (provided)
160 stencil buffer bit size. For example, if you requested StencilBits := 8,
161 and you got 16-bits stencil buffer: StencilBits value will still remain 8.
162 This is sensible in case you close the window, tweak some settings
163 and try to open it again. Use @code(glGetInteger(GL_STENCIL_BITS))
164 when window is open to query current (actual) buffer size. }
165 property StencilBits: Cardinal read FStencilBits write FStencilBits default DefaultStencilBits;
166
167 { How many samples are required for multi-sampling (anti-aliasing).
168
169 1 means that no multi-sampling is required.
170 Values larger than 1 mean that we require OpenGL context with
171 multi-sampling capabilities. Various GPUs may support various
172 values (it's a trade-off between quality and speed),
173 try typical values 2 or 4.
174
175 You can enable/disable anti-aliasing in your program by code like
176
177 @longCode(#
178 if GLFeatures.Multisample then glEnable(GL_MULTISAMPLE);
179 if GLFeatures.Multisample then glDisable(GL_MULTISAMPLE);
180 #)
181
182 But usually that's not needed, as it is "on" by default
183 (GL_ARB_multisample spec says so) if you requested multi-sampling context
184 (that is, if this property is > 1). See GL_ARB_multisample spec for details:
185 [http://opengl.org/registry/specs/ARB/multisample.txt].
186
187 Just like with other XxxBits property, we may get more
188 samples than we requested (e.g. if you request 3, you will most probably
189 get 4). But we will never get less --- if window system
190 will not be able to provide GL context with requested number of bits,
191 we will raise an error.
192
193 TODO: this may change to be similar to Lazarus
194 TOpenGLControl.MultiSampling, and also be more comfortable --- to retry
195 initialization with no multi-sampling. In this case this property will
196 not be changed, to be nice.
197
198 You can always read OpenGL GL_SAMPLE_BUFFERS_ARB and GL_SAMPLES_ARB
199 values after initializing OpenGL context, to know exactly
200 how many samples did you actually get, and did you get multi-sampling at all.
201 Actually, we already initialize global CastleGLUtils.GLCurrentMultiSampling
202 for you, you can use this. }
203 property MultiSampling: Cardinal read FMultiSampling write FMultiSampling default 1;
204 end;
205
206 { OpenGL(ES) context. }
207 TGLContext = class
208 private
209 type
210 TGLContextList = {$ifdef FPC}specialize{$endif} TObjectList<TGLContext>;
211 class var
212 { TGLContext instances between @link(Initialize) (without exception) and
213 @link(Finalize).
214
215 We use this to share rendering contexts,
216 as all rendering contexts in our engine must share rendering resources,
217 like OpenGL textures, shaders, VBOs.
218 This sharing makes caching easier, e.g. TCastleScene and textures cache
219 is not per-context but just one global cache.
220
221 May be @nil if empty. }
222 FInitializedContexts: TGLContextList;
223 strict private
224 FInitialized: Boolean;
225 protected
226 { Any initialized context. A new context
227 should share data with it. May be @nil if no sharing necessary
228 (which means this is 1st context). }
229 function SharedContext: TGLContext;
230
231 { Override in descendants to initialize rendering context.
232
233 No need to worry in descendants about what happens when this raises
234 an exception (non-virtual @link(Initialize) will make sure to call
235 @link(FinalizeCore) in such case).
236
237 No need to worry in descendants whether this is called on already-initialized
238 context. (non-virtual @link(Initialize) will make sure to never call
239 this when context is already initialized.) }
240 procedure InitializeCore(const Requirements: TGLContextRequirements); virtual; abstract;
241
242 { Override in descendants to finalize rendering context,
243 reverting work done by @link(InitializeCore).
244
245 Has to be implemented to tolerate without errors a partially open context,
246 because this will be called also when @link(InitializeCore)
247 raised an exception. }
248 procedure FinalizeCore; virtual; abstract;
249
250 { Override in descendants to make this rendering context current.
251
252 Implementation can assume context is initialized. }
253 procedure MakeCurrentCore; virtual; abstract;
254
255 { Override in descendants to swap buffers.
256
257 Implementation can assume context is initialized.
258
259 Implementation can assume context was created with DoubleBuffer. }
260 procedure SwapBuffersCore; virtual; abstract;
261 public
262 class function InitializedContextsCount: Cardinal;
263
264 destructor Destroy; override;
265
266 { Initialize rendering context.
267 Called after creating native window.
268 Calling this is ignored when used on already-initialized context.
269 If context cannot be initialized, this raises an exception.
270 But it leaves this class in reliable (not initialized) state. }
271 procedure Initialize(const Requirements: TGLContextRequirements);
272
273 { Finalize rendering context, reverting work done by @link(Initialize).
274 Called before destroying native window.
275 Calling this is ignored when used on non-initialized context. }
276 procedure Finalize;
277
278 { Make the GL context current.
279 Should only be called on initialized context. }
280 procedure MakeCurrent;
281
282 { Swap buffers.
283 Should only be called on initialized context.
284 Should only be called on context created with DoubleBuffer. }
285 procedure SwapBuffers;
286
287 { Is the context initialized now,
288 that is between @link(Initialize) and @link(Finalize). }
289 property Initialized: Boolean read FInitialized;
290 end;
291
292 implementation
293
294 { Note: We plan to use this approach (TGLContext class)
295 to initialize OpenGL(ES) contexts everywhere,
296 for both TCastleWindow and TCastleControl.
297
298 It is almost done at this point: we have
299 - wgl,
300 - EGL,
301 - glX descendants.
302 And they are used by TCastleWindow and Delphi + TCastleControl.
303
304 TODO: But we have some notable exceptions:
305 - TCastleWindow on Cocoa uses custom code
306 - TCastleWindow on Android and iOS use special organization (library)
307 - TCastleControl on LCL uses LCL TOpenGLControl
308
309 At some point, everything will likely be adjusted to TGLContext,
310 and we'll be able to simplify some API.
311 }
312
313 uses {$ifdef OpenGLES} CastleGLES, {$else} CastleGL, {$endif}
314 CastleUtils, CastleStringUtils, CastleGLUtils, CastleLog;
315
316 { TGLContextRequirements ----------------------------------------------------- }
317
318 constructor TGLContextRequirements.Create(AOwner: TComponent);
319 begin
320 inherited;
321 DoubleBuffer := true;
322 DepthBits := DefaultDepthBits;
323 StencilBits := DefaultStencilBits;
324 MultiSampling := 1;
325 end;
326
327 function TGLContextRequirements.GetColorBits: Cardinal;
328 begin
329 Result := RedBits + GreenBits + BlueBits;
330 end;
331
332 procedure TGLContextRequirements.SetColorBits(const Value: Cardinal);
333 begin
334 RedBits := Value div 3;
335 BlueBits := Value div 3;
336 GreenBits := Value - RedBits - BlueBits;
337 Assert(Value = ColorBits);
338 end;
339
340 function TGLContextRequirements.RequestedBufferAttributes: String;
341 begin
342 if DoubleBuffer then
343 Result := 'double buffered'
344 else
345 Result := 'single buffered';
346 if ColorBits > 0 then
347 Result := Result + Format(', with RGB colors bits (%d, %d, %d) (total %d color bits)', [RedBits, GreenBits, BlueBits, ColorBits]);
348 if DepthBits > 0 then
349 Result := Result + Format(', with %d-bits sized depth buffer', [DepthBits]);
350 if StencilBits > 0 then
351 Result := Result + Format(', with %d-bits sized stencil buffer', [StencilBits]);
352 if AlphaBits > 0 then
353 Result := Result + Format(', with %d-bits sized alpha channel', [AlphaBits]);
354 if MultiSampling > 1 then
355 Result := Result + Format(', with multisampling (%d samples)', [MultiSampling]);
356 end;
357
358 procedure TGLContextRequirements.CheckRequestedBufferAttributes(
359 const ProviderName: string; ProvidedStencilBits, ProvidedDepthBits,
360 ProvidedAlphaBits, ProvidedMultiSampling: Cardinal);
361
362 procedure CheckRequestedBits(const Name: string; RequestedBits, ProvidedBits: Cardinal);
363 begin
364 if ProvidedBits < RequestedBits then
365 raise EGLContextNotPossible.CreateFmt('%s provided OpenGL context with %s'
366 +' %d-bits sized but at least %d-bits sized is required',
367 [ ProviderName, Name, ProvidedBits, RequestedBits ]);
368 end;
369
370 begin
371 CheckRequestedBits('stencil buffer', StencilBits, ProvidedStencilBits);
372 CheckRequestedBits('depth buffer', DepthBits, ProvidedDepthBits);
373 CheckRequestedBits('alpha channel', AlphaBits, ProvidedAlphaBits);
374
375 { If MultiSampling <= 1, this means that multisampling not required,
376 so don't check it. Even if MultiSampling = 1 and ProvidedMultiSampling = 0
377 (as most backends report no multisampling as num samples = 0), it's all Ok. }
378
379 if MultiSampling > 1 then
380 begin
381 if ProvidedMultiSampling < MultiSampling then
382 raise EGLContextNotPossible.CreateFmt('%s provided OpenGL context with %d ' +
383 'samples for multisampling (<= 1 means that no multisampling was provided) ' +
384 'but at last %d samples for multisampling is required',
385 [ ProviderName, ProvidedMultiSampling, MultiSampling ]);
386 end;
387 end;
388
389 { TGLContext --------------------------------------------------------------- }
390
391 procedure TGLContext.Initialize(const Requirements: TGLContextRequirements);
392 begin
393 if FInitialized then
394 Exit;
395
396 try
397 InitializeCore(Requirements);
398 except
399 FinalizeCore;
400 raise;
401 end;
402
403 FInitialized := true;
404
405 if FInitializedContexts = nil then
406 FInitializedContexts := TGLContextList.Create(false);
407 Assert(not FInitializedContexts.Contains(Self));
408 FInitializedContexts.Add(Self);
409
410 // This should always be true, FInitialized is just more efficient than checking Contains
411 Assert(FInitialized = FInitializedContexts.Contains(Self));
412 end;
413
414 procedure TGLContext.Finalize;
415 begin
416 if not FInitialized then
417 Exit;
418
419 FinalizeCore;
420 FInitialized := false;
421 if FInitializedContexts <> nil then
422 begin
423 FInitializedContexts.Remove(Self);
424
425 // This should always be true, FInitialized is just more efficient than checking Contains
426 Assert(FInitialized = FInitializedContexts.Contains(Self));
427 end else
428 begin
429 WritelnWarning('TGLContext', 'Finalizing TGLContext instance after finalization of CastleInternalContextBase unit, we no longer track currently initialized contexts');
430 end;
431 end;
432
433 destructor TGLContext.Destroy;
434 begin
435 { We do not Finalize here automatically, since possibly native window
436 was already destroyed, and trying to do Finalize now would cause further errors.
437 So we just warn.
438 Outside code should always make sure to call Finalize before destroying.
439
440 We remove from FInitializedContexts, to prevent danling pointers on this list. }
441
442 if (FInitializedContexts <> nil) and
443 (FInitializedContexts.Contains(Self)) then
444 begin
445 WritelnWarning('TGLContext', 'Destroying TGLContext instance with initialized OpenGL context; you should call Finalize first');
446 FInitializedContexts.Remove(Self);
447 end;
448
449 inherited;
450 end;
451
452 class function TGLContext.InitializedContextsCount: Cardinal;
453 begin
454 if FInitializedContexts <> nil then
455 Result := FInitializedContexts.Count
456 else
457 Result := 0;
458 end;
459
460 function TGLContext.SharedContext: TGLContext;
461 begin
462 if InitializedContextsCount >= 1 then // also checks FInitializedContexts <> nil
463 begin
464 Result := FInitializedContexts.First;
465 Assert(Result <> Self, 'TGLContext.SharedContext should be used before adding context to FInitializedContexts, so Self should not be on the list yet');
466 end else
467 Result := nil;
468 end;
469
470 procedure TGLContext.MakeCurrent;
471 begin
472 Assert(Initialized);
473 MakeCurrentCore;
474 end;
475
476 procedure TGLContext.SwapBuffers;
477 begin
478 Assert(Initialized);
479 SwapBuffersCore;
480 end;
481
482 initialization
483 finalization
484 FreeAndNil(TGLContext.FInitializedContexts);
485 end.