Debian Codegraph @

src/scene/castlescreeneffects.pas

raw
1 {
2 Copyright 2010-2023 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 { Screen effects (post-processing) using shaders (TCastleScreenEffects). }
17 unit CastleScreenEffects;
18
19 {$I castleconf.inc}
20
21 interface
22
23 uses SysUtils, Classes,
24 {$ifdef OpenGLES} CastleGLES, {$else} CastleGL, {$endif}
25 CastleVectors, CastleGLShaders, CastleUIControls, X3DNodes, CastleGLImages,
26 CastleRectangles, CastleScene, CastleTransform, CastleCameras, CastleGLUtils,
27 CastleRenderOptions, CastleInternalRenderer;
28
29 type
30 { Screen effects are shaders that post-process the rendered screen.
31 The effects may be defined using @url(https://castle-engine.io/x3d_extensions_screen_effects.php
32 X3D node ScreenEffect).
33
34 This control applies screen effects (post-processing)
35 on the rendering done by children and (when this class is used as an ancestor)
36 it's descendants.
37
38 It can be used to apply screen effects over any UI control,
39 like @link(TCastleViewport),
40 @link(TCastleButton), @link(TCastleImageControl) and so on.
41 Simply place the desired control as child of this control.
42
43 To make it easier to apply effects on @link(TCastleViewport),
44 it already descends from this class. So, while you can, you don't need to wrap
45 @link(TCastleViewport) instance inside another @link(TCastleScreenEffects)
46 instance. You can instead directly call @link(AddScreenEffect) on your
47 @link(TCastleViewport) instance.
48
49 Note that the UI controls rendered for the screen effects
50 (our children and descendants) must always initialize and fill
51 colors of the entire rectangle (@link(RenderRect)) of this control.
52 Otherwise, the results are undefined, as an internal texture that is used
53 for screen effects is initially undefined.
54 You may use e.g. @link(TCastleRectangleControl) to fill the background with a solid color
55 from @link(TCastleRectangleControl.Color).
56 Or use @link(TCastleViewport) with @link(TCastleViewport.Transparent) = @false (default)
57 which fills background with @link(TCastleViewport.BackgroundColor).
58 }
59 TCastleScreenEffects = class(TCastleUserInterface)
60 strict private
61 type
62 TScreenPoint = packed record
63 Position: TVector2;
64 TexCoord: TVector2;
65 end;
66 var
67 { Scene containing screen effects }
68 ScreenEffectsScene: TCastleScene;
69 ScreenEffectsRoot: TX3DRootNode;
70 FScreenEffectsTimeScale: Single;
71 { World to pass dummy camera position to ScreenEffectsScene. }
72 World: TCastleRootTransform;
73 FRenderer: TRenderer;
74 FPrepareParams: TPrepareParams;
75
76 { OpenGL(ES) resources for screen effects. }
77 { If a texture for screen effects is ready, then
78 ScreenEffectTextureDest/Src/Depth/Target are non-zero and
79 ScreenEffectRTT is non-nil.
80 Also, ScreenEffectTextureWidth/Height indicate size of the texture,
81 as well as ScreenEffectRTT.Width/Height. }
82 ScreenEffectTextureDest, ScreenEffectTextureSrc: TGLuint;
83 ScreenEffectTextureTarget: TGLenum;
84 ScreenEffectTextureDepth: TGLuint;
85 ScreenEffectRTT: TGLRenderToTexture;
86 ScreenEffectTextureWidth: Cardinal;
87 ScreenEffectTextureHeight: Cardinal;
88 { Saved ScreenEffectsCount/NeedDepth result, during rendering. }
89 CurrentScreenEffectsCount: Integer;
90 CurrentScreenEffectsNeedDepth: boolean;
91 ScreenPointVbo: TGLuint;
92 ScreenPointVao: TVertexArrayObject;
93 ScreenPoint: packed array [0..3] of TScreenPoint;
94
95 FScreenEffectsEnable: Boolean;
96
97 function GetScreenEffectsCount: Cardinal;
98 function GetScreenEffectsNeedDepth: Boolean;
99 function GetScreenEffect(const Index: Integer): TGLSLProgram;
100
101 procedure GLContextCloseEvent(Sender: TObject);
102 protected
103 { Valid only between Render and RenderOverChildren calls.
104 Tells whether we actually use screen effects, thus RenderWithoutScreenEffects
105 renders to texture.
106 Read-only in descendants. }
107 RenderScreenEffects: Boolean;
108
109 { Descendants with special rendering code should override this,
110 and @italic(never) override @link(Render) or @link(RenderOverChildren)
111 (as those two methods have special implementation in this class).
112
113 This rendering method will be called regardless if we have
114 or not some screen effects.
115 When no screen effects are actually used (e.g. @link(AddScreenEffect)
116 wasn't used, @code(InternalExtraScreenEffectsCount) is zero), then our @link(Render)
117 trivially calls this method without doing anything else. }
118 procedure RenderWithoutScreenEffects; virtual;
119
120 { Render these additional screen effects, defined by explicit TGLSLProgram
121 instead of by AddScreenEffect call.
122 This is internal, only to be used by TCastleViewport.
123 @exclude }
124 function InternalExtraGetScreenEffects(
125 const Index: Integer): TGLSLProgram; virtual;
126 { @exclude }
127 function InternalExtraScreenEffectsCount: Integer; virtual;
128 { @exclude }
129 function InternalExtraScreenEffectsNeedDepth: Boolean; virtual;
130 public
131 constructor Create(AOwner: TComponent); override;
132 destructor Destroy; override;
133
134 { Add or remove a ScreenEffect node that defines new shader screen effect.
135 See https://castle-engine.io/x3d_extensions_screen_effects.php .
136
137 In the simple case, you can pass here an instance of TScreenEffectNode.
138 In a general case, you can passs here any X3D node you want,
139 just remember that only the TScreenEffectNode inside will be rendered.
140 You can e.g. pass a TGroupNode with TScreenEffectNode and TTimeSensorNode
141 as children,
142 and use TTimeSensorNode to provide time to your shader uniform parameter.
143 Or you can e.g. pass an X3D graph loaded from X3D file
144 using @link(X3DLoad.LoadNode), this way you can define effects
145 inside an external X3D file, e.g. like this:
146
147 @longCode(#
148 ScreenEffects.AddScreenEffect(
149 LoadNode('castle-data:/screen_effects_scene.x3dv'));
150 #)
151
152 If you're looking for inspirations what to put in screen_effects_scene.x3dv,
153 see https://github.com/castle-engine/demo-models/tree/master/screen_effects .
154 See also CGE example in "examples/screen_effects_demo/" directory
155 ( https://github.com/castle-engine/castle-engine/tree/master/examples/screen_effects_demo )
156 that shows more screen effects code,
157 and shows how to load or construct X3D node graph with ScreenEffect.
158
159 The memory management of the node added here is automatic:
160 the added screen effect becomes owned by the internal X3D Group node.
161 It's reference-count is increased at AddScreenEffect, and decreased
162 at RemoveScreenEffect, and it is automatically freed when reference-count
163 drops to zero.
164
165 This means that, if you create the provided Node by code,
166 and don't add it anywhere else, then the node will be freed
167 automatically at our destructor (if you call AddScreenEffect
168 and do not call RemoveScreenEffect on it),
169 or at RemoveScreenEffect call.
170 If you don't want this, use @link(TX3DNode.KeepExistingBegin)
171 to manage the node destruction yourself.
172
173 Note that the given Node should not be used by other TCastlScene instances.
174 In general, a node should not be present in more than one TCastlScene instance,
175 and we already insert the node into an internal TCastlScene instance.
176 Use TX3DNode.DeepCopy if necessary to duplicate node into multiple scenes.
177
178 Note that you can enable/disable the effect using @link(TScreenEffectNode.Enabled),
179 or enable/disable all using @link(ScreenEffectsEnable).
180 You do not need to remove the node by @link(RemoveScreenEffect) if you only want
181 to disable it temporarily.
182 }
183 procedure AddScreenEffect(const Node: TAbstractChildNode);
184 procedure RemoveScreenEffect(const Node: TAbstractChildNode);
185
186 procedure BeforeRender; override;
187 procedure Render; override;
188 procedure RenderOverChildren; override;
189 procedure Update(const SecondsPassed: Single; var HandleInput: boolean); override;
190 procedure GLContextClose; override;
191
192 { Scale time passing inside TimeSensor nodes you add as part of AddScreenEffect.
193 May be 0 to stop time passing.
194 This has deliberately long name, instead of simple TimeScale,
195 to make it clear that it's completely independent from
196 @link(TCastleAbstractRootTransform.TimeScale). }
197 property ScreenEffectsTimeScale: Single
198 read FScreenEffectsTimeScale write FScreenEffectsTimeScale {$ifdef FPC}default 1{$endif};
199
200 { Enable or disable all screen effects added by AddScreenEffect.
201 When this is @true, particular screen effects can still be enabled/disabled
202 using @link(TScreenEffectNode.Enabled).
203 When this is @false, all effects are disabled, regardless of
204 @link(TScreenEffectNode.Enabled). }
205 property ScreenEffectsEnable: Boolean
206 read FScreenEffectsEnable write FScreenEffectsEnable default true;
207
208 { Make the screen effects rendering resources ready (e.g. link shaders). }
209 procedure PrepareResources;
210 end;
211
212 implementation
213
214 uses CastleUtils, CastleLog, CastleRenderContext, CastleInternalGLUtils,
215 CastleApplicationProperties, CastleInternalScreenEffects;
216
217 { TCastleScreenEffects ------------------------------------------------------- }
218
219 constructor TCastleScreenEffects.Create(AOwner: TComponent);
220 begin
221 inherited;
222 FScreenEffectsTimeScale := 1;
223 FScreenEffectsEnable := true;
224
225 FRenderer := TRenderer.Create(nil);
226
227 FPrepareParams := TPrepareParams.Create;
228 FPrepareParams.GlobalLights := nil;
229 FPrepareParams.GlobalFog := nil;
230 FPrepareParams.RendererToPrepareShapes := FRenderer;
231
232 ApplicationProperties.OnGLContextCloseObject.Add(
233 {$ifdef FPC}@{$endif} GLContextCloseEvent);
234 end;
235
236 destructor TCastleScreenEffects.Destroy;
237 begin
238 ApplicationProperties.OnGLContextCloseObject.Remove(
239 {$ifdef FPC}@{$endif} GLContextCloseEvent);
240
241 FreeAndNil(FPrepareParams);
242 FreeAndNil(FRenderer);
243 inherited;
244 end;
245
246 procedure TCastleScreenEffects.GLContextCloseEvent(Sender: TObject);
247 begin
248 if ScreenEffectsScene <> nil then
249 ScreenEffectsScene.GLContextClose;
250 end;
251
252 procedure TCastleScreenEffects.AddScreenEffect(const Node: TAbstractChildNode);
253 begin
254 if ScreenEffectsScene = nil then
255 begin
256 ScreenEffectsRoot := TX3DRootNode.Create;
257
258 { We create TCastleScene that is used only for rendering screen effects.
259 This way we can make all "support" things for screen effects work,
260 e.g. textures will be initialized using CastleInternalRenderer,
261 TimeSensor will work and can be fed into shader uniform etc. }
262 ScreenEffectsScene := TCastleScene.Create(Self);
263 ScreenEffectsScene.Name := 'ScreenEffectsScene';
264 ScreenEffectsScene.Load(ScreenEffectsRoot, true);
265 ScreenEffectsScene.ProcessEvents := true;
266
267 (* We setup World with camera knowledge to make some ProximitySensors working,
268 like a dummy "ProximitySensors { size 10000 10000 10000 }". *)
269 World := TCastleRootTransform.Create(Self);
270 World.Add(ScreenEffectsScene);
271 World.MainCamera := TCastleCamera.Create(Self);
272 World.Add(World.MainCamera); // necessary to be able to query camera world coords
273 end;
274
275 { Note that AddChildren by default has AllowDuplicates=true,
276 and enables multiple instances of this node on a list. That's good. }
277 ScreenEffectsRoot.AddChildren(Node);
278
279 { Send InternalCameraChanged now, to activate ProximitySensors inside new nodes. }
280 ScreenEffectsScene.InternalCameraChanged;
281 end;
282
283 procedure TCastleScreenEffects.RemoveScreenEffect(const Node: TAbstractChildNode);
284 begin
285 if ScreenEffectsRoot <> nil then
286 begin
287 ScreenEffectsRoot.FdChildren.Remove(Node);
288 ScreenEffectsRoot.FdChildren.Changed;
289 end;
290 end;
291
292 function TCastleScreenEffects.InternalExtraGetScreenEffects(const Index: Integer): TGLSLProgram;
293 begin
294 raise EInternalError.Create('Override InternalExtraGetScreenEffects if you override InternalExtraScreenEffectsCount. In TCastleScreenEffects, InternalExtraScreenEffectsCount returns zero, so InternalExtraGetScreenEffects should never be called');
295 Result := nil; // silence FPC warnings about undefined result
296 end;
297
298 function TCastleScreenEffects.InternalExtraScreenEffectsCount: Integer;
299 begin
300 Result := 0;
301 end;
302
303 function TCastleScreenEffects.InternalExtraScreenEffectsNeedDepth: Boolean;
304 begin
305 Result := false;
306 end;
307
308 function TCastleScreenEffects.GetScreenEffectsCount: Cardinal;
309 begin
310 Result := 0;
311 if ScreenEffectsEnable then
312 begin
313 if ScreenEffectsScene <> nil then
314 { TCastleScene already implemented logic to only count screen effects
315 that are enabled, and their GLSL code linked successfully.
316 Cool, we depend on it. }
317 Result := Result + ScreenEffectsScene.InternalScreenEffectsCount;
318 Result := Result + InternalExtraScreenEffectsCount;
319 end;
320 end;
321
322 function TCastleScreenEffects.GetScreenEffectsNeedDepth: Boolean;
323 begin
324 Result := ScreenEffectsEnable and (
325 ((ScreenEffectsScene <> nil) and ScreenEffectsScene.InternalScreenEffectsNeedDepth) or
326 InternalExtraScreenEffectsNeedDepth
327 );
328 end;
329
330 function TCastleScreenEffects.GetScreenEffect(const Index: Integer): TGLSLProgram;
331 var
332 SceneEffects: Integer;
333 begin
334 if ScreenEffectsScene <> nil then
335 SceneEffects := ScreenEffectsScene.InternalScreenEffectsCount
336 else
337 SceneEffects := 0;
338
339 if Index < SceneEffects then
340 Result := ScreenEffectsScene.InternalScreenEffects(Index)
341 else
342 Result := InternalExtraGetScreenEffects(Index - SceneEffects);
343 end;
344
345 procedure TCastleScreenEffects.Render;
346 var
347 SR: TRectangle;
348
349 { Calculate
350 RenderScreenEffects (whether we actually do anything about screen effects),
351 CurrentScreenEffectsCount,
352 CurrentScreenEffectsNeedDepth.
353 }
354 procedure CheckScreenEffects;
355 begin
356 { Check do we have any screen effects to show.
357
358 Save GetScreenEffectsCount (and later GetScreenEffectsNeedDepth) result,
359 to not recalculate it,
360 and make the rest of code stable --- this way we know
361 CurrentScreenEffectsCount and later CurrentScreenEffectsNeedDepth
362 values are constant, even if user modifies FScreenEffects in the middle. }
363 CurrentScreenEffectsCount := GetScreenEffectsCount;
364 RenderScreenEffects := CurrentScreenEffectsCount <> 0;
365 if not RenderScreenEffects then Exit; // no need to do anything else
366
367 { all the checks below should pass on a modern GPU }
368 SR := RenderRect.Round;
369 RenderScreenEffects :=
370 (not GLFeatures.EnableFixedFunction) and
371 GLFeatures.UseMultiTexturing and
372 { check IsTextureSized, to gracefully work (without screen effects)
373 on old desktop OpenGL that does not support NPOT textures. }
374 IsTextureSized(SR.Width, SR.Height, tsAny);
375 if not RenderScreenEffects then Exit; // no need to do anything else
376
377 { check the need to render depth buffer to a texture. }
378 CurrentScreenEffectsNeedDepth := GetScreenEffectsNeedDepth;
379 if CurrentScreenEffectsNeedDepth and not GLFeatures.TextureDepth then
380 begin
381 { We support only screen effects that do not require depth.
382 TODO: It would be cleaner to still enable screen effects not using
383 depth (and only them), instead of just disabling all screen effects. }
384 RenderScreenEffects := false;
385 Exit;
386 end;
387 end;
388
389 { Create and setup new OpenGL texture for screen effects.
390 Depends on ScreenEffectTextureWidth, ScreenEffectTextureHeight being set. }
391 function CreateScreenEffectTexture(const Depth: boolean): TGLuint;
392
393 { Create new OpenGL texture for screen effect.
394 Calls glTexImage2D or glTexImage2DMultisample
395 (depending on multi-sampling requirements).
396
397 - image contents are always unallocated (pixels = nil for glTexImage2D).
398 For screen effects, we never need to load initial image contents,
399 and we also do not have to care about pixel packing.
400 - level for mipmaps is always 0
401 - border is always 0
402 - image target is ScreenEffectTextureTarget
403 - size is ScreenEffectTextureWidth/Height }
404 procedure TexImage2D(const InternalFormat: TGLint;
405 const Format, AType: TGLenum);
406 begin
407 {$ifndef OpenGLES}
408 if (GLFeatures.CurrentMultiSampling > 1) and GLFeatures.FBOMultiSampling then
409 glTexImage2DMultisample(ScreenEffectTextureTarget,
410 GLFeatures.CurrentMultiSampling, InternalFormat,
411 ScreenEffectTextureWidth,
412 ScreenEffectTextureHeight,
413 { fixedsamplelocations = TRUE are necessary in case we use
414 this with cbColor mode, where FBO will also have renderbuffer
415 for depth (and maybe stencil). In this case,
416 https://www.opengl.org/registry/specs/ARB/texture_multisample.txt
417 says that
418
419 if the attached images are a mix of
420 renderbuffers and textures, the value of
421 TEXTURE_FIXED_SAMPLE_LOCATIONS must be TRUE for all attached
422 textures.
423
424 which implies that this parameter must be true.
425 See https://sourceforge.net/p/castle-engine/tickets/22/ . }
426 GL_TRUE) else
427 {$endif}
428 glTexImage2D(ScreenEffectTextureTarget, 0, InternalFormat,
429 ScreenEffectTextureWidth,
430 ScreenEffectTextureHeight, 0, Format, AType, nil);
431 end;
432
433 begin
434 glGenTextures(1, @Result);
435 glBindTexture(ScreenEffectTextureTarget, Result);
436 {$ifndef OpenGLES}
437 { for multisample texture, these cannot be configured (OpenGL makes
438 "invalid enumerant" error) }
439 if ScreenEffectTextureTarget <> GL_TEXTURE_2D_MULTISAMPLE then
440 {$endif}
441 begin
442 { TODO: NEAREST or LINEAR?
443 Allow to config this at each screen effect,
444 and optionally create another version? }
445 SetTextureFilter(ScreenEffectTextureTarget, TextureFilter(minNearest, magNearest));
446 glTexParameteri(ScreenEffectTextureTarget, GL_TEXTURE_WRAP_S, GLFeatures.CLAMP_TO_EDGE);
447 glTexParameteri(ScreenEffectTextureTarget, GL_TEXTURE_WRAP_T, GLFeatures.CLAMP_TO_EDGE);
448 end;
449 if Depth then
450 begin
451 {$ifndef OpenGLES}
452 // TODO-es What do we use here? See TGLRenderToTexture TODO at similar place
453 if GLFeatures.ShadowVolumesPossible and GLFeatures.PackedDepthStencil then
454 TexImage2D(GL_DEPTH24_STENCIL8_EXT, GL_DEPTH_STENCIL_EXT, GL_UNSIGNED_INT_24_8_EXT) else
455 {$endif}
456 TexImage2D(GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT,
457 { On OpenGLES, using GL_UNSIGNED_BYTE will result in FBO failing
458 with INCOMPLETE_ATTACHMENT.
459 http://www.khronos.org/registry/gles/extensions/OES/OES_depth_texture.txt
460 allows only GL_UNSIGNED_SHORT or GL_UNSIGNED_INT for depth textures. }
461 {$ifdef OpenGLES} GL_UNSIGNED_SHORT {$else} GL_UNSIGNED_BYTE {$endif});
462 //glTexParameteri(ScreenEffectTextureTarget, GL_TEXTURE_COMPARE_MODE_ARB, GL_NONE);
463 //glTexParameteri(ScreenEffectTextureTarget, GL_DEPTH_TEXTURE_MODE_ARB, GL_LUMINANCE);
464 end else
465 TexImage2D({$ifdef OpenGLES} GL_RGB {$else} GL_RGB8 {$endif},
466 GL_RGB, GL_UNSIGNED_BYTE);
467
468 TextureMemoryProfiler.Allocate(Result, 'screen-contents', '', { TODO } 0, false,
469 ScreenEffectTextureWidth, ScreenEffectTextureHeight, 1);
470 end;
471
472 procedure BeginRenderingToTexture;
473 begin
474 { We need a temporary texture, for screen effect. }
475 if (ScreenEffectTextureDest = 0) or
476 (ScreenEffectTextureSrc = 0) or
477 (CurrentScreenEffectsNeedDepth <> (ScreenEffectTextureDepth <> 0)) or
478 (ScreenEffectRTT = nil) or
479 (ScreenEffectTextureWidth <> SR.Width ) or
480 (ScreenEffectTextureHeight <> SR.Height) then
481 begin
482 glFreeTexture(ScreenEffectTextureDest);
483 glFreeTexture(ScreenEffectTextureSrc);
484 glFreeTexture(ScreenEffectTextureDepth);
485 FreeAndNil(ScreenEffectRTT);
486
487 {$ifndef OpenGLES}
488 if (GLFeatures.CurrentMultiSampling > 1) and GLFeatures.FBOMultiSampling then
489 ScreenEffectTextureTarget := GL_TEXTURE_2D_MULTISAMPLE else
490 {$endif}
491 ScreenEffectTextureTarget := GL_TEXTURE_2D;
492
493 ScreenEffectTextureWidth := SR.Width;
494 ScreenEffectTextureHeight := SR.Height;
495 { We use two textures: ScreenEffectTextureDest is the destination
496 of framebuffer, ScreenEffectTextureSrc is the source to render.
497
498 Although for some effects one texture (both src and dest) is enough.
499 But when you have > 1 effect and one of the effects has non-local
500 operations (they read color values that can be modified by operations
501 of the same shader, so it's undefined (depends on how shaders are
502 executed in parallel) which one is first) then the artifacts are
503 visible. For example, use castle-model-viewer "Edge Detect" effect +
504 any other effect. }
505 ScreenEffectTextureDest := CreateScreenEffectTexture(false);
506 ScreenEffectTextureSrc := CreateScreenEffectTexture(false);
507 if CurrentScreenEffectsNeedDepth then
508 ScreenEffectTextureDepth := CreateScreenEffectTexture(true);
509
510 { create new TGLRenderToTexture (usually, framebuffer object) }
511 ScreenEffectRTT := TGLRenderToTexture.Create(
512 ScreenEffectTextureWidth, ScreenEffectTextureHeight);
513 ScreenEffectRTT.SetTexture(ScreenEffectTextureDest, ScreenEffectTextureTarget);
514 ScreenEffectRTT.CompleteTextureTarget := ScreenEffectTextureTarget;
515 { use the same multi-sampling strategy as container }
516 ScreenEffectRTT.MultiSampling := GLFeatures.CurrentMultiSampling;
517 if CurrentScreenEffectsNeedDepth then
518 begin
519 ScreenEffectRTT.Buffer := tbColorAndDepth;
520 ScreenEffectRTT.DepthTexture := ScreenEffectTextureDepth;
521 ScreenEffectRTT.DepthTextureTarget := ScreenEffectTextureTarget;
522 end else
523 ScreenEffectRTT.Buffer := tbColor;
524 ScreenEffectRTT.Stencil := GLFeatures.ShadowVolumesPossible;
525 ScreenEffectRTT.GLContextOpen;
526
527 WritelnLog('Screen effects', Format('Created texture for screen effects, with size %d x %d, with depth texture: %s',
528 [ ScreenEffectTextureWidth,
529 ScreenEffectTextureHeight,
530 BoolToStr(CurrentScreenEffectsNeedDepth, true) ]));
531 end;
532
533 RenderContext.Viewport := SR;
534 { Any subquequent changes to RenderContext.Viewport should by shifted,
535 such that point SR.LeftBottom is actually at (0,0). }
536 RenderContext.ViewportDelta := -SR.LeftBottom;
537 { Note: the effective glViewport is now Rectangle(0, 0, SR.Width, SR.Height). }
538
539 ScreenEffectRTT.RenderBegin;
540 ScreenEffectRTT.SetTexture(ScreenEffectTextureDest, ScreenEffectTextureTarget);
541 end;
542
543 begin
544 inherited;
545
546 { Whether we have to render screen effects or not (regular TCastleViewport items),
547 break TDrawableImage batching as we no longer draw only images. }
548 TDrawableImage.BatchingFlush;
549
550 CheckScreenEffects;
551 if RenderScreenEffects then
552 BeginRenderingToTexture;
553 RenderWithoutScreenEffects;
554 end;
555
556 procedure TCastleScreenEffects.RenderWithoutScreenEffects;
557 begin
558 end;
559
560 procedure TCastleScreenEffects.RenderOverChildren;
561 var
562 SR: TRectangle;
563
564 procedure RenderWithScreenEffectsCore;
565
566 procedure RenderOneEffect(Shader: TGLSLProgram);
567 var
568 BoundTextureUnits: Cardinal;
569 AttribVertex, AttribTexCoord: TGLSLAttribute;
570 begin
571 if ScreenPointVbo = 0 then
572 begin
573 { generate and fill ScreenPointVbo. It's contents are constant. }
574 glGenBuffers(1, @ScreenPointVbo);
575 ScreenPoint[0].TexCoord := Vector2(0, 0);
576 ScreenPoint[0].Position := Vector2(-1, -1);
577 ScreenPoint[1].TexCoord := Vector2(1, 0);
578 ScreenPoint[1].Position := Vector2( 1, -1);
579 ScreenPoint[2].TexCoord := Vector2(1, 1);
580 ScreenPoint[2].Position := Vector2( 1, 1);
581 ScreenPoint[3].TexCoord := Vector2(0, 1);
582 ScreenPoint[3].Position := Vector2(-1, 1);
583 RenderContext.BindBuffer[btArray] := ScreenPointVbo;
584 glBufferData(GL_ARRAY_BUFFER, SizeOf(ScreenPoint), @(ScreenPoint[0]), GL_STATIC_DRAW);
585 end;
586
587 if ScreenPointVao = nil then
588 ScreenPointVao := TVertexArrayObject.Create(nil);
589
590 RenderContext.CurrentProgram := Shader;
591 RenderContext.CurrentVao := ScreenPointVao;
592
593 RenderContext.BindBuffer[btArray] := ScreenPointVbo;
594
595 glActiveTexture(GL_TEXTURE0); // GLFeatures.UseMultiTexturing is already checked
596 glBindTexture(ScreenEffectTextureTarget, ScreenEffectTextureSrc);
597 BoundTextureUnits := 1;
598
599 if CurrentScreenEffectsNeedDepth then
600 begin
601 glActiveTexture(GL_TEXTURE1);
602 glBindTexture(ScreenEffectTextureTarget, ScreenEffectTextureDepth);
603 Inc(BoundTextureUnits);
604 end;
605
606 Shader.Uniform('screen').SetValue(0);
607 if CurrentScreenEffectsNeedDepth then
608 Shader.Uniform('screen_depth').SetValue(1);
609 Shader.Uniform('screen_width').SetValue(TGLint(ScreenEffectTextureWidth));
610 Shader.Uniform('screen_height').SetValue(TGLint(ScreenEffectTextureHeight));
611
612 { Note that we ignore SetupUniforms result --- if some texture
613 could not be bound, it will be undefined for shader.
614 I don't see anything much better to do now. }
615 Shader.SetupUniforms(BoundTextureUnits);
616
617 { Note that there's no need to worry about Rect.Left or Rect.Bottom,
618 here or inside RenderWithScreenEffectsCore, because we're already within
619 RenderContext.Viewport that takes care of this. }
620
621 AttribVertex := Shader.Attribute('vertex');
622 AttribVertex.EnableArrayVector2(ScreenPointVao, SizeOf(TScreenPoint),
623 OffsetUInt(ScreenPoint[0].Position, ScreenPoint[0]));
624 AttribTexCoord := Shader.Attribute('tex_coord');
625 AttribTexCoord.EnableArrayVector2(ScreenPointVao, SizeOf(TScreenPoint),
626 OffsetUInt(ScreenPoint[0].TexCoord, ScreenPoint[0]));
627
628 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
629
630 AttribVertex.DisableArray;
631 AttribTexCoord.DisableArray;
632 RenderContext.BindBuffer[btArray] := 0;
633 end;
634
635 var
636 I: Integer;
637 begin
638 { Render all except the last screen effects: from texture
639 (ScreenEffectTextureDest/Src) and to texture (using ScreenEffectRTT) }
640
641 { The effective glViewport should be now Rectangle(0, 0, SR.Width, SR.Height).
642 Although our "Render" implementation already set it
643 (somewhat indirectly, using ViewportDelta),
644 but something since then could have changed the Viewport
645 (e.g. ControlRenderBegin done right before C.RenderOverChildren in CastleGLContainer).
646 So set it as we need, again.
647 And this time we don't need to deal with ViewportDelta, just zero it. }
648 RenderContext.ViewportDelta := TVector2Integer.Zero;
649 RenderContext.Viewport := Rectangle(0, 0, SR.Width, SR.Height);
650
651 for I := 0 to CurrentScreenEffectsCount - 2 do
652 begin
653 ScreenEffectRTT.RenderBegin;
654 ScreenEffectRTT.SetTexture(ScreenEffectTextureDest, ScreenEffectTextureTarget);
655 RenderOneEffect(GetScreenEffect(I));
656 ScreenEffectRTT.RenderEnd;
657
658 SwapValues(ScreenEffectTextureDest, ScreenEffectTextureSrc);
659 end;
660
661 { the last effect gets a texture, and renders straight into screen }
662 RenderContext.ViewportDelta := TVector2Integer.Zero;
663 RenderContext.Viewport := RenderRect.Round;
664 RenderOneEffect(GetScreenEffect(CurrentScreenEffectsCount - 1));
665 end;
666
667 procedure EndRenderingToTexture;
668 begin
669 SR := RenderRect.Round;
670
671 ScreenEffectRTT.RenderEnd;
672
673 SwapValues(ScreenEffectTextureDest, ScreenEffectTextureSrc);
674
675 OrthoProjection(FloatRectangle(0, 0, SR.Width, SR.Height));
676 RenderWithScreenEffectsCore;
677 end;
678
679 begin
680 inherited;
681 if RenderScreenEffects then
682 EndRenderingToTexture;
683 end;
684
685 procedure TCastleScreenEffects.Update(const SecondsPassed: Single; var HandleInput: boolean);
686 var
687 RemoveItem: TRemoveType;
688 begin
689 inherited;
690 if (ScreenEffectsScene <> nil) and ScreenEffectsEnable then
691 begin
692 RemoveItem := rtNone;
693 ScreenEffectsScene.Update(SecondsPassed * ScreenEffectsTimeScale, RemoveItem);
694 { We ignore RemoveItem --- ScreenEffectsScene cannot be removed.
695 Also, this is always TCastleScene that should not change RemoveItem ever. }
696 end;
697 end;
698
699 procedure TCastleScreenEffects.PrepareResources;
700 begin
701 if ScreenEffectsScene <> nil then
702 begin
703 {$warnings off} // using deprecated, this should be internal
704 ScreenEffectsScene.PrepareResources([prScreenEffects], FPrepareParams);
705 {$warnings on}
706 end;
707 end;
708
709 procedure TCastleScreenEffects.BeforeRender;
710 begin
711 inherited;
712 PrepareResources;
713 end;
714
715 procedure TCastleScreenEffects.GLContextClose;
716 begin
717 glFreeTexture(ScreenEffectTextureDest);
718 glFreeTexture(ScreenEffectTextureSrc);
719 glFreeTexture(ScreenEffectTextureDepth);
720 ScreenEffectTextureTarget := 0; //< clear, for safety
721 FreeAndNil(ScreenEffectRTT);
722 glFreeBuffer(ScreenPointVbo);
723 FreeAndNil(ScreenPointVao);
724 inherited;
725 end;
726
727 end.