Render Pass Controller

Render Pass Controllers in Gorilla3D enable multi-pass rendering techniques by allowing you to execute custom rendering stages before, after, or during the main rendering loop. They are essential for implementing advanced effects like reflections, refractions, depth passes, post-processing, and custom shaders.

Overview

A render pass controller (TGorillaRenderPassController) manages a separate rendering stage with its own:

  • Frame Buffer Object (FBO) - Output texture
  • Renderer - Independent rendering pipeline
  • Viewport Configuration - Custom size and scaling
  • Control Filtering - Selective object rendering
  • Shader Material - Custom shader effects

Common applications include:

  • Water reflections and refractions
  • Shadow mapping
  • Screen space effects
  • Post-processing filters
  • Environment mapping
  • Depth passes

Render Pass Types

Render passes execute at different stages of the rendering pipeline:

Pre-Pass (TRenderPassType.Pre)

Executes before the main rendering loop.

Use Cases:

  • Shadow map generation
  • Reflection captures
  • Refraction captures
  • Depth pre-passes
  • Environment mapping

Example:

ReflectionPass := TGorillaRenderPassReflection.Create(Self);
ReflectionPass._Type := TRenderPassType.Pre;  // Executes before main scene

Post-Pass (TRenderPassType.Post)

Executes after the main rendering loop.

Use Cases:

  • Post-processing effects (blur, bloom, FXAA)
  • Color grading
  • Screen space effects (SSAO, SSS)
  • Tone mapping
  • Composite operations

Example:

BlurPass := TGorillaRenderPassCustomBlur.Create(Self);
BlurPass._Type := TRenderPassType.Post;  // Executes after main scene

Intermediate Pass (TRenderPassType.Intermediate)

Executes during the main rendering loop.

Use Cases:

  • Special rendering modes
  • Layer-based rendering
  • Multi-stage effects

Example:

CustomPass := TMyCustomRenderPass.Create(Self);
CustomPass._Type := TRenderPassType.Intermediate;

Render Methods

RenderListToFBO

Renders all 3D objects from the scene to the render pass FBO.

Behavior:

  • Iterates through viewport's 3D controls
  • Respects AllowedControls and IgnoredControls
  • Uses render pass's custom camera/projection matrices
  • Outputs to FBO texture

Use Cases:

  • Reflection/refraction passes
  • Shadow mapping
  • Environment captures
  • Depth rendering

Example:

DepthPass.Method := TRenderPassMethod.RenderListToFBO;

RectToFBO

Renders a fullscreen quad with a shader material to the FBO.

Behavior:

  • Renders single rectangle covering viewport
  • Applies assigned shader material
  • No 3D object iteration
  • Used for screen-space effects

Use Cases:

  • Post-processing (blur, sharpen, color correction)
  • Compositing operations
  • Screen space effects
  • Texture filtering

Example:

BlurPass.Method := TRenderPassMethod.RectToFBO;
BlurPass.Shader := BlurShaderMaterial;

Render Procedures

The RenderProc property controls how objects are rendered within a pass:

DefaultRendering

Uses complete WBOIT (Weighted Blended Order Independent Transparency) pipeline:

  • Separate opaque and translucent passes
  • Order-independent transparency
  • Correct blending results

Use When:

  • Need accurate transparency
  • Rendering complex scenes with mixed opaque/translucent objects
  • Quality is priority

Example:

ReflectionPass.RenderProc := TRenderPassRenderingProc.DefaultRendering;

ListRendering

Renders all objects straight forward without separation:

  • Single pass for all objects
  • Ignores transparency order
  • No translucent/opaque distinction
  • Faster but less accurate

Use When:

  • Rendering only opaque objects (depth pass, shadow mapping)
  • Performance is critical
  • Transparency doesn't matter for the pass

Example:

DepthPass.RenderProc := TRenderPassRenderingProc.ListRendering;

Basic Configuration

Linking to Viewport

Every render pass must be linked to a viewport:

var
  ReflectionPass: TGorillaRenderPassReflection;
begin
  ReflectionPass := TGorillaRenderPassReflection.Create(Self);
  ReflectionPass.Viewport := GorillaViewport1;

  // Rest of configuration...
end;

Unique ID

Each render pass requires a unique identifier:

// Automatically set from component name at design-time
ReflectionPass.Name := 'ReflectionPass1';  // ID = 'ReflectionPass1'

// Or set manually
ReflectionPass.Id := 'WaterReflection';

Important: Duplicate IDs will cause conflicts. The new pass overwrites the existing one.


Basic Properties

// Enable/disable pass
ReflectionPass.Enabled := True;

// Set rendering type
ReflectionPass._Type := TRenderPassType.Pre;

// Set rendering method
ReflectionPass.Method := TRenderPassMethod.RenderListToFBO;

// Set rendering procedure
ReflectionPass.RenderProc := TRenderPassRenderingProc.DefaultRendering;

// Number of times to execute per frame
ReflectionPass.Iterations := 1;  // Useful for ping-pong effects

Viewport Size Configuration

Render passes can use custom viewport sizes different from the main viewport.

Using Main Viewport Size

ReflectionPass.OverwriteViewportSize := False;  // Use main viewport dimensions

The pass then renders in the render target size of the viewport (TGorillaViewport.GetRenderTargetSize()), which already contains HighRes, RenderScale and a fixed RenderWidth / RenderHeight - see Render Resolution and Scaling.


Custom Fixed Size

ReflectionPass.OverwriteViewportSize := True;
ReflectionPass.ViewportWidth := 1024;
ReflectionPass.ViewportHeight := 1024;

Use Cases:

  • Shadow mapping (fixed resolution shadow maps)
  • Texture atlases
  • Performance optimization (lower resolution passes)

Scaled Size

ReflectionPass.OverwriteViewportSize := True;
ReflectionPass.ViewportWidth := 1024;
ReflectionPass.ViewportHeight := 1024;
ReflectionPass.ScaleViewportSize := True;
ReflectionPass.ViewportScale := 0.5;  // Results in 512x512

Note: ScaleViewportSize only works together with OverwriteViewportSize = True. Without an individual size the pass always renders in the render target size of the viewport, which already contains its scaling. To lower the resolution of the main pass and all such passes together, use Viewport.RenderScale.

Use Cases:

  • Performance optimization
  • Blur passes (often done at lower res)
  • Mobile platforms

Combining Custom Size and Scale

ReflectionPass.OverwriteViewportSize := True;
ReflectionPass.ViewportWidth := 512;
ReflectionPass.ViewportHeight := 512;
ReflectionPass.ScaleViewportSize := True;
ReflectionPass.ViewportScale := 2.0;  // Results in 1024x1024

Control Filtering

Control filtering allows selective rendering of scene objects in a render pass.

Ignoring Controls

Exclude specific objects from rendering:

// Exclude water plane from reflection pass
ReflectionPass.IgnoreControl(WaterPlane);

// Exclude multiple objects
ReflectionPass.IgnoreControl(WaterPlane);
ReflectionPass.IgnoreControl(UnderwaterRocks);
ReflectionPass.IgnoreControl(Seaweed);

Automatic Child Handling:

  • Sub-meshes are automatically ignored
  • Child components are automatically ignored

Design-Time Configuration:

// Via IgnoredControls collection in Object Inspector
ReflectionPass.IgnoredControls.Add();
// Then set Control property to desired object

Allowing Specific Controls

Create an explicit allow-list for rendering:

// Only render specific objects
ReflectionPass.AllowControl(Sky);
ReflectionPass.AllowControl(Mountains);
ReflectionPass.AllowControl(Trees);

// Everything else is ignored

Behavior:

  • If AllowedControls is empty: All objects render except those in IgnoredControls
  • If AllowedControls is not empty: Only allowed objects render, then IgnoredControls is checked against them

Example Scenario:

// Allow terrain and props
BackfacePass.AllowControl(Terrain);
BackfacePass.AllowControl(Props);

// But ignore specific prop
BackfacePass.IgnoreControl(TransparentWindow);  // Excluded from allowed props

Checking If Control Is Ignored

if ReflectionPass.IsControlIgnored(WaterPlane) then
  ShowMessage('Water plane will not be rendered in reflection');

Background Color

Using Viewport Color

ReflectionPass.OverwriteColor := False;  // Use viewport's background color

Custom Background Color

ReflectionPass.OverwriteColor := True;
ReflectionPass.BackgroundColor := TAlphaColorRec.Skyblue;

Use Cases:

  • Reflection passes with different sky colors
  • Green-screen style effects
  • Debug visualization

Pass Chaining

Link multiple passes together by feeding one pass's output into another:

var
  Pass1, Pass2: TGorillaRenderPassController;
begin
  // Pass2 uses Pass1's output as input
  Pass2.SetInputPass(Pass1);

  // Or check current input
  var InputPass := Pass2.GetInputPass();
end;

Common Pattern - Blur Ping-Pong:

// Horizontal blur
BlurH.SetInputPass(SourcePass);

// Vertical blur uses horizontal output
BlurV.SetInputPass(BlurH);

// Final composite uses vertical output
FinalPass.SetInputPass(BlurV);

Events and Callbacks

Render passes provide events for custom logic at various stages:

OnBeginSetup

Called once per frame before pass setup begins:

procedure TForm1.OnReflectionBeginSetup(ASender: TObject;
  const AContext: TContext3D; const ACount: Integer; const APass: TRenderPass);
begin
  // Prepare pass-specific data
  // Update matrices
  // Configure camera
end;

ReflectionPass.OnBeginSetup := OnReflectionBeginSetup;

OnEndSetup

Called once per frame after pass setup completes:

procedure TForm1.OnReflectionEndSetup(ASender: TObject;
  const AContext: TContext3D; const ACount: Integer; const APass: TRenderPass);
begin
  // Cleanup
  // Reset states
end;

ReflectionPass.OnEndSetup := OnReflectionEndSetup;

OnBeginRender

Called before each iteration renders:

procedure TForm1.OnBlurBeginRender(ASender: TObject;
  const AContext: TContext3D; const ACount: Integer; const APass: TRenderPass);
begin
  // ACount indicates current iteration (0-based)
  // Configure iteration-specific parameters
end;

BlurPass.OnBeginRender := OnBlurBeginRender;
BlurPass.Iterations := 3;  // OnBeginRender called 3 times

OnEndRender

Called after each iteration completes:

procedure TForm1.OnBlurEndRender(ASender: TObject;
  const AContext: TContext3D; const ACount: Integer; const APass: TRenderPass);
begin
  // Post-iteration cleanup
  // Swap ping-pong buffers
end;

BlurPass.OnEndRender := OnBlurEndRender;

Accessing Output Texture

Get the render pass's output texture for use in materials or other passes:

var
  OutputTex: TTexture;
begin
  OutputTex := ReflectionPass.OutputTexture;

  // Use in material
  CustomPlaneMaterial.Texture := OutputTex;
end;

Built-In Render Passes

Gorilla3D includes several ready-to-use render pass implementations:

TGorillaRenderPassReflection

Renders reflected scene for water and mirror surfaces.

Features:

  • Mirrored camera matrix
  • Configurable mirror plane
  • Automatic control exclusion

Example:

var
  ReflectionPass: TGorillaRenderPassReflection;
begin
  ReflectionPass := TGorillaRenderPassReflection.Create(Self);
  ReflectionPass.Viewport := Viewport;
  ReflectionPass.Camera := Camera;

  // Configure mirror plane (Y=0 plane for water)
  ReflectionPass.MirrorPosition.Point := Point3D(0, 0, 0);
  ReflectionPass.MirrorNormal.Point := Point3D(0, -1, 0);
  ReflectionPass.MirrorSize := 100.0;

  // Exclude water from rendering
  ReflectionPass.IgnoreControl(WaterPlane);
end;

→ API reference: TGorillaRenderPassReflection


TGorillaRenderPassRefraction

Renders refracted (underwater) scene for water surfaces.

Features:

  • Normal camera view
  • Depth information output
  • Configurable surface plane

Example:

var
  RefractionPass: TGorillaRenderPassRefraction;
begin
  RefractionPass := TGorillaRenderPassRefraction.Create(Self);
  RefractionPass.Viewport := Viewport;

  // Configure water surface
  RefractionPass.SurfacePosition.Point := Point3D(0, 0, 0);
  RefractionPass.SurfaceNormal.Point := Point3D(0, 1, 0);

  // Exclude water from rendering
  RefractionPass.IgnoreControl(WaterPlane);
end;

→ API reference: TGorillaRenderPassRefraction


TGorillaRenderPassCustomDepth

Renders scene depth to texture for shadow mapping or depth effects.

Features:

  • Depth-only rendering
  • Configurable depth range
  • Optimized for shadow mapping

Example:

var
  DepthPass: TGorillaRenderPassCustomDepth;
begin
  DepthPass := TGorillaRenderPassCustomDepth.Create(Self);
  DepthPass.Viewport := Viewport;
  DepthPass.RenderProc := TRenderPassRenderingProc.ListRendering;  // Faster

  // Custom resolution for shadow map
  DepthPass.OverwriteViewportSize := True;
  DepthPass.ViewportWidth := 2048;
  DepthPass.ViewportHeight := 2048;
end;

→ API reference: TGorillaRenderPassCustomDepth


TGorillaRenderPassCascadedShadows

The modern Cascaded Shadow Maps (CSM) system for directional, spot and point lights. It is an internal pass driven by the viewport — you do not create it manually. Enable and configure it through Viewport.Shadows (a TGorillaShadowSystemSettings instance), then flag the casting lights.

Example:

// Enable and tune the shadow system
GorillaViewport1.Shadows.Enabled         := True;
GorillaViewport1.Shadows.CascadeCount    := 4;
GorillaViewport1.Shadows.MapResolution   := 2048;
GorillaViewport1.Shadows.MaxDirLights    := 1;
GorillaViewport1.Shadows.Filter          := TGorillaShadowFilter.PCF3;
GorillaViewport1.Shadows.Strength        := 1.0;    // global shadow darkness [0..1]
GorillaViewport1.Shadows.AutoFitCascades := True;   // fit cascades to scene geometry

// Mark which lights cast shadows
MyDirLight.CastShadow := True;

→ API reference: TGorillaRenderPassCascadedShadows


TGorillaRenderPassCustomBlur

Applies Gaussian blur to input texture.

Features:

  • Horizontal/vertical separation
  • Configurable blur radius
  • Ping-pong iterations

Example:

var
  BlurPass: TGorillaRenderPassCustomBlur;
begin
  BlurPass := TGorillaRenderPassCustomBlur.Create(Self);
  BlurPass.Viewport := Viewport;
  BlurPass.Method := TRenderPassMethod.RectToFBO;

  // Configure blur
  BlurPass.BlurRadius := 5.0;
  BlurPass.Iterations := 2;  // Blur twice

  // Input from previous pass
  BlurPass.SetInputPass(SourcePass);
end;

→ API reference: TGorillaRenderPassBlur (CustomBlur)


TGorillaRenderPassFXAA

Fast approximate anti-aliasing post-process.

Example:

var
  FXAAPass: TGorillaRenderPassFXAA;
begin
  FXAAPass := TGorillaRenderPassFXAA.Create(Self);
  FXAAPass.Viewport := Viewport;
  FXAAPass._Type := TRenderPassType.Post;
  FXAAPass.Method := TRenderPassMethod.RectToFBO;
end;

→ API reference: TGorillaRenderPassFXAA


TGorillaRenderPassEnvironment

Captures the scene into a dynamic cube map for environment mapping and reflections.

Features:

  • Six-face cube map capture from a configurable point
  • Static or dynamic (per-frame) refresh
  • Optional embedded light, per-face center offsets

Example:

var
  EnvPass: TGorillaRenderPassEnvironment;
begin
  EnvPass := TGorillaRenderPassEnvironment.Create(Self);
  EnvPass.Viewport := Viewport;
  EnvPass.Position := Point3D(0, 2, 0);
  EnvPass.MapSize := 256;
  EnvPass.IsDynamic := True;
  EnvPass.IgnoreControl(ReflectiveObject);
end;

→ API reference: TGorillaRenderPassEnvironment


TGorillaRenderPassFace

Renders front- or back-face vertex positions into a float texture — the entry/exit geometry for ray-cast volumetric rendering.

Features:

  • Front-/back-face selection
  • Selectable output coordinate space (model / view / view-proj / depth)
  • Custom vertex code via VertexUserFunc

Example:

var
  FacePass: TGorillaRenderPassFace;
begin
  FacePass := TGorillaRenderPassFace.Create(Self);
  FacePass.Viewport := Viewport;
  FacePass.FaceKind := FrontFace;
  FacePass.FaceOutput := ModelSpace;
end;

→ API reference: TGorillaRenderPassFace


TGorillaRenderPassUnderwater

Full-screen underwater post effect: distortion, depth fog, caustics, fisheye and vignette that fade in below a water surface.

Features:

  • Smooth fade around the water surface height
  • Animated distortion and caustics
  • Depth-based color absorption / tint

Example:

var
  UnderwaterPass: TGorillaRenderPassUnderwater;
begin
  UnderwaterPass := TGorillaRenderPassUnderwater.Create(Self);
  UnderwaterPass.Viewport := Viewport;
  UnderwaterPass._Type := TRenderPassType.Post;
  UnderwaterPass.SurfaceHeight := 0.0;
  UnderwaterPass.TintColor := $FF14506E;
end;

→ API reference: TGorillaRenderPassUnderwater

Advanced Techniques

Conditional Pass Execution

Skip rendering a pass for specific frames:

procedure TForm1.OnTimer(Sender: TObject);
begin
  // Only update reflection every 3rd frame for performance
  if (FrameCount mod 3) <> 0 then
    ReflectionPass.SkipRendering();
end;

Dynamic Resolution Scaling

Adjust pass resolution based on performance:

procedure TForm1.AdjustPassQuality(AFPS: Single);
begin
  if AFPS < 30 then
  begin
    // Reduce reflection resolution (needs an individual pass size)
    ReflectionPass.OverwriteViewportSize := True;
    ReflectionPass.ViewportWidth := 1024;
    ReflectionPass.ViewportHeight := 1024;
    ReflectionPass.ScaleViewportSize := True;
    ReflectionPass.ViewportScale := 0.5;
  end
  else if AFPS > 55 then
  begin
    // Restore full resolution
    ReflectionPass.ScaleViewportSize := False;
  end;
end;

Create Your Own Render Pass

Gorilla3D allows to write your own render pass controllers. The base classes for implementation are TGorillaRenderPassController, TGorillaRenderPassMaterial and TGorillaRenderPassMaterialSource.

It is important to define what the render pass is intended to do:

  • Render all elements with the same material
  • Render all elements with their original material
  • Render once with a render material

Render All Elements With The Same Material

unit MyDepthRenderPass;

interface

uses
  System.Classes,
  System.Types,
  System.UITypes,
  System.SysUtils,
  System.Generics.Collections,
  System.Math.Vectors,
  FMX.Types,
  FMX.Types3D,
  FMX.Controls3D,
  FMX.Materials,
  FMX.MaterialSources,
  Gorilla.Context.Texturing,
  Gorilla.Context.Rendering,
  Gorilla.Controller;

type
  TMyDepthMaterialSource = class;

  TMyDepthMaterial = class(TGorillaRenderPassMaterial)
    protected
      FVertexShaderMVZ : TContextShader;
      FPixelShaderZ    : TContextShader;

      procedure DoApply(const Context: TContext3D); override;
      procedure DoInitialize(); override;

    public
      constructor Create(ASource : TCustomDepthMaterialSource); reintroduce; virtual;
      destructor Destroy(); override;
  end;

  TMyDepthMaterialSource = class(TGorillaRenderPassMaterialSource)
    protected
      function CreateMaterial() : TMaterial; override;
      procedure DoPassesChanged(Sender: TObject); override;

    public
      constructor Create(AOwnerPass : TGorillaRenderPassController); override;
      destructor Destroy(); override;
  end;

  TMyDepthRenderPass = class(TGorillaRenderPassController)
    protected
      FDefaultColor : TAlphaColor;
      FDefaultDepth : Single;

      function CreateMaterialSource() : TGorillaRenderPassMaterialSource; override;

      function GetMapSize() : TPoint;
      procedure SetMapSize(AValue : TPoint);

      procedure DoConfigure(); override;
      procedure DoCreateRenderer(); override;
      procedure DoOnCreateCompositeTexture(
        ASender : TObject; const ASize : TPoint; const AScale : Single;
        out ATexture : TGorillaTextureBitmap); override;
      procedure DoOnBeginRenderPassSetup(const ACount : Integer;
        const APass : TRenderPass); override;
      procedure DoOnEndRenderPassSetup(const ACount : Integer;
        const APass : TRenderPass); override;

      procedure DoSetupTexturesByViewport(const AContext : TContext3D;
        const AWidth, AHeight : Integer); override;

    public
      property MapSize : TPoint read GetMapSize write SetMapSize;
      property BiasMatrix : TMatrix3D read FBiasMatrix;
      property DefaultDepth : Single read FDefaultDepth write FDefaultDepth;

      constructor Create(AOwner : TComponent;
        const AId : String = 'MyDepth'); reintroduce; virtual;
      destructor Destroy(); override;

      function GetViewMatrix(const AContext : TContext3D) : TMatrix3D; override;
      function GetProjectionMatrix(const AContext : TContext3D) : TMatrix3D; override;
      procedure SetupMatrices(const AContext : TContext3D); virtual;

      function GetOutputTexture() : TTexture; override;
      function GetTextureMatrix(AContext : TContext3D;
        const AUseBias : Boolean = true) : TMatrix3D; override;
  end;

implementation

uses
  System.Math,
  System.IOUtils,
  Gorilla.Context.Buffers,
  Gorilla.Context,
  Gorilla.Renderer;

  {$I ..\..\instance\material\glsl\Gorilla.GLSL.Common.inc}

  ResourceString GORILLA_MYDEPTH_VS =
    'in vec3 a_Position;'#13#10 +
    'uniform mat4 _ModelViewProjMatrix;'#13#10 +
    'void main(){'#13#10 +
    '  vec4 fvPosition = vec4(a_Position.x, a_Position.y, a_Position.z, 1.0);'#13#10 +
    '  gl_Position = _ModelViewProjMatrix * fvPosition;'#13#10 +
    '}';

  ResourceString GORILLA_MYDEPTH_FS =
    'layout (location = 0) out float o_FragColor;'#13#10 +

    'void main(){'#13#10 +
    '  o_FragColor = gl_FragCoord.z;'#13#10 +
    '}';

{ TMyDepthMaterial }

constructor TMyDepthMaterial.Create(ASource : TMyDepthMaterialSource);
begin
  inherited Create(ASource);
end;

destructor TMyDepthMaterial.Destroy();
begin
  inherited;
end;

procedure TMyDepthMaterial.DoInitialize();
var LOGLBytes : TArray<Byte>;
begin
  Inc(FShaderUpdateCounter);

  ///
  /// VertexShader
  ///
  /// The shader stores the simple gl_FragCoord.z value
  LOGLBytes := TEncoding.ASCII.GetBytes(GORILLA_SHADER_VERSION + GORILLA_MYDEPTH_VS);
  FVertexShader := TShaderManager.RegisterShaderFromData(
    Format('MyDepth-%x-%x.fvs', [NativeUInt(Self), FShaderUpdateCounter]),
    TContextShaderKind.VertexShader, '', [
      TContextShaderSource.Create(TContextShaderArch.GLSL,
        LOGLBytes,
        [
        TContextShaderVariable.Create('ModelViewProjMatrix', TContextShaderVariableKind.Matrix, 0, 4)
        ]
      )
    ]);

  ///
  /// PixelShader / FragmentShader
  ///
  LOGLBytes := TEncoding.ASCII.GetBytes(GORILLA_SHADER_VERSION + GORILLA_MYDEPTH_FS);
  FPixelShader := TShaderManager.RegisterShaderFromData(
    Format('MyDepth-%x-%x.fps', [NativeUInt(Self), FShaderUpdateCounter]),
    TContextShaderKind.PixelShader, '', [
      TContextShaderSource.Create(TContextShaderArch.GLSL,
        LOGLBytes,
        []
      )
    ]);
end;

procedure TMyDepthMaterial.DoApply(const Context: TContext3D);
var LEyeMatrix : TMatrix3D;
    LCtx : TGorillaContext;
begin
  // Set shaders
  Context.SetShaders(FVertexShader, FPixelShader);

  if not (Context is TGorillaContext) then
    Exit;

  LCtx := TGorillaContext(Context);
  LCtx.SetContextStates([TContextState.csFrontFace, TContextState.csZTestOn,
    TContextState.csZWriteOn]);

  LEyeMatrix := FSource.OwnerPass.GetCurrentModelViewProjectionMatrix();
  LCtx.SetShaderVariable('ModelViewProjMatrix', LEyeMatrix, true);
end;

{ TMyDepthMaterialSource }

constructor TMyDepthMaterialSource.Create(AOwnerPass : TGorillaRenderPassController);
begin
  inherited Create(AOwnerPass);
end;

destructor TMyDepthMaterialSource.Destroy();
begin
  inherited;
end;

function TMyDepthMaterialSource.CreateMaterial() : TMaterial;
begin
  FHasMaterial := true;
  Result := TMyDepthMaterial.Create(Self);
end;

procedure TCustomDepthMaterialSource.DoPassesChanged(Sender: TObject);
begin
  // do nothing
end;

{ TGorillaMyDepthRenderPass }

constructor TGorillaMyDepthRenderPass.Create(AOwner : TComponent;
  const AId : String = 'MyDepth');
begin
  inherited Create(AOwner, AId);
end;

destructor TGorillaMyDepthRenderPass.Destroy();
begin
  FreeAndNil(FShader);

  inherited;
end;

procedure TGorillaMyDepthRenderPass.DoConfigure();
begin
  inherited;

  // Depth pass rendering should be done before main pass
  FType := TRenderPassType.Pre;
  // We want all objects to be rendered individually
  FMethod := TRenderPassMethod.RenderListToFBO;

  // Because transparency is not important for depth pass rendering
  // we can switch to simple list rendering
  FRenderProc := TRenderPassRenderingProc.ListRendering;

  FRendererFlags := [TRendererFlag.IgnoreRenderTargets,
    TRendererFlag.IgnoreCompositeCtrl, TRendererFlag.IgnoreEmissiveBlur,
    TRendererFlag.IgnoreGlobalIllum, TRendererFlag.IgnoreSSS, 
    TRendererFlag.IgnoreSSAO];

  FRecalcProjMatrix := true;
  FRecalcViewMatrix := true;

  // optionally reduce the size of rendering
//  FOverwriteViewportSize := true;
//  FViewportSize := Point(1024, 1024);

  FDefaultColor := TAlphaColorRec.Black;
  FDefaultDepth := 1;

  FShader := CreateMaterialSource();
  FShader.Stored := false;
end;

function TGorillaMyDepthRenderPass.CreateMaterialSource() : TGorillaRenderPassMaterialSource;
begin
  result := TMyDepthMaterialSource.Create(Self);
end;

function TGorillaMyDepthRenderPass.GetMapSize() : TPoint;
begin
  Result := ViewportSize;
end;

procedure TGorillaMyDepthRenderPass.SetMapSize(AValue : TPoint);
begin
  ViewportSize := AValue;
  FRecalcProjMatrix := true;
end;

procedure TGorillaMyDepthRenderPass.DoSetupTexturesByViewport(
  const AContext : TContext3D; const AWidth, AHeight : Integer);
begin
  inherited;
end;

function TGorillaMyDepthRenderPass.GetOutputTexture() : TTexture;
begin
  Result := inherited;
end;

function TGorillaMyDepthRenderPass.GetTextureMatrix(AContext : TContext3D;
  const AUseBias : Boolean = true) : TMatrix3D;
begin
  Result := inherited;
end;

function TGorillaMyDepthRenderPass.GetViewMatrix(const AContext : TContext3D) : TMatrix3D;
begin
  Result := inherited GetViewMatrix(AContext);
end;

function TGorillaMyDepthRenderPass.GetProjectionMatrix(const AContext : TContext3D) : TMatrix3D;
begin
  Result := inherited GetProjectionMatrix(AContext);
end;

procedure TGorillaMyDepthRenderPass.SetupMatrices(const AContext : TContext3D);
var LViewMat,
    LProjMat : TMatrix3D;
begin
  LViewMat := GetViewMatrix(AContext);
  LProjMat := GetProjectionMatrix(AContext);
  FTextureMatrix := LViewMat * LProjMat;

  AContext.SetCameraMatrix(LViewMat);
  AContext.SetCameraAngleOfView(Viewport.CurrentCamera.AngleOfView);
end;

procedure TGorillaMyDepthRenderPass.DoCreateRenderer();
begin
  inherited;

  if Assigned(FRenderer) then
    FRenderer.RenderTargets := [TRenderTarget.Color_0];
end;

procedure TGorillaMyDepthRenderPass.DoOnCreateCompositeTexture(
  ASender : TObject; const ASize : TPoint; const AScale : Single;
  out ATexture : TGorillaTextureBitmap);
var LTexRef : TTexture;
begin
  // For depth we need at least 16 bit per channel, so we need to create a different
  // texture than the default one
  /// create fullscreen context rendering texture
  /// this is a composition texture for WBOIT forward rendering OR deferred rendering
  ATexture := TGorillaTextureBitmap.Create();
  ATexture.BeginSetup();
  try
    ATexture.Style := [TTextureStyle.RenderTarget];
    ATexture.SetSize(ASize.X, ASize.Y);
    ATexture.BitmapScale := AScale;

    ATexture.DataType := TGorillaTextureDataType.dtHalfFloat;
    ATexture.Components := TPixelFormatEx.R16F;
//    ATexture.DataType := TGorillaTextureDataType.dtFloat;
//    ATexture.Components := TPixelFormatEx.R32F;
    ATexture.Format := TPixelFormatEx.R;
    ATexture.MinFilter := TTextureFilter.Linear;
    ATexture.MagFilter := TTextureFilter.Linear;
    ATexture.WrapS := TGorillaTextureWrap.ClampToBorder;
    ATexture.WrapT := TGorillaTextureWrap.ClampToBorder;
    ATexture.BorderColor := TAlphaColorF.Create(1, 1, 1, 1);
  finally
    ATexture.EndSetup();
  end;

  // Return a texture reference and set scaling
  LTexRef := ATexture.Texture;
  ITextureAccess(LTexRef).TextureScale := AScale;
end;

procedure TGorillaMyDepthRenderPass.DoOnBeginRenderPassSetup(
  const ACount : Integer; const APass : TRenderPass);
var LCtx : TGorillaContext;
begin
  inherited;

  if not (Assigned(FRenderer) and Assigned(FRenderer.SharedContext)) then
    Exit;

  if not (FRenderer.SharedContext is TGorillaContext) then
    Exit;

  LCtx := TGorillaContext(Renderer.SharedContext);

  LCtx.SetContextStates([TContextState.csZWriteOn, TContextState.csZTestOn,
    TContextState.csFrontFace]);

  LCtx.ClearEx([TRenderTarget.Color_0, TRenderTarget.Depth],
    FDefaultColor, FDefaultDepth, 0);
  LCtx.DefaultFrameBuf.Prepare([TRenderTarget.Color_0]);

  SetupMatrices(FRenderer.SharedContext);
end;

procedure TGorillaMyDepthRenderPass.DoOnEndRenderPassSetup(
  const ACount : Integer; const APass : TRenderPass);
begin
  inherited;
end;

initialization

  RegisterClasses([TGorillaMyDepthRenderPass]);

finalization

  UnregisterClasses([TGorillaMyDepthRenderPass]);

end.

Render All Elements With Their Original Material

In case you want to render elements f.e. only with a different perspective, this mode expects not to create a render material and render material source.

In your render pass class the CreateMaterialSource needs to return NIL. The controller will then select the current material of the elements rendered.

function TGorillaMyDepthRenderPass.CreateMaterialSource() : TGorillaRenderPassMaterialSource;
begin
  result := nil;
end;

Render Once With A Render Material

For post effects this mode is the intended way.


Performance Considerations

  1. Resolution Matters: Lower resolution passes are much faster. Use scaled viewports for non-critical passes.

  2. Minimize Passes: Each render pass has overhead. Combine effects when possible.

  3. Use ListRendering for Depth: When transparency doesn't matter (depth/shadow passes), use TRenderPassRenderingProc.ListRendering.

  4. Control Filtering: Exclude unnecessary objects. Every object tested has a small cost.

  5. Conditional Execution: Skip passes when not visible or needed (use SkipRendering()).

  6. Iterations Cost: Each iteration re-renders. Use sparingly.

  7. Pass Order: Pre-passes execute first. Minimize pre-pass count.

Troubleshooting

Pass Not Executing

Problem: Render pass doesn't seem to run.

Solutions:

  • Verify Enabled := True
  • Check Viewport is assigned
  • Ensure unique Id property
  • Verify _Type is set correctly

Black/Empty Output Texture

Problem: OutputTexture is black or empty.

Solutions:

  • Check renderer is created (Viewport must be assigned)
  • Verify FBO size is valid (> 0)
  • For RectToFBO, ensure Shader is assigned
  • Check OverwriteViewportSize configuration

Objects Not Filtered Correctly

Problem: Ignored controls still render.

Solutions:

  • Call IgnoreControl() after objects are created
  • Check if object is a child (parent might not be ignored)
  • Verify AllowedControls is not blocking exclusion
  • Use IsControlIgnored() to debug

Performance Issues

Problem: Render passes cause slowdown.

Solutions:

  • Reduce viewport resolution with ViewportScale
  • Use ListRendering instead of DefaultRendering
  • Minimize control filtering complexity
  • Skip passes when not needed
  • Reduce Iterations count

Best Practices

  1. Always Exclude Self: Water reflections should exclude the water plane itself.

  2. Use Pre-Passes Sparingly: Each pre-pass delays the main render. Minimize count.

  3. Match Resolution to Use: Shadow maps can be lower res. Reflections should match quality needs.

  4. Unique IDs: Use descriptive, unique IDs like 'WaterReflection' not 'Pass1'.

  5. Event Usage: Use events for dynamic configuration, not fixed setup.

  6. Chain When Possible: Link passes with SetInputPass() for cleaner code.

  7. Profile First: Measure performance impact before optimizing.

See Also

API Reference: Built-In Render Passes