TGorillaTextureBitmap

Gorilla3D extends Delphi's built-in TTextureBitmap with TGorillaTextureBitmap, a specialized bitmap class that gives you full control over GPU texture configuration. This guide explains why the extension exists, how it relates to the FMX texture pipeline, and how to use it effectively.

Table of Contents

Why TGorillaTextureBitmap?

FMX's TTextureBitmap is designed for UI rendering: it creates textures in BGRA/RGBA format with unsigned byte data, and does not expose settings like wrapping mode, internal format, data type, or mip-map levels. This is fine for 2D images, but 3D rendering requires much more control:

  • Shadow maps need depth-only textures (Depth24, Depth32)
  • HDR rendering needs floating-point formats (RGBA16F, RGBA32F)
  • G-buffers need specific component layouts (RG16F for normals, R32F for depth)
  • Environment maps need cube map textures
  • Volumetric effects need 3D textures
  • Post-processing needs configurable wrapping (ClampToEdge vs Repeated)

TGorillaTextureBitmap solves all of these by extending TTextureBitmap with the missing GPU texture parameters while staying compatible with FMX's rendering pipeline.

FMX Texture Pipeline Recap

In standard FMX, the texture pipeline works like this:

TBitmap (CPU image data)
  └── TTextureBitmap (extends TBitmap, owns a TTexture)
        └── TTexture (GPU texture handle)
  1. TBitmap holds pixel data in CPU memory
  2. TTextureBitmap extends TBitmap and internally creates a TTexture when the Texture property is accessed
  3. TTexture represents the GPU-side texture handle, always created with the FMX defaults (BGRA, unsigned byte, no wrapping control)

The problem: FMX hard-codes the texture format. When TTextureBitmap creates its internal TTexture, it uses fixed pixel format, fixed data type, and overwrites the Style property — losing any MipMap settings you may have configured.

What Gorilla3D Adds

Gorilla3D inserts its own classes into this pipeline:

TBitmap
  └── TTextureBitmap (FMX)
        └── TGorillaTextureBitmap (Gorilla3D)
              └── TGorillaTexture (extends TTexture)

TGorillaTextureBitmap stores all extended texture settings (format, components, wrapping, filtering, data type) and applies them when the GPU texture is created. TGorillaTexture extends TTexture with the actual GPU-level properties.

Class Hierarchy

// FMX base classes
FMX.Graphics.TBitmap
  └── FMX.Graphics.TTextureBitmap
        └── Gorilla.Context.Texturing.TGorillaTextureBitmap

FMX.Types3D.TTexture
  └── Gorilla.Context.Texturing.TGorillaTexture

Creating Textures

Basic Creation

uses Gorilla.Context.Texturing;

// Create a standard RGBA texture bitmap
var LBmp := TGorillaTextureBitmap.Create(512, 512);
try
  // Use it...
finally
  LBmp.Free;
end;

Creating with Custom Format

Use BeginSetup / EndSetup to batch property changes and avoid premature GPU texture creation:

var LBmp := TGorillaTextureBitmap.Create(1024, 1024);
LBmp.BeginSetup();
try
  LBmp.Format     := TPixelFormatEx.RGBA16F;
  LBmp.Components := TPixelFormatEx.RGBA16F;
  LBmp.DataType   := TGorillaTextureDataType.dtHalfFloat;
  LBmp.MinFilter  := TTextureFilter.Linear;
  LBmp.MagFilter  := TTextureFilter.Linear;
  LBmp.WrapS      := TGorillaTextureWrap.ClampToEdge;
  LBmp.WrapT      := TGorillaTextureWrap.ClampToEdge;
  LBmp.Style       := [TTextureStyle.RenderTarget];
finally
  LBmp.EndSetup();
end;

Creating a Depth Texture (for Shadow Maps)

var LDepth := TGorillaTextureBitmap.Create(1024, 1024);
LDepth.BeginSetup();
try
  LDepth.Format     := TPixelFormatEx.Depth;
  LDepth.Components := TPixelFormatEx.Depth24;
  LDepth.DataType   := TGorillaTextureDataType.dtUnsignedInt;
  LDepth.MinFilter  := TTextureFilter.Nearest;
  LDepth.MagFilter  := TTextureFilter.Nearest;
  LDepth.WrapS      := TGorillaTextureWrap.ClampToBorder;
  LDepth.WrapT      := TGorillaTextureWrap.ClampToBorder;
  LDepth.BorderColor := TAlphaColorF.Create(1, 1, 1, 1);
finally
  LDepth.EndSetup();
end;

Texture Properties

Core Properties

Property Type Description
Kind TGorillaTextureKind Texture type: Texture2D, Texture3D, CubeMap, ImageTexture3D, Array2D
Format TPixelFormatEx Pixel data format (e.g., BGRA, RGBA16F, Depth24)
Components TPixelFormatEx Internal format / number of color components
DataType TGorillaTextureDataType Data type per channel: dtUnsignedByte, dtFloat, dtHalfFloat, etc.
Style TTextureStyles Texture styles: MipMaps, Dynamic, RenderTarget, Volatile

Filtering

Property Type Description
MinFilter TTextureFilter Minification filter: Nearest or Linear
MagFilter TTextureFilter Magnification filter: Nearest or Linear

Wrapping

Property Type Description
WrapS TGorillaTextureWrap Horizontal wrapping
WrapT TGorillaTextureWrap Vertical wrapping
WrapR TGorillaTextureWrap Depth wrapping (3D textures only)
BorderColor TAlphaColorF Border color for ClampToBorder mode

Advanced Properties

Property Type Description
MipMapLevels Integer Number of auto-generated mip-map levels
IsMultiSampled Boolean Enable multisampled texture
Multisamples Integer Multisample count (2, 4, 8, 16)
Depth Integer Depth dimension for 3D textures
IsCompressed Boolean Enable PNG compression for CPU-side storage. NOT the same as GPU block compression - see Compressed Textures
ProtectFormatSettings Boolean Prevent FMX from overwriting format on Assign
AttachedCubeMapFace TGorillaCubeMapFace Active cube map face for FBO rendering
GorillaTexture TGorillaTexture The underlying GPU texture (read-only)

Pixel Formats

TPixelFormatEx extends FMX's TPixelFormat with GPU-native formats:

Category Formats
Standard RGB, RGBA, BGR, BGRA
8-bit per channel R8, RG8, RGB8, RGBA8, SRGB8, SRGB8_ALPHA8
16-bit float R16F, RG16F, RGB16F, RGBA16F
32-bit float R32F, RG32F, RGB32F, RGBA32F
Integer R8UI, R16UI, R32UI, RG8UI, RGBA8UI, RGBA32UI, etc.
Depth Depth16, Depth24, Depth32
Depth+Stencil Depth24Stencil8, Depth32Stencil8

FMX vs Gorilla Format Comparison

FMX (TPixelFormat) Gorilla (TPixelFormatEx) Notes
TPixelFormat.BGRA TPixelFormatEx.BGRA Default on Windows
TPixelFormat.RGBA TPixelFormatEx.RGBA Default on macOS/iOS/Android
not available TPixelFormatEx.RGBA16F HDR rendering
not available TPixelFormatEx.Depth24 Shadow maps
not available TPixelFormatEx.RG16F Normal maps, VSM
not available TPixelFormatEx.R32F Single-channel float

Wrapping and Filtering

Wrapping Modes

Mode Description Use Case
Clamp Clamp to [0,1] range General purpose
ClampToEdge Edge pixels are extended Render targets, post-processing
ClampToBorder Uses BorderColor outside [0,1] Shadow maps (white border = no shadow)
Repeated Tile the texture Terrain, tiling materials
MirroredRepeat Tile with mirroring Seamless tiling

FMX does not expose wrapping at all — it always uses the platform default. With TGorillaTextureBitmap you can set wrapping per axis.

Note: TGorillaTextureBitmap defaults to ClampToEdge on all three axes, whereas the underlying TGorillaTexture defaults to Repeated. When you assign a texture bitmap to a material it carries its own wrap settings, so set them explicitly for the use case at hand.

Tiling and Seamless Repeats

Texture tiling — repeating an image multiple times across UV coordinates — is configured on the material's bitmap pool entry (Tiling / TilingX / TilingY, see Default Material → The Bitmaps Property). The tiling itself is performed in GLSL via mod(texcoord * tiling, 1.0) and is independent of the wrap mode.

The wrap mode, however, decides whether the tiling looks seamless. Because the bilinear/mip-map filter footprint straddles the tile seams, a clamping wrap mode samples and clamps to the texture border at every seam:

Important: For tiling, WrapS / WrapT (and WrapR for 3D textures) must not be Clamp, ClampToEdge or ClampToBorder — otherwise dark / black lines appear along the tile edges. Use Repeated (or MirroredRepeat) for seamless tiling.

The clamping modes are intended for non-tiled use: render targets and post-processing (ClampToEdge) or shadow-map depth textures with a white border (ClampToBorder).

Filtering

FMX's TTexture has MinFilter and MagFilter but they are not accessible through TTextureBitmap. TGorillaTextureBitmap exposes them directly.

LBmp.MinFilter := TTextureFilter.Linear;  // smooth when shrinking
LBmp.MagFilter := TTextureFilter.Nearest; // sharp when enlarging

3D Textures and Cube Maps

3D Textures

Used for volumetric effects and voxel cone tracing:

var LVol := TGorillaTextureBitmap.Create();
LVol.BeginSetup();
try
  LVol.Kind       := TGorillaTextureKind.Texture3D;
  LVol.Format     := TPixelFormatEx.RGBA8;
  LVol.Components := TPixelFormatEx.RGBA8;
  LVol.Set3DSize(64, 64, 64);
finally
  LVol.EndSetup();
end;

Cube Maps

Used for environment mapping and skyboxes:

var LCube := TGorillaTextureBitmap.Create(256, 256);
LCube.BeginSetup();
try
  LCube.Kind := TGorillaTextureKind.CubeMap;
  LCube.Format := TPixelFormatEx.RGBA8;
  LCube.Components := TPixelFormatEx.RGBA8;
finally
  LCube.EndSetup();
end;

// Upload each face
LCube.AttachedCubeMapFace := TGorillaCubeMapFace.PositiveX;
LCube.UpdateCubeMapFace(TGorillaCubeMapFace.PositiveX, LCube.GorillaTexture, AData, APitch);
// ... repeat for all 6 faces

Compressed Textures

Two very different things are called "texture compression", and Gorilla3D supports both. They solve different problems, and mixing them up is easy because both use the name IsCompressed — on two different classes.

Storage compression GPU block compression
Property TGorillaTextureBitmap.IsCompressed TGorillaTexture.IsCompressed — set by the backend, do not assign it yourself
What it compresses The CPU-side bitmap, as PNG in a memory stream The texture in video memory
Saves System RAM, asset package size VRAM, 4:1 to 6:1
Controlled by Per bitmap One global switch
Backends all OpenGL only

If your problem is "the dedicated GPU memory is full and the driver starts spilling into shared memory", the second one is what you want.

Storage compression (CPU side)

TGorillaTextureBitmap can keep its pixel data as PNG in a memory stream instead of as raw pixels. This reduces system memory and asset package size; the GPU texture is unaffected.

LBmp.IsCompressed := True;
// Bitmap data is stored as PNG in CompressedData stream
// Call Decompress() to restore pixel data when needed
LBmp.Decompress();
Method Description
ClearAfterCompression() Free pixel data after compression
Recompress() Re-compress current pixel data
Decompress() Restore pixel data from compressed stream

GPU block compression (video memory)

Block compression keeps the texture compressed for its entire life on the GPU. A 2048 × 2048 RGBA texture occupies 16 MB uncompressed and 4 MB as DXT5 — and it stays that way while it is being sampled.

Gorilla3D lets the driver do the compression: the image data is still handed to OpenGL as ordinary RGBA, only the internal format is a compressed one. That means no new file formats, no asset conversion, and no changes to your own code beyond the switch.

Is it active by default?

No. The default is off, so nothing changes in an existing project until you ask for it:

uses Gorilla.Context.Types;

GorillaTextureCompression := tcOff;   // default

Enabling it in your project

Set the global switch before the first texture is created — compression only applies to textures created afterwards. The safest place is your .dpr, before Application.Initialize:

program MyGame;

uses
  Gorilla.Context.Types,   // GorillaTextureCompression
  FMX.Forms,
  Unit1 in 'Unit1.pas' {Form1};

begin
  // Block-compress textures in video memory. Must be set before any texture
  // exists - a texture already uploaded stays uncompressed.
  GorillaTextureCompression := tcFast;

  Application.Initialize;
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.

Setting it later (in FormCreate, or worse in FormShow) is a common mistake: by then the framework has usually created its render targets and the first material textures, and those stay uncompressed without any warning. The counters described below make that visible.

The modes

Mode Format Ratio Notes
tcOff — 1:1 Default. Nothing is compressed.
tcFast DXT5 (RGBA) / DXT1 (RGB) 4:1 / 6:1 Fast to encode. Visible artefacts on hard colour edges — text, logos, sharp gradients.
tcQuality BC7 / BPTC 4:1 Clearly better than DXT on edges, but the driver's encoder is much slower. Expect a noticeably longer start-up. Falls back to DXT when GL_ARB_texture_compression_bptc is missing.

Both modes require the matching driver extension (GL_EXT_texture_compression_s3tc, GL_ARB_texture_compression_bptc). If it is missing, the texture is simply created uncompressed — nothing fails.

Which textures are compressed

Compression is applied only where it is safe and worthwhile. A texture is left uncompressed when it is:

  • a render target or multisampled — a compressed format cannot be a render target
  • not TGorillaTextureKind.Texture2D — cube maps, 3D and array textures are excluded
  • marked TTextureStyle.Volatile or TTextureStyle.External
  • not 8 bits per channel — depth and floating-point textures are excluded
  • smaller than GorillaTextureCompressionMinEdge on either axis
// Only compress textures of at least 512 px per edge (default: 256).
// Small textures are usually the ones with hard edges - icons, fonts, colour
// ramps - which lose the most and save the least.
GorillaTextureCompressionMinEdge := 512;

Note on TTextureStyle.Dynamic: dynamic textures are compressed. In FMX Dynamic only means "may be updated", and almost every texture created from a TBitmap carries it — excluding them would mean compressing almost nothing. The consequence is that a texture you really do re-upload every frame gets re-compressed by the driver on every upload. If you have such a texture and it costs you frame time, either mark it Volatile or turn compression off.

Measuring what it actually did

Do not assume the driver honoured the request — a driver may accept a compressed internal format and still store the texture uncompressed. Gorilla3D asks it afterwards (GL_TEXTURE_COMPRESSED, GL_TEXTURE_COMPRESSED_IMAGE_SIZE) and keeps the tally:

uses Gorilla.Context.Profiler;

// after your scene has been built
Log.d('compressed: %d textures, %.1f MB, saved %.1f MB (factor %.2f)',
  [TGorillaTextureStats.CompressedCount,
   TGorillaTextureStats.CompressedBytes / (1024 * 1024),
   TGorillaTextureStats.SavedBytes() / (1024 * 1024),
   TGorillaTextureStats.Ratio()]);

// and when nothing was compressed, this says why
Log.d('considered %d, rejected %d: %s',
  [TGorillaTextureStats.ConsideredCount,
   TGorillaTextureStats.RejectedCount,
   TGorillaTextureStats.RejectSummary()]);
Member Description
CompressedCount / UncompressedCount Textures the driver did / did not compress
PlainBytes / CompressedBytes What they would have cost, and what they cost
SavedBytes() / Ratio() The difference, and the achieved ratio
ConsideredCount / RejectedCount How often the decision was made at all, and how often it was negative
RejectSummary() Reasons with counts, e.g. Rendertarget/MSAA=60, zu klein=3
HasS3TC / HasBPTC Extension availability (-1 = never queried)
LastFormat / FormatName() The internal format actually used

ConsideredCount matters more than it looks: "0 compressed textures" can mean the decision was never reached (switch set too late) or that it was always negative (a guard rejected everything). Those are different bugs.

A measured example

A football game with a large painted pitch texture, a goal-net texture, kit atlases and imported stadium models, on an RTX 4070 Laptop:

Textures VRAM
tcOff 208 1801 MB
tcFast 208 450 MB

1350 MB saved, factor 4.00, with 60 render targets and 3 undersized textures correctly left alone. tcQuality saved exactly the same (BC7 is also 4:1) and added about 15 seconds to start-up.

Backend support

Backend Supported Why
OpenGL (Windows, Linux) yes The driver compresses on upload
Vulkan no No driver-side encoder — data must arrive already in blocks
Metal no Same

GorillaTextureCompression has no effect on Vulkan and Metal. Supporting those means shipping pre-compressed assets (BCn DDS / KTX2) and uploading the blocks without decoding them.

Note: Gorilla3D can read DDS files containing DXT data, but the image layer currently decodes them to RGBA (DecodeDXT1/3/5), so the blocks never reach the GPU. Loading a DDS therefore does not save video memory by itself — the switch above does.

Multisampled Textures

For MSAA (multisample anti-aliasing) render targets:

LBmp.BeginSetup();
try
  LBmp.IsMultiSampled := True;
  LBmp.Multisamples := 4; // 2, 4, 8, or 16
finally
  LBmp.EndSetup();
end;

On OpenGL, this changes the texture type from GL_TEXTURE_2D to GL_TEXTURE_2D_MULTISAMPLE.

The Buffer Workaround

FMX internally stores all bitmap data as BGRA/RGBA with unsigned bytes. When you need a different format (e.g., RG16F for variance shadow maps), the FMX bitmap buffer cannot hold the data correctly.

TGorillaTextureBitmap solves this with an internal Buffer:

  • If the configured Format differs from the default BGRA/RGBA, a separate buffer (Buffer / BufferSize) is allocated
  • This buffer holds the raw pixel data in the correct format
  • The buffer is uploaded directly to the GPU via UpdateBuffer()

You typically do not interact with the buffer directly — it is managed automatically. But you can read the properties:

if LBmp.Buffer <> nil then
  // Texture uses the workaround buffer (non-standard format)
  WriteLn('Buffer size: ', LBmp.BufferSize);

TGorillaTexture

TGorillaTexture extends FMX's TTexture with the same extended properties. It is created automatically by TGorillaTextureBitmap when the GorillaTexture property is accessed.

Key additions over TTexture:

Property Type Description
Kind TGorillaTextureKind Texture type
Components TPixelFormatEx Internal format
Format TPixelFormatEx Data format
DataType TGorillaTextureDataType Channel data type
WrapS/T/R TGorillaTextureWrap Per-axis wrapping
MipMapLevels Integer Mip-map level count
TextureUnit Integer Last bound texture unit
IsCompressed Boolean Whether this texture is block-compressed in video memory. Written by the backend after asking the driver — read it, do not set it. Unrelated to TGorillaTextureBitmap.IsCompressed, which is PNG storage compression.

Methods:

Method Description
Clear() Clear texture data on GPU
GenerateMipMap() Generate mip-maps on GPU
RequestTextureData(ABytes, ASize, ALevel) Read texture data back from GPU

Best Practices

  • Always use BeginSetup() / EndSetup() when configuring multiple properties — this prevents intermediate GPU texture (re)creation
  • Use ProtectFormatSettings := True when assigning from FMX bitmaps to prevent format override
  • For render targets, set Style := [TTextureStyle.RenderTarget]
  • Use ClampToEdge for render pass textures to avoid border artefacts
  • Use ClampToBorder with white BorderColor for shadow map depth textures
  • Prefer TPixelFormatEx.RGBA16F over RGBA32F for HDR — half the memory, sufficient precision
  • Use Nearest filtering for depth/position G-buffer textures, Linear for color
  • On Windows, FMX defaults to BGRA byte order; on macOS/iOS/Android it uses RGBA — TGorillaTextureBitmap handles this transparently
  • The GorillaTexture property returns the existing texture or creates one — use TextureReference if you only want to check without creating
  • If you run out of dedicated video memory, reach for GPU block compression before you start shrinking textures — it costs a factor of four in memory and nothing in resolution
  • Set GorillaTextureCompression in the .dpr before Application.Initialize, never in a form event — textures created earlier stay uncompressed, silently
  • Never trust that compression happened; read TGorillaTextureStats once after your scene is built. A driver may accept a compressed format and store the texture uncompressed anyway