diff --git a/CLAUDE.md b/CLAUDE.md index bb35429..375c6ff 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -26,6 +26,8 @@ continuity. | `tools/capture.sh ` | Renders the real client offscreen in a throwaway `tidewall-capture-*` Docker container (Xvfb, Mesa software rendering) and saves a PNG. Fails on a blank frame or a renderer fallback. | | `tools/godot.sh --script res://tools/island_map.gd -- --seed=N --out=res://captures/island.png` | Draws a top-down map of a seed's island, with a contour at each tide level. | | `make bot-matches` | Plays 20 bot-only matches (several minutes, under `nice`) and checks every one has a winner, under a tenth of deaths are drownings, easy bots place worst and hard bots take the most eliminations. `BOT_MATCH_SEEDS=5 BOT_MATCH_FIRST=40` changes the seeds. | +| `make match` | Plays one whole offline match, lobby to results: a scripted player and 23 bots on a local server (about 25 s). Saves the command log to `build/match/match.tclog`, replays it and checks the replay ends on the same state hash. `MATCH_SEED=N` changes the seed; the default, 2, is one where the scripted player also builds. | +| `make match-captures` | Renders eight stages of that match from its command log (`captures/match_.png`), about 3 minutes. Needs Docker. Look at them. | | `make terrain-capture` | Renders the terrain crack check and a skirtless control in the capture container. The control must crack and the real terrain must not. Needs Docker. | | `make capture-test` | Proves the capture harness works and rejects a blank frame. Needs Docker, so it isn't part of `make check`. | diff --git a/Makefile b/Makefile index a53393e..ae7c2ae 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ # Tidewall build entry points. Everything runs headless with the repo-local engine. GODOT := tools/godot.sh -.PHONY: check import parse test test-selfcheck smoke capture-test terrain-capture binaries verify-engine bot-matches +.PHONY: check import parse test test-selfcheck smoke capture-test terrain-capture binaries verify-engine bot-matches match match-captures ## Everything that must pass before a push. check: verify-engine binaries parse test test-selfcheck smoke @@ -36,6 +36,16 @@ smoke: import bot-matches: import @tools/bot_matches.sh +## Plays one whole offline match, lobby to results, with a scripted player and 23 bots, +## then replays its command log and checks the replay ends in the same state. +## MATCH_SEED picks the seed. +match: import + @tools/match.sh + +## Renders each stage of the match `make match` last played. Needs Docker. +match-captures: import + @tools/match_captures.sh + ## Renders the capture test scenes in the offscreen container. Needs Docker. capture-test: import @tools/capture_selfcheck.sh diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c6ab2b5..e202f61 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -77,8 +77,10 @@ deterministic. - A match has one `u64` seed, always logged. - Gameplay randomness comes only from named streams, created from the match seed and a - stable name: `rng.stream("loot")`, `"weapons"`, `"bots"`, `"worldgen"`, and so on, on one `SimRng`. + stable name: `rng.stream("loot")`, `"weapons"`, `"drop"`, `"worldgen"`, and so on, on one `SimRng`. One system's extra rolls can't disturb another's. +- Bots don't draw from those streams. Each bot has its own generator, seeded from the + match seed and its player ID, so nothing a bot thinks changes the simulation's state. - Simulation code **never** calls `randf`, `randi`, `Time`, or anything else that varies between runs. Presentation can use whatever randomness it likes, for effects. - The same seed and the same command log produce the same state hash, on the same engine @@ -91,6 +93,27 @@ to millimetres. Determinism is for tests, replays and worldgen. Clients don't rely on bit-exact matches with the server. Reconciliation corrects any difference. +## Command log and replay + +`CommandLog` (`src/server/`) holds a match's seed, its rules and every command the +server was given: the simulation tick it arrived on, the handle it came from and the +command's 14 bytes. `ServerLoop.submit()` is the one way commands get in, for people, +scripts and bots alike, so a recording server logs them all, accepted or not. On disk +it is a JSON header and the records compressed with Zstandard, about 0.6 MB for a +24-player match. + +`MatchReplay` plays a log again: the same seed and rules, the same commands on the same +ticks, and nobody thinking. It ends on the same state hash as the recording, which +`make match` checks after every run. A replay can stop at any tick, which is how the +match captures draw a moment of a real match. Replays are exact only on the same engine +build, like everything else that relies on determinism. + +`ScriptedPlayer` (`src/bots/`) is a stand-in for a person at the controls. It plays a +human seat as a bot would, and also cuts driftwood and builds a breakwater and a wall, +so a scripted match covers the drop, loot, combat, harvesting, building and the tide +from a player's seat. `ServerLoop.play_humans_by_script()` turns it on; no shipped mode +uses it. + ## Snapshot format A snapshot is a binary, little-endian packet: @@ -178,6 +201,15 @@ full-resolution heightfield at every level, so lighting doesn't change across a The terrain shader blends procedural sand, marsh, grass and rock layers using splat weights from the island's elevation bands, with rock on steep ground. +## The match view + +`MatchView` (`src/client/`) is the client's picture of one match: sky, sun, terrain, +sea, points of interest, props, built pieces and `EntityView`, which draws players, the +barge, items and chests. All of it reads one `Simulation` and never writes to it, and a +new match gets a new view. The camera sits on a player's shoulder through `CameraRig`. +Until snapshots arrive, the simulation it reads is a local server's or a replay's; the +figures, barge and items are stand-in shapes for the art pass to replace. + ## Performance budgets | Budget | Target | diff --git a/src/bots/bot_brain.gd b/src/bots/bot_brain.gd index 39ad6d2..feba449 100644 --- a/src/bots/bot_brain.gd +++ b/src/bots/bot_brain.gd @@ -229,7 +229,7 @@ func _stop() -> void: func _drop(sim: Simulation, grid: NavGrid, world: BotWorld) -> PlayerCommand: state = "drop" if _landing < 0 and not world.markers.is_empty() and sim.drop != null: - var rng: RandomNumberGenerator = sim.rng.stream("bots") + var rng: RandomNumberGenerator = nav.stream(sim) var a: Vector2 = Vector2(sim.drop.start.x, sim.drop.start.z) var b: Vector2 = Vector2(sim.drop.finish.x, sim.drop.finish.z) var near: Array[int] = [] @@ -365,7 +365,7 @@ static func _weapon_score(me: SimEntity, slot: int, distance: float) -> float: func _update_aim_error(sim: Simulation) -> void: if (sim.tick + player_id) % Tuning.BOT_AIM_WANDER_TICKS == 0: - var rng: RandomNumberGenerator = sim.rng.stream("bots") + var rng: RandomNumberGenerator = nav.stream(sim) _aim_error_goal = Vector2(rng.randf_range(-1.0, 1.0), rng.randf_range(-0.5, 0.5)) * _aim_error_degrees _aim_error = _aim_error.lerp(_aim_error_goal, 0.25) @@ -400,7 +400,7 @@ func _combat_move(sim: Simulation, grid: NavGrid, me: SimEntity, target: SimEnti to /= gap var wanted: float = minf(clampf(def.range_full * 0.8, 5.0, 30.0), _fire_range(def) * 0.8) if sim.tick >= _strafe_until: - var rng: RandomNumberGenerator = sim.rng.stream("bots") + var rng: RandomNumberGenerator = nav.stream(sim) _strafe = -_strafe _strafe_until = sim.tick + rng.randi_range(TICKS / 2, TICKS * 2) var side: Vector2 = Vector2(-to.y, to.x) * _strafe @@ -758,7 +758,7 @@ func _hunt(sim: Simulation, world: BotWorld) -> void: var arrived: bool = _goal_set and nav.status != NavBot.MOVING if not _goal_set or arrived or sim.tick >= _hunt_until: var phase: int = sim.tide.phase_at(sim.tick) if sim.tide != null else 0 - _hunt_goal = world.random_safe(sim.rng.stream("bots"), phase) + _hunt_goal = world.random_safe(nav.stream(sim), phase) _hunt_until = sim.tick + 40 * TICKS _go(_hunt_goal, 4.0) else: diff --git a/src/bots/nav_bot.gd b/src/bots/nav_bot.gd index 00a1702..46ff12b 100644 --- a/src/bots/nav_bot.gd +++ b/src/bots/nav_bot.gd @@ -36,6 +36,20 @@ var _stuck_ticks: int = 0 var _stuck_tries: int = 0 var _jump_next: bool = false var _leap_tick: int = -1 +var _rng: RandomNumberGenerator = null +var _rng_seed: int = 0 + + +## This bot's own random stream, seeded from the match seed and its player ID. Bots +## never draw from the simulation's streams: a bot is a player, and nothing a player +## thinks may change the simulation's state, or a replay of the same commands with no +## bots thinking would end up with a different state hash. +func stream(sim: Simulation) -> RandomNumberGenerator: + if _rng == null or _rng_seed != sim.rng.match_seed: + _rng = RandomNumberGenerator.new() + _rng_seed = sim.rng.match_seed + _rng.seed = _rng_seed ^ SimRng._hash_name("bot:%d" % player_id) + return _rng func _init(id: int) -> void: @@ -172,12 +186,12 @@ func _ride(sim: Simulation, player: SimEntity) -> PlayerCommand: return PlayerCommand.from_input(sim.tick, Vector2.ZERO, 0.0, 0.0, buttons) -## A random open dry point within ROAM_RANGE that a path reaches, from the "bots" +## A random open dry point within ROAM_RANGE that a path reaches, from the bot's own ## stream. Plans the path at once, so it uses the tick's planning budget. func _pick_roam_goal(sim: Simulation, grid: NavGrid, player: SimEntity) -> void: if not grid.can_plan(): return - var rng: RandomNumberGenerator = sim.rng.stream("bots") + var rng: RandomNumberGenerator = stream(sim) var centre: Vector3 = player.position if player.drop_state == Drop.ABOARD: centre = Vector3(Tuning.WORLD_SIZE_METRES * 0.5, 0.0, Tuning.WORLD_SIZE_METRES * 0.5) diff --git a/src/bots/scripted_player.gd b/src/bots/scripted_player.gd new file mode 100644 index 0000000..27e8975 --- /dev/null +++ b/src/bots/scripted_player.gd @@ -0,0 +1,177 @@ +## A stand-in for a person at the controls, for whole-match runs with no network and +## nobody watching. It plays a human seat through the same door as everyone else: one +## PlayerCommand a tick. +## +## It drops, loots, fights and keeps ahead of the tide as a normal bot does, and adds +## what bots don't do yet: once it has a weapon and nothing more pressing, it cuts +## driftwood with the boathook and builds a breakwater and a wall where it stands. So +## one scripted match exercises the drop, loot, combat, harvesting, building and the +## tide from a player's seat. +class_name ScriptedPlayer +extends BotBrain + +const WAIT: int = 0 +const HARVEST: int = 1 +const BUILD: int = 2 +const DONE: int = 3 +const STEP_NAMES: Array[String] = ["wait", "harvest", "build", "done"] + +## Driftwood to gather before building: a breakwater and a wall, and a swing to spare. +const WANTED_DRIFTWOOD: int = 45 +## How far to look for something to cut, in metres. +const SEARCH_RADIUS: float = 45.0 +## Starts the script this long after landing even with no weapon found. +const UNARMED_WAIT_SECONDS: float = 45.0 +## Gives up on one prop, and on the whole script, after this long. +const PROP_TIMEOUT_SECONDS: float = 25.0 +const SCRIPT_TIMEOUT_SECONDS: float = 150.0 +## Inside this distance the script walks straight at the prop instead of path-finding. +const DIRECT_METRES: float = 6.0 + +var step: int = WAIT +## Driftwood gained and pieces placed by the script so far. +var harvested: int = 0 +var built: int = 0 + +var _landed_tick: int = -1 +var _script_since: int = 0 +var _driving: bool = false +var _prop: int = -1 +var _prop_since: int = 0 +var _skipped_props: Dictionary = {} +var _to_build: Array[int] = [StructureSet.BREAKWATER, StructureSet.WALL] +var _build_yaw: float = 0.0 +var _build_tries: int = 0 +var _stock_before: int = -1 +var _wood_seen: int = 0 + + +func _init(id: int, level: int = NORMAL) -> void: + super(id, level) + + +func step_name() -> String: + return STEP_NAMES[step] + + +func think(sim: Simulation, grid: NavGrid, world: BotWorld) -> PlayerCommand: + var me: SimEntity = sim.entities.find(player_id) + if me == null or me.eliminated or me.drop_state != Drop.NONE or step == DONE: + return super(sim, grid, world) + if _landed_tick < 0: + _landed_tick = sim.tick + var wood: int = me.materials[Materials.DRIFTWOOD] + if wood > _wood_seen: + harvested += wood - _wood_seen + _wood_seen = wood + var busy: bool = _fleeing or target_id != 0 or _stage != OUTSIDE or me.swimming or not me.on_ground or _heal_slot(me) >= 0 + if step == WAIT and not busy: + if _weapon_slot >= 0 or sim.tick - _landed_tick >= roundi(UNARMED_WAIT_SECONDS * TICKS): + step = HARVEST + _script_since = sim.tick + if step != WAIT and sim.tick - _script_since > roundi(SCRIPT_TIMEOUT_SECONDS * TICKS): + step = DONE + if busy or step == WAIT or step == DONE: + _release() + return super(sim, grid, world) + # The script has the controls this tick. Keep the senses going, and hand back to + # the brain on the next tick if they turn anything up. + _driving = true + _sense(sim, world, me) + _check_tide(sim, world, me) + if target_id != 0 or _fleeing: + return _hold(sim, me) + if step == HARVEST: + state = "harvest" + return _harvest(sim, grid, me) + state = "build" + return _build(sim, me) + + +## Gives the path follower back to the brain with no goal of the script's left in it. +func _release() -> void: + if _driving: + _stop() + _driving = false + _stock_before = -1 + + +func _hold(sim: Simulation, me: SimEntity) -> PlayerCommand: + return PlayerCommand.from_input(sim.tick, Vector2.ZERO, float(me.yaw) / PlayerCommand.YAW_STEPS * TAU, 0.0) + + +## Walks to the nearest driftwood prop and swings at it until there's enough to build. +func _harvest(sim: Simulation, grid: NavGrid, me: SimEntity) -> PlayerCommand: + if me.materials[Materials.DRIFTWOOD] >= WANTED_DRIFTWOOD: + step = BUILD + _stop() + _build_yaw = float(me.yaw) / PlayerCommand.YAW_STEPS * TAU + return _hold(sim, me) + var standing: bool = _prop >= 0 and sim.props.is_standing(_prop) + if not standing or sim.tick - _prop_since > roundi(PROP_TIMEOUT_SECONDS * TICKS): + if standing: + _skipped_props[_prop] = true + _prop = _find_prop(sim, me) + _prop_since = sim.tick + if _prop < 0: + step = DONE + return _hold(sim, me) + var box: AABB = sim.props.boxes[_prop] + var eye: Vector3 = Harvest.eye(me) + var centre: Vector3 = box.get_center() + var aim: Vector3 = Vector3(centre.x, clampf(eye.y, box.position.y + 0.2, box.end.y - 0.1), centre.z) + var to: Vector3 = aim - eye + var flat: float = Vector2(to.x, to.z).length() + var yaw: float = atan2(to.x, to.z) + if PropSet._distance_to_box(box, eye) <= Harvest.reach() - 0.6: + _stop() + return PlayerCommand.from_input(sim.tick, Vector2.ZERO, yaw, atan2(to.y, flat), PlayerCommand.BUTTON_FIRE, Simulation.BOATHOOK_SLOT) + if flat <= DIRECT_METRES: + _stop() + var buttons: int = PlayerCommand.BUTTON_JUMP if (sim.tick - _prop_since) % (2 * TICKS) == 2 * TICKS - 1 else 0 + return PlayerCommand.from_input(sim.tick, Vector2(0.0, 1.0), yaw, 0.0, buttons) + _go(Vector3(centre.x, box.position.y, centre.z), DIRECT_METRES - 1.0) + var walk: PlayerCommand = nav.think(sim, grid) + if nav.status == NavBot.UNREACHABLE: + _skipped_props[_prop] = true + _prop = -1 + return walk + + +## The nearest standing driftwood prop on dry ground that hasn't been given up on. +func _find_prop(sim: Simulation, me: SimEntity) -> int: + for prop: int in sim.props.near(me.position, SEARCH_RADIUS): + if _skipped_props.has(prop) or sim.props.material_of(prop) != Materials.NAMES[Materials.DRIFTWOOD]: + continue + var box: AABB = sim.props.boxes[prop] + if box.position.y > sim.sea_level + 0.5 and absf(box.position.y - me.position.y) < 8.0: + return prop + return -1 + + +## Places each piece on the list where the player stands, trying each quarter turn. +func _build(sim: Simulation, me: SimEntity) -> PlayerCommand: + var stock: int = me.materials[Materials.DRIFTWOOD] + if _stock_before >= 0: + if stock < _stock_before: + built += 1 + _to_build.pop_front() + _build_tries = 0 + else: + _build_tries += 1 + _build_yaw += PI * 0.5 + if _build_tries >= 4: + _to_build.pop_front() + _build_tries = 0 + _stock_before = -1 + while not _to_build.is_empty() and stock < StructureSet.cost_of(_to_build[0]): + _to_build.pop_front() + if _to_build.is_empty(): + step = DONE + return _hold(sim, me) + if me.action_cooldown > 0: + return PlayerCommand.from_input(sim.tick, Vector2.ZERO, _build_yaw, 0.0) + _stock_before = stock + return PlayerCommand.from_input( + sim.tick, Vector2.ZERO, _build_yaw, 0.0, + PlayerCommand.BUTTON_BUILD | PlayerCommand.BUTTON_FIRE, _to_build[0], Materials.DRIFTWOOD) diff --git a/src/bots/scripted_player.gd.uid b/src/bots/scripted_player.gd.uid new file mode 100644 index 0000000..ab6908b --- /dev/null +++ b/src/bots/scripted_player.gd.uid @@ -0,0 +1 @@ +uid://n65m74kr6a20 diff --git a/src/client/entities/entity_view.gd b/src/client/entities/entity_view.gd new file mode 100644 index 0000000..e925794 --- /dev/null +++ b/src/client/entities/entity_view.gd @@ -0,0 +1,213 @@ +## Draws what moves in a match: players, the sky barge while it crosses, items lying +## in the world and sea chests. `sync()` matches everything to the simulation as it is +## now. These are stand-in shapes built in code, in the weathered seafaring palette of +## docs/ORIGINALITY.md: an oilskin coat, a sou'wester and a canvas wing-sail. The art +## pass replaces them. Nothing here is ever used for collision. +class_name EntityView +extends Node3D + +## Oilskin colours. A player's is picked by entity ID; the local player wears the first. +const OILSKINS: Array[Color] = [ + Color(0.86, 0.66, 0.16), Color(0.56, 0.27, 0.20), Color(0.33, 0.55, 0.56), Color(0.36, 0.40, 0.30), + Color(0.48, 0.46, 0.44), Color(0.30, 0.36, 0.48), Color(0.62, 0.44, 0.28), +] +const SKIN: Color = Color(0.74, 0.58, 0.46) +const CANVAS: Color = Color(0.84, 0.80, 0.68) +const TAR: Color = Color(0.19, 0.16, 0.13) +const PLANK: Color = Color(0.50, 0.45, 0.37) +const CHEST_SHUT: Color = Color(0.33, 0.55, 0.56) +const CHEST_OPEN: Color = Color(0.22, 0.20, 0.18) +const ITEM: Color = Color(0.93, 0.80, 0.42) +## How far apart passengers stand on the barge's deck, in metres. The simulation +## carries them all at one point; this only spreads them out to be seen. +const DECK_SPACING: float = 1.3 +const DECK_ROWS: int = 4 + +## The entity drawn in the brightest oilskin, or 0. +var local_id: int = 0 + +var _sim: Simulation +## Entity ID -> the figure's root node. +var _figures: Dictionary = {} +var _barge: Node3D +var _pickups: MultiMeshInstance3D +var _chests: MultiMeshInstance3D + + +func setup(sim: Simulation) -> void: + _sim = sim + _barge = _build_barge() + _barge.visible = false + add_child(_barge) + _pickups = _box_field("Pickups", Vector3(0.34, 0.34, 0.34), true) + add_child(_pickups) + _chests = _box_field("Chests", Vector3(0.9, 0.55, 0.6), false) + add_child(_chests) + sync() + + +func figure_count() -> int: + return _figures.size() + + +## The figure drawn for a player, or null. +func figure_of(entity_id: int) -> Node3D: + return _figures.get(entity_id) + + +func barge() -> Node3D: + return _barge + + +func sync() -> void: + if _sim == null: + return + var drop: Drop = _sim.drop + var crossing: bool = drop != null and not drop.finished + var heading: float = 0.0 + if drop != null: + var along: Vector3 = drop.finish - drop.start + heading = atan2(along.x, along.z) + _barge.visible = crossing + if crossing: + _barge.position = drop.barge_position(_sim.tick) + _barge.rotation.y = heading + + var seen: Dictionary = {} + var aboard: int = 0 + for entity: SimEntity in _sim.entities.entities(): + if entity.archetype != SimEntity.ARCHETYPE_PLAYER: + continue + seen[entity.id] = true + var figure: Node3D = _figures.get(entity.id) + if figure == null: + figure = _build_figure(entity.id) + _figures[entity.id] = figure + add_child(figure) + figure.visible = not entity.eliminated + figure.position = entity.position + figure.rotation.y = float(entity.yaw) / PlayerCommand.YAW_STEPS * TAU + if entity.drop_state == Drop.ABOARD: + var column: int = aboard / DECK_ROWS + var row: int = aboard % DECK_ROWS + var offset: Vector3 = Vector3((row - (DECK_ROWS - 1) * 0.5) * DECK_SPACING, 0.0, (2.5 - column) * DECK_SPACING) + figure.position += offset.rotated(Vector3.UP, heading) + figure.rotation.y = heading + aboard += 1 + figure.scale.y = Tuning.CROUCH_HEIGHT / Tuning.PLAYER_HEIGHT if entity.crouching else 1.0 + (figure.get_node("Sail") as Node3D).visible = entity.drop_state == Drop.GLIDING + for entity_id: int in _figures.keys(): + if not seen.has(entity_id): + _figures[entity_id].queue_free() + _figures.erase(entity_id) + + var items: MultiMesh = _pickups.multimesh + items.instance_count = _sim.pickups.size() + for index: int in _sim.pickups.size(): + var pickup: SimEntity = _sim.entities.find(_sim.pickups[index]) + var at: Vector3 = pickup.position + Vector3(0.0, 0.3, 0.0) if pickup != null else Vector3(0.0, -1000.0, 0.0) + items.set_instance_transform(index, Transform3D(Basis(Vector3.UP, 0.6 * index), at)) + items.set_instance_color(index, ITEM) + var chests: MultiMesh = _chests.multimesh + chests.instance_count = _sim.loot.chest_positions.size() + for index: int in _sim.loot.chest_positions.size(): + chests.set_instance_transform(index, Transform3D(Basis.IDENTITY, _sim.loot.chest_positions[index] + Vector3(0.0, 0.28, 0.0))) + chests.set_instance_color(index, CHEST_OPEN if _sim.loot.chest_opened[index] != 0 else CHEST_SHUT) + + +func _process(_delta: float) -> void: + sync() + + +func _build_figure(entity_id: int) -> Node3D: + var coat: Color = OILSKINS[0] if entity_id == local_id else OILSKINS[1 + entity_id % (OILSKINS.size() - 1)] + var figure: Node3D = Node3D.new() + figure.name = "player_%d" % entity_id + var legs: BoxMesh = BoxMesh.new() + legs.size = Vector3(0.42, 0.8, 0.26) + figure.add_child(_part(legs, TAR, Vector3(0.0, 0.4, 0.0))) + var body: CapsuleMesh = CapsuleMesh.new() + body.radius = 0.3 + body.height = 0.95 + figure.add_child(_part(body, coat, Vector3(0.0, 1.05, 0.0))) + var head: SphereMesh = SphereMesh.new() + head.radius = 0.16 + head.height = 0.32 + figure.add_child(_part(head, SKIN, Vector3(0.0, 1.6, 0.0))) + var brim: CylinderMesh = CylinderMesh.new() + brim.top_radius = 0.17 + brim.bottom_radius = 0.33 + brim.height = 0.16 + # The sou'wester's brim runs long at the back. + figure.add_child(_part(brim, coat.darkened(0.25), Vector3(0.0, 1.76, -0.05))) + var sail_mesh: BoxMesh = BoxMesh.new() + sail_mesh.size = Vector3(2.6, 0.04, 0.9) + var sail: MeshInstance3D = _part(sail_mesh, CANVAS, Vector3(0.0, 2.15, -0.1)) + sail.name = "Sail" + sail.rotation.x = deg_to_rad(-8.0) + sail.visible = false + figure.add_child(sail) + return figure + + +## A flat-bottomed hull hung under a canvas envelope. Its deck is at the origin, where +## the simulation carries the passengers. +func _build_barge() -> Node3D: + var barge: Node3D = Node3D.new() + barge.name = "Barge" + var deck: BoxMesh = BoxMesh.new() + deck.size = Vector3(7.5, 0.3, 11.0) + barge.add_child(_part(deck, PLANK, Vector3(0.0, -0.15, 0.0))) + var hull: BoxMesh = BoxMesh.new() + hull.size = Vector3(6.4, 1.3, 9.6) + barge.add_child(_part(hull, TAR, Vector3(0.0, -0.95, 0.0))) + for side: float in [-1.0, 1.0]: + var rail: BoxMesh = BoxMesh.new() + rail.size = Vector3(0.15, 0.7, 11.0) + barge.add_child(_part(rail, TAR, Vector3(side * 3.68, 0.35, 0.0))) + for end: float in [-1.0, 1.0]: + var rope: CylinderMesh = CylinderMesh.new() + rope.top_radius = 0.05 + rope.bottom_radius = 0.05 + rope.height = 7.0 + barge.add_child(_part(rope, PLANK.darkened(0.3), Vector3(side * 3.4, 3.5, end * 4.6))) + var envelope: SphereMesh = SphereMesh.new() + envelope.radius = 1.0 + envelope.height = 2.0 + var bag: MeshInstance3D = _part(envelope, CANVAS, Vector3(0.0, 10.5, 0.0)) + bag.scale = Vector3(5.2, 3.8, 9.0) + barge.add_child(bag) + return barge + + +func _part(mesh: PrimitiveMesh, colour: Color, at: Vector3) -> MeshInstance3D: + var material: StandardMaterial3D = StandardMaterial3D.new() + material.albedo_color = colour + material.roughness = 0.85 + mesh.material = material + var instance: MeshInstance3D = MeshInstance3D.new() + instance.mesh = mesh + instance.position = at + return instance + + +func _box_field(node_name: String, size: Vector3, glow: bool) -> MultiMeshInstance3D: + var material: StandardMaterial3D = StandardMaterial3D.new() + material.vertex_color_use_as_albedo = true + material.roughness = 0.7 + if glow: + material.emission_enabled = true + material.emission = ITEM + material.emission_energy_multiplier = 0.5 + var mesh: BoxMesh = BoxMesh.new() + mesh.size = size + mesh.material = material + var multimesh: MultiMesh = MultiMesh.new() + multimesh.transform_format = MultiMesh.TRANSFORM_3D + multimesh.use_colors = true + multimesh.mesh = mesh + var instance: MultiMeshInstance3D = MultiMeshInstance3D.new() + instance.name = node_name + instance.multimesh = multimesh + instance.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF + return instance diff --git a/src/client/entities/entity_view.gd.uid b/src/client/entities/entity_view.gd.uid new file mode 100644 index 0000000..96e3e3f --- /dev/null +++ b/src/client/entities/entity_view.gd.uid @@ -0,0 +1 @@ +uid://cx6ttunmd4ng4 diff --git a/src/client/match_view.gd b/src/client/match_view.gd new file mode 100644 index 0000000..6a6f527 --- /dev/null +++ b/src/client/match_view.gd @@ -0,0 +1,148 @@ +## The client's picture of one match: sky, sun, terrain, sea, points of interest, props, +## built pieces and everything that moves, all drawn from one Simulation, with the +## third-person camera on a player's shoulder. It only reads the simulation. +## +## A match gets a new Simulation, so it gets a new MatchView. Until snapshots arrive +## (v0.5) the simulation it reads is the local server's or a replay's. +class_name MatchView +extends Node3D + +var sim: Simulation +var terrain: TerrainView +var water: WaterView +var pois: PoiView +var props: PropView +var structures: StructureView +var entities: EntityView +var camera: Camera3D +var rig: CameraRig = CameraRig.new() + + +## Builds the scene for `simulation`. `local_id` is the player this client plays, or 0. +func setup(simulation: Simulation, local_id: int = 0) -> void: + sim = simulation + var sky_material: ProceduralSkyMaterial = ProceduralSkyMaterial.new() + sky_material.sky_top_color = Color(0.32, 0.5, 0.68) + sky_material.sky_horizon_color = Color(0.82, 0.78, 0.68) + sky_material.ground_bottom_color = Color(0.18, 0.2, 0.2) + sky_material.ground_horizon_color = Color(0.82, 0.78, 0.68) + var sky: Sky = Sky.new() + sky.sky_material = sky_material + var environment: Environment = Environment.new() + environment.background_mode = Environment.BG_SKY + environment.sky = sky + environment.ambient_light_source = Environment.AMBIENT_SOURCE_SKY + environment.ambient_light_energy = 0.45 + environment.tonemap_mode = Environment.TONE_MAPPER_FILMIC + environment.fog_enabled = true + environment.fog_light_color = Color(0.78, 0.78, 0.74) + environment.fog_density = 0.0005 + environment.fog_aerial_perspective = 0.4 + var world: WorldEnvironment = WorldEnvironment.new() + world.environment = environment + add_child(world) + var sun: DirectionalLight3D = DirectionalLight3D.new() + sun.rotation_degrees = Vector3(-35.0, -130.0, 0.0) + sun.light_energy = 0.95 + sun.shadow_enabled = true + sun.directional_shadow_max_distance = 400.0 + add_child(sun) + + camera = Camera3D.new() + camera.near = CameraRig.NEAR + camera.far = 2500.0 + camera.fov = CameraRig.FOV + add_child(camera) + camera.make_current() + + if sim.island != null: + terrain = TerrainView.new() + terrain.setup(sim.island) + add_child(terrain) + water = WaterView.new() + add_child(water) + pois = PoiView.new() + pois.setup(sim.pois) + add_child(pois) + props = PropView.new() + props.setup(sim.props) + add_child(props) + structures = StructureView.new() + structures.setup(sim.structures) + add_child(structures) + entities = EntityView.new() + entities.local_id = local_id + entities.setup(sim) + add_child(entities) + sync() + + +## Matches everything drawn to the simulation as it is now. +func sync() -> void: + water.follow(sim) + props.sync() + structures.sync() + entities.sync() + + +## Puts the camera on a player's shoulder, looking where they look. `pitch` replaces +## their own pitch when given, in radians, for views such as looking down from a glide. +func follow(entity_id: int, pitch: float = NAN) -> bool: + var player: SimEntity = sim.entities.find(entity_id) + if player == null: + return false + var yaw: float = float(player.yaw) / PlayerCommand.YAW_STEPS * TAU + var look_pitch: float = pitch if not is_nan(pitch) else float(player.pitch) / PlayerCommand.PITCH_MAX * (PI * 0.5) + camera.transform = rig.solve(player.position, yaw, look_pitch, player.crouching, sim.ground) + camera.fov = rig.fov() + _focus() + return true + + +## Frames a player from outside: the camera stands `distance` metres off at `height` +## above their feet and looks at them, from the first of eight directions that has a +## clear line and no prop around the lens. With `beyond` given, it starts on the far +## side of the player from that point, so the point is in the picture behind them. +func frame(entity_id: int, distance: float = 6.0, height: float = 2.6, beyond: Vector3 = Vector3.INF) -> bool: + var player: SimEntity = sim.entities.find(entity_id) + if player == null: + return false + var chest: Vector3 = player.position + Vector3(0.0, 1.2, 0.0) + var first: float = float(player.yaw) / PlayerCommand.YAW_STEPS * TAU + PI + if beyond != Vector3.INF: + first = atan2(player.position.x - beyond.x, player.position.z - beyond.z) + var eye: Vector3 = chest + for turn: int in 8: + # Straight on first, then alternately to each side. + var angle: float = first + (turn + 1) / 2 * (PI / 4.0) * (1.0 if turn % 2 == 1 else -1.0) + eye = player.position + Vector3(sin(angle) * distance, height, cos(angle) * distance) + eye.y = maxf(eye.y, sim.ground.terrain_height(eye.x, eye.z) + 1.0) + var feet: Vector3 = Vector3(eye.x, sim.ground.terrain_height(eye.x, eye.z), eye.z) + if sim.ground.raycast(chest, eye) >= 1.0 and sim.props.near(feet, 5.0).is_empty(): + break + look_from(eye, chest if beyond == Vector3.INF else chest.lerp(beyond, 0.35)) + return true + + +## Puts the camera at `eye`, looking at `target`. +func look_from(eye: Vector3, target: Vector3) -> void: + camera.transform = Transform3D(Basis.IDENTITY, eye).looking_at(target, Vector3.UP) + camera.fov = CameraRig.FOV + _focus() + + +## The whole island from high over its south-west, as the lobby shows it. +func overview() -> void: + var size: float = Tuning.WORLD_SIZE_METRES + look_from(Vector3(size * 0.2, 300.0, size * 0.92), Vector3(size * 0.5, 0.0, size * 0.47)) + + +## Builds every terrain chunk for the current camera at once. For loading and captures. +func settle() -> void: + if terrain != null: + terrain.build_all_now() + + +func _focus() -> void: + if terrain != null: + terrain.focus = camera.position diff --git a/src/client/match_view.gd.uid b/src/client/match_view.gd.uid new file mode 100644 index 0000000..9658073 --- /dev/null +++ b/src/client/match_view.gd.uid @@ -0,0 +1 @@ +uid://ctcbsm7hld1dc diff --git a/src/server/command_log.gd b/src/server/command_log.gd new file mode 100644 index 0000000..e4f9272 --- /dev/null +++ b/src/server/command_log.gd @@ -0,0 +1,178 @@ +## A match's seed, rules and every command the server was given, in the order it got +## them. With the same engine build that is enough to play the match again exactly: +## the simulation takes nothing else in. See MatchReplay. +## +## Each record is the simulation tick the command arrived on, the handle it came from +## and the command's own 14 bytes. Commands are logged whether or not the simulation +## accepted them, so a replay turns the same ones down. +## +## On disk: "TWCL", a u32 header length, the header as JSON, a u32 length of the raw +## records, then the records compressed with Zstandard. The seed is a string in the +## header, because JSON numbers can't hold 63 bits. +class_name CommandLog +extends RefCounted + +const MAGIC: String = "TWCL" +const VERSION: int = 1 +## at-tick u32, handle s32, then the command. +const RECORD_SIZE: int = 8 + PlayerCommand.ENCODED_SIZE +## Refuse files that claim more than this many raw bytes: about four full matches. +const MAX_RAW_BYTES: int = 64 * 1024 * 1024 +const RULE_KEYS: Array[String] = [ + "max_players", "min_players", "team_size", "lobby_ticks", "countdown_ticks", "results_ticks", "fill_with_bots", +] + +var session_seed: int = 0 +## Human participants, who join with handles 1 and up before the first tick. +var humans: int = 0 +var rules: MatchRules = MatchRules.new() +## What the recording ended with: the simulation tick, its state hash and the winning +## handles. `final_hash` is empty for a recording that was never finished. +var final_tick: int = 0 +var final_hash: String = "" +var winners: Array[int] = [] +## Free-form notes for whoever reads the file: bot count, difficulty and so on. Not +## needed to replay. +var notes: Dictionary = {} + +var _records: StreamPeerBuffer = StreamPeerBuffer.new() + + +func _init(seed_value: int = 0, human_players: int = 0, match_rules: MatchRules = null) -> void: + session_seed = seed_value + humans = human_players + if match_rules != null: + rules = match_rules + _records.big_endian = false + + +func count() -> int: + return _records.get_size() / RECORD_SIZE + + +## Adds a command that arrived from `handle` while the simulation was at `at_tick`. +func record(at_tick: int, handle: int, command: PlayerCommand) -> void: + _records.seek(_records.get_size()) + _records.put_u32(at_tick) + _records.put_32(handle) + _records.put_data(command.encode()) + + +func at_tick_of(index: int) -> int: + return _records.data_array.decode_u32(index * RECORD_SIZE) + + +func handle_of(index: int) -> int: + return _records.data_array.decode_s32(index * RECORD_SIZE + 4) + + +func command_of(index: int) -> PlayerCommand: + return PlayerCommand.decode(_records.data_array, index * RECORD_SIZE + 8) + + +## Marks the recording finished with the state it reached. +func finish(flow: Match) -> void: + final_tick = flow.sim.tick + final_hash = flow.sim.state_hash() + winners = flow.winners.duplicate() + + +func header() -> Dictionary: + var rule_values: Dictionary = {} + for key: String in RULE_KEYS: + rule_values[key] = rules.get(key) + return { + "version": VERSION, + "engine": Engine.get_version_info()["string"], + "seed": str(session_seed), + "humans": humans, + "rules": rule_values, + "records": count(), + "final_tick": final_tick, + "final_hash": final_hash, + "winners": winners, + "notes": notes, + } + + +func to_bytes() -> PackedByteArray: + var head: PackedByteArray = JSON.stringify(header()).to_utf8_buffer() + var raw: PackedByteArray = _records.data_array + var out: StreamPeerBuffer = StreamPeerBuffer.new() + out.big_endian = false + out.put_data(MAGIC.to_ascii_buffer()) + out.put_u32(head.size()) + out.put_data(head) + out.put_u32(raw.size()) + if raw.size() > 0: + out.put_data(raw.compress(FileAccess.COMPRESSION_ZSTD)) + return out.data_array + + +## Reads a log back, or returns null if the bytes aren't a usable log. Nothing in a bad +## file can raise an error: every length is checked before it is used. +static func from_bytes(bytes: PackedByteArray) -> CommandLog: + if bytes.size() < 12 or bytes.slice(0, 4).get_string_from_ascii() != MAGIC: + return null + var head_size: int = bytes.decode_u32(4) + if head_size <= 0 or 8 + head_size + 4 > bytes.size(): + return null + var parser: JSON = JSON.new() + if parser.parse(bytes.slice(8, 8 + head_size).get_string_from_utf8()) != OK or not parser.data is Dictionary: + return null + var head: Dictionary = parser.data + if int(head.get("version", 0)) != VERSION or not head.get("rules") is Dictionary or not str(head.get("seed", "")).is_valid_int(): + return null + var raw_size: int = bytes.decode_u32(8 + head_size) + if raw_size < 0 or raw_size > MAX_RAW_BYTES or raw_size % RECORD_SIZE != 0: + return null + var raw: PackedByteArray = PackedByteArray() + if raw_size > 0: + var packed: PackedByteArray = bytes.slice(12 + head_size) + if packed.is_empty(): + return null + raw = packed.decompress(raw_size, FileAccess.COMPRESSION_ZSTD) + if raw.size() != raw_size: + return null + var result: CommandLog = CommandLog.new(str(head["seed"]).to_int(), clampi(int(head.get("humans", 0)), 0, Tuning.SOLO_PLAYERS)) + var rule_values: Dictionary = head["rules"] + for key: String in RULE_KEYS: + if not rule_values.has(key): + return null + if key == "fill_with_bots": + result.rules.fill_with_bots = bool(rule_values[key]) + else: + result.rules.set(key, int(rule_values[key])) + result.rules.max_players = clampi(result.rules.max_players, 1, Tuning.SOLO_PLAYERS) + result.rules.team_size = maxi(result.rules.team_size, 1) + result.final_tick = int(head.get("final_tick", 0)) + result.final_hash = str(head.get("final_hash", "")) + if head.get("winners") is Array: + for winner: Variant in head["winners"]: + result.winners.append(int(winner)) + if head.get("notes") is Dictionary: + result.notes = head["notes"] + result._records.data_array = raw + return result + + +## Writes the log to `path`, creating its folder. Returns OK or the error. +func save(path: String) -> Error: + var folder: String = path.get_base_dir() + if not DirAccess.dir_exists_absolute(folder): + var made: Error = DirAccess.make_dir_recursive_absolute(folder) + if made != OK: + return made + var file: FileAccess = FileAccess.open(path, FileAccess.WRITE) + if file == null: + return FileAccess.get_open_error() + file.store_buffer(to_bytes()) + file.close() + return OK + + +## Reads the log at `path`, or returns null if it is missing or unusable. +static func load_from(path: String) -> CommandLog: + if not FileAccess.file_exists(path): + return null + return from_bytes(FileAccess.get_file_as_bytes(path)) diff --git a/src/server/command_log.gd.uid b/src/server/command_log.gd.uid new file mode 100644 index 0000000..137e50f --- /dev/null +++ b/src/server/command_log.gd.uid @@ -0,0 +1 @@ +uid://b0f8jbsbyhwiu diff --git a/src/server/match_replay.gd b/src/server/match_replay.gd new file mode 100644 index 0000000..5dbaeda --- /dev/null +++ b/src/server/match_replay.gd @@ -0,0 +1,85 @@ +## Plays a recorded match again from its CommandLog: the same seed, the same rules, the +## same commands on the same ticks, and nobody thinking. Bots and scripted players +## aren't run; their commands are in the log like everyone else's. +## +## The replay covers the log's first match, from the lobby to its results. +class_name MatchReplay +extends RefCounted + +var commands: CommandLog +var flow: Match +var sim: Simulation: + get: + return flow.sim +## Server ticks run, lobby and countdown included. +var ticks: int = 0 + +var _cursor: int = 0 + + +func _init(command_log: CommandLog) -> void: + commands = command_log + flow = Match.new(commands.session_seed, commands.rules) + for handle: int in range(1, commands.humans + 1): + flow.join(handle) + + +## True once the match's results are in, or the match can't go on. +func finished() -> bool: + return flow.phase == Match.RESULTS + + +## Runs one server tick. Returns false, doing nothing, once the match has finished. +func step() -> bool: + if finished(): + return false + if flow.in_match(): + var tick: int = sim.tick + while _cursor < commands.count() and commands.at_tick_of(_cursor) <= tick: + if commands.at_tick_of(_cursor) == tick: + flow.submit_command(commands.handle_of(_cursor), commands.command_of(_cursor)) + _cursor += 1 + flow.step() + ticks += 1 + return true + + +## Steps until `done` returns true (it is asked before each tick), the match finishes, +## or `limit` server ticks have run. Returns true if `done` was satisfied. +func run_until(done: Callable, limit: int = default_limit()) -> bool: + while ticks < limit: + if done.call(): + return true + if not step(): + return bool(done.call()) + return bool(done.call()) + + +## Steps to the match's results. Returns true if it got there within `limit` ticks. +func run_to_end(limit: int = default_limit()) -> bool: + while ticks < limit and step(): + pass + return finished() + + +## The longest a logged match can take in server ticks: lobby, countdown, the tide's +## whole schedule, and slack. +func default_limit() -> int: + return commands.rules.lobby_ticks + commands.rules.countdown_ticks + Tide.new(0).time_limit_offset() + 60 * Tuning.TICK_RATE_HZ + + +## Compares where the replay is with what the recording ended on. Call after +## run_to_end(). Returns {"ok", "tick", "expected_tick", "hash", "expected_hash", +## "winners", "expected_winners"}. +func verify() -> Dictionary: + var digest: String = sim.state_hash() + return { + "ok": finished() and not commands.final_hash.is_empty() and digest == commands.final_hash + and sim.tick == commands.final_tick and flow.winners == commands.winners, + "tick": sim.tick, + "expected_tick": commands.final_tick, + "hash": digest, + "expected_hash": commands.final_hash, + "winners": flow.winners.duplicate(), + "expected_winners": commands.winners.duplicate(), + } diff --git a/src/server/match_replay.gd.uid b/src/server/match_replay.gd.uid new file mode 100644 index 0000000..deeb50d --- /dev/null +++ b/src/server/match_replay.gd.uid @@ -0,0 +1 @@ +uid://bbybxusl4dakt diff --git a/src/server/server_loop.gd b/src/server/server_loop.gd index d787853..c35a648 100644 --- a/src/server/server_loop.gd +++ b/src/server/server_loop.gd @@ -15,6 +15,10 @@ var sim: Simulation: ## Entity IDs of everyone in the current match, humans first. var player_ids: Array[int] = [] var bots: Array[BotBrain] = [] +## Human seats played by script, when play_humans_by_script() was called. +var scripted: Array[ScriptedPlayer] = [] +## When set, every command the server is given during the first match goes in it. +var recorder: CommandLog = null ## The current or next match's navigation grid and bot map, built while the lobby waits. var nav: NavGrid = null var world: BotWorld = null @@ -25,6 +29,8 @@ var tick_usec: PackedInt64Array = PackedInt64Array() ## Server ticks run, across every match. var ticks: int = 0 +var _script_humans: bool = false + ## `human_players` join as idle participants with handles 1 and up; `bot_count` bots ## fill the rest of every match. With `rules` null the match starts at once, and the @@ -32,11 +38,7 @@ var ticks: int = 0 func _init(match_seed: int, human_players: int, bot_count: int, rules: MatchRules = null, difficulty: int = -1) -> void: bot_difficulty = difficulty if rules == null: - rules = MatchRules.immediate() - rules.max_players = maxi(human_players + bot_count, 1) - rules.fill_with_bots = bot_count > 0 - # With only bots there's nobody to wait for, so the lobby starts with no one in it. - rules.min_players = 0 if human_players == 0 and bot_count > 0 else 1 + rules = immediate_rules(human_players, bot_count) match_flow = Match.new(match_seed, rules) nav = NavGrid.build(match_flow.sim) world = BotWorld.build(match_flow.sim, nav) @@ -47,14 +49,55 @@ func _init(match_seed: int, human_players: int, bot_count: int, rules: MatchRule _advance() +## Rules for a server that skips the lobby and fills the match with `bot_count` bots. +static func immediate_rules(human_players: int, bot_count: int) -> MatchRules: + var rules: MatchRules = MatchRules.immediate() + rules.max_players = maxi(human_players + bot_count, 1) + rules.fill_with_bots = bot_count > 0 + # With only bots there's nobody to wait for, so the lobby starts with no one in it. + rules.min_players = 0 if human_players == 0 and bot_count > 0 else 1 + return rules + + +## Starts recording every command into a new log, which is returned. Call before the +## first tick; the log covers the first match. +func record_commands() -> CommandLog: + var humans: int = 0 + for handle: int in match_flow.participants: + if not match_flow.bot_handles.has(handle): + humans += 1 + recorder = CommandLog.new(match_flow.session_seed, humans, match_flow.rules) + recorder.notes = {"bot_difficulty": bot_difficulty} + return recorder + + +## From now on, every human seat is played by a ScriptedPlayer: a stand-in for a +## person at the controls, for whole-match tests before and without the network. +func play_humans_by_script() -> void: + _script_humans = true + if match_flow.in_match(): + _track_players() + + +## Gives the simulation a participant's command for the current match. Returns false +## if it was turned down. This is the one way commands get in, for people, scripts and +## bots alike, so the recorder sees them all. +func submit(handle: int, command: PlayerCommand) -> bool: + if recorder != null and match_flow.matches_started == 1 and match_flow.in_match(): + recorder.record(sim.tick, handle, command) + return match_flow.submit_command(handle, command) + + ## Runs one tick and records how long it took. func run_tick() -> void: var started: int = Time.get_ticks_usec() if match_flow.in_match(): nav.sync(sim) world.observe(sim) + for player: ScriptedPlayer in scripted: + submit(match_flow.handle_of[player.player_id], player.think(sim, nav, world)) for bot: BotBrain in bots: - sim.submit_command(bot.player_id, bot.think(sim, nav, world)) + submit(match_flow.handle_of[bot.player_id], bot.think(sim, nav, world)) _advance() ticks += 1 tick_usec.append(Time.get_ticks_usec() - started) @@ -65,9 +108,12 @@ func _advance() -> void: for event: Dictionary in match_flow.events: if event["type"] == "match_started": _track_players() + elif event["type"] == "match_ended" and recorder != null and match_flow.matches_started == 1 and recorder.final_hash.is_empty(): + recorder.finish(match_flow) elif event["type"] == "phase" and event["to"] == "lobby": player_ids.clear() bots.clear() + scripted.clear() if event["from"] == "results": nav = NavGrid.build(match_flow.sim) world = BotWorld.build(match_flow.sim, nav) @@ -76,10 +122,14 @@ func _advance() -> void: func _track_players() -> void: player_ids.clear() bots.clear() + scripted.clear() for handle: int in match_flow.participants: var entity_id: int = match_flow.entity_of[handle] player_ids.append(entity_id) - if match_flow.bot_handles.has(handle): + if not match_flow.bot_handles.has(handle): + if _script_humans: + scripted.append(ScriptedPlayer.new(entity_id)) + else: var level: int = bot_difficulty if bot_difficulty >= 0 else bots.size() % Tuning.BOT_DIFFICULTIES.size() bots.append(BotBrain.new(entity_id, level)) world.player_ids = player_ids.duplicate() diff --git a/test/bots/test_scripted_player.gd b/test/bots/test_scripted_player.gd new file mode 100644 index 0000000..0362929 --- /dev/null +++ b/test/bots/test_scripted_player.gd @@ -0,0 +1,44 @@ +extends TestCase + +## The scripted player from issue M8: a stand-in for a person, which also harvests and +## builds, things bots don't do yet. + + +func test_a_scripted_seat_sends_commands_like_anyone_else() -> void: + var loop: ServerLoop = ServerLoop.new(99, 1, 1) + loop.play_humans_by_script() + assert_eq(loop.scripted.size(), 1) + assert_eq(loop.scripted[0].player_id, 1) + assert_eq(loop.bots.size(), 1) + for _index: int in Tuning.TICK_RATE_HZ * 24: + loop.run_tick() + assert_ne(loop.sim.entities.find(1).drop_state, Drop.ABOARD, "the scripted player leapt from the barge") + + +func test_harvests_driftwood_and_builds_with_it() -> void: + # Seed 2 is the match `make match` plays: the player lands, finds a weapon, cuts + # driftwood and puts up a breakwater and a wall about a minute in. + var loop: ServerLoop = ServerLoop.new(2, 1, 23) + loop.play_humans_by_script() + var player: ScriptedPlayer = loop.scripted[0] + var placed: int = 0 + var harvests: int = 0 + while loop.ticks < 2400 and player.step != ScriptedPlayer.DONE: + loop.run_tick() + for event: Dictionary in loop.sim.events: + if event["type"] == "piece_placed" and event["player"] == player.player_id: + placed += 1 + elif event["type"] == "harvest" and event["player"] == player.player_id: + harvests += 1 + assert_eq(player.step, ScriptedPlayer.DONE) + assert_true(harvests >= 3, "swung at props %d times" % harvests) + assert_true(player.harvested >= ScriptedPlayer.WANTED_DRIFTWOOD, "harvested %d" % player.harvested) + assert_eq(player.built, 2) + assert_eq(placed, 2) + var kinds: Array[int] = [] + for piece: StructureSet.Piece in loop.sim.structures.pieces.values(): + if piece.owner == player.player_id: + kinds.append(piece.kind) + kinds.sort() + assert_eq(kinds, [StructureSet.WALL, StructureSet.BREAKWATER] as Array[int]) + assert_false(loop.sim.entities.find(player.player_id).eliminated) diff --git a/test/bots/test_scripted_player.gd.uid b/test/bots/test_scripted_player.gd.uid new file mode 100644 index 0000000..3c53b8f --- /dev/null +++ b/test/bots/test_scripted_player.gd.uid @@ -0,0 +1 @@ +uid://cci7ssoaiiyt8 diff --git a/test/capture/match_barge.tscn b/test/capture/match_barge.tscn new file mode 100644 index 0000000..afd1a59 --- /dev/null +++ b/test/capture/match_barge.tscn @@ -0,0 +1,7 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/match_scene.gd" id="1"] + +[node name="CaptureMatch" type="Node3D"] +script = ExtResource("1") +stage = "barge" diff --git a/test/capture/match_built.tscn b/test/capture/match_built.tscn new file mode 100644 index 0000000..49cfe4c --- /dev/null +++ b/test/capture/match_built.tscn @@ -0,0 +1,7 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/match_scene.gd" id="1"] + +[node name="CaptureMatch" type="Node3D"] +script = ExtResource("1") +stage = "built" diff --git a/test/capture/match_final.tscn b/test/capture/match_final.tscn new file mode 100644 index 0000000..8fb4631 --- /dev/null +++ b/test/capture/match_final.tscn @@ -0,0 +1,7 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/match_scene.gd" id="1"] + +[node name="CaptureMatch" type="Node3D"] +script = ExtResource("1") +stage = "final" diff --git a/test/capture/match_glide.tscn b/test/capture/match_glide.tscn new file mode 100644 index 0000000..6fd49d6 --- /dev/null +++ b/test/capture/match_glide.tscn @@ -0,0 +1,7 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/match_scene.gd" id="1"] + +[node name="CaptureMatch" type="Node3D"] +script = ExtResource("1") +stage = "glide" diff --git a/test/capture/match_landed.tscn b/test/capture/match_landed.tscn new file mode 100644 index 0000000..8bf8d3e --- /dev/null +++ b/test/capture/match_landed.tscn @@ -0,0 +1,7 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/match_scene.gd" id="1"] + +[node name="CaptureMatch" type="Node3D"] +script = ExtResource("1") +stage = "landed" diff --git a/test/capture/match_lobby.tscn b/test/capture/match_lobby.tscn new file mode 100644 index 0000000..8b1bb3d --- /dev/null +++ b/test/capture/match_lobby.tscn @@ -0,0 +1,7 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/match_scene.gd" id="1"] + +[node name="CaptureMatch" type="Node3D"] +script = ExtResource("1") +stage = "lobby" diff --git a/test/capture/match_results.tscn b/test/capture/match_results.tscn new file mode 100644 index 0000000..4f3a92b --- /dev/null +++ b/test/capture/match_results.tscn @@ -0,0 +1,7 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/match_scene.gd" id="1"] + +[node name="CaptureMatch" type="Node3D"] +script = ExtResource("1") +stage = "results" diff --git a/test/capture/match_scene.gd b/test/capture/match_scene.gd new file mode 100644 index 0000000..76be484 --- /dev/null +++ b/test/capture/match_scene.gd @@ -0,0 +1,149 @@ +## Capture scenario for a whole match. It replays the command log `make match` saved +## to the moment `stage` names, draws that moment with the client's MatchView, and +## prints what it shows as a caption (Godot's default font; this is a test caption, +## not the game's HUD). +## +## Stages: lobby, barge, glide, landed, built, final, tide (the island just before the +## end, from where the lobby saw it), results. +extends Node3D + +const TICKS: int = Tuning.TICK_RATE_HZ +## The scripted player's handle. +const PLAYER: int = 1 + +@export var log_path: String = "res://build/match/match.tclog" +@export var stage: String = "lobby" + +var _replay: MatchReplay +var _view: MatchView + + +func _ready() -> void: + var commands: CommandLog = CommandLog.load_from(log_path) + if commands == null: + push_error("match capture: no usable command log at %s; run `make match` first" % log_path) + return + _replay = MatchReplay.new(commands) + var flow: Match = _replay.flow + var last: int = commands.final_tick + match stage: + "lobby": + pass + "barge": + _replay.run_until(func() -> bool: return flow.in_match() and flow.sim.tick >= 2 * TICKS) + "glide": + _replay.run_until(func() -> bool: return _player() != null and _player().drop_state == Drop.GLIDING) + _run_ticks(TICKS) + "landed": + _replay.run_until(func() -> bool: return _player() != null and _player().drop_state == Drop.NONE and flow.in_match()) + _run_ticks(4 * TICKS) + "built": + _replay.run_until(func() -> bool: return flow.sim.structures.count() >= 2) + _run_ticks(3 * TICKS) + "tide": + _replay.run_until(func() -> bool: return flow.in_match() and flow.sim.tick >= last - 2 * TICKS) + "final": + _replay.run_until(func() -> bool: return flow.in_match() and flow.sim.tick > 10 * TICKS and flow.alive().size() <= 3) + "results": + _replay.run_to_end() + _: + push_error("match capture: unknown stage '%s'" % stage) + return + + var sim: Simulation = flow.sim + var player_id: int = int(flow.entity_of.get(PLAYER, 0)) + _view = MatchView.new() + _view.setup(sim, player_id) + add_child(_view) + var watched: int = _watched() + var who: String = "nobody" + if stage == "lobby" or stage == "tide": + _view.overview() + who = "the island" + elif stage == "barge": + var along: Vector3 = (sim.drop.finish - sim.drop.start).normalized() + var at: Vector3 = sim.drop.barge_position(sim.tick) + _view.look_from(at - along * 22.0 + Vector3(0.0, 9.0, 0.0) + along.cross(Vector3.UP) * 9.0, at + along * 40.0 - Vector3(0.0, 22.0, 0.0)) + who = "the barge" + elif watched != 0: + var entity: SimEntity = sim.entities.find(flow.entity_of[watched]) + var airborne: bool = entity.drop_state != Drop.NONE + if stage == "built" and sim.structures.count() > 0: + var piece: StructureSet.Piece = sim.structures.pieces.values()[0] + _view.frame(entity.id, 7.0, 2.8, piece.boxes[0].get_center()) + elif stage == "results": + _view.frame(entity.id) + else: + _view.follow(entity.id, deg_to_rad(-22.0) if airborne else deg_to_rad(-9.0)) + who = "the player" if watched == PLAYER else "bot %d" % -watched + else: + _view.overview() + _view.settle() + _caption(_describe(who)) + + +func _player() -> SimEntity: + var flow: Match = _replay.flow + if not flow.entity_of.has(PLAYER): + return null + return flow.sim.entities.find(flow.entity_of[PLAYER]) + + +func _run_ticks(count: int) -> void: + for _index: int in count: + if not _replay.step(): + return + + +## The handle the camera follows: the player while they stand, then whoever they're +## spectating, then a winner, then anyone still standing. 0 for nobody. +func _watched() -> int: + var flow: Match = _replay.flow + var living: Array[int] = flow.alive() + if living.has(PLAYER): + return PLAYER + var target: int = flow.spectate_target(PLAYER) + if target != 0 and flow.entity_of.has(target): + return target + if not flow.winners.is_empty(): + return flow.winners[0] + return living[0] if not living.is_empty() else 0 + + +func _describe(who: String) -> String: + var flow: Match = _replay.flow + var sim: Simulation = flow.sim + var lines: Array[String] = [] + lines.append("%s · %s · seed %d" % [stage.to_upper(), flow.phase_name(), _replay.commands.session_seed]) + if flow.phase == Match.LOBBY or flow.phase == Match.COUNTDOWN: + lines.append("%d waiting · the match starts in %d s" % [flow.participants.size(), (flow.rules.lobby_ticks + flow.rules.countdown_ticks) / TICKS]) + return "\n".join(lines) + lines.append("%d:%02d · %d of %d standing · sea %.1f m · tide phase %d" % [ + sim.tick / TICKS / 60, sim.tick / TICKS % 60, flow.alive().size(), flow.summary().size(), sim.sea_level, + sim.tide.phase_at(sim.tick) + 1 if sim.tide != null else 0]) + var me: SimEntity = _player() + if me != null: + lines.append("player: health %d · driftwood %d · %d pieces built · watching %s" % [ + me.health, me.materials[Materials.DRIFTWOOD], sim.structures.count(), who]) + if flow.phase == Match.RESULTS: + for row: Dictionary in flow.summary(): + if row["place"] <= 3 or row["handle"] == PLAYER: + lines.append("#%d %s · %d eliminations · %d damage · %d s" % [ + row["place"], "player" if row["handle"] == PLAYER else "bot %d" % -int(row["handle"]), + row["eliminations"], row["damage_dealt"], roundi(row["survival_seconds"])]) + return "\n".join(lines) + + +func _caption(text: String) -> void: + var settings: LabelSettings = LabelSettings.new() + settings.font_size = 20 + settings.font_color = Color(0.96, 0.94, 0.88) + settings.outline_size = 6 + settings.outline_color = Color(0.08, 0.09, 0.1) + var label: Label = Label.new() + label.label_settings = settings + label.text = text + label.position = Vector2(18.0, 14.0) + var layer: CanvasLayer = CanvasLayer.new() + layer.add_child(label) + add_child(layer) diff --git a/test/capture/match_scene.gd.uid b/test/capture/match_scene.gd.uid new file mode 100644 index 0000000..a5ba5b9 --- /dev/null +++ b/test/capture/match_scene.gd.uid @@ -0,0 +1 @@ +uid://ix887lku6smh diff --git a/test/capture/match_tide.tscn b/test/capture/match_tide.tscn new file mode 100644 index 0000000..82bd47b --- /dev/null +++ b/test/capture/match_tide.tscn @@ -0,0 +1,7 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/match_scene.gd" id="1"] + +[node name="CaptureMatch" type="Node3D"] +script = ExtResource("1") +stage = "tide" diff --git a/test/client/test_match_view.gd b/test/client/test_match_view.gd new file mode 100644 index 0000000..3ac8a17 --- /dev/null +++ b/test/client/test_match_view.gd @@ -0,0 +1,81 @@ +extends TestCase + +## The client's picture of a match (issue M8): one view over a simulation, with every +## player, the barge, items and chests drawn from it. + + +func _match(bots: int = 3) -> ServerLoop: + return ServerLoop.new(2, 1, bots) + + +func test_draws_every_player_and_the_barge() -> void: + var loop: ServerLoop = _match() + var view: MatchView = MatchView.new() + view.setup(loop.sim, 1) + assert_eq(view.entities.figure_count(), 4) + assert_true(view.entities.barge().visible) + assert_true(view.entities.barge().position.distance_to(loop.sim.drop.barge_position(loop.sim.tick)) < 0.001) + # Passengers are spread over the deck, not stacked on one spot. + assert_true(view.entities.figure_of(1).position.distance_to(view.entities.figure_of(2).position) > 1.0) + assert_eq(view.entities.get_node("Pickups").multimesh.instance_count, loop.sim.pickups.size()) + assert_eq(view.entities.get_node("Chests").multimesh.instance_count, loop.sim.loot.chest_positions.size()) + assert_not_null(view.terrain) + view.free() + + +func test_follows_the_simulation() -> void: + var loop: ServerLoop = _match() + var view: MatchView = MatchView.new() + view.setup(loop.sim, 1) + while not loop.sim.drop.finished: + loop.run_tick() + loop.sim.entities.find(3).health = 0 + loop.run_tick() + loop.sim.set_sea_level(6.5) + view.sync() + assert_false(view.entities.barge().visible, "the barge is gone once the drop is over") + assert_false(view.entities.figure_of(3).visible, "an eliminated player isn't drawn") + var bot: SimEntity = loop.sim.entities.find(2) + if not bot.eliminated: + assert_true(view.entities.figure_of(2).position.distance_to(bot.position) < 0.001) + assert_near(view.water.level, 6.5, 0.001) + assert_eq(view.entities.get_node("Pickups").multimesh.instance_count, loop.sim.pickups.size()) + view.free() + + +func test_gliding_players_show_a_wing_sail() -> void: + var loop: ServerLoop = _match(1) + var view: MatchView = MatchView.new() + view.setup(loop.sim, 1) + var bot: SimEntity = loop.sim.entities.find(2) + assert_false((view.entities.figure_of(2).get_node("Sail") as Node3D).visible) + var guard: int = 0 + while bot.drop_state != Drop.GLIDING and guard < 3000: + loop.run_tick() + guard += 1 + view.sync() + assert_eq(bot.drop_state, Drop.GLIDING) + assert_true((view.entities.figure_of(2).get_node("Sail") as Node3D).visible) + view.free() + + +func test_the_camera_follows_a_player_and_frames_one() -> void: + var loop: ServerLoop = _match() + var view: MatchView = MatchView.new() + view.setup(loop.sim, 1) + while not loop.sim.drop.finished: + loop.run_tick() + view.sync() + var bot: SimEntity = loop.sim.entities.find(2) + assert_true(view.follow(2)) + var gap: float = view.camera.position.distance_to(bot.position) + assert_true(gap > 0.5 and gap < 6.0, "the camera is %f m from the player" % gap) + assert_eq(view.terrain.focus, view.camera.position) + assert_true(view.frame(2)) + var to_player: Vector3 = (bot.position + Vector3(0.0, 1.2, 0.0) - view.camera.position).normalized() + assert_true(to_player.dot(-view.camera.transform.basis.z) > 0.98, "the camera looks at the player") + assert_false(view.follow(999)) + assert_false(view.frame(999)) + view.overview() + assert_true(view.camera.position.y > 200.0) + view.free() diff --git a/test/client/test_match_view.gd.uid b/test/client/test_match_view.gd.uid new file mode 100644 index 0000000..17e2c99 --- /dev/null +++ b/test/client/test_match_view.gd.uid @@ -0,0 +1 @@ +uid://0vi50i7uptfw diff --git a/test/server/test_command_log.gd b/test/server/test_command_log.gd new file mode 100644 index 0000000..d343899 --- /dev/null +++ b/test/server/test_command_log.gd @@ -0,0 +1,105 @@ +extends TestCase + +## The command log from issue M8: what a match was given, kept so it can be replayed. + + +func _command(tick: int, buttons: int) -> PlayerCommand: + return PlayerCommand.from_input(tick, Vector2(0.5, -1.0), 1.25, -0.3, buttons, 2, 1) + + +func _log() -> CommandLog: + var rules: MatchRules = MatchRules.new() + rules.max_players = 6 + rules.lobby_ticks = 12 + rules.fill_with_bots = false + # A seed too large for a JSON number to hold exactly. + var commands: CommandLog = CommandLog.new(0x7FFFFFFFFFFFFFF1, 2, rules) + commands.record(0, 1, _command(0, PlayerCommand.BUTTON_JUMP)) + commands.record(0, -3, _command(0, 0)) + commands.record(7, 2, _command(9, PlayerCommand.BUTTON_FIRE | PlayerCommand.BUTTON_BUILD)) + commands.final_tick = 8 + commands.final_hash = "abc123" + commands.winners = [-3] as Array[int] + commands.notes = {"bots": 4} + return commands + + +func test_records_keep_their_tick_handle_and_command() -> void: + var commands: CommandLog = _log() + assert_eq(commands.count(), 3) + assert_eq(commands.at_tick_of(2), 7) + assert_eq(commands.handle_of(1), -3) + assert_eq(commands.handle_of(2), 2) + assert_eq(commands.command_of(2).encode(), _command(9, PlayerCommand.BUTTON_FIRE | PlayerCommand.BUTTON_BUILD).encode()) + + +func test_round_trips_through_bytes() -> void: + var commands: CommandLog = _log() + var back: CommandLog = CommandLog.from_bytes(commands.to_bytes()) + assert_not_null(back) + assert_eq(back.session_seed, 0x7FFFFFFFFFFFFFF1, "the whole 63-bit seed survives") + assert_eq(back.humans, 2) + assert_eq(back.rules.max_players, 6) + assert_eq(back.rules.lobby_ticks, 12) + assert_false(back.rules.fill_with_bots) + assert_eq(back.rules.countdown_ticks, commands.rules.countdown_ticks) + assert_eq(back.count(), 3) + for index: int in 3: + assert_eq(back.at_tick_of(index), commands.at_tick_of(index)) + assert_eq(back.handle_of(index), commands.handle_of(index)) + assert_eq(back.command_of(index).encode(), commands.command_of(index).encode()) + assert_eq(back.final_tick, 8) + assert_eq(back.final_hash, "abc123") + assert_eq(back.winners, [-3] as Array[int]) + assert_eq(int(back.notes["bots"]), 4) + + +func test_an_empty_log_round_trips() -> void: + var back: CommandLog = CommandLog.from_bytes(CommandLog.new(5, 0).to_bytes()) + assert_not_null(back) + assert_eq(back.count(), 0) + assert_eq(back.session_seed, 5) + + +func test_saves_and_loads_a_file() -> void: + var path: String = "user://test_command_log/roundtrip.tclog" + assert_eq(_log().save(path), OK) + var back: CommandLog = CommandLog.load_from(path) + assert_not_null(back) + assert_eq(back.count(), 3) + DirAccess.remove_absolute(path) + assert_null(CommandLog.load_from(path), "a missing file is no log") + + +func test_bad_bytes_are_refused_without_errors() -> void: + var good: PackedByteArray = _log().to_bytes() + assert_null(CommandLog.from_bytes(PackedByteArray())) + assert_null(CommandLog.from_bytes("TWCL".to_ascii_buffer())) + var wrong_magic: PackedByteArray = good.duplicate() + wrong_magic[0] = 0x58 + assert_null(CommandLog.from_bytes(wrong_magic)) + # Cut short anywhere: never a log with records missing, never an engine error. + for size: int in range(0, good.size(), 7): + var cut: CommandLog = CommandLog.from_bytes(good.slice(0, size)) + assert_true(cut == null or cut.count() == 3, "cut at %d bytes" % size) + # A header length that points past the end. + var long_header: PackedByteArray = good.duplicate() + long_header.encode_u32(4, 0x7FFFFFFF) + assert_null(CommandLog.from_bytes(long_header)) + # A header that isn't JSON. + var head_size: int = good.decode_u32(4) + var not_json: PackedByteArray = good.duplicate() + for index: int in range(8, 8 + head_size): + not_json[index] = 0x7B + assert_null(CommandLog.from_bytes(not_json)) + # A raw length that is huge, or not a whole number of records. + var huge: PackedByteArray = good.duplicate() + huge.encode_u32(8 + head_size, 0x7FFFFFF0) + assert_null(CommandLog.from_bytes(huge)) + var ragged: PackedByteArray = good.duplicate() + ragged.encode_u32(8 + head_size, CommandLog.RECORD_SIZE * 3 + 1) + assert_null(CommandLog.from_bytes(ragged)) + # Records that don't decompress to the promised length. + var short: PackedByteArray = good.duplicate() + short.encode_u32(8 + head_size, CommandLog.RECORD_SIZE * 40) + assert_null(CommandLog.from_bytes(short)) diff --git a/test/server/test_command_log.gd.uid b/test/server/test_command_log.gd.uid new file mode 100644 index 0000000..a05d31a --- /dev/null +++ b/test/server/test_command_log.gd.uid @@ -0,0 +1 @@ +uid://clgykma7ju4if diff --git a/test/server/test_match_replay.gd b/test/server/test_match_replay.gd new file mode 100644 index 0000000..4ce9731 --- /dev/null +++ b/test/server/test_match_replay.gd @@ -0,0 +1,93 @@ +extends TestCase + +## Issue M8: a seed and a command log reproduce a match. + + +## Plays a small match to its end with one scripted player, recording it. +func _recorded(seed_value: int, bots: int, rules: MatchRules = null) -> ServerLoop: + var loop: ServerLoop = ServerLoop.new(seed_value, 1, bots, rules) + loop.play_humans_by_script() + loop.record_commands() + var limit: int = BotBatch.tick_limit() + 2000 + while loop.ticks < limit and loop.recorder.final_hash.is_empty(): + loop.run_tick() + return loop + + +func test_a_replay_ends_in_the_same_state() -> void: + var loop: ServerLoop = _recorded(41, 5) + var commands: CommandLog = loop.recorder + assert_false(commands.final_hash.is_empty(), "the match ended") + assert_eq(commands.winners.size(), 1) + assert_true(commands.count() >= commands.final_tick * 6, "every seat's command is logged every tick") + # Through bytes, as a saved file would be. + var replay: MatchReplay = MatchReplay.new(CommandLog.from_bytes(commands.to_bytes())) + assert_true(replay.run_to_end()) + var verdict: Dictionary = replay.verify() + assert_true(verdict["ok"], "replay %s" % verdict) + assert_eq(replay.sim.tick, commands.final_tick) + assert_eq(replay.flow.winners, commands.winners) + assert_false(replay.step(), "a finished replay doesn't step") + + +func test_a_replay_runs_the_lobby_and_countdown_too() -> void: + var rules: MatchRules = MatchRules.new() + rules.max_players = 4 + rules.lobby_ticks = 20 + rules.countdown_ticks = 10 + var loop: ServerLoop = _recorded(42, 3, rules) + var replay: MatchReplay = MatchReplay.new(loop.recorder) + assert_eq(replay.flow.phase, Match.LOBBY) + assert_true(replay.run_until(func() -> bool: return replay.flow.in_match())) + assert_eq(replay.ticks, 30) + assert_eq(replay.sim.tick, 0) + assert_true(replay.run_to_end()) + assert_true(replay.verify()["ok"]) + + +func test_a_replay_can_stop_partway() -> void: + var loop: ServerLoop = _recorded(41, 5) + var again: ServerLoop = ServerLoop.new(41, 1, 5) + again.play_humans_by_script() + for _index: int in 400: + again.run_tick() + var replay: MatchReplay = MatchReplay.new(loop.recorder) + assert_true(replay.run_until(func() -> bool: return replay.sim.tick >= 400)) + assert_eq(replay.sim.tick, 400) + assert_eq(replay.sim.state_hash(), again.sim.state_hash(), "the replay passes through the same states") + + +func test_different_commands_give_a_different_match() -> void: + var loop: ServerLoop = _recorded(41, 5) + var silent: CommandLog = CommandLog.new(41, 1, loop.recorder.rules) + silent.final_tick = loop.recorder.final_tick + silent.final_hash = loop.recorder.final_hash + silent.winners = loop.recorder.winners + var replay: MatchReplay = MatchReplay.new(silent) + replay.run_to_end() + assert_false(replay.verify()["ok"], "nobody moving isn't the same match") + + +func test_bots_leave_the_simulations_random_streams_alone() -> void: + # A bot is a player: thinking must not change the simulation, or a replay with no + # bots thinking could never reach the same state. + var loop: ServerLoop = ServerLoop.new(9, 0, 8) + for _index: int in 900: + loop.run_tick() + assert_false(loop.sim.rng.stream_names().has("bots")) + + +func test_only_the_first_match_is_recorded() -> void: + var rules: MatchRules = ServerLoop.immediate_rules(0, 3) + rules.results_ticks = 2 + var loop: ServerLoop = ServerLoop.new(5, 0, 3, rules) + var commands: CommandLog = loop.record_commands() + for bot: BotBrain in loop.bots.slice(1): + loop.sim.entities.find(bot.player_id).health = 0 + loop.run_tick() + assert_false(commands.final_hash.is_empty()) + var count: int = commands.count() + for _index: int in 30: + loop.run_tick() + assert_eq(loop.match_flow.matches_started, 2) + assert_eq(commands.count(), count, "the second match isn't added to the log") diff --git a/test/server/test_match_replay.gd.uid b/test/server/test_match_replay.gd.uid new file mode 100644 index 0000000..eba35dc --- /dev/null +++ b/test/server/test_match_replay.gd.uid @@ -0,0 +1 @@ +uid://dt28p01xtfa12 diff --git a/tools/match.gd b/tools/match.gd new file mode 100644 index 0000000..0719580 --- /dev/null +++ b/tools/match.gd @@ -0,0 +1,129 @@ +## Plays one whole offline match, from the lobby to the results and back to the lobby: +## one scripted player and bots on a local server. Then saves the command log, reads it +## back, replays it with nobody thinking and checks the replay ends in the same state. +## +## tools/godot.sh --script res://tools/match.gd -- [--seed=N] [--bots=23] +## [--out=res://build/match/match.tclog] +## +## Prints one JSON object per line. Exits 1 on any script or engine error, if the match +## doesn't finish with a winner, or if the replay differs. +extends SceneTree + + +func _init() -> void: + var seed_value: int = 20261112 + var bots: int = Tuning.SOLO_PLAYERS - 1 + var out: String = "res://build/match/match.tclog" + for arg: String in OS.get_cmdline_user_args(): + if arg.begins_with("--seed=") and arg.trim_prefix("--seed=").is_valid_int(): + seed_value = arg.trim_prefix("--seed=").to_int() + elif arg.begins_with("--bots=") and arg.trim_prefix("--bots=").is_valid_int(): + bots = clampi(arg.trim_prefix("--bots=").to_int(), 1, Tuning.SOLO_PLAYERS - 1) + elif arg.begins_with("--out="): + out = arg.trim_prefix("--out=") + else: + print("match FAIL: unknown argument '%s'" % arg) + quit(2) + return + var errors: ErrorCounter = ErrorCounter.new() + OS.add_logger(errors) + var problems: Array[String] = _play(seed_value, bots, out) + OS.remove_logger(errors) + if errors.count() > 0: + problems.append("%d script or engine errors, first: %s" % [errors.count(), errors.first()]) + for problem: String in problems: + print("match FAIL: %s" % problem) + if problems.is_empty(): + print("match: ok (lobby to results with no errors; the saved command log replays to the same state)") + quit(0 if problems.is_empty() else 1) + + +func _play(seed_value: int, bots: int, out: String) -> Array[String]: + var problems: Array[String] = [] + var rules: MatchRules = MatchRules.new() + rules.max_players = 1 + bots + rules.min_players = 1 + var loop: ServerLoop = ServerLoop.new(seed_value, 1, bots, rules) + loop.play_humans_by_script() + var commands: CommandLog = loop.record_commands() + commands.notes["bots"] = bots + var flow: Match = loop.match_flow + _log("start", seed_value, {"players": 1, "bots": bots, "phase": flow.phase_name(), "engine": Engine.get_version_info()["string"]}) + + var limit: int = rules.lobby_ticks + rules.countdown_ticks + rules.results_ticks + BotBatch.tick_limit() + var summary: Array[Dictionary] = [] + var phases: Array[String] = [flow.phase_name()] + var player: ScriptedPlayer = null + var player_step: String = "" + var landed: bool = false + var back_in_lobby: bool = false + var sim: Simulation = loop.sim + while loop.ticks < limit and not back_in_lobby: + loop.run_tick() + for event: Dictionary in flow.events: + match event["type"]: + "phase": + phases.append(event["to"]) + _log("phase", seed_value, {"tick": loop.ticks, "from": event["from"], "to": event["to"]}) + back_in_lobby = event["from"] == "results" + "match_started": + player = loop.scripted[0] if not loop.scripted.is_empty() else null + sim = loop.sim + "placed": + if event["handle"] == 1: + _log("player_out", seed_value, {"sim_tick": event["tick"], "place": event["place"], "cause": event["cause"], "by": event["by"]}) + "match_ended": + summary = flow.summary() + _log("ended", seed_value, {"sim_tick": sim.tick, "winners": event["winners"], "timed_out": event["timed_out"]}) + if player != null and flow.in_match(): + var me: SimEntity = sim.entities.find(player.player_id) + if me != null and not landed and me.drop_state == Drop.NONE: + landed = true + _log("player_landed", seed_value, {"sim_tick": sim.tick, "at": [snappedf(me.position.x, 0.1), snappedf(me.position.y, 0.1), snappedf(me.position.z, 0.1)]}) + if player.step_name() != player_step: + player_step = player.step_name() + _log("player_script", seed_value, {"sim_tick": sim.tick, "step": player_step, "harvested": player.harvested, "built": player.built}) + + if not back_in_lobby: + problems.append("the match didn't get back to the lobby in %d ticks (phases: %s)" % [limit, phases]) + for wanted: String in Match.PHASE_NAMES: + if not phases.has(wanted): + problems.append("the match never reached the %s phase" % wanted) + if commands.final_hash.is_empty(): + problems.append("the match never ended") + return problems + if commands.winners.is_empty(): + problems.append("the match ended with no winner") + for row: Dictionary in summary: + if row["place"] <= 3 or row["handle"] == 1: + _log("result", seed_value, row) + var stats: Dictionary = loop.timing_stats() + _log("timing", seed_value, stats) + if player != null: + _log("player", seed_value, {"harvested": player.harvested, "built": player.built, "script": player.step_name()}) + + var saved: Error = commands.save(out) + if saved != OK: + problems.append("couldn't save the command log to %s (error %d)" % [out, saved]) + return problems + var loaded: CommandLog = CommandLog.load_from(out) + if loaded == null: + problems.append("the saved command log at %s can't be read back" % out) + return problems + var replay: MatchReplay = MatchReplay.new(loaded) + replay.run_to_end() + var verdict: Dictionary = replay.verify() + verdict["records"] = loaded.count() + verdict["file"] = out + verdict["bytes"] = FileAccess.get_file_as_bytes(out).size() + _log("replay", seed_value, verdict) + if not verdict["ok"]: + problems.append("the replay ended at tick %d with hash %s, the match at tick %d with %s" % [ + verdict["tick"], verdict["hash"], verdict["expected_tick"], verdict["expected_hash"]]) + return problems + + +func _log(event: String, seed_value: int, fields: Dictionary) -> void: + var record: Dictionary = {"event": event, "seed": seed_value} + record.merge(fields, false) + print(JSON.stringify(record)) diff --git a/tools/match.gd.uid b/tools/match.gd.uid new file mode 100644 index 0000000..b5de777 --- /dev/null +++ b/tools/match.gd.uid @@ -0,0 +1 @@ +uid://w4tmw68id3hg diff --git a/tools/match.sh b/tools/match.sh new file mode 100755 index 0000000..c9c5666 --- /dev/null +++ b/tools/match.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Plays one whole offline match, lobby to results: one scripted player and 23 bots on +# a local server. Saves the command log to build/match/match.tclog, replays it and +# checks the replay ends in the same state. Prints one JSON line per event and the +# verdict. See tools/match.gd. +# +# tools/match.sh seed 2, where the scripted player also builds +# MATCH_SEED=7 tools/match.sh +set -uo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/.." + +seed="${MATCH_SEED:-2}" +[[ "$seed" =~ ^[0-9]+$ ]] || { echo "match FAIL: bad MATCH_SEED '$seed'"; exit 2; } +raw="$(timeout --signal=KILL 900 nice -n 15 tools/godot.sh --script res://tools/match.gd -- --seed="$seed" 2>&1)" +code=$? +grep -E '^\{|^match' <<<"$raw" +if [[ "$code" -ne 0 ]] && ! grep -q '^match' <<<"$raw"; then + echo "match FAIL: the run exited $code" + tail -n 15 <<<"$raw" +fi +exit "$code" diff --git a/tools/match_captures.sh b/tools/match_captures.sh new file mode 100755 index 0000000..cb67875 --- /dev/null +++ b/tools/match_captures.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Renders each stage of the match `make match` last played, from its command log, in +# the capture container: captures/match_.png. Needs Docker and +# build/match/match.tclog. Open the images and look at them. +set -uo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/.." + +if [[ ! -f build/match/match.tclog ]]; then + echo "match-captures FAIL: no build/match/match.tclog; run 'make match' first" + exit 1 +fi +status=0 +for stage in lobby barge glide landed built final tide results; do + if ! tools/capture.sh "match_$stage" "captures/match_$stage.png"; then + echo "match-captures FAIL: stage $stage" + status=1 + fi +done +[[ "$status" -eq 0 ]] && echo "match-captures: ok (8 stages in captures/match_*.png)" +exit "$status"