Debian Codegraph @

src/base_rendering/castleinternalcontextegl.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 { Initializes OpenGL or OpenGLES context using cross-platform EGL. }
17 unit CastleInternalContextEgl;
18
19 {$i castleconf.inc}
20
21 interface
22
23 uses SysUtils, Classes,
24 CastleInternalContextBase, CastleInternalEgl;
25
26 type
27 { Initializes OpenGL or OpenGLES context using cross-platform EGL. }
28 TGLContextEgl = class(TGLContext)
29 private
30 class var
31 Display: EGLDisplay;
32 EGLMajor, EGLMinor: EGLint;
33 var
34 Context: EGLContext;
35 Surface: EGLSurface;
36 { Call eglCreateContext, hiding some differences between
37 OpenGLES and OpenGL needs. }
38 function CallEglCreateContext(Config: EGLConfig;
39 ShareContextEgl: EGLContext): EGLContext;
40 { Check is EGL version at least as specified. }
41 function VersionAtLeast(const Major, Minor: EGLint): Boolean;
42
43 { Initialize EGL library, Display, and version (EGLMajor, EGLMinor).
44 Does nothing if already initialized.
45
46 The Display is a class variable, so it's shared between all contexts.
47 This is important, as we cannot terminate eglTerminate(Display)
48 just in any FinalizeCore.
49 eglTerminate(Display) it would release Display of all contexts.
50 We need to call eglTerminate(Display) only when finalizing the last context. }
51 procedure ClassInitialize;
52
53 { Finalize Display.
54 Does nothing if already finalized. }
55 procedure ClassFinalize;
56 protected
57 procedure InitializeCore(const Requirements: TGLContextRequirements); override;
58 procedure FinalizeCore; override;
59 procedure MakeCurrentCore; override;
60 procedure SwapBuffersCore; override;
61 public
62 // Set this before using Initialize and other methods
63 WndPtr: EGLNativeWindowType;
64
65 { Query context size, returns 0 0 if cannot query for some reason. }
66 procedure QuerySize(out AWidth, AHeight: EGLint);
67 end;
68
69 implementation
70
71 uses Math,
72 CastleLog, CastleUtils, CastleGLUtils;
73
74 { EGL references:
75 - http://www.khronos.org/registry/egl/sdk/docs/man/xhtml/eglIntro.html .
76 - See http://www.khronos.org/registry/egl/sdk/docs/man/xhtml/
77 for an up-to-date reference of EGL.
78 - FPC example in packages/opengles/examples/es2example1.pas was also useful.
79 }
80
81 { EGL error codes and descriptions from
82 http://www.khronos.org/registry/egl/sdk/docs/man/xhtml/eglGetError.html }
83 function EGLError: string;
84 var
85 ErrorCode: EGLint;
86 begin
87 ErrorCode := eglGetError();
88 case ErrorCode of
89 EGL_SUCCESS: Result := 'The last function succeeded without error.';
90 EGL_NOT_INITIALIZED: Result := 'EGL is not initialized, or could not be initialized, for the specified EGL display connection.';
91 EGL_BAD_ACCESS: Result := 'EGL cannot access a requested resource (for example a context is bound in another thread).';
92 EGL_BAD_ALLOC: Result := 'EGL failed to allocate resources for the requested operation.';
93 EGL_BAD_ATTRIBUTE: Result := 'An unrecognized attribute or attribute value was passed in the attribute list.';
94 EGL_BAD_CONTEXT: Result := 'An EGLContext argument does not name a valid EGL rendering context.';
95 EGL_BAD_CONFIG: Result := 'An EGLConfig argument does not name a valid EGL frame buffer configuration.';
96 EGL_BAD_CURRENT_SURFACE: Result := 'The current surface of the calling thread is a window, pixel buffer or pixmap that is no longer valid.';
97 EGL_BAD_DISPLAY: Result := 'An EGLDisplay argument does not name a valid EGL display connection.';
98 EGL_BAD_SURFACE: Result := 'An EGLSurface argument does not name a valid surface (window, pixel buffer or pixmap) configured for GL rendering.';
99 EGL_BAD_MATCH: Result := 'Arguments are inconsistent (for example, a valid context requires buffers not supplied by a valid surface).';
100 EGL_BAD_PARAMETER: Result := 'One or more argument values are invalid.';
101 EGL_BAD_NATIVE_PIXMAP: Result := 'A NativePixmapType argument does not refer to a valid native pixmap.';
102 EGL_BAD_NATIVE_WINDOW: Result := 'A NativeWindowType argument does not refer to a valid native window.';
103 EGL_CONTEXT_LOST: Result := 'A power management event has occurred. The application must destroy all contexts and reinitialise OpenGL ES state and objects to continue rendering.';
104 else Result := Format('EGL error %d', [ErrorCode]);
105 end;
106 end;
107
108 { TGLContextEgl -------------------------------------------------------------- }
109
110 function TGLContextEgl.VersionAtLeast(const Major, Minor: EGLint): Boolean;
111 begin
112 Result := (EGLMajor > Major) or
113 ((EGLMajor = Major) and (EGLMinor >= Minor));
114 end;
115
116 {$ifdef OpenGLES}
117
118 { Call eglCreateContext, passing attributes to initialize OpenGL ES 3,
119 eventually fallback on OpenGL ES 2. }
120 function TGLContextEgl.CallEglCreateContext(Config: EGLConfig;
121 ShareContextEgl: EGLContext): EGLContext;
122 const
123 ContextAttribsEs2: array [0..2] of EGLint =
124 ( EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE);
125 ContextAttribsEs3: array [0..2] of EGLint =
126 ( EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE);
127 begin
128 Result := eglCreateContext(Display, Config, ShareContextEgl, @ContextAttribsEs3);
129 if Result = EGL_NO_CONTEXT then
130 Context := eglCreateContext(Display, Config, ShareContextEgl, @ContextAttribsEs2);
131 end;
132
133 {$else}
134
135 { Call eglCreateContext, passing attributes to initialize OpenGL.
136 We may request "core" profile or debug context,
137 following TGLFeatures.RequestCapabilities. }
138 function TGLContextEgl.CallEglCreateContext(Config: EGLConfig;
139 ShareContextEgl: EGLContext): EGLContext;
140 var
141 ContextAttribs: TInt32List;
142 begin
143 if VersionAtLeast(1, 4) then
144 begin
145 if eglBindAPI(EGL_OPENGL_API) <> EGL_TRUE then
146 raise EGLContextNotPossible.Create('EGL: Cannot bind OpenGL API. Error reported: ' + EGLError);
147 end else
148 raise EGLContextNotPossible.Create('EGL version is too old to initialize OpenGL (not ES), we need at least 1.4');
149
150 ContextAttribs := TInt32List.Create;
151 try
152 if TGLFeatures.RequestCapabilities = rcForceModern then
153 begin
154 if VersionAtLeast(1, 5) then
155 ContextAttribs.AddRange([
156 EGL_CONTEXT_MAJOR_VERSION, TGLFeatures.ModernVersionMajor,
157 EGL_CONTEXT_MINOR_VERSION, TGLFeatures.ModernVersionMinor,
158 EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT
159 { Not used, following https://www.khronos.org/opengl/wiki/OpenGL_Context#Context_types
160 forward-compatible really only makes sense on macOS.
161 The "core" profile is what should be just used with new OpenGLs on sane
162 (non-macOS) platforms. }
163 //EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE, EGL_TRUE,
164 ])
165 else
166 WritelnWarning('OpenGL core context could not be requested, because EGL version is too old');
167 end;
168 if TGLFeatures.Debug then
169 begin
170 if VersionAtLeast(1, 5) then
171 ContextAttribs.AddRange([
172 EGL_CONTEXT_OPENGL_DEBUG, EGL_TRUE
173 ])
174 else
175 WritelnWarning('OpenGL debug context could not be requested, because EGL version is too old');
176 end;
177 ContextAttribs.Add(EGL_NONE);
178 Result := eglCreateContext(Display, Config, ShareContextEgl, PEGLint(ContextAttribs.L));
179 finally FreeAndNil(ContextAttribs) end;
180 end;
181
182 {$endif}
183
184 procedure TGLContextEgl.ClassInitialize;
185 begin
186 if Display = EGL_NO_DISPLAY { nil } then
187 begin
188 if not EglAvailable then
189 raise EGLContextNotPossible.Create('Could not load EGL library, required to initialize context');
190
191 Display := eglGetDisplay(EGL_DEFAULT_DISPLAY);
192 if Display = EGL_NO_DISPLAY then
193 { This does not set eglGetError, so we don't use EGLError in message below. }
194 raise EGLContextNotPossible.Create('EGL: Cannot get display');
195
196 if eglInitialize(Display, @EGLMajor, @EGLMinor) = EGL_FALSE then
197 raise EGLContextNotPossible.Create('EGL: Cannot initialize: ' + EGLError);
198 WritelnLog('EGL initialized (version %d.%d).', [EGLMajor, EGLMinor]);
199 end;
200 end;
201
202 procedure TGLContextEgl.ClassFinalize;
203 begin
204 if Display <> EGL_NO_DISPLAY { nil } then
205 begin
206 { Release the current context, to allow eglTerminate to release resources.
207 This allows on Android to reopen OpenGL context from the application
208 (like android_demo ReopenContextButton). }
209 if eglMakeCurrent(Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT) = EGL_FALSE then
210 WritelnWarning('EGL', 'Cannot release current context: ' + EGLError);
211 if eglTerminate(Display) = EGL_FALSE then
212 WritelnWarning('EGL', 'Cannot terminate display connection: ' + EGLError);
213 Display := EGL_NO_DISPLAY;
214 end;
215 end;
216
217 procedure TGLContextEgl.InitializeCore(const Requirements: TGLContextRequirements);
218 var
219 Config: EGLConfig;
220 ShareContextEgl: EGLContext;
221 NumConfig: EGLint;
222 ConfigAttribs: TInt32List;
223 begin
224 ClassInitialize;
225
226 ConfigAttribs := TInt32List.Create;
227 try
228 if Requirements.StencilBits > 0 then
229 ConfigAttribs.AddRange([EGL_STENCIL_SIZE, Requirements.StencilBits]);
230 if Requirements.AlphaBits > 0 then
231 ConfigAttribs.AddRange([EGL_ALPHA_SIZE, Requirements.AlphaBits]);
232 ConfigAttribs.AddRange([
233 EGL_DEPTH_SIZE, Requirements.DepthBits,
234 EGL_RED_SIZE , Max(1, Requirements.RedBits),
235 EGL_GREEN_SIZE, Max(1, Requirements.GreenBits),
236 EGL_BLUE_SIZE , Max(1, Requirements.BlueBits),
237 EGL_RENDERABLE_TYPE,
238 {$ifdef OpenGLES} EGL_OPENGL_ES2_BIT, {$else} EGL_OPENGL_BIT, {$endif}
239 EGL_NONE
240 ]);
241 if eglChooseConfig(Display, PEGLint(ConfigAttribs.L), @Config, 1, @NumConfig) = EGL_FALSE then
242 raise EGLContextNotPossible.Create('EGL: Cannot choose config: ' + EGLError);
243 finally FreeAndNil(ConfigAttribs) end;
244
245 if SharedContext <> nil then
246 ShareContextEgl := (SharedContext as TGLContextEgl).Context
247 else
248 ShareContextEgl := EGL_NO_CONTEXT;
249 Context := CallEglCreateContext(Config, ShareContextEgl);
250 if Context = EGL_NO_CONTEXT then
251 raise EGLContextNotPossible.Create('EGL: Cannot create context: ' + EGLError);
252
253 Surface := eglCreateWindowSurface(Display, Config, WndPtr, nil);
254 if Surface = EGL_NO_SURFACE then
255 raise EGLContextNotPossible.Create('EGL: Cannot create surface: ' + EGLError);
256 end;
257
258 procedure TGLContextEgl.FinalizeCore;
259 begin
260 if Surface <> EGL_NO_SURFACE { nil } then
261 begin
262 if eglDestroySurface(Display, Surface) = EGL_FALSE then
263 WritelnWarning('EGL', 'Cannot destroy surface: ' + EGLError);
264 Surface := EGL_NO_SURFACE;
265 end;
266
267 if InitializedContextsCount = 1 then // we are the last context
268 ClassFinalize;
269 end;
270
271 procedure TGLContextEgl.MakeCurrentCore;
272 begin
273 if eglMakeCurrent(Display, Surface, Surface, Context) = EGL_FALSE then
274 WritelnWarning('EGL', 'Cannot make context current: ' + EGLError);
275 end;
276
277 procedure TGLContextEgl.SwapBuffersCore;
278 begin
279 if eglSwapBuffers(Display, Surface) = EGL_FALSE then
280 WritelnWarning('EGL', 'Cannot swap buffers (this is normal if app is no longer active): ' + EGLError);
281 end;
282
283 procedure TGLContextEgl.QuerySize(out AWidth, AHeight: EGLint);
284 begin
285 if eglQuerySurface(Display, Surface, EGL_WIDTH, @AWidth) = EGL_FALSE then
286 begin
287 WritelnWarning('EGL', 'Cannot query surface width (this is normal if app is no longer active): ' + EGLError);
288 AWidth := 0; // otherwise AWidth would be left undefined
289 end;
290 if eglQuerySurface(Display, Surface, EGL_HEIGHT, @AHeight) = EGL_FALSE then
291 begin
292 WritelnWarning('EGL', 'Cannot query surface height (this is normal if app is no longer active): ' + EGLError);
293 AHeight := 0; // otherwise AHeight would be left undefined
294 end;
295 end;
296
297 end.