W3: Chunked terrain mesh, collision and LOD

TerrainView draws the island as 16 x 16 chunks of 64 m, each at one of
four detail levels (2, 4, 8 and 16 m spacing) chosen by distance to the
camera. TerrainChunkBuilder builds chunk geometry on WorkerThreadPool
threads; the main thread only uploads finished meshes, within a 2 ms
per-frame budget, nearest chunks first.

- Seams: every chunk hangs skirts deeper than twice the most any level
  strays from the full-resolution edge, so neighbours at any two levels
  meet without a crack. Normals come from the full-resolution heightfield
  at every level, and back faces light like the ground above them.
- Splat material: a procedural shader blends sand, marsh, grass and rock
  with weights from the island's bands, averaged over 4 m so borders
  blend. Steep ground turns to rock and summits weather pale.
- Collision stays SimGround's heightfield, with no renderer involved.
- Capture scenarios terrain, terrain_lod (tinted by level) and
  terrain_cracks (magenta sky). tools/crack_check.gd counts sky pixels
  seen through the ground; make terrain-capture requires cracks in a
  skirtless control and none in the real terrain.

Tests: chunk vertices sit on the heightfield; skirts cover every pairing
of levels on sampled shared edges; detail falls with distance; flying
across the island at 30 m/s for 2,037 frames streams 661 chunk rebuilds
with the worst main-thread frame at 0.8 to 1.4 ms (headless, CPU only);
24 players over 900 ticks on two generated islands never sink into the
ground, and a player sprints up towards a summit unharmed.
make terrain-capture: control 437 crack pixels, terrain 0.

Closes #10

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 14:28:30 -05:00
co-authored by Claude Opus 5.5
parent c70d0c1c4f
commit 8b74485168
22 changed files with 840 additions and 1 deletions
+81
View File
@@ -0,0 +1,81 @@
// Tidewall terrain: four procedural layers (sand, marsh, grass, rock) blended by the
// splat weights in the vertex colour, with rock taking over on steep ground and weathered
// pale stone on the summits. No textures: every pattern is generated here.
shader_type spatial;
render_mode cull_disabled;
uniform float summit_height = 50.0;
uniform float max_slope_cos = 0.69;
uniform vec3 sand_colour : source_color = vec3(0.80, 0.71, 0.52);
uniform vec3 marsh_colour : source_color = vec3(0.37, 0.39, 0.25);
uniform vec3 grass_colour : source_color = vec3(0.31, 0.42, 0.22);
uniform vec3 rock_colour : source_color = vec3(0.47, 0.44, 0.39);
uniform vec3 summit_colour : source_color = vec3(0.74, 0.72, 0.67);
// Debug: tint each chunk by its level of detail (set per instance by TerrainView).
instance uniform float lod_tint = -1.0;
varying vec3 world_position;
varying vec3 world_normal;
float hash(vec2 p) {
p = fract(p * vec2(123.34, 456.21));
p += dot(p, p + 45.32);
return fract(p.x * p.y);
}
float value_noise(vec2 p) {
vec2 i = floor(p);
vec2 f = fract(p);
vec2 u = f * f * (3.0 - 2.0 * f);
return mix(mix(hash(i), hash(i + vec2(1.0, 0.0)), u.x),
mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), u.x), u.y);
}
float fbm(vec2 p) {
float total = 0.0;
float amplitude = 0.5;
for (int octave = 0; octave < 4; octave++) {
total += amplitude * value_noise(p);
p *= 2.03;
amplitude *= 0.5;
}
return total;
}
void vertex() {
world_position = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz;
world_normal = normalize((MODEL_MATRIX * vec4(NORMAL, 0.0)).xyz);
}
void fragment() {
vec2 p = world_position.xz;
float broad = fbm(p * 0.035);
float fine = fbm(p * 0.6);
float ripple = 0.5 + 0.5 * sin(dot(p, vec2(0.55, 0.32)) + broad * 9.0);
vec3 sand = sand_colour * (0.9 + 0.12 * fine) * (0.97 + 0.04 * ripple);
vec3 marsh = mix(marsh_colour * 0.75, marsh_colour * 1.1, smoothstep(0.35, 0.65, broad + 0.2 * fine));
vec3 grass = grass_colour * (0.78 + 0.35 * broad) * (0.9 + 0.15 * fine);
grass = mix(grass, grass * vec3(1.15, 1.05, 0.7), smoothstep(0.55, 0.75, broad));
float strata = 0.5 + 0.5 * sin(world_position.y * 2.1 + broad * 5.0);
vec3 rock = rock_colour * (0.82 + 0.22 * fine + 0.1 * strata);
vec3 summit = summit_colour * (0.88 + 0.14 * fine);
rock = mix(rock, summit, smoothstep(summit_height - 4.0, summit_height + 4.0, world_position.y + 3.0 * broad));
vec4 weights = max(COLOR, vec4(0.0));
float steep = 1.0 - smoothstep(max_slope_cos - 0.08, max_slope_cos + 0.12, world_normal.y);
weights = mix(weights, vec4(0.0, 0.0, 0.0, 1.0), steep);
weights /= max(weights.r + weights.g + weights.b + weights.a, 0.0001);
vec3 albedo = sand * weights.r + marsh * weights.g + grass * weights.b + rock * weights.a;
if (lod_tint >= 0.0) {
vec3 tints[4] = vec3[](vec3(1.0, 0.5, 0.5), vec3(0.5, 1.0, 0.5), vec3(0.5, 0.6, 1.0), vec3(1.0, 1.0, 0.4));
albedo *= tints[int(lod_tint) % 4];
}
ALBEDO = albedo;
// Skirts and any face seen from below must light like the ground above them, so
// use the terrain normal for both faces instead of the flipped back-face normal.
NORMAL = normalize((VIEW_MATRIX * vec4(world_normal, 0.0)).xyz);
ROUGHNESS = mix(0.95, 0.6, weights.g);
SPECULAR = 0.2;
}
+1
View File
@@ -0,0 +1 @@
uid://c7ee5h5pe6qjq
+178
View File
@@ -0,0 +1,178 @@
## Builds render-mesh arrays for one square chunk of the island's heightfield at one
## level of detail. Pure and thread-safe: it only reads the heightfield and bands, so
## TerrainView runs it on worker threads and only uploads meshes on the main thread.
##
## Seams: every chunk hangs a skirt, a vertical strip of triangles, from each edge down
## by more than any level of detail can disagree with any other along that edge. A
## neighbour at a different detail level then meets a wall instead of a gap, so there
## are never cracks to see through. Normals come from the full-resolution heightfield at
## every level, so lighting matches across a level boundary.
##
## Splat weights go in the vertex colour: r sand, g marsh, b grass, a rock. The terrain
## shader blends procedural layers with them.
class_name TerrainChunkBuilder
extends RefCounted
## Heightfield cells along a chunk's side. 32 cells of 2 m make 64 m chunks.
const CHUNK_CELLS: int = 32
## Sample step at each level of detail. Level 0 is full resolution.
const LOD_STEPS: Array[int] = [1, 2, 4, 8]
const SKIRT_MARGIN: float = 0.5
## Samples either side that splat weights are averaged over.
const WEIGHT_RADIUS: int = 2
const _BAND_WEIGHTS: Dictionary = {
Island.Band.SEA: Color(1.0, 0.0, 0.0, 0.0),
Island.Band.BEACH: Color(1.0, 0.0, 0.0, 0.0),
Island.Band.MARSH: Color(0.0, 1.0, 0.0, 0.0),
Island.Band.FOREST: Color(0.0, 0.0, 1.0, 0.0),
Island.Band.HIGHLAND: Color(0.0, 0.0, 0.0, 1.0),
Island.Band.SUMMIT: Color(0.0, 0.0, 0.0, 1.0),
}
## Chunks along each side of the world.
static func chunks_per_side(ground: SimGround) -> int:
return (ground.samples - 1) / CHUNK_CELLS
## World-space bounds of a chunk's footprint, as (min x, min z, size).
static func chunk_rect(ground: SimGround, chunk: Vector2i) -> Rect2:
var size: float = CHUNK_CELLS * ground.cell
return Rect2(chunk.x * size, chunk.y * size, size, size)
## Mesh arrays for `chunk` at level `lod`, ready for ArrayMesh.add_surface_from_arrays.
## Vertices are in world space. `skirts` is false only for the capture that proves the
## crack check can see cracks.
static func build(ground: SimGround, bands: PackedByteArray, chunk: Vector2i, lod: int, skirts: bool = true) -> Array:
var step: int = LOD_STEPS[lod]
var per_side: int = CHUNK_CELLS / step + 1
var origin: Vector2i = chunk * CHUNK_CELLS
var samples: int = ground.samples
var heights: PackedFloat32Array = ground.heights
var cell: float = ground.cell
var vertices: PackedVector3Array = PackedVector3Array()
var normals: PackedVector3Array = PackedVector3Array()
var colours: PackedColorArray = PackedColorArray()
var uvs: PackedVector2Array = PackedVector2Array()
var total: int = per_side * per_side + 4 * per_side
vertices.resize(total)
normals.resize(total)
colours.resize(total)
uvs.resize(total)
for row: int in per_side:
for column: int in per_side:
var gx: int = origin.x + column * step
var gz: int = origin.y + row * step
var index: int = row * per_side + column
var at: int = gz * samples + gx
vertices[index] = Vector3(gx * cell, heights[at], gz * cell)
normals[index] = _normal(heights, samples, cell, gx, gz)
colours[index] = _weights(bands, samples, gx, gz)
uvs[index] = Vector2(gx, gz) * cell
var indices: PackedInt32Array = PackedInt32Array()
for row: int in per_side - 1:
for column: int in per_side - 1:
var a: int = row * per_side + column
var b: int = a + 1
var c: int = a + per_side
var d: int = c + 1
indices.append_array(PackedInt32Array([a, b, c, b, d, c]))
var depth: float = skirt_depth(ground, chunk) if skirts else 0.0
var skirt_start: int = per_side * per_side
# Edges in order: north (row 0), south (last row), west (column 0), east (last column).
for edge: int in 4:
for position: int in per_side:
var top: int = _edge_vertex(edge, position, per_side)
var index: int = skirt_start + edge * per_side + position
vertices[index] = vertices[top] - Vector3(0.0, depth, 0.0)
normals[index] = normals[top]
colours[index] = colours[top]
uvs[index] = uvs[top]
for position: int in per_side - 1:
var top_a: int = _edge_vertex(edge, position, per_side)
var top_b: int = _edge_vertex(edge, position + 1, per_side)
var low_a: int = skirt_start + edge * per_side + position
var low_b: int = low_a + 1
indices.append_array(PackedInt32Array([top_a, top_b, low_a, top_b, low_b, low_a]))
var arrays: Array = []
arrays.resize(Mesh.ARRAY_MAX)
arrays[Mesh.ARRAY_VERTEX] = vertices
arrays[Mesh.ARRAY_NORMAL] = normals
arrays[Mesh.ARRAY_COLOR] = colours
arrays[Mesh.ARRAY_TEX_UV] = uvs
arrays[Mesh.ARRAY_INDEX] = indices
return arrays
## How far the skirts hang below a chunk's edges: twice the most that any level of
## detail strays from the full-resolution edge, plus a margin. Two neighbours share
## each edge, so this covers any pairing of levels.
static func skirt_depth(ground: SimGround, chunk: Vector2i) -> float:
var worst: float = 0.0
var origin: Vector2i = chunk * CHUNK_CELLS
for edge: int in 4:
for step: int in LOD_STEPS:
for position: int in CHUNK_CELLS + 1:
var low: int = (position / step) * step
var high: int = mini(low + step, CHUNK_CELLS)
var t: float = 0.0 if high == low else float(position - low) / float(high - low)
var exact: float = _edge_height(ground, origin, edge, position)
var coarse: float = lerpf(_edge_height(ground, origin, edge, low), _edge_height(ground, origin, edge, high), t)
worst = maxf(worst, absf(exact - coarse))
return 2.0 * worst + SKIRT_MARGIN
## Splat weights averaged over the samples within WEIGHT_RADIUS, so layer borders blend
## over a few metres instead of stepping from sample to sample.
static func _weights(bands: PackedByteArray, samples: int, gx: int, gz: int) -> Color:
var total: Color = Color(0.0, 0.0, 0.0, 0.0)
var count: int = 0
for z: int in range(maxi(gz - WEIGHT_RADIUS, 0), mini(gz + WEIGHT_RADIUS, samples - 1) + 1):
for x: int in range(maxi(gx - WEIGHT_RADIUS, 0), mini(gx + WEIGHT_RADIUS, samples - 1) + 1):
total += _BAND_WEIGHTS[bands[z * samples + x]]
count += 1
return total / float(count)
static func _edge_height(ground: SimGround, origin: Vector2i, edge: int, position: int) -> float:
var gx: int = origin.x
var gz: int = origin.y
match edge:
0:
gx += position
1:
gx += position
gz += CHUNK_CELLS
2:
gz += position
_:
gx += CHUNK_CELLS
gz += position
return ground.heights[gz * ground.samples + gx]
static func _edge_vertex(edge: int, position: int, per_side: int) -> int:
match edge:
0:
return position
1:
return (per_side - 1) * per_side + position
2:
return position * per_side
_:
return position * per_side + per_side - 1
static func _normal(heights: PackedFloat32Array, samples: int, cell: float, gx: int, gz: int) -> Vector3:
var left: float = heights[gz * samples + maxi(gx - 1, 0)]
var right: float = heights[gz * samples + mini(gx + 1, samples - 1)]
var up: float = heights[maxi(gz - 1, 0) * samples + gx]
var down: float = heights[mini(gz + 1, samples - 1) * samples + gx]
return Vector3(left - right, 2.0 * cell, up - down).normalized()
@@ -0,0 +1 @@
uid://ccwnw5e74lpwj
+176
View File
@@ -0,0 +1,176 @@
## Draws the island's terrain as streamed chunks with distance-based levels of detail.
##
## Each frame it picks the wanted detail level for every chunk from its distance to
## `focus` (normally the camera). Chunks whose level changed are rebuilt by
## TerrainChunkBuilder on WorkerThreadPool threads; the main thread only turns finished
## arrays into meshes, and stops for the frame once it has spent UPLOAD_BUDGET_USEC.
## So streaming never builds geometry on the main thread.
##
## Collision never comes from here. The simulation's SimGround is the one solid shape,
## on the server and in client prediction alike.
class_name TerrainView
extends Node3D
const SHADER: Shader = preload("res://src/client/terrain/terrain.gdshader")
## Distance from the focus to a chunk's nearest point at which each coarser level takes
## over. Index i is where level i + 1 begins.
const LOD_DISTANCES: Array[float] = [90.0, 200.0, 420.0]
## Main-thread time allowed per frame for turning finished builds into meshes.
const UPLOAD_BUDGET_USEC: int = 2_000
## Builds allowed in flight at once, so a fast camera can't queue the whole island.
const MAX_IN_FLIGHT: int = 6
## Where detail is centred, in world space.
var focus: Vector3 = Vector3.ZERO
## Tint chunks by detail level, for captures that check seams.
var show_lod: bool = false
## False only to prove that seams would crack without skirts. Never off in the game.
var skirts: bool = true
## Main-thread microseconds spent in the most recent `_process`, and the most ever.
var last_frame_usec: int = 0
var max_frame_usec: int = 0
var uploads: int = 0
var _island: Island
var _material: ShaderMaterial
var _per_side: int = 0
## Chunk -> MeshInstance3D
var _instances: Dictionary = {}
## Chunk -> level currently shown
var _shown: Dictionary = {}
## Chunk -> level being built
var _building: Dictionary = {}
var _finished: Array[Dictionary] = []
var _mutex: Mutex = Mutex.new()
var _tasks: Array[int] = []
## Prepares the view for `island`. Call before adding to the tree, or right after.
func setup(island: Island) -> void:
_island = island
_per_side = TerrainChunkBuilder.chunks_per_side(island.ground)
_material = ShaderMaterial.new()
_material.shader = SHADER
_material.set_shader_parameter("summit_height", Tuning.ISLAND_SUMMIT_BAND)
_material.set_shader_parameter("max_slope_cos", cos(deg_to_rad(Tuning.MAX_SLOPE_DEGREES)))
## Builds every chunk at its wanted level right now, on the calling thread. For loading
## screens, tests and captures, where a hitch doesn't matter.
func build_all_now() -> void:
for chunk: Vector2i in _all_chunks():
var lod: int = wanted_lod(chunk)
_apply(chunk, lod, TerrainChunkBuilder.build(_island.ground, _island.bands, chunk, lod, skirts))
## The detail level `chunk` should be shown at for the current focus.
func wanted_lod(chunk: Vector2i) -> int:
var rect: Rect2 = TerrainChunkBuilder.chunk_rect(_island.ground, chunk)
var nearest: Vector2 = Vector2(
clampf(focus.x, rect.position.x, rect.end.x), clampf(focus.z, rect.position.y, rect.end.y))
var distance: float = nearest.distance_to(Vector2(focus.x, focus.z))
for index: int in LOD_DISTANCES.size():
if distance < LOD_DISTANCES[index]:
return index
return LOD_DISTANCES.size()
## The level a chunk is shown at, or -1 if it isn't built yet.
func shown_lod(chunk: Vector2i) -> int:
return _shown.get(chunk, -1)
## True when every chunk is shown at its wanted level and nothing is building.
func settled() -> bool:
if not _building.is_empty():
return false
for chunk: Vector2i in _all_chunks():
if shown_lod(chunk) != wanted_lod(chunk):
return false
return true
func _process(_delta: float) -> void:
if _island == null:
return
var started: int = Time.get_ticks_usec()
_upload_finished(started)
_queue_changes()
last_frame_usec = Time.get_ticks_usec() - started
max_frame_usec = maxi(max_frame_usec, last_frame_usec)
func _exit_tree() -> void:
for task: int in _tasks:
WorkerThreadPool.wait_for_task_completion(task)
_tasks.clear()
func _queue_changes() -> void:
# Nearest chunks first, so detail arrives where the player is looking from.
var pending: Array[Vector2i] = []
for chunk: Vector2i in _all_chunks():
if not _building.has(chunk) and shown_lod(chunk) != wanted_lod(chunk):
pending.append(chunk)
var centre: Vector2 = Vector2(focus.x, focus.z)
var ground: SimGround = _island.ground
pending.sort_custom(func(a: Vector2i, b: Vector2i) -> bool:
return TerrainChunkBuilder.chunk_rect(ground, a).get_center().distance_squared_to(centre) \
< TerrainChunkBuilder.chunk_rect(ground, b).get_center().distance_squared_to(centre))
for chunk: Vector2i in pending:
if _building.size() >= MAX_IN_FLIGHT:
break
var lod: int = wanted_lod(chunk)
_building[chunk] = lod
_tasks.append(WorkerThreadPool.add_task(_build_on_worker.bind(chunk, lod)))
func _build_on_worker(chunk: Vector2i, lod: int) -> void:
var arrays: Array = TerrainChunkBuilder.build(_island.ground, _island.bands, chunk, lod, skirts)
_mutex.lock()
_finished.append({"chunk": chunk, "lod": lod, "arrays": arrays})
_mutex.unlock()
func _upload_finished(started: int) -> void:
# Reap completed tasks so the pool doesn't keep their records.
var running: Array[int] = []
for task: int in _tasks:
if WorkerThreadPool.is_task_completed(task):
WorkerThreadPool.wait_for_task_completion(task)
else:
running.append(task)
_tasks = running
while Time.get_ticks_usec() - started < UPLOAD_BUDGET_USEC:
_mutex.lock()
var result: Dictionary = {} if _finished.is_empty() else _finished.pop_front()
_mutex.unlock()
if result.is_empty():
return
var chunk: Vector2i = result["chunk"]
_building.erase(chunk)
_apply(chunk, result["lod"], result["arrays"])
func _apply(chunk: Vector2i, lod: int, arrays: Array) -> void:
var mesh: ArrayMesh = ArrayMesh.new()
mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arrays)
mesh.surface_set_material(0, _material)
var instance: MeshInstance3D = _instances.get(chunk)
if instance == null:
instance = MeshInstance3D.new()
instance.name = "Chunk_%d_%d" % [chunk.x, chunk.y]
add_child(instance)
_instances[chunk] = instance
instance.mesh = mesh
instance.set_instance_shader_parameter("lod_tint", float(lod) if show_lod else -1.0)
_shown[chunk] = lod
uploads += 1
func _all_chunks() -> Array[Vector2i]:
var chunks: Array[Vector2i] = []
for z: int in _per_side:
for x: int in _per_side:
chunks.append(Vector2i(x, z))
return chunks
+1
View File
@@ -0,0 +1 @@
uid://dl7o5bhcs733r