Drawing

Terrain from height maps

A map engine's ground comes as tiles of heights: a small grid of numbers per tile, at every level of a quadtree. This page shows how to turn them into terrain on the GPU: one shared grid that each tile lifts with its own heights, a box that culling can trust, skirts that hide the cracks between levels, normals that match across tiles, imagery on top, and a flat tile bent onto a planet. The last part shows how RASM does it. Which tiles to load is in Tile streaming under a memory budget.

In short

  • A tile is a height map: (n + 1)² heights for n × n cells, plus a border of one sample around them. 16 bits a sample is enough.
  • Every tile shares one grid mesh. The vertex shader reads the tile's heights and lifts each vertex. No mesh per tile.
  • The grid is a unit box, and the tile's transform stretches it to the tile's size and height range. So culling sees the real bounds.
  • Tiles of different levels leave cracks along their edges. A skirt, a strip hanging down under each edge, hides them.
  • Normals come from the heights around each vertex. The border gives the edge vertices the same four neighbours in both tiles, so the light has no seam.
  • Heights stored on one shared grid of steps (a power of two) are bit-equal on a shared edge.
  • On a planet, a flat tile drops by d² / 2R at d from its centre: 5 cm off the true sphere at 100 km.

1The problem

The simple way builds a mesh for each tile on the CPU: a vertex per height, with its position, normal and texture coordinates. That is a lot of bytes for what is only a number per point, and the CPU builds and uploads it for every tile that arrives.

A mesh per tile

tile 1 mesh tile 2 mesh 64 B a vertex: position, normal, uv, tangent ~100 KiB a tile

The CPU builds every vertex, and each tile's mesh takes its own space in the vertex buffers.

Heights per tile, one shared grid

one grid heights, 2 B each 2.4 KiB a tile the GPU lifts the grid

A tile is a small texture. The vertex shader reads it and moves each vertex of the shared grid up.

2A height map

A height map is a grid of samples, one per point of the tile's grid. For n × n cells there are (n + 1)² points. Add one more sample around them, the border: it belongs to the neighbour tiles, and section 5 needs it. So a tile of n cells has (n + 3)² samples.

4 × 4 cells: 5 × 5 points (green), 7 × 7 samples with the border (amber) One sample to metres 0x0C40 a 16-bit value: 3136 offset + scale × 3136 metres: 512 + 1/16 × 3136 = 708 m 16 bits give 65 536 steps. At 1/16 m a step, one tile covers 4096 m of height: enough for any tile, since each tile has its own offset.
Grid point (i, j) is sample (i + 1, j + 1). A 32-bit float sample can hold metres directly; 16 bits with an offset per tile is half the size and as precise where it matters.

3Lift a shared grid on the GPU

Every tile with n cells draws the same grid mesh. Its vertices know only where they are in the grid. The vertex shader reads the tile's height at that point and puts the vertex there. A big trick makes culling work too: the grid is a unit box, and the tile's transform stretches the box to the tile.

1. the shared grid a unit box: y from 0 to 1 2. vertex shader h = offset + scale × sample sample at grid point (i, j) y = (h − lowest) / range skirt vertex: h − skirt normal from 4 neighbours 3. the tile's transform range scale = (size, range, size)
The box runs from the tile's lowest height to its highest. Culling transforms the grid's bounding sphere with the tile's matrix, as for any mesh, and gets a sphere around the real terrain. No per-tile bounds are needed.
12

Two triangles a cell

Split along the same diagonal everywhere. A point inside a cell is on one of the two flat triangles.

one texel,no filtering

Exact samples

The shader loads the texel of its grid point. Nothing is filtered, so the CPU can compute the same height.

Every pass lifts it

The shadow pass and the main pass run the same lifting code, so the terrain casts and receives its own shadows.

4Cracks between levels, and skirts

Next to a fine tile, a coarse tile has fewer points along their shared edge. The fine edge follows the hills between the coarse points; the coarse edge is a straight line there. The two edges part, and the sky shows through the gap.

The crack coarse edge: 2 points fine edge: 5 points the gap between them: the sky shows A skirt fills it a strip hangs down from each edge
The skirt is one more row of vertices under each edge, at the edge's height minus the skirt's length, joined to the edge by a strip. It is part of the same grid, so it costs a few triangles a tile and no extra draw.

The skirt must be at least as long as the largest gap. The gap grows with the hills and with the difference of levels: one level of difference leaves at most the coarse tile's own error. Try it.

Raise the hills until the gap shows, then lengthen the skirt until it covers the gap everywhere.

5Normals that match across tiles

A vertex's normal comes from the slope of the heights around it: the difference of the samples left and right, and before and behind. At a tile's edge, one of those samples is in the neighbour tile. Without the border, the edge vertex only has a one-sided difference, and its neighbour across the edge has the other side. The light then breaks along every tile edge.

No border: one-sided slopes

left tile's slope right tile's slope

Two normals at one point: a line of light along the edge.

A border of one sample

both tiles: the same two samples

The border sample is the neighbour's first inner sample. Both tiles compute the same central difference.

Bit-equal edges

Two tiles share an edge's samples, but each stores them from its own offset. Put every height on one world grid of steps first, with a step that is a power of two (1/16 m), and give each tile an offset that is a whole number of steps. Then offset + scale × value is exact in floats, and both tiles get the same bits on the edge, on the CPU and on the GPU alike.

6Imagery on top

The color of the ground is an image per tile, draped over it by the grid's texture coordinates: (0, 0) at one corner, (1, 1) at the other. A tile does not need an image of its own level.

0 … 1

Its own image

The usual case: the tile's image covers it exactly.

child

A part of the parent's

A child can show a quarter of its parent's image, by an offset and a scale, until its own arrives.

clamp

Clamped edges

A repeating sampler would blend the left edge into the right one. Clamp it.

7A flat tile on a round planet

On a globe, each tile lives in its own local frame (east, up, north at its centre). A flat tile is tangent to the planet at its centre. Away from the centre the planet falls away below the plane, so neighbour tiles, tangent at different points, would not meet. Bend each vertex down by the drop of a sphere.

drop d² / 2R d The flat tile (blue) is tangent at its centre; the planet (thick) falls below it. The parabola d² / 2R is the sphere's drop to within d⁴ / 8R³.
The true drop of a sphere is R − √(R² − d²). Its series starts with d² / 2R; the next term, d⁴ / 8R³, is how far the parabola is from the sphere.

drop(d) = d² / 2R

sphere − parabola ≈ d⁴ / 8R³

d
metres from the tile's centre, across its plane
R
the planet's radius: 6 371 km for the Earth
7.8 mdrop 10 km from the centre10 000² / (2 · 6 371 000)
785 mdrop 100 km from the centre100 000² / (2 · 6 371 000)
5 µmparabola off the sphere at 10 km10 000⁴ / (8 · 6 371 000³)
5 cmparabola off the sphere at 100 km100 000⁴ / (8 · 6 371 000³)

So tiles up to a few hundred kilometres sit on the globe to a few centimetres. The roots of a whole-globe tree (a hemisphere each) need a curved grid instead: this bending is not enough there.

8Pitfalls

Holes along some tile edges, more where the hills are steep
The skirt is shorter than the gap between two levels. Make it at least the coarser tile's geometric error, more for steep ground.
A line of light along every tile edge
One-sided slopes at the edges: give each tile a border of one sample, from its neighbours' heights.
Tiles pop out of view at the screen's edge, or behind a hill
The bounds are the flat grid's, not the lifted terrain's. Stretch the unit box to the tile's height range, so culling sees the real bounds.
A thin line of the wrong color at a tile's edge
The imagery repeats: sample it with clamping.
Neighbour tiles do not meet on a globe
Each tile is flat in its own frame. Bend it by d² / 2R, or use smaller tiles near the roots.
Steps on smooth slopes
8-bit heights. Use 16 bits (or floats) with an offset per tile.

9In RASM

A terrain tile is an ordinary entity: a TERRAIN material that holds the tile's heights, on the shared grid of Renderer::getTerrainMesh, with the transform of getTerrainTransform. So it goes through the same GPU culling, occlusion culling, shadows, TAA and MSAA as any mesh, and it is a tile's content for the TileStreamer like any other.

the application textures and rows shaders
application heights: R16_UNORM,(cells + 3)² samples imagery: RGBA8 sRGB createTerrainTile renderer material row: TerrainData heights, scale, offset, minHeight, skirt, radius entity on getTerrainMesh(cells), shared by all transform: the tile's boxgetTerrainTransform shaders getVertexOutput(rasm.slang) getDepthPosition(shadow.slang) getTerrainVertex(lib/terrain.slang)
Only a TERRAIN material's draws take the branch: the vertex stage reads the instance's material id, which is the same for the whole draw. The fragment stage shades the tile as PBR, with the lifted normal and the imagery as base color.
// From examples/24_map_tiles/main.cpp, shortened: a tile's heights and image came from the server.
rasm::TextureHandle heights = engine.createTexture({.name = "Tile Heights", .width = HEIGHTS_WIDTH, .height = HEIGHTS_WIDTH, .format = rasm::Format::R16_UNORM, .usage = rasm::TextureUsage::SAMPLED});
engine.getRenderContext().fillTexture(heights, data.heights.data());
const rasm::TerrainTile terrain = engine.createTerrainTile({.center = tileOrigin(node.level, node.x, node.y),
                                                            .size = size,
                                                            .terrain = {.heights = heights,
                                                                        .heightScale = static_cast<float>(HEIGHT_STEP),
                                                                        .heightOffset = data.heightOffset,
                                                                        .minHeight = data.minHeight,
                                                                        .maxHeight = data.maxHeight,
                                                                        .skirt = static_cast<float>(size * SKIRT)},
                                                            .imagery = image,
                                                            .roughness = 0.95f});
// The grid is shared, so the content lists the entity, the material and the two textures, and not the mesh.
streamer.setTileContent(node.tile, {.entities = entities, .entityCount = 1, .materials = materials, .materialCount = 1, .textures = textures, .textureCount = 2});

Where RASM follows this page, and where it differs

TopicThis pageRASM
Heights16 bits with an offset, or floatsR16_UNORM (a sample is its integer, 0 to 65535) or R32_SFLOAT; metres = heightOffset + heightScale × sample (TerrainMaterial). The cells are the texture's width − 3, from 1 to MAX_TERRAIN_CELLS (256).
The gridshared, a unit boxgetTerrainMesh(cells): (cells + 1)² vertices at y = 1 and a skirt of 4 (cells + 1) at y = 0, made once per size and kept until the renderer goes. No LODs and no meshlets (their bounds would be the flat grid's). destroyMesh refuses it.
Boxlowest to highest heightgetTerrainTransform: minHeight lowered by the skirt and by the curvature at the corners, to maxHeight, so the skirts are inside it too; at least 1 mm high.
Skirtsat least the largest gapTerrainMaterial::skirt, in metres, chosen by the application (24_map_tiles: 5% of the tile's width).
Normalscentral differences with a borderPer vertex, in getTerrainVertex, from the four samples around it, with the curvature's slope; interpolated across the triangle. The fragment stage has no normal map for terrain.
Imageryits own, or a part of the parent'sThe base color: TerrainTileDesc::imagery, with imageryRect as its texture transform; a slot made by createTerrainTile clamps.
Curvatured² / 2RTerrainMaterial::sphereRadius; 0 is flat.
The CPU's heightthe same rulesampleTerrainHeight and getTerrainPosition: the two triangles of a cell, split from (0, 1) to (1, 0), with corners computed in floats as the shader does; for placing objects and cameras, and to check a picked point. Vector features draped on a tile use it too (Draping on terrain).
Changes between levels—None: a tile swaps at once (no geomorphing between levels).
2.4 KiBa tile's heights in 24_map_tiles: 35 × 35 samples, 32 × 32 cellsthe 17 × 17 mesh it had took 31 KiB for 16 × 16 cells
0.03 msupdate on average over a 1500-frame flight, 48 MiB heldRelease, headless, RTX 3060
2.6 msthe longest frame after the first 304 tiles uploaded a frame

Where it lives in code

WhatWhere
The APITerrainTileDesc, TerrainTile, TerrainHeights, getTerrainTransform, sampleTerrainHeight, getTerrainPosition in include/rasm/terrain.h; TerrainMaterial, MaterialType::TERRAIN in include/rasm/material.h; Renderer::getTerrainMesh, Renderer::createTerrainTile
The grid and the CPU rulebuildTerrainGrid (src/scene/terrain.h) and the rest in src/scene/terrain.cpp
The material rowgfx::TerrainData in MaterialData (src/renderer/uberMaterialTypes.h, shaders/lib/core.slang), written by toMaterialData in src/renderer/gpuScene.cpp
Lifting the gridgetTerrainVertex in shaders/lib/terrain.slang, called by getVertexOutput (shaders/passes/rasm.slang) and getDepthPosition (shaders/passes/shadow.slang)
The C API (1.4)rasm_create_terrain_tile, rasm_get_terrain_mesh, rasm_get_terrain_transform, rasm_sample_terrain_height, rasm_get_terrain_position in src/c/cTerrain.cpp
Teststests/terrainTests.cpp (the grid, the triangle rule, bit-equal edges, the box, the curvature); the image tests terrain and far_terrain (two levels side by side, no seam)
Exampleexamples/24_map_tiles: a 32 km quadtree of terrain tiles made on 3 server threads, streamed under 48 MiB
Keep these true
  • sampleTerrainHeight and getTerrainVertex follow one rule: the same sample for a grid point, the same diagonal, the same float sum. A change to one changes the other, and tests/terrainTests.cpp.
  • Every pass that pulls vertices lifts a TERRAIN draw: the main pass, the shadow pass and the pick pass (Picking), whose hit on a tile lies on the surface getTerrainPosition gives.
  • The grid has no meshlets and no LODs: their bounds and cones come from the flat grid.
  • A tile's content never lists the grid: every tile of that size shares it.
Not done yet

Whole-globe roots: the bending is a parabola for tiles up to a few hundred kilometres, and the roots of a globe's tree need a curved grid (D44). No geomorphing: a tile swaps at once when the cut changes. A heights file from disk (a 16-bit PNG) loads as 8 bits (D36), so the application fills the texture itself.

Further reading