Terrain System

The Gorilla3D Terrain System provides powerful tools for creating realistic landscapes in your 3D applications. This guide covers everything you need to know about creating, customizing, and optimizing terrain in your games and simulations.

Table of Contents

Overview

The terrain system offers three main components:

  • TGorillaTerrain - Standard planar terrain from heightmaps or procedural algorithms
  • TGorillaSphereTerrain - Spherical/planetary terrain with heightmap deformation
  • TGorillaCVLODTerrain - Level-of-detail terrain by camera view with dynamic mesh optimization

Getting Started

Creating a Basic Terrain

The simplest way to create terrain is to drop a TGorillaTerrain component onto your viewport:

var
  LTerrain: TGorillaTerrain;
begin
  LTerrain := TGorillaTerrain.Create(Self);
  LTerrain.Parent := GorillaViewport1;
  LTerrain.Width := 100;
  LTerrain.Height := 20;
  LTerrain.Depth := 100;
  LTerrain.SetXYResolution(256, 256);
end;

Loading a Heightmap

Heightmaps are grayscale images where pixel brightness determines terrain height.

Runtime Loading

var
  LHeightMap: TBitmap;
begin
  LHeightMap := TBitmap.Create;
  try
    LHeightMap.LoadFromFile('terrain_heightmap.png');
    LTerrain.HeightMap := LHeightMap;
    LTerrain.RebuildTerrain;
  finally
    LHeightMap.Free;
  end;
end;

Design-Time Loading

You can load heightmaps directly in the IDE:

  1. Select the terrain component in the Structure View
  2. In the Object Inspector, find the HeightMap property
  3. Click the [...] button to open the bitmap editor
  4. Load your heightmap image
  5. The heightmap will be embedded in your form file (.fmx)

Benefits of Design-Time Loading:

  • Immediate visual feedback in the designer
  • No need for external file loading code
  • Heightmap is packaged with your application

Note: After loading a heightmap at design-time, click the viewport to refresh the display.

Resolution and Performance

Understanding Resolution

Resolution defines the number of vertices in your terrain grid. Higher resolution means more detail but requires more memory and processing power.

Recommended Resolutions:

  • 64 × 64 - Low detail, best for mobile
  • 128 × 128 - Medium detail, good balance
  • 256 × 256 - High detail (~66,000 vertices, 131,072 triangles, ~6.3MB)
  • 512 × 512 - Very high detail (~263,000 vertices, 524,288 triangles, ~25MB)
// Set resolution using property
LTerrain.Resolution := Point(256, 256);

// Or set X and Y separately
LTerrain.ResolutionX := 256;
LTerrain.ResolutionY := 256;

// Or use the method
LTerrain.SetXYResolution(256, 256);

Mobile Considerations

Important: Android has a maximum of 65,536 indices per mesh. Keep resolutions below 256×256 for mobile platforms.

Performance Optimization

Static Buffering

Enable static buffering to upload terrain data directly to GPU memory:

LTerrain.StaticBuffering := True;  // Default

// or use (1st parameter is for static buffering)
LTerrain.RebuildTerrain(True, False);

Note: Static buffering improves rendering performance but prevents showing debug visualizations (grid/vertices).

Mesh Decimation

Reduce vertex count while maintaining visual quality:

// Automatic decimation during rebuild
LTerrain.AutoDecimate := True;
LTerrain.RebuildTerrain;

// Manual decimation with custom parameters
LTerrain.RebuildTerrain(False, False);  // Keep mesh data in memory
LTerrain.Decimate(0.2, 3.0, 0.0001);
LTerrain.StaticBuffering := True;  // Upload to GPU after decimation

Decimation Parameters:

  • Ratio (0.0-1.0): Target reduction (0.2 = reduce to 20% of original)
  • Agression (default 3.0): Higher values = more aggressive reduction
  • Tolerance (default 0.0001): Smaller values = preserve more detail

Procedural Terrain Generation

Generate realistic terrain without heightmap images using procedural algorithms.

Available Algorithms

Hill Algorithm

Creates smooth rolling hills:

var
  LAlgorithm: THillRandomTerrain;
begin
  LAlgorithm := THillRandomTerrain.Create;
  try
    LAlgorithm.Size := 9;           // Grid size (2^9+1 = 513x513)
    LAlgorithm.Hills := 20;         // Number of hills
    LAlgorithm.MinRadius := 10;     // Minimum hill radius
    LAlgorithm.MaxRadius := 100;    // Maximum hill radius
    LTerrain.RandomTerrain(LAlgorithm);
  finally
    LAlgorithm.Free;
  end;
end;

// Or use the simple version
LTerrain.RandomTerrain(TRandomTerrainAlgorithmType.Hill);

Diamond Square Algorithm

Popular algorithm for realistic terrain with valleys and peaks:

var
  LAlgorithm: TDiamondSquareTerrain;
begin
  LAlgorithm := TDiamondSquareTerrain.Create;
  try
    LAlgorithm.Size := 9;      // Grid size
    LAlgorithm.MSeed := 1000;  // Random seed
    LTerrain.RandomTerrain(LAlgorithm);
  finally
    LAlgorithm.Free;
  end;
end;

Perlin Noise

Smooth, natural-looking terrain with configurable interpolation:

var
  LAlgorithm: TPerlinNoiseTerrain;
begin
  LAlgorithm := TPerlinNoiseTerrain.Create;
  try
    LAlgorithm.Size := 7;
    LAlgorithm.Intensity := 0.25;
    LAlgorithm.Interpolation := TPerlinNoiseInterpolation.Cosine;
    LAlgorithm.DiamondSquareFactor := 0.75;
    LAlgorithm.DiamondSquareEnabled := True;
    LTerrain.RandomTerrain(LAlgorithm);
  finally
    LAlgorithm.Free;
  end;
end;

Interpolation Types:

  • Linear - Fast, sharp edges
  • Cosine - Smooth, natural (default)
  • Cubic - Very smooth, slower

Plateau Terrain

Creates flat elevated areas surrounded by lower terrain:

var
  LAlgorithm: TPlateauTerrain;
begin
  LAlgorithm := TPlateauTerrain.Create;
  try
    LAlgorithm.Size := 9;
    LAlgorithm.Plateaus := 3;          // Number of plateaus
    LAlgorithm.MinSize := 50;          // Minimum radius
    LAlgorithm.MaxSize := 250;         // Maximum radius
    LAlgorithm.MinHeight := 0.25;      // Minimum height factor
    LAlgorithm.MaxHeight := 1.0;       // Maximum height factor
    LAlgorithm.Inverted := False;      // True for lowlands instead
    LTerrain.RandomTerrain(LAlgorithm);
  finally
    LAlgorithm.Free;
  end;
end;

Brownian Terrain

Particle-based terrain with smooth deformation:

var
  LAlgorithm: TBrownianTerrain;
begin
  LAlgorithm := TBrownianTerrain.Create;
  try
    LAlgorithm.Size := 9;
    LAlgorithm.Particles := 3000;      // More = more detail, slower
    LAlgorithm.MinHeight := 0.01;
    LAlgorithm.MaxHeight := 0.05;
    LTerrain.RandomTerrain(LAlgorithm);
  finally
    LAlgorithm.Free;
  end;
end;

Mandelbrot and Planar

  • Mandelbrot - Creates the famous fractal pattern (fixed, good as a base)
  • Planar - Flat terrain, useful as a starting point for custom modification

Design-Time Generation

You can generate procedural terrain directly in the IDE without writing code:

  1. Drop a TGorillaTerrain component onto your viewport
  2. Right-click the terrain component in the Structure View
  3. Navigate to the "Random Terrain" submenu
  4. Select one of the available algorithms:
    • Hill
    • DiamondSquare
    • Mandelbrot
    • PerlinNoise
    • Plateau
    • Brownian
    • Planar
  5. Click the viewport to refresh the display

Benefits:

  • Quick prototyping and experimentation
  • No code required for basic terrain
  • Immediate visual feedback
  • Generated heightmap is embedded in your form

Customization: The design-time generators use default parameters. For fine-tuned control, use the runtime approach with custom algorithm properties.

g3d-ide-terrain

Advanced Features

Smoothing

Smooth heightmaps that are lower resolution than your terrain grid:

LTerrain.Smoothing := 5;  // Range: 0-20, higher = smoother

Smoothing applies blur iterations to the heightmap before generating vertices. Set to 0 to disable.

Two-Sided Rendering

Render both front and back faces of terrain triangles:

LTerrain.TwoFace := True;

Note: Keep this False (default) for better performance. Only enable if you need to see terrain from below.

Debug Visualization

Visualize terrain structure during development:

// Show vertex points
LTerrain.ShowVertices := True;
LTerrain.VerticeColor := TAlphaColorRec.Yellow;

// Show polygon grid
LTerrain.ShowGrid := True;

Important: Debug visualization only works when StaticBuffering := False. Disable in production builds.

Update Management

Use BeginUpdate/EndUpdate to batch property changes:

LTerrain.BeginUpdate;
try
  LTerrain.Width := 200;
  LTerrain.Height := 50;
  LTerrain.Resolution := Point(512, 512);
  LTerrain.Smoothing := 10;
finally
  LTerrain.EndUpdate;  // Rebuilds once
end;

Planting System

The planting feature allows you to automatically populate terrain with vegetation, rocks, or other objects. It's an instancing system that adjusts models to follow terrain topology.

How Planting Works

The planting algorithm:

  1. Divides terrain into a grid of cells
  2. Places instances inside of grid cells regularly or randomly
  3. Adjusts each instance's Y-position to match terrain height
  4. Optionally randomizes scale and rotation
  5. Treats all submeshes in the source model equally

Important: All submeshes inside the source model are treated equally when creating instances.

Design-Time Planting

Configure planting directly in the IDE:

  1. Select your terrain component
  2. Right-click the component and select the Planting option
  3. Select the source mesh on top
  4. Setup parameters for automatic placement

g3d-ide-planting-1

Source Models

The planting algorithm is straight forward and treats all submeshes inside the source model equaly on creating instances. Therefore it can produce unexpected results.

The source model should contain a flat hierarchy without or less transformation of sub-meshes.

NOTICE: The applied instance transformation is absolute and not relative to the source model.

Configuration

The algorithm will create instances for all meshes inside the selected template / source model.

Basically the algorithm splits the terrain into cells for more realistic placement.

Setting Description
Clear Instances Clears all previously available instances in the source.
Minimum Scale If “Random Scaling” is activated, this is the lowest limit for scaling.
Instance Scale A basis scaling of each instance (will be multiplied with source scale if “Apply Source Transformation” is activated.
Space Adjustment between cell-center and source size.
Padding Increasing this value will compress cells for planting. Objects will be placed closer together.
Random Y-Rotation This is not suitable for all kind of source models. Depending on the internal transformation of submeshes.
Random Scaling This will randomly scale instances with limitations given by “Minimum Scale”.
Apply Random Grid-Offset Terrain is splitted into equal size grid cells. To produce a more realistic look, you can add some random offset to the cell-center.
Apply Source Transformation It will apply the transformation of the owner model. This is not suitable for all kind of models, depending on the internal transformation of submeshes.
Count The number of instances that should be created. This should be adjusted to the GPU you are using and the outcome you expect.

g3d-ide-planting-2

Spherical Terrain

Create planetary terrain with TGorillaSphereTerrain:

var
  LSphereTerrain: TGorillaSphereTerrain;
begin
  LSphereTerrain := TGorillaSphereTerrain.Create(Self);
  LSphereTerrain.Parent := GorillaViewport1;
  LSphereTerrain.Width := 50;
  LSphereTerrain.Height := 50;
  LSphereTerrain.Depth := 50;
  LSphereTerrain.SetXYResolution(512, 512);
  LSphereTerrain.HeightScale := 0.1;  // Controls deformation amount

  // Load heightmap for planet surface
  LSphereTerrain.HeightMap := MyPlanetHeightMap;
  LSphereTerrain.RebuildTerrain;
end;

The sphere terrain uses the same algorithms as planar terrain but deforms a sphere surface instead of a flat plane.

LOD Terrain

TGorillaCVLODTerrain provides level-of-detail optimization for large terrains. It stands for Camera-View-Level-Of-Detail-Terrain.

var
  LLODTerrain: TGorillaCVLODTerrain;
begin
  LLODTerrain := TGorillaCVLODTerrain.Create(Self);
  LLODTerrain.Parent := GorillaViewport1;
  LLODTerrain.Camera := Camera1;  // Required for distance calculations
  LLODTerrain.Width := 500;
  LLODTerrain.Height := 50;
  LLODTerrain.Depth := 500;
  LLODTerrain.SetXYResolution(256, 256);

  // LOD configuration
  LLODTerrain.CurrentLOD := 0;              // 0 = highest detail
  LLODTerrain.LODLevels := 4;               // Number of detail levels
  LLODTerrain.ClusterSize := 32;            // Vertices per cluster
  LLODTerrain.CameraMovementThreshold := 5.0;  // Update sensitivity
  LLODTerrain.UpdateInterval := 100;        // Update frequency (ms)

  LLODTerrain.RebuildTerrain;
end;

Note: The LOD clustering system is experimental. For best results, use the CurrentLOD property to test different detail levels.

Materials and Texturing

Apply materials to terrain using material sources:

var
  LMaterial: TGorillaLambertMaterialSource;
begin
  LMaterial := TGorillaLambertMaterialSource.Create(Self);
  LMaterial.Diffuse := 'grass_texture.png';
  LMaterial.Normal := 'grass_normal.png';
  LTerrain.MaterialSource := LMaterial;
end;

Texture coordinates are automatically generated based on terrain position (0,0 to 1,1).

Custom Algorithms

Create custom procedural terrain by extending TRandomTerrainAlgorithm:

type
  TMyCustomTerrain = class(TRandomTerrainAlgorithm)
  protected
    procedure Generate;
  public
    function GetHeightMap: TBitmap; override;
  end;

procedure TMyCustomTerrain.Generate;
var
  x, y: Integer;
begin
  FWidth := 513;
  FHeight := 513;
  SetLength(FData, FWidth);
  for x := 0 to FWidth - 1 do
  begin
    SetLength(FData[x], FHeight);
    for y := 0 to FHeight - 1 do
    begin
      // Your custom height calculation
      FData[x][y] := YourHeightFunction(x, y);  // Range 0.0 to 1.0
    end;
  end;
end;

function TMyCustomTerrain.GetHeightMap: TBitmap;
begin
  Generate;
  Result := inherited GetHeightMap;  // Converts FData to bitmap
end;

Best Practices

Memory Management

  1. Use appropriate resolution for your target platform
  2. Enable StaticBuffering for terrains that don't change
  3. Free heightmap bitmaps after loading if not needed
  4. Use decimation to reduce polygon count

Visual Quality

  1. Start with resolution matching your heightmap size
  2. Use smoothing for upscaled heightmaps
  3. Apply normal maps for enhanced detail without geometry
  4. Combine multiple algorithms for varied terrain

Performance

  1. Keep mobile terrain under 256×256 resolution
  2. Disable TwoFace unless absolutely needed
  3. Turn off debug visualization in production
  4. Use LOD terrain for large landscapes
  5. Profile vertex/triangle counts with GetLODStatistics

Workflow

  1. Prototype with procedural algorithms
  2. Fine-tune with custom heightmaps
  3. Optimize with decimation
  4. Apply materials and lighting
  5. Test on target hardware

Troubleshooting

Terrain appears flat

  • Check that heightmap is assigned and not empty
  • Verify Height property is set to appropriate scale
  • Ensure HeightScale is not 0 (for sphere terrain)

Performance issues

  • Reduce Resolution
  • Enable AutoDecimate or manually call Decimate()
  • Verify StaticBuffering is enabled
  • Check triangle count (256×256 = ~131K triangles)

Heightmap not loading

  • Verify image format (PNG, BMP, JPG supported)
  • Check image is grayscale or color (uses luminance)
  • Ensure file path is correct

Debug visualization not showing

  • Set StaticBuffering := False
  • Rebuild terrain
  • Check ShowVertices or ShowGrid is True

See Also

API Reference

Related Topics