M2: The rising tide

The tide now runs every match, from the drop on, and water flows along the
terrain instead of standing everywhere under one level.

- Tide (src/sim/tide.gd): Tuning.TIDE_PHASES as a schedule of holds and
  rises. Level, forecast (each hold announces its level), stage, drowning
  rate, surge timing and the time limit are pure functions of the tick.
- SafeGround (src/sim/safe_ground.gd): safe ground from elevation on an 8 m
  grid, and per-island planned levels. A phase's level is lowered, when it
  must be, to just under the top of the largest piece of land still dry when
  the phase begins; every phase still rises at least TIDE_MIN_RISE_METRES and
  the last keeps its table level.
- Flood (src/sim/flood.gd): a 4 m grid aligned with building cells. Water
  reaches cells from the world's edge through ground under the sea and edges
  no breakwater stack seals. Cut-off ground stays dry until overtopped or
  breached, then fills at BREACH_FLOW_METRES_PER_SECOND. Incremental: only
  the edges where water stopped are re-tested, once a second.
- Players, drowning and structure wear use the local water. Breakwaters wear
  by head and fail past BREAKWATER_MAX_HEAD; a breach floods what's behind.
- Storm surges: each phase's `surge` damage hits pieces near the water when
  its rise begins.
- Sudden death after the last rise, then a time limit. Match breaks ties
  (most health, highest feet, earliest join) at the limit and when the last
  players fall together, so every match ends with a winner.

Tests: test_tide (18) covers the schedule and forecasts, planned levels,
overtopping, a sealed ring, breach and fill rate, spill-over, pressure wear
and head failure, dry pieces, surges, drowning under the real tide, sudden
death, the time limit and simultaneous eliminations. test_island's 100-seed
sweep now checks that every phase leaves safe ground reachable on foot from
the whole main landmass within the phase's time (closest margin 14 s).
A full rise with 24 bots measured p99 1.5 ms, max 1.9 ms per tick.

Closes #25

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-11 20:48:41 -05:00
co-authored by Claude Opus 5.5
parent c6f3c19004
commit 8a6fb93b50
18 changed files with 1194 additions and 21 deletions
+281
View File
@@ -0,0 +1,281 @@
## 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
## 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
## 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:
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)
+1
View File
@@ -0,0 +1 @@
uid://dwo1wm7hkh01t
+69 -7
View File
@@ -50,6 +50,9 @@ var winners: Array[int] = []
var events: Array[Dictionary] = []
var _next_bot_handle: int = FIRST_BOT_HANDLE
## Handles placed during the current step, for breaking a tie when the last players
## fall together.
var _placed_this_step: Array[int] = []
## How many started the current match.
var _match_size: int = 0
@@ -135,6 +138,7 @@ func alive() -> Array[int]:
## Advances one server tick.
func step() -> void:
events.clear()
_placed_this_step.clear()
phase_ticks += 1
match phase:
LOBBY:
@@ -182,6 +186,7 @@ func _start() -> void:
team_of[handle] = index / size
_match_size = participants.size()
sim.start_drop()
sim.start_tide()
sim.place_loot()
matches_started += 1
_enter(DROP)
@@ -205,28 +210,85 @@ func _place(handle: int, by: int, left: bool) -> void:
var place: int = _match_size - placements.size()
var record: Dictionary = {"handle": handle, "place": place, "by": by, "left": left}
placements.append(record)
if not left:
_placed_this_step.append(handle)
var event: Dictionary = record.duplicate()
event["type"] = "placed"
events.append(event)
## Ends the match when at most one team has anyone standing.
## Ends the match when at most one team has anyone standing, or when the tide's time
## limit runs out. If the last players fall on the same tick, or time runs out with
## several still standing, the tie-break picks the winner, so every match that started
## with players has one.
func _check_finished() -> void:
if not in_match():
return
var living: Array[int] = alive()
var teams: Dictionary = {}
for handle: int in alive():
for handle: int in living:
teams[team_of[handle]] = true
if teams.size() > 1:
var timed_out: bool = sim.tide != null and sim.tide.stage_at(sim.tick) == Tide.OVER
if teams.size() > 1 and not timed_out:
return
winners.clear()
for handle: int in alive():
winners.append(handle)
# Winners take first place, after everyone eliminated.
if teams.size() >= 1:
var best: int = living[0] if teams.size() == 1 else _tie_break(living)
for handle: int in living:
if team_of[handle] == team_of[best]:
winners.append(handle)
# Anyone else still standing at the time limit is placed by the tie-break, worst last.
var losers: Array[int] = []
for handle: int in living:
if not winners.has(handle):
losers.append(handle)
while not losers.is_empty():
var worst: int = _tie_break(losers, true)
losers.erase(worst)
_place(worst, 0, false)
elif not _placed_this_step.is_empty():
# Everyone fell on the same tick: the tie-break raises one team back to first.
var best: int = _tie_break(_placed_this_step)
for handle: int in _placed_this_step:
if team_of[handle] == team_of[best]:
winners.append(handle)
var kept: Array[Dictionary] = []
for record: Dictionary in placements:
if not winners.has(record["handle"]):
kept.append(record)
placements = kept
# Renumber the rest of this tick's fallers below the winners.
var place: int = _match_size
for record: Dictionary in placements:
record["place"] = place
place -= 1
for handle: int in winners:
placements.append({"handle": handle, "place": 1, "by": 0, "left": false})
_enter(RESULTS)
events.append({"type": "match_ended", "match": current_seed(), "winners": winners.duplicate()})
events.append({"type": "match_ended", "match": current_seed(), "winners": winners.duplicate(), "timed_out": timed_out})
## The best of `handles` by the tie-break: most health, then highest feet, then the
## earliest to join. With `worst`, the worst instead.
func _tie_break(handles: Array[int], worst: bool = false) -> int:
var chosen: int = handles[0]
for handle: int in handles:
if handle == chosen:
continue
var better: bool = _beats(handle, chosen)
if better != worst:
chosen = handle
return chosen
func _beats(a: int, b: int) -> bool:
var pa: SimEntity = sim.entities.find(entity_of[a])
var pb: SimEntity = sim.entities.find(entity_of[b])
if pa.health != pb.health:
return pa.health > pb.health
if not is_equal_approx(pa.position.y, pb.position.y):
return pa.position.y > pb.position.y
return participants.find(a) < participants.find(b)
## Back to the lobby: bots leave, the match's bookkeeping is cleared, and the next
+97
View File
@@ -0,0 +1,97 @@
## Safe ground: where the tide's next level leaves dry land, worked out from elevation on
## an 8 m grid over the island. It also plans the island's tide levels, so that each
## phase leaves safe ground on the main landmass: the table's level for a phase is
## lowered, when it has to be, to just under the highest point of the largest piece of
## land still dry when that phase's hold begins. The last phase always takes its table
## level, which covers every island.
class_name SafeGround
extends RefCounted
const STRIDE_METRES: float = 8.0
const STEPS: Array[Vector2i] = [Vector2i(1, 0), Vector2i(-1, 0), Vector2i(0, 1), Vector2i(0, -1)]
var side: int = 0
var heights: PackedFloat32Array = PackedFloat32Array()
func _init(ground: SimGround) -> void:
side = floori(Tuning.WORLD_SIZE_METRES / STRIDE_METRES) + 1
heights.resize(side * side)
for gz: int in side:
for gx: int in side:
heights[gz * side + gx] = ground.terrain_height(gx * STRIDE_METRES, gz * STRIDE_METRES)
func highest() -> float:
var top: float = -INF
for value: float in heights:
top = maxf(top, value)
return top
## True where the ground at a point stands above `level`.
func is_safe(x: float, z: float, level: float) -> bool:
var gx: int = clampi(roundi(x / STRIDE_METRES), 0, side - 1)
var gz: int = clampi(roundi(z / STRIDE_METRES), 0, side - 1)
return heights[gz * side + gx] > level
## Every phase's level for this island, in phase order. See the class comment.
func plan_levels() -> PackedFloat32Array:
var levels: PackedFloat32Array = PackedFloat32Array()
var before: float = Tuning.SEA_LEVEL_START
var last: int = Tuning.TIDE_PHASES.size() - 1
for index: int in Tuning.TIDE_PHASES.size():
var level: float = float(Tuning.TIDE_PHASES[index]["level"])
if index < last:
var top: float = top_of(largest_dry_piece(before))
level = minf(level, top - Tuning.TIDE_SAFE_MARGIN_METRES)
level = maxf(level, before + Tuning.TIDE_MIN_RISE_METRES)
else:
level = maxf(level, before + Tuning.TIDE_MIN_RISE_METRES)
levels.append(level)
before = level
return levels
## The largest connected piece of ground above `level`, as a mark per grid cell.
func largest_dry_piece(level: float) -> PackedByteArray:
var seen: PackedByteArray = PackedByteArray()
seen.resize(side * side)
var best: PackedInt32Array = PackedInt32Array()
for start: int in side * side:
if seen[start] != 0 or heights[start] <= level:
continue
seen[start] = 1
var piece: PackedInt32Array = PackedInt32Array([start])
var head: int = 0
while head < piece.size():
var cell: int = piece[head]
head += 1
var x: int = cell % side
var z: int = cell / side
for step: Vector2i in STEPS:
var nx: int = x + step.x
var nz: int = z + step.y
if nx < 0 or nz < 0 or nx >= side or nz >= side:
continue
var next: int = nz * side + nx
if seen[next] == 0 and heights[next] > level:
seen[next] = 1
piece.append(next)
if piece.size() > best.size():
best = piece
var marks: PackedByteArray = PackedByteArray()
marks.resize(side * side)
for cell: int in best:
marks[cell] = 1
return marks
## The highest ground in a marked area, or -INF if it's empty.
func top_of(area: PackedByteArray) -> float:
var top: float = -INF
for cell: int in side * side:
if area[cell] != 0:
top = maxf(top, heights[cell])
return top
+1
View File
@@ -0,0 +1 @@
uid://dtu58jltyyigi
+61 -4
View File
@@ -28,6 +28,11 @@ var props: PropSet = PropSet.new()
var sea_level: float = Tuning.SEA_LEVEL_START
## Damage per second to a player underwater with no breath left. Set by the tide phase.
var drown_dps: int = Tuning.TIDE_PHASES[0]["drown_dps"]
## The tide's schedule, from start_tide() on. Null in tests that set the sea by hand.
var tide: Tide = null
## Where the sea reaches, on an island. Null on a test ground, where the sea is
## everywhere under `sea_level`.
var flood: Flood = null
## Every built piece. Their boxes are part of `ground`.
var structures: StructureSet = StructureSet.new()
## The sky barge, from start_drop() on. Null in matches and tests that start on foot.
@@ -64,6 +69,7 @@ func _init(match_seed: int, world: SimGround = null) -> void:
pois.add_solids_to(world)
props = PropSet.generate(island, pois)
props.add_solids_to(world)
flood = Flood.create(world)
ground = world
structures.props = props
@@ -140,12 +146,32 @@ static func crate_spill_points(prop_set: PropSet) -> Dictionary:
return points
## Starts the tide's schedule from this tick.
func start_tide() -> void:
if island != null:
tide = Tide.new(tick, SafeGround.new(ground).plan_levels())
else:
tide = Tide.new(tick)
## Height of the water surface over a point: the sea level where the flood reaches,
## Flood.NO_WATER where it doesn't. On a test ground, the sea level everywhere.
func water_level_at(point: Vector3) -> float:
if flood == null:
return sea_level
return flood.level_at(point.x, point.z)
## Advances the simulation by one tick.
func step() -> void:
events.clear()
if tide != null:
_advance_tide()
elif flood != null:
flood.flow(sea_level, SECONDS_PER_TICK)
structures.advance_building()
if tick % Tuning.TICK_RATE_HZ == Tuning.TICK_RATE_HZ - 1:
structures.tide_damage(sea_level, ground, events)
structures.tide_damage(sea_level, ground, events, flood)
for player_id: int in _players:
var queued: Dictionary = _pending[player_id]
var command: PlayerCommand = queued.get(tick)
@@ -182,9 +208,10 @@ func _ride(player: SimEntity, command: PlayerCommand) -> void:
func _apply_command(player: SimEntity, command: PlayerCommand) -> void:
Movement.step(player, command, ground, sea_level)
var water: float = water_level_at(player.position)
Movement.step(player, command, ground, water)
var sprinting: bool = command != null and command.is_pressed(PlayerCommand.BUTTON_SPRINT)
Water.update(player, sea_level, drown_dps, sprinting)
Water.update(player, water_level_at(player.position), drown_dps, sprinting)
if player.action_cooldown > 0:
player.action_cooldown -= 1
Weapons.update(player)
@@ -244,9 +271,34 @@ func _check_eliminations() -> void:
Inventory.drop_all(self, player)
## Moves the sea surface. Takes effect on the next step.
## Moves the sea surface, and spreads the flood for it at once. Takes effect on the
## next step. With the tide running, the tide sets the level every tick instead.
func set_sea_level(level: float) -> void:
sea_level = level
if flood != null:
flood.update(level, structures, 0.0)
## The tide's tick: the sea level, drowning damage, storm surges, the flood's spread and
## sudden death.
func _advance_tide() -> void:
sea_level = tide.level_at(tick)
drown_dps = tide.drown_dps_at(tick)
if flood != null:
if tick % Tuning.TICK_RATE_HZ == 0:
flood.update(sea_level, structures, SECONDS_PER_TICK)
else:
flood.flow(sea_level, SECONDS_PER_TICK)
if tide.surge_starts(tick):
var amount: int = tide.surge_damage_at(tick)
events.append({"type": "surge", "phase": tide.phase_at(tick), "damage": amount})
if amount > 0:
structures.surge(amount, sea_level, ground, events, flood)
if tide.stage_at(tick) == Tide.SUDDEN_DEATH and tick % Tuning.TICK_RATE_HZ == Tuning.TICK_RATE_HZ - 1:
for player_id: int in _players:
var player: SimEntity = entities.find(player_id)
if not player.eliminated and player.drop_state == Drop.NONE:
player.health = maxi(player.health - Tuning.TIDE_SUDDEN_DEATH_DPS, 0)
## Damages a piece. Returns true if this destroyed it; anything it held up collapses.
@@ -319,6 +371,11 @@ func state_hash() -> String:
buffer.put_64(roundi(value * 1000.0))
buffer.put_64(roundi(sea_level * 1000.0))
buffer.put_32(drown_dps)
buffer.put_64(tide.started_tick if tide != null else -1)
if tide != null:
buffer.put_data(tide.levels.to_byte_array())
if flood != null:
flood.write_state(buffer)
buffer.put_64(props.count())
buffer.put_data(props.health.to_byte_array())
structures.write_state(buffer)
+35 -3
View File
@@ -439,12 +439,13 @@ func ground_changed(area: AABB, ground: SimGround, events: Array[Dictionary]) ->
return collapse_unsupported(lost, ground, events)
## One second of the sea against every piece with its base under `sea_level`.
func tide_damage(sea_level: float, ground: SimGround, events: Array[Dictionary]) -> void:
## One second of the sea against every piece with its base under the water that reaches
## it. With no flood (a test ground), that's `sea_level` everywhere.
func tide_damage(sea_level: float, ground: SimGround, events: Array[Dictionary], flood: Flood = null) -> void:
var hit: Array[Vector2i] = []
for piece: Piece in pieces.values():
var base: float = piece.slot.y * Tuning.BUILD_LEVEL_METRES
var head: float = sea_level - base
var head: float = water_at(piece, sea_level, flood) - base
if head <= 0.0:
continue
var amount: int = Tuning.TIDE_STRUCTURE_DPS
@@ -454,3 +455,34 @@ func tide_damage(sea_level: float, ground: SimGround, events: Array[Dictionary])
# Damage after the scan, since destroying pieces changes the dictionary.
for entry: Vector2i in hit:
damage(entry.x, entry.y, "tide", ground, events)
## A storm surge: `amount` damage to every piece whose base is below the water that
## reaches it plus Tuning.TIDE_SURGE_HEIGHT_METRES.
func surge(amount: int, sea_level: float, ground: SimGround, events: Array[Dictionary], flood: Flood = null) -> void:
var hit: PackedInt32Array = PackedInt32Array()
for piece: Piece in pieces.values():
var water: float = water_at(piece, sea_level, flood)
if water <= Flood.NO_WATER:
continue
if piece.slot.y * Tuning.BUILD_LEVEL_METRES < water + Tuning.TIDE_SURGE_HEIGHT_METRES:
hit.append(piece.id)
for piece_id: int in hit:
if pieces.has(piece_id):
damage(piece_id, amount, "surge", ground, events)
## The water surface a piece stands in: for a wall or breakwater, the higher of the two
## cells it divides; otherwise its own cell. Flood.NO_WATER where the sea doesn't reach.
func water_at(piece: Piece, sea_level: float, flood: Flood) -> float:
if flood == null:
return sea_level
var size: float = Tuning.GRID_CELL_METRES
var x: float = (piece.slot.x + 0.5) * size
var z: float = (piece.slot.z + 0.5) * size
match piece.slot.w:
SLOT_WALL_X:
return maxf(flood.level_at(piece.slot.x * size - size * 0.5, z), flood.level_at(piece.slot.x * size + size * 0.5, z))
SLOT_WALL_Z:
return maxf(flood.level_at(x, piece.slot.z * size - size * 0.5), flood.level_at(x, piece.slot.z * size + size * 0.5))
return flood.level_at(x, z)
+115
View File
@@ -0,0 +1,115 @@
## The tide's schedule: Tuning.TIDE_PHASES played from the tick the tide started. Each
## phase holds the water still for `hold` seconds, then raises it over `rise` seconds to
## its `level`. After the last rise comes sudden death, and when that has run its course
## the match must end. Everything here is a pure function of elapsed ticks, so any tick's
## water level, forecast and phase can be asked for at any time.
class_name Tide
extends RefCounted
const HOLD: int = 0
const RISE: int = 1
const SUDDEN_DEATH: int = 2
const OVER: int = 3
const TICKS: int = Tuning.TICK_RATE_HZ
var started_tick: int = 0
## Each phase's level, from SafeGround.plan_levels() on an island, or the table's.
var levels: PackedFloat32Array = PackedFloat32Array()
## Tick offsets from the start: where each phase's hold and rise begin.
var _hold_starts: PackedInt32Array = PackedInt32Array()
var _rise_starts: PackedInt32Array = PackedInt32Array()
var _rise_ends: PackedInt32Array = PackedInt32Array()
func _init(start_tick: int, phase_levels: PackedFloat32Array = PackedFloat32Array()) -> void:
started_tick = start_tick
levels = phase_levels
if levels.is_empty():
for phase: Dictionary in Tuning.TIDE_PHASES:
levels.append(float(phase["level"]))
var at: int = 0
for phase: Dictionary in Tuning.TIDE_PHASES:
_hold_starts.append(at)
at += roundi(float(phase["hold"]) * TICKS)
_rise_starts.append(at)
at += maxi(roundi(float(phase["rise"]) * TICKS), 1)
_rise_ends.append(at)
static func phase_count() -> int:
return Tuning.TIDE_PHASES.size()
## Ticks from the start until sudden death begins.
func sudden_death_offset() -> int:
return _rise_ends[_rise_ends.size() - 1]
## Ticks from the start until the match must end.
func time_limit_offset() -> int:
return sudden_death_offset() + roundi(Tuning.TIDE_SUDDEN_DEATH_SECONDS * TICKS)
## The phase index in effect at `tick`: the one whose hold or rise is under way, or the
## last one from sudden death on.
func phase_at(tick: int) -> int:
var elapsed: int = tick - started_tick
for index: int in phase_count():
if elapsed < _rise_ends[index]:
return index
return phase_count() - 1
## HOLD, RISE, SUDDEN_DEATH or OVER at `tick`.
func stage_at(tick: int) -> int:
var elapsed: int = tick - started_tick
if elapsed >= time_limit_offset():
return OVER
if elapsed >= sudden_death_offset():
return SUDDEN_DEATH
var index: int = phase_at(tick)
return RISE if elapsed >= _rise_starts[index] else HOLD
## The sea level at `tick`. Before the tide starts it's the starting level.
func level_at(tick: int) -> float:
var elapsed: int = tick - started_tick
if elapsed <= 0:
return Tuning.SEA_LEVEL_START
var index: int = phase_at(tick)
var from: float = Tuning.SEA_LEVEL_START if index == 0 else levels[index - 1]
var to: float = levels[index]
if elapsed >= _rise_ends[index]:
return to
if elapsed < _rise_starts[index]:
return from
var fraction: float = float(elapsed - _rise_starts[index]) / (_rise_ends[index] - _rise_starts[index])
return lerpf(from, to, fraction)
## The level the water is heading for: the current phase's level, announced from the
## start of its hold. From sudden death on, the final level.
func forecast_at(tick: int) -> float:
return levels[phase_at(tick)]
## Ticks until the current hold ends and the water starts rising, or 0 while it rises.
func ticks_until_rise(tick: int) -> int:
if stage_at(tick) != HOLD:
return 0
return _rise_starts[phase_at(tick)] - (tick - started_tick)
func drown_dps_at(tick: int) -> int:
return int(Tuning.TIDE_PHASES[phase_at(tick)]["drown_dps"])
## True on the first tick of a phase's rise: when that phase's storm surge strikes.
func surge_starts(tick: int) -> bool:
var elapsed: int = tick - started_tick
return _rise_starts.has(elapsed)
func surge_damage_at(tick: int) -> int:
return int(Tuning.TIDE_PHASES[phase_at(tick)].get("surge", 0))
+1
View File
@@ -0,0 +1 @@
uid://beq3hlpyycdxq
+26 -7
View File
@@ -175,14 +175,33 @@ const PROP_POI_CLEARANCE: float = 3.0
# must exceed ISLAND_MAX_HEIGHT, so that every match ends.
const ISLAND_MAX_HEIGHT: float = 70.0
const TIDE_PHASES: Array[Dictionary] = [
{"hold": 150.0, "rise": 60.0, "level": 8.0, "drown_dps": 2},
{"hold": 100.0, "rise": 50.0, "level": 18.0, "drown_dps": 4},
{"hold": 80.0, "rise": 45.0, "level": 30.0, "drown_dps": 6},
{"hold": 60.0, "rise": 40.0, "level": 42.0, "drown_dps": 8},
{"hold": 45.0, "rise": 35.0, "level": 54.0, "drown_dps": 12},
{"hold": 30.0, "rise": 30.0, "level": 64.0, "drown_dps": 16},
{"hold": 20.0, "rise": 40.0, "level": 75.0, "drown_dps": 25},
{"hold": 150.0, "rise": 60.0, "level": 8.0, "drown_dps": 2, "surge": 0},
{"hold": 100.0, "rise": 50.0, "level": 18.0, "drown_dps": 4, "surge": 40},
{"hold": 80.0, "rise": 45.0, "level": 30.0, "drown_dps": 6, "surge": 60},
{"hold": 60.0, "rise": 40.0, "level": 42.0, "drown_dps": 8, "surge": 80},
{"hold": 45.0, "rise": 35.0, "level": 54.0, "drown_dps": 12, "surge": 100},
{"hold": 30.0, "rise": 30.0, "level": 64.0, "drown_dps": 16, "surge": 120},
{"hold": 20.0, "rise": 40.0, "level": 75.0, "drown_dps": 25, "surge": 150},
]
## Each island's levels are planned from its terrain (SafeGround): a phase's level is
## lowered, if need be, to this far under the top of the largest piece of land still
## dry when it begins, but every phase still rises at least TIDE_MIN_RISE_METRES. The
## last phase always takes its table level.
const TIDE_SAFE_MARGIN_METRES: float = 2.0
const TIDE_MIN_RISE_METRES: float = 4.0
## When a phase's rise begins, a storm surge does the phase's `surge` damage once to
## every built piece whose base is below the water plus this height, where that water
## reaches it. Breakwaters take it too.
const TIDE_SURGE_HEIGHT_METRES: float = 2.0
## Sudden death begins when the last rise ends: every player still standing loses this
## much health a second, armor or not. When it has run this long, the match ends and
## the winner is decided by Match's tie-break: most health, then highest feet, then
## earliest to join. So every match ends within the tide's total time plus this.
const TIDE_SUDDEN_DEATH_SECONDS: float = 60.0
const TIDE_SUDDEN_DEATH_DPS: int = 5
## The flood grid's cells are this big, matching the building grid so breakwater edges
## line up with cell edges.
const FLOOD_CELL_METRES: float = 4.0
# Building
const GRID_CELL_METRES: float = 4.0