Default Material
The TGorillaDefaultMaterial is the core shader system of Gorilla3D. It uses a node-based architecture to generate GLSL shader source code at runtime. Instead of writing monolithic shaders, the system composes vertex and fragment shaders from a hierarchical tree of TGorillaNodeEntity nodes. This enables flexible shader customization by replacing or inserting specific nodes without rewriting entire shader code.
Node-Based Shader Architecture
When a material is compiled, the TGorillaNodeBuilder instance traverses the node tree and calls ToString() on each TGorillaNodeEntity. Each node decides its output based on activated defines, allowing features to be toggled on or off at compile time.
Shader Structure
Vertex Shader (TGorillaGLSLVertexShader):
Pragma (GLSL version)
└─ Globals (constants, types, uniforms, functions)
└─ Entry Point (main)
├─ Transformation nodes
├─ Displacement nodes
├─ Clipping nodes
├─ Surface Shader (custom user code)
└─ Output nodes
Fragment Shader (TGorillaGLSLFragmentShader):
Pragma (GLSL version)
└─ Globals (constants, types, uniforms, functions)
└─ Entry Point (main)
├─ Clipping / transformation
├─ Normal / bump mapping
├─ Parallax occlusion mapping
├─ Lighting loop (shading, attenuation, shadows)
├─ PBR preparation
├─ Surface Shader (final color computation)
└─ Multi-target output
Node Classes
| Class | Purpose |
|---|---|
TGorillaNodeEntity |
Base class; ToString() returns source code snippets |
TGorillaCompositeNode |
Container holding sub-nodes with hierarchical output |
TGorillaUniformsNode |
Manages input variables for specific shader languages |
TGorillaGlobalsNode |
Storage for globals, constants, attributes, types, uniforms |
TGorillaDeclarationNode |
Base for type/function declarations |
TGorillaOperationNode |
Builds mathematical/logical expressions in node format |
TGorillaSurfaceShaderNode |
Entry point for user-specific shader implementation |
Important Fragment Shader Nodes
| Node | Purpose |
|---|---|
TGorillaGLSLClippingPlaneNode |
Clipping plane computation |
TGorillaGLSLGetTransfVertPosNode |
Transformed vertex position |
TGorillaGLSLGetNormalNode |
Normal vector computation |
TGorillaGLSLGetBumpNormalNode |
Bump/normal map computation |
TGorillaGLSLPOMApplyNode |
Parallax occlusion mapping |
TGorillaGLSLLightsLoopNode |
Lighting loop (shading, attenuation, shadows) |
TGorillaGLSLGetBaseColorNode |
Base color / texture sampling |
TGorillaGLSLSpecularMapNode |
Specular map sampling |
TGorillaGLSLAddEnvironmentNode |
Environment map application |
TGorillaGLSLAddReflectionNode |
Reflection application |
TGorillaGLSLFragColorOutputNode |
Final fragment output |
TGorillaGLSLWeightedBlendedOITNode |
Order-independent transparency |
Shader Define System
Features are toggled through compile-time defines. Add or remove defines to enable/disable shader functionality:
Material.AddDefine(GORILLA_GLSL_DEFINE_LIGHTING);
Material.RemoveDefine(GORILLA_GLSL_DEFINE_PBR);
Available Defines
Shader Type:
GORILLA_GLSL_DEFINE_VERTEXSHADER/GORILLA_GLSL_DEFINE_FRAGMENTSHADER
Lighting & Shading:
GORILLA_GLSL_DEFINE_LIGHTING— Core lighting computationGORILLA_GLSL_DEFINE_PHONG/GORILLA_GLSL_DEFINE_BLINNPHONG— Shading modelsGORILLA_GLSL_DEFINE_PBR— Physically-based rendering
Mapping Techniques:
GORILLA_GLSL_DEFINE_NORMALMAP/GORILLA_GLSL_DEFINE_BUMP— Normal/bump mappingGORILLA_GLSL_DEFINE_POM— Parallax occlusion mappingGORILLA_GLSL_DEFINE_DISPLACEMENT— Vertex displacement
Shadows & Effects:
GORILLA_GLSL_DEFINE_SHADOWwith_SMor_VSM— Shadow / variance shadow mappingGORILLA_GLSL_DEFINE_REFLECTION/GORILLA_GLSL_DEFINE_REFRACTIONGORILLA_GLSL_DEFINE_ENVIRONMENT— Environment mapping
Texturing:
GORILLA_GLSL_DEFINE_USE_TEXTURE— General texturingGORILLA_GLSL_DEFINE_USE_VERTEXCOLOR— Vertex color usageGORILLA_GLSL_DEFINE_SPECULARMAP— Specular texture mapping
Uniform Buffer: TGorillaShaderData
All shader parameters are transmitted via a packed record (TGorillaShaderData) as a Uniform Buffer Object (UBO). This is more efficient than submitting variables individually.
Key Fields
Matrices:
ModelViewProjectionMatrix,ViewMatrix,ProjectionMatrix
Camera & Timing:
TimeInfo— (start, current, previous, delta)EyePos— Camera positionViewDir— Camera direction
Material & Lighting:
Material[0]— Material propertiesLights[0..MAX]— Light source arrayLightsCount— Active light countShadingModel— Lambert / Phong / PBRShadingIntensity,Brightness
Fog:
FogMode,FogDensity,FogStart,FogEnd,FogColor
Scene Bounds:
FrustumMin/Max,SceneMin/Max,BoundaryMin/MaxViewSize— Viewport dimensions and camera near/far
Special:
ClippingPlane— Single clipping planePassData[0]— Reflection/refraction matrices and PBR parameters
GLSL Variables
Vertex Attributes
Sixteen standard attributes are pre-declared:
a_Position, a_Normal, a_Tangent, a_Binormal
a_TexCoord0, a_TexCoord1, a_TexCoord2, a_TexCoord3
a_Color, a_Color1, a_Color2, a_Color3
Varying Parameters (vars.*)
Data passed from vertex to fragment shader:
| Name | Type | Purpose |
|---|---|---|
vars.v_VertPos |
vec4 | Original vertex position |
vars.v_TransfVertPos |
vec3 | Transformed vertex position |
vars.v_TBN |
mat3 | Tangent-Binormal-Normal matrix |
vars.v_TBN_UT |
mat3 | TBN untransformed |
vars.v_TexCoord0 |
vec2 | Primary texture coordinates |
vars.v_Color0 |
vec4 | Vertex color data |
vars.v_ReflProjTextureCoords |
vec4 | Reflection texture projection |
vars.v_RefrProjTextureCoords |
vec4 | Refraction texture projection |
TLocals Structure (Vertex Shader)
Modify these fields in the custom VertexShader function instead of varyings directly:
Position, TransfVertexPos, WorldViewProjVertPos
TexCoord0, TexCoord1, TexCoord2, TexCoord3, Color0
Normal, Tangent, Binormal
Displace
ClippingPlane
TLocals Structure (Fragment Shader)
Available fields in the custom SurfaceShader function:
Lighting:
LightDir, LightVec, LightType, LightDist
Attenuation, SceneAttenuation
Ambient, Diffuse, Specular, Emissive
Geometry:
TransfVertPos, FragDepth
Normal, FragViewDir
TexCoord0, TexCoord1, TexCoord2, TexCoord3
Color Computation:
SpecularColor, BaseColor, SumColor
Alpha, Shading, ShadowSum, BumpSum
Default Textures
| Texture | Shader | Condition | Type |
|---|---|---|---|
_DisplacementMapTexture |
Vertex | DEFINE_DISPLACEMENT |
sampler2D |
_Texture0 |
Fragment | DEFINE_USE_TEXTURE |
sampler2D / samplerCube / sampler3D |
_NormalMapTexture |
Fragment | DEFINE_NORMALMAP |
sampler2D |
_SpecularMapTexture |
Fragment | DEFINE_SPECULARMAP |
sampler2D |
_EnvironmentTexture |
Fragment | DEFINE_ENVIRONMENT |
samplerCube |
_ReflectionTexture |
Fragment | DEFINE_REFLECTION |
sampler2D |
_RefractionTexture |
Fragment | DEFINE_REFRACTION |
sampler2D |
_DepthTexture |
Fragment | DEFINE_DEPTH |
sampler2D |
Render Targets (MRT)
Multiple render target output from the fragment shader:
| Target | Value | Condition |
|---|---|---|
o_Albedo |
LOCALS.SumColor |
Always |
o_Alpha |
LOCALS.Alpha |
Always |
o_Position |
vec4(TransfVertPos, FragDepth) |
Always |
o_Normals |
LOCALS.Normal.xyz |
Always |
o_Components |
vec4(TexCoord0.xy, 1.0, 1.0) |
Deferred rendering |
o_Ambient |
LOCALS.Ambient.xyz |
Deferred rendering |
o_Emissive |
LOCALS.Emissive.xyz |
Deferred rendering |
o_Specular |
LOCALS.Specular.xyz |
Deferred rendering |
Custom VertexShader and SurfaceShader
The TGorillaDefaultMaterialSource exposes two customizable shader functions: VertexShader and SurfaceShader. These allow you to inject custom GLSL code into the shader pipeline without creating a material subclass.
VertexShader Function
Modify vertex positions and transforms:
void VertexShader(inout TLocals DATA){
// Modify vertex position and related transforms
// IMPORTANT: When modifying Position, also update
// TransfVertexPos and WorldViewProjVertPos consistently
}
SurfaceShader Function
Compute the final fragment color:
void SurfaceShader(inout TLocals DATA){
// Compute final fragment color
// Set BaseColor, Alpha, and other lighting properties
DATA.BaseColor = tex2D(_Texture0, DATA.TexCoord0);
DATA.Alpha = DATA.BaseColor.a;
}
Design-Time Usage
In the Object Inspector, expand the VertexShader or SurfaceShader property and write your GLSL code directly in the Text subproperty.
Runtime Usage
Important: The
VertexShaderandSurfaceShaderproperties are dynamic properties (published asTStrings). You cannot simply assign a string to.Textat runtime. Instead, you must assign aTStringListinstance to the property.
var
LShader: TStringList;
begin
LShader := TStringList.Create();
try
LShader.Add('void SurfaceShader(inout TLocals DATA){');
LShader.Add(' DATA.BaseColor = tex2D(_Texture0, DATA.TexCoord0);');
LShader.Add(' DATA.Alpha = DATA.BaseColor.a;');
LShader.Add('}');
// Correct: Assign TStringList to the property
Material.SurfaceShader := LShader;
finally
LShader.Free();
end;
end;
The same applies to the VertexShader property:
var
LShader: TStringList;
begin
LShader := TStringList.Create();
try
LShader.Add('void VertexShader(inout TLocals DATA){');
LShader.Add(' // Apply sine wave displacement');
LShader.Add(' float wave = sin(DATA.Position.x * 4.0 + _TimeInfo.y) * 0.1;');
LShader.Add(' DATA.Position.y += wave;');
LShader.Add(' DATA.TransfVertexPos = (_ModelViewMatrix * vec4(DATA.Position.xyz, 1.0)).xyz;');
LShader.Add(' DATA.WorldViewProjVertPos = _MVPMatrix * vec4(DATA.Position.xyz, 1.0);');
LShader.Add('}');
// Correct: Assign TStringList to the property
Material.VertexShader := LShader;
finally
LShader.Free();
end;
end;
Warning: Do not use
Material.SurfaceShader.Text := '...'orMaterial.VertexShader.Text := '...'at runtime. Since these are dynamic properties, writing to.Textdirectly will not trigger the necessary internal update mechanism. Always assign aTStrings/TStringListinstance.
Example: Spritesheet Animation
void SurfaceShader(inout TLocals DATA){
float SPRITE_COLUMNS = 3.0;
float SPRITE_ROWS = 3.0;
uint NUM_SPRITES = 9;
uint idx = int(abs(sin(_TimeInfo.y) * 8.0)) % NUM_SPRITES;
vec2 pos = vec2(idx % 3, idx / 3);
DATA.BaseColor = tex2D(_Texture0, vec2(
(DATA.TexCoord0.x / SPRITE_COLUMNS) + pos.x * (1.0 / SPRITE_COLUMNS),
(DATA.TexCoord0.y / SPRITE_ROWS) + pos.y * (1.0 / SPRITE_ROWS)));
DATA.Alpha = DATA.BaseColor.a;
if(DATA.Alpha < 0.04) discard;
}
Extending the Material at Runtime
Adding Custom Uniform Buffers
Define a packed record respecting OpenGL's std140 layout alignment (16-byte blocks):
type
TMyParams = packed record
Point: TPoint3D;
MyValue: Single; // Fits in same 16-byte block as Point
end;
Override DoUpdateShaderUniformBuffers() to register it:
procedure TMyMaterial.DoUpdateShaderUniformBuffers(const AProgram: TGorillaShaderProgram);
begin
inherited;
AProgram.RegisterUniformBuffer('MyParams', @FMyParams, SizeOf(FMyParams));
end;
Access in GLSL with underscore prefix: _MyParams._Point.
Registering Custom Textures
Override DoCreateDefaultBitmaps():
procedure TMyMaterial.DoCreateDefaultBitmaps();
var
LEntry: TGorillaTextureBitmapPoolEntry;
begin
inherited;
LEntry := DoAddOrUpdateBitmapToPool('MYTEXTURE0',
TPixelFormatEx.RGBA8, TPixelFormatEx.RGBA,
GORILLA_DEFAULT_TEXTURE_DATATYPE, false, true, true);
if Assigned(LEntry) then
LEntry.SetExtendedProperties(
TGorillaTextureWrap.Repeated, TGorillaTextureWrap.Repeated,
TGorillaTextureWrap.Repeated,
TTextureFilter.Linear, TTextureFilter.Linear);
end;
Access via _MYTEXTURE0 in shaders. The naming convention is: the pool name becomes _<NAME> in GLSL.
Declaring Custom Shader Variables
Override DoSetupFragmentShader():
procedure TMyMaterial.DoSetupFragmentShader();
var
LUniform: TGorillaGLSLUniformsNode;
begin
inherited;
// Register variable for the shader pipeline
FFSShaderSource.AddVariables([
TContextShaderVariable.Create('MyPointF',
TContextShaderVariableKind.Float2, FFSVarIndex, 0)
]);
Inc(FFSVarIndex);
// Add GLSL uniform declaration
LUniform := TGorillaGLSLUniformsNode.Create(FragmentShaderNode);
LUniform.AddDeclaration('_MyPointF', TGorillaShaderNodeVariableType.stVec2);
FragmentShaderNode.Globals.Uniforms.Add(LUniform);
end;
Adding Custom GLSL Functions
Create a declaration node class:
type
TMyFuncNode = class(TGorillaDeclarationNode)
function ToString: String; override;
end;
function TMyFuncNode.ToString: String;
begin
Result := 'vec4 MyFunc(sampler2D tex, vec2 uv){' +
'return texture2D(tex, uv);}';
end;
Register it in the shader globals:
FragmentShaderNode.Globals.Functions.Add(
TMyFuncNode.Create(FragmentShaderNode)
);
Replacing Existing Nodes
To replace an existing node (e.g., the base color computation):
var
LOldIdx: Integer;
begin
LOldIdx := FragmentShaderNode.SurfaceShader.IndexOf(
TGorillaGLSLGetBaseColorNode, '');
if LOldIdx > -1 then
begin
FragmentShaderNode.SurfaceShader.Delete(LOldIdx);
FragmentShaderNode.SurfaceShader.Insert(LOldIdx, LNewNode);
end;
end;
The Bitmaps Property (Texture Pool)
Every TGorillaDefaultMaterialSource exposes a published Bitmaps property of type TGorillaBitmapPool — an TOwnedCollection of TGorillaBitmapPoolEntry items. This pool is the central place where all textures of a material live, including the built-in ones (Texture0, NormalMap, SpecularMap, …) as well as any custom textures you add. Properties like Texture0 or NormalMap are convenience accessors that internally resolve to a pool entry.
Each entry maps to a GLSL sampler: an entry named MyTexture becomes _MyTexture in the shader code.
TGorillaBitmapPoolEntry Properties
| Property | Type | Default | Purpose |
|---|---|---|---|
Name |
String |
— | Entry name; becomes _<Name> in GLSL |
Bitmap |
TBitmap |
— | The actual texture image data (BMP, PNG, JPEG). When you assign a TGorillaTextureBitmap, all of its extended GPU settings are honoured |
TextureKind |
TGorillaTextureKind |
Texture2D |
Texture2D, Texture3D, CubeMap, … |
ShaderKind |
TContextShaderKind |
Pixel |
Which shader stage uses the texture (Pixel / Vertex) |
Tiling |
TPointF |
(1.0, 1.0) |
Number of texture repeats across the X/Y axes |
TilingX |
Single |
1.0 |
Repeat count on the X-axis (component of Tiling) |
TilingY |
Single |
1.0 |
Repeat count on the Y-axis (component of Tiling) |
WrapS |
TGorillaTextureWrap |
ClampToEdge |
Horizontal wrap mode |
WrapT |
TGorillaTextureWrap |
ClampToEdge |
Vertical wrap mode |
WrapR |
TGorillaTextureWrap |
ClampToEdge |
Depth wrap mode (3D textures) |
MinFilter / MagFilter |
TTextureFilter |
Linear |
Minification / magnification filter |
Format / InternalFormat |
TPixelFormatEx |
— | Pixel format and internal GPU format |
DataType |
TGorillaTextureDataType |
— | Channel data type |
BorderColor |
TAlphaColor |
— | Border color used by ClampToBorder |
ProtectFormatSettings |
Boolean |
False |
Prevent FMX from overwriting the format settings at runtime |
IsDynamic |
Boolean |
False |
Texture is produced by a render pass (reflection/refraction/depth) |
The
Bitmapproperty is therefore the raw image source of a texture entry, whileFormat,DataType,WrapS/T/R, the filters andTilingdescribe how that image is uploaded to the GPU and sampled in the shader.
Texture Tiling
Tiling (and its scalar components TilingX / TilingY) controls how often a texture is repeated across the surface's UV coordinates. A value of (1.0, 1.0) shows the texture exactly once; (4.0, 4.0) repeats it four times along each axis.
Tiling is applied in GLSL by scaling and wrapping the texture coordinates, conceptually:
texcoord = mod(texcoord * tiling, 1.0);
// Repeat the diffuse texture 8×8 times across the mesh
Material.Bitmaps.Items[0].Tiling := PointF(8.0, 8.0);
Material.Bitmaps.Items[0].WrapS := TGorillaTextureWrap.Repeated;
Material.Bitmaps.Items[0].WrapT := TGorillaTextureWrap.Repeated;
Important — avoid black seam lines when tiling: Setting
Tilingalone does not change the wrap mode. Because the tiling is computed withmod(texcoord * tiling, 1.0), it works even with a clamping wrap mode — but withWrapS/WrapT(andWrapRfor 3D textures) set toClamp,ClampToEdgeorClampToBorder, the bilinear/mip-map filter footprint at every tile seam samples (and clamps to) the texture border. The result is visible dark / black lines along the tile edges.For seamless tiling you must explicitly set
WrapS/WrapT(/ WrapR) toTGorillaTextureWrap.Repeated(orMirroredRepeat). Note that a fresh bitmap pool entry defaults to a clamping wrap mode, so this step is required wheneverTiling > 1.
| Use case | Tiling | WrapS / WrapT (/ WrapR) | Result |
|---|---|---|---|
| No repetition | (1.0, 1.0) |
any | Single texture, edges controlled by wrap mode |
| Seamless repeating | (N, M) |
Repeated |
Seamless tiling, no dark seams |
| Seamless mirrored | (N, M) |
MirroredRepeat |
Seamless tiling with mirrored repeats |
| Single + custom border | (1.0, 1.0) |
ClampToBorder |
Single texture surrounded by BorderColor |
Design-Time Texture Management
- Open the Bitmaps property editor in the Object Inspector
- Add an item with a unique name (e.g.,
MyTexture) - Select the shader target (PixelShader / VertexShader)
- Configure properties:
- Bitmap — Image data (BMP, PNG, JPEG)
- Format / InternalFormat — OpenGL format specifications
- MagFilter / MinFilter — Texture filtering
- WrapS / WrapT / WrapR — Texture wrapping mode
- Tiling / TilingX / TilingY — Texture repeat count across the UV axes
- ProtectFormatSettings — Preserve settings at runtime
The texture name MyTexture becomes _MyTexture in GLSL code.
When you increase Tiling above
1, remember to also switch WrapS / WrapT (and WrapR for 3D textures) to Repeated or MirroredRepeat — otherwise black seam lines appear at the tile borders (see Texture Tiling).