diff --git a/Makefile b/Makefile index 76ef3fc..2c7ef79 100644 --- a/Makefile +++ b/Makefile @@ -63,7 +63,7 @@ discovery-check: import ## Renders what a network client sees on the barge, gliding and landed. Needs Docker. client-captures: import - @for stage in barge glide landed; do tools/capture.sh client_$$stage captures/client_$$stage.png; done + @for stage in barge glide landed basin build build_refused; do tools/capture.sh client_$$stage captures/client_$$stage.png; done ## Renders the capture test scenes in the offscreen container. Needs Docker. capture-test: import diff --git a/src/app/client_session.gd b/src/app/client_session.gd index e642aa3..a0d9d41 100644 --- a/src/app/client_session.gd +++ b/src/app/client_session.gd @@ -16,6 +16,8 @@ var link: NetClient = null var local: LocalServer = null ## The picture of the current match's world, or null before there is one. var view: MatchView = null +## Where a piece would go, in build mode while playing. A child of `view`. +var ghost: BuildGhost = null ## Every match phase this client has been in, in order, without repeats. var phases: Array[int] = [] ## Frames in which the client's own player was in the match, and frames pumped. @@ -130,19 +132,44 @@ func _show(delta: float) -> void: remove_child(view) view.queue_free() view = null + ghost = null if _viewed != null: view = MatchView.new() view.setup(_viewed, 0) add_child(view) move_child(view, 0) + ghost = BuildGhost.new() + ghost.visible = false + view.add_child(ghost) if view == null: return view.entities.local_id = mirror.own_id if mirror.own_id != 0 else view.entities.local_id view.entities.barge_at = mirror.barge_at view.rig.update_aim(input.aiming() and mirror.own_id != 0, delta) view.sync() + _show_ghost() if mirror.own_id != 0: # The player's own look is newer than any command made from it. view.follow(mirror.own_id, input.pitch, input.yaw) elif mirror.watched_id == 0 or not view.follow(mirror.watched_id): view.overview() + + +## The build ghost, in build mode while this client plays: the piece the next build +## would place, asked of the client's own world and predicted player, as the server +## will ask its own. Its look is the newest the mouse has given. +func _show_ghost() -> void: + if ghost == null: + return + var player: SimEntity = game.prediction.player + if not (input.build_mode and game.playing() and mirror.own_id != 0 and Building.is_allowed(player)): + ghost.visible = false + return + var yaw: int = player.yaw + var pitch: int = player.pitch + var look: PlayerCommand = PlayerCommand.from_input(0, Vector2.ZERO, input.yaw, input.pitch) + player.yaw = look.yaw + player.pitch = look.pitch + ghost.update(game.world, player, input.build_kind, input.material) + player.yaw = yaw + player.pitch = pitch diff --git a/src/client/water/water.gdshader b/src/client/water/water.gdshader index 36d771e..3b7edd8 100644 --- a/src/client/water/water.gdshader +++ b/src/client/water/water.gdshader @@ -15,6 +15,12 @@ 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; +// Where the flood reaches: one texel per flood cell, white where flooded, covering +// [0, flood_extent] metres on both axes. Dry cells inside it aren't drawn; outside it +// is open sea. +uniform bool use_flood_mask = false; +uniform sampler2D flood_mask : filter_nearest, repeat_disable; +uniform float flood_extent = 1024.0; varying vec3 world_position; @@ -44,6 +50,12 @@ void vertex() { void fragment() { vec2 p = world_position.xz; float t = TIME; + if (use_flood_mask) { + vec2 cell_uv = p / flood_extent; + if (all(greaterThanEqual(cell_uv, vec2(0.0))) && all(lessThan(cell_uv, vec2(1.0))) && texture(flood_mask, cell_uv).r < 0.5) { + discard; + } + } // Thickness of water between this surface and whatever is behind it. float scene_depth = texture(depth_texture, SCREEN_UV).r; diff --git a/src/client/water/water_view.gd b/src/client/water/water_view.gd index 70cad03..bcf0523 100644 --- a/src/client/water/water_view.gd +++ b/src/client/water/water_view.gd @@ -1,6 +1,9 @@ ## 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. +## Where the simulation has a flood, the sea is only drawn over the cells it reaches: +## a mask texture of the flooded cells goes to the shader, which leaves dry cells +## (a basin behind a breakwater) bare. The mask is rebuilt only when the flood pours. ## The surface is the only thing here; drowning and swimming live in the simulation. class_name WaterView extends Node3D @@ -14,6 +17,10 @@ const SUBDIVISIONS: int = 32 var level: float = 0.0 var _surface: MeshInstance3D +var _material: ShaderMaterial +var _mask: ImageTexture = null +var _mask_flood: Flood = null +var _mask_pours: int = -1 func _ready() -> void: @@ -29,10 +36,49 @@ func set_level(sea_level: float) -> void: _surface.position.y = sea_level -## Matches the surface to the simulation's current sea level. +## Matches the surface to the simulation's current sea level and flood. func follow(sim: Simulation) -> void: if not is_equal_approx(sim.sea_level, level) or _surface == null: set_level(sim.sea_level) + set_flood(sim.flood) + + +## Draws the sea only over `flood`'s flooded cells, or everywhere for null. Cheap +## when nothing has poured since the last call. +func set_flood(flood: Flood) -> void: + if _surface == null: + _build() + if flood == null: + _mask_flood = null + _mask_pours = -1 + _material.set_shader_parameter("use_flood_mask", false) + return + if flood == _mask_flood and flood.pours == _mask_pours: + return + _mask_flood = flood + _mask_pours = flood.pours + var bytes: PackedByteArray = flood.flooded.duplicate() + for index: int in bytes.size(): + if bytes[index] != 0: + bytes[index] = 255 + var image: Image = Image.create_from_data(flood.side, flood.side, false, Image.FORMAT_R8, bytes) + if _mask == null or _mask.get_width() != flood.side: + _mask = ImageTexture.create_from_image(image) + else: + _mask.update(image) + _material.set_shader_parameter("flood_mask", _mask) + _material.set_shader_parameter("flood_extent", flood.side * flood.cell) + _material.set_shader_parameter("use_flood_mask", true) + + +## True if the sea is drawn over the world point (x, z): flooded, or off the grid. +func shows_water_at(x: float, z: float) -> bool: + if _mask_flood == null: + return true + var extent: float = _mask_flood.side * _mask_flood.cell + if x < 0.0 or z < 0.0 or x >= extent or z >= extent: + return true + return _mask_flood.is_flooded(x, z) func surface() -> MeshInstance3D: @@ -46,9 +92,9 @@ func _build() -> void: mesh.size = Vector2(SIZE, SIZE) mesh.subdivide_width = SUBDIVISIONS mesh.subdivide_depth = SUBDIVISIONS - var material: ShaderMaterial = ShaderMaterial.new() - material.shader = SHADER - mesh.material = material + _material = ShaderMaterial.new() + _material.shader = SHADER + mesh.material = _material _surface = MeshInstance3D.new() _surface.name = "Sea" _surface.mesh = mesh diff --git a/src/net/client_game.gd b/src/net/client_game.gd index 56bb4ef..eb13fd3 100644 --- a/src/net/client_game.gd +++ b/src/net/client_game.gd @@ -18,6 +18,8 @@ extends RefCounted ## The most ticks predicted in one advance(). Further behind than this, the ticks in ## between go without commands. const MAX_CATCH_UP_TICKS: int = 12 +## FX records kept for views at most; older ones are dropped. +const MAX_FX: int = 256 var receiver: SnapshotReceiver = SnapshotReceiver.new() var prediction: ClientPrediction = ClientPrediction.new() @@ -52,6 +54,12 @@ var bad_packets: int = 0 ## expect `world` the moment a notice arrives leave it off. `make_world` must be safe ## to call from another thread when it is on. var build_in_background: bool = false +## Shots, impacts and swings the server reported (NetFx records, positions in world +## metres), oldest first, for views and sound to take. Kept to MAX_FX; whoever draws +## them empties it. +var fx: Array[Dictionary] = [] +## FX records received in all. +var fx_received: int = 0 ## Called after each snapshot has been taken in, with no arguments. Soak tests use it ## to compare the client's world with the server's at that moment. var on_snapshot: Callable = Callable() @@ -186,6 +194,16 @@ func _receive_now(channel: int, bytes: PackedByteArray) -> void: bad_packets += 1 return _take_notice(notice) + elif not bytes.is_empty() and bytes[0] == NetFx.MSG_FX: + var message: Dictionary = NetFx.decode(bytes) + if message.is_empty(): + bad_packets += 1 + return + for record: Dictionary in message["events"]: + fx.append(record) + fx_received += 1 + while fx.size() > MAX_FX: + fx.pop_front() elif receiver.apply(bytes): _take_snapshot() if on_snapshot.is_valid(): diff --git a/src/net/client_mirror.gd b/src/net/client_mirror.gd index 70d75c3..68ca735 100644 --- a/src/net/client_mirror.gd +++ b/src/net/client_mirror.gd @@ -21,8 +21,14 @@ var barge_at: Vector3 = Vector3.INF ## The moment being drawn, in simulation ticks. var time: float = 0.0 +## Ticks of flood the client works through at most in one frame. +const MAX_FLOOD_CATCH_UP_TICKS: int = 90 + var _drop: Drop = null var _drop_world: Simulation = null +## The last tick the client's flood was brought up to, and for which world. +var _flood_tick: int = 0 +var _flood_world: Simulation = null func sync(game: ClientGame) -> void: @@ -44,6 +50,7 @@ func sync(game: ClientGame) -> void: time = float(receiver.sim_tick) world.tick = maxi(floori(time), 0) world.sea_level = world.tide.level_at(world.tick) if world.tide != null else receiver.sea_level + follow_flood(world) if in_match: if _drop == null or _drop_world != world: @@ -100,6 +107,36 @@ func sync(game: ClientGame) -> void: world.projectiles = projectiles +## Spreads the client's flood as the server's tide tick does: across the edges the +## current breakwaters leave open once a second, and filling breached basins every +## tick. The server never sends the flood; it follows from the sea level and the +## pieces, which the client already has. It is only drawn (and used by prediction), +## so a breakwater that arrives a moment late can at worst show water a little early. +func follow_flood(world: Simulation) -> void: + if world.flood == null: + return + if _flood_world != world: + _flood_world = world + _flood_tick = world.tick + world.flood.update(world.sea_level, world.structures, 0.0) + return + if world.tide == null or world.tick <= _flood_tick: + return + # After a long gap (a stall, or joining late) catch up on the last few seconds only. + var first: int = maxi(_flood_tick + 1, world.tick - MAX_FLOOD_CATCH_UP_TICKS) + for tick: int in range(first, world.tick + 1): + var level: float = world.tide.level_at(tick) + if tick % Tuning.TICK_RATE_HZ == 0: + world.flood.update(level, world.structures, Simulation.SECONDS_PER_TICK) + else: + world.flood.flow(level, Simulation.SECONDS_PER_TICK) + if first > _flood_tick + 1: + # The skipped time still fills basins, and the sea still reaches what it can. + world.flood.update(world.sea_level, world.structures, (first - _flood_tick - 1) * Simulation.SECONDS_PER_TICK) + _flood_tick = world.tick + world.flood.sea_level = world.sea_level + + func _show_player(entity: SimEntity, record: PackedInt32Array, shown: Dictionary) -> void: var flags: int = record[NetSnapshot.R_FLAGS] entity.yaw = posmod(roundi(float(shown["yaw"]) / TAU * PlayerCommand.YAW_STEPS), PlayerCommand.YAW_STEPS) diff --git a/src/net/net_fx.gd b/src/net/net_fx.gd new file mode 100644 index 0000000..d579e5a --- /dev/null +++ b/src/net/net_fx.gd @@ -0,0 +1,174 @@ +## Things that happen and are gone, on the wire: shots fired, where shots landed, and +## harvesting swings. They change nothing a client keeps (damage, broken props and +## pieces arrive in snapshots and WORLD), so they are only for drawing and sound: an +## FX message goes unreliably on the state channel next to each snapshot, and a lost +## one is a missed flash, not a wrong world. Sending them reliably would add to the +## reliable traffic that has to be acknowledged, which a bad link can least afford. +## +## server -> FX +## u8 type, u32 simulation tick of the newest event, u8 count, then events: +## u8 kind, u8 ticks before the newest, varint player entity, u8 item code plus one, +## s16 x 3 position in decimetres, +## SHOT: s16 yaw and s16 pitch of the aim, in 1/10000 radian, +## IMPACT: u8 what was hit (Weapons.HIT_), varint target, +## HARVEST: varint prop, or 0 and varint piece plus one for a piece. +## +## Positions are where the shot began, where it landed, or the swinging player's feet. +## The decoder returns an empty Dictionary for anything malformed and never raises. +class_name NetFx +extends RefCounted + +const MSG_FX: int = 18 + +const SHOT: int = 1 +const IMPACT: int = 2 +const HARVEST: int = 3 +const KIND_NAMES: Array[String] = ["", "shot", "impact", "harvest"] + +const HEADER_BYTES: int = 6 +const MAX_EVENTS: int = 255 +## Decimetres: positions to 10 cm, over +/- 3.2 km. +const POSITION_SCALE: float = 10.0 +const ANGLE_SCALE: float = 10000.0 + + +## The FX record for a simulation event, or an empty Dictionary for events that aren't +## FX. `players` maps entity IDs to their feet, for harvest swings. +static func from_event(event: Dictionary, tick: int, players: Dictionary = {}) -> Dictionary: + match String(event.get("type", "")): + "shot": + var direction: Vector3 = event["direction"] + return { + "kind": SHOT, "tick": tick, "player": int(event["player"]), "item": int(event["item"]), + "position": event["from"], + "yaw": atan2(direction.x, direction.z), "pitch": asin(clampf(direction.y, -1.0, 1.0)), + } + "impact": + return { + "kind": IMPACT, "tick": tick, "player": int(event["player"]), "item": int(event["item"]), + "position": event["point"], "hit": int(event["hit"]), "target": int(event["target"]), + } + "harvest", "piece_hit": + var player: int = int(event["player"]) + return { + "kind": HARVEST, "tick": tick, "player": player, "item": -1, + "position": players.get(player, Vector3.ZERO), + "prop": int(event.get("prop", -1)), "piece": int(event.get("piece", 0)), + } + return {} + + +## Encodes up to MAX_EVENTS records, newest last, keeping to `max_bytes`. Records past +## the limit are left out, oldest first. Returns an empty array for none. +static func encode(records: Array[Dictionary], max_bytes: int = Tuning.NET_SNAPSHOT_MAX_BYTES) -> PackedByteArray: + if records.is_empty(): + return PackedByteArray() + var newest: int = int(records[records.size() - 1]["tick"]) + var bodies: Array[PackedByteArray] = [] + var total: int = HEADER_BYTES + for index: int in range(records.size() - 1, -1, -1): + var record: Dictionary = records[index] + var back: int = newest - int(record["tick"]) + if back < 0 or back > 255: + continue + var body: PackedByteArray = _encode_one(record, back) + if total + body.size() > max_bytes or bodies.size() >= MAX_EVENTS: + break + total += body.size() + bodies.push_front(body) + if bodies.is_empty(): + return PackedByteArray() + var out: StreamPeerBuffer = StreamPeerBuffer.new() + out.big_endian = false + out.put_u8(MSG_FX) + out.put_u32(newest) + out.put_u8(bodies.size()) + for body: PackedByteArray in bodies: + out.put_data(body) + return out.data_array + + +static func _encode_one(record: Dictionary, back: int) -> PackedByteArray: + var out: StreamPeerBuffer = StreamPeerBuffer.new() + out.big_endian = false + var kind: int = int(record["kind"]) + out.put_u8(kind) + out.put_u8(back) + NetSnapshot._put_varint(out, maxi(int(record["player"]), 0)) + out.put_u8(clampi(int(record["item"]) + 1, 0, 255)) + var position: Vector3 = record["position"] + for value: float in [position.x, position.y, position.z]: + out.put_16(clampi(roundi(value * POSITION_SCALE), -32768, 32767)) + match kind: + SHOT: + out.put_16(clampi(roundi(wrapf(float(record["yaw"]), -PI, PI) * ANGLE_SCALE), -32768, 32767)) + out.put_16(clampi(roundi(float(record["pitch"]) * ANGLE_SCALE), -32768, 32767)) + IMPACT: + out.put_u8(clampi(int(record["hit"]), 0, 255)) + NetSnapshot._put_varint(out, maxi(int(record["target"]), 0)) + HARVEST: + NetSnapshot._put_varint(out, maxi(int(record["prop"]), -1) + 1) + NetSnapshot._put_varint(out, maxi(int(record["piece"]), 0)) + return out.data_array + + +## {"tick": newest tick, "events": Array of records as from_event() makes them, with +## positions and angles as decoded}, or {} if malformed. +static func decode(bytes: PackedByteArray) -> Dictionary: + if bytes.size() < HEADER_BYTES or bytes[0] != MSG_FX: + return {} + var newest: int = bytes.decode_u32(1) + var count: int = bytes[5] + var cursor: Array[int] = [HEADER_BYTES] + var events: Array[Dictionary] = [] + for _index: int in count: + if cursor[0] + 2 > bytes.size(): + return {} + var kind: int = bytes[cursor[0]] + var back: int = bytes[cursor[0] + 1] + cursor[0] += 2 + if kind < SHOT or kind > HARVEST: + return {} + var player: int = NetSnapshot._read_varint(bytes, cursor) + if player < 0 or cursor[0] + 7 > bytes.size(): + return {} + var item: int = bytes[cursor[0]] - 1 + var position: Vector3 = Vector3( + bytes.decode_s16(cursor[0] + 1) / POSITION_SCALE, + bytes.decode_s16(cursor[0] + 3) / POSITION_SCALE, + bytes.decode_s16(cursor[0] + 5) / POSITION_SCALE) + cursor[0] += 7 + var record: Dictionary = {"kind": kind, "tick": newest - back, "player": player, "item": item, "position": position} + match kind: + SHOT: + if cursor[0] + 4 > bytes.size(): + return {} + record["yaw"] = bytes.decode_s16(cursor[0]) / ANGLE_SCALE + record["pitch"] = bytes.decode_s16(cursor[0] + 2) / ANGLE_SCALE + cursor[0] += 4 + IMPACT: + if cursor[0] + 1 > bytes.size(): + return {} + record["hit"] = bytes[cursor[0]] + cursor[0] += 1 + record["target"] = NetSnapshot._read_varint(bytes, cursor) + if int(record["target"]) < 0: + return {} + HARVEST: + var prop: int = NetSnapshot._read_varint(bytes, cursor) + var piece: int = NetSnapshot._read_varint(bytes, cursor) + if prop < 0 or piece < 0: + return {} + record["prop"] = prop - 1 + record["piece"] = piece + events.append(record) + if cursor[0] != bytes.size(): + return {} + return {"tick": newest, "events": events} + + +## The direction a SHOT record aims along. +static func aim(record: Dictionary) -> Vector3: + var yaw: float = float(record["yaw"]) + var pitch: float = float(record["pitch"]) + return Vector3(sin(yaw) * cos(pitch), sin(pitch), cos(yaw) * cos(pitch)) diff --git a/src/net/net_fx.gd.uid b/src/net/net_fx.gd.uid new file mode 100644 index 0000000..ec0d993 --- /dev/null +++ b/src/net/net_fx.gd.uid @@ -0,0 +1 @@ +uid://byl2i67hpew72 diff --git a/src/server/local_server.gd b/src/server/local_server.gd index 7054a69..7991439 100644 --- a/src/server/local_server.gd +++ b/src/server/local_server.gd @@ -53,6 +53,9 @@ func tick(client: ClientGame) -> void: client.receive(NetProtocol.CHANNEL_CONTROL, game.own_changes[HANDLE]) if game.snapshot_due(): client.receive(NetProtocol.CHANNEL_STATE, game.snapshot_for(HANDLE)) + var fx: PackedByteArray = game.fx_for(HANDLE) + if not fx.is_empty(): + client.receive(NetProtocol.CHANNEL_STATE, fx) ## What someone is sent on joining: the match notice, then the whole world. diff --git a/src/server/net_game.gd b/src/server/net_game.gd index b6d9393..23c0c7b 100644 --- a/src/server/net_game.gd +++ b/src/server/net_game.gd @@ -27,6 +27,11 @@ var own_changes: Dictionary = {} var _last_command: Dictionary = {} ## Handle -> what they were last told they carry, as _own_notice() lists it. var _own_sent: Dictionary = {} +## FX records (NetFx) from the last few simulation ticks, oldest first, and the newest +## simulation tick whose FX each handle has been sent. +var _fx: Array[Dictionary] = [] +var _fx_sent: Dictionary = {} +var _fx_tick: int = -1 func _init(server_loop: ServerLoop, server_net: NetServer) -> void: @@ -116,6 +121,9 @@ func after_tick() -> void: sender.reset() for handle: int in _last_command: _last_command[handle] = -1 + _fx.clear() + _fx_sent.clear() + _fx_tick = -1 net.match_seed = flow.current_seed() if changed: for handle: int in net.handles(): @@ -138,9 +146,55 @@ func after_tick() -> void: if not bytes.is_empty(): own_changes[handle] = bytes net.send(handle, NetProtocol.CHANNEL_CONTROL, bytes, true) + _collect_fx() for handle: int in net.handles(): if sender.has_client(handle) and snapshot_due_for(handle): net.send(handle, NetProtocol.CHANNEL_STATE, snapshot_for(handle), false) + var fx: PackedByteArray = fx_for(handle) + if not fx.is_empty(): + net.send(handle, NetProtocol.CHANNEL_STATE, fx, false) + + +## Keeps this tick's shots, impacts and swings as FX records, once per simulation tick +## (outside a match the simulation isn't stepped and its events are stale). +func _collect_fx() -> void: + var sim: Simulation = loop.sim + if not loop.match_flow.in_match() or sim.tick == _fx_tick: + return + _fx_tick = sim.tick + var feet: Dictionary = {} + for event: Dictionary in sim.events: + if event["type"] == "harvest" or event["type"] == "piece_hit": + var player: SimEntity = sim.entities.find(int(event["player"])) + if player != null: + feet[player.id] = player.position + var record: Dictionary = NetFx.from_event(event, sim.tick, feet) + if not record.is_empty(): + _fx.append(record) + # A client is sent its FX at least every snapshot interval; keep a little more. + var oldest: int = sim.tick - Tuning.NET_SNAPSHOT_INTERVAL_TICKS * 4 + while not _fx.is_empty() and int(_fx[0]["tick"]) <= oldest: + _fx.pop_front() + + +## An FX message of what happened near what `handle` watches since it was last sent +## one, or nothing. Marks those as sent. +func fx_for(handle: int) -> PackedByteArray: + var since: int = int(_fx_sent.get(handle, -1)) + _fx_sent[handle] = _fx_tick + if _fx.is_empty(): + return PackedByteArray() + var watched: int = viewer_of(handle) + var viewer: SimEntity = loop.sim.entities.find(watched) if watched != 0 else null + var limit: float = Tuning.NET_FX_RADIUS_METRES * Tuning.NET_FX_RADIUS_METRES + var chosen: Array[Dictionary] = [] + for record: Dictionary in _fx: + if int(record["tick"]) <= since: + continue + var involved: bool = watched != 0 and (int(record["player"]) == watched or int(record.get("target", 0)) == watched) + if involved or (viewer != null and (record["position"] as Vector3).distance_squared_to(viewer.position) <= limit): + chosen.append(record) + return NetFx.encode(chosen) ## True on the ticks a snapshot goes out to an owner that carries packets for a single diff --git a/src/sim/flood.gd b/src/sim/flood.gd index 8602100..4ddf3ac 100644 --- a/src/sim/flood.gd +++ b/src/sim/flood.gd @@ -30,6 +30,9 @@ 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 = {} @@ -233,6 +236,7 @@ func _passable(from: int, to: int) -> bool: ## 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) diff --git a/src/sim/tuning.gd b/src/sim/tuning.gd index 7837e50..f68e4d7 100644 --- a/src/sim/tuning.gd +++ b/src/sim/tuning.gd @@ -16,6 +16,9 @@ const NET_SNAPSHOT_INTERVAL_TICKS: int = 2 ## The most bytes in one snapshot. Keeps a packet inside one UDP datagram on any ## ordinary link, and a client under 18 KB/s before packet headers. const NET_SNAPSHOT_MAX_BYTES: int = 1200 +## Shots, impacts and swings further than this from what a client watches aren't sent +## to it, unless they involve the player it watches. +const NET_FX_RADIUS_METRES: float = 250.0 ## A client is sent other players and shots within this many metres on the map of the ## player it is watching: a little further than the longest weapon reaches. const NET_INTEREST_PLAYERS_METRES: float = 380.0 diff --git a/test/capture/client_basin.tscn b/test/capture/client_basin.tscn new file mode 100644 index 0000000..a737033 --- /dev/null +++ b/test/capture/client_basin.tscn @@ -0,0 +1,7 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/client_scene.gd" id="1"] + +[node name="CaptureClient" type="Node3D"] +script = ExtResource("1") +stage = "basin" diff --git a/test/capture/client_build.tscn b/test/capture/client_build.tscn new file mode 100644 index 0000000..1b3e369 --- /dev/null +++ b/test/capture/client_build.tscn @@ -0,0 +1,7 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/client_scene.gd" id="1"] + +[node name="CaptureClient" type="Node3D"] +script = ExtResource("1") +stage = "build" diff --git a/test/capture/client_build_refused.tscn b/test/capture/client_build_refused.tscn new file mode 100644 index 0000000..af58861 --- /dev/null +++ b/test/capture/client_build_refused.tscn @@ -0,0 +1,7 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/client_scene.gd" id="1"] + +[node name="CaptureClient" type="Node3D"] +script = ExtResource("1") +stage = "build_refused" diff --git a/test/capture/client_scene.gd b/test/capture/client_scene.gd index 4c698a4..c294535 100644 --- a/test/capture/client_scene.gd +++ b/test/capture/client_scene.gd @@ -3,7 +3,12 @@ ## by its autoplay script. The picture is the client's own: its copy of the world, its ## predicted player, everyone else as the server's snapshots have them. ## -## Stages: barge (a few seconds into the drop), glide, landed. +## Stages: barge (a few seconds into the drop), glide, landed, and basin: once landed, +## the server rings a patch of low ground near the shore with breakwaters and play goes +## on until the tide has risen past it, so the sea stands outside the ring and the +## ground inside, below the sea, stays dry on the client too (issue N11). build and +## build_refused: once landed, the client goes into build mode for a driftwood wall, +## with plenty of materials or none, so the ghost shows in its allowed or refused tint. extends Node3D const DT: float = 1.0 / Tuning.TICK_RATE_HZ @@ -59,7 +64,7 @@ func _ready() -> void: reached = me.drop_state == Drop.ABOARD and _session.game.prediction.next_tick > 3 * Tuning.TICK_RATE_HZ "glide": reached = me.drop_state == Drop.GLIDING - "landed": + "landed", "basin", "build", "build_refused": reached = me.drop_state == Drop.NONE if reached and since < 0: since = 0 @@ -70,6 +75,15 @@ func _ready() -> void: if since < 0: push_error("client capture: never reached stage '%s'" % stage) return + var basin_text: String = "" + if stage == "basin": + basin_text = _basin() + if basin_text.is_empty(): + return + elif stage.begins_with("build"): + basin_text = _build_mode(stage == "build") + if basin_text.is_empty(): + return _session.view.settle() var others: int = 0 var camera: Camera3D = _session.view.camera @@ -85,7 +99,127 @@ func _ready() -> void: stage.to_upper(), flow.phase_name(), match_seed, HOST, _net.name_of(_session.link.handle), _session.view.entities.figure_count(), others, _loop.sim.tick, _session.game.prediction.next_tick, _session.game.receiver.applied, _session.game.replica.applied, _session.game.prediction.mispredictions, - ]) + ] + basin_text) + + +## Stops the autoplay where the player stands and goes into build mode for a driftwood +## wall, after the server has given the player plenty of materials or taken them all. +## Returns a caption line, or "" after reporting an error. +func _build_mode(afford: bool) -> String: + var flow: Match = _loop.match_flow + var mine: SimEntity = _loop.sim.entities.find(int(flow.entity_of.get(_session.link.handle, 0))) + if mine == null or mine.eliminated: + push_error("client capture: the player isn't in the match to build") + return "" + mine.materials = PackedInt32Array([200, 200, 200] if afford else [0, 0, 0]) + var me: SimEntity = _session.game.prediction.player + _session.input.autoplay = false + _session.input.build_mode = true + _session.input.build_kind = StructureSet.WALL + _session.input.material = Materials.DRIFTWOOD + _session.input.yaw = float(me.yaw) / PlayerCommand.YAW_STEPS * TAU + _session.input.pitch = -0.3 + for _round: int in 45: + _game.poll() + _loop.run_tick() + _game.after_tick() + _session.pump(DT) + var ghost: BuildGhost = _session.ghost + if ghost == null or not ghost.visible: + push_error("client capture: no build ghost is showing") + return "" + if ghost.valid != afford: + push_error("client capture: the ghost says %s, expected %s" % [Building.Result.keys()[ghost.result], "OK" if afford else "refused"]) + return "" + return "\nBUILD MODE · driftwood wall · ghost %s (%s) · driftwood carried %d" % [ + "allowed" if ghost.valid else "refused", Building.Result.keys()[ghost.result], _session.game.prediction.player.materials[Materials.DRIFTWOOD], + ] + + +## Rings low ground with breakwaters on the server, plays on until the tide stands over +## it, and frames the ring. Returns a caption line, or "" after reporting an error. +func _basin() -> String: + var sim: Simulation = _loop.sim + var flood: Flood = sim.flood + var level: float = sim.tide.levels[0] + var ring: Vector2i = _find_basin(flood, level, _session.game.prediction.player.position) + if ring.x < 0: + push_error("client capture: no low ground to ring below the first tide level %.1f m" % level) + return "" + # Two breakwaters a side on every edge of the 3 x 3 cells, based at the edge's floor. + var stone: int = Materials.code_of("stone") + var piece_levels: int = roundi(Tuning.GRID_CELL_METRES / Tuning.BUILD_LEVEL_METRES) + for along: int in range(3): + for wall: Vector4i in [ + Vector4i(ring.x, 0, ring.y + along, StructureSet.SLOT_WALL_X), + Vector4i(ring.x + 3, 0, ring.y + along, StructureSet.SLOT_WALL_X), + Vector4i(ring.x + along, 0, ring.y, StructureSet.SLOT_WALL_Z), + Vector4i(ring.x + along, 0, ring.y + 3, StructureSet.SLOT_WALL_Z), + ]: + var a: int = wall.z * flood.side + wall.x + var b: int = a - 1 if wall.w == StructureSet.SLOT_WALL_X else a - flood.side + var base: int = floori(maxf(flood.floors[a], flood.floors[b]) / Tuning.BUILD_LEVEL_METRES) + for stack: int in 2: + sim.structures.add(StructureSet.BREAKWATER, stone, Vector4i(wall.x, base + stack * piece_levels, wall.z, wall.w), 0, 0, sim.tick, sim.ground) + var inside: Vector3 = Vector3((ring.x + 1.5) * flood.cell, 0.0, (ring.y + 1.5) * flood.cell) + var outside: Vector3 = Vector3((ring.x - 1.5) * flood.cell, 0.0, (ring.y + 1.5) * flood.cell) + var floor_inside: float = flood.floors[flood.cell_of(inside.x, inside.z)] + var client_flood: Flood = null + for _round: int in 400 * Tuning.TICK_RATE_HZ: + _game.poll() + _loop.run_tick() + _game.after_tick() + _session.pump(DT) + client_flood = _session.game.world.flood + if sim.sea_level > floor_inside + 1.0 and _session.game.world.sea_level > floor_inside + 1.0 and client_flood.is_flooded(outside.x, outside.z): + break + if not (sim.sea_level > floor_inside + 1.0): + push_error("client capture: the tide never rose over the ringed ground") + return "" + _session.pump(DT) + var ground: float = sim.ground.terrain_height(inside.x, inside.z) + _session.view.look_from(inside + Vector3(-19.0, ground + 15.0, -17.0), Vector3(inside.x, ground, inside.z)) + return "\nBASIN · ring at (%.0f, %.0f), floor inside %.1f m, sea %.1f m\ninside dry: server %s, client %s, drawn %s · outside flooded on the client: %s" % [ + inside.x, inside.z, floor_inside, _session.game.world.sea_level, + not flood.is_flooded(inside.x, inside.z), not client_flood.is_flooded(inside.x, inside.z), + not _session.view.water.shows_water_at(inside.x, inside.z), client_flood.is_flooded(outside.x, outside.z), + ] + + +## The corner cell of a 3 x 3 patch of dry ground whose floor lies between 0.6 m and +## 1.5 m under `level` everywhere in it and in the ring of cells around it, closest to +## `near`, or (-1, -1). +func _find_basin(flood: Flood, level: float, near: Vector3) -> Vector2i: + var best: Vector2i = Vector2i(-1, -1) + var best_distance: float = INF + for cz: int in range(2, flood.side - 6): + for cx: int in range(2, flood.side - 6): + var fits: bool = true + for dz: int in range(-1, 4): + for dx: int in range(-1, 4): + var index: int = (cz + dz) * flood.side + cx + dx + var cell_floor: float = flood.floors[index] + if flood.flooded[index] != 0 or cell_floor < 0.6 or cell_floor > level - 1.5: + fits = false + break + if not fits: + break + if not fits: + continue + # Open sea must reach the patch's surroundings: a flooded cell near it. + var shore: bool = false + for dz: int in range(-3, 6): + for dx: int in range(-3, 6): + var index: int = (cz + dz) * flood.side + cx + dx + if index >= 0 and index < flood.flooded.size() and flood.flooded[index] != 0: + shore = true + if not shore: + continue + var distance: float = Vector2((cx + 1.5) * flood.cell - near.x, (cz + 1.5) * flood.cell - near.z).length() + if distance < best_distance: + best_distance = distance + best = Vector2i(cx, cz) + return best func _exit_tree() -> void: diff --git a/test/client/test_client_flood.gd b/test/client/test_client_flood.gd new file mode 100644 index 0000000..8dc27dc --- /dev/null +++ b/test/client/test_client_flood.gd @@ -0,0 +1,107 @@ +extends TestCase + +## Issue N11: a network client follows the flood from the tide and the pieces it has, +## and the sea isn't drawn over ground the flood hasn't reached. + +const SIDE: int = 513 +const SPACING: float = 2.0 +## A 200 m square of land 1 m high in open sea, as in test_tide. +const LAND_MIN: float = 400.0 +const LAND_MAX: float = 600.0 +## Breakwaters on the edges of cells 120 to 122, a 12 m square. +const RING_MIN: int = 120 +const RING_MAX: int = 122 +const INSIDE: Vector3 = Vector3(486.0, 1.0, 486.0) +const OUTSIDE: Vector3 = Vector3(450.0, 1.0, 450.0) + + +func _world() -> Simulation: + var values: PackedFloat32Array = PackedFloat32Array() + values.resize(SIDE * SIDE) + for gz: int in SIDE: + for gx: int in SIDE: + var x: float = gx * SPACING + var z: float = gz * SPACING + var land: bool = x >= LAND_MIN and x <= LAND_MAX and z >= LAND_MIN and z <= LAND_MAX + values[gz * SIDE + gx] = 1.0 if land else -Tuning.ISLAND_SEA_DEPTH + var ground: SimGround = SimGround.from_heights(values, SIDE, SPACING) + var world: Simulation = Simulation.new(3, ground) + world.flood = Flood.create(ground) + # A tide whose first rise takes the sea to 3 m. + var levels: PackedFloat32Array = PackedFloat32Array() + for index: int in Tide.phase_count(): + levels.append(3.0 + index) + world.tide = Tide.new(0, levels) + return world + + +func _ring(world: Simulation) -> void: + var stone: int = Materials.code_of("stone") + for along: int in range(RING_MIN, RING_MAX + 1): + for slot: Vector4i in [ + Vector4i(RING_MIN, 0, along, StructureSet.SLOT_WALL_X), + Vector4i(RING_MAX + 1, 0, along, StructureSet.SLOT_WALL_X), + Vector4i(along, 0, RING_MIN, StructureSet.SLOT_WALL_Z), + Vector4i(along, 0, RING_MAX + 1, StructureSet.SLOT_WALL_Z), + ]: + world.structures.add(StructureSet.BREAKWATER, stone, slot, 0, 0, 0, world.ground) + + +## Moves the client's world to `tick` the way ClientMirror.sync() does. +func _show_at(mirror: ClientMirror, world: Simulation, tick: int) -> void: + world.tick = tick + world.sea_level = world.tide.level_at(tick) + mirror.follow_flood(world) + + +func test_the_client_keeps_a_ringed_basin_dry_as_the_tide_rises() -> void: + var world: Simulation = _world() + _ring(world) + var mirror: ClientMirror = ClientMirror.new() + _show_at(mirror, world, 0) + assert_false(world.flood.is_flooded(OUTSIDE.x, OUTSIDE.z), "dry land at the start") + var risen: int = world.tide.sudden_death_offset() + # Frame by frame through the first rise, a few ticks a frame. + var first_rise_end: int = roundi((float(Tuning.TIDE_PHASES[0]["hold"]) + float(Tuning.TIDE_PHASES[0]["rise"])) * Tuning.TICK_RATE_HZ) + for tick: int in range(0, first_rise_end + 120, 3): + _show_at(mirror, world, tick) + assert_true(world.sea_level >= 3.0) + assert_true(world.flood.is_flooded(OUTSIDE.x, OUTSIDE.z), "the land outside the ring floods") + assert_eq(world.water_level_at(OUTSIDE), world.sea_level, "and fills to the sea") + assert_false(world.flood.is_flooded(INSIDE.x, INSIDE.z), "inside the ring stays dry") + assert_true(risen > first_rise_end) + + var view: WaterView = WaterView.new() + view.follow(world) + assert_true(view.shows_water_at(OUTSIDE.x, OUTSIDE.z), "the sea is drawn outside") + assert_false(view.shows_water_at(INSIDE.x, INSIDE.z), "but not over the basin") + assert_true(view.shows_water_at(-50.0, 300.0), "and everywhere off the grid") + view.free() + + +func test_a_late_frame_catches_up_and_a_missing_ring_floods_the_basin() -> void: + var world: Simulation = _world() + var mirror: ClientMirror = ClientMirror.new() + _show_at(mirror, world, 0) + # One frame long after the rise: the client catches up all at once. + _show_at(mirror, world, roundi(240.0 * Tuning.TICK_RATE_HZ)) + assert_true(world.flood.is_flooded(INSIDE.x, INSIDE.z), "with no ring the basin floods") + assert_eq(world.water_level_at(INSIDE), world.sea_level, "and has filled to the sea") + + +func test_the_mask_changes_only_when_the_flood_pours() -> void: + var world: Simulation = _world() + var view: WaterView = WaterView.new() + view.follow(world) + var material: ShaderMaterial = view.surface().mesh.surface_get_material(0) + assert_true(bool(material.get_shader_parameter("use_flood_mask"))) + var mask: Texture2D = material.get_shader_parameter("flood_mask") + assert_eq(mask.get_width(), world.flood.side) + var pours: int = world.flood.pours + world.set_sea_level(3.0) + assert_true(world.flood.pours > pours, "the sea rising over the land pours") + view.follow(world) + assert_true(view.shows_water_at(INSIDE.x, INSIDE.z)) + view.set_flood(null) + assert_false(bool(material.get_shader_parameter("use_flood_mask")), "no flood: the sea everywhere") + view.free() diff --git a/test/client/test_client_flood.gd.uid b/test/client/test_client_flood.gd.uid new file mode 100644 index 0000000..875563c --- /dev/null +++ b/test/client/test_client_flood.gd.uid @@ -0,0 +1 @@ +uid://blh4oh3o15t4i diff --git a/test/net/parser_fuzz.gd b/test/net/parser_fuzz.gd index 3b8ec58..35ef07a 100644 --- a/test/net/parser_fuzz.gd +++ b/test/net/parser_fuzz.gd @@ -51,6 +51,11 @@ func collect_seeds() -> void: seeds.append(bytes) if tick % 10 == 0: seeds.append(game.snapshot_for(1)) + seeds.append(NetFx.encode([ + {"kind": NetFx.SHOT, "tick": 90, "player": 3, "item": 2, "position": Vector3(100.0, 12.0, 200.0), "yaw": 1.0, "pitch": -0.2}, + {"kind": NetFx.IMPACT, "tick": 91, "player": 3, "item": 2, "position": Vector3(110.0, 11.0, 210.0), "hit": Weapons.HIT_PLAYER, "target": 7}, + {"kind": NetFx.HARVEST, "tick": 92, "player": 4, "item": -1, "position": Vector3(50.0, 9.0, 60.0), "prop": 12, "piece": 0}, + ] as Array[Dictionary])) var command: PlayerCommand = PlayerCommand.from_input(12, Vector2(0.3, 1.0), 1.0, 0.2, PlayerCommand.BUTTON_FIRE, 2, 1) seeds.append(NetSnapshot.encode_input(40, [command, command] as Array[PlayerCommand])) seeds.append(NetProtocol.encode_hello("Fuzzer")) @@ -100,7 +105,7 @@ func feed(bytes: PackedByteArray) -> void: var results: Array = [ NetProtocol.decode_hello(bytes), NetProtocol.decode_welcome(bytes), NetProtocol.decode_reject(bytes), NetSnapshot.decode_input(bytes), NetSnapshot.decode_snapshot(bytes), NetSnapshot.decode_match(bytes), - NetWorld.decode_world(bytes), NetWorld.decode_own(bytes), + NetWorld.decode_world(bytes), NetWorld.decode_own(bytes), NetFx.decode(bytes), NetDiscovery.decode_query(bytes), NetDiscovery.decode_info(bytes), NetDiscovery.decode_register(bytes), NetDiscovery.decode_challenge(bytes), NetDiscovery.decode_list(bytes), ] @@ -152,5 +157,6 @@ func _mutate(bytes: PackedByteArray) -> void: var types: Array[int] = [ NetProtocol.MSG_HELLO, NetProtocol.MSG_WELCOME, NetProtocol.MSG_REJECT, NetSnapshot.MSG_MATCH, NetWorld.MSG_WORLD, NetWorld.MSG_OWN, NetSnapshot.MSG_SNAPSHOT, NetSnapshot.MSG_INPUT, + NetFx.MSG_FX, ] bytes[0] = types[rng.randi_range(0, types.size() - 1)] diff --git a/test/net/test_net_fx.gd b/test/net/test_net_fx.gd new file mode 100644 index 0000000..9d283ba --- /dev/null +++ b/test/net/test_net_fx.gd @@ -0,0 +1,66 @@ +extends TestCase + +## Issue N11: shots, impacts and swings on the wire (NetFx). + + +func _records() -> Array[Dictionary]: + return [ + {"kind": NetFx.SHOT, "tick": 400, "player": 3, "item": 2, "position": Vector3(100.25, 12.5, 200.0), "yaw": 1.2345, "pitch": -0.25}, + {"kind": NetFx.IMPACT, "tick": 401, "player": 3, "item": 2, "position": Vector3(130.0, 11.0, 220.0), "hit": Weapons.HIT_PLAYER, "target": 700}, + {"kind": NetFx.HARVEST, "tick": 402, "player": 4, "item": -1, "position": Vector3(50.0, 9.0, 60.0), "prop": 12, "piece": 0}, + {"kind": NetFx.HARVEST, "tick": 402, "player": 5, "item": -1, "position": Vector3(51.0, 9.0, 61.0), "prop": -1, "piece": 33}, + ] + + +func test_records_survive_the_trip() -> void: + var bytes: PackedByteArray = NetFx.encode(_records()) + var message: Dictionary = NetFx.decode(bytes) + assert_false(message.is_empty()) + assert_eq(message["tick"], 402) + var events: Array = message["events"] + assert_eq(events.size(), 4) + for index: int in 4: + var sent: Dictionary = _records()[index] + var got: Dictionary = events[index] + for key: String in sent: + if key == "position": + assert_true((got[key] as Vector3).distance_to(sent[key]) <= 0.06, "%s within 6 cm" % key) + elif key == "yaw" or key == "pitch": + assert_near(float(got[key]), float(sent[key]), 0.0001) + else: + assert_eq(got[key], sent[key], "event %d %s" % [index, key]) + assert_true(NetFx.aim(events[0]).is_normalized()) + + +func test_an_event_from_the_simulation_becomes_a_record() -> void: + var direction: Vector3 = Vector3(0.3, -0.2, 0.9).normalized() + var shot: Dictionary = NetFx.from_event({"type": "shot", "player": 9, "item": 4, "from": Vector3(1.0, 2.0, 3.0), "direction": direction}, 77) + assert_eq(shot["kind"], NetFx.SHOT) + assert_true(NetFx.aim(shot).distance_to(direction) < 0.0001, "the aim comes back") + var swing: Dictionary = NetFx.from_event({"type": "harvest", "player": 9, "prop": 5, "material": 0, "amount": 3}, 77, {9: Vector3(4.0, 5.0, 6.0)}) + assert_eq(swing["position"], Vector3(4.0, 5.0, 6.0)) + assert_true(NetFx.from_event({"type": "pickup", "player": 9}, 77).is_empty(), "only FX events") + + +func test_too_many_keep_the_newest_and_the_byte_limit() -> void: + var many: Array[Dictionary] = [] + for index: int in 300: + many.append({"kind": NetFx.SHOT, "tick": 1000 + index / 10, "player": index, "item": 1, "position": Vector3(index, 1.0, 2.0), "yaw": 0.0, "pitch": 0.0}) + var bytes: PackedByteArray = NetFx.encode(many) + assert_true(bytes.size() <= Tuning.NET_SNAPSHOT_MAX_BYTES, "%d bytes" % bytes.size()) + var events: Array = NetFx.decode(bytes)["events"] + assert_true(events.size() > 40) + assert_eq(int(events[events.size() - 1]["player"]), 299, "the newest is kept") + assert_eq(NetFx.encode([] as Array[Dictionary]).size(), 0) + + +func test_malformed_messages_are_refused() -> void: + var bytes: PackedByteArray = NetFx.encode(_records()) + for cut: int in bytes.size(): + assert_true(NetFx.decode(bytes.slice(0, cut)).is_empty(), "cut at %d" % cut) + var longer: PackedByteArray = bytes.duplicate() + longer.append(0) + assert_true(NetFx.decode(longer).is_empty(), "trailing bytes") + var bad_kind: PackedByteArray = bytes.duplicate() + bad_kind[NetFx.HEADER_BYTES] = 9 + assert_true(NetFx.decode(bad_kind).is_empty(), "unknown kind") diff --git a/test/net/test_net_fx.gd.uid b/test/net/test_net_fx.gd.uid new file mode 100644 index 0000000..96807ca --- /dev/null +++ b/test/net/test_net_fx.gd.uid @@ -0,0 +1 @@ +uid://dyrisqacc7jfk diff --git a/test/server/test_client_game.gd b/test/server/test_client_game.gd index 9313c95..83d307b 100644 --- a/test/server/test_client_game.gd +++ b/test/server/test_client_game.gd @@ -205,3 +205,89 @@ func test_a_client_freed_while_its_island_is_made_waits_for_it() -> void: assert_true(client.building_world()) client = null assert_true(true, "freeing it with a task running raises no error") + + +## N11: shots, impacts and swings near what the client watches reach it as FX +## records, each one an event the server's simulation really had. The client's own +## player, once landed, is given a hitscan weapon and fires at the ground. +func test_shots_and_hits_reach_the_client() -> void: + var client: ClientGame = ClientGame.new() + assert_true(loop.match_flow.join(7)) + game.adopt(7) + client.receive(NetProtocol.CHANNEL_CONTROL, game.match_notice()) + client.receive(NetProtocol.CHANNEL_CONTROL, game.world_notice()) + var weapon: ItemDef = null + for def: ItemDef in ItemCatalog.all(): + if def.kind == ItemDef.WEAPON and def.projectile_speed <= 0.0 and def.ammo_code >= 0 and def.damage > 0: + weapon = def + break + assert_not_null(weapon, "a hitscan weapon to fire") + var happened: Dictionary = {} + var shots: int = 0 + var impacts: int = 0 + var armed: bool = false + for round_index: int in 4000: + var flow: Match = loop.match_flow + var mine: SimEntity = loop.sim.entities.find(int(flow.entity_of.get(7, 0))) if flow.in_match() else null + if mine != null and mine.drop_state == Drop.NONE and not mine.eliminated: + if not armed: + armed = true + # Wherever it came down, stand it on dry ground well above the sea. + mine.position = _dry_spot(loop.sim) + mine.velocity = Vector3.ZERO + mine.swimming = false + mine.on_ground = true + Inventory.give(mine, weapon.code, 1) + Inventory.give(mine, weapon.ammo_code, 60) + # Press and release, so any weapon fires again. + var buttons: int = PlayerCommand.BUTTON_FIRE if round_index % 8 == 0 else 0 + loop.submit(7, PlayerCommand.from_input(loop.sim.tick, Vector2.ZERO, 0.0, -0.7, buttons, 1)) + loop.run_tick() + game.after_tick() + if loop.match_flow.in_match(): + for event: Dictionary in loop.sim.events: + var record: Dictionary = NetFx.from_event(event, loop.sim.tick) + if not record.is_empty(): + # A scattering weapon lands several pellets on one tick. + var key: String = "%d %d %d" % [record["tick"], record["kind"], record["player"]] + if not happened.has(key): + happened[key] = [] + (happened[key] as Array).append(record["position"]) + for event: Dictionary in loop.match_flow.events: + if event["type"] == "phase": + client.receive(NetProtocol.CHANNEL_CONTROL, game.match_notice()) + if not game.world_changes.is_empty(): + client.receive(NetProtocol.CHANNEL_CONTROL, game.world_changes) + if game.snapshot_due(): + client.receive(NetProtocol.CHANNEL_STATE, game.snapshot_for(7)) + var fx: PackedByteArray = game.fx_for(7) + if not fx.is_empty(): + client.receive(NetProtocol.CHANNEL_STATE, fx) + for record: Dictionary in client.fx: + var key: String = "%d %d %d" % [record["tick"], record["kind"], record["player"]] + assert_true(happened.has(key), "FX %s happened on the server" % key) + if happened.has(key) and record["kind"] != NetFx.HARVEST: + var near: bool = false + for position: Vector3 in happened[key]: + near = near or (record["position"] as Vector3).distance_to(position) < 0.1 + assert_true(near, "FX %s at the same place" % key) + shots += 1 if record["kind"] == NetFx.SHOT else 0 + impacts += 1 if record["kind"] == NetFx.IMPACT else 0 + client.fx.clear() + if shots >= 3 and impacts >= 3: + break + assert_true(armed, "the player landed and was armed") + assert_true(shots >= 3, "shots arrived: %d" % shots) + assert_true(impacts >= 3, "and where they landed: %d" % impacts) + assert_eq(client.bad_packets, 0) + assert_true(game.fx_for(7).is_empty(), "nothing is sent twice") + + +func _dry_spot(sim: Simulation) -> Vector3: + for z: int in range(64, 960, 16): + for x: int in range(64, 960, 16): + var y: float = sim.ground.terrain_height(x, z) + var feet: Vector3 = Vector3(x, y, z) + if y > 15.0 and not sim.ground.body_blocked(feet, 2.0, Tuning.PLAYER_HEIGHT, 0.0): + return feet + return Vector3(512.0, sim.ground.terrain_height(512.0, 512.0), 512.0)