space-browser / commits / e7ace75
dev: add a debug mode to improve QA
@@ -5,4 +5,12 @@
55 - Do not confuse the prototypes scope and features with this final implementation design. They were explorations with different objectives.
66 - Start and stop the dev servers only with `./dev-start.sh` and `./dev-stop.sh`. Never run `go run`, `vite` or `npm run dev` directly.
77 - Use `agent-browser` to experience the game from a players point of view.
8+- Drive it through `./tools/agent.sh` (commands in its header): it converts every
9+ target to screen pixels inside the page, so nothing has to guess the camera.
10+- The dev build draws the pointer as a ring of cells and prints `cell / world / px`
11+ plus the thing under it in the top left, because screenshots never contain the
12+ browser cursor. `window.__game` (`cam`, `state`, `toScreen`, `toWorld`,
13+ `targets()`) is the same information for `agent-browser eval`.
14+- `GET :8090/debug/state` returns the pushed state with no client attached
15+ (`you`/`held` are 0): use it to assert what the server did.
816 - Do not add new designs, systems or mechanics without the user asking explicitly.
@@ -7,6 +7,7 @@
77 <style>
88 html, body { margin: 0; height: 100%; background: #0c0803; overflow: hidden; cursor: crosshair; }
99 canvas { display: block; }
10+ #dev { position: fixed; left: 6px; top: 6px; margin: 0; font: 12px ui-monospace, SFMono-Regular, Menlo, monospace; color: #c78a20; pointer-events: none; white-space: pre; }
1011 </style>
1112 </head>
1213 <body>
@@ -1,5 +1,5 @@
11 import { connect, type State } from './net';
2-import type { Loose, Ore, Ship, Shot } from './sim';
2+import { toWorld, type Loose, type Ore, type Ship, type Shot } from './sim';
33 import { View, CELL, CELL_WORLD, ZOOM_MIN, ZOOM_MAX, type Camera } from './view';
44
55 const canvas = document.getElementById('view') as HTMLCanvasElement;
@@ -50,7 +50,120 @@ const at = (e: MouseEvent) => {
5050 };
5151 };
5252
53+// An agent driving this page sees no cursor and cannot know where the camera is,
54+// so it gets the transform the game itself uses, never a copy of it: world point
55+// to screen pixel, screen pixel to world point, and every clickable thing already
56+// converted. It also gets the pointer drawn in cells, because a screenshot cannot
57+// show the browser's own cursor.
58+type Target = {
59+ id: number;
60+ kind: string; // me, ship, piece, loose, ore, or a body kind
61+ owner: number; // the hull a piece belongs to, 0 for anything loose
62+ x: number;
63+ y: number;
64+ px: number;
65+ py: number;
66+ cellX: number;
67+ cellY: number;
68+ cellPx: number; // the centre of that cell: a click lands on a glyph, not between four
69+ cellPy: number;
70+ d: number; // world distance from your hull, nearest first
71+};
72+
73+const canvasBox = () => {
74+ const r = canvas.getBoundingClientRect();
75+ return { left: r.left, top: r.top, width: r.width, height: r.height, cell: CELL, cols: r.width / CELL, rows: r.height / CELL };
76+};
77+const cellOf = (px: number, py: number) => {
78+ const r = canvas.getBoundingClientRect();
79+ return { cellX: Math.floor((px - r.left) / CELL), cellY: Math.floor((py - r.top) / CELL) };
80+};
81+const screen = (x: number, y: number) => {
82+ const r = canvas.getBoundingClientRect();
83+ return { px: r.left + r.width / 2 + (x - cam.x) / wpp(), py: r.top + r.height / 2 - (y - cam.y) / wpp() };
84+};
85+
86+const targets = (): Target[] => {
87+ const me = ships.get(state?.you ?? 0);
88+ const box = canvasBox();
89+ const out: Target[] = [];
90+ const add = (id: number, kind: string, owner: number, x: number, y: number) => {
91+ const s = screen(x, y);
92+ const c = cellOf(s.px, s.py);
93+ out.push({
94+ id,
95+ kind,
96+ owner,
97+ x,
98+ y,
99+ px: s.px,
100+ py: s.py,
101+ ...c,
102+ cellPx: box.left + (c.cellX + 0.5) * CELL,
103+ cellPy: box.top + (c.cellY + 0.5) * CELL,
104+ d: me ? Math.hypot(x - me.x, y - me.y) : 0,
105+ });
106+ };
107+ for (const s of ships.values()) {
108+ add(s.id, s.id === state?.you ? 'me' : 'ship', 0, s.x, s.y);
109+ for (const p of s.pieces) {
110+ const w = toWorld(s, p);
111+ add(p.id, 'piece', s.id, w.x, w.y);
112+ }
113+ }
114+ for (const l of loose.values()) add(l.id, 'loose', 0, l.x, l.y);
115+ for (const o of ore.values()) add(o.id, 'ore', 0, o.x, o.y);
116+ for (const b of state?.bodies ?? []) add(b.id, b.kind, 0, b.x, b.y);
117+ return out.sort((a, b) => a.d - b.d);
118+};
119+
120+let pointer: { px: number; py: number; cellX: number; cellY: number; world: { x: number; y: number } } | null = null;
121+const dev = import.meta.env.DEV; // the bridge and the drawn cursor are for testing only
122+const label = dev ? document.createElement('pre') : null;
123+if (label) {
124+ label.id = 'dev';
125+ document.body.append(label);
126+}
127+
128+// Drawn every move: the reticle in cells, and one line of text spelling out the
129+// cell, the world point and the thing under it.
130+const aim = (e: MouseEvent) => {
131+ const c = cellOf(e.clientX, e.clientY);
132+ const w = at(e);
133+ pointer = { px: e.clientX, py: e.clientY, ...c, world: w };
134+ if (!label) return;
135+ view.setPointer(c.cellX, c.cellY);
136+ const hit = targets().find((t) => t.cellX === c.cellX && t.cellY === c.cellY);
137+ label.textContent =
138+ `cell ${c.cellX},${c.cellY} world ${Math.round(w.x)},${Math.round(w.y)} px ${Math.round(e.clientX)},${Math.round(e.clientY)}` +
139+ (hit ? `\n${hit.kind} ${hit.id}` : '');
140+};
141+
142+const game = {
143+ get cam() {
144+ return { x: cam.x, y: cam.y, zoom: cam.zoom, follow: cam.follow };
145+ },
146+ get state() {
147+ return state;
148+ },
149+ get pointer() {
150+ return pointer;
151+ },
152+ canvas: canvasBox,
153+ cellOf,
154+ toScreen: screen,
155+ toWorld: (px: number, py: number) => at({ clientX: px, clientY: py } as MouseEvent),
156+ targets,
157+};
158+declare global {
159+ interface Window {
160+ __game: typeof game;
161+ }
162+}
163+if (dev) window.__game = game;
164+
53165 addEventListener('pointerdown', (e) => {
166+ aim(e);
54167 if (e.button !== 0) {
55168 pan0 = { x: e.clientX, y: e.clientY };
56169 return;
@@ -61,6 +174,7 @@ addEventListener('pointerdown', (e) => {
61174 });
62175
63176 addEventListener('pointermove', (e) => {
177+ aim(e);
64178 if (pan0) {
65179 pan(-(e.clientX - pan0.x) * wpp(), (e.clientY - pan0.y) * wpp());
66180 pan0 = { x: e.clientX, y: e.clientY };
@@ -198,6 +198,25 @@ function crosshair(): THREE.Group {
198198 return g;
199199 }
200200
201+// The dev cursor: a ring of cells around the pointer cell, one cell per plate. The
202+// browser never paints its own pointer into a screenshot, so the game draws one
203+// that lands on the exact cell a click will resolve to. It is a ring and not a
204+// plus, so it can never be read as the order marker the ship is flying to.
205+function reticle(): THREE.Group {
206+ const g = new THREE.Group();
207+ for (const dx of [-1, 0, 1]) {
208+ for (const dy of [-1, 0, 1]) {
209+ if (!dx && !dy) continue;
210+ const p = plate(0.8, 0.8, 1);
211+ p.material.color.copy(lum(0.85, 6));
212+ p.position.set(dx, dy, 0);
213+ g.add(p);
214+ }
215+ }
216+ g.position.z = 1; // over the fuel gauge
217+ return g;
218+}
219+
201220 const disk = (r: number, v: number, idx: number, x = 0, y = 0): THREE.Mesh => {
202221 const m = new THREE.Mesh(
203222 new THREE.CircleGeometry(r, 48),
@@ -282,6 +301,7 @@ export class View {
282301 private shotMeshes = new Map<number, Part>();
283302 private bodyMeshes = new Map<number, THREE.Group>();
284303 private marker = crosshair();
304+ private cursor = reticle();
285305 private hud = new THREE.Scene();
286306 private hudCam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 100);
287307 private fuelBar = new THREE.Group();
@@ -300,6 +320,8 @@ export class View {
300320 // it hop from one cell to the next.
301321 this.hudCam.position.z = 10;
302322 this.hud.add(this.fuelBar);
323+ this.cursor.visible = false;
324+ this.hud.add(this.cursor);
303325 for (let i = 0; i < FUEL_CELLS; i++) {
304326 const m = plate(1, 1, 1);
305327 this.fuelCells.push(m);
@@ -404,6 +426,14 @@ export class View {
404426 g.rotation.z = h;
405427 }
406428
429+ // The pointer, in cells from the top left corner: one cell is one glyph, so the
430+ // mark sits on the cell the click will resolve to and nowhere between them.
431+ setPointer(cx: number | null, cy = 0): void {
432+ this.cursor.visible = cx !== null;
433+ if (cx === null) return;
434+ this.cursor.position.set(cx - this.cols / 2 + 0.5, this.rows / 2 - cy - 0.5, 1);
435+ }
436+
407437 // The fuel gauge is a row of cells two rows off the bottom of the screen, in a
408438 // layer that only knows about cells. Gold while there is plenty, and a red pulse
409439 // that quickens as the tank empties.
@@ -0,0 +1 @@
1+/// <reference types="vite/client" />
@@ -198,6 +198,7 @@ func main() {
198198 h := newHub()
199199 go h.tick()
200200 http.HandleFunc("/ws", h.handle)
201+ http.HandleFunc("/debug/state", h.debugState)
201202 log.Fatal(http.ListenAndServe(*addr, nil))
202203 }
203204
@@ -927,10 +928,7 @@ func (h *hub) tick() {
927928 for range time.Tick(time.Second / tickRate) {
928929 h.mu.Lock()
929930 h.step(tickDt)
930- players := make([]*player, 0, len(h.clients))
931- for c := range h.clients {
932- players = append(players, c.p)
933- }
931+ players := h.players()
934932 // Marshal under the lock: the state is shared, not copied per client.
935933 out := make(map[*client][]byte, len(h.clients))
936934 for c := range h.clients {
@@ -951,8 +949,31 @@ func (h *hub) tick() {
951949 }
952950 }
953951
952+// The same state the websocket pushes, for a test that only needs to look: no
953+// client, so you and held are zero. The socket stays the only way to act.
954+func (h *hub) debugState(w http.ResponseWriter, r *http.Request) {
955+ h.mu.Lock()
956+ b, err := json.Marshal(state{T: "state", Bodies: h.bodies, Loose: h.loose, Ore: h.ore, Shots: h.shots, Players: h.players()})
957+ h.mu.Unlock()
958+ if err != nil {
959+ http.Error(w, err.Error(), http.StatusInternalServerError)
960+ return
961+ }
962+ w.Header().Set("Content-Type", "application/json")
963+ w.Write(b)
964+}
965+
954966 // ---- lookup ----
955967
968+// Every ship in the world. The caller holds the lock.
969+func (h *hub) players() []*player {
970+ players := make([]*player, 0, len(h.clients))
971+ for c := range h.clients {
972+ players = append(players, c.p)
973+ }
974+ return players
975+}
976+
956977 func (h *hub) body(id int) *body {
957978 for _, b := range h.bodies {
958979 if b.ID == id {
@@ -0,0 +1,173 @@
1+#!/usr/bin/env bash
2+# Agent-facing probe for Space Browser.
3+#
4+# The browser never paints its own cursor, and the world->screen transform only
5+# exists inside the page. So every coordinate below is converted by the page
6+# itself (window.__game, see client/src/main.ts) and nothing here does the maths.
7+# A point this script prints is the point the game will act on.
8+#
9+# ./tools/agent.sh open open the game (only if it is not already up)
10+# ./tools/agent.sh reload reload the page: a brand new player
11+# ./tools/agent.sh state you, held, camera, canvas, ships, bodies, ore
12+# ./tools/agent.sh targets [kind] every clickable thing, nearest first
13+# ./tools/agent.sh move --target ore:41 | --cell 60,30 | --world 120,-40 | --px 636,288
14+# ./tools/agent.sh click --target ore:41
15+# ./tools/agent.sh drag --target ore:41 --to-cell 60,30
16+# ./tools/agent.sh world the same state straight from the server, no browser
17+# ./tools/agent.sh shot out.png screenshot, plus the canvas box it was taken with
18+# ./tools/agent.sh peer a second tab: a second player, for PvP
19+# ./tools/agent.sh tab <n> switch tab
20+set -euo pipefail
21+
22+URL=${URL:-http://localhost:5173}
23+API=${API:-http://localhost:8090}
24+cd "$(dirname "$0")/.."
25+
26+ab() { agent-browser "$@"; }
27+# eval prints the value as JSON: unwrap it so bash sees plain text.
28+js() {
29+ local out
30+ out=$(ab eval "$1")
31+ printf '%s\n' "$out" | jq -r . 2>/dev/null || printf '%s\n' "$out"
32+}
33+
34+ready() { [ "$(ab eval 'typeof window.__game === "object" && window.__game.state ? 1 : 0' 2>/dev/null)" = "1" ]; }
35+
36+ensure() {
37+ ready || ab open "$URL" >/dev/null 2>&1 || true
38+ for _ in $(seq 40); do
39+ ready && return 0
40+ sleep 0.25
41+ done
42+ echo "agent.sh: window.__game never appeared: is ./dev-start.sh running at $URL?" >&2
43+ exit 1
44+}
45+
46+# Resolve one point to "px py", in page coordinates.
47+coords() {
48+ local t="" c="" w="" p=""
49+ while [ $# -gt 0 ]; do
50+ case "$1" in
51+ --target) t=$2; shift 2 ;;
52+ --cell) c=$2; shift 2 ;;
53+ --world) w=$2; shift 2 ;;
54+ --px) p=$2; shift 2 ;;
55+ *) echo "agent.sh: unknown flag $1" >&2; exit 2 ;;
56+ esac
57+ done
58+ [ -n "$t$c$w$p" ] || { echo "agent.sh: give --target, --cell, --world or --px" >&2; exit 2; }
59+ local out
60+ out=$(js "(() => {
61+ const g = window.__game, s = { t: '$t', c: '$c', w: '$w', p: '$p' };
62+ let px, py;
63+ if (s.t) {
64+ const [kind, id] = s.t.split(':');
65+ const h = g.targets().find((x) => x.kind === kind && x.id === Number(id));
66+ if (!h) return 'ERR nothing named ' + s.t + ' on screen; run: agent.sh targets';
67+ px = h.cellPx; py = h.cellPy; // the centre of its cell, not its exact pixel
68+ } else if (s.c) {
69+ const [x, y] = s.c.split(',').map(Number), r = g.canvas();
70+ px = r.left + (x + 0.5) * r.cell; py = r.top + (y + 0.5) * r.cell;
71+ } else if (s.w) {
72+ const [x, y] = s.w.split(',').map(Number), q = g.toScreen(x, y);
73+ px = q.px; py = q.py;
74+ } else {
75+ [px, py] = s.p.split(',').map(Number);
76+ }
77+ return Math.round(px) + ' ' + Math.round(py);
78+ })()")
79+ case "$out" in ERR*) echo "agent.sh: ${out#ERR }" >&2; exit 1 ;; esac
80+ echo "$out"
81+}
82+
83+# point <spec...>: sets PX and PY, or dies with the reason.
84+point() {
85+ local p
86+ p=$(coords "$@")
87+ PX=${p% *}
88+ PY=${p#* }
89+}
90+
91+cmd=${1:-help}
92+shift || true
93+case "$cmd" in
94+ open)
95+ ensure
96+ echo "open $(js 'location.href')"
97+ js "JSON.stringify(window.__game.canvas())"
98+ ;;
99+ reload)
100+ ab open "$URL" >/dev/null
101+ ensure
102+ echo "reloaded $URL"
103+ ;;
104+ state)
105+ ensure
106+ js "JSON.stringify({ you: __game.state.you, held: __game.state.held, cam: __game.cam, canvas: __game.canvas(), ships: __game.state.players, bodies: __game.state.bodies, ore: __game.state.ore, loose: __game.state.loose })"
107+ ;;
108+ targets)
109+ ensure
110+ js "JSON.stringify(__game.targets().filter((t) => !'${1:-}' || t.kind === '${1:-}').map((t) => ({ kind: t.kind, id: t.id, owner: t.owner, cell: t.cellX + ',' + t.cellY, px: Math.round(t.cellPx) + ',' + Math.round(t.cellPy), world: Math.round(t.x) + ',' + Math.round(t.y), d: Math.round(t.d) })))"
111+ ;;
112+ move)
113+ ensure
114+ point "$@"
115+ ab mouse move "$PX" "$PY" >/dev/null
116+ echo "moved to $PX $PY"
117+ ;;
118+ click)
119+ ensure
120+ point "$@"
121+ ab mouse move "$PX" "$PY" >/dev/null
122+ ab mouse down >/dev/null
123+ ab mouse up >/dev/null
124+ echo "clicked $PX $PY"
125+ ;;
126+ drag)
127+ ensure
128+ from=()
129+ to=()
130+ while [ $# -gt 0 ]; do
131+ case "$1" in
132+ --to-cell) to+=(--cell "$2"); shift 2 ;;
133+ --to-world) to+=(--world "$2"); shift 2 ;;
134+ --to-target) to+=(--target "$2"); shift 2 ;;
135+ --to-px) to+=(--px "$2"); shift 2 ;;
136+ *) from+=("$1"); shift ;;
137+ esac
138+ done
139+ [ ${#to[@]} -gt 0 ] || { echo "agent.sh: drag needs --to-cell, --to-world, --to-target or --to-px" >&2; exit 2; }
140+ point "${from[@]}"
141+ fx=$PX fy=$PY
142+ point "${to[@]}"
143+ tx=$PX ty=$PY
144+ ab mouse move "$fx" "$fy" >/dev/null
145+ ab mouse down >/dev/null
146+ for i in 1 2 3; do ab mouse move $((fx + (tx - fx) * i / 3)) $((fy + (ty - fy) * i / 3)) >/dev/null; done
147+ ab mouse up >/dev/null
148+ echo "dragged $fx $fy -> $tx $ty"
149+ ;;
150+ world)
151+ curl -sf "$API/debug/state" | jq -c .
152+ ;;
153+ shot)
154+ ensure
155+ ab screenshot "${1:-shot.png}" >/dev/null
156+ echo "${1:-shot.png}"
157+ js "JSON.stringify({ cam: __game.cam, canvas: __game.canvas() })"
158+ ;;
159+ peer)
160+ ab tab new "$URL" >/dev/null
161+ ensure
162+ echo "second player in a new tab"
163+ ab tab list
164+ ;;
165+ tab)
166+ ab tab "$1" >/dev/null
167+ ensure
168+ echo "tab $1"
169+ ;;
170+ *)
171+ sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//'
172+ ;;
173+esac