Files
tidewall/src/sim/flood.gd
T
claudeandClaude Opus 5.5 8505216568 A11: Chart, minimap and tide forecast
The island as a hand-drawn nautical chart: paper land with ink contours
every 5 m (heavier every 25 m) and a coastline, the sea in the sea's
ink, place names drawn from the seed, the barge's route, and the
player's mark. The land the coming tide will flood is hatched, and land
the sea has already taken is washed with the sea, so the forecast isn't
told by colour alone.

- Flood.forecast(level, structures): a copy of the flood spread to a
  level as update() would, with today's breakwaters. Changes nothing.
- ChartMap: FULL (opened and closed with the new "map" binding, M) and
  MINI (240 m around the player, top left, during the drop and play).
  The paper is drawn once per world (about 270 ms) and shared; the
  forecast overlay is redrawn at most once a second, and only when the
  forecast level, the flood or the pieces changed.
- PlaceNames: names from original coastal words and a word for each
  kind of place, the same for every player of a match.
- make chart-captures renders the chart before and after the first tide.

Solo matches have no teammates; ChartMap draws `mates` when duos (M7)
give it some.

Closes #51

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 11:46:35 -05:00

305 lines
11 KiB
GDScript

## Where the sea actually is. The tide sets one sea level, but water only reaches ground
## it can flow to: from the world's edge, through cells whose lowest ground is under the
## sea, and across cell edges that no breakwater seals. Low ground cut off by higher
## land or by a breakwater ring stays dry until the sea overtops what holds it back, or
## a breakwater breaks. Then the water pours in, and the newly reached cells fill at
## Tuning.BREACH_FLOW_METRES_PER_SECOND until they stand level with the sea.
##
## The grid's cells are Tuning.FLOOD_CELL_METRES square and line up with the building
## grid, so breakwaters stand exactly on cell edges. A cell's floor is the lowest terrain
## in it. Water never drains: once a cell is flooded it stays flooded.
##
## Updating is incremental. The flood remembers every edge where it was stopped, and
## re-tests only those when the sea rises or breakwaters change.
class_name Flood
extends RefCounted
## level_at() for a cell the sea doesn't reach.
const NO_WATER: float = -1000.0
## No breakwater stack yet on an edge, while reading barriers.
const NO_STACK: int = -1000000
## Neighbour steps by direction: +x, -x, +z, -z.
const STEPS: Array[Vector2i] = [Vector2i(1, 0), Vector2i(-1, 0), Vector2i(0, 1), Vector2i(0, -1)]
var side: int = 0
var cell: float = Tuning.FLOOD_CELL_METRES
## Per cell: lowest terrain, flooded (1) or not, and the filling group it belongs to (-1
## once it stands level with the sea).
var floors: PackedFloat32Array = PackedFloat32Array()
var flooded: PackedByteArray = PackedByteArray()
var fill_group: PackedInt32Array = PackedInt32Array()
## The sea level the flood was last spread for.
var sea_level: float = Tuning.SEA_LEVEL_START
## Counts every pour, so a view can tell the flooded cells changed without comparing
## them. Not match state.
var pours: int = 0
## Filling groups: group ID -> {"level": float, "cells": PackedInt32Array}.
var _groups: Dictionary = {}
var _next_group: int = 0
## Edges the water was stopped at, as cell * 4 + direction, in the order found.
var _blocked: Dictionary = {}
## Sealed edges: edge key -> height of the breakwater top. See edge_key().
var _barriers: Dictionary = {}
## StructureSet next ID and piece count when barriers were last read.
var _structures_seen: Vector2i = Vector2i(-1, -1)
## Builds the flood grid over `ground` and floods everything the starting sea reaches.
static func create(ground: SimGround, level: float = Tuning.SEA_LEVEL_START) -> Flood:
var flood: Flood = Flood.new()
flood.side = ceili(Tuning.WORLD_SIZE_METRES / flood.cell)
var count: int = flood.side * flood.side
flood.floors.resize(count)
flood.flooded.resize(count)
flood.fill_group.resize(count)
flood.fill_group.fill(-1)
var per_cell: int = roundi(flood.cell / ground.cell)
var direct: bool = is_equal_approx(per_cell * ground.cell, flood.cell) and (flood.side * per_cell) < ground.samples
for cz: int in flood.side:
for cx: int in flood.side:
var lowest: float = INF
if direct:
# Read the heightfield samples in and around the cell straight from the array.
for gz: int in range(cz * per_cell, cz * per_cell + per_cell + 1):
var row: int = gz * ground.samples
for gx: int in range(cx * per_cell, cx * per_cell + per_cell + 1):
lowest = minf(lowest, ground.heights[row + gx])
else:
for sz: int in 3:
for sx: int in 3:
lowest = minf(lowest, ground.terrain_height((cx + sx * 0.5) * flood.cell, (cz + sz * 0.5) * flood.cell))
flood.floors[cz * flood.side + cx] = lowest
flood.sea_level = level
# The open sea: every border cell under the starting level, filled at once.
var start: PackedInt32Array = PackedInt32Array()
for index: int in flood.side:
for border: int in [index, (flood.side - 1) * flood.side + index, index * flood.side, index * flood.side + flood.side - 1]:
if flood.flooded[border] == 0 and flood.floors[border] < level:
flood.flooded[border] = 1
start.append(border)
flood._spread(start)
return flood
## The flood cell under a world point.
func cell_of(x: float, z: float) -> int:
var cx: int = clampi(floori(x / cell), 0, side - 1)
var cz: int = clampi(floori(z / cell), 0, side - 1)
return cz * side + cx
## Height of the water surface over the cell at a world point, or NO_WATER if the sea
## doesn't reach it. May be below the ground while a breached basin is still filling.
func level_at(x: float, z: float) -> float:
return level_of_cell(cell_of(x, z))
func level_of_cell(index: int) -> float:
if flooded[index] == 0:
return NO_WATER
var group: int = fill_group[index]
if group >= 0:
return minf(float(_groups[group]["level"]), sea_level)
return sea_level
func is_flooded(x: float, z: float) -> bool:
return flooded[cell_of(x, z)] != 0
## Number of flooded cells.
func flooded_count() -> int:
return flooded.count(1)
## Key of the edge between cell (cx - 1, cz) and (cx, cz) for axis 0, or (cx, cz - 1) and
## (cx, cz) for axis 1. The same numbering as StructureSet's wall slots.
func edge_key(cx: int, cz: int, axis: int) -> int:
return (cz * side + cx) * 2 + axis
## The top of the breakwater sealing the edge between neighbouring cells, or -INF.
func barrier_between(a: int, b: int) -> float:
var ax: int = a % side
var bx: int = b % side
var key: int
if ax != bx:
key = edge_key(maxi(ax, bx), a / side, 0)
else:
key = edge_key(ax, maxi(a / side, b / side), 1)
return float(_barriers.get(key, -INF))
## Reads breakwaters from `structures` if it changed since last time. Returns true if
## it did.
func refresh_barriers(structures: StructureSet) -> bool:
var seen: Vector2i = Vector2i(structures.next_id(), structures.count())
if seen == _structures_seen:
return false
_structures_seen = seen
# Breakwater levels by edge, then each edge's sealed height: a stack of breakwaters
# from the ground up (the lowest may hang one level over lower ground, as its skirt
# fills the gap), each starting no higher than the one under it ends.
var levels: Dictionary = {}
for piece: StructureSet.Piece in structures.pieces.values():
if piece.kind != StructureSet.BREAKWATER:
continue
var axis: int = 0 if piece.slot.w == StructureSet.SLOT_WALL_X else 1
if piece.slot.x < 0 or piece.slot.z < 0 or piece.slot.x >= side or piece.slot.z >= side:
continue
var key: int = edge_key(piece.slot.x, piece.slot.z, axis)
if not levels.has(key):
levels[key] = PackedInt32Array()
levels[key].append(piece.slot.y)
_barriers.clear()
var piece_levels: int = roundi(Tuning.GRID_CELL_METRES / Tuning.BUILD_LEVEL_METRES)
for key: int in levels:
var stack: PackedInt32Array = levels[key]
stack.sort()
var index: int = key / 2
var cx: int = index % side
var cz: int = index / side
var other: int = (index - 1) if key % 2 == 0 else (index - side)
if (key % 2 == 0 and cx == 0) or (key % 2 == 1 and cz == 0):
continue
var edge_floor: float = maxf(floors[index], floors[other])
var top_level: int = NO_STACK
for level: int in stack:
if top_level == NO_STACK:
if level * Tuning.BUILD_LEVEL_METRES > edge_floor + Tuning.BUILD_LEVEL_METRES:
break
top_level = level + piece_levels
elif level <= top_level:
top_level = maxi(top_level, level + piece_levels)
else:
break
if top_level != NO_STACK:
_barriers[key] = top_level * Tuning.BUILD_LEVEL_METRES
return true
## Spreads the water for a new sea level and the current breakwaters, and advances
## filling basins by `seconds` of flow. Returns how many cells newly flooded.
func update(level: float, structures: StructureSet, seconds: float) -> int:
sea_level = level
if structures != null:
refresh_barriers(structures)
var reached: int = 0
var edges: Array = _blocked.keys()
for key: int in edges:
if not _blocked.has(key):
continue
var from: int = key / 4
var to: int = _neighbour(from, key % 4)
if flooded[to] != 0:
_blocked.erase(key)
continue
if _passable(from, to):
_blocked.erase(key)
reached += _pour(to)
_advance_groups(seconds)
return reached
## The cells the sea will have reached once it stands at `level`, if the breakwaters in
## `structures` (null: the ones last read) hold as they are now: a copy of this flood
## spread to that level, as update() would spread it. Changes nothing here. For the
## chart's tide forecast (A11).
func forecast(level: float, structures: StructureSet = null) -> PackedByteArray:
var copy: Flood = Flood.new()
copy.side = side
copy.cell = cell
copy.floors = floors
copy.flooded = flooded.duplicate()
copy.fill_group = fill_group.duplicate()
copy.sea_level = sea_level
copy._blocked = _blocked.duplicate()
copy._barriers = _barriers.duplicate()
copy._structures_seen = _structures_seen
copy.update(maxf(level, sea_level), structures, 0.0)
return copy.flooded
## Follows the sea level and advances filling basins, without re-spreading. Cheap
## enough for every tick.
func flow(level: float, seconds: float) -> void:
sea_level = level
_advance_groups(seconds)
## Writes the flooded cells, filling groups and barriers, for Simulation.state_hash().
func write_state(buffer: StreamPeerBuffer) -> void:
buffer.put_64(roundi(sea_level * 1000.0))
buffer.put_data(flooded)
buffer.put_64(_groups.size())
for group: int in _groups:
buffer.put_32(group)
buffer.put_64(roundi(float(_groups[group]["level"]) * 1000.0))
buffer.put_64(_barriers.size())
func _neighbour(index: int, direction: int) -> int:
var step: Vector2i = STEPS[direction]
var x: int = index % side + step.x
var z: int = index / side + step.y
if x < 0 or z < 0 or x >= side or z >= side:
return -1
return z * side + x
func _passable(from: int, to: int) -> bool:
return floors[to] < sea_level and barrier_between(from, to) < sea_level
## Water pours across an edge into `to`, and on through everything it can reach. The
## reached cells fill together, from their lowest floor up.
func _pour(to: int) -> int:
pours += 1
flooded[to] = 1
var queue: PackedInt32Array = PackedInt32Array([to])
_spread(queue)
var group: int = _next_group
_next_group += 1
var bottom: float = INF
for index: int in queue:
bottom = minf(bottom, floors[index])
_groups[group] = {"level": bottom, "cells": queue}
for index: int in queue:
fill_group[index] = group
return queue.size()
## Breadth-first flood from the cells in `queue`, which must already be marked flooded.
## Appends every newly flooded cell to `queue` and records where the water stopped.
func _spread(queue: PackedInt32Array) -> void:
var head: int = 0
while head < queue.size():
var index: int = queue[head]
head += 1
for direction: int in 4:
var next: int = _neighbour(index, direction)
if next < 0 or flooded[next] != 0:
continue
if _passable(index, next):
flooded[next] = 1
queue.append(next)
else:
_blocked[index * 4 + direction] = true
func _advance_groups(seconds: float) -> void:
if _groups.is_empty():
return
var done: Array[int] = []
for group: int in _groups:
var entry: Dictionary = _groups[group]
entry["level"] = float(entry["level"]) + Tuning.BREACH_FLOW_METRES_PER_SECOND * seconds
if float(entry["level"]) >= sea_level:
done.append(group)
for group: int in done:
for index: int in _groups[group]["cells"]:
if fill_group[index] == group:
fill_group[index] = -1
_groups.erase(group)