From 4993601616c708acd2e52475f4e9df9387dcdd18 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 09:01:36 -0500 Subject: [PATCH] A9: In-game HUD, with a FEED message for the kill feed and who stands The HUD (src/client/hud) is drawn in the paper-and-ink motifs of the style guide: - top centre: the tide post, the most prominent thing on screen. It is a notched post with the sea filled in, the next level's rust notch and the player's own height. Beside it are the phase, the time to the rise, both levels and how far the player stands above or below the next line; - top right: how many are standing, and the kill feed in words; - bottom left: health and armour, each with a number, a word, quarter notches and its own hatching. Low health adds LOW; - bottom centre: the boathook and five slots, with names on two lines, rounds and reserve or counts, and tier pips; - bottom right: materials, and the build line ("NOT ENOUGH" when short). Snapshots only carry nearby players, so the server now sends FEED (NetFeed, reliable) when anyone is placed and at each phase change. It carries who is standing, the match size and the newest 16 entries with names. Bots get crew names (CrewNames). HudState works out what to show from the client, or from a server's match for captures and tests, so the drawing never reaches into either. The project now stretches canvas items from a 1280x720 base, so the HUD scales to any screen. make hud-captures renders it at 1280x720 and 3840x2160. The parser fuzzer covers FEED. Closes #49 Co-Authored-By: Claude Opus 5.5 --- Makefile | 10 +- project.godot | 7 + src/app/client_session.gd | 13 + src/client/hud/hud.gd | 365 +++++++++++++++++++++++++++++ src/client/hud/hud.gd.uid | 1 + src/client/hud/hud_state.gd | 155 ++++++++++++ src/client/hud/hud_state.gd.uid | 1 + src/net/client_game.gd | 13 + src/net/net_feed.gd | 96 ++++++++ src/net/net_feed.gd.uid | 1 + src/server/crew_names.gd | 19 ++ src/server/crew_names.gd.uid | 1 + src/server/local_server.gd | 3 + src/server/net_game.gd | 35 +++ test/capture/client_hud.tscn | 7 + test/capture/client_hud_build.tscn | 7 + test/capture/client_scene.gd | 70 +++++- test/client/test_hud.gd | 203 ++++++++++++++++ test/client/test_hud.gd.uid | 1 + test/net/parser_fuzz.gd | 10 +- 20 files changed, 1009 insertions(+), 9 deletions(-) create mode 100644 src/client/hud/hud.gd create mode 100644 src/client/hud/hud.gd.uid create mode 100644 src/client/hud/hud_state.gd create mode 100644 src/client/hud/hud_state.gd.uid create mode 100644 src/net/net_feed.gd create mode 100644 src/net/net_feed.gd.uid create mode 100644 src/server/crew_names.gd create mode 100644 src/server/crew_names.gd.uid create mode 100644 test/capture/client_hud.tscn create mode 100644 test/capture/client_hud_build.tscn create mode 100644 test/client/test_hud.gd create mode 100644 test/client/test_hud.gd.uid diff --git a/Makefile b/Makefile index 24e545f..763f4f3 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 client-check client-captures style-captures discovery-check fuzz soak soak-selfcheck server-package-check +.PHONY: check import parse test test-selfcheck smoke capture-test terrain-capture binaries verify-engine bot-matches match match-captures client-check client-captures hud-captures style-captures discovery-check fuzz soak soak-selfcheck server-package-check ## Everything that must pass before a push. check: verify-engine binaries parse test test-selfcheck smoke @@ -63,7 +63,13 @@ discovery-check: import ## Renders what a network client sees on the barge, gliding and landed. Needs Docker. client-captures: import - @for stage in barge glide landed basin build build_refused; do tools/capture.sh client_$$stage captures/client_$$stage.png; done + @for stage in barge glide landed basin build build_refused hud hud_build; do tools/capture.sh client_$$stage captures/client_$$stage.png; done + +## A9: the HUD at 1280x720 and at 3840x2160 (captures/hud_*.png). Needs Docker. +hud-captures: import + @CAPTURE_SIZE=1280x720 tools/capture.sh client_hud captures/hud_720.png + @CAPTURE_SIZE=1280x720 tools/capture.sh client_hud_build captures/hud_build_720.png + @CAPTURE_SIZE=3840x2160 tools/capture.sh client_hud captures/hud_2160.png ## A1: the woodcut print pass on and off, side by side scenes (captures/style_*.png). Needs Docker. style-captures: import diff --git a/project.godot b/project.godot index 968b94a..495dbab 100644 --- a/project.godot +++ b/project.godot @@ -25,3 +25,10 @@ gdscript/warnings/shadowed_variable=1 [physics] common/physics_ticks_per_second=30 + +[display] + +window/size/viewport_width=1280 +window/size/viewport_height=720 +window/stretch/mode="canvas_items" +window/stretch/aspect="expand" diff --git a/src/app/client_session.gd b/src/app/client_session.gd index 53aaa19..3ad6e72 100644 --- a/src/app/client_session.gd +++ b/src/app/client_session.gd @@ -24,6 +24,9 @@ var phases: Array[int] = [] var frames_playing: int = 0 var frames: int = 0 +## The in-game HUD, once the session is in a scene tree. +var hud: Hud = null + var _viewed: Simulation = null var _status: Label = null @@ -90,6 +93,8 @@ func _ready() -> void: _status.add_theme_color_override("font_outline_color", Palette.OUTLINE) _status.add_theme_constant_override("outline_size", 6) add_child(_status) + hud = Hud.new() + add_child(hud) if DisplayServer.get_name() != "headless" and not input.autoplay: Input.mouse_mode = Input.MOUSE_MODE_CAPTURED @@ -98,6 +103,14 @@ func _process(delta: float) -> void: pump(delta) if _status != null: _status.text = status_text() + if hud != null: + hud.show_state(hud_state()) + + +## What the HUD should show now. +func hud_state() -> HudState: + var handle: int = LocalServer.HANDLE if local != null else (link.handle if link != null else 0) + return HudState.from_client(game, input, handle) func _unhandled_input(event: InputEvent) -> void: diff --git a/src/client/hud/hud.gd b/src/client/hud/hud.gd new file mode 100644 index 0000000..f4a042b --- /dev/null +++ b/src/client/hud/hud.gd @@ -0,0 +1,365 @@ +## The in-game HUD (A9), in the paper-and-ink motifs of docs/STYLE.md: a painted tide +## post at top centre (the tide is the match's clock), who is standing and the kill feed +## at top right, health and armour at bottom left, the boathook and five slots at bottom +## centre, materials and build mode at bottom right. +## +## Laid out for a 1280x720 canvas; the project's canvas_items stretch scales it to any +## screen. Nothing relies on colour alone: health and armour carry numbers, words and +## different patterns, tiers are pips, and the tide's danger is a word and a notch. +## show_state() takes a HudState and draws only that. +class_name Hud +extends Control + +const FONT_SMALL: int = 13 +const FONT_BODY: int = 16 +const FONT_TITLE: int = 22 +const MARGIN: float = 18.0 + +var state: HudState = HudState.new() + +var _tide: TidePost +var _standing: Label +var _feed: VBoxContainer +var _vitals: Vitals +var _hotbar: HBoxContainer +var _materials: VBoxContainer +var _build: Label +## When a feed line was first shown (msec), so lines fade after HudState.FEED_SECONDS. +var _feed_seen: Dictionary = {} +## Captures turn this off to keep every line of the feed. +var fade_feed: bool = true + + +func _init() -> void: + name = "Hud" + set_anchors_preset(Control.PRESET_FULL_RECT) + mouse_filter = Control.MOUSE_FILTER_IGNORE + + _tide = TidePost.new() + _tide.set_anchors_preset(Control.PRESET_CENTER_TOP) + _tide.custom_minimum_size = Vector2(330.0, 104.0) + _tide.size = _tide.custom_minimum_size + _tide.position = Vector2(-165.0, MARGIN - 6.0) + add_child(_tide) + + _standing = _label(FONT_TITLE, Palette.PAPER) + _standing.set_anchors_preset(Control.PRESET_TOP_RIGHT) + _standing.horizontal_alignment = HORIZONTAL_ALIGNMENT_RIGHT + _standing.position = Vector2(-320.0 - MARGIN, MARGIN) + _standing.size = Vector2(320.0, 30.0) + add_child(_standing) + + _feed = VBoxContainer.new() + _feed.set_anchors_preset(Control.PRESET_TOP_RIGHT) + _feed.position = Vector2(-380.0 - MARGIN, MARGIN + 36.0) + _feed.size = Vector2(380.0, 140.0) + _feed.alignment = BoxContainer.ALIGNMENT_BEGIN + _feed.add_theme_constant_override("separation", 2) + add_child(_feed) + + _vitals = Vitals.new() + _vitals.set_anchors_preset(Control.PRESET_BOTTOM_LEFT) + _vitals.custom_minimum_size = Vector2(270.0, 76.0) + _vitals.size = _vitals.custom_minimum_size + _vitals.position = Vector2(MARGIN, -76.0 - MARGIN) + add_child(_vitals) + + _hotbar = HBoxContainer.new() + _hotbar.set_anchors_preset(Control.PRESET_CENTER_BOTTOM) + _hotbar.add_theme_constant_override("separation", 6) + _hotbar.alignment = BoxContainer.ALIGNMENT_CENTER + _hotbar.size = Vector2(6.0 * 86.0 + 5.0 * 6.0, 84.0) + _hotbar.position = Vector2(-_hotbar.size.x * 0.5, -84.0 - MARGIN) + add_child(_hotbar) + + _build = _label(FONT_BODY, Palette.PAPER) + _build.set_anchors_preset(Control.PRESET_CENTER_BOTTOM) + _build.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER + _build.size = Vector2(520.0, 24.0) + _build.position = Vector2(-260.0, -84.0 - MARGIN - 30.0) + add_child(_build) + + _materials = VBoxContainer.new() + _materials.set_anchors_preset(Control.PRESET_BOTTOM_RIGHT) + _materials.size = Vector2(190.0, 84.0) + _materials.position = Vector2(-190.0 - MARGIN, -84.0 - MARGIN) + _materials.add_theme_constant_override("separation", 2) + add_child(_materials) + show_state(state) + + +## Shows `shown`, and nothing that isn't in it. +func show_state(shown: HudState) -> void: + state = shown + _tide.tide = shown.tide + _tide.visible = not shown.tide.is_empty() + _tide.queue_redraw() + _standing.visible = shown.total > 0 + _standing.text = "%d of %d standing" % [shown.standing, shown.total] + + var now: int = Time.get_ticks_msec() + var lines: Array[Dictionary] = [] + for line: Dictionary in shown.feed: + var key: String = String(line["text"]) + if not _feed_seen.has(key): + _feed_seen[key] = now + if fade_feed and now - int(_feed_seen[key]) > int(HudState.FEED_SECONDS * 1000.0): + continue + lines.append(line) + _fit_labels(_feed, lines.size(), HORIZONTAL_ALIGNMENT_RIGHT) + for index: int in lines.size(): + var label: Label = _feed.get_child(index) as Label + label.text = String(lines[index]["text"]) + label.add_theme_color_override("font_color", Palette.OILSKIN if lines[index]["you"] else Palette.PAPER) + if shown.feed.is_empty(): + _feed_seen.clear() + + _vitals.visible = shown.playing + _vitals.health = shown.health + _vitals.armor = shown.armor + _vitals.queue_redraw() + + _hotbar.visible = shown.playing + while _hotbar.get_child_count() < shown.slots.size(): + var box: SlotBox = SlotBox.new() + box.custom_minimum_size = Vector2(86.0, 84.0) + _hotbar.add_child(box) + for index: int in _hotbar.get_child_count(): + var box: SlotBox = _hotbar.get_child(index) as SlotBox + box.visible = index < shown.slots.size() + if box.visible: + box.slot = shown.slots[index] + box.number = index + box.queue_redraw() + + _materials.visible = shown.playing + _fit_labels(_materials, Materials.NAMES.size(), HORIZONTAL_ALIGNMENT_RIGHT) + for code: int in Materials.NAMES.size(): + var count: int = shown.materials[code] if code < shown.materials.size() else 0 + (_materials.get_child(code) as Label).text = "%s %d" % [Materials.NAMES[code].replace("_", " ").capitalize(), count] + + _build.visible = shown.playing and not shown.build.is_empty() + if _build.visible: + var build: Dictionary = shown.build + _build.text = "BUILDING · %s in %s · costs %d%s" % [String(build["kind"]).capitalize(), String(build["material"]).replace("_", " "), + int(build["cost"]), "" if build["affordable"] else " · NOT ENOUGH"] + _build.add_theme_color_override("font_color", Palette.PAPER if build["affordable"] else Palette.WARNING) + + +## Keeps exactly `count` labels in `box`, adding or removing at the end. +func _fit_labels(box: BoxContainer, count: int, align: HorizontalAlignment) -> void: + while box.get_child_count() < count: + var label: Label = _label(FONT_BODY, Palette.PAPER) + label.horizontal_alignment = align + box.add_child(label) + while box.get_child_count() > count: + var last: Node = box.get_child(box.get_child_count() - 1) + box.remove_child(last) + last.free() + + +static func _label(font_size: int, colour: Color) -> Label: + var label: Label = Label.new() + label.add_theme_font_size_override("font_size", font_size) + label.add_theme_color_override("font_color", colour) + label.add_theme_color_override("font_outline_color", Palette.OUTLINE) + label.add_theme_constant_override("outline_size", 5) + label.mouse_filter = Control.MOUSE_FILTER_IGNORE + return label + + +## A paper panel with an ink border and an offset ink shadow, like a printed card. +static func draw_card(item: CanvasItem, rect: Rect2, raised: bool = false) -> void: + item.draw_rect(Rect2(rect.position + Vector2(3.0, 3.0), rect.size), Color(Palette.INK, 0.55)) + item.draw_rect(rect, Color(Palette.PAPER, 0.93)) + item.draw_rect(rect, Palette.INK, false, 3.0 if raised else 1.5) + + +static func draw_text(item: CanvasItem, at: Vector2, text: String, font_size: int, colour: Color = Palette.INK, + width: float = -1.0, align: HorizontalAlignment = HORIZONTAL_ALIGNMENT_LEFT) -> void: + var font: Font = ThemeDB.fallback_font + item.draw_string(font, at, text, align, width, font_size, colour) + + +static func roman(value: int) -> String: + const NUMERALS: Array[String] = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"] + return NUMERALS[value] if value >= 0 and value < NUMERALS.size() else str(value) + + +## The tide post: a notched wooden post with the sea filled to its level, the next +## level's notch, and the player's own height, beside the phase and the time to the rise. +class TidePost: + extends Control + + var tide: Dictionary = {} + + func _init() -> void: + mouse_filter = Control.MOUSE_FILTER_IGNORE + + func _draw() -> void: + if tide.is_empty(): + return + var card: Rect2 = Rect2(Vector2.ZERO, size) + Hud.draw_card(self, card) + var sea: float = tide["sea"] + var next: float = tide["next"] + var feet: float = tide["feet"] + var low: float = floorf(sea - 3.0) + var high: float = maxf(next, sea) + 5.0 + if not is_nan(feet): + high = maxf(high, minf(feet + 2.0, low + 40.0)) + var post: Rect2 = Rect2(16.0, 10.0, 26.0, size.y - 20.0) + var to_y: Callable = func(level: float) -> float: + return post.end.y - clampf((level - low) / (high - low), 0.0, 1.0) * post.size.y + draw_rect(post, Palette.PLANK_BLEACHED) + # Water up to the sea, with a wave cut across its top. + var water_top: float = to_y.call(sea) + draw_rect(Rect2(post.position.x, water_top, post.size.x, post.end.y - water_top), Palette.SEA_INK) + var wave: PackedVector2Array = PackedVector2Array() + for step: int in 7: + wave.append(Vector2(post.position.x + post.size.x * step / 6.0, water_top + (2.5 if step % 2 == 0 else -2.5))) + draw_polyline(wave, Palette.PAPER, 1.5) + # Notches each metre, longer each five. + var metre: float = ceilf(low) + while metre <= high: + var y: float = to_y.call(metre) + var long: bool = int(metre) % 5 == 0 + draw_line(Vector2(post.position.x, y), Vector2(post.position.x + (12.0 if long else 6.0), y), Palette.INK, 1.0) + metre += 1.0 + draw_rect(post, Palette.INK, false, 1.5) + # The next level: a rust notch cut into both sides, with a dashed line across. + if next > sea + 0.05: + var next_y: float = to_y.call(next) + draw_dashed_line(Vector2(post.position.x - 6.0, next_y), Vector2(post.end.x + 6.0, next_y), Palette.WARNING, 2.0, 4.0) + draw_colored_polygon(PackedVector2Array([Vector2(post.position.x - 10.0, next_y - 5.0), Vector2(post.position.x - 2.0, next_y), Vector2(post.position.x - 10.0, next_y + 5.0)]), Palette.WARNING) + # The player's own height: a yellow pointer on the right of the post. + if not is_nan(feet): + var feet_y: float = to_y.call(feet) + draw_colored_polygon(PackedVector2Array([Vector2(post.end.x + 2.0, feet_y), Vector2(post.end.x + 12.0, feet_y - 6.0), Vector2(post.end.x + 12.0, feet_y + 6.0)]), Palette.OILSKIN) + draw_polyline(PackedVector2Array([Vector2(post.end.x + 2.0, feet_y), Vector2(post.end.x + 12.0, feet_y - 6.0), Vector2(post.end.x + 12.0, feet_y + 6.0), Vector2(post.end.x + 2.0, feet_y)]), Palette.INK, 1.0) + + var x: float = post.end.x + 26.0 + var width: float = size.x - x - 10.0 + Hud.draw_text(self, Vector2(x, 30.0), "TIDE %s of %s" % [Hud.roman(int(tide["phase"])), Hud.roman(int(tide["phases"]))], Hud.FONT_TITLE) + var stage: int = tide["stage"] + var timing: String + match stage: + Tide.HOLD: + var seconds: int = ceili(float(tide["rise_in"])) + timing = "Rises in %d:%02d" % [seconds / 60, seconds % 60] + Tide.RISE: + timing = "RISING" + Tide.SUDDEN_DEATH: + timing = "HIGH WATER · last land" + _: + timing = "Slack water" + Hud.draw_text(self, Vector2(x, 54.0), timing, Hud.FONT_BODY, Palette.WARNING if stage != Tide.HOLD else Palette.INK, width) + Hud.draw_text(self, Vector2(x, 74.0), "Sea %.1f m · next %.1f m" % [sea, next], Hud.FONT_SMALL, Palette.INK, width) + if not is_nan(feet): + var above: float = feet - next + var line: String = "You: %.1f m above the next line" % above if above >= 0.0 else "You: %.1f m BELOW the next line" % -above + Hud.draw_text(self, Vector2(x, 92.0), line, Hud.FONT_SMALL, Palette.INK if above >= 0.0 else Palette.WARNING, width) + + +## Health and armour bars: each a number, a word, notches every quarter and its own +## pattern, so they read without colour. Low health adds LOW and rust hatching. +class Vitals: + extends Control + + var health: int = 0 + var armor: int = 0 + + func _init() -> void: + mouse_filter = Control.MOUSE_FILTER_IGNORE + + func _draw() -> void: + Hud.draw_card(self, Rect2(Vector2.ZERO, size)) + _bar(Rect2(76.0, 12.0, size.x - 88.0, 22.0), "HEALTH", health, Tuning.PLAYER_MAX_HEALTH, false) + _bar(Rect2(76.0, 44.0, size.x - 88.0, 18.0), "ARMOUR", armor, Tuning.PLAYER_MAX_ARMOR, true) + + func _bar(rect: Rect2, word: String, value: int, most: int, striped: bool) -> void: + var low: bool = not striped and value <= most / 4 + Hud.draw_text(self, Vector2(10.0, rect.position.y + rect.size.y * 0.5 + 5.0), word, Hud.FONT_SMALL) + draw_rect(rect, Color(Palette.INK, 0.15)) + var filled: Rect2 = Rect2(rect.position, Vector2(rect.size.x * clampf(float(value) / most, 0.0, 1.0), rect.size.y)) + var fill: Color = Palette.WARNING if low else (Palette.SEA_PAINT if striped else Palette.OCHRE_RED.lerp(Palette.TAR, 0.1)) + draw_rect(filled, fill) + if striped or low: + # Armour is hatched one way; low health the other. + var step: float = 6.0 + var x: float = filled.position.x - filled.size.y + while x < filled.end.x: + var a: Vector2 = Vector2(x, filled.end.y) if striped else Vector2(x, filled.position.y) + var b: Vector2 = Vector2(x + filled.size.y, filled.position.y) if striped else Vector2(x + filled.size.y, filled.end.y) + var clipped: PackedVector2Array = _clip(a, b, filled) + if clipped.size() == 2: + draw_line(clipped[0], clipped[1], Color(Palette.INK, 0.45), 1.5) + x += step + for quarter: int in range(1, 4): + var qx: float = rect.position.x + rect.size.x * quarter / 4.0 + draw_line(Vector2(qx, rect.position.y), Vector2(qx, rect.position.y + 5.0), Palette.INK, 1.0) + draw_rect(rect, Palette.INK, false, 1.5) + var text: String = "%d%s" % [value, " LOW" if low else ""] + Hud.draw_text(self, Vector2(rect.position.x + 6.0, rect.position.y + rect.size.y * 0.5 + 5.0), text, Hud.FONT_BODY, + Palette.PAPER if value > most / 3 else Palette.INK) + + static func _clip(a: Vector2, b: Vector2, rect: Rect2) -> PackedVector2Array: + # Clips the segment to the rect's x range (the y range always fits). + var from: Vector2 = a + var to: Vector2 = b + if to.x < rect.position.x or from.x > rect.end.x: + return PackedVector2Array() + if from.x < rect.position.x: + from = from.lerp(to, (rect.position.x - from.x) / (to.x - from.x)) + if to.x > rect.end.x: + to = from.lerp(to, (rect.end.x - from.x) / (to.x - from.x)) + return PackedVector2Array([from, to]) + + +## One hotbar slot: its key number, the item's name, count or rounds, and tier pips. +## The held one is raised, has a heavier border and an oilskin band. +class SlotBox: + extends Control + + var slot: Dictionary = {} + var number: int = 0 + + func _init() -> void: + mouse_filter = Control.MOUSE_FILTER_IGNORE + + func _draw() -> void: + var selected: bool = bool(slot.get("selected", false)) + var rect: Rect2 = Rect2(Vector2(0.0, 0.0 if selected else 8.0), size - Vector2(0.0, 8.0)) + if bool(slot.get("empty", true)): + draw_rect(rect, Color(Palette.INK, 0.35)) + draw_rect(rect, Color(Palette.PAPER_DIM, 0.8), false, 1.0) + Hud.draw_text(self, rect.position + Vector2(6.0, 16.0), str(number), Hud.FONT_SMALL, Palette.PAPER_DIM) + return + Hud.draw_card(self, rect, selected) + if selected: + draw_rect(Rect2(rect.position, Vector2(rect.size.x, 6.0)), Palette.OILSKIN) + draw_rect(Rect2(rect.position, Vector2(rect.size.x, 6.0)), Palette.INK, false, 1.0) + Hud.draw_text(self, rect.position + Vector2(5.0, 15.0), str(number), Hud.FONT_SMALL - 2, Palette.INK) + # The name on up to two lines, split between words, so nothing is cut off. + var words: PackedStringArray = String(slot.get("name", "")).split(" ") + var first: String = words[0] if words.size() > 0 else "" + var rest: String = " ".join(words.slice(1)) if words.size() > 1 else "" + var width: float = rect.size.x - 8.0 + Hud.draw_text(self, rect.position + Vector2(4.0, 31.0), first, Hud.FONT_SMALL, Palette.INK, width, HORIZONTAL_ALIGNMENT_CENTER) + if not rest.is_empty(): + Hud.draw_text(self, rect.position + Vector2(4.0, 45.0), rest, Hud.FONT_SMALL, Palette.INK, width, HORIZONTAL_ALIGNMENT_CENTER) + var amount: String = "" + if int(slot.get("rounds", -1)) >= 0: + amount = "%d | %d" % [int(slot["rounds"]), int(slot["reserve"])] + elif int(slot.get("count", 0)) > 1: + amount = "x%d" % int(slot["count"]) + if not amount.is_empty(): + Hud.draw_text(self, rect.position + Vector2(4.0, 60.0), amount, Hud.FONT_SMALL, Palette.INK, width, HORIZONTAL_ALIGNMENT_CENTER) + var tier: int = int(slot.get("tier", -1)) + if tier >= 0: + # Pips: filled up to the tier, out of four, so tier reads without colour. + for pip: int in Tuning.WEAPON_TIERS.size(): + var centre: Vector2 = rect.position + Vector2(rect.size.x * 0.5 + (pip - 1.5) * 11.0, rect.size.y - 7.0) + if pip <= tier: + draw_circle(centre, 3.5, Palette.GILT if tier >= 2 else Palette.INK) + draw_arc(centre, 3.5, 0.0, TAU, 12, Palette.INK, 1.0) diff --git a/src/client/hud/hud.gd.uid b/src/client/hud/hud.gd.uid new file mode 100644 index 0000000..63e36dd --- /dev/null +++ b/src/client/hud/hud.gd.uid @@ -0,0 +1 @@ +uid://cic0qgduge4io diff --git a/src/client/hud/hud_state.gd b/src/client/hud/hud_state.gd new file mode 100644 index 0000000..0877d04 --- /dev/null +++ b/src/client/hud/hud_state.gd @@ -0,0 +1,155 @@ +## What the HUD shows, as plain data: worked out from the client's game and input +## (from_client) or from a server's simulation and match (from_match, for captures and +## tests), so the HUD's drawing never reaches into either. See Hud. +class_name HudState +extends RefCounted + +## Seconds a kill feed entry stays on screen. +const FEED_SECONDS: float = 9.0 +const FEED_LINES: int = 5 + +## True while the player is in the match: vitals, hotbar and materials are shown. +var playing: bool = false +var health: int = 0 +var armor: int = 0 +## The boathook, then one per inventory slot: {"name", "count", "rounds", "reserve", +## "magazine", "tier" (-1 for no tier), "selected", "empty"}. +var slots: Array[Dictionary] = [] +var materials: PackedInt32Array = PackedInt32Array([0, 0, 0]) +## {} when not building, else {"kind", "material", "cost", "affordable"}. +var build: Dictionary = {} +## {} before the tide starts, else {"phase" (1-based), "phases", "stage" (Tide.HOLD...), +## "sea", "next", "rise_in" (seconds), "feet" (NAN when not standing anywhere)}. +var tide: Dictionary = {} +var standing: int = 0 +var total: int = 0 +## Lines for the kill feed, oldest first: {"text", "you"}. +var feed: Array[Dictionary] = [] + + +## The HUD for a client: its own predicted player, the world's tide and the server's feed. +static func from_client(game: ClientGame, input: ClientInput, own_handle: int, feed_ages: Dictionary = {}) -> HudState: + var state: HudState = HudState.new() + state.standing = game.standing + state.total = game.match_size + state.feed = feed_lines(game.feed, own_handle) + if game.world != null and game.world.tide != null and game.match_phase != Match.LOBBY and game.match_phase != Match.COUNTDOWN: + var feet: float = NAN + if game.playing(): + feet = game.own_position().y + state.tide = tide_of(game.world.tide, game.world.tick, feet) + if game.playing(): + var me: SimEntity = game.prediction.player + var drawn: SimEntity = game.world.entities.find(me.id) if game.world != null else null + state.playing = true + state.health = drawn.health if drawn != null else me.health + state.armor = drawn.armor if drawn != null else me.armor + _fill_carried(state, me) + state.build = build_of(input.build_mode, input.build_kind, input.material, me.materials) + return state + + +## The HUD for `handle` in a server's match, as a client of theirs would see it. +static func from_match(flow: Match, handle: int, build_mode: bool = false, build_kind: int = StructureSet.WALL, material: int = Materials.DRIFTWOOD) -> HudState: + var state: HudState = HudState.new() + var sim: Simulation = flow.sim + var started: bool = flow.in_match() or flow.phase == Match.RESULTS + state.standing = flow.alive().size() + state.total = flow.participants.size() if started else 0 + var entries: Array[Dictionary] = [] + for record: Dictionary in flow.kill_feed: + var entry: Dictionary = record.duplicate() + entry["victim"] = record["handle"] + entry["victim_name"] = CrewNames.for_bot(int(record["handle"])) if int(record["handle"]) < 0 else "Player %d" % int(record["handle"]) + entry["by_name"] = "" if int(record["by"]) == 0 else (CrewNames.for_bot(int(record["by"])) if int(record["by"]) < 0 else "Player %d" % int(record["by"])) + entries.append(entry) + state.feed = feed_lines(entries, handle) + var me: SimEntity = sim.entities.find(int(flow.entity_of.get(handle, 0))) + if sim.tide != null and started: + state.tide = tide_of(sim.tide, sim.tick, me.position.y if me != null and not me.eliminated else NAN) + if me != null and not me.eliminated and flow.in_match(): + state.playing = true + state.health = me.health + state.armor = me.armor + _fill_carried(state, me) + state.build = build_of(build_mode, build_kind, material, me.materials) + return state + + +static func tide_of(tide: Tide, tick: int, feet: float) -> Dictionary: + return { + "phase": tide.phase_at(tick) + 1, "phases": Tide.phase_count(), "stage": tide.stage_at(tick), + "sea": tide.level_at(tick), "next": tide.forecast_at(tick), + "rise_in": float(tide.ticks_until_rise(tick)) / Tuning.TICK_RATE_HZ, "feet": feet, + } + + +static func build_of(on: bool, kind: int, material: int, carried: PackedInt32Array) -> Dictionary: + if not on: + return {} + var kinds: Array = Tuning.BUILD_PIECES.keys() + var kind_name: String = String(kinds[kind]) if kind >= 0 and kind < kinds.size() else "piece" + var cost: int = int(Tuning.BUILD_PIECES.get(kind_name, {}).get("cost", 0)) + return {"kind": kind_name, "material": Materials.NAMES[material], "cost": cost, + "affordable": material < carried.size() and carried[material] >= cost} + + +## Kill feed entries as lines of words, naming `own_handle` "You". Only the newest +## FEED_LINES. +static func feed_lines(entries: Array[Dictionary], own_handle: int) -> Array[Dictionary]: + var lines: Array[Dictionary] = [] + for index: int in range(maxi(0, entries.size() - FEED_LINES), entries.size()): + var entry: Dictionary = entries[index] + var victim_is_you: bool = int(entry.get("victim", 0)) == own_handle and own_handle != 0 + var by_is_you: bool = int(entry.get("by", 0)) == own_handle and own_handle != 0 + var victim: String = "You" if victim_is_you else String(entry.get("victim_name", "Someone")) + var by: String = "You" if by_is_you else String(entry.get("by_name", "")) + lines.append({"text": feed_text(victim, by, String(entry.get("cause", "none")), int(entry.get("item", -1)), victim_is_you), "you": victim_is_you or by_is_you}) + return lines + + +static func feed_text(victim: String, by: String, cause: String, item: int, victim_is_you: bool) -> String: + var weapon: String = "" + if item >= 0 and item < ItemCatalog.count(): + weapon = " with %s" % item_name(ItemCatalog.get_def(item).id).to_lower() + match cause: + "weapon": + if not by.is_empty() and by != victim: + return "%s took %s%s" % [by, "you" if victim_is_you else victim, weapon] + return "%s went down" % victim + "fall": + return "%s fell" % victim + "drown": + return "%s drowned" % victim + "tide": + return "The tide took %s" % ("you" if victim_is_you else victim) + "left": + return "%s left" % victim + return "%s is out" % victim + + +## "flintlock_pistol" -> "Flintlock Pistol". +static func item_name(id: String) -> String: + return id.replace("_", " ").capitalize() + + +static func _fill_carried(state: HudState, me: SimEntity) -> void: + state.materials = me.materials.duplicate() + # The boathook is always carried, before the slots; `selected` 0 holds it. + state.slots.append({"selected": me.selected == 0, "empty": false, "name": item_name(ItemCatalog.BOATHOOK), + "count": 1, "rounds": -1, "reserve": -1, "magazine": 0, "tier": -1, "tool": true}) + for slot: int in me.slot_items.size(): + var code: int = me.slot_items[slot] + var entry: Dictionary = {"selected": me.selected == slot + 1, "empty": code == Inventory.EMPTY, + "name": "", "count": 0, "rounds": -1, "reserve": -1, "magazine": 0, "tier": 0} + if code != Inventory.EMPTY: + var def: ItemDef = ItemCatalog.get_def(code) + entry["name"] = item_name(def.id) + entry["count"] = me.slot_counts[slot] + entry["tier"] = me.slot_tiers[slot] if def.is_weapon() else -1 + if def.uses_magazine(): + entry["rounds"] = me.slot_rounds[slot] + entry["magazine"] = def.magazine + var ammo: int = Inventory.ammo_index(def.ammo_code) + entry["reserve"] = me.ammo[ammo] if ammo >= 0 and ammo < me.ammo.size() else 0 + state.slots.append(entry) diff --git a/src/client/hud/hud_state.gd.uid b/src/client/hud/hud_state.gd.uid new file mode 100644 index 0000000..0ef6dc0 --- /dev/null +++ b/src/client/hud/hud_state.gd.uid @@ -0,0 +1 @@ +uid://by20dltxfwshu diff --git a/src/net/client_game.gd b/src/net/client_game.gd index eb13fd3..00fec87 100644 --- a/src/net/client_game.gd +++ b/src/net/client_game.gd @@ -60,6 +60,11 @@ var build_in_background: bool = false var fx: Array[Dictionary] = [] ## FX records received in all. var fx_received: int = 0 +## The kill feed as the server last told it (NetFeed entries, newest last), how many +## are standing and how many began the match. For the HUD. +var feed: Array[Dictionary] = [] +var standing: int = 0 +var match_size: int = 0 ## Called after each snapshot has been taken in, with no arguments. Soak tests use it ## to compare the client's world with the server's at that moment. var on_snapshot: Callable = Callable() @@ -180,6 +185,14 @@ func _receive_now(channel: int, bytes: PackedByteArray) -> void: bad_packets += 1 return _take_world(message) + elif type == NetFeed.MSG_FEED: + var told: Dictionary = NetFeed.decode(bytes) + if told.is_empty(): + bad_packets += 1 + return + feed = told["entries"] + standing = told["standing"] + match_size = told["total"] elif type == NetWorld.MSG_OWN: var carried: Dictionary = NetWorld.decode_own(bytes) if carried.is_empty(): diff --git a/src/net/net_feed.gd b/src/net/net_feed.gd new file mode 100644 index 0000000..23991b8 --- /dev/null +++ b/src/net/net_feed.gd @@ -0,0 +1,96 @@ +## The kill feed and the count of who is standing, on the wire, for the HUD (A9). +## Snapshots only carry players near the one a client watches, so the client can't +## count the living or see eliminations across the island by itself; the server tells +## everyone with a FEED message on the control channel (reliable) whenever someone is +## placed, and when a match begins. +## +## server -> FEED +## u8 type, u8 standing, u8 players in the match, u8 entry count, then entries: +## s32 victim handle, s32 eliminator handle (0 = none), u8 cause (CAUSES), +## u8 item code plus one (0 = none), u8 place, u8 flags (1 = tied), +## str victim name, str eliminator name, +## where str is u8 byte length then that many UTF-8 bytes (at most MAX_NAME_BYTES). +## +## The decoder returns an empty Dictionary for anything malformed and never raises. +class_name NetFeed +extends RefCounted + +const MSG_FEED: int = 19 +## How an entry came about, by the Match's cause names. +const CAUSES: Array[String] = ["none", "weapon", "fall", "drown", "tide", "left"] +const HEADER_BYTES: int = 4 +const ENTRY_FIXED_BYTES: int = 12 +const MAX_ENTRIES: int = 16 +const MAX_NAME_BYTES: int = 32 +const FLAG_TIED: int = 1 + + +## Encodes the count and `entries`, newest last. Each entry has "victim", "by", +## "cause" (a name in CAUSES), "item" (-1 none), "place", "tied", "victim_name" and +## "by_name". Only the newest MAX_ENTRIES are kept. +static func encode(standing: int, total: int, entries: Array[Dictionary]) -> PackedByteArray: + var out: StreamPeerBuffer = StreamPeerBuffer.new() + out.put_u8(MSG_FEED) + out.put_u8(clampi(standing, 0, 255)) + out.put_u8(clampi(total, 0, 255)) + var first: int = maxi(0, entries.size() - MAX_ENTRIES) + out.put_u8(entries.size() - first) + for index: int in range(first, entries.size()): + var entry: Dictionary = entries[index] + out.put_32(int(entry.get("victim", 0))) + out.put_32(int(entry.get("by", 0))) + out.put_u8(maxi(0, CAUSES.find(String(entry.get("cause", "none"))))) + out.put_u8(clampi(int(entry.get("item", -1)) + 1, 0, 255)) + out.put_u8(clampi(int(entry.get("place", 0)), 0, 255)) + out.put_u8(FLAG_TIED if bool(entry.get("tied", false)) else 0) + _put_name(out, String(entry.get("victim_name", ""))) + _put_name(out, String(entry.get("by_name", ""))) + return out.data_array + + +## {"standing", "total", "entries": Array[Dictionary]} with the fields encode() takes, +## or an empty Dictionary. +static func decode(bytes: PackedByteArray) -> Dictionary: + if bytes.size() < HEADER_BYTES or bytes[0] != MSG_FEED: + return {} + var count: int = bytes[3] + if count > MAX_ENTRIES: + return {} + var entries: Array[Dictionary] = [] + var at: int = HEADER_BYTES + for _index: int in count: + if at + ENTRY_FIXED_BYTES > bytes.size(): + return {} + var cause: int = bytes[at + 8] + if cause >= CAUSES.size(): + return {} + var entry: Dictionary = { + "victim": bytes.decode_s32(at), "by": bytes.decode_s32(at + 4), "cause": CAUSES[cause], + "item": int(bytes[at + 9]) - 1, "place": int(bytes[at + 10]), "tied": bytes[at + 11] & FLAG_TIED != 0, + } + at += ENTRY_FIXED_BYTES + var names: Array[String] = [] + for _name: int in 2: + if at >= bytes.size(): + return {} + var length: int = bytes[at] + if length > MAX_NAME_BYTES or at + 1 + length > bytes.size(): + return {} + names.append(bytes.slice(at + 1, at + 1 + length).get_string_from_utf8()) + at += 1 + length + entry["victim_name"] = names[0] + entry["by_name"] = names[1] + entries.append(entry) + if at != bytes.size(): + return {} + return {"standing": int(bytes[1]), "total": int(bytes[2]), "entries": entries} + + +static func _put_name(out: StreamPeerBuffer, text: String) -> void: + var raw: PackedByteArray = text.to_utf8_buffer() + # Cut on a character boundary, never inside one. + while raw.size() > MAX_NAME_BYTES: + text = text.substr(0, text.length() - 1) + raw = text.to_utf8_buffer() + out.put_u8(raw.size()) + out.put_data(raw) diff --git a/src/net/net_feed.gd.uid b/src/net/net_feed.gd.uid new file mode 100644 index 0000000..398a647 --- /dev/null +++ b/src/net/net_feed.gd.uid @@ -0,0 +1 @@ +uid://c3atn0r4ms2l6 diff --git a/src/server/crew_names.gd b/src/server/crew_names.gd new file mode 100644 index 0000000..0b2e3e9 --- /dev/null +++ b/src/server/crew_names.gd @@ -0,0 +1,19 @@ +## Names for bots in the kill feed: plain coastal words, the kind a crew gives each +## other. Bot handles count down from -1, so the first bot of every match is the first +## name; past the list a number is added. +class_name CrewNames +extends RefCounted + +const NAMES: Array[String] = [ + "Gannet", "Skerry", "Thole", "Scupper", "Cockle", "Fathom", "Lugworm", "Pollack", + "Spindrift", "Tarry", "Wherry", "Fulmar", "Kittiwake", "Limpet", "Oakum", "Dory", + "Sculpin", "Shingle", "Brine", "Marram", "Whelk", "Kelp", "Bollard", "Gunnel", +] + + +static func for_bot(handle: int) -> String: + var index: int = absi(handle) - 1 + if index < 0: + return "Crew" + var base: String = NAMES[index % NAMES.size()] + return base if index < NAMES.size() else "%s %d" % [base, index / NAMES.size() + 1] diff --git a/src/server/crew_names.gd.uid b/src/server/crew_names.gd.uid new file mode 100644 index 0000000..1afd188 --- /dev/null +++ b/src/server/crew_names.gd.uid @@ -0,0 +1 @@ +uid://djnuyci14c2wb diff --git a/src/server/local_server.gd b/src/server/local_server.gd index 7991439..c47bcb1 100644 --- a/src/server/local_server.gd +++ b/src/server/local_server.gd @@ -49,6 +49,8 @@ func tick(client: ClientGame) -> void: client.receive(NetProtocol.CHANNEL_CONTROL, game.match_notice()) if not game.world_changes.is_empty(): client.receive(NetProtocol.CHANNEL_CONTROL, game.world_changes) + if not game.feed_changes.is_empty(): + client.receive(NetProtocol.CHANNEL_CONTROL, game.feed_changes) if game.own_changes.has(HANDLE): client.receive(NetProtocol.CHANNEL_CONTROL, game.own_changes[HANDLE]) if game.snapshot_due(): @@ -65,3 +67,4 @@ func _greet(client: ClientGame) -> void: _greeted = true client.receive(NetProtocol.CHANNEL_CONTROL, game.match_notice()) client.receive(NetProtocol.CHANNEL_CONTROL, game.world_notice()) + client.receive(NetProtocol.CHANNEL_CONTROL, game.feed_notice()) diff --git a/src/server/net_game.gd b/src/server/net_game.gd index 23c0c7b..78dd567 100644 --- a/src/server/net_game.gd +++ b/src/server/net_game.gd @@ -22,6 +22,8 @@ var bad_inputs: int = 0 ## messages it sent, by handle. For owners that carry the packets themselves. var world_changes: PackedByteArray = PackedByteArray() var own_changes: Dictionary = {} +## The FEED message (NetFeed) the last after_tick() sent everyone, or empty. +var feed_changes: PackedByteArray = PackedByteArray() ## Handle -> the newest command tick received from them this match. var _last_command: Dictionary = {} @@ -59,6 +61,7 @@ func poll() -> void: adopt(handle) _send_match(handle) net.send(handle, NetProtocol.CHANNEL_CONTROL, world_notice(), true) + net.send(handle, NetProtocol.CHANNEL_CONTROL, feed_notice(), true) var joined: Dictionary = event.duplicate() joined["watching"] = watching events.append(joined) @@ -111,9 +114,13 @@ func take_input(handle: int, bytes: PackedByteArray) -> void: func after_tick() -> void: var flow: Match = loop.match_flow var changed: bool = false + var feed_changed: bool = false world_changes = PackedByteArray() + feed_changes = PackedByteArray() own_changes.clear() for event: Dictionary in flow.events: + if event["type"] == "placed" or event["type"] == "match_started": + feed_changed = true if event["type"] == "phase": changed = true if event["to"] == "lobby": @@ -128,6 +135,11 @@ func after_tick() -> void: if changed: for handle: int in net.handles(): _send_match(handle) + if changed or feed_changed: + feed_changes = feed_notice() + for handle: int in net.handles(): + if sender.has_client(handle): + net.send(handle, NetProtocol.CHANNEL_CONTROL, feed_changes, true) # The world goes before the snapshots, which say how much of it there is to know. if not world.is_for(loop.sim): # A new match's simulation: everyone starts again from the whole of it. @@ -233,6 +245,29 @@ func match_notice() -> PackedByteArray: return NetSnapshot.encode_match(flow.phase, index, flow.current_seed()) +## The FEED message as things stand: who is standing and the newest kill feed entries. +func feed_notice() -> PackedByteArray: + var flow: Match = loop.match_flow + var entries: Array[Dictionary] = [] + var first: int = maxi(0, flow.kill_feed.size() - NetFeed.MAX_ENTRIES) + for index: int in range(first, flow.kill_feed.size()): + var entry: Dictionary = flow.kill_feed[index].duplicate() + entry["victim"] = entry["handle"] + entry["victim_name"] = name_of(int(entry["handle"])) + entry["by_name"] = name_of(int(entry["by"])) if int(entry["by"]) != 0 else "" + entries.append(entry) + var started: bool = flow.in_match() or flow.phase == Match.RESULTS + return NetFeed.encode(flow.alive().size(), flow.participants.size() if started else 0, entries) + + +## A participant's name for the HUD: the one they joined with, or a bot's crew name. +func name_of(handle: int) -> String: + if loop.match_flow.bot_handles.has(handle) or handle < 0: + return CrewNames.for_bot(handle) + var joined: String = net.name_of(handle) if net != null else "" + return joined if not joined.is_empty() else "Player %d" % handle + + ## The entity a participant is watching: their own player, the player they spectate ## once eliminated (or, for someone who arrived mid-match, from the start), or 0 when ## they aren't in a match. diff --git a/test/capture/client_hud.tscn b/test/capture/client_hud.tscn new file mode 100644 index 0000000..d91cb73 --- /dev/null +++ b/test/capture/client_hud.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 = "hud" diff --git a/test/capture/client_hud_build.tscn b/test/capture/client_hud_build.tscn new file mode 100644 index 0000000..07e1b16 --- /dev/null +++ b/test/capture/client_hud_build.tscn @@ -0,0 +1,7 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://test/capture/client_scene.gd" id="1"] + +[node name="CaptureClient" type="Node3D"] +script = ExtResource("1") +stage = "hud_build" diff --git a/test/capture/client_scene.gd b/test/capture/client_scene.gd index c294535..222e140 100644 --- a/test/capture/client_scene.gd +++ b/test/capture/client_scene.gd @@ -9,6 +9,10 @@ ## ground inside, below the sea, stays dry on the client too (issue N11). build and ## build_refused: once landed, the client goes into build mode for a driftwood wall, ## with plenty of materials or none, so the ghost shows in its allowed or refused tint. +## hud and hud_build (issue A9): once landed, the server hands the player a carbine, a +## fowling piece and bandages, wounds them a little and takes three bots out in +## different ways, so every part of the HUD has something to show; hud_build then goes +## into build mode. Every stage draws the HUD as the client's HudState has it. extends Node3D const DT: float = 1.0 / Tuning.TICK_RATE_HZ @@ -64,7 +68,7 @@ func _ready() -> void: reached = me.drop_state == Drop.ABOARD and _session.game.prediction.next_tick > 3 * Tuning.TICK_RATE_HZ "glide": reached = me.drop_state == Drop.GLIDING - "landed", "basin", "build", "build_refused": + "landed", "basin", "build", "build_refused", "hud", "hud_build": reached = me.drop_state == Drop.NONE if reached and since < 0: since = 0 @@ -84,6 +88,14 @@ func _ready() -> void: basin_text = _build_mode(stage == "build") if basin_text.is_empty(): return + elif stage.begins_with("hud"): + basin_text = _stage_hud() + if basin_text.is_empty(): + return + if stage == "hud_build" and _build_mode(true).is_empty(): + return + _session.hud.fade_feed = false + _session.hud.show_state(_session.hud_state()) _session.view.settle() var others: int = 0 var camera: Camera3D = _session.view.camera @@ -95,6 +107,9 @@ func _ready() -> void: if to.length() < 150.0 and to.normalized().dot(-camera.basis.z) > 0.8: others += 1 var flow: Match = _loop.match_flow + if stage.begins_with("hud"): + _caption("HUD · %s · seed %d · %s%s" % [stage.to_upper(), match_seed, flow.phase_name(), basin_text], Vector2(18.0, 132.0), 15) + return _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, @@ -102,6 +117,53 @@ func _ready() -> void: ] + basin_text) +## Gives the player things to carry and a wound, takes three bots out (one by the +## player's carbine, one drowned, one to the tide), and plays on a second so the client +## hears of it. Returns a caption line, or "" after reporting an error. +func _stage_hud() -> String: + var flow: Match = _loop.match_flow + var sim: Simulation = _loop.sim + var mine: SimEntity = sim.entities.find(int(flow.entity_of.get(_session.link.handle, 0))) + if mine == null or mine.eliminated: + push_error("client capture: the player isn't in the match for the HUD") + return "" + Inventory.give(mine, ItemCatalog.code_of("dock_carbine"), 1, -1, 2) + Inventory.give(mine, ItemCatalog.code_of("fowling_piece"), 1, -1, 0) + Inventory.give(mine, ItemCatalog.code_of("sailcloth_bandage"), 3) + Inventory.give(mine, ItemCatalog.code_of("cartridges"), 45) + Inventory.select(mine, 1) + mine.materials = PackedInt32Array([140, 60, 12]) + mine.health = 64 + mine.armor = 35 + var causes: Array[int] = [SimEntity.CAUSE_WEAPON, SimEntity.CAUSE_DROWN, SimEntity.CAUSE_TIDE] + var taken: int = 0 + for bot: int in flow.bot_handles.keys(): + var player: SimEntity = sim.entities.find(int(flow.entity_of.get(bot, 0))) + if player == null or player.eliminated: + continue + player.health = 0 + player.last_cause = causes[taken] + player.last_attacker = mine.id if causes[taken] == SimEntity.CAUSE_WEAPON else 0 + taken += 1 + for _round: int in 3: + _game.poll() + _loop.run_tick() + _game.after_tick() + _session.pump(DT) + if taken == causes.size(): + break + for _round: int in Tuning.TICK_RATE_HZ: + _game.poll() + _loop.run_tick() + _game.after_tick() + _session.pump(DT) + var hud: HudState = _session.hud_state() + if hud.feed.size() < 3 or not hud.playing or hud.tide.is_empty(): + push_error("client capture: the HUD has %d feed lines, playing %s, tide %s" % [hud.feed.size(), hud.playing, hud.tide]) + return "" + return " · %d of %d standing, %d feed lines" % [hud.standing, hud.total, hud.feed.size()] + + ## Stops the autoplay where the player stands and goes into build mode for a driftwood ## wall, after the server has given the player plenty of materials or taken them all. ## Returns a caption line, or "" after reporting an error. @@ -229,16 +291,16 @@ func _exit_tree() -> void: _net.close() -func _caption(text: String) -> void: +func _caption(text: String, at: Vector2 = Vector2(18.0, 14.0), font_size: int = 20) -> void: var settings: LabelSettings = LabelSettings.new() - settings.font_size = 20 + settings.font_size = font_size 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) + label.position = at var layer: CanvasLayer = CanvasLayer.new() layer.add_child(label) add_child(layer) diff --git a/test/client/test_hud.gd b/test/client/test_hud.gd new file mode 100644 index 0000000..218ef98 --- /dev/null +++ b/test/client/test_hud.gd @@ -0,0 +1,203 @@ +extends TestCase + +## Issue A9: the in-game HUD, the FEED message that tells it who is standing and who +## fell, and HudState, which works out what it shows. + +const FRAME: float = 1.0 / 60.0 + + +func _rules() -> MatchRules: + var rules: MatchRules = MatchRules.new() + rules.max_players = 4 + rules.min_players = 1 + rules.lobby_ticks = 6 + rules.countdown_ticks = 6 + rules.results_ticks = 6 + return rules + + +func test_feed_round_trips() -> void: + var entries: Array[Dictionary] = [ + {"victim": -3, "by": 1, "cause": "weapon", "item": 2, "place": 4, "tied": false, "victim_name": "Thole", "by_name": "Ada"}, + {"victim": 1, "by": 0, "cause": "tide", "item": -1, "place": 3, "tied": true, "victim_name": "Ada", "by_name": ""}, + ] + var told: Dictionary = NetFeed.decode(NetFeed.encode(3, 24, entries)) + assert_eq(told["standing"], 3) + assert_eq(told["total"], 24) + assert_eq(told["entries"].size(), 2) + for index: int in 2: + for key: String in entries[index]: + assert_eq(told["entries"][index][key], entries[index][key], "%s of entry %d" % [key, index]) + + +func test_feed_keeps_only_the_newest_entries_and_cuts_long_names_on_characters() -> void: + var entries: Array[Dictionary] = [] + for index: int in NetFeed.MAX_ENTRIES + 5: + entries.append({"victim": -index - 1, "cause": "drown", "place": 24 - index, "victim_name": "ÆØÅ".repeat(20)}) + var told: Dictionary = NetFeed.decode(NetFeed.encode(1, 24, entries)) + assert_eq(told["entries"].size(), NetFeed.MAX_ENTRIES) + assert_eq(told["entries"][NetFeed.MAX_ENTRIES - 1]["victim"], -(NetFeed.MAX_ENTRIES + 5), "the newest is last") + var name: String = told["entries"][0]["victim_name"] + assert_true(name.to_utf8_buffer().size() <= NetFeed.MAX_NAME_BYTES) + assert_true(name.begins_with("ÆØÅ") and name.length() == NetFeed.MAX_NAME_BYTES / 2, "cut between characters: %s" % name) + + +func test_malformed_feed_is_refused() -> void: + var good: PackedByteArray = NetFeed.encode(2, 4, [{"victim": -1, "cause": "fall", "victim_name": "Kelp"}] as Array[Dictionary]) + assert_false(NetFeed.decode(good).is_empty()) + for cut: int in good.size(): + assert_true(NetFeed.decode(good.slice(0, cut)).is_empty(), "cut at %d" % cut) + var longer: PackedByteArray = good.duplicate() + longer.append(0) + assert_true(NetFeed.decode(longer).is_empty(), "trailing bytes") + var bad_cause: PackedByteArray = good.duplicate() + bad_cause[NetFeed.HEADER_BYTES + 8] = NetFeed.CAUSES.size() + assert_true(NetFeed.decode(bad_cause).is_empty(), "unknown cause") + var many: PackedByteArray = good.duplicate() + many[3] = NetFeed.MAX_ENTRIES + 1 + assert_true(NetFeed.decode(many).is_empty(), "too many entries") + + +func test_feed_lines_are_words_and_name_you() -> void: + var flint: int = ItemCatalog.code_of(String(Tuning.WEAPONS.keys()[1])) + var entries: Array[Dictionary] = [ + {"victim": -2, "by": 1, "cause": "weapon", "item": flint, "victim_name": "Skerry", "by_name": "Ada"}, + {"victim": 1, "by": -4, "cause": "weapon", "item": -1, "victim_name": "Ada", "by_name": "Scupper"}, + {"victim": -5, "by": 0, "cause": "drown", "victim_name": "Cockle"}, + {"victim": -6, "by": 0, "cause": "tide", "victim_name": "Fathom"}, + {"victim": -7, "by": 0, "cause": "left", "victim_name": "Lugworm"}, + {"victim": -8, "by": 0, "cause": "fall", "victim_name": "Pollack"}, + ] + var lines: Array[Dictionary] = HudState.feed_lines(entries, 1) + assert_eq(lines.size(), HudState.FEED_LINES, "only the newest") + assert_eq(lines[0]["text"], "Scupper took you") + assert_true(lines[0]["you"]) + assert_eq(lines[1]["text"], "Cockle drowned") + assert_eq(lines[2]["text"], "The tide took Fathom") + assert_eq(lines[3]["text"], "Lugworm left") + assert_eq(lines[4]["text"], "Pollack fell") + assert_false(lines[4]["you"]) + var first: Array[Dictionary] = HudState.feed_lines(entries.slice(0, 1), 1) + assert_eq(first[0]["text"], "You took Skerry with %s" % HudState.item_name(ItemCatalog.get_def(flint).id).to_lower()) + + +func test_crew_names_are_stable_and_distinct() -> void: + assert_eq(CrewNames.for_bot(-1), CrewNames.NAMES[0]) + var seen: Dictionary = {} + for handle: int in range(-1, -49, -1): + var name: String = CrewNames.for_bot(handle) + assert_false(seen.has(name), "%s used twice" % name) + seen[name] = true + + +func test_offline_client_is_told_who_stands_and_who_fell() -> void: + var game: ClientGame = ClientGame.new() + var local: LocalServer = LocalServer.new(5, 3, _rules()) + for _tick: int in 200: + local.tick(game) + if game.playing(): + break + assert_true(game.playing(), "the match began") + assert_eq(game.match_size, 4) + assert_eq(game.standing, 4) + var flow: Match = local.loop.match_flow + var bot: int = flow.bot_handles.keys()[0] + var bot_player: SimEntity = flow.sim.entities.find(flow.entity_of[bot]) + bot_player.health = 0 + bot_player.last_cause = SimEntity.CAUSE_DROWN + local.tick(game) + assert_eq(game.standing, 3, "told at once") + assert_eq(game.feed.size(), 1) + assert_eq(game.feed[0]["victim"], bot) + assert_eq(game.feed[0]["victim_name"], CrewNames.for_bot(bot)) + assert_eq(game.feed[0]["cause"], "drown") + assert_eq(game.bad_packets, 0) + var state: HudState = HudState.from_client(game, ClientInput.new(), LocalServer.HANDLE) + assert_eq(state.feed[0]["text"], "%s drowned" % CrewNames.for_bot(bot)) + assert_true(state.playing) + assert_eq(state.health, Tuning.PLAYER_MAX_HEALTH) + assert_eq(state.slots.size(), Tuning.INVENTORY_SLOTS + 1, "the boathook and the slots") + assert_true(state.slots[0]["selected"], "the boathook is held at first") + assert_false(state.tide.is_empty()) + assert_eq(state.tide["phase"], 1) + assert_true(state.tide["next"] >= state.tide["sea"]) + + +func test_from_match_reads_the_server_player_and_build_mode() -> void: + var loop: ServerLoop = ServerLoop.new(5, 1, 3, _rules()) + loop.play_humans_by_script() + while not loop.match_flow.in_match(): + loop.run_tick() + for _tick: int in 30: + loop.run_tick() + var flow: Match = loop.match_flow + var handle: int = flow.participants.filter(func(h: int) -> bool: return h > 0)[0] + var me: SimEntity = flow.sim.entities.find(flow.entity_of[handle]) + me.materials[Materials.STONE] = 5 + var state: HudState = HudState.from_match(flow, handle, true, StructureSet.WALL, Materials.STONE) + assert_true(state.playing) + assert_eq(state.build["kind"], "wall") + assert_eq(state.build["material"], "stone") + assert_false(state.build["affordable"], "5 stone isn't a wall") + me.materials[Materials.STONE] = 50 + assert_true(HudState.from_match(flow, handle, true, StructureSet.WALL, Materials.STONE).build["affordable"]) + assert_true(HudState.from_match(flow, handle).build.is_empty(), "not building") + assert_eq(state.standing, 4) + assert_false(is_nan(float(state.tide["feet"]))) + + +func test_hud_shows_only_what_the_state_holds() -> void: + var hud: Hud = Hud.new() + var empty: HudState = HudState.new() + hud.show_state(empty) + assert_eq(_texts(hud), [] as Array[String], "nothing to show before a match") + var state: HudState = HudState.new() + state.playing = true + state.health = 20 + state.armor = 50 + state.standing = 7 + state.total = 24 + state.tide = {"phase": 2, "phases": 6, "stage": Tide.HOLD, "sea": 3.0, "next": 6.5, "rise_in": 42.0, "feet": 4.0} + state.slots = [{"selected": true, "empty": false, "name": "Boathook", "count": 1, "rounds": -1, "reserve": -1, "tier": -1}] as Array[Dictionary] + state.feed = [{"text": "Kelp drowned", "you": false}] as Array[Dictionary] + hud.show_state(state) + var texts: Array[String] = _texts(hud) + assert_true(texts.has("7 of 24 standing"), "%s" % [texts]) + assert_true(texts.has("Kelp drowned")) + assert_true(texts.has("Driftwood 0")) + hud.show_state(empty) + texts = _texts(hud) + assert_false(texts.has("Kelp drowned"), "an empty feed clears the lines") + hud.free() + + +func test_session_shows_a_hud_while_playing_offline() -> void: + var session: ClientSession = ClientSession.new() + session.input.autoplay = true + session._ready() + session.play_offline(2, 3, _rules()) + for _frame: int in 60 * 20: + session.pump(FRAME) + if session.game.playing(): + break + assert_true(session.game.playing()) + var state: HudState = session.hud_state() + assert_true(state.playing) + assert_eq(state.total, 4) + session.hud.show_state(state) + assert_true(_texts(session.hud).has("4 of 4 standing")) + session.free() + + +## The text of every label shown: visible itself and in every parent up to the HUD. +func _texts(node: Node) -> Array[String]: + var found: Array[String] = [] + var item: CanvasItem = node as CanvasItem + if item != null and not item.visible: + return found + var label: Label = node as Label + if label != null: + found.append(label.text) + for child: Node in node.get_children(): + found.append_array(_texts(child)) + return found diff --git a/test/client/test_hud.gd.uid b/test/client/test_hud.gd.uid new file mode 100644 index 0000000..ca092bb --- /dev/null +++ b/test/client/test_hud.gd.uid @@ -0,0 +1 @@ +uid://dd8x7krt170h0 diff --git a/test/net/parser_fuzz.gd b/test/net/parser_fuzz.gd index 35ef07a..c76b39b 100644 --- a/test/net/parser_fuzz.gd +++ b/test/net/parser_fuzz.gd @@ -1,5 +1,5 @@ ## Feeds malformed messages to every parser that reads bytes from the network: the -## handshake, inputs, snapshots, match notices, world and inventory messages, and +## handshake, inputs, snapshots, match notices, world and inventory messages, feeds, and ## discovery, plus the stateful snapshot receiver and the list server's handler. ## Messages are mutations of real ones taken from a running match (bit flips, ## truncation, extension, splices, runs of 0x00 and 0xFF, a different type byte) and @@ -57,6 +57,10 @@ func collect_seeds() -> void: {"kind": NetFx.HARVEST, "tick": 92, "player": 4, "item": -1, "position": Vector3(50.0, 9.0, 60.0), "prop": 12, "piece": 0}, ] as Array[Dictionary])) var command: PlayerCommand = PlayerCommand.from_input(12, Vector2(0.3, 1.0), 1.0, 0.2, PlayerCommand.BUTTON_FIRE, 2, 1) + seeds.append(NetFeed.encode(9, 24, [ + {"victim": -3, "by": 2, "cause": "weapon", "item": 2, "place": 10, "victim_name": "Thole", "by_name": "Fuzzer"}, + {"victim": 2, "by": 0, "cause": "tide", "item": -1, "place": 9, "tied": true, "victim_name": "Fuzzer", "by_name": ""}, + ] as Array[Dictionary])) seeds.append(NetSnapshot.encode_input(40, [command, command] as Array[PlayerCommand])) seeds.append(NetProtocol.encode_hello("Fuzzer")) seeds.append(NetProtocol.encode_welcome(3, 77, 24, "Fuzzer")) @@ -105,7 +109,7 @@ func feed(bytes: PackedByteArray) -> void: var results: Array = [ NetProtocol.decode_hello(bytes), NetProtocol.decode_welcome(bytes), NetProtocol.decode_reject(bytes), NetSnapshot.decode_input(bytes), NetSnapshot.decode_snapshot(bytes), NetSnapshot.decode_match(bytes), - NetWorld.decode_world(bytes), NetWorld.decode_own(bytes), NetFx.decode(bytes), + NetWorld.decode_world(bytes), NetWorld.decode_own(bytes), NetFx.decode(bytes), NetFeed.decode(bytes), NetDiscovery.decode_query(bytes), NetDiscovery.decode_info(bytes), NetDiscovery.decode_register(bytes), NetDiscovery.decode_challenge(bytes), NetDiscovery.decode_list(bytes), ] @@ -157,6 +161,6 @@ func _mutate(bytes: PackedByteArray) -> void: var types: Array[int] = [ NetProtocol.MSG_HELLO, NetProtocol.MSG_WELCOME, NetProtocol.MSG_REJECT, NetSnapshot.MSG_MATCH, NetWorld.MSG_WORLD, NetWorld.MSG_OWN, NetSnapshot.MSG_SNAPSHOT, NetSnapshot.MSG_INPUT, - NetFx.MSG_FX, + NetFx.MSG_FX, NetFeed.MSG_FEED, ] bytes[0] = types[rng.randi_range(0, types.size() - 1)]