From be987b6f8266591dcf319e3a666a53544f661b1f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 12:24:50 -0500 Subject: [PATCH] W6: Water and swimming The simulation has a global sea level (Simulation.sea_level, changed with set_sea_level and read every tick, so the tide can move it mid-match). Walkers wade more slowly in water over WADE_DEPTH; in water SWIM_DEPTH deep they swim: floating head-out, sprint-swimming, diving with crouch, kicking out with jump, and standing again in the shallows. Falling into deep water does no fall damage. Water tracks breath, stamina and drowning in whole ticks: swimming spends stamina, an exhausted swimmer slips under, and with no breath left the tide phase's drown damage lands once a second. All of it, plus the sea level, is in the state hash. WaterView draws the sea surface at the simulation's level with a procedural shader: depth-tinted colour, foam at the waterline, ripples. Closes #13 Co-Authored-By: Claude Opus 5.5 --- docs/GDD.md | 6 +- src/client/water/water.gdshader | 74 +++++++++ src/client/water/water.gdshader.uid | 1 + src/client/water/water_view.gd | 58 +++++++ src/client/water/water_view.gd.uid | 1 + src/sim/movement.gd | 104 ++++++++++++- src/sim/sim_entity.gd | 6 + src/sim/simulation.gd | 22 ++- src/sim/tuning.gd | 28 ++++ src/sim/water.gd | 71 +++++++++ src/sim/water.gd.uid | 1 + test/capture/terrain_scene.gd | 7 + test/capture/water_flood.tscn | 9 ++ test/capture/water_shore.tscn | 10 ++ test/client/test_water_view.gd | 20 +++ test/client/test_water_view.gd.uid | 1 + test/sim/test_water.gd | 231 ++++++++++++++++++++++++++++ test/sim/test_water.gd.uid | 1 + 18 files changed, 641 insertions(+), 10 deletions(-) create mode 100644 src/client/water/water.gdshader create mode 100644 src/client/water/water.gdshader.uid create mode 100644 src/client/water/water_view.gd create mode 100644 src/client/water/water_view.gd.uid create mode 100644 src/sim/water.gd create mode 100644 src/sim/water.gd.uid create mode 100644 test/capture/water_flood.tscn create mode 100644 test/capture/water_shore.tscn create mode 100644 test/client/test_water_view.gd create mode 100644 test/client/test_water_view.gd.uid create mode 100644 test/sim/test_water.gd create mode 100644 test/sim/test_water.gd.uid diff --git a/docs/GDD.md b/docs/GDD.md index 1d0e79b..3d12203 100644 --- a/docs/GDD.md +++ b/docs/GDD.md @@ -117,7 +117,11 @@ seed, so only damage is match state. The last phase raises the sea above the highest ground, so every match ends. Players standing in shallow water wade and slow down. Underwater, they lose breath over `BREATH_SECONDS`, and then take the phase's `drown_dps`. Swimming is slow and leaves a -player unable to build or fire. Water flows along the terrain, so low ground that is +player unable to build or fire. Players swim where the water over the floor is at least +`SWIM_DEPTH`, floating head-out at `SWIM_FLOAT_DEPTH`; crouch dives and jump kicks out of +the water. Swimming spends stamina (`SWIM_STAMINA_SECONDS`, faster when sprint-swimming), +which comes back on land. A swimmer with no stamina slips under and starts losing breath, +so a long swim out to sea can drown. Landing in deep water does no fall damage. Water flows along the terrain, so low ground that is cut off from the sea stays dry until something opens a path. ## Building diff --git a/src/client/water/water.gdshader b/src/client/water/water.gdshader new file mode 100644 index 0000000..36d771e --- /dev/null +++ b/src/client/water/water.gdshader @@ -0,0 +1,74 @@ +// Tidewall sea: one transparent surface at the simulation's sea level. Colour deepens +// with the water's thickness, read from the depth buffer, so shallows over sand show +// green-grey and open water turns slate blue. A pale band of foam marks the waterline, +// where the tide is about to reach. Small procedural ripples move the normals. No +// textures: every pattern is generated here. +shader_type spatial; +render_mode blend_mix, depth_draw_always, cull_disabled, specular_schlick_ggx; + +uniform sampler2D depth_texture : hint_depth_texture, filter_linear; +uniform vec3 shallow_colour : source_color = vec3(0.42, 0.55, 0.50); +uniform vec3 deep_colour : source_color = vec3(0.10, 0.22, 0.30); +uniform vec3 foam_colour : source_color = vec3(0.86, 0.88, 0.84); +// Metres of water over which the colour goes from shallow to deep. +uniform float depth_scale = 7.0; +// Width of the foam at the waterline, in metres of water thickness. +uniform float foam_width = 0.6; +uniform float ripple_strength = 0.25; + +varying vec3 world_position; + +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 waves(vec2 p, float t) { + return value_noise(p * 0.45 + vec2(t * 0.11, t * 0.07)) * 0.6 + + value_noise(p * 1.3 - vec2(t * 0.19, -t * 0.05)) * 0.4; +} + +void vertex() { + world_position = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz; +} + +void fragment() { + vec2 p = world_position.xz; + float t = TIME; + + // Thickness of water between this surface and whatever is behind it. + float scene_depth = texture(depth_texture, SCREEN_UV).r; + vec4 behind = INV_PROJECTION_MATRIX * vec4(SCREEN_UV * 2.0 - 1.0, scene_depth, 1.0); + behind.xyz /= behind.w; + float thickness = max(-behind.z - (-VERTEX.z), 0.0); + // Convert view distance to roughly vertical metres using the view angle. + float vertical = thickness * clamp(abs(normalize(VERTEX).y) + 0.25, 0.25, 1.0); + + float deep = 1.0 - exp(-vertical / depth_scale); + vec3 water = mix(shallow_colour, deep_colour, deep); + + float e = 0.35; + float h = waves(p, t); + float hx = waves(p + vec2(e, 0.0), t) - h; + float hz = waves(p + vec2(0.0, e), t) - h; + // Ripples fade with distance, so the far sea doesn't shimmer into noise. + float ripple = ripple_strength * exp(-length(VERTEX) / 140.0); + vec3 n = normalize(vec3(-hx * ripple / e, 1.0, -hz * ripple / e)); + NORMAL = normalize((VIEW_MATRIX * vec4(n, 0.0)).xyz); + + float foam_edge = 1.0 - smoothstep(0.0, foam_width, vertical + (h - 0.5) * 0.4); + ALBEDO = mix(water, foam_colour, foam_edge * 0.85); + ROUGHNESS = mix(0.12, 0.6, foam_edge); + METALLIC = 0.0; + SPECULAR = 0.5; + ALPHA = clamp(mix(0.55, 0.96, deep) + foam_edge * 0.3, 0.0, 1.0); +} diff --git a/src/client/water/water.gdshader.uid b/src/client/water/water.gdshader.uid new file mode 100644 index 0000000..ecc1eed --- /dev/null +++ b/src/client/water/water.gdshader.uid @@ -0,0 +1 @@ +uid://b7qhmjym78vlr diff --git a/src/client/water/water_view.gd b/src/client/water/water_view.gd new file mode 100644 index 0000000..70cad03 --- /dev/null +++ b/src/client/water/water_view.gd @@ -0,0 +1,58 @@ +## Draws the sea: one flat surface at the simulation's sea level, wide enough to reach +## past the horizon from anywhere on the island. `follow(sim)` moves it whenever the +## tide changes the level, so what players see is always the level the server uses. +## The surface is the only thing here; drowning and swimming live in the simulation. +class_name WaterView +extends Node3D + +const SHADER: Shader = preload("res://src/client/water/water.gdshader") +## Side of the surface, in metres, centred on the world. +const SIZE: float = 6000.0 +## Grid steps across the surface. It is flat, so few are needed. +const SUBDIVISIONS: int = 32 + +var level: float = 0.0 + +var _surface: MeshInstance3D + + +func _ready() -> void: + if _surface == null: + _build() + + +## Places the surface at `sea_level`. Cheap; safe to call every frame. +func set_level(sea_level: float) -> void: + if _surface == null: + _build() + level = sea_level + _surface.position.y = sea_level + + +## Matches the surface to the simulation's current sea level. +func follow(sim: Simulation) -> void: + if not is_equal_approx(sim.sea_level, level) or _surface == null: + set_level(sim.sea_level) + + +func surface() -> MeshInstance3D: + if _surface == null: + _build() + return _surface + + +func _build() -> void: + var mesh: PlaneMesh = PlaneMesh.new() + mesh.size = Vector2(SIZE, SIZE) + mesh.subdivide_width = SUBDIVISIONS + mesh.subdivide_depth = SUBDIVISIONS + var material: ShaderMaterial = ShaderMaterial.new() + material.shader = SHADER + mesh.material = material + _surface = MeshInstance3D.new() + _surface.name = "Sea" + _surface.mesh = mesh + _surface.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF + var centre: float = Tuning.WORLD_SIZE_METRES * 0.5 + _surface.position = Vector3(centre, level, centre) + add_child(_surface) diff --git a/src/client/water/water_view.gd.uid b/src/client/water/water_view.gd.uid new file mode 100644 index 0000000..8bda68d --- /dev/null +++ b/src/client/water/water_view.gd.uid @@ -0,0 +1 @@ +uid://fkpqxmr813lf diff --git a/src/sim/movement.gd b/src/sim/movement.gd index ea0d062..d7f927e 100644 --- a/src/sim/movement.gd +++ b/src/sim/movement.gd @@ -1,6 +1,6 @@ ## Command-driven player movement: walk, sprint, crouch, jump, gravity, slopes, -## step-up, sliding and fall damage. Deterministic: it depends only on the entity, the -## command and the ground. +## step-up, sliding, fall damage, wading and swimming. Deterministic: it depends only on +## the entity, the command, the ground and the sea level. class_name Movement extends RefCounted @@ -9,7 +9,9 @@ const DT: float = 1.0 / Tuning.TICK_RATE_HZ ## Advances one player by one tick. `command` may be null, meaning no input this tick: ## the player keeps looking the same way and stops trying to move, but still falls. -static func step(player: SimEntity, command: PlayerCommand, ground: SimGround) -> void: +## `sea_level` is the water surface; the default means no water at all. Breath, stamina +## and drowning are Water's job, after this. +static func step(player: SimEntity, command: PlayerCommand, ground: SimGround, sea_level: float = -INF) -> void: var wish: Vector3 = Vector3.ZERO var wants_jump: bool = false player.crouching = false @@ -20,6 +22,20 @@ static func step(player: SimEntity, command: PlayerCommand, ground: SimGround) - wants_jump = command.is_pressed(PlayerCommand.BUTTON_JUMP) and not player.crouching wish = _wish_velocity(command, player.crouching) + if player.swimming: + if wants_jump and player.stamina_ticks > 0 and _at_surface(player, sea_level): + # Kick up out of the water. Airborne from here; back in if it lands in deep water. + player.swimming = false + player.on_ground = false + player.velocity.y = Tuning.JUMP_VELOCITY + else: + _swim(player, command, ground, sea_level) + return + + # Wading: water over the feet slows walkers and stops sprinting. + if player.on_ground and sea_level - player.position.y > Tuning.WADE_DEPTH: + wish = wish.limit_length(Tuning.WADE_SPEED) + var velocity: Vector3 = player.velocity if player.on_ground: velocity.x = wish.x @@ -33,7 +49,10 @@ static func step(player: SimEntity, command: PlayerCommand, ground: SimGround) - velocity.z += (wish.z - velocity.z) * Tuning.AIR_CONTROL velocity = _move_horizontally(player, velocity, ground) - _move_vertically(player, velocity, ground) + _move_vertically(player, velocity, ground, sea_level) + # Walked, or the tide rose, into water deep enough to swim. + if not player.swimming and player.on_ground and Water.is_deep(sea_level, player.position.y): + _enter_water(player) ## Height of the player's body, which shrinks while crouching. @@ -82,12 +101,13 @@ static func _move_horizontally(player: SimEntity, velocity: Vector3, ground: Sim static func _can_move_to(player: SimEntity, target: Vector3, ground: SimGround) -> bool: - var step: float = Tuning.STEP_HEIGHT if player.on_ground else 0.0 + var supported: bool = player.on_ground or player.swimming + var step: float = Tuning.STEP_HEIGHT if supported else 0.0 # On foot, the body is tested where it will stand: on whatever it steps up onto at # the target. Otherwise the next riser of a stair narrower than the body would block # a player who hasn't been lifted onto the current one yet. var body: Vector3 = target - if player.on_ground: + if supported: body.y = maxf(target.y, ground.support_height(target.x, target.z, target.y + step)) if ground.body_blocked(body, Tuning.PLAYER_RADIUS, body_height(player), step): return false @@ -100,7 +120,7 @@ static func _can_move_to(player: SimEntity, target: Vector3, ground: SimGround) return true -static func _move_vertically(player: SimEntity, velocity: Vector3, ground: SimGround) -> void: +static func _move_vertically(player: SimEntity, velocity: Vector3, ground: SimGround, sea_level: float) -> void: var feet: Vector3 = player.position if player.on_ground: var reach: float = feet.y + Tuning.STEP_HEIGHT @@ -125,6 +145,12 @@ static func _move_vertically(player: SimEntity, velocity: Vector3, ground: SimGr player.position.y = new_y var support: float = ground.support_height(feet.x, feet.z, maxf(feet.y, new_y)) + # Falling into deep water: the water catches the player, with no fall damage. + if velocity.y <= 0.0 and Water.is_deep(sea_level, support) and new_y <= sea_level - Tuning.SWIM_DEPTH: + player.position.y = maxf(new_y, support) + player.velocity = velocity + _enter_water(player) + return if new_y > support: player.velocity = velocity return @@ -157,3 +183,67 @@ static func _land(player: SimEntity, impact_speed: float) -> void: var excess: float = drop - Tuning.FALL_DAMAGE_SAFE_METRES if excess > 0.0: player.health = maxi(player.health - roundi(excess * Tuning.FALL_DAMAGE_PER_METRE), 0) + + +static func _enter_water(player: SimEntity) -> void: + player.swimming = true + player.on_ground = false + player.velocity.y *= Tuning.WATER_ENTRY_DAMP + + +## True when a swimmer is up at the surface, head out, and so can kick out of the water. +static func _at_surface(player: SimEntity, sea_level: float) -> bool: + return player.position.y >= sea_level - Tuning.SWIM_FLOAT_DEPTH - 0.2 + + +## One tick in deep water. Swimmers move at SWIM_SPEED (faster sprinting while stamina +## lasts), float with the head out, dive while crouch is held, and rest on the sea floor +## rather than sinking through it. Out of stamina, they slip under. Where the water +## over the floor gets shallow they stand up and walk. +static func _swim(player: SimEntity, command: PlayerCommand, ground: SimGround, sea_level: float) -> void: + var has_stamina: bool = player.stamina_ticks > 0 + var speed: float = Tuning.SWIM_SPEED + var diving: bool = false + var move: Vector3 = Vector3.ZERO + if command != null: + var input: Vector2 = command.move_vector() + if input.length() > 1.0: + input = input.normalized() + var angle: float = command.yaw_radians() + var forward: Vector3 = Vector3(sin(angle), 0.0, cos(angle)) + var right: Vector3 = Vector3(-cos(angle), 0.0, sin(angle)) + move = right * input.x + forward * input.y + diving = command.is_pressed(PlayerCommand.BUTTON_CROUCH) + if command.is_pressed(PlayerCommand.BUTTON_SPRINT) and has_stamina and input.y > 0.0: + speed = Tuning.SWIM_SPRINT_SPEED + if not has_stamina: + speed *= Tuning.SWIM_EXHAUSTED_FACTOR + var velocity: Vector3 = move * speed + + var float_depth: float = Tuning.SWIM_FLOAT_DEPTH if has_stamina else Tuning.SWIM_EXHAUSTED_DEPTH + var wanted: float = -Tuning.SWIM_VERTICAL_SPEED + if not diving: + wanted = clampf((sea_level - float_depth - player.position.y) * 4.0, -Tuning.SWIM_VERTICAL_SPEED, Tuning.SWIM_VERTICAL_SPEED) + velocity.y = move_toward(player.velocity.y, wanted, Tuning.SWIM_VERTICAL_ACCEL * DT) + + velocity = _move_horizontally(player, velocity, ground) + var new_y: float = player.position.y + velocity.y * DT + var floor_y: float = ground.support_height(player.position.x, player.position.z, maxf(player.position.y, new_y) + Tuning.STEP_HEIGHT) + if new_y <= floor_y: + new_y = floor_y + velocity.y = maxf(velocity.y, 0.0) + if velocity.y > 0.0 and ground.body_blocked(Vector3(player.position.x, new_y, player.position.z), Tuning.PLAYER_RADIUS, body_height(player), 0.0): + new_y = player.position.y + velocity.y = 0.0 + player.position.y = new_y + player.velocity = velocity + + # Shallow enough to stand: back on foot, without fall damage. + if sea_level - floor_y < Tuning.SWIM_EXIT_DEPTH: + player.swimming = false + if floor_y >= player.position.y - Tuning.GROUND_SNAP: + player.position.y = floor_y + player.velocity.y = 0.0 + player.on_ground = _walkable_support(ground, player.position) + else: + player.on_ground = false diff --git a/src/sim/sim_entity.gd b/src/sim/sim_entity.gd index 284b655..fb4d168 100644 --- a/src/sim/sim_entity.gd +++ b/src/sim/sim_entity.gd @@ -14,6 +14,12 @@ var health: int = 0 ## Standing on walkable ground. False while jumping, falling or sliding. var on_ground: bool = false var crouching: bool = false +## Floating or diving in deep water. Swimmers can't build or fire. +var swimming: bool = false +## Breath, stamina and time spent without breath, in ticks. See Water. +var breath_ticks: int = 0 +var stamina_ticks: int = 0 +var drown_ticks: int = 0 func _init(entity_id: int, entity_archetype: int) -> void: diff --git a/src/sim/simulation.gd b/src/sim/simulation.gd index 87151ab..2fc7a99 100644 --- a/src/sim/simulation.gd +++ b/src/sim/simulation.gd @@ -21,6 +21,11 @@ var pois: PoiSet = PoiSet.new() ## Trees, scrub, boulders, wrecks and crates, whose boxes are part of `ground`. Empty ## when a test supplied its own ground. var props: PropSet = PropSet.new() +## Height of the sea surface, in metres. The tide changes it during a match; movement +## and drowning read it every tick, so a change takes effect on the next step. +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"] ## Player entity ID -> { command tick -> PlayerCommand } var _pending: Dictionary = {} @@ -59,6 +64,7 @@ func add_player() -> int: player.position = Vector3(x, ground.terrain_height(x, z), z) player.on_ground = true player.health = Tuning.PLAYER_MAX_HEALTH + Water.reset(player) _players.append(player.id) _pending[player.id] = {} return player.id @@ -94,7 +100,14 @@ func step() -> void: func _apply_command(player: SimEntity, command: PlayerCommand) -> void: - Movement.step(player, command, ground) + Movement.step(player, command, ground, sea_level) + var sprinting: bool = command != null and command.is_pressed(PlayerCommand.BUTTON_SPRINT) + Water.update(player, sea_level, drown_dps, sprinting) + + +## Moves the sea surface. Takes effect on the next step. +func set_sea_level(level: float) -> void: + sea_level = level ## Damages a prop. Returns true if this destroyed it; its collision goes at once. @@ -119,12 +132,17 @@ func state_hash() -> String: buffer.put_32(entity.health) buffer.put_32(entity.yaw) buffer.put_32(entity.pitch) - buffer.put_u8((1 if entity.on_ground else 0) | (2 if entity.crouching else 0)) + buffer.put_u8((1 if entity.on_ground else 0) | (2 if entity.crouching else 0) | (4 if entity.swimming else 0)) + buffer.put_32(entity.breath_ticks) + buffer.put_32(entity.stamina_ticks) + buffer.put_32(entity.drown_ticks) for value: float in [entity.position.x, entity.position.y, entity.position.z]: buffer.put_64(roundi(value * 1000.0)) for value: float in [entity.velocity.x, entity.velocity.y, entity.velocity.z]: buffer.put_64(roundi(value * 1000.0)) + buffer.put_64(roundi(sea_level * 1000.0)) + buffer.put_32(drown_dps) buffer.put_64(props.count()) buffer.put_data(props.health.to_byte_array()) diff --git a/src/sim/tuning.gd b/src/sim/tuning.gd index c9289ea..f5ce2e0 100644 --- a/src/sim/tuning.gd +++ b/src/sim/tuning.gd @@ -49,6 +49,34 @@ const CROUCH_HEIGHT: float = 1.2 const FALL_DAMAGE_SAFE_METRES: float = 6.0 const FALL_DAMAGE_PER_METRE: float = 8.0 +# Water, in metres and seconds. Depths are water over the floor under the player. +## The sea level a match starts at. The tide raises it from here. +const SEA_LEVEL_START: float = 0.0 +## Deeper than this, walkers wade at WADE_SPEED and can't sprint. +const WADE_DEPTH: float = 0.4 +## Water this deep over the floor lifts a player off it to swim. +const SWIM_DEPTH: float = 1.35 +## A swimmer stands again where the water over the floor is shallower than this. +const SWIM_EXIT_DEPTH: float = 1.2 +## A swimmer floats with the feet this far under the surface, head out. +const SWIM_FLOAT_DEPTH: float = 1.3 +## With no stamina left a swimmer sinks until the feet are this far under: head under. +const SWIM_EXHAUSTED_DEPTH: float = 2.2 +const SWIM_SPRINT_SPEED: float = 3.2 +## Fraction of SWIM_SPEED left to an exhausted swimmer. +const SWIM_EXHAUSTED_FACTOR: float = 0.6 +## Diving and rising speed, and how fast vertical speed changes in the water. +const SWIM_VERTICAL_SPEED: float = 2.0 +const SWIM_VERTICAL_ACCEL: float = 12.0 +## Fraction of downward speed kept on hitting deep water. +const WATER_ENTRY_DAMP: float = 0.25 +## Seconds of paddling a full stamina bar allows. Sprint-swimming spends it faster. +const SWIM_STAMINA_SECONDS: float = 45.0 +const SWIM_SPRINT_STAMINA_COST: int = 3 +## Ticks of stamina and breath regained per tick out of the water or above it. +const STAMINA_RECOVERY_RATE: int = 3 +const BREATH_RECOVERY_RATE: int = 4 + # The island. Worldgen fills the whole world square; the island is about a kilometre # across, sized for 24 players. Heights are metres above the starting sea level. ## Spacing of the terrain heightfield, in metres. The grid covers WORLD_SIZE_METRES. diff --git a/src/sim/water.gd b/src/sim/water.gd new file mode 100644 index 0000000..c83830d --- /dev/null +++ b/src/sim/water.gd @@ -0,0 +1,71 @@ +## The sea as the simulation sees it: one global level that the tide (M2) raises during +## a match, and what it does to players. Movement handles swimming itself; this keeps +## breath, stamina and drowning, and answers depth questions. +## +## Depths and states, for a player whose feet are at `y` over a floor at `floor`: +## - wading: on the floor in water deeper than WADE_DEPTH. Slower, no sprint. +## - swimming: water at least SWIM_DEPTH over the floor, so the player floats with the +## head above the surface (feet SWIM_FLOAT_DEPTH under it). Swimming costs stamina; +## with none left the player can't stay up and slips under. +## - under: head below the surface. Breath runs down; at zero the phase's drown damage +## lands once a second until the head is out again. +## Breath and stamina are counted in whole ticks, so they hash and replay exactly. +class_name Water +extends RefCounted + +const TICKS: int = Tuning.TICK_RATE_HZ + + +## Water depth over a floor at `floor_y`, or 0 on dry ground. +static func depth_over(sea_level: float, floor_y: float) -> float: + return maxf(sea_level - floor_y, 0.0) + + +## True when the water over `floor_y` is deep enough to swim in. +static func is_deep(sea_level: float, floor_y: float) -> bool: + return sea_level - floor_y >= Tuning.SWIM_DEPTH + + +static func head_under(player: SimEntity, sea_level: float) -> bool: + return player.position.y + Movement.body_height(player) < sea_level + + +static func max_breath_ticks() -> int: + return roundi(Tuning.BREATH_SECONDS * TICKS) + + +static func max_stamina_ticks() -> int: + return roundi(Tuning.SWIM_STAMINA_SECONDS * TICKS) + + +## Gives a new player full breath and stamina. +static func reset(player: SimEntity) -> void: + player.breath_ticks = max_breath_ticks() + player.stamina_ticks = max_stamina_ticks() + player.drown_ticks = 0 + + +## Updates breath, stamina and drowning for one tick, after the player has moved. +## `sprinting` is whether the player asked to swim fast this tick. +static func update(player: SimEntity, sea_level: float, drown_dps: int, sprinting: bool) -> void: + if player.health <= 0: + return + # Stamina: swimming drains it, faster when sprinting; out of the water it returns. + if player.swimming: + var cost: int = Tuning.SWIM_SPRINT_STAMINA_COST if sprinting else 1 + player.stamina_ticks = maxi(player.stamina_ticks - cost, 0) + else: + player.stamina_ticks = mini(player.stamina_ticks + Tuning.STAMINA_RECOVERY_RATE, max_stamina_ticks()) + + if head_under(player, sea_level): + if player.breath_ticks > 0: + player.breath_ticks -= 1 + player.drown_ticks = 0 + else: + player.drown_ticks += 1 + if player.drown_ticks >= TICKS: + player.drown_ticks = 0 + player.health = maxi(player.health - drown_dps, 0) + else: + player.drown_ticks = 0 + player.breath_ticks = mini(player.breath_ticks + Tuning.BREATH_RECOVERY_RATE, max_breath_ticks()) diff --git a/src/sim/water.gd.uid b/src/sim/water.gd.uid new file mode 100644 index 0000000..e5bbe15 --- /dev/null +++ b/src/sim/water.gd.uid @@ -0,0 +1 @@ +uid://c7e4vegn1qf4y diff --git a/test/capture/terrain_scene.gd b/test/capture/terrain_scene.gd index eb2e7ef..132c66f 100644 --- a/test/capture/terrain_scene.gd +++ b/test/capture/terrain_scene.gd @@ -19,6 +19,9 @@ const CRACK_COLOUR: Color = Color(1.0, 0.0, 1.0) ## the camera stands `poi_view` (x right, y up, z out of the front) from its origin. @export var poi_kind: String = "" @export var poi_view: Vector3 = Vector3(6.0, 7.0, 22.0) +## Draw the sea at `sea_level`. Never in crack checks, where it would hide seams. +@export var show_water: bool = true +@export var sea_level: float = Tuning.SEA_LEVEL_START ## Draw the island's props too. @export var show_props: bool = false ## When set, frame the first prop of this kind whose surroundings hold at least @@ -113,6 +116,10 @@ func _ready() -> void: sim_props.damage(crowd[index], 100000) prop_view_node.sync() break + if show_water and not crack_check: + var water: WaterView = WaterView.new() + water.set_level(sea_level) + add_child(water) add_child(camera) camera.look_at(look_at_point) camera.make_current() diff --git a/test/capture/water_flood.tscn b/test/capture/water_flood.tscn new file mode 100644 index 0000000..4ed3d2a --- /dev/null +++ b/test/capture/water_flood.tscn @@ -0,0 +1,9 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"] + +[node name="CaptureWater" type="Node3D"] +script = ExtResource("1") +island_seed = 2 +show_props = true +sea_level = 18.0 diff --git a/test/capture/water_shore.tscn b/test/capture/water_shore.tscn new file mode 100644 index 0000000..46ccf19 --- /dev/null +++ b/test/capture/water_shore.tscn @@ -0,0 +1,10 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/terrain_scene.gd" id="1"] + +[node name="CaptureWater" type="Node3D"] +script = ExtResource("1") +island_seed = 2 +show_props = true +poi_kind = "dock" +poi_view = Vector3(-18, 9, 26) diff --git a/test/client/test_water_view.gd b/test/client/test_water_view.gd new file mode 100644 index 0000000..e41414e --- /dev/null +++ b/test/client/test_water_view.gd @@ -0,0 +1,20 @@ +extends TestCase + +## The client sea from issue W6 follows the simulation's sea level. + + +func test_surface_follows_the_simulation_sea_level() -> void: + var sim: Simulation = Simulation.new(1, SimGround.flat()) + var view: WaterView = WaterView.new() + view.follow(sim) + assert_eq(view.surface().position.y, Tuning.SEA_LEVEL_START) + sim.set_sea_level(8.0) + view.follow(sim) + assert_eq(view.surface().position.y, 8.0) + assert_eq(view.level, 8.0) + # The surface covers the whole world and well past it, so no edge is ever in view. + var mesh: PlaneMesh = view.surface().mesh + assert_true(mesh.size.x >= Tuning.WORLD_SIZE_METRES * 4.0) + assert_near(view.surface().position.x, Tuning.WORLD_SIZE_METRES * 0.5, 0.001) + assert_eq(view.surface().cast_shadow, GeometryInstance3D.SHADOW_CASTING_SETTING_OFF) + view.free() diff --git a/test/client/test_water_view.gd.uid b/test/client/test_water_view.gd.uid new file mode 100644 index 0000000..471660d --- /dev/null +++ b/test/client/test_water_view.gd.uid @@ -0,0 +1 @@ +uid://bqm81iki1cguk diff --git a/test/sim/test_water.gd b/test/sim/test_water.gd new file mode 100644 index 0000000..c1371dd --- /dev/null +++ b/test/sim/test_water.gd @@ -0,0 +1,231 @@ +extends TestCase + +## Water and swimming from issue W6: wading, swimming, stamina, breath, drowning, and a +## sea level that can change mid-match. + +const EAST: float = PI * 0.5 +const WEST: float = -PI * 0.5 +const SECOND: int = Tuning.TICK_RATE_HZ + +var _tick: int = 0 + + +func before_each() -> void: + _tick = 0 + + +## Flat ground at height 0 for x < 20, sloping down at 1 in 4 to -10 at x = 60, flat beyond. +func _beach() -> SimGround: + var side: int = 128 + var values: PackedFloat32Array = PackedFloat32Array() + values.resize(side * side) + for z: int in side: + for x: int in side: + values[z * side + x] = -clampf((float(x) - 20.0) * 0.25, 0.0, 10.0) + return SimGround.from_heights(values, side, 1.0) + + +func _player(at: Vector3) -> SimEntity: + var player: SimEntity = SimEntity.new(1, SimEntity.ARCHETYPE_PLAYER) + player.position = at + player.health = Tuning.PLAYER_MAX_HEALTH + player.on_ground = true + Water.reset(player) + return player + + +func _run(player: SimEntity, ground: SimGround, sea: float, ticks: int, move: Vector2, yaw: float, buttons: int = 0, drown_dps: int = 5) -> void: + for _index: int in ticks: + var command: PlayerCommand = PlayerCommand.from_input(_tick, move, yaw, 0.0, buttons) + _tick += 1 + Movement.step(player, command, ground, sea) + Water.update(player, sea, drown_dps, command.is_pressed(PlayerCommand.BUTTON_SPRINT)) + + +func test_wading_slows_walkers_and_stops_sprinting() -> void: + var ground: SimGround = _beach() + # Sea 0.8 m over the flat part of the beach: deeper than WADE_DEPTH, too shallow to swim. + var player: SimEntity = _player(Vector3(5.0, 0.0, 64.0)) + _run(player, ground, 0.8, SECOND, Vector2(0.0, 1.0), EAST, PlayerCommand.BUTTON_SPRINT) + assert_false(player.swimming) + assert_true(player.on_ground) + assert_near(player.position.x - 5.0, Tuning.WADE_SPEED, 0.01) + # Ankle-deep water doesn't slow anyone. + var dry: SimEntity = _player(Vector3(5.0, 0.0, 70.0)) + _run(dry, ground, Tuning.WADE_DEPTH - 0.1, SECOND, Vector2(0.0, 1.0), EAST, PlayerCommand.BUTTON_SPRINT) + assert_near(dry.position.x - 5.0, Tuning.SPRINT_SPEED, 0.01) + + +func test_walking_into_the_sea_swims_and_walking_out_stands_again() -> void: + var ground: SimGround = _beach() + var player: SimEntity = _player(Vector3(10.0, 0.0, 64.0)) + _run(player, ground, -2.0, SECOND, Vector2(0.0, 1.0), EAST) + assert_near(player.position.x, 10.0 + Tuning.WALK_SPEED, 0.01) + var reached_swim: bool = false + for _tick: int in SECOND * 15: + _run(player, ground, -2.0, 1, Vector2(0.0, 1.0), EAST) + if player.swimming: + reached_swim = true + break + # The floor drops 1 in 4, so swimming starts where it is SWIM_DEPTH under the sea. + var expected_x: float = 20.0 + (2.0 + Tuning.SWIM_DEPTH) * 4.0 + assert_near(player.position.x, expected_x, 0.3) + assert_true(reached_swim, "never started swimming, at %s" % player.position) + assert_false(player.on_ground) + # Floating: feet SWIM_FLOAT_DEPTH under the surface, head out. + _run(player, ground, -2.0, SECOND * 2, Vector2(0.0, 1.0), EAST) + assert_near(player.position.y, -2.0 - Tuning.SWIM_FLOAT_DEPTH, 0.05) + assert_false(Water.head_under(player, -2.0)) + var x0: float = player.position.x + _run(player, ground, -2.0, SECOND, Vector2(0.0, 1.0), EAST) + assert_near(player.position.x - x0, Tuning.SWIM_SPEED, 0.05) + # Back to shore: standing again once the water is shallow. + _run(player, ground, -2.0, SECOND * 15, Vector2(0.0, 1.0), WEST) + assert_false(player.swimming, "still swimming at %s" % player.position) + assert_true(player.on_ground) + assert_true(player.position.x < 20.0) + assert_near(player.position.y, ground.terrain_height(player.position.x, 64.0), 0.01) + assert_eq(player.health, Tuning.PLAYER_MAX_HEALTH) + + +func test_swimming_drains_stamina_and_exhaustion_drowns() -> void: + var ground: SimGround = _beach() + var sea: float = 0.0 + var player: SimEntity = _player(Vector3(100.0, -10.0, 64.0)) + _run(player, ground, sea, 2, Vector2.ZERO, EAST) + assert_true(player.swimming) + var full: int = Water.max_stamina_ticks() + # Sprint-swimming costs more than paddling. + _run(player, ground, sea, SECOND, Vector2(0.0, 1.0), WEST, PlayerCommand.BUTTON_SPRINT) + var after_sprint: int = player.stamina_ticks + assert_eq(full - after_sprint, (SECOND + 2) * Tuning.SWIM_SPRINT_STAMINA_COST - 2 * (Tuning.SWIM_SPRINT_STAMINA_COST - 1)) + _run(player, ground, sea, SECOND, Vector2(0.0, 1.0), EAST) + assert_eq(after_sprint - player.stamina_ticks, SECOND) + # Tread water until exhausted: then the swimmer slips under and loses breath. + _run(player, ground, sea, player.stamina_ticks, Vector2.ZERO, EAST) + assert_eq(player.stamina_ticks, 0) + _run(player, ground, sea, SECOND * 2, Vector2.ZERO, EAST) + assert_true(Water.head_under(player, sea), "an exhausted swimmer should go under, feet at %.2f" % player.position.y) + assert_true(player.breath_ticks < Water.max_breath_ticks()) + assert_eq(player.health, Tuning.PLAYER_MAX_HEALTH, "no damage while breath lasts") + # Breath runs out, then drown damage lands once a second. + _run(player, ground, sea, player.breath_ticks, Vector2.ZERO, EAST) + assert_eq(player.breath_ticks, 0) + assert_eq(player.health, Tuning.PLAYER_MAX_HEALTH) + _run(player, ground, sea, SECOND * 3, Vector2.ZERO, EAST, 0, 7) + assert_eq(player.health, Tuning.PLAYER_MAX_HEALTH - 21) + # Drowning continues to death and stops there. + _run(player, ground, sea, SECOND * 30, Vector2.ZERO, EAST, 0, 7) + assert_eq(player.health, 0) + + +func test_diving_costs_breath_and_surfacing_restores_it() -> void: + var ground: SimGround = _beach() + var player: SimEntity = _player(Vector3(100.0, -10.0, 64.0)) + # Rise from the sea floor to the surface first. + _run(player, ground, 0.0, SECOND * 8, Vector2.ZERO, EAST) + assert_eq(player.breath_ticks, Water.max_breath_ticks()) + _run(player, ground, 0.0, SECOND * 2, Vector2.ZERO, EAST, PlayerCommand.BUTTON_CROUCH) + assert_true(Water.head_under(player, 0.0), "diving should take the head under") + assert_true(player.position.y < -Tuning.SWIM_FLOAT_DEPTH - 1.0) + var low: int = player.breath_ticks + assert_true(low < Water.max_breath_ticks()) + _run(player, ground, 0.0, SECOND * 3, Vector2.ZERO, EAST) + assert_false(Water.head_under(player, 0.0)) + assert_true(player.breath_ticks > low) + _run(player, ground, 0.0, SECOND * 10, Vector2.ZERO, EAST) + assert_eq(player.breath_ticks, Water.max_breath_ticks()) + # Divers rest on the sea floor rather than sinking through it. + _run(player, ground, 0.0, SECOND * 10, Vector2.ZERO, EAST, PlayerCommand.BUTTON_CROUCH) + assert_true(player.position.y >= ground.terrain_height(100.0, 64.0) - 0.001) + + +func test_falling_into_deep_water_does_no_fall_damage() -> void: + var ground: SimGround = _beach() + var player: SimEntity = _player(Vector3(100.0, 40.0, 64.0)) + player.on_ground = false + _run(player, ground, 0.0, SECOND * 4, Vector2.ZERO, EAST) + assert_true(player.swimming) + assert_eq(player.health, Tuning.PLAYER_MAX_HEALTH) + # The same fall onto dry ground hurts. + var dry: SimEntity = _player(Vector3(5.0, 40.0, 64.0)) + dry.on_ground = false + _run(dry, ground, 0.0, SECOND * 4, Vector2.ZERO, EAST) + assert_true(dry.health < Tuning.PLAYER_MAX_HEALTH) + + +func test_jumping_from_the_water_leaves_it_and_lands_back_in() -> void: + var ground: SimGround = _beach() + var player: SimEntity = _player(Vector3(100.0, -10.0, 64.0)) + _run(player, ground, 0.0, SECOND * 8, Vector2.ZERO, EAST) + var float_y: float = player.position.y + _run(player, ground, 0.0, 1, Vector2.ZERO, EAST, PlayerCommand.BUTTON_JUMP) + assert_false(player.swimming) + var peak: float = player.position.y + for _i: int in SECOND: + _run(player, ground, 0.0, 1, Vector2.ZERO, EAST) + peak = maxf(peak, player.position.y) + assert_true(peak > float_y + 1.0, "jumped only to %.2f from %.2f" % [peak, float_y]) + _run(player, ground, 0.0, SECOND, Vector2.ZERO, EAST) + assert_true(player.swimming) + assert_eq(player.health, Tuning.PLAYER_MAX_HEALTH) + # No jumping out with no stamina left. + player.stamina_ticks = 0 + _run(player, ground, 0.0, 1, Vector2.ZERO, EAST, PlayerCommand.BUTTON_JUMP) + assert_true(player.swimming) + + +func test_raising_the_sea_takes_effect_on_the_next_tick() -> void: + var sim: Simulation = Simulation.new(1, _beach()) + var id: int = sim.add_player() + var player: SimEntity = sim.entities.find(id) + player.position = Vector3(10.0, 0.0, 64.0) + player.on_ground = true + assert_eq(sim.sea_level, Tuning.SEA_LEVEL_START) + sim.step() + assert_false(player.swimming) + sim.set_sea_level(3.0) + sim.step() + assert_true(player.swimming, "the sea rose over the player's head but they aren't swimming") + for _i: int in SECOND * 3: + sim.step() + assert_near(player.position.y, 3.0 - Tuning.SWIM_FLOAT_DEPTH, 0.05) + assert_eq(player.breath_ticks, Water.max_breath_ticks(), "a swimmer floating at the surface breathes again") + # Wading depth slows walking at once. + sim.set_sea_level(0.9) + for _i: int in SECOND * 2: + sim.step() + assert_false(player.swimming) + assert_true(player.on_ground) + var x0: float = player.position.x + for _i: int in SECOND: + sim.submit_command(id, PlayerCommand.from_input(sim.tick, Vector2(0.0, 1.0), WEST, 0.0, PlayerCommand.BUTTON_SPRINT)) + sim.step() + assert_near(x0 - player.position.x, Tuning.WADE_SPEED, 0.05) + # Dropping the sea leaves a dry player walking at full pace. + sim.set_sea_level(-5.0) + x0 = player.position.x + for _i: int in SECOND: + sim.submit_command(id, PlayerCommand.from_input(sim.tick, Vector2(0.0, 1.0), WEST, 0.0, 0)) + sim.step() + assert_near(x0 - player.position.x, Tuning.WALK_SPEED, 0.05) + + +func test_water_state_is_hashed_and_deterministic() -> void: + var a: Simulation = Simulation.new(2, _beach()) + var b: Simulation = Simulation.new(2, _beach()) + var a_id: int = 0 + for sim: Simulation in [a, b]: + var id: int = sim.add_player() + a_id = id + var player: SimEntity = sim.entities.find(id) + player.position = Vector3(100.0, -10.0, 64.0) + for _i: int in SECOND * 3: + sim.submit_command(id, PlayerCommand.from_input(sim.tick, Vector2(0.0, 1.0), EAST, 0.0, PlayerCommand.BUTTON_CROUCH)) + sim.step() + assert_eq(a.state_hash(), b.state_hash()) + (a.entities.find(a_id) as SimEntity).breath_ticks -= 1 + assert_ne(a.state_hash(), b.state_hash(), "breath must be part of the hash") + (a.entities.find(a_id) as SimEntity).breath_ticks += 1 + a.set_sea_level(0.001) + assert_ne(a.state_hash(), b.state_hash(), "the sea level must be part of the hash") diff --git a/test/sim/test_water.gd.uid b/test/sim/test_water.gd.uid new file mode 100644 index 0000000..7e67e90 --- /dev/null +++ b/test/sim/test_water.gd.uid @@ -0,0 +1 @@ +uid://cko341rttixdi