Gorilla.Terrain.CVLOD Unit Reference
Level-of-detail terrain with dynamic mesh optimization.
Unit: Gorilla.Terrain.CVLOD
Status: Experimental - clustering system not fully implemented
Overview
TGorillaCVLODTerrain provides level-of-detail optimization for large terrains by adjusting mesh density based on distance from camera. This reduces vertex count while maintaining visual quality.
Current Implementation:
- Simple LOD mode using
CurrentLODproperty works well - Clustering system is experimental and not recommended for production use
Types
TTerrainCluster
type
TTerrainCluster = record
GridX, GridY: Integer;
Size: Integer;
LODLevel: Integer;
DistanceToCamera: Single;
StartIndex: Integer;
EndIndex: Integer;
IsDirty: Boolean;
end;
Represents a quad cluster in the LOD terrain system.
Fields:
GridX, GridY- Position in cluster gridSize- Size in verticesLODLevel- Current detail level (0 = highest)DistanceToCamera- Cached distance for sortingStartIndex, EndIndex- Index range in mesh bufferIsDirty- Needs regeneration flag
Classes
TTerrainUpdateTask
Manages asynchronous mesh updates for the LOD terrain.
Status: Not fully implemented. Async updates currently disabled.
TGorillaCVLODTerrain
Level-of-detail terrain with dynamic mesh optimization.
Inheritance: TGorillaTerrain → TGorillaCVLODTerrain
Properties
Camera
property Camera: TCamera read FCamera write SetCamera;
Camera reference for distance-based LOD calculations.
Required: Must be set for automatic LOD updates (clustering mode)
Note: Not required for simple LOD mode using CurrentLOD
CurrentLOD
property CurrentLOD: Integer read FCurrentLOD write SetCurrentLOD default 0;
Current LOD level for entire terrain (simple mode without clustering).
Range: 0 (highest detail) to LODLevels-1 (lowest detail)
Default: 0
LOD to Resolution Mapping:
- LOD 0: Full resolution (step = 1)
- LOD 1: Half resolution (step = 2)
- LOD 2: Quarter resolution (step = 4)
- LOD 3: Eighth resolution (step = 8)
Example:
// Test different detail levels
LLODTerrain.CurrentLOD := 0; // Highest
LLODTerrain.RebuildTerrain;
LLODTerrain.CurrentLOD := 2; // Quarter resolution
LLODTerrain.RebuildTerrain;
LODLevels
property LODLevels: Integer read FLODLevels write SetLODLevels default 4;
Number of detail levels.
Range: 1 to 8
Default: 4
ClusterSize
property ClusterSize: Integer read FClusterSize write SetClusterSize default 32;
Size of each cluster in vertices (clustering mode only).
Range: 8 to 128
Default: 32
Trade-off: Smaller = more granular LOD but more overhead
Note: Only used in experimental clustering mode
AsyncUpdate
property AsyncUpdate: Boolean read FAsyncUpdate write SetAsyncUpdate default false;
Enable asynchronous mesh updates on background thread.
Status: Not fully implemented, keep disabled
Default: False
CameraMovementThreshold
property CameraMovementThreshold: Single read FCameraMovementThreshold write FCameraMovementThreshold;
Minimum camera movement (units) to trigger LOD update (clustering mode).
Default: 5.0
Trade-off: Lower = smoother transitions, higher CPU usage
UpdateInterval
property UpdateInterval: Integer read FUpdateInterval write FUpdateInterval default 100;
Minimum time between LOD updates in milliseconds (clustering mode).
Default: 100ms
Purpose: Prevents excessive updates during rapid camera movement
Methods
RebuildTerrain
procedure RebuildTerrain(const AStaticBuffering: Boolean = true;
const ADecimate: Boolean = false); override;
Overridden to generate terrain at specified CurrentLOD level.
Behavior:
- Uses current
CurrentLODvalue to determine mesh density - Generates vertices at reduced resolution based on LOD
- Maintains same terrain dimensions
- Calculates normals and tangents from reduced mesh
Example:
LLODTerrain.CurrentLOD := 1; // Half resolution
LLODTerrain.RebuildTerrain;
ForceUpdateLOD
procedure ForceUpdateLOD;
Immediately updates all clusters based on current camera position (clustering mode).
Note: Only useful in clustering mode (experimental)
SetCustomLODDistances
procedure SetCustomLODDistances(const ADistances: array of Single);
Sets custom distance thresholds for each LOD level (clustering mode).
Parameters:
ADistances- Array of distances (length must equal LODLevels)
Example:
LLODTerrain.SetCustomLODDistances([10.0, 30.0, 100.0, 300.0]);
Note: Only used in clustering mode (experimental)
GetLODStatistics
procedure GetLODStatistics(out ATotalVertices, ATotalIndices: Integer;
out ALODDistribution: TArray<Integer>);
Returns current LOD statistics.
Parameters:
ATotalVertices- Total vertex count (output)ATotalIndices- Total index count (output)ALODDistribution- Clusters per LOD level (output)
Example:
var
LVerts, LIndices: Integer;
LDist: TArray<Integer>;
begin
LLODTerrain.GetLODStatistics(LVerts, LIndices, LDist);
ShowMessage(Format('Vertices: %d, Indices: %d', [LVerts, LIndices]));
end;
Usage Modes
Simple LOD Mode (Recommended)
Use CurrentLOD property to manually control detail level:
var
LTerrain: TGorillaCVLODTerrain;
begin
LTerrain := TGorillaCVLODTerrain.Create(Self);
LTerrain.Parent := GorillaViewport1;
LTerrain.Width := 200;
LTerrain.Height := 40;
LTerrain.Depth := 200;
LTerrain.SetXYResolution(512, 512);
LTerrain.HeightMap := MyHeightMap;
// Set LOD level manually
LTerrain.CurrentLOD := 0; // Full detail when close
LTerrain.RebuildTerrain;
end;
When to change LOD:
- In camera movement event
- Based on distance calculation
- In response to performance metrics
Dynamic LOD Based on Distance
procedure TForm1.UpdateTerrainLOD(ATerrain: TGorillaCVLODTerrain; ACamera: TCamera);
var
LDistance: Single;
LNewLOD: Integer;
begin
// Calculate distance from camera to terrain
LDistance := ATerrain.AbsolutePosition.Distance(ACamera.AbsolutePosition);
// Determine LOD level
if LDistance < 50 then
LNewLOD := 0 // Full detail
else if LDistance < 150 then
LNewLOD := 1 // Half detail
else if LDistance < 400 then
LNewLOD := 2 // Quarter detail
else
LNewLOD := 3; // Eighth detail
// Update if changed
if ATerrain.CurrentLOD <> LNewLOD then
begin
ATerrain.CurrentLOD := LNewLOD;
ATerrain.RebuildTerrain;
end;
end;
Multiple Terrain Tiles with LOD
type
TTerrainTile = record
Terrain: TGorillaCVLODTerrain;
Position: TPoint3D;
end;
var
FTiles: array of TTerrainTile;
procedure UpdateAllTerrainLODs(ACamera: TCamera);
var
i: Integer;
LDistance: Single;
LLODLevel: Integer;
begin
for i := 0 to High(FTiles) do
begin
LDistance := FTiles[i].Position.Distance(ACamera.AbsolutePosition);
// Calculate appropriate LOD
LLODLevel := Trunc(LDistance / 100); // Simple distance-based
LLODLevel := Min(LLODLevel, 3); // Clamp to max LOD
if FTiles[i].Terrain.CurrentLOD <> LLODLevel then
begin
FTiles[i].Terrain.CurrentLOD := LLODLevel;
FTiles[i].Terrain.RebuildTerrain;
end;
end;
end;
Performance Analysis
Vertex Reduction by LOD Level
For a 512×512 terrain:
| LOD | Resolution | Vertices | Triangles | Reduction |
|---|---|---|---|---|
| 0 | 512×512 | 263,169 | 524,288 | 0% |
| 1 | 256×256 | 66,049 | 131,072 | 75% |
| 2 | 128×128 | 16,641 | 32,768 | 93% |
| 3 | 64×64 | 4,225 | 8,192 | 98% |
Performance Impact
Benefits:
- Reduced vertex processing
- Lower memory bandwidth
- Faster rendering
- Better frame rates for large scenes
Costs:
- Rebuild time when changing LOD
- Potential visual popping during transitions
- Additional logic for LOD management
Optimization Tips
- Minimize LOD changes - Only rebuild when distance threshold crossed
- Add hysteresis - Use different thresholds for increasing/decreasing LOD
- Smooth transitions - Fade between LOD levels or use distance fog
- Cache LOD versions - Pre-generate and store multiple LOD levels
- Batch updates - Update multiple terrains in one frame
Visual Quality
Preventing Popping
LOD changes can cause visible "popping". Mitigation strategies:
Distance Fog:
// Use fog to hide distant terrain details
GorillaViewport1.FogEnabled := True;
GorillaViewport1.FogDistance := 300;
GorillaViewport1.FogColor := TAlphaColorRec.Skyblue;
Hysteresis:
const
LOD_THRESHOLDS_DECREASE = [0, 40, 120, 350]; // Going to lower detail
LOD_THRESHOLDS_INCREASE = [0, 60, 180, 450]; // Going to higher detail
var
LLastLOD: Integer = 0;
procedure UpdateLODWithHysteresis(ADistance: Single);
var
LNewLOD: Integer;
LThresholds: array[0..3] of Single;
begin
// Use different thresholds based on current LOD direction
if LDistance > FPreviousDistance then
LThresholds := LOD_THRESHOLDS_DECREASE // Moving away
else
LThresholds := LOD_THRESHOLDS_INCREASE; // Moving closer
// Calculate LOD (simplified)
LNewLOD := CalculateLOD(ADistance, LThresholds);
if LNewLOD <> LLastLOD then
begin
LTerrain.CurrentLOD := LNewLOD;
LTerrain.RebuildTerrain;
LLastLOD := LNewLOD;
end;
FPreviousDistance := LDistance;
end;
Morphing (Advanced): Blend between LOD levels in vertex shader (not built-in, requires custom shader).
Clustering Mode (Experimental)
The clustering system divides terrain into chunks with independent LOD levels.
Status: Not recommended for production use. Has known issues:
- Potential seams between clusters
- Incomplete async update implementation
- Performance overhead may outweigh benefits
If you want to experiment:
var
LTerrain: TGorillaCVLODTerrain;
begin
LTerrain := TGorillaCVLODTerrain.Create(Self);
LTerrain.Parent := GorillaViewport1;
LTerrain.Camera := Camera1; // Required for clustering
LTerrain.Width := 500;
LTerrain.Height := 50;
LTerrain.Depth := 500;
LTerrain.SetXYResolution(256, 256);
// Clustering configuration
LTerrain.LODLevels := 4;
LTerrain.ClusterSize := 32;
LTerrain.CameraMovementThreshold := 5.0;
LTerrain.UpdateInterval := 100;
LTerrain.AsyncUpdate := False; // Keep disabled
LTerrain.RebuildTerrain;
LTerrain.ForceUpdateLOD; // Update clusters
end;
Best Practices
- Use simple LOD mode -
CurrentLODproperty is stable and effective - Update on distance thresholds - Not every frame
- Add hysteresis - Prevent rapid switching
- Combine with culling - Don't render distant terrains at all
- Profile performance - Measure actual impact
- Consider alternatives - Paging, tiling, or streaming for huge worlds
See Also
- Gorilla.Terrain - Base terrain class
- Terrain User Guide - LOD usage examples