diff --git a/CLAUDE.md b/CLAUDE.md index 8cd853a..68bbe0a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -30,6 +30,9 @@ continuity. | `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. | +| `tools/godot.sh -- --connect=HOST:PORT --autoplay --client-seconds=N` | Runs the client headless against a server for N seconds, played by its script, and prints one JSON line saying how far it got. `--offline` plays a server in the same process instead. On a real display, with no options, the game starts an offline match; see `src/app/client_config.gd`. | +| `make client-check` | Starts a server and a client as two processes, joins them over loopback UDP and checks the client plays (about a minute, real time). | +| `make client-captures` | Renders what a network client sees on the barge, gliding and landed (`captures/client_.png`). Needs Docker. Look at them. | | `make capture-test` | Proves the capture harness works and rejects a blank frame. Needs Docker, so it isn't part of `make check`. | Run one group of tests with `tools/run_tests.sh --root=res://test/sim` or diff --git a/Makefile b/Makefile index f0b6fcb..8d26f08 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 match match-captures +.PHONY: check import parse test test-selfcheck smoke capture-test terrain-capture binaries verify-engine bot-matches match match-captures client-check client-captures ## Everything that must pass before a push. check: verify-engine binaries parse test test-selfcheck smoke @@ -46,6 +46,15 @@ match: import match-captures: import @tools/match_captures.sh +## Joins a real client process to a real server process over loopback UDP and checks +## it gets from the lobby into the match. About a minute, in real time. +client-check: import + @tools/client_check.sh + +## 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 + ## 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 0f78bf2..c236c14 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -408,8 +408,39 @@ weights from the island's elevation bands, with rock on steep ground. 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. +The figures, barge and items are stand-in shapes for the art pass to replace. + +In play, the simulation it reads is the client's own copy of the world: the +`Simulation` that `ClientGame` generates from the match's seed and never steps. +`ClientWorld` keeps its pieces, props, chests and tide in line with the server, and +`ClientMirror` (`src/net/`) writes the rest of the picture into it every frame: each +entity the server has told this client about, where it is being drawn now (everyone +else from the recent past, the client's own player where it was predicted), the barge, +the clock and the sea level. So the same views draw a networked match, a local +server's simulation in a test, or a replay in a capture, and there is one set of +drawing code. Captures and tests still point a `MatchView` straight at a server's +simulation. + +## The client program + +`ClientSession` (`src/app/`) is the game while it is in a match: a `ClientGame`, a +`ClientInput` turning the keyboard and mouse into one command a tick, a `ClientMirror` +and a `MatchView`. Its `pump()` does a frame's work and needs no scene tree, so tests +drive it. + +The server is either across the network (`--connect=HOST:PORT`, a `NetClient`) or in +the same process (`LocalServer`, `src/server/`): the same `ServerLoop` and `NetGame` a +dedicated server runs, with the packets handed across in memory, reliable ones first, +in the order a socket would deliver them. The client can't tell the difference, so +offline play is the network path with no network, as "Rules that do not bend" asks. + +`src/app/main.gd` picks the mode: `--server` runs the dedicated server; otherwise the +game starts an offline match, or joins a server with `--connect`. Without a window +(`tools/godot.sh` is always headless) a mode has to be asked for. `--autoplay` puts a +small script at the controls and `--client-seconds=N` quits after N seconds with one +JSON line saying how far the client got, which is what `make client-check` reads. +There are no menus yet (N6, A10) and no HUD (A9): one line of text says when the +client is connecting, in the lobby or watching. ## Performance budgets diff --git a/src/app/client_config.gd b/src/app/client_config.gd new file mode 100644 index 0000000..40f8d28 --- /dev/null +++ b/src/app/client_config.gd @@ -0,0 +1,74 @@ +## What the client was asked to do on the command line. +## +## tidewall an offline match against bots +## tidewall --connect=HOST[:PORT] join a server +## options: --name=NAME --seed=N --bots=N (offline) --autoplay +## --client-seconds=N quit after N seconds, saying what happened +## +## Menus replace most of this later. Under tools/godot.sh, which has no window, a mode +## has to be asked for: --offline or --connect. +class_name ClientConfig +extends RefCounted + +const DEFAULT_NAME: String = "Islander" +const DEFAULT_BOTS: int = Tuning.SOLO_PLAYERS - 1 + +## Empty to play offline. +var host: String = "" +var port: int = ServerConfig.DEFAULT_PORT +var player_name: String = DEFAULT_NAME +var match_seed: int = 0 +var has_seed: bool = false +var bots: int = DEFAULT_BOTS +var autoplay: bool = false +## Quit after this many seconds; 0 runs until the window is closed. +var seconds: float = 0.0 +## True when --offline or --connect was given. +var asked: bool = false +var errors: Array[String] = [] + + +static func parse(args: PackedStringArray) -> ClientConfig: + var config: ClientConfig = ClientConfig.new() + for arg: String in args: + var parts: PackedStringArray = arg.split("=", true, 1) + var value: String = parts[1] if parts.size() == 2 else "" + match parts[0]: + "--offline": + config.asked = true + "--autoplay": + config.autoplay = true + "--connect": + config.asked = true + var at: int = value.rfind(":") + config.host = value if at < 0 else value.substr(0, at) + if at >= 0: + var port_text: String = value.substr(at + 1) + config.port = port_text.to_int() if port_text.is_valid_int() else 0 + if config.host.is_empty(): + config.errors.append("--connect needs a host, as in --connect=192.0.2.7:%d" % ServerConfig.DEFAULT_PORT) + if config.port < 1 or config.port > 65535: + config.errors.append("the port in --connect must be between 1 and 65535") + "--name": + config.player_name = value + "--seed": + config.has_seed = value.is_valid_int() + config.match_seed = value.to_int() + if not config.has_seed: + config.errors.append("--seed must be a whole number, got '%s'" % value) + "--bots": + config.bots = value.to_int() + if not value.is_valid_int() or config.bots < 0 or config.bots > Tuning.SOLO_PLAYERS - 1: + config.errors.append("--bots must be between 0 and %d, got '%s'" % [Tuning.SOLO_PLAYERS - 1, value]) + "--client-seconds": + config.seconds = value.to_float() + if not value.is_valid_float() or config.seconds <= 0.0: + config.errors.append("--client-seconds must be a number above 0, got '%s'" % value) + _: + if arg.begins_with("--"): + config.errors.append("unknown option '%s'" % arg) + return config + + +func is_valid() -> bool: + return errors.is_empty() diff --git a/src/app/client_config.gd.uid b/src/app/client_config.gd.uid new file mode 100644 index 0000000..c7b83f4 --- /dev/null +++ b/src/app/client_config.gd.uid @@ -0,0 +1 @@ +uid://bkko3gtgadosa diff --git a/src/app/client_session.gd b/src/app/client_session.gd new file mode 100644 index 0000000..e661f7f --- /dev/null +++ b/src/app/client_session.gd @@ -0,0 +1,146 @@ +## The client program while it is in a game: a ClientGame fed by a server (one across +## the network, or a LocalServer in this process when playing offline), the keyboard +## and mouse turned into its commands, and a MatchView drawing the client's world as +## ClientMirror fills it in. +## +## pump() does a frame's work and needs no scene tree, so tests drive it directly. +class_name ClientSession +extends Node3D + +var game: ClientGame = ClientGame.new() +var mirror: ClientMirror = ClientMirror.new() +var input: ClientInput = ClientInput.new() +## The connection, when playing on a server across the network. +var link: NetClient = null +## The server in this process, when playing offline. +var local: LocalServer = null +## The picture of the current match's world, or null before there is one. +var view: MatchView = 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. +var frames_playing: int = 0 +var frames: int = 0 + +var _viewed: Simulation = null +var _status: Label = null + + +func _init() -> void: + game.sample_input = _sample + + +## Starts joining the server at `host`. Returns an error if the socket can't be made. +func connect_to(host: String, port: int, player_name: String) -> Error: + link = NetClient.new() + game.attach(link) + return link.connect_to(host, port, player_name) + + +## Starts an offline match of this player and `bots` bots on a server in this process. +func play_offline(match_seed: int, bots: int, rules: MatchRules = null) -> void: + local = LocalServer.new(match_seed, bots, rules) + + +## Leaves the server, if there is one across the network. +func leave() -> void: + if link != null: + link.leave() + + +## One line saying where things stand, for the corner of the screen and the log. +func status_text() -> String: + if link != null and link.state != NetClient.JOINED: + return link.status_text() + if game.world == null: + return "Waiting for the server" + var phase: String = Match.PHASE_NAMES[game.match_phase] + if game.match_phase == Match.LOBBY or game.match_phase == Match.COUNTDOWN: + return "In the %s" % phase + if game.playing(): + return "" + return "Watching" if game.match_phase != Match.RESULTS else "The match is over" + + +## One frame: packets in, commands out, and the picture brought up to date. +func pump(delta: float) -> void: + frames += 1 + input.poll() + if link != null: + game.poll() + if local != null: + local.advance(delta, game) + game.advance(delta) + if game.world != null and (phases.is_empty() or phases[phases.size() - 1] != game.match_phase): + phases.append(game.match_phase) + if game.playing(): + frames_playing += 1 + mirror.sync(game) + _show(delta) + + +func _ready() -> void: + _status = Label.new() + _status.position = Vector2(24.0, 20.0) + _status.add_theme_font_size_override("font_size", 22) + _status.add_theme_color_override("font_outline_color", Color(0.08, 0.08, 0.08)) + _status.add_theme_constant_override("outline_size", 6) + add_child(_status) + if DisplayServer.get_name() != "headless" and not input.autoplay: + Input.mouse_mode = Input.MOUSE_MODE_CAPTURED + + +func _process(delta: float) -> void: + pump(delta) + if _status != null: + _status.text = status_text() + + +func _unhandled_input(event: InputEvent) -> void: + var captured: bool = Input.mouse_mode == Input.MOUSE_MODE_CAPTURED + var key: InputEventKey = event as InputEventKey + var click: InputEventMouseButton = event as InputEventMouseButton + if key != null and key.pressed and key.physical_keycode == KEY_ESCAPE: + # Escape lets go of the mouse; a click takes it back. + Input.mouse_mode = Input.MOUSE_MODE_VISIBLE + elif click != null and click.pressed and not captured and not input.autoplay: + Input.mouse_mode = Input.MOUSE_MODE_CAPTURED + else: + input.handle(event, captured) + + +func _exit_tree() -> void: + leave() + + +func _sample(tick: int) -> PlayerCommand: + if input.autoplay and game.world != null: + return input.autoplay_command(tick, game.prediction.player, game.world.ground) + return input.command(tick) + + +## Draws the client's world: a new MatchView whenever there is a new world, and the +## camera on the watched player's shoulder, or over the island when there is nobody. +func _show(delta: float) -> void: + if game.world != _viewed: + _viewed = game.world + if view != null: + remove_child(view) + view.queue_free() + view = null + if _viewed != null: + view = MatchView.new() + view.setup(_viewed, 0) + add_child(view) + move_child(view, 0) + 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() + 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() diff --git a/src/app/client_session.gd.uid b/src/app/client_session.gd.uid new file mode 100644 index 0000000..f840027 --- /dev/null +++ b/src/app/client_session.gd.uid @@ -0,0 +1 @@ +uid://c8vm3i2nd55jh diff --git a/src/app/main.gd b/src/app/main.gd index 6ee3c1d..b60e5aa 100644 --- a/src/app/main.gd +++ b/src/app/main.gd @@ -1,18 +1,70 @@ ## Application entry point. Picks the mode from the command line: ## ## tools/godot.sh -- --server [options] headless dedicated server (see ServerConfig) +## tidewall [options] the game: an offline match, or +## tidewall --connect=HOST[:PORT] a match on a server (see ClientConfig) ## -## Client startup is added by later milestones. +## Without a window (tools/godot.sh is always headless) the game only starts when +## --offline or --connect asks for it, so a bare run prints a line and stops. extends Node +var _config: ClientConfig +var _session: ClientSession +var _left: float = 0.0 + func _ready() -> void: var args: PackedStringArray = OS.get_cmdline_user_args() if not args.has("--server"): # Also accept --server before the "--" separator. - args = OS.get_cmdline_args() + var all: PackedStringArray = OS.get_cmdline_args() + if all.has("--server"): + args = all var config: ServerConfig = ServerConfig.parse(args) if config.server: add_child(HeadlessServer.new(config)) return - print("Tidewall") + _config = ClientConfig.parse(args) + if not _config.is_valid(): + for problem: String in _config.errors: + printerr("tidewall: " + problem) + get_tree().quit(2) + return + if DisplayServer.get_name() == "headless" and not _config.asked: + print("Tidewall") + return + _session = ClientSession.new() + _session.input.autoplay = _config.autoplay + if _config.host.is_empty(): + var match_seed: int = _config.match_seed if _config.has_seed else int(Time.get_unix_time_from_system() * 1000.0) & 0x7FFFFFFF + _session.play_offline(match_seed, _config.bots) + else: + var error: Error = _session.connect_to(_config.host, _config.port, _config.player_name) + if error != OK: + printerr("tidewall: couldn't open a connection: %s" % error_string(error)) + get_tree().quit(1) + return + add_child(_session) + _left = _config.seconds + + +func _process(delta: float) -> void: + if _session == null or _config.seconds <= 0.0: + return + _left -= delta + if _left > 0.0: + return + # A timed run says what happened, for scripts: one JSON line. + var phases: Array[String] = [] + for phase: int in _session.phases: + phases.append(Match.PHASE_NAMES[phase]) + var joined: bool = _session.local != null or _session.link.state == NetClient.JOINED + print(JSON.stringify({ + "event": "client", "joined": joined, "status": _session.status_text(), "phases": phases, + "frames": _session.frames, "frames_playing": _session.frames_playing, + "world_messages": _session.game.replica.applied, "bad_packets": _session.game.bad_packets, + "corrections": _session.game.prediction.mispredictions, + })) + _session.leave() + _session = null + get_tree().quit(0 if joined else 1) diff --git a/src/client/client_input.gd b/src/client/client_input.gd new file mode 100644 index 0000000..760e819 --- /dev/null +++ b/src/client/client_input.gd @@ -0,0 +1,131 @@ +## Turns the keyboard and mouse into the local player's commands, one per tick. +## +## Keys (physical positions, so they sit the same on any layout): +## W A S D move · Space jump · Ctrl crouch · Shift sprint · left mouse use or fire · +## right mouse aim · R reload · E pick up or open · G drop the held item · +## 1 the boathook, 2 to 6 the five slots · B build mode on and off · +## in build mode 1 to 5 pick wall, floor, ramp, roof or breakwater, Tab the material, +## and left mouse places. +## Rebinding and gamepads come with the settings menu. +## +## With `autoplay` on, a simple script plays instead: it leaps from the barge over +## land, glides, and walks about. That is for tests and for checking a connection with +## nobody at the keyboard. +class_name ClientInput +extends RefCounted + +var settings: InputSettings = InputSettings.new() +## The look direction, in radians, in the simulation's convention. +var yaw: float = 0.0 +var pitch: float = 0.0 +## What is held down now: Vector2(strafe right, forward) and PlayerCommand.BUTTON_ bits. +var move: Vector2 = Vector2.ZERO +var buttons: int = 0 +## The held selection outside build mode: 0 the boathook, 1 to 5 a slot. +var slot: int = 0 +var build_mode: bool = false +## The piece kind and material placed in build mode. +var build_kind: int = StructureSet.WALL +var material: int = Materials.DRIFTWOOD +var autoplay: bool = false + + +func aiming() -> bool: + return buttons & PlayerCommand.BUTTON_AIM != 0 and not build_mode + + +## Reads what is held down from the keyboard and mouse. Call once a frame. +func poll() -> void: + if autoplay: + return + move = Vector2( + _axis(KEY_D, KEY_A), + _axis(KEY_W, KEY_S), + ) + buttons = 0 + var keys: Dictionary = { + KEY_SPACE: PlayerCommand.BUTTON_JUMP, KEY_CTRL: PlayerCommand.BUTTON_CROUCH, + KEY_SHIFT: PlayerCommand.BUTTON_SPRINT, KEY_R: PlayerCommand.BUTTON_RELOAD, + KEY_E: PlayerCommand.BUTTON_INTERACT, KEY_G: PlayerCommand.BUTTON_DROP, + } + for key: Key in keys: + if Input.is_physical_key_pressed(key): + buttons |= int(keys[key]) + if Input.is_mouse_button_pressed(MOUSE_BUTTON_LEFT): + buttons |= PlayerCommand.BUTTON_FIRE + if Input.is_mouse_button_pressed(MOUSE_BUTTON_RIGHT): + buttons |= PlayerCommand.BUTTON_AIM + + +## Takes one input event: mouse motion turns the look, and keys that act once per +## press do. `captured` says whether the mouse belongs to the game just now. +func handle(event: InputEvent, captured: bool) -> void: + if autoplay: + return + var motion: InputEventMouseMotion = event as InputEventMouseMotion + if motion != null and captured: + turn(motion.relative) + return + var key: InputEventKey = event as InputEventKey + if key != null and key.pressed and not key.echo: + press(key.physical_keycode) + + +## Turns the look by a mouse motion, in pixels. +func turn(relative: Vector2) -> void: + var look: Vector2 = settings.apply_mouse(relative, yaw, pitch, aiming()) + yaw = look.x + pitch = look.y + + +## A key that acts once per press: the number row, build mode and the material. +func press(keycode: Key) -> void: + if keycode == KEY_B: + build_mode = not build_mode + elif keycode == KEY_TAB and build_mode: + material = (material + 1) % Materials.NAMES.size() + elif keycode >= KEY_1 and keycode <= KEY_9: + var number: int = keycode - KEY_1 + if build_mode: + if number < StructureSet.KINDS.size(): + build_kind = number + elif number <= Inventory.slot_count(): + slot = number + + +## The command for `tick`, from what is held now. +func command(tick: int) -> PlayerCommand: + var pressed: int = buttons + var selection: int = slot + if build_mode: + pressed |= PlayerCommand.BUTTON_BUILD + selection = build_kind + return PlayerCommand.from_input(tick, move, yaw, pitch, pressed, selection, material) + + +## The script's command for `tick`: `me` is the client's copy of its own player and +## `ground` the island under it. +func autoplay_command(tick: int, me: SimEntity, ground: SimGround) -> PlayerCommand: + var centre: float = Tuning.WORLD_SIZE_METRES * 0.5 + yaw = atan2(centre - me.position.x, centre - me.position.z) + pitch = deg_to_rad(-12.0) + move = Vector2.ZERO + buttons = 0 + if me.drop_state == Drop.ABOARD: + # Over dry land, with a moment to look about first. + if tick > 3 * Tuning.TICK_RATE_HZ and ground.terrain_height(me.position.x, me.position.z) > Tuning.ISLAND_BEACH_TOP + 2.0: + buttons = PlayerCommand.BUTTON_JUMP + elif me.drop_state != Drop.NONE: + move = Vector2(0.0, 1.0) + else: + # Walk a slow circle about the middle of the island, with a hop now and then. + var seconds: float = float(tick) / Tuning.TICK_RATE_HZ + yaw += sin(seconds * 0.4) * 1.2 + move = Vector2(0.0, 1.0) if fmod(seconds, 9.0) < 6.0 else Vector2.ZERO + if tick % (4 * Tuning.TICK_RATE_HZ) == 0: + buttons = PlayerCommand.BUTTON_JUMP + return command(tick) + + +func _axis(positive: Key, negative: Key) -> float: + return (1.0 if Input.is_physical_key_pressed(positive) else 0.0) - (1.0 if Input.is_physical_key_pressed(negative) else 0.0) diff --git a/src/client/client_input.gd.uid b/src/client/client_input.gd.uid new file mode 100644 index 0000000..78956d2 --- /dev/null +++ b/src/client/client_input.gd.uid @@ -0,0 +1 @@ +uid://x752jdh6pmnn diff --git a/src/client/entities/entity_view.gd b/src/client/entities/entity_view.gd index e925794..3349e22 100644 --- a/src/client/entities/entity_view.gd +++ b/src/client/entities/entity_view.gd @@ -25,6 +25,9 @@ const DECK_ROWS: int = 4 ## The entity drawn in the brightest oilskin, or 0. var local_id: int = 0 +## Where to draw the barge, when its owner knows better than the simulation's tick: a +## network client, which draws between ticks. Vector3.INF leaves it to the tick. +var barge_at: Vector3 = Vector3.INF var _sim: Simulation ## Entity ID -> the figure's root node. @@ -70,7 +73,7 @@ func sync() -> void: heading = atan2(along.x, along.z) _barge.visible = crossing if crossing: - _barge.position = drop.barge_position(_sim.tick) + _barge.position = barge_at if barge_at != Vector3.INF else drop.barge_position(_sim.tick) _barge.rotation.y = heading var seen: Dictionary = {} diff --git a/src/client/match_view.gd b/src/client/match_view.gd index 6a6f527..757160a 100644 --- a/src/client/match_view.gd +++ b/src/client/match_view.gd @@ -2,8 +2,9 @@ ## 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. +## A match gets a new Simulation, so it gets a new MatchView. In play the simulation is +## the client's own copy of the world, which ClientMirror fills with what the server +## has sent; captures and tests also point it at a server's or a replay's. class_name MatchView extends Node3D @@ -86,14 +87,21 @@ func sync() -> void: ## 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: +## their own pitch when given, in radians, for views such as looking down from a glide, +## and `look_yaw` their yaw, for the local player, whose look is newer than any command. +func follow(entity_id: int, pitch: float = NAN, look_yaw: 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 yaw: float = look_yaw if not is_nan(look_yaw) else 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) + # Where the figure is drawn: on the barge's deck that is its own place, not the + # one point the simulation carries every passenger at. + var feet: Vector3 = player.position + var figure: Node3D = entities.figure_of(entity_id) + if figure != null and player.drop_state == Drop.ABOARD: + feet = figure.position + camera.transform = rig.solve(feet, yaw, look_pitch, player.crouching, sim.ground) camera.fov = rig.fov() _focus() return true diff --git a/src/net/client_mirror.gd b/src/net/client_mirror.gd new file mode 100644 index 0000000..70d75c3 --- /dev/null +++ b/src/net/client_mirror.gd @@ -0,0 +1,132 @@ +## Writes what a ClientGame is showing into the client's own copy of the world, so +## that everything which draws a Simulation draws a networked match the same way. +## +## The client's world is a Simulation that is never stepped. ClientWorld keeps its +## pieces, props, chests and tide in line with the server. This adds the rest of the +## picture, afresh every frame: every entity the server has told this client about, +## where it is being drawn now (everyone else from the recent past, the client's own +## player where it was predicted), the barge, the clock and the sea level. Nothing +## here is authoritative, and nothing reads it back but views and the client's own +## check before placing a piece. +class_name ClientMirror +extends RefCounted + +## The entity the camera belongs on: the client's own player, or whoever it is +## spectating. 0 outside a match. +var watched_id: int = 0 +## The client's own player while it is in the match, or 0. +var own_id: int = 0 +## Where the barge is being drawn, or Vector3.INF when it isn't crossing. +var barge_at: Vector3 = Vector3.INF +## The moment being drawn, in simulation ticks. +var time: float = 0.0 + +var _drop: Drop = null +var _drop_world: Simulation = null + + +func sync(game: ClientGame) -> void: + var world: Simulation = game.world + watched_id = 0 + own_id = 0 + barge_at = Vector3.INF + if world == null: + return + var receiver: SnapshotReceiver = game.receiver + var playing: bool = game.playing() + var in_match: bool = receiver.own_id != 0 and game.remote.started + if playing: + # The own player is drawn part way through the newest predicted tick. + time = float(game.prediction.next_tick - 1) + game.clock.fraction() + elif in_match: + time = game.remote.time + else: + 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 + + if in_match: + if _drop == null or _drop_world != world: + # The route comes from the seed alone, as the server's does. + _drop = Drop.plan(world.ground, SimRng.new(game.world_seed), 0) + _drop_world = world + _drop.finished = _drop.is_over(world.tick) + world.drop = _drop + if not _drop.finished: + barge_at = _drop.barge_position(world.tick).lerp(_drop.barge_position(world.tick + 1), time - floorf(time)) + else: + world.drop = null + + var seen: Dictionary = {} + var pickups: Array[int] = [] + var projectiles: Array[int] = [] + if in_match: + for entity_id: int in receiver.entities: + var record: PackedInt32Array = receiver.entities[entity_id] + var shown: Dictionary = game.remote.sample(entity_id) + if shown.is_empty(): + continue + var archetype: int = record[NetSnapshot.R_ARCHETYPE] + var entity: SimEntity = world.entities.find(entity_id) + if entity == null: + entity = world.entities.restore(entity_id, archetype) + elif entity.archetype != archetype: + continue + seen[entity_id] = true + entity.position = shown["position"] + match archetype: + SimEntity.ARCHETYPE_PLAYER: + _show_player(entity, record, shown) + SimEntity.ARCHETYPE_PICKUP: + entity.item = record[NetSnapshot.R_ITEM] - 1 + entity.item_count = record[NetSnapshot.R_COUNT] + entity.item_tier = record[NetSnapshot.R_TIER] + pickups.append(entity_id) + SimEntity.ARCHETYPE_PROJECTILE: + entity.item = record[NetSnapshot.R_ITEM] - 1 + entity.owner_id = record[NetSnapshot.R_OWNER] + projectiles.append(entity_id) + if seen.has(receiver.own_id): + watched_id = receiver.own_id + if playing and seen.has(receiver.own_id): + own_id = receiver.own_id + _show_own(world.entities.find(own_id), game) + for entity: SimEntity in world.entities.entities(): + if not seen.has(entity.id): + world.entities.remove(entity.id) + pickups.sort() + projectiles.sort() + world.pickups = pickups + world.projectiles = projectiles + + +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) + entity.pitch = clampi(roundi(float(shown["pitch"]) / (PI * 0.5) * PlayerCommand.PITCH_MAX), -PlayerCommand.PITCH_MAX, PlayerCommand.PITCH_MAX) + entity.health = record[NetSnapshot.R_HEALTH] + entity.armor = record[NetSnapshot.R_ARMOR] + entity.on_ground = flags & NetSnapshot.FLAG_ON_GROUND != 0 + entity.crouching = flags & NetSnapshot.FLAG_CROUCHING != 0 + entity.swimming = flags & NetSnapshot.FLAG_SWIMMING != 0 + entity.eliminated = flags & NetSnapshot.FLAG_ELIMINATED != 0 + entity.drop_state = (flags >> NetSnapshot.FLAG_DROP_SHIFT) & 3 + # What is in the player's hands, for whoever draws it: the item's code, or -1. + entity.item = record[NetSnapshot.R_HELD] - 1 + if entity.drop_state == Drop.ABOARD and barge_at != Vector3.INF: + entity.position = barge_at + + +## The client's own player: where and how it was predicted, not where the server last +## had it. +func _show_own(entity: SimEntity, game: ClientGame) -> void: + var me: SimEntity = game.prediction.player + entity.position = game.own_position() + entity.yaw = me.yaw + entity.pitch = me.pitch + entity.on_ground = me.on_ground + entity.crouching = me.crouching + entity.swimming = me.swimming + entity.drop_state = me.drop_state + if me.drop_state == Drop.ABOARD and barge_at != Vector3.INF: + entity.position = barge_at diff --git a/src/net/client_mirror.gd.uid b/src/net/client_mirror.gd.uid new file mode 100644 index 0000000..9d782f5 --- /dev/null +++ b/src/net/client_mirror.gd.uid @@ -0,0 +1 @@ +uid://bfhscfjoig3tb diff --git a/src/server/local_server.gd b/src/server/local_server.gd new file mode 100644 index 0000000..7054a69 --- /dev/null +++ b/src/server/local_server.gd @@ -0,0 +1,64 @@ +## A whole server inside the client program, for playing offline. It is the same +## ServerLoop and NetGame a dedicated server runs, and the client talks to it with the +## same packets through the same ClientGame; they are handed across in memory instead +## of sent over a socket. So offline play and network play are one code path. +class_name LocalServer +extends RefCounted + +## The one person's handle. +const HANDLE: int = 1 +## If a frame takes long, at most this many ticks are run to catch up. +const MAX_TICKS_PER_FRAME: int = 4 + +var loop: ServerLoop +var game: NetGame + +var _accumulator: float = 0.0 +var _greeted: bool = false + + +## A match of one person and `bots` bots. With `rules` null it starts at once, and a +## new one starts after each one's results. +func _init(match_seed: int, bots: int, rules: MatchRules = null) -> void: + loop = ServerLoop.new(match_seed, 1, bots, rules) + game = NetGame.new(loop, NetServer.new()) + game.adopt(HANDLE) + + +## Runs the server for `delta` seconds of real time, carrying packets both ways. +func advance(delta: float, client: ClientGame) -> void: + _greet(client) + _accumulator += delta + var due: int = mini(floori(_accumulator * Tuning.TICK_RATE_HZ), MAX_TICKS_PER_FRAME) + _accumulator = minf(_accumulator - float(due) / Tuning.TICK_RATE_HZ, 1.0 / Tuning.TICK_RATE_HZ) + for _index: int in due: + tick(client) + + +## One server tick: the client's packets go in, and everything the server has for it +## comes out, reliable messages first, in the order a socket would deliver them. +func tick(client: ClientGame) -> void: + _greet(client) + for bytes: PackedByteArray in client.outbox: + game.take_input(HANDLE, bytes) + client.outbox.clear() + loop.run_tick() + game.after_tick() + 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.own_changes.has(HANDLE): + client.receive(NetProtocol.CHANNEL_CONTROL, game.own_changes[HANDLE]) + if game.snapshot_due(): + client.receive(NetProtocol.CHANNEL_STATE, game.snapshot_for(HANDLE)) + + +## What someone is sent on joining: the match notice, then the whole world. +func _greet(client: ClientGame) -> void: + if _greeted: + return + _greeted = true + client.receive(NetProtocol.CHANNEL_CONTROL, game.match_notice()) + client.receive(NetProtocol.CHANNEL_CONTROL, game.world_notice()) diff --git a/src/server/local_server.gd.uid b/src/server/local_server.gd.uid new file mode 100644 index 0000000..7d0a04c --- /dev/null +++ b/src/server/local_server.gd.uid @@ -0,0 +1 @@ +uid://do7rh3lofmurm diff --git a/src/sim/entity_registry.gd b/src/sim/entity_registry.gd index 4d8a240..a68c8a9 100644 --- a/src/sim/entity_registry.gd +++ b/src/sim/entity_registry.gd @@ -18,6 +18,23 @@ func create(archetype: int) -> SimEntity: return entity +## Creates an entity under an ID chosen elsewhere: a network client's copy of one the +## server made. Iteration stays in ascending ID order. +func restore(id: int, archetype: int) -> SimEntity: + var entity: SimEntity = SimEntity.new(id, archetype) + var newest: bool = id >= _next_id + _by_id[id] = entity + _next_id = maxi(_next_id, id + 1) + if not newest: + var ids: Array = _by_id.keys() + ids.sort() + var sorted: Dictionary = {} + for key: int in ids: + sorted[key] = _by_id[key] + _by_id = sorted + return entity + + ## Returns the entity, or null if it doesn't exist or has been removed. func find(id: int) -> SimEntity: return _by_id.get(id) diff --git a/test/capture/client_barge.tscn b/test/capture/client_barge.tscn new file mode 100644 index 0000000..3ed9dc7 --- /dev/null +++ b/test/capture/client_barge.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 = "barge" diff --git a/test/capture/client_glide.tscn b/test/capture/client_glide.tscn new file mode 100644 index 0000000..572fc36 --- /dev/null +++ b/test/capture/client_glide.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 = "glide" diff --git a/test/capture/client_landed.tscn b/test/capture/client_landed.tscn new file mode 100644 index 0000000..35cd3b3 --- /dev/null +++ b/test/capture/client_landed.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 = "landed" diff --git a/test/capture/client_scene.gd b/test/capture/client_scene.gd new file mode 100644 index 0000000..4b914c1 --- /dev/null +++ b/test/capture/client_scene.gd @@ -0,0 +1,104 @@ +## Capture scenario for the network client (issue N10): a headless server listening +## on loopback UDP in this process, and the real ClientSession connected to it, played +## 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. +extends Node3D + +const DT: float = 1.0 / Tuning.TICK_RATE_HZ +const HOST: String = "127.0.0.1" +const LIMIT_ROUNDS: int = 200 * Tuning.TICK_RATE_HZ + +@export var stage: String = "barge" +@export var match_seed: int = 2 +@export var bots: int = 23 + +var _loop: ServerLoop +var _net: NetServer +var _game: NetGame +var _session: ClientSession + + +func _ready() -> void: + var rules: MatchRules = MatchRules.new() + rules.max_players = bots + 1 + rules.lobby_ticks = 6 + rules.countdown_ticks = 6 + _loop = ServerLoop.new(match_seed, 0, bots, rules) + _net = NetServer.new() + if _net.listen(0, HOST) != OK: + push_error("client capture: the server couldn't listen on loopback") + return + _game = NetGame.new(_loop, _net) + _session = ClientSession.new() + _session.input.autoplay = true + if _session.connect_to(HOST, _net.port(), "Mara") != OK: + push_error("client capture: the client couldn't open a connection") + return + add_child(_session) + # The picture is of one moment, so the session isn't left running behind it. + _session.set_process(false) + var me: SimEntity = _session.game.prediction.player + var since: int = -1 + for _round: int in LIMIT_ROUNDS: + _game.poll() + _loop.run_tick() + _game.after_tick() + _session.pump(DT) + var reached: bool = false + if _session.game.playing(): + match stage: + "barge": + 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": + reached = me.drop_state == Drop.NONE + if reached and since < 0: + since = 0 + elif since >= 0: + since += 1 + if since >= (2 * Tuning.TICK_RATE_HZ if stage != "barge" else 1): + break + if since < 0: + push_error("client capture: never reached stage '%s'" % stage) + return + _session.view.settle() + var others: int = 0 + var camera: Camera3D = _session.view.camera + for entity: SimEntity in _session.game.world.entities.entities(): + if entity.archetype != SimEntity.ARCHETYPE_PLAYER or entity.id == _session.mirror.own_id or entity.eliminated: + continue + var figure: Node3D = _session.view.entities.figure_of(entity.id) + var to: Vector3 = (figure.position if figure != null else entity.position) + Vector3(0.0, 1.0, 0.0) - camera.position + if to.length() < 150.0 and to.normalized().dot(-camera.basis.z) > 0.8: + others += 1 + var flow: Match = _loop.match_flow + _caption("NETWORK CLIENT · %s · %s · seed %d\njoined %s over UDP as \"%s\" · %d players drawn, %d others ahead of the camera\nsimulation tick %d on the server, %d predicted here · %d snapshots, %d world messages, %d corrections" % [ + 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, + ]) + + +func _exit_tree() -> void: + if _session != null: + _session.leave() + if _net != null: + _net.close() + + +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/client_scene.gd.uid b/test/capture/client_scene.gd.uid new file mode 100644 index 0000000..23f2114 --- /dev/null +++ b/test/capture/client_scene.gd.uid @@ -0,0 +1 @@ +uid://nuibatv3oksp diff --git a/test/client/test_client_session.gd b/test/client/test_client_session.gd new file mode 100644 index 0000000..450ad43 --- /dev/null +++ b/test/client/test_client_session.gd @@ -0,0 +1,228 @@ +extends TestCase + +## Issue N10: the client program's session. Offline it plays against a server in the +## same process; on the network, against a real server over loopback UDP. Both go +## through the same ClientGame, and the same MatchView draws the client's own copy of +## the world. + +const HOST: String = "127.0.0.1" +const DT: float = 1.0 / Tuning.TICK_RATE_HZ +const FRAME: float = 1.0 / 60.0 + +var session: ClientSession +var net: NetServer + + +func before_each() -> void: + session = ClientSession.new() + session.input.autoplay = true + net = null + + +func after_each() -> void: + session.leave() + session.free() + if net != null: + net.close() + + +func _own() -> SimEntity: + return session.game.prediction.player + + +func _agrees(sim: Simulation, message: String) -> void: + session.game.replica.sync(sim.tick) + assert_eq(NetWorld.world_hash(session.game.world), NetWorld.world_hash(sim), message) + + +func test_offline_play_goes_through_the_same_client_against_a_local_server() -> void: + session.play_offline(2, 3) + assert_null(session.link) + assert_null(session.game.net, "no socket: the packets are handed across") + var server: ServerLoop = session.local.loop + var seen_barge: bool = false + var most_figures: int = 0 + var landed_frame: int = -1 + for frame: int in 60 * 150: + session.pump(FRAME) + if session.view != null: + most_figures = maxi(most_figures, session.view.entities.figure_count()) + if session.view.entities.barge().visible and session.mirror.own_id != 0: + if not seen_barge: + seen_barge = true + var figure: Node3D = session.view.entities.figure_of(session.mirror.own_id) + assert_not_null(figure, "the client's own player is drawn") + assert_true(figure.position.distance_to(session.view.entities.barge().position) < 6.0, "on the barge's deck") + assert_true(session.view.camera.position.distance_to(figure.position) < 9.0, "the camera is on its shoulder") + if landed_frame < 0 and session.game.playing() and _own().drop_state == Drop.NONE: + landed_frame = frame + if landed_frame >= 0 and frame > landed_frame + 60 * 8: + break + assert_true(seen_barge) + assert_true(landed_frame > 0, "the scripted player leapt and came down") + assert_eq(session.phases[0], Match.DROP) + assert_eq(most_figures, 4, "all four players were drawn at once") + assert_true(session.frames_playing > 60 * 20) + var flow: Match = server.match_flow + var mine: SimEntity = server.sim.entities.find(flow.entity_of[LocalServer.HANDLE]) + assert_false(mine.eliminated) + assert_eq(session.mirror.own_id, mine.id) + assert_eq(session.status_text(), "", "nothing to say while playing") + var figure: Node3D = session.view.entities.figure_of(mine.id) + assert_true(figure.position.distance_to(mine.position) < 1.5, "drawn %.2f m from where the server has it" % figure.position.distance_to(mine.position)) + var came_down: Vector3 = mine.position + assert_true(session.view.camera.position.distance_to(figure.position) < 9.0) + assert_eq(session.view.sim, session.game.world, "the view draws the client's own copy of the world") + assert_ne(session.game.world, server.sim) + assert_eq(session.view.entities.get_node("Chests").multimesh.instance_count, server.sim.loot.chest_positions.size()) + assert_near(session.game.world.sea_level, server.sim.sea_level, 0.05) + _agrees(server.sim, "on the ground") + assert_eq(session.game.bad_packets, 0) + assert_eq(session.local.game.bad_inputs, 0) + assert_true(session.game.prediction.max_correction < 1.0, "largest correction %.2f m" % session.game.prediction.max_correction) + # On seed 2 a bot finds the scripted player soon after. From then on the client + # watches whoever it is given to watch. + for frame: int in 60 * 60: + session.pump(FRAME) + if mine.eliminated and session.mirror.watched_id != 0 and session.mirror.watched_id != mine.id: + break + assert_true(came_down.distance_to(mine.position) > 3.0, "it walked: the server took its commands") + assert_true(mine.eliminated, "the scripted player fell") + assert_false(session.game.playing()) + assert_eq(session.mirror.own_id, 0) + assert_eq(session.status_text(), "Watching") + var watched: Node3D = session.view.entities.figure_of(session.mirror.watched_id) + assert_not_null(watched) + assert_true(session.view.camera.position.distance_to(watched.position) < 9.0, "the camera moved to the player being watched") + _agrees(server.sim, "while watching") + + +func test_a_scripted_client_plays_a_whole_match_on_a_real_server() -> void: + var rules: MatchRules = MatchRules.new() + rules.max_players = 4 + rules.min_players = 1 + rules.lobby_ticks = 10 + rules.countdown_ticks = 10 + rules.results_ticks = 90 + var loop: ServerLoop = ServerLoop.new(41, 0, 3, rules) + net = NetServer.new() + assert_eq(net.listen(0, HOST), OK) + var game: NetGame = NetGame.new(loop, net) + assert_eq(session.connect_to(HOST, net.port(), "Mara"), OK) + assert_true(session.status_text().length() > 0, "it says it is connecting") + var flow: Match = loop.match_flow + var started: int = Time.get_ticks_msec() + var spectated: int = 0 + var checked: int = 0 + # A server tick and a client frame of the same length each round, so the clocks + # agree however fast this machine is. + while Time.get_ticks_msec() - started < 240000 and not session.phases.has(Match.RESULTS): + game.poll() + loop.run_tick() + game.after_tick() + session.pump(DT) + if flow.in_match() and not session.game.playing() and session.mirror.watched_id != 0: + spectated += 1 + if flow.in_match() and loop.ticks % 300 == 0 and session.game.replica.seq == game.world.seq: + checked += 1 + _agrees(loop.sim, "at tick %d" % loop.sim.tick) + assert_eq(session.phases, [Match.LOBBY, Match.COUNTDOWN, Match.DROP, Match.PLAY, Match.RESULTS] as Array[int], "lobby to results") + assert_eq(flow.phase, Match.RESULTS) + assert_eq(session.link.state, NetClient.JOINED) + assert_eq(session.game.match_index, 0) + assert_true(session.frames_playing > 300, "it played for %d ticks" % session.frames_playing) + assert_true(checked > 0, "the worlds were compared %d times" % checked) + assert_not_null(session.view) + assert_eq(session.view.sim.island.heightmap_hash(), loop.sim.island.heightmap_hash()) + # Results: the camera is on whoever is left, or the client itself if it won. + assert_true(session.mirror.watched_id != 0, "someone to watch at the end") + assert_not_null(session.view.entities.figure_of(session.mirror.watched_id)) + var summary: Array[Dictionary] = flow.summary() + assert_eq(summary.size(), 4) + assert_eq(session.game.bad_packets, 0) + assert_eq(game.bad_inputs, 0) + assert_eq(session.game.replica.gaps, 0) + print("N10 match over UDP: %d server ticks, client played %d and watched %d, %d world checks, %d corrections (largest %.2f m), %d WORLD messages" % [ + loop.ticks, session.frames_playing, spectated, checked, session.game.prediction.mispredictions, + session.game.prediction.max_correction, session.game.replica.applied, + ]) + + +func test_keys_and_mouse_become_commands() -> void: + var input: ClientInput = ClientInput.new() + input.move = Vector2(1.0, -1.0) + input.buttons = PlayerCommand.BUTTON_FIRE | PlayerCommand.BUTTON_SPRINT + input.press(KEY_3) + var command: PlayerCommand = input.command(77) + assert_eq(command.tick, 77) + assert_eq(command.move_x, PlayerCommand.AXIS_MAX) + assert_eq(command.move_y, -PlayerCommand.AXIS_MAX) + assert_eq(command.selection, 2, "3 is the second slot: 1 is the boathook") + assert_true(command.is_pressed(PlayerCommand.BUTTON_FIRE) and command.is_pressed(PlayerCommand.BUTTON_SPRINT)) + assert_false(command.is_pressed(PlayerCommand.BUTTON_BUILD)) + input.press(KEY_1) + assert_eq(input.command(78).selection, Simulation.BOATHOOK_SLOT) + input.press(KEY_9) + assert_eq(input.slot, 0, "there is no eighth slot") + # Build mode: the number row picks the piece, Tab the material, fire places. + input.press(KEY_TAB) + assert_eq(input.material, Materials.DRIFTWOOD, "Tab does nothing outside build mode") + input.press(KEY_B) + input.press(KEY_5) + input.press(KEY_TAB) + command = input.command(79) + assert_true(command.is_pressed(PlayerCommand.BUTTON_BUILD)) + assert_eq(command.selection, StructureSet.BREAKWATER) + assert_eq(command.material, Materials.STONE) + input.press(KEY_7) + assert_eq(input.build_kind, StructureSet.BREAKWATER, "there is no seventh piece") + input.press(KEY_B) + assert_eq(input.command(80).selection, 0, "back to what was held") + # The mouse turns the look: right is clockwise seen from above, up looks up. + input.turn(Vector2(100.0, -40.0)) + assert_true(input.yaw > PI, "turned right from north: %.2f" % input.yaw) + assert_true(input.pitch > 0.0) + command = input.command(81) + assert_eq(command.yaw, PlayerCommand.from_input(0, Vector2.ZERO, input.yaw, input.pitch).yaw) + # Aiming slows the look, and build mode doesn't aim. + input.buttons = PlayerCommand.BUTTON_AIM + assert_true(input.aiming()) + input.press(KEY_B) + assert_false(input.aiming()) + + +func test_the_command_line_picks_the_mode() -> void: + var offline: ClientConfig = ClientConfig.parse(PackedStringArray([])) + assert_true(offline.is_valid()) + assert_false(offline.asked) + assert_eq(offline.host, "") + assert_eq(offline.bots, Tuning.SOLO_PLAYERS - 1) + var join: ClientConfig = ClientConfig.parse(PackedStringArray(["--connect=play.example:7000", "--name=Mara", "--autoplay", "--client-seconds=2.5"])) + assert_true(join.is_valid(), str(join.errors)) + assert_true(join.asked) + assert_eq(join.host, "play.example") + assert_eq(join.port, 7000) + assert_eq(join.player_name, "Mara") + assert_true(join.autoplay) + assert_near(join.seconds, 2.5, 0.001) + assert_eq(ClientConfig.parse(PackedStringArray(["--connect=192.0.2.7"])).port, ServerConfig.DEFAULT_PORT) + var seeded: ClientConfig = ClientConfig.parse(PackedStringArray(["--offline", "--seed=9", "--bots=5"])) + assert_true(seeded.asked and seeded.has_seed) + assert_eq(seeded.match_seed, 9) + assert_eq(seeded.bots, 5) + for bad: String in ["--connect=", "--connect=host:0", "--connect=host:port", "--seed=x", "--bots=99", "--client-seconds=0", "--nonsense"]: + assert_false(ClientConfig.parse(PackedStringArray([bad])).is_valid(), bad) + + +func test_restored_entities_keep_their_ids_and_their_order() -> void: + var registry: EntityRegistry = EntityRegistry.new() + registry.restore(7, SimEntity.ARCHETYPE_PLAYER) + registry.restore(3, SimEntity.ARCHETYPE_PICKUP) + registry.restore(12, SimEntity.ARCHETYPE_PLAYER) + registry.restore(5, SimEntity.ARCHETYPE_PROJECTILE) + var ids: Array[int] = [] + for entity: SimEntity in registry.entities(): + ids.append(entity.id) + assert_eq(ids, [3, 5, 7, 12] as Array[int]) + assert_eq(registry.find(3).archetype, SimEntity.ARCHETYPE_PICKUP) + assert_eq(registry.create(SimEntity.ARCHETYPE_PLAYER).id, 13, "new IDs carry on past the highest") diff --git a/test/client/test_client_session.gd.uid b/test/client/test_client_session.gd.uid new file mode 100644 index 0000000..cce6f7a --- /dev/null +++ b/test/client/test_client_session.gd.uid @@ -0,0 +1 @@ +uid://etxgijcgqvye diff --git a/tools/client_check.sh b/tools/client_check.sh new file mode 100755 index 0000000..f722432 --- /dev/null +++ b/tools/client_check.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# Starts a real dedicated server and a real client as two processes, joins the client +# to the server over loopback UDP with its autoplay script at the controls, and checks +# it got from the lobby into the match and played. Both run headless and in real time, +# so this takes about a minute: the lobby waits 20 s and counts down 10 s. +# +# tools/client_check.sh CLIENT_CHECK_PORT=N picks the UDP port (default 24677) +set -euo pipefail + +repo="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +port="${CLIENT_CHECK_PORT:-24677}" +out="$repo/build/client-check" +mkdir -p "$out" + +nice -n 15 "$repo/tools/godot.sh" -- --server --listen --port="$port" --seed=41 --bots=3 --ticks=2100 >"$out/server.log" 2>&1 & +server=$! +trap 'kill "$server" 2>/dev/null || true' EXIT +sleep 3 +set +e +nice -n 15 "$repo/tools/godot.sh" -- --connect="127.0.0.1:$port" --name=Mara --autoplay --client-seconds=55 >"$out/client.log" 2>&1 +client_code=$? +wait "$server" +server_code=$? +set -e +trap - EXIT + +report="$(grep -m1 '"event":"client"' "$out/client.log" || true)" +fail() { + echo "client-check: $1" >&2 + echo " client: ${report:-no report}" >&2 + tail -n 5 "$out/server.log" >&2 + exit 1 +} +[[ "$client_code" -eq 0 ]] || fail "the client exited with $client_code" +[[ "$server_code" -eq 0 ]] || fail "the server exited with $server_code" +[[ -n "$report" ]] || fail "the client said nothing" +grep -q '"joined":true' <<<"$report" || fail "the client never joined" +grep -q '"phases":\["lobby","countdown","drop"' <<<"$report" || fail "the client didn't follow the match from the lobby into the drop" +grep -q '"bad_packets":0' <<<"$report" || fail "the client was sent packets it couldn't read" +playing="$(sed -n 's/.*"frames_playing":\([0-9]*\).*/\1/p' <<<"$report")" +[[ "${playing:-0}" -ge 300 ]] || fail "the client's player was in the match for only ${playing:-0} frames" +grep -q '"event":"player_joined".*"name":"Mara"' "$out/server.log" || fail "the server never saw the client join" +grep -q '"errors":0,"event":"stop"' "$out/server.log" || fail "the server logged errors" +if grep -q 'SCRIPT ERROR' "$out/client.log"; then fail "the client logged script errors"; fi +echo "client-check: ok (joined over UDP, lobby to drop, played $playing frames, no bad packets)" +echo " $report"