Debian Codegraph @

src/base_rendering/castleglimages_rendertotexture.inc

raw
1 {%MainUnit castleglimages.pas}
2 {
3 Copyright 2001-2023 Michalis Kamburelis.
4
5 This file is part of "Castle Game Engine".
6
7 "Castle Game Engine" is free software; see the file COPYING.txt,
8 included in this distribution, for details about the copyright.
9
10 "Castle Game Engine" is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 ----------------------------------------------------------------------------
15 }
16
17 { Part of CastleGLImages unit: rendering to texture (TGLRenderToTexture). }
18
19 {$ifdef read_interface}
20
21 {$ifdef read_interface_type}
22 //type - don't add this Delphi can't parse it correctly
23 EFramebufferError = class(Exception);
24 EFramebufferSizeTooLow = class(EFramebufferError);
25 EFramebufferInvalid = class(EFramebufferError);
26
27 TGLRenderToTextureBuffer = (tbColor, tbDepth, tbColorAndDepth, tbNone);
28
29 { Rendering to texture with OpenGL.
30 Uses framebuffer (if available), and has fallback to glCopyTexSubImage2D
31 for (really) old OpenGL implementations. }
32 TGLRenderToTexture = class
33 private
34 FWidth: Cardinal;
35 FHeight: Cardinal;
36
37 FTexture: TGLTextureId;
38 FTextureTarget: TGLenum;
39 FCompleteTextureTarget: TGLenum;
40 FDepthTextureTarget: TGLenum;
41 FBuffer: TGLRenderToTextureBuffer;
42 FStencil: boolean;
43 FDepthTexture: TGLTextureId;
44
45 FGLInitialized: boolean;
46 Framebuffer, RenderbufferColor, RenderbufferDepth, RenderbufferStencil: TGLuint;
47
48 FramebufferBound: boolean;
49 FColorBufferAlpha: boolean;
50 FMultiSampling: Cardinal;
51 public
52 { Constructor. Doesn't require OpenGL context,
53 and doesn't initialize the framebuffer.
54 You'll have to use GLContextOpen before actually making Render. }
55 constructor Create(const AWidth, AHeight: Cardinal);
56
57 destructor Destroy; override;
58
59 { Width and height must correspond to texture initialized width / height.
60 You cannot change them when OpenGL stuff is already initialized
61 (after GLContextOpen and before GLContextClose or destructor).
62 @groupBegin }
63 property Width: Cardinal read FWidth write FWidth;
64 property Height: Cardinal read FHeight write FHeight;
65 { @groupEnd }
66
67 { Texture associated with the rendered buffer image.
68 If @link(Buffer) is tbColor or tbColorAndDepth then we will capture
69 here color contents. If @link(Buffer) is tbDepth then we will capture
70 here depth contents (useful e.g. for shadow maps).
71 If If @link(Buffer) is tbNone, this is ignored.
72
73 We require this texture to be set to a valid texture (not 0)
74 before GLContextOpen (unless Buffer is tbNone).
75 Also, if you later change it,
76 be careful to assign here other textures of only the same size and format.
77 This allows us to call glCheckFramebufferStatusEXT (and eventually
78 fallback to non-stencil version) right at GLContextOpen call, and no need
79 to repeat it (e.g. at each RenderBegin).
80
81 Changed by SetTexture. }
82 property Texture: TGLTextureId read FTexture default 0;
83
84 { Target of texture associated with rendered buffer.
85 This is GL_TEXTURE_2D for normal 2D textures, but may also be
86 GL_TEXTURE_RECTANGLE, GL_TEXTURE_CUBE_MAP_POSITIVE_X etc. for
87 other texture types.
88
89 Companion to @link(Texture) property, changed together by SetTexture. }
90 property TextureTarget: TGLenum read FTextureTarget default GL_TEXTURE_2D;
91
92 { Change @link(Texture) and @link(TextureTarget).
93
94 May be changed also when OpenGL stuff (framebuffer) is already
95 initialized. This is useful, as it allows you to reuse framebuffer
96 setup for rendering to different textures (as long as other settings
97 are Ok, like Width and Height).
98
99 It may even be changed between RenderBegin and RenderEnd.
100 In fact, this is advised, if you have to call SetTexture often:
101 SetTexture call outside of RenderBegin / RenderEnd causes two
102 costly BindFramebuffer calls, that may be avoided when you're
103 already between RenderBegin / RenderEnd. }
104 procedure SetTexture(const ATexture: TGLTextureId;
105 const ATextureTarget: TGLenum);
106
107 { Bind target of texture associated with rendered color buffer.
108 "Bind target" means that it describes the whole texture, for example
109 for cube map it should be GL_TEXTURE_CUBE_MAP. }
110 property CompleteTextureTarget: TGLenum
111 read FCompleteTextureTarget write FCompleteTextureTarget default GL_TEXTURE_2D;
112
113 { Depth texture used when @link(Buffer) = tbColorAndDepth.
114 Note that this is not used when @link(Buffer) = tbDepth
115 (the @link(Texture) and TextureTarget are used then).
116 This must be set before GLContextOpen, and not modified later
117 until GLContextClose. }
118 property DepthTexture: TGLTextureId read FDepthTexture write FDepthTexture;
119 property DepthTextureTarget: TGLenum read FDepthTextureTarget write FDepthTextureTarget
120 default GL_TEXTURE_2D;
121
122 { Which buffer (color and/or depth) should we catch to the texture.
123
124 @unorderedList(
125 @item(tbColor: the @link(Texture) will contain color contents.)
126 @item(tbDepth: the @link(Texture) will contain depth contents.)
127 @item(tbColorAndDepth: the @link(Texture) will contain color
128 contents, the @link(DepthTexture) will contain depth contents.)
129 @item(tbNone: we will not capture screen contents to any texture at all.
130 This is useful for rendering a screen that you want
131 to capture to normal image with @link(SaveScreen).
132 Be sure to capture the screen before RenderEnd.)
133 )
134
135 For tbDepth and tbColorAndDepth, the texture that will receive
136 depth contents must have GL_DEPTH_COMPONENT* format,
137 and we'll render depth buffer contents to it.
138
139 For tbDepth, if the framebuffer is used (normal on recent GPUs),
140 we will not write to the color buffer at all,
141 so this is quite optimal for rendering shadow maps.
142
143 This must be set before GLContextOpen, cannot be changed later. }
144 property Buffer: TGLRenderToTextureBuffer
145 read FBuffer write FBuffer default tbColor;
146
147 { Should we require stencil buffer.
148
149 This is usually safe, as FBO spec even requires that some format
150 with stencil buffer must be available.
151
152 However, @italic(this has a high chance to fail if you need
153 @link(Buffer) = tbDepth or tbColorAndDepth).
154 Reason: on GPU with packed depth and stencil buffer
155 (see http://www.opengl.org/registry/specs/EXT/packed_depth_stencil.txt
156 and https://www.khronos.org/registry/OpenGL/extensions/OES/OES_packed_depth_stencil.txt)
157 FBO with separate depth and stencil may not be possible.
158 And when your texture is GL_DEPTH_COMPONENT, this is a must.
159 In the future, we could allow some flag to allow you to use texture
160 with GL_DEPTH_STENCIL format, this would work with packed depth/stencil
161 (actually, even require it). For now, @italic(it's advised to turn
162 off @name when you use @link(Buffer) = tbDepth or tbColorAndDepth). }
163 property Stencil: boolean
164 read FStencil write FStencil default true;
165
166 { Initialize OpenGL stuff (framebuffer).
167
168 When OpenGL stuff is initialized (from GLContextOpen until
169 GLContextClose or destruction) this class is tied to the current OpenGL context.
170
171 @raises(EFramebufferSizeTooLow When required @link(Width) x @link(Height)
172 is larger than maximum renderbuffer (single buffer within framebuffer)
173 size.)
174
175 @raises(EFramebufferInvalid When framebuffer is used,
176 and check glCheckFramebufferStatusEXT fails. This should not happen,
177 it means a programmer error. Or "unsupported" result
178 of glCheckFramebufferStatusEXT (that is possible regardless of programmer)
179 we have a nice fallback to non-FBO implementation.) }
180 procedure GLContextOpen;
181
182 { Release all OpenGL stuff (if anything initialized).
183 This is also automatically called in destructor. }
184 procedure GLContextClose;
185
186 { Begin rendering into the texture. Commands following this will
187 render to the texture image.
188
189 When framebuffer is used, it's bound here.
190
191 When framebuffer is not used, this doesn't do anything.
192 So note that all rendering will be done to normal screen in this case. }
193 procedure RenderBegin;
194
195 { End rendering into the texture.
196
197 When framebuffer is used, this binds the normal screen back.
198
199 When framebuffer is not used, this does actual copying from the
200 screen to the texture using glCopyTexSubImage2D. We use
201 glCopyTexSubImage2D --- which means texture internal format
202 should already be initialized! If you don't have any initial texture data,
203 you can always initialize by glTexImage2D with @nil as pointer to data.
204
205 During copying, we may change OpenGL bound 2D texture and read buffer.
206 So their values are ignored, and may be changed arbitrarily, by this
207 method.
208
209 @param(RenderBeginFollows This allows for an optimizaion,
210 to minimize the number of BindFramebuffer calls when you render
211 many textures in the row using the same TGLRenderToTexture.
212 If @true, then you @bold(must) call RenderBegin after this
213 (before drawing anything else to OpenGL).
214 We will internally leave framebuffer bound, which means that
215 this RenderEnd and the very next RenderBegin will actually do nothing.)
216 }
217 procedure RenderEnd(const RenderBeginFollows: boolean = false);
218
219 { Generate mipmaps for the texture.
220 Uses GPU capability to generate mipmaps fast.
221
222 This will raise an exception if necessary OpenGL(ES) version/extension
223 to do is not available (but it really indicates ancient
224 OpenGL(ES) version, all moden versions support this).
225
226 Check HasGenerateMipmap before calling this, if you want to avoid
227 getting the exception. }
228 procedure GenerateMipmap;
229
230 { Color buffer name. Use only when Buffer = tbNone, between GLContextOpen
231 and GLContextClose. This is the buffer name that you should pass to
232 SaveScreen_NoFlush, currently it's just rbColorAttachment0
233 if we actually have FBO or rbBack if not. }
234 function ColorBuffer: TColorBuffer;
235
236 { Do we require color buffer with alpha channel.
237 Relevant only when Buffer = tbNone (as in all other cases,
238 we do not have the color buffer --- colors either go into some texture
239 or are ignored).
240
241 This must be set before GLContextOpen, cannot be changed later. }
242 property ColorBufferAlpha: boolean read FColorBufferAlpha write FColorBufferAlpha
243 default false;
244
245 { All buffers (color and such) will be created with the
246 specified number of samples for multisampling.
247 Values greater than 1 mean that multisampling is used, which enables
248 anti-aliasing.
249 Note that all your textures (in @link(Texture), @link(DepthTexture))
250 must be created with the same number of samples.
251
252 Ignored if not GLFBOMultiSampling. }
253 property MultiSampling: Cardinal
254 read FMultiSampling write FMultiSampling default 1;
255
256 { Save the screen to an image.
257 Call this between RenderBegin and RenderEnd. }
258 function SaveScreen(const ImageClass: TCastleImageClass;
259 const Rect: TRectangle): TCastleImage;
260 end;
261 {$endif read_interface_type}
262
263 {$ifdef read_interface_func}
264
265 { Are we currently doing off-screen rendering.
266 This is @true if we're between
267 TGLRenderToTexture.RenderBegin and TGLRenderToTexture.RenderEnd. }
268 function OffscreenRendering: Boolean;
269
270 {$endif read_interface_func}
271
272 {$endif read_interface}
273
274 {$ifdef read_implementation}
275
276 var
277 FOffscreenRendering: Cardinal;
278
279 function OffscreenRendering: Boolean;
280 begin
281 Result := FOffscreenRendering <> 0;
282 end;
283
284 { BindFramebuffer stack ------------------------------------------------------ }
285
286 var
287 { We may want to use an FBO, while another FBO is already used.
288
289 Right now, this situation happens only when we use castle-model-viewer
290 with --screenshot option, and we load a scene that uses a generated
291 texture (like RenderedTexture or GeneratedShadowMap).
292
293 It's important in such cases that we should restore at the end
294 previously bound FBO --- not necessarily just FBO number 0. }
295 BoundFboStack: TUInt32List;
296
297 { The FBO id meaning "the screen".
298 This is 0 in usual circumstances, except on iOS and iPhone Simulator it can be non-zero
299 (see https://stackoverflow.com/questions/11617013/why-would-glbindframebuffergl-framebuffer-0-result-in-blank-screen-in-cocos2d)
300 }
301 ScreenFbo: TGLuint;
302 ScreenFboQueried: boolean;
303
304 { Use instead of glBindFramebuffer(GL_FRAMEBUFFER, Fbo),
305 for non-zero Fbo. This will bind and add this Fbo to stack. }
306 procedure BindFramebuffer(const Fbo: TGLuint);
307 begin
308 Assert(Fbo <> 0);
309 Assert(Fbo <> ScreenFbo);
310 if BoundFboStack = nil then
311 BoundFboStack := TUInt32List.Create;
312 { See the ScreenFbo documentation for reason why we need to query it now.
313 We use ScreenFboQueried to
314 1. optimize (no need for glGetIntegerv every time we do BindFramebuffer)
315 2. avoid spamming the console with a warning each frame on iOS and iPhone Simulator }
316 if (BoundFboStack.Count = 0) and (not ScreenFboQueried) then
317 begin
318 ScreenFboQueried := true;
319 glGetIntegerv(GL_FRAMEBUFFER_BINDING, @ScreenFbo);
320 if ScreenFbo <> 0 then
321 { See about GTK3:
322 https://stackoverflow.com/questions/62422683/framebuffer-issue-render-to-texture-with-gtk3-glarea-vs-glfw-identical-opengl#62436181
323
324 See about Qt6:
325 https://doc.qt.io/qt-6/qopenglfunctions.html
326 "Note that Qt will translate a framebuffer argument of 0 to the currently bound QOpenGLContext's defaultFramebufferObject()."
327 https://doc.qt.io/qt-6/qopenglcontext.html#defaultFramebufferObject
328 "On some platforms (for instance, iOS) the default framebuffer object depends on the surface being rendered to, and might be different from 0."
329 }
330 WritelnLog('The screen FBO is not 0, it is %d. This known to happen on iOS, iPhone Simulator, GTK 3, Qt6.',
331 [ScreenFbo]);
332 end;
333 BoundFboStack.Add(Fbo);
334
335 if GLFeatures.Framebuffer then
336 glBindFramebuffer(GL_FRAMEBUFFER, Fbo);
337 end;
338
339 { Remove the top Fbo from the stack, and bind previous (new top) Fbo.
340 Binds FBO number 0 (normal OpenGL buffer, actually uses ScreenFbo as it may
341 be <> 0 on iOS / iPhone Simulator) if stack becomes empty.
342
343 PreviousFboDefaultBuffer is set to the default draw buffer suitable
344 for currently (after this call) bound FBO. It's GL_BACK if we're
345 now in normal rendering to window (TODO: we assume you always use double-buffer then),
346 or GL_COLOR_ATTACHMENT0 if we're in another non-window FBO.
347 TODO: it should be GL_NONE if we're in another non-window FBO for tbDepth.
348 Without this, if you would blindly try SetDrawBuffer(GL_BACK)
349 after UnbindFramebuffer, and you are in another single-buffered FBO,
350 OpenGL (at least NVidia and fglrx) will (rightly) report OpenGL
351 "invalid enum" error. }
352 procedure UnbindFramebuffer(out PreviousFboDefaultBuffer: TGLenum); overload;
353 var
354 PreviousFbo: TGLuint;
355 begin
356 if (BoundFboStack <> nil) and (BoundFboStack.Count <> 0) then
357 begin
358 BoundFboStack.Count := BoundFboStack.Count - 1;
359 if BoundFboStack.Count <> 0 then
360 PreviousFbo := BoundFboStack.Last
361 else
362 PreviousFbo := ScreenFbo;
363 end else
364 PreviousFbo := ScreenFbo;
365
366 if PreviousFbo = ScreenFbo then
367 PreviousFboDefaultBuffer := GL_BACK
368 else
369 PreviousFboDefaultBuffer := GL_COLOR_ATTACHMENT0;
370
371 if GLFeatures.Framebuffer then
372 glBindFramebuffer(GL_FRAMEBUFFER, PreviousFbo);
373 end;
374
375 procedure UnbindFramebuffer; overload;
376 var
377 PreviousFboDefaultBuffer: TGLenum;
378 begin
379 UnbindFramebuffer(PreviousFboDefaultBuffer);
380 { ignore PreviousFboDefaultBuffer }
381 end;
382
383 { TGLRenderToTexture --------------------------------------------------------- }
384
385 { Fortunately, all constants with equal meanings have also equal values
386 both for EXT_framebuffer_object and ARB_framebuffer_object (as "core extension"
387 in OpenGL 3). Checked for
388 - FramebufferStatusToString error statuses
389 (except ARB version simply removed some constans (so they will only
390 occur if we happen to use EXT version))
391 - GL_STENCIL_ATTACHMENT
392 - GL_DEPTH_STENCIL
393 - GL_DEPTH_ATTACHMENT
394 - GL_FRAMEBUFFER
395 - GL_COLOR_ATTACHMENT0
396 }
397
398 { Wrapper around glFramebufferTexture2D }
399 procedure FramebufferTexture2D(const Target: TGLenum;
400 const AttachmentDepthAndStencil: boolean;
401 Attachment, TexTarget: TGLenum; const Texture: TGLTextureId; const Level: TGLint);
402 begin
403 Assert(Texture <> 0, 'Texture 0 assigned to framebuffer, FBO will be incomplete');
404 if GLFeatures.Framebuffer then
405 begin
406 if AttachmentDepthAndStencil then
407 begin
408 WritelnLog('FBO', 'Setting GL_DEPTH_ATTACHMENT and GL_STENCIL_ATTACHMENT to the same texture');
409 glFramebufferTexture2D(Target, GL_DEPTH_ATTACHMENT , TexTarget, Texture, Level);
410 glFramebufferTexture2D(Target, GL_STENCIL_ATTACHMENT, TexTarget, Texture, Level);
411 end else
412 glFramebufferTexture2D(Target, Attachment, TexTarget, Texture, Level);
413 end;
414 end;
415
416 constructor TGLRenderToTexture.Create(const AWidth, AHeight: Cardinal);
417 begin
418 inherited Create;
419
420 if not ApplicationProperties.IsGLContextOpen then
421 raise EFramebufferError.Create('Cannot create TGLRenderToTexture when OpenGL context is not available. Do this later -- e.g. from events like TCastleControl.OnOpen, TCastleWindow.OnOpen, Application.OnInitialize, or after an explicit call to TCastleWindow.Open.');
422
423 FTextureTarget := GL_TEXTURE_2D;
424 FCompleteTextureTarget := GL_TEXTURE_2D;
425 FDepthTextureTarget := GL_TEXTURE_2D;
426 FStencil := true;
427
428 FWidth := AWidth;
429 FHeight := AHeight;
430 FMultiSampling := 1;
431 end;
432
433 destructor TGLRenderToTexture.Destroy;
434 begin
435 GLContextClose;
436 inherited;
437 end;
438
439 procedure TGLRenderToTexture.SetTexture(
440 const ATexture: TGLTextureId;
441 const ATextureTarget: TGLenum);
442 begin
443 if (ATexture <> FTexture) or (ATextureTarget <> FTextureTarget) then
444 begin
445 FTexture := ATexture;
446 FTextureTarget := ATextureTarget;
447 if Framebuffer <> 0 then
448 begin
449 if not FramebufferBound then
450 BindFramebuffer(Framebuffer);
451 if GLFeatures.Framebuffer then
452 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, TextureTarget, Texture, 0);
453 if not FramebufferBound then
454 UnbindFramebuffer;
455 end;
456 end;
457 end;
458
459 procedure TGLRenderToTexture.GLContextOpen;
460
461 function FramebufferStatusToString(const Status: TGLenum): string;
462 {$ifndef OpenGLES}
463 const
464 GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS = GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT;
465 {$endif}
466 begin
467 { some of these messages based on spec wording
468 http://oss.sgi.com/projects/ogl-sample/registry/EXT/framebuffer_object.txt ,
469 http://www.opengl.org/registry/specs/ARB/framebuffer_object.txt }
470 case Status of
471 GL_FRAMEBUFFER_COMPLETE : Result := 'Complete (no error)';
472 GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT : Result := 'INCOMPLETE_ATTACHMENT: Not all framebuffer attachment points are "framebuffer attachment complete"';
473 GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT : Result := 'INCOMPLETE_MISSING_ATTACHMENT: None image attached to the framebuffer. On some GPUs/drivers (fglrx) it may also mean that desired image size is too large';
474 GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS : Result := 'INCOMPLETE_DIMENSIONS: Not all attached images have the same width and height';
475 {$ifndef OpenGLES}
476 GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT : Result := 'INCOMPLETE_FORMATS: Not all images attached to the attachment points COLOR_ATTACHMENT* have the same internal format';
477 GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER : Result := 'INCOMPLETE_DRAW_BUFFER: The value of FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is NONE for some color attachment point(s) named by DRAW_BUFFERi';
478 GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER : Result := 'INCOMPLETE_READ_BUFFER: READ_BUFFER is not NONE, and the value of FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is NONE for the color attachment point named by READ_BUFFER';
479 GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE : Result := 'INCOMPLETE_MULTISAMPLE: The value of RENDERBUFFER_SAMPLES is not the same for all attached images.';
480 {$endif}
481 GL_FRAMEBUFFER_UNSUPPORTED : Result := 'UNSUPPORTED: The combination of internal formats of the attached images violates an implementation-dependent set of restrictions';
482 0: Result := 'OpenGL error during CheckFramebufferStatus';
483 else Result := 'Unknown FramebufferStatus error: ' + GLErrorString(Status);
484 end;
485 end;
486
487 { Create and bind and set renderbuffer storage.
488 If AttachmentDepthAndStencil, we attach to both depth/stencil,
489 and provided Attachment value is ignored. Otherwise, we attach to the given
490 Attachment. }
491 procedure GenBindRenderbuffer(var RenderbufferId: TGLuint;
492 const InternalFormat: TGLenum; const AttachmentDepthAndStencil: boolean;
493 Attachment: TGLenum);
494 begin
495 if GLFeatures.Framebuffer then
496 begin
497 glGenRenderbuffers(1, @RenderbufferId);
498 glBindRenderbuffer(GL_RENDERBUFFER, RenderbufferId);
499 {$ifndef OpenGLES}
500 if (MultiSampling > 1) and GLFeatures.FBOMultiSampling then
501 glRenderbufferStorageMultisample(GL_RENDERBUFFER, MultiSampling, InternalFormat, Width, Height) else
502 {$endif}
503 glRenderbufferStorage(GL_RENDERBUFFER, InternalFormat, Width, Height);
504 if AttachmentDepthAndStencil then
505 begin
506 // WritelnLog('FBO', 'Setting GL_DEPTH_ATTACHMENT and GL_STENCIL_ATTACHMENT to the same renderbuffer');
507 { Radeon drivers (ATI Mobility Radeon HD 4330) throw OpenGL error "invalid enum"
508 when trying to use GL_DEPTH_STENCIL_ATTACHMENT. }
509 glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, RenderbufferId);
510 glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, RenderbufferId);
511 end else
512 glFramebufferRenderbuffer(GL_FRAMEBUFFER, Attachment, GL_RENDERBUFFER, RenderbufferId);
513 end;
514 end;
515
516 function ColorBufferFormat: TGLenum;
517 begin
518 if ColorBufferAlpha then
519 Result := GL_RGBA
520 else
521 Result := GL_RGB;
522 end;
523
524 var
525 Status: TGLenum;
526 DepthBufferFormatPacked, DepthAttachmentPacked: TGLenum;
527 DepthAttachmentWithStencil: boolean;
528 Success: boolean;
529 PreviousFboDefaultBuffer: TGLenum;
530 begin
531 Assert(not FGLInitialized, 'You cannot call TGLRenderToTexture.GLContextInit on already OpenGL-initialized instance. Call GLContextClose first if this is really what you want.');
532
533 if GLFeatures.Framebuffer and
534 (not (GLVersion.BuggyFBOCubeMap and TargetIsCubeMapSide(TextureTarget))) then
535 begin
536 if (Width > GLFeatures.MaxRenderbufferSize) or
537 (Height > GLFeatures.MaxRenderbufferSize) then
538 raise EFramebufferSizeTooLow.CreateFmt('Maximum renderbuffer (within framebuffer) size is %d x %d in your OpenGL implementation, while we require %d x %d',
539 [ GLFeatures.MaxRenderbufferSize, GLFeatures.MaxRenderbufferSize, Width, Height ]);
540
541 glGenFramebuffers(1, @Framebuffer);
542 BindFramebuffer(Framebuffer);
543
544 { When GLFeatures.PackedDepthStencil and stencil is wanted
545 (a very common case!, as most GPUs have EXT_packed_depth_stencil
546 and for shadow volumes we want stencil) we desperately want to
547 use one renderbuffer or one texture with combined depth/stencil info.
548 Other possibilities may be not available at all,
549 as OpenGL only guarantees we can create FBO matching current screen configuration. }
550 {$ifndef OpenGLES}
551 if Stencil and GLFeatures.PackedDepthStencil then
552 begin
553 DepthBufferFormatPacked := GL_DEPTH_STENCIL;
554 DepthAttachmentWithStencil := true;
555 DepthAttachmentPacked := GL_DEPTH_STENCIL_ATTACHMENT;
556 end else
557 // TODO-es This is probably needed on gles too?
558 // we have GL_DEPTH_STENCIL_OES.
559 {$endif}
560 begin
561 DepthBufferFormatPacked :=
562 { OpenGLES notes:
563 - When depth is a texture, GL_DEPTH_COMPONENT works just as well
564 as GL_DEPTH_COMPONENT16. Our depth textures use UNSIGNED_SHORT,
565 so they match 16 bits. Although when we use UNSIGNED_INT for
566 depth for screen effects it also works...
567 So it really doesn't seem to matter, at least for Mesa OpenGLES
568 everything works.
569 - For renderbuffer, we really need to use the enum with 16 suffix.
570 Otherwise (on Mesa OpenGLES) we'll get FBO incomplete errors. }
571 {$ifdef OpenGLES} GL_DEPTH_COMPONENT16
572 {$else} GL_DEPTH_COMPONENT
573 {$endif};
574 DepthAttachmentPacked := GL_DEPTH_ATTACHMENT;
575 DepthAttachmentWithStencil := false;
576 end;
577
578 case Buffer of
579 tbColor:
580 begin
581 FramebufferTexture2D(GL_FRAMEBUFFER, false, GL_COLOR_ATTACHMENT0, TextureTarget, Texture, 0);
582 GenBindRenderbuffer(RenderbufferDepth, DepthBufferFormatPacked, DepthAttachmentWithStencil, DepthAttachmentPacked);
583 end;
584 tbDepth:
585 begin
586 { Needed to consider FBO "complete" }
587 SetDrawBuffer(GL_NONE);
588 SetReadBuffer(GL_NONE);
589
590 FramebufferTexture2D(GL_FRAMEBUFFER, DepthAttachmentWithStencil, DepthAttachmentPacked, TextureTarget, Texture, 0);
591 end;
592 tbColorAndDepth:
593 begin
594 FramebufferTexture2D(GL_FRAMEBUFFER, false, GL_COLOR_ATTACHMENT0, TextureTarget, Texture, 0);
595 FramebufferTexture2D(GL_FRAMEBUFFER, DepthAttachmentWithStencil, DepthAttachmentPacked, DepthTextureTarget, DepthTexture, 0);
596 end;
597 tbNone:
598 begin
599 GenBindRenderbuffer(RenderbufferColor, ColorBufferFormat, false, GL_COLOR_ATTACHMENT0);
600 GenBindRenderbuffer(RenderbufferDepth, DepthBufferFormatPacked, DepthAttachmentWithStencil, DepthAttachmentPacked);
601 end;
602 {$ifndef COMPILER_CASE_ANALYSIS}
603 else raise EInternalError.Create('Buffer 1?');
604 {$endif}
605 end;
606
607 { setup separate stencil buffer }
608 if Stencil and not GLFeatures.PackedDepthStencil then
609 { initialize RenderbufferStencil, attach it to FBO stencil }
610 GenBindRenderbuffer(RenderbufferStencil, GL_STENCIL_INDEX, false, GL_STENCIL_ATTACHMENT);
611
612 Success := false;
613 try
614 CheckGLErrors('Check errors before checking FBO status');
615 Status := glCheckFramebufferStatus(GL_FRAMEBUFFER);
616 case Status of
617 GL_FRAMEBUFFER_COMPLETE: Success := true;
618 GL_FRAMEBUFFER_UNSUPPORTED: WritelnWarning('FBO', 'Unsupported framebuffer configuration, will fallback to glCopyTexSubImage2D approach. If your window is invisible (like for "castle-model-viewer --screenshot"), you may get only a black screen.');
619 else raise EFramebufferInvalid.CreateFmt('Framebuffer check failed: %s (FBO error number %d)',
620 [ FramebufferStatusToString(Status), Status]);
621 end;
622 finally
623 { Always, regardless of Success, unbind FBO and restore normal gl*Buffer }
624 glBindRenderbuffer(GL_RENDERBUFFER, 0);
625 UnbindFramebuffer(PreviousFboDefaultBuffer);
626
627 if Buffer = tbDepth then
628 begin
629 SetDrawBuffer(PreviousFboDefaultBuffer);
630 SetReadBuffer(PreviousFboDefaultBuffer);
631 end;
632
633 { If failure, release resources. In particular, this sets Framebuffer = 0,
634 which will be a signal to other methods that FBO is not supported. }
635 if not Success then
636 GLContextClose;
637 end;
638 end;
639
640 FGLInitialized := true;
641 end;
642
643 procedure TGLRenderToTexture.GLContextClose;
644
645 procedure FreeRenderbuffer(var Buf: TGLuint);
646 begin
647 if Buf <> 0 then
648 begin
649 if GLFeatures.Framebuffer then
650 glDeleteRenderbuffers(1, @Buf);
651 Buf := 0;
652 end;
653 end;
654
655 procedure FreeFramebuffer(var Buf: TGLuint);
656 begin
657 if Buf <> 0 then
658 begin
659 if GLFeatures.Framebuffer then
660 glDeleteFramebuffers(1, @Buf);
661 Buf := 0;
662 end;
663 end;
664
665 begin
666 FreeRenderbuffer(RenderbufferColor);
667 FreeRenderbuffer(RenderbufferDepth);
668 FreeRenderbuffer(RenderbufferStencil);
669 FreeFramebuffer(Framebuffer);
670 end;
671
672 procedure TGLRenderToTexture.RenderBegin;
673 begin
674 Inc(FOffscreenRendering);
675
676 if Framebuffer <> 0 then
677 begin
678 if not FramebufferBound then
679 begin
680 BindFramebuffer(Framebuffer);
681 FramebufferBound := true;
682
683 if Buffer = tbDepth then
684 begin
685 SetDrawBuffer(GL_NONE);
686 SetReadBuffer(GL_NONE);
687 end;
688 end;
689 Assert(FramebufferBound);
690 end;
691 end;
692
693 { A debug trick, saves color or depth buffer of the generated framebuffer image
694 to a URL (file:///tmp/framebuffer_color/depth.png, change the code below
695 if you want other URL). Useful e.g. to visualize captured shadow maps. }
696 { $define DEBUG_SAVE_FRAMEBUFFER_DEPTH}
697 { $define DEBUG_SAVE_FRAMEBUFFER_COLOR}
698
699 procedure TGLRenderToTexture.RenderEnd(const RenderBeginFollows: boolean);
700
701 {$ifdef DEBUG_SAVE_FRAMEBUFFER_COLOR}
702 procedure SaveColor(const Url: String);
703 var
704 Image: TCastleImage;
705 begin
706 Image := TRGBImage.Create(Width, Height);
707 try
708 BeforePackImage(Image);
709 try
710 glReadPixels(0, 0, Width, Height, ImageGLFormat(Image),
711 ImageGLType(Image), Image.RawPixels);
712 finally AfterPackImage(Image) end;
713
714 SaveImage(Image, Url);
715 finally FreeAndNil(Image) end;
716 end;
717 {$endif DEBUG_SAVE_FRAMEBUFFER_COLOR}
718
719 {$ifdef DEBUG_SAVE_FRAMEBUFFER_DEPTH}
720 procedure SaveDepth(const Url: String);
721 var
722 Image: TGrayscaleImage;
723 begin
724 Image := TGrayscaleImage.Create(Width, Height);
725 try
726 BeforePackImage(Image);
727 try
728 glReadPixels(0, 0, Width, Height, GL_DEPTH_COMPONENT,
729 ImageGLType(Image), Image.RawPixels);
730 finally AfterPackImage(Image) end;
731
732 SaveImage(Image, Url);
733 finally FreeAndNil(Image) end;
734 end;
735 {$endif DEBUG_SAVE_FRAMEBUFFER_DEPTH}
736
737 var
738 PreviousFboDefaultBuffer: TGLenum;
739 begin
740 {$ifdef DEBUG_SAVE_FRAMEBUFFER_COLOR}
741 if Buffer <> tbDepth then
742 SaveColor('file:///tmp/framebuffer_color.png');
743 {$endif DEBUG_SAVE_FRAMEBUFFER_COLOR}
744 {$ifdef DEBUG_SAVE_FRAMEBUFFER_DEPTH}
745 SaveDepth('file:///tmp/framebuffer_depth.png');
746 {$endif DEBUG_SAVE_FRAMEBUFFER_DEPTH}
747
748 if Framebuffer <> 0 then
749 begin
750 Assert(FramebufferBound);
751 if not RenderBeginFollows then
752 begin
753 UnbindFramebuffer(PreviousFboDefaultBuffer);
754 FramebufferBound := false;
755
756 if Buffer = tbDepth then
757 begin
758 SetDrawBuffer(PreviousFboDefaultBuffer);
759 SetReadBuffer(PreviousFboDefaultBuffer);
760 end;
761 end;
762 end else
763 if Buffer <> tbNone then
764 begin
765 { Actually update OpenGL texture }
766 glBindTexture(CompleteTextureTarget, Texture);
767 SetReadBuffer(GL_BACK);
768 glCopyTexSubImage2D(TextureTarget, 0, 0, 0, 0, 0, Width, Height);
769
770 if Buffer = tbColorAndDepth then
771 begin
772 glBindTexture(DepthTextureTarget, DepthTexture);
773 SetReadBuffer(GL_BACK);
774 glCopyTexSubImage2D(DepthTextureTarget, 0, 0, 0, 0, 0, Width, Height);
775 end;
776 end;
777
778 Dec(FOffscreenRendering);
779 end;
780
781 procedure TGLRenderToTexture.GenerateMipmap;
782 begin
783 glBindTexture(CompleteTextureTarget, Texture);
784 CastleInternalGLUtils.GenerateMipmap(CompleteTextureTarget);
785 { TODO: size of these mipmaps is not accounted for in texture memory profiler }
786 end;
787
788 function TGLRenderToTexture.ColorBuffer: TColorBuffer;
789 begin
790 if Framebuffer <> 0 then
791 Result := cbColorAttachment0 else
792 Result := cbBack;
793 end;
794
795 function TGLRenderToTexture.SaveScreen(const ImageClass: TCastleImageClass;
796 const Rect: TRectangle): TCastleImage;
797 var
798 NonMultiFbo: TGLRenderToTexture;
799 begin
800 Assert(FramebufferBound);
801
802 if (MultiSampling > 1) and
803 GLFeatures.FBOMultiSampling then
804 begin
805 if not GLFeatures.FramebufferBlit then
806 raise Exception.Create('Cannot get FBO contents without glBlitFramebuffer supported. You need a newer GPU for this application to work.');
807
808 { In case we used multi-sampling FBO for rendering,
809 we cannot directly use glReadPixels on it. See the bottom of
810 https://www.khronos.org/opengl/wiki/GL_EXT_framebuffer_multisample :
811 we need to blit the Fbo into another non-multisampling FBO first. }
812 NonMultiFbo := TGLRenderToTexture.Create(Width, Height);
813 try
814 NonMultiFbo.Buffer := tbNone;
815 NonMultiFbo.ColorBufferAlpha := ColorBufferAlpha;
816 NonMultiFbo.GLContextOpen;
817
818 glBindFramebuffer(GL_READ_FRAMEBUFFER, Framebuffer);
819 glBindFramebuffer(GL_DRAW_FRAMEBUFFER, NonMultiFbo.Framebuffer);
820 glBlitFramebuffer(0, 0, Width, Height, 0, 0, Width, Height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
821
822 glBindFramebuffer(GL_FRAMEBUFFER, NonMultiFbo.Framebuffer);
823 Result := SaveScreen_NoFlush(ImageClass, Rect, ColorBuffer);
824
825 // bind again our own FBO, to be consistent with behavior in non-multi-sampling cases
826 glBindFramebuffer(GL_FRAMEBUFFER, Framebuffer);
827 finally FreeAndNil(NonMultiFbo) end;
828 end else
829 Result := SaveScreen_NoFlush(ImageClass, Rect, ColorBuffer);
830 end;
831
832 {$endif read_implementation}