Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eef899e015 | ||
|
|
217751f76c | ||
|
|
1924a45c84 | ||
|
|
304e56d6e6 | ||
|
|
ef19d362c6 | ||
|
|
26d7079084 | ||
|
|
013c29e4da | ||
|
|
2b8aa6b233 | ||
|
|
3a7c9af9f2 |
@@ -0,0 +1,8 @@
|
||||
.devbox/
|
||||
nimbledeps/
|
||||
data/tiles/
|
||||
nimble.paths
|
||||
tests/t[a-z]*
|
||||
!tests/*.nim
|
||||
server
|
||||
run/
|
||||
@@ -0,0 +1,32 @@
|
||||
# Notes (feeds README Findings)
|
||||
|
||||
## Geometry edge-case log
|
||||
- BROKE: `cellsTouched` returned nothing for a polygon wholly inside one cell (no edge crosses the cell, no cell corner inside poly). FIX: also hit if a polygon vertex lies in the cell.
|
||||
- Test bug (not code): "shared endpoint" case asserted a point hugging a wall the token stands on line with was hidden; it is legitimately visible. Removed.
|
||||
- Design choices that avoided bugs (all pass first run): rays to each endpoint at -eps/0/+eps (1e-4 rad); ray/segment u-range inclusive with 1e-9 tolerance so no cracks at shared vertices / T-junctions; parallel (collinear) rays skipped since neighbouring +-eps rays cover them; token on an endpoint: that endpoint skipped for ray generation and hits at t<=1e-9 ignored.
|
||||
- Moves: inclusive intersection (touching = blocked) so no squeezing through shared vertices. Limit: token standing exactly on a wall can't move off it; server must keep tokens off walls.
|
||||
- Vision circle = inscribed 64-gon (max error r*(1-cos(pi/64)) ~ 0.12% of r).
|
||||
|
||||
## Layout
|
||||
- Hand-authored (no RNG): reproducible by construction. 6 rooms, 7 corridors, 1 pillar (R1), T-junction (partition at x=3000 in R3 ends mid south wall), collinear split (R3 north wall at x=3200), long thin corridor (R2-R5, 1024x64), doors: R2 west (closed), R5 north (open).
|
||||
|
||||
## Phase 2a (server)
|
||||
- Port 8080 was taken on dev box (docker puma): `PORT=8088 devbox run server|nginx` (sed into run/nginx.conf; server prints invite origin from PORT). Default 8080.
|
||||
- Verified: WS path tricks rejected (webby 400 on %2f/%00); `/_tiles/` 404 when hit directly.
|
||||
- Non-owned move => `error` (not moveAck: server pos of an unseen token would leak).
|
||||
- `by` = "gm"|"A"|"B" (conn role name).
|
||||
- Smoke: `devbox run smoke` (isolated via tools/withserver.sh: server+nginx on 19000/18088, run/test/invites.txt written by server).
|
||||
|
||||
## Phase 3
|
||||
- BUG (client): reconnect did not reset state (stale tokens/explored/sprites); server already resends hello+state on every connect. FIX: reducer resets on `hello`, main.ts clears sprites/masks/doors/pending (tiles kept). Reducer test added.
|
||||
- BUG (client): door click `if (d)` would ignore door id 0. FIX: `!== null`.
|
||||
- Leak scenario bugs were scenario bugs (diagonal steps through walls), not server bugs; server answered `ok:false` as designed.
|
||||
- Leak checker B-string check initially flagged legit `remove{id:"B"}`; exempted token/remove.
|
||||
- Perf finding: cellsTouched (~0.6 ms) is 15x the visibility polygon (~0.04 ms); per-move vision_ms is dominated by explored-cell computation.
|
||||
|
||||
## Post-phase-3 manual-test bug
|
||||
- BUG (server, geometry.nim): `visibilityPolygon` sorted circle-segment angles in [0,2pi) together with wall-endpoint atan2 angles in (-pi,pi] -> fan vertices out of angular order -> bow-tie polygon, even-odd `inside`/`cellsTouched` dropped regions (tokens in plain LOS not shown, explored/tiles missing). Position dependent. FIX: wrap circle angles with atan2(sin,cos).
|
||||
- Why tests missed it: leakcheck recomputed its oracle with the same `visibilityPolygon` (only checked "nothing extra leaks", never "everything visible shows"), and only subject A was checked. Now: independent clear-LOS (segment test) oracle, `SUBJECT=A|B`, geometry regression test.
|
||||
|
||||
## Token radius bug
|
||||
- BUG (server): move validation treated tokens as points; client drew radius 20, so tokens stopped half inside walls/pillar/doors. FIX: `moveBlocked(..., r)` also requires dest circle clear (point-segment dist >= r); `tokenRadius` in scene.json + `hello`. 64 px corridors/doorways leave 12 px slack each side of the centreline. Leak scenario steps adjusted to stop >= r from the closed door/wall.
|
||||
@@ -0,0 +1,92 @@
|
||||
# Server-authoritative vision prototype (throwaway)
|
||||
|
||||
Question: can the server alone decide what each player sees (tokens, fog, map tiles) so a modified client learns nothing hidden? Stack: Nim + mummy (WS/HTTP), SQLite, nginx (static + `X-Accel-Redirect` tiles), Vite + TS + Pixi v8 client.
|
||||
|
||||
## Run (everything through devbox)
|
||||
```
|
||||
devbox run gen # data/scene.json + data/tiles/*.png (deterministic, hand-authored layout)
|
||||
devbox run client # npm install, reducer test, tsc + vite build -> client/dist
|
||||
PORT=8088 devbox run server # :9000 backend, prints invite links, writes run/invites.txt
|
||||
PORT=8088 devbox run nginx # public port; separate terminal
|
||||
```
|
||||
`PORT` (default 8080) is only the public nginx port and the origin printed in invite links. On the dev box 8080 is taken by unrelated docker, hence 8088 in all examples.
|
||||
|
||||
Open the 3 invite links (gm, A, B) each in a **separate browser or profile**. The link sets cookie `sid=<secret>` (HttpOnly, SameSite=Strict) and redirects to `/`; the WS and tile requests authenticate by that cookie. One cookie jar = one identity, so two links in the same profile overwrite each other. Same cookie in two tabs = same player (shared vision, both connections synced).
|
||||
|
||||
Browser rendering was NOT verified (no browser in the build environment): only HTTP/WS behaviour is scripted-tested (served `/`, JS bundle 200, join -> cookie, WS through nginx, tiles).
|
||||
|
||||
## Tests
|
||||
| cmd | what |
|
||||
|---|---|
|
||||
| `devbox run test` | regen map + `nimble test` (geometry: visibility, moves, cells, seed sanity) |
|
||||
| `devbox run client` | includes client reducer test (`npm run check`, incl. reconnect reset) |
|
||||
| `devbox run smoke` | fresh DB, server+nginx, auth/cookie/tile/steal/garbage checks |
|
||||
| `devbox run leaktest` | runs twice (SUBJECT=A, SUBJECT=B), fresh DB each; subject walks ~240 steps through rooms, corridor, open/closed doors while GM + B act; Nim checker (`tools/leakcheck.nim`) replays `run/leak-transcript.jsonl` |
|
||||
| `devbox run concurrency` | 60 s (`DUR=` secs) A, B, GM(6 monsters + doors) at 20-50 ms per token |
|
||||
| `devbox run bench` | vision microbench |
|
||||
|
||||
Tests are isolated: `tools/withserver.sh` uses `run/test/` (own DB, invites, nginx conf/logs) and ports 18088 (nginx) / 19000 (server), overridable via `TEST_PORT`/`TEST_BACKEND_PORT`; the live session on 8088/9000 and `run/` are never touched. Server stats print on stop into `run/test/server.log`.
|
||||
|
||||
### Leak test asserts
|
||||
Ground truth = GM socket (tokens + doors per gseq). A's expected vision/explored is recomputed with `geometry.nim`, never from A's own messages. Per gseq:
|
||||
- (a) A receives only hello/vision/explored/token/remove/moveAck; no wall-like keys (walls, door, open, a, b, segments...) anywhere.
|
||||
- (b) every token A is sent is inside the independently computed polygon (0.5 px boundary tolerance); every token inside it IS in A's view (completeness); view positions == truth; A's `vision` polygon equals the recomputed one (1e-6); A's explored set == recomputed set.
|
||||
- (c) `remove` arrives when a token leaves; scenario must show M1, M2, M5, B and >= 3 removes.
|
||||
- (d) 256 tiles requested at 40+ points (10240 requests, incl. unexplored): 200 iff an explored cell touches the tile at that gseq, else 403.
|
||||
- (e) A never gets B-bound info: no B string outside token/remove, no `by:B` on others' tokens, hello tokens == ["A"], no error msgs.
|
||||
Negative control done once by hand: injecting an out-of-vision token / a 200 for an unexplored tile into the transcript is flagged.
|
||||
|
||||
Result: PASS (220 gseq groups, 465 A msgs, 4 other tokens seen, 6 removes, tiles 1792 x 200 / 8448 x 403, 2163 explored cells, 0 failures).
|
||||
|
||||
### Concurrency result (60 s, PASS)
|
||||
Load was ~225 intents/s (A 28, B 28, 6 monsters 169) + door toggles every 1-3 s. 13876 mutations, no crash, 0 errors, gseq never went backwards at any client (non-decreasing; messages of one mutation share a gseq), every intent acked (sent == acks for all 3 clients), and after quiesce each client's tokens/doors/vision/explored == a fresh connection's snapshot.
|
||||
|
||||
## Measurements (laptop, release build, localhost)
|
||||
| metric | avg | p95 | worst |
|
||||
|---|---|---|---|
|
||||
| vision recompute per player move (server, incl. cellsTouched + diff) | 0.75 ms | - | 2.6 ms |
|
||||
| vision recompute per monster move | 0.000 ms (no vision) | - | 0.005 ms |
|
||||
| door toggle (2 roles) | 0.10 ms | - | 0.15 ms |
|
||||
| bench: 1 visibility polygon | 0.036 ms | - | 0.13 ms |
|
||||
| bench: 6 polygons | 0.20 ms | - | 0.29 ms |
|
||||
| bench: 1 poly + cellsTouched | 0.67 ms | - | 1.8 ms |
|
||||
| bench: 6 polys + cellsTouched | 4.7 ms | - | 7.3 ms |
|
||||
| latency intent -> ack (sender, via nginx) | 0.92 ms | 1.98 ms | 13.9 ms |
|
||||
| latency intent -> arrival at other clients | 1.26 ms | 2.37 ms | 11.2 ms |
|
||||
|
||||
Bytes per delivery (only recipients that got something):
|
||||
| mutation | recipient | avg B |
|
||||
|---|---|---|
|
||||
| monster move | GM | 243 |
|
||||
| monster move | player who sees it | 147 |
|
||||
| player move | the mover (ack + token + new `vision` + `explored` diff) | 3470-3710 (worst 5.0 KB) |
|
||||
| player move | GM | 144 |
|
||||
| door toggle | GM | 44 |
|
||||
|
||||
"6 moving tokens" with vision: monsters have none in this design, so the 6-token case is the bench (a 6-token party in one role = 6 polys per recompute: 0.2 ms polys, 4.7 ms with cell marking). Concurrency exercised 6 simultaneously moving monsters (no vision cost) + 2 players.
|
||||
|
||||
## Findings
|
||||
**Worked**
|
||||
- Server-only filtering is simple under one global lock: validate -> mutate -> recompute -> persist -> per-connection diff -> send. Players never receive walls/doors/other tokens; leak test finds nothing.
|
||||
- Per-connection `known` map gives correct enter/leave (`token`/`remove`) and a fresh connection gets full state; clients reset on `hello`.
|
||||
- Token radius `tokenRadius` (20 px, data/scene.json via tools/genmap.mjs) is server-authoritative and sent in `hello` (client falls back to 20 if absent). A move is accepted only if the centre path crosses no blocking wall AND the destination circle is >= r from every blocking wall (open doors ignored). Only the destination is checked, so a token already overlapping a wall (closed door, legacy DB) can leave. Vision origin stays the token centre.
|
||||
- Tile gating via nginx `internal` + `X-Accel-Redirect` after Nim checks explored cells; `/_tiles/` unreachable directly.
|
||||
- Moves: inclusive segment test blocks squeezing through shared vertices; non-owned/malformed moves get `error` (not an ack, an ack would echo the position of an unseen token).
|
||||
|
||||
**Edge cases that broke (see NOTES.md)**: `cellsTouched` missed polygons wholly inside one cell (fix: vertex-in-cell test); client did not reset on reconnect (fix: reset on `hello`); door id 0 falsy check; leak scenario steps crossing walls diagonally (scenario bug, server correctly refused).
|
||||
|
||||
**mummy suitability**
|
||||
- Send is thread-safe by construction: `WebSocket.send` appends the encoded frame to one server-wide deque under `sendQueueLock` and triggers the IO thread (mummy.nim ~L262-311); the IO thread drains it. Per-socket events are serialized by mummy. Because we also send while holding our own lock, per-socket order == gseq order, so no separate broadcaster was needed. 60 s of mixed 3-client load, ~14k mutations, ~40k messages: no crash, no reorder, no loss, consistent final views.
|
||||
- Caveats: `WebSocket` has no `==`/hash, we key a table by its raw bytes (shortcut, works while it is one pointer-sized ref). Everything is serialized by one lock, so throughput is single-core bound (fine here: ~1 ms/move). Sending under the lock is cheap (queue push) but a slow client cannot block it; there is no backpressure/limit on a slow client's queue (memory grows).
|
||||
- Pinned to an exact commit (no tags upstream).
|
||||
|
||||
**Worries for a real VTT**
|
||||
- Vision is O(rays x walls) per token (culled only by bbox); needs a spatial grid for big maps. cellsTouched (O(bbox cells x poly edges)) is ~15x costlier than the polygon itself and dominates.
|
||||
- Explored grid: 128x128 cells here; explored set sent whole on connect, kept in memory + one SQLite row per cell. Larger maps need run-length/bitmap + per-tile summaries.
|
||||
- Full `vision` polygon resent on each player move (~3.3 KB of the ~3.5 KB); needs deltas or lower-res polygons.
|
||||
- Cookie = the secret (bearer, no rotation/expiry); invite links in logs/URLs are credentials. HTTPS needed beyond localhost.
|
||||
- Tiles do not update when a door changes (static art; only fog changes); a revealed tile stays visible forever and leaks the whole tile (256 px), not just the explored cells; tile granularity vs exploredCell is a leak/size tradeoff.
|
||||
- Polygon boundary epsilon: ray nudges (1e-4 rad) and inclusive tolerances; tokens right on the boundary are ambiguous (tests use a 0.5 px tolerance). A token standing exactly on a wall cannot move off it; server must keep tokens off walls.
|
||||
- Fog masks are Graphics that grow unbounded (explored rects re-tessellated); needs baking to a RenderTexture. Pixi `Text` per token is heavy vs `BitmapText` at scale.
|
||||
- Browser rendering (fog masks, drag, reconnect visuals) is unverified: only the reducer and HTTP/WS paths were tested.
|
||||
- Timing trusts a single machine/loopback; latencies exclude real network and client render.
|
||||
@@ -0,0 +1,2 @@
|
||||
node_modules/
|
||||
dist/
|
||||
@@ -0,0 +1,6 @@
|
||||
<!doctype html>
|
||||
<meta charset="utf-8"><title>servervision</title>
|
||||
<style>html,body{margin:0;height:100%;overflow:hidden;background:#000}
|
||||
#bar{position:fixed;top:0;left:0;right:0;padding:2px 8px;font:12px monospace;color:#0f0;background:#000a;z-index:1;pointer-events:none}</style>
|
||||
<div id="bar"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
+1314
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "servervision-client",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc && vite build",
|
||||
"check": "node --test src/state.test.ts"
|
||||
},
|
||||
"dependencies": { "pixi.js": "^8.0.0" },
|
||||
"devDependencies": { "typescript": "^5.6.0", "vite": "^6.0.0", "@types/node": "^22.0.0" }
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import { Application, Container, Graphics, Sprite, Text, Texture } from 'pixi.js';
|
||||
import { apply, newState, tilesOfCells, type Tok, type V2 } from './state.ts';
|
||||
|
||||
const s = newState();
|
||||
const bar = document.getElementById('bar')!;
|
||||
let conn = 'connecting';
|
||||
// identity from hello.tokens: a player owns only the token whose id is their slot ("A"/"B")
|
||||
const who = () => (s.role === 'player' ? `player ${s.owned[0] ?? '?'}` : s.role ?? '?');
|
||||
const status = () => (bar.textContent = `${who()} conn=${conn} gseq=${s.gseq}${s.lastError ? ' err=' + s.lastError : ''}`);
|
||||
|
||||
const app = new Application();
|
||||
await app.init({ resizeTo: window, background: 0x000000, antialias: true });
|
||||
document.body.appendChild(app.canvas);
|
||||
|
||||
const world = new Container();
|
||||
const tilesL = new Container();
|
||||
const doorsG = new Graphics();
|
||||
const tokensL = new Container();
|
||||
// Fog: dim = everywhere except current vision; black = everywhere except explored. Inverse stencil masks.
|
||||
const dim = new Graphics();
|
||||
const black = new Graphics();
|
||||
const visionM = new Graphics();
|
||||
const exploredM = new Graphics();
|
||||
dim.addChild(visionM); dim.setMask({ mask: visionM, inverse: true });
|
||||
black.addChild(exploredM); black.setMask({ mask: exploredM, inverse: true });
|
||||
world.addChild(tilesL, dim, black, doorsG, tokensL);
|
||||
app.stage.addChild(world);
|
||||
|
||||
// ---- tiles ----
|
||||
const tileState = new Map<string, 'loading' | 'ok' | 'fail'>();
|
||||
function loadTile(key: string) {
|
||||
if (tileState.has(key) && tileState.get(key) !== 'fail') return;
|
||||
tileState.set(key, 'loading');
|
||||
fetch(`/tiles/${key}.png`)
|
||||
.then((r) => (r.ok ? r.blob() : Promise.reject(r.status))) // 403 = not available (yet)
|
||||
.then((b) => createImageBitmap(b))
|
||||
.then((bmp) => {
|
||||
const [x, y] = key.split('_').map(Number);
|
||||
const sp = new Sprite(Texture.from(bmp));
|
||||
sp.position.set(x * s.tileSize, y * s.tileSize);
|
||||
tilesL.addChild(sp);
|
||||
tileState.set(key, 'ok');
|
||||
})
|
||||
.catch(() => tileState.set(key, 'fail'));
|
||||
}
|
||||
|
||||
// ---- tokens ----
|
||||
const sprites = new Map<string, Container>();
|
||||
const dragging = new Map<string, true>();
|
||||
function drawToken(t: Tok) {
|
||||
let c = sprites.get(t.id);
|
||||
if (!c) {
|
||||
c = new Container();
|
||||
const g = new Graphics().circle(0, 0, s.tokenR).fill(t.mine ? 0x3a9d3a : 0xb03030).stroke({ width: 3, color: 0xffffff });
|
||||
const l = new Text({ text: t.name, style: { fontSize: 14, fill: 0xffffff, stroke: { color: 0, width: 3 } } });
|
||||
l.anchor.set(0.5, 0); l.y = s.tokenR + 2;
|
||||
c.addChild(g, l);
|
||||
tokensL.addChild(c); sprites.set(t.id, c);
|
||||
}
|
||||
if (!dragging.has(t.id)) c.position.set(t.pos[0], t.pos[1]); // incoming pos ignored while locally dragging
|
||||
}
|
||||
const canDrag = (t: Tok) => s.role === 'gm' || t.mine;
|
||||
|
||||
// ---- ws ----
|
||||
let ws: WebSocket;
|
||||
const send = (o: object) => ws.readyState === 1 && ws.send(JSON.stringify(o));
|
||||
let reqId = 0;
|
||||
const pending = new Map<number, string>();
|
||||
|
||||
function onMsg(m: any) {
|
||||
if (m.t === 'moveAck') {
|
||||
const id = pending.get(m.reqId); pending.delete(m.reqId);
|
||||
if (!m.ok && id && !dragging.has(id)) { // snap to server pos
|
||||
const t = s.tokens.get(id), c = sprites.get(id);
|
||||
if (t) t.pos = m.pos;
|
||||
c?.position.set(m.pos[0], m.pos[1]);
|
||||
}
|
||||
s.gseq = m.gseq;
|
||||
return;
|
||||
}
|
||||
const fresh = apply(s, m);
|
||||
switch (m.t) {
|
||||
case 'hello':
|
||||
for (const c of sprites.values()) c.destroy({ children: true });
|
||||
sprites.clear(); pending.clear(); visionM.clear(); exploredM.clear(); doorsG.clear(); // tiles kept: explored only grows
|
||||
fit();
|
||||
if (s.role === 'gm') { dim.visible = black.visible = false; const n = Math.ceil(s.w / s.tileSize), k = Math.ceil(s.h / s.tileSize); for (let y = 0; y < k; y++) for (let x = 0; x < n; x++) loadTile(x + '_' + y); }
|
||||
else { for (const g of [dim, black]) g.clear().rect(0, 0, s.w, s.h).fill(0x000000); dim.alpha = 0.6; }
|
||||
break;
|
||||
case 'walls': case 'door': drawDoors(); break;
|
||||
case 'vision':
|
||||
visionM.clear();
|
||||
for (const p of s.polys) visionM.poly(p.flat()).fill(0xffffff);
|
||||
break;
|
||||
case 'explored':
|
||||
if (fresh!.length) {
|
||||
for (const [cx, cy] of fresh!) exploredM.rect(cx * s.cell, cy * s.cell, s.cell, s.cell);
|
||||
exploredM.fill(0xffffff); // shortcut: Graphics grows unbounded, re-tessellates; bake to RenderTexture when cells >~50k
|
||||
// retry failed/unrequested tiles under newly explored cells
|
||||
for (const k of tilesOfCells(fresh!, s)) loadTile(k);
|
||||
}
|
||||
break;
|
||||
case 'token': drawToken(s.tokens.get(m.id)!); break;
|
||||
case 'remove': sprites.get(m.id)?.destroy({ children: true }); sprites.delete(m.id); break;
|
||||
}
|
||||
}
|
||||
function connect() {
|
||||
ws = new WebSocket(`${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/ws`);
|
||||
ws.onopen = () => { conn = 'open'; status(); };
|
||||
ws.onclose = () => { conn = 'closed (retry 2s)'; status(); setTimeout(connect, 2000); }; // state reset on hello; server resends everything
|
||||
ws.onmessage = (e) => { onMsg(JSON.parse(e.data)); status(); };
|
||||
}
|
||||
|
||||
// ---- walls (GM only) ----
|
||||
function drawDoors() {
|
||||
doorsG.clear();
|
||||
for (const w of s.walls.values()) {
|
||||
doorsG.moveTo(...w.a).lineTo(...w.b).stroke({ width: w.door ? 6 : 3, color: w.door ? (w.open ? 0x40ff40 : 0xff4040) : 0xffff00 });
|
||||
}
|
||||
}
|
||||
function pickDoor(p: V2): string | null {
|
||||
const tol = 10 / world.scale.x;
|
||||
for (const w of s.walls.values()) {
|
||||
if (!w.door) continue;
|
||||
const [ax, ay] = w.a, [bx, by] = w.b, dx = bx - ax, dy = by - ay;
|
||||
const u = Math.max(0, Math.min(1, ((p[0] - ax) * dx + (p[1] - ay) * dy) / (dx * dx + dy * dy || 1)));
|
||||
if (Math.hypot(p[0] - (ax + u * dx), p[1] - (ay + u * dy)) < tol) return w.id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---- camera + input ----
|
||||
function fit() { const k = Math.min(innerWidth / s.w, innerHeight / s.h); world.scale.set(k); world.position.set(0, 0); }
|
||||
const toWorld = (e: PointerEvent | WheelEvent): V2 => [(e.clientX - world.x) / world.scale.x, (e.clientY - world.y) / world.scale.x];
|
||||
let pan: { x: number; y: number } | null = null;
|
||||
let drag: { id: string; dx: number; dy: number; last: number } | null = null;
|
||||
const moveTok = (id: string, pos: V2) => { const r = ++reqId; pending.set(r, id); send({ t: 'move', reqId: r, id, pos }); };
|
||||
const cv = app.canvas;
|
||||
cv.addEventListener('pointerdown', (e) => {
|
||||
cv.setPointerCapture(e.pointerId);
|
||||
const p = toWorld(e);
|
||||
for (const [id, c] of [...sprites].reverse()) { // O(N) hit test on press
|
||||
const t = s.tokens.get(id)!;
|
||||
if (canDrag(t) && Math.hypot(p[0] - c.x, p[1] - c.y) <= s.tokenR) { drag = { id, dx: c.x - p[0], dy: c.y - p[1], last: 0 }; dragging.set(id, true); return; }
|
||||
}
|
||||
if (s.role === 'gm') { const d = pickDoor(p); if (d !== null) { send({ t: 'door', id: d, open: !s.walls.get(d)!.open }); return; } }
|
||||
pan = { x: e.clientX - world.x, y: e.clientY - world.y };
|
||||
});
|
||||
cv.addEventListener('pointermove', (e) => {
|
||||
if (drag) {
|
||||
const p = toWorld(e), pos: V2 = [p[0] + drag.dx, p[1] + drag.dy];
|
||||
sprites.get(drag.id)!.position.set(pos[0], pos[1]); // optimistic
|
||||
const now = performance.now();
|
||||
if (now - drag.last >= 50) { drag.last = now; moveTok(drag.id, pos); }
|
||||
} else if (pan) world.position.set(e.clientX - pan.x, e.clientY - pan.y);
|
||||
});
|
||||
const up = () => {
|
||||
if (drag) {
|
||||
const c = sprites.get(drag.id)!, pos: V2 = [c.x, c.y];
|
||||
moveTok(drag.id, pos); // final
|
||||
const t = s.tokens.get(drag.id); if (t) t.pos = pos;
|
||||
dragging.delete(drag.id); drag = null;
|
||||
}
|
||||
pan = null;
|
||||
};
|
||||
cv.addEventListener('pointerup', up); cv.addEventListener('pointercancel', up);
|
||||
cv.addEventListener('wheel', (e) => {
|
||||
e.preventDefault();
|
||||
const p = toWorld(e), k = Math.max(0.05, Math.min(8, world.scale.x * Math.exp(-e.deltaY * 0.001)));
|
||||
world.scale.set(k); world.position.set(e.clientX - p[0] * k, e.clientY - p[1] * k);
|
||||
}, { passive: false });
|
||||
|
||||
status();
|
||||
connect();
|
||||
@@ -0,0 +1,47 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { apply, newState, tilesOfCells } from './state.ts';
|
||||
|
||||
test('protocol reducer: fake server script', () => {
|
||||
const s = newState();
|
||||
apply(s, { t: 'hello', gseq: 1, role: 'player', tokens: ['a'], world: { w: 4096, h: 4096 }, tileSize: 512, exploredCell: 64 });
|
||||
assert.equal(s.role, 'player');
|
||||
assert.equal(s.walls.size, 0); // players never get walls
|
||||
assert.deepEqual(apply(s, { t: 'explored', gseq: 2, cells: [[0, 0], [1, 0]] }), [[0, 0], [1, 0]]);
|
||||
assert.deepEqual(apply(s, { t: 'explored', gseq: 3, cells: [[1, 0], [2, 0]] }), [[2, 0]]); // diff accumulates
|
||||
assert.equal(s.explored.size, 3);
|
||||
apply(s, { t: 'vision', gseq: 4, polys: [[[0, 0], [1, 0], [1, 1]]] });
|
||||
apply(s, { t: 'vision', gseq: 5, polys: [] });
|
||||
assert.equal(s.polys.length, 0); // full replacement
|
||||
apply(s, { t: 'token', gseq: 6, id: 'a', name: 'A', kind: 'pc', pos: [5, 6], mine: true });
|
||||
apply(s, { t: 'token', gseq: 7, id: 'a', name: 'A', kind: 'pc', pos: [7, 8], mine: true });
|
||||
assert.deepEqual(s.tokens.get('a')!.pos, [7, 8]);
|
||||
apply(s, { t: 'remove', gseq: 8, id: 'a' });
|
||||
assert.equal(s.tokens.size, 0);
|
||||
assert.equal(s.gseq, 8);
|
||||
});
|
||||
|
||||
test('gm walls + door', () => {
|
||||
const s = newState();
|
||||
apply(s, { t: 'walls', gseq: 1, walls: [{ id: 'd1', a: [0, 0], b: [10, 0], door: true, open: false }] });
|
||||
apply(s, { t: 'door', gseq: 2, id: 'd1', open: true });
|
||||
assert.equal(s.walls.get('d1')!.open, true);
|
||||
});
|
||||
|
||||
test('tilesOfCells', () => {
|
||||
const g = { w: 4096, h: 4096, tileSize: 512, cell: 64 };
|
||||
assert.deepEqual([...tilesOfCells([[0, 0], [7, 7]], g)], ['0_0']);
|
||||
assert.deepEqual([...tilesOfCells([[8, 0]], g)], ['1_0']);
|
||||
assert.deepEqual([...tilesOfCells([[0, 0]], { ...g, cell: 1024 })].length, 4); // cell spans 2x2 tiles
|
||||
});
|
||||
|
||||
test('hello resets state (reconnect)', () => {
|
||||
const s = newState();
|
||||
apply(s, { t: 'hello', gseq: 1, role: 'player', tokens: ['a'], world: { w: 4096, h: 4096 }, tileSize: 512, exploredCell: 64 });
|
||||
apply(s, { t: 'token', gseq: 2, id: 'a', name: 'A', kind: 'pc', pos: [5, 6], mine: true });
|
||||
apply(s, { t: 'explored', gseq: 3, cells: [[0, 0]] });
|
||||
apply(s, { t: 'hello', gseq: 9, role: 'player', tokens: ['a'], world: { w: 4096, h: 4096 }, tileSize: 512, exploredCell: 64 });
|
||||
assert.equal(s.tokens.size, 0);
|
||||
assert.equal(s.explored.size, 0);
|
||||
assert.equal(s.gseq, 9);
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
// Pure protocol state + reducer (no Pixi) so it can be checked without a server.
|
||||
export type V2 = [number, number];
|
||||
export type Tok = { id: string; name: string; kind: string; pos: V2; mine: boolean };
|
||||
export type Wall = { id: string; a: V2; b: V2; door: boolean; open: boolean };
|
||||
export type Msg = { t: string; gseq: number; [k: string]: any };
|
||||
|
||||
export type State = {
|
||||
role: 'gm' | 'player' | null;
|
||||
owned: string[];
|
||||
w: number; h: number; tileSize: number; cell: number; tokenR: number;
|
||||
walls: Map<string, Wall>;
|
||||
polys: V2[][];
|
||||
explored: Set<string>;
|
||||
tokens: Map<string, Tok>;
|
||||
gseq: number;
|
||||
lastError: string;
|
||||
};
|
||||
|
||||
export const newState = (): State => ({
|
||||
role: null, owned: [], w: 0, h: 0, tileSize: 512, cell: 32, tokenR: 20,
|
||||
walls: new Map(), polys: [], explored: new Set(), tokens: new Map(), gseq: 0, lastError: '',
|
||||
});
|
||||
|
||||
// Returns newly-added explored cells (only for t=explored), else undefined.
|
||||
export function apply(s: State, m: Msg): V2[] | undefined {
|
||||
s.gseq = m.gseq;
|
||||
switch (m.t) {
|
||||
case 'hello': // server resends full state after hello: start clean (reconnect)
|
||||
Object.assign(s, newState(), { gseq: m.gseq });
|
||||
s.role = m.role; s.owned = m.tokens; s.w = m.world.w; s.h = m.world.h;
|
||||
s.tileSize = m.tileSize; s.cell = m.exploredCell; s.tokenR = m.tokenRadius ?? s.tokenR; // ?? : older server omits it
|
||||
break;
|
||||
case 'walls':
|
||||
s.walls = new Map((m.walls as Wall[]).map((w) => [w.id, w]));
|
||||
break;
|
||||
case 'door': {
|
||||
const w = s.walls.get(m.id);
|
||||
if (w) w.open = m.open;
|
||||
break;
|
||||
}
|
||||
case 'vision': s.polys = m.polys; break;
|
||||
case 'explored': {
|
||||
const fresh: V2[] = [];
|
||||
for (const c of m.cells as V2[]) {
|
||||
const k = c[0] + ',' + c[1];
|
||||
if (!s.explored.has(k)) { s.explored.add(k); fresh.push(c); }
|
||||
}
|
||||
return fresh;
|
||||
}
|
||||
case 'token':
|
||||
s.tokens.set(m.id, { id: m.id, name: m.name, kind: m.kind, pos: m.pos, mine: !!m.mine });
|
||||
break;
|
||||
case 'remove': s.tokens.delete(m.id); break;
|
||||
case 'error': s.lastError = m.msg; break;
|
||||
// moveAck handled by the view (needs pending/drag state)
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Tile keys "x_y" overlapped by the given explored cells.
|
||||
export function tilesOfCells(cells: V2[], s: Pick<State, 'w' | 'h' | 'tileSize' | 'cell'>): Set<string> {
|
||||
const out = new Set<string>();
|
||||
const maxX = Math.ceil(s.w / s.tileSize) - 1, maxY = Math.ceil(s.h / s.tileSize) - 1;
|
||||
for (const [cx, cy] of cells) {
|
||||
const x0 = Math.floor((cx * s.cell) / s.tileSize), x1 = Math.floor(((cx + 1) * s.cell - 1) / s.tileSize);
|
||||
const y0 = Math.floor((cy * s.cell) / s.tileSize), y1 = Math.floor(((cy + 1) * s.cell - 1) / s.tileSize);
|
||||
for (let y = Math.max(0, y0); y <= Math.min(maxY, y1); y++)
|
||||
for (let x = Math.max(0, x0); x <= Math.min(maxX, x1); x++) out.add(x + '_' + y);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022", "module": "ESNext", "moduleResolution": "bundler",
|
||||
"lib": ["ES2022", "DOM"], "strict": true, "noEmit": true, "skipLibCheck": true,
|
||||
"allowImportingTsExtensions": true, "erasableSyntaxOnly": true, "types": ["node"]
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export default { base: './', build: { target: 'es2022' } };
|
||||
@@ -0,0 +1,954 @@
|
||||
{
|
||||
"world": {
|
||||
"w": 4096,
|
||||
"h": 4096
|
||||
},
|
||||
"tileSize": 256,
|
||||
"visionRadius": 400,
|
||||
"tokenRadius": 20,
|
||||
"exploredCell": 32,
|
||||
"walls": [
|
||||
{
|
||||
"id": 0,
|
||||
"a": [
|
||||
256,
|
||||
256
|
||||
],
|
||||
"b": [
|
||||
1024,
|
||||
256
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 1,
|
||||
"a": [
|
||||
256,
|
||||
1024
|
||||
],
|
||||
"b": [
|
||||
608,
|
||||
1024
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"a": [
|
||||
672,
|
||||
1024
|
||||
],
|
||||
"b": [
|
||||
1024,
|
||||
1024
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"a": [
|
||||
256,
|
||||
256
|
||||
],
|
||||
"b": [
|
||||
256,
|
||||
1024
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"a": [
|
||||
1024,
|
||||
256
|
||||
],
|
||||
"b": [
|
||||
1024,
|
||||
608
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"a": [
|
||||
1024,
|
||||
672
|
||||
],
|
||||
"b": [
|
||||
1024,
|
||||
1024
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"a": [
|
||||
1536,
|
||||
256
|
||||
],
|
||||
"b": [
|
||||
2304,
|
||||
256
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"a": [
|
||||
1536,
|
||||
1024
|
||||
],
|
||||
"b": [
|
||||
1888,
|
||||
1024
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"a": [
|
||||
1952,
|
||||
1024
|
||||
],
|
||||
"b": [
|
||||
2304,
|
||||
1024
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"a": [
|
||||
1536,
|
||||
256
|
||||
],
|
||||
"b": [
|
||||
1536,
|
||||
608
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"a": [
|
||||
1536,
|
||||
608
|
||||
],
|
||||
"b": [
|
||||
1536,
|
||||
672
|
||||
],
|
||||
"door": true,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"a": [
|
||||
1536,
|
||||
672
|
||||
],
|
||||
"b": [
|
||||
1536,
|
||||
1024
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"a": [
|
||||
2304,
|
||||
256
|
||||
],
|
||||
"b": [
|
||||
2304,
|
||||
608
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 13,
|
||||
"a": [
|
||||
2304,
|
||||
672
|
||||
],
|
||||
"b": [
|
||||
2304,
|
||||
1024
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 14,
|
||||
"a": [
|
||||
2816,
|
||||
256
|
||||
],
|
||||
"b": [
|
||||
3200,
|
||||
256
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 15,
|
||||
"a": [
|
||||
2816,
|
||||
1024
|
||||
],
|
||||
"b": [
|
||||
3168,
|
||||
1024
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 16,
|
||||
"a": [
|
||||
3232,
|
||||
1024
|
||||
],
|
||||
"b": [
|
||||
3584,
|
||||
1024
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 17,
|
||||
"a": [
|
||||
2816,
|
||||
256
|
||||
],
|
||||
"b": [
|
||||
2816,
|
||||
608
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 18,
|
||||
"a": [
|
||||
2816,
|
||||
672
|
||||
],
|
||||
"b": [
|
||||
2816,
|
||||
1024
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 19,
|
||||
"a": [
|
||||
3584,
|
||||
256
|
||||
],
|
||||
"b": [
|
||||
3584,
|
||||
1024
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 20,
|
||||
"a": [
|
||||
256,
|
||||
2048
|
||||
],
|
||||
"b": [
|
||||
608,
|
||||
2048
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 21,
|
||||
"a": [
|
||||
672,
|
||||
2048
|
||||
],
|
||||
"b": [
|
||||
1024,
|
||||
2048
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 22,
|
||||
"a": [
|
||||
256,
|
||||
2816
|
||||
],
|
||||
"b": [
|
||||
1024,
|
||||
2816
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 23,
|
||||
"a": [
|
||||
256,
|
||||
2048
|
||||
],
|
||||
"b": [
|
||||
256,
|
||||
2816
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 24,
|
||||
"a": [
|
||||
1024,
|
||||
2048
|
||||
],
|
||||
"b": [
|
||||
1024,
|
||||
2400
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 25,
|
||||
"a": [
|
||||
1024,
|
||||
2464
|
||||
],
|
||||
"b": [
|
||||
1024,
|
||||
2816
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 26,
|
||||
"a": [
|
||||
1536,
|
||||
2048
|
||||
],
|
||||
"b": [
|
||||
1888,
|
||||
2048
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 27,
|
||||
"a": [
|
||||
1888,
|
||||
2048
|
||||
],
|
||||
"b": [
|
||||
1952,
|
||||
2048
|
||||
],
|
||||
"door": true,
|
||||
"open": true
|
||||
},
|
||||
{
|
||||
"id": 28,
|
||||
"a": [
|
||||
1952,
|
||||
2048
|
||||
],
|
||||
"b": [
|
||||
2304,
|
||||
2048
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 29,
|
||||
"a": [
|
||||
1536,
|
||||
2816
|
||||
],
|
||||
"b": [
|
||||
2304,
|
||||
2816
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 30,
|
||||
"a": [
|
||||
1536,
|
||||
2048
|
||||
],
|
||||
"b": [
|
||||
1536,
|
||||
2400
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 31,
|
||||
"a": [
|
||||
1536,
|
||||
2464
|
||||
],
|
||||
"b": [
|
||||
1536,
|
||||
2816
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 32,
|
||||
"a": [
|
||||
2304,
|
||||
2048
|
||||
],
|
||||
"b": [
|
||||
2304,
|
||||
2400
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 33,
|
||||
"a": [
|
||||
2304,
|
||||
2464
|
||||
],
|
||||
"b": [
|
||||
2304,
|
||||
2816
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 34,
|
||||
"a": [
|
||||
2816,
|
||||
2048
|
||||
],
|
||||
"b": [
|
||||
3168,
|
||||
2048
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 35,
|
||||
"a": [
|
||||
3232,
|
||||
2048
|
||||
],
|
||||
"b": [
|
||||
3584,
|
||||
2048
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 36,
|
||||
"a": [
|
||||
2816,
|
||||
2816
|
||||
],
|
||||
"b": [
|
||||
3584,
|
||||
2816
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 37,
|
||||
"a": [
|
||||
2816,
|
||||
2048
|
||||
],
|
||||
"b": [
|
||||
2816,
|
||||
2400
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 38,
|
||||
"a": [
|
||||
2816,
|
||||
2464
|
||||
],
|
||||
"b": [
|
||||
2816,
|
||||
2816
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 39,
|
||||
"a": [
|
||||
3584,
|
||||
2048
|
||||
],
|
||||
"b": [
|
||||
3584,
|
||||
2816
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 40,
|
||||
"a": [
|
||||
3200,
|
||||
256
|
||||
],
|
||||
"b": [
|
||||
3584,
|
||||
256
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 41,
|
||||
"a": [
|
||||
1024,
|
||||
608
|
||||
],
|
||||
"b": [
|
||||
1536,
|
||||
608
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 42,
|
||||
"a": [
|
||||
1024,
|
||||
672
|
||||
],
|
||||
"b": [
|
||||
1536,
|
||||
672
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 43,
|
||||
"a": [
|
||||
2304,
|
||||
608
|
||||
],
|
||||
"b": [
|
||||
2816,
|
||||
608
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 44,
|
||||
"a": [
|
||||
2304,
|
||||
672
|
||||
],
|
||||
"b": [
|
||||
2816,
|
||||
672
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 45,
|
||||
"a": [
|
||||
1024,
|
||||
2400
|
||||
],
|
||||
"b": [
|
||||
1536,
|
||||
2400
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 46,
|
||||
"a": [
|
||||
1024,
|
||||
2464
|
||||
],
|
||||
"b": [
|
||||
1536,
|
||||
2464
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 47,
|
||||
"a": [
|
||||
2304,
|
||||
2400
|
||||
],
|
||||
"b": [
|
||||
2816,
|
||||
2400
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 48,
|
||||
"a": [
|
||||
2304,
|
||||
2464
|
||||
],
|
||||
"b": [
|
||||
2816,
|
||||
2464
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 49,
|
||||
"a": [
|
||||
1888,
|
||||
1024
|
||||
],
|
||||
"b": [
|
||||
1888,
|
||||
2048
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 50,
|
||||
"a": [
|
||||
1952,
|
||||
1024
|
||||
],
|
||||
"b": [
|
||||
1952,
|
||||
2048
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 51,
|
||||
"a": [
|
||||
3168,
|
||||
1024
|
||||
],
|
||||
"b": [
|
||||
3168,
|
||||
2048
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 52,
|
||||
"a": [
|
||||
3232,
|
||||
1024
|
||||
],
|
||||
"b": [
|
||||
3232,
|
||||
2048
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 53,
|
||||
"a": [
|
||||
608,
|
||||
1024
|
||||
],
|
||||
"b": [
|
||||
608,
|
||||
2048
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 54,
|
||||
"a": [
|
||||
672,
|
||||
1024
|
||||
],
|
||||
"b": [
|
||||
672,
|
||||
2048
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 55,
|
||||
"a": [
|
||||
600,
|
||||
600
|
||||
],
|
||||
"b": [
|
||||
680,
|
||||
600
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 56,
|
||||
"a": [
|
||||
600,
|
||||
680
|
||||
],
|
||||
"b": [
|
||||
680,
|
||||
680
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 57,
|
||||
"a": [
|
||||
600,
|
||||
600
|
||||
],
|
||||
"b": [
|
||||
600,
|
||||
680
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 58,
|
||||
"a": [
|
||||
680,
|
||||
600
|
||||
],
|
||||
"b": [
|
||||
680,
|
||||
680
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
},
|
||||
{
|
||||
"id": 59,
|
||||
"a": [
|
||||
3000,
|
||||
700
|
||||
],
|
||||
"b": [
|
||||
3000,
|
||||
1024
|
||||
],
|
||||
"door": false,
|
||||
"open": false
|
||||
}
|
||||
],
|
||||
"floors": [
|
||||
[
|
||||
256,
|
||||
256,
|
||||
1024,
|
||||
1024
|
||||
],
|
||||
[
|
||||
1536,
|
||||
256,
|
||||
2304,
|
||||
1024
|
||||
],
|
||||
[
|
||||
2816,
|
||||
256,
|
||||
3584,
|
||||
1024
|
||||
],
|
||||
[
|
||||
256,
|
||||
2048,
|
||||
1024,
|
||||
2816
|
||||
],
|
||||
[
|
||||
1536,
|
||||
2048,
|
||||
2304,
|
||||
2816
|
||||
],
|
||||
[
|
||||
2816,
|
||||
2048,
|
||||
3584,
|
||||
2816
|
||||
],
|
||||
[
|
||||
1024,
|
||||
608,
|
||||
1536,
|
||||
672
|
||||
],
|
||||
[
|
||||
2304,
|
||||
608,
|
||||
2816,
|
||||
672
|
||||
],
|
||||
[
|
||||
1024,
|
||||
2400,
|
||||
1536,
|
||||
2464
|
||||
],
|
||||
[
|
||||
2304,
|
||||
2400,
|
||||
2816,
|
||||
2464
|
||||
],
|
||||
[
|
||||
1888,
|
||||
1024,
|
||||
1952,
|
||||
2048
|
||||
],
|
||||
[
|
||||
3168,
|
||||
1024,
|
||||
3232,
|
||||
2048
|
||||
],
|
||||
[
|
||||
608,
|
||||
1024,
|
||||
672,
|
||||
2048
|
||||
]
|
||||
],
|
||||
"tokens": [
|
||||
{
|
||||
"id": "A",
|
||||
"kind": "player",
|
||||
"name": "Player A",
|
||||
"pos": [
|
||||
400,
|
||||
400
|
||||
],
|
||||
"gmOnly": false
|
||||
},
|
||||
{
|
||||
"id": "B",
|
||||
"kind": "player",
|
||||
"name": "Player B",
|
||||
"pos": [
|
||||
400,
|
||||
2200
|
||||
],
|
||||
"gmOnly": false
|
||||
},
|
||||
{
|
||||
"id": "M1",
|
||||
"kind": "monster",
|
||||
"name": "Monster 1",
|
||||
"pos": [
|
||||
900,
|
||||
900
|
||||
],
|
||||
"gmOnly": true
|
||||
},
|
||||
{
|
||||
"id": "M2",
|
||||
"kind": "monster",
|
||||
"name": "Monster 2",
|
||||
"pos": [
|
||||
1920,
|
||||
640
|
||||
],
|
||||
"gmOnly": true
|
||||
},
|
||||
{
|
||||
"id": "M3",
|
||||
"kind": "monster",
|
||||
"name": "Monster 3",
|
||||
"pos": [
|
||||
3400,
|
||||
500
|
||||
],
|
||||
"gmOnly": true
|
||||
},
|
||||
{
|
||||
"id": "M4",
|
||||
"kind": "monster",
|
||||
"name": "Monster 4",
|
||||
"pos": [
|
||||
900,
|
||||
2700
|
||||
],
|
||||
"gmOnly": true
|
||||
},
|
||||
{
|
||||
"id": "M5",
|
||||
"kind": "monster",
|
||||
"name": "Monster 5",
|
||||
"pos": [
|
||||
1920,
|
||||
2400
|
||||
],
|
||||
"gmOnly": true
|
||||
},
|
||||
{
|
||||
"id": "M6",
|
||||
"kind": "monster",
|
||||
"name": "Monster 6",
|
||||
"pos": [
|
||||
3200,
|
||||
2400
|
||||
],
|
||||
"gmOnly": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
{
|
||||
"$schema": "https://raw.githubusercontent.com/jetify-com/devbox/0.17.2/.schema/devbox.schema.json",
|
||||
"packages": {
|
||||
"nim": "2",
|
||||
"nimble": "latest",
|
||||
"nginx": "latest",
|
||||
"nodejs": "latest",
|
||||
"sqlite": {
|
||||
"version": "latest",
|
||||
"outputs": [
|
||||
"out",
|
||||
"bin"
|
||||
]
|
||||
}
|
||||
},
|
||||
"shell": {
|
||||
"init_hook": [],
|
||||
"scripts": {
|
||||
"gen": [
|
||||
"node tools/genmap.mjs"
|
||||
],
|
||||
"client": [
|
||||
"cd client && npm install --silent && npm run check && npm run build"
|
||||
],
|
||||
"test": [
|
||||
"node tools/genmap.mjs",
|
||||
"nimble test",
|
||||
"devbox run smoke",
|
||||
"devbox run leaktest",
|
||||
"DUR=15 devbox run concurrency"
|
||||
],
|
||||
"server": [
|
||||
"nimble build -d:release -y",
|
||||
"mkdir -p run",
|
||||
"./server"
|
||||
],
|
||||
"nginx": [
|
||||
"mkdir -p run/temp client/dist",
|
||||
"sed \"s/NGX_PORT/${PORT:-8080}/;s/NGX_BACKEND/${BACKEND_PORT:-9000}/\" nginx/nginx.conf > run/nginx.conf",
|
||||
"nginx -p \"$PWD/\" -c run/nginx.conf -e run/error.log"
|
||||
],
|
||||
"leaktest": [
|
||||
"mkdir -p run/test && nim c -d:release --hints:off -o:run/test/leakcheck tools/leakcheck.nim",
|
||||
"for s in A B; do SUBJECT=$s tools/withserver.sh sh -c 'node tools/leak.mjs && run/test/leakcheck' || exit 1; done"
|
||||
],
|
||||
"concurrency": [
|
||||
"tools/withserver.sh node tools/concurrency.mjs"
|
||||
],
|
||||
"smoke": [
|
||||
"tools/withserver.sh node tools/smoke.mjs"
|
||||
],
|
||||
"bench": [
|
||||
"nim c -d:release --hints:off -r -o:run/bench tools/bench.nim"
|
||||
]
|
||||
}
|
||||
},
|
||||
"env": {
|
||||
"NIMBLE_DIR": "$DEVBOX_PROJECT_ROOT/.devbox/nimble"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
{
|
||||
"lockfile_version": "1",
|
||||
"packages": {
|
||||
"gawk@latest": {
|
||||
"last_modified": "2026-10-02T22:55:44Z",
|
||||
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#gawk",
|
||||
"source": "devbox-search",
|
||||
"version": "5.4.1",
|
||||
"systems": {
|
||||
"aarch64-darwin": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/49jhcfya6jlc7p2hibbl2y5sfz132j3i-gawk-5.4.1",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "man",
|
||||
"path": "/nix/store/1sclicd2js7iipqnw4vn1rmy3scjg72v-gawk-5.4.1-man",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "info",
|
||||
"path": "/nix/store/n8gfvirxjm8z5zq7cx30qrmhn40w7jrb-gawk-5.4.1-info"
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/49jhcfya6jlc7p2hibbl2y5sfz132j3i-gawk-5.4.1"
|
||||
},
|
||||
"aarch64-linux": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/2bwpli20ff4f7hg5ck477p8s57kj857w-gawk-5.4.1",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "man",
|
||||
"path": "/nix/store/wfnxkfk386wl2plrhqx7lwfj4z84r493-gawk-5.4.1-man",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "info",
|
||||
"path": "/nix/store/l6wddbkc3rxavhbxyl48gn47rw8fq0pd-gawk-5.4.1-info"
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/2bwpli20ff4f7hg5ck477p8s57kj857w-gawk-5.4.1"
|
||||
},
|
||||
"x86_64-linux": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/63g104xwbzfpcq0h7c99w19m6j9ly3p1-gawk-5.4.1",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "man",
|
||||
"path": "/nix/store/0azvqykndxs3clnj974q99cjfnmpprjv-gawk-5.4.1-man",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "info",
|
||||
"path": "/nix/store/l4pwpdc6hrgy8n3diy24n389k53jqqjk-gawk-5.4.1-info"
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/63g104xwbzfpcq0h7c99w19m6j9ly3p1-gawk-5.4.1"
|
||||
}
|
||||
}
|
||||
},
|
||||
"gettext@latest": {
|
||||
"last_modified": "2026-10-02T22:55:44Z",
|
||||
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#gettext",
|
||||
"source": "devbox-search",
|
||||
"version": "1.0",
|
||||
"systems": {
|
||||
"aarch64-darwin": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/d73j7348argskpyvj28wq8n65mj6yg9x-gettext-1.0",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "man",
|
||||
"path": "/nix/store/arv8546qvpn8cr2bsgvzbzzzypmdv1kp-gettext-1.0-man",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "doc",
|
||||
"path": "/nix/store/4myr9gbsxvryjnwanyyhnnpqrdh56d5n-gettext-1.0-doc"
|
||||
},
|
||||
{
|
||||
"name": "info",
|
||||
"path": "/nix/store/b4d4imijjkkzr49zh5mq4gz2j9m2s047-gettext-1.0-info"
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/d73j7348argskpyvj28wq8n65mj6yg9x-gettext-1.0"
|
||||
},
|
||||
"aarch64-linux": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/8aimx510wyy0rzy7mllcjad5299jd17a-gettext-1.0",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "man",
|
||||
"path": "/nix/store/qllbgswyx416d7r7kqkyxvafpfbasmr8-gettext-1.0-man",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "doc",
|
||||
"path": "/nix/store/r2d6saacyqv8m9d8bvaidv4x2raqjb7z-gettext-1.0-doc"
|
||||
},
|
||||
{
|
||||
"name": "info",
|
||||
"path": "/nix/store/hsrnhwfpvrs4x4a5807cprpyz4qclgxy-gettext-1.0-info"
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/8aimx510wyy0rzy7mllcjad5299jd17a-gettext-1.0"
|
||||
},
|
||||
"x86_64-darwin": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/9mxzw5vwn99vx2b74ipjzk8x4b784fjy-gettext-1.0",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "man",
|
||||
"path": "/nix/store/r87hlf9pn8q3a8rnplzhy9lbgaadqcr8-gettext-1.0-man",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "doc",
|
||||
"path": "/nix/store/xmssbi5i2w3fv67hrv6c29wdiv8gxywi-gettext-1.0-doc"
|
||||
},
|
||||
{
|
||||
"name": "info",
|
||||
"path": "/nix/store/j4lz4zqicd1mw2l5c272ialxhl0nkc0b-gettext-1.0-info"
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/9mxzw5vwn99vx2b74ipjzk8x4b784fjy-gettext-1.0"
|
||||
},
|
||||
"x86_64-linux": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/gfkkr23q11kvyz6xxyxz3qbsp1msxdcv-gettext-1.0",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "man",
|
||||
"path": "/nix/store/njdszjnrb0n7c6m6jzmx5539ac0ybn9g-gettext-1.0-man",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "doc",
|
||||
"path": "/nix/store/z2p7kr1a45gz9m9g3s6rary2avk3gs9x-gettext-1.0-doc"
|
||||
},
|
||||
{
|
||||
"name": "info",
|
||||
"path": "/nix/store/8vqnaf3h4vlb8q5w9z9kscqld7m5rdif-gettext-1.0-info"
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/gfkkr23q11kvyz6xxyxz3qbsp1msxdcv-gettext-1.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"github:NixOS/nixpkgs/nixpkgs-unstable": {
|
||||
"last_modified": "2026-10-20T14:23:57Z",
|
||||
"resolved": "github:NixOS/nixpkgs/5adc50831c259f87faeb09ddf930d43597197473?lastModified=1792506237&narHash=sha256-Q%2F8KLB6jNfpaUN1HAedE%2Fu%2FEt9feE%2FzYSsutBLKrCFk%3D"
|
||||
},
|
||||
"nginx@latest": {
|
||||
"last_modified": "2026-10-02T22:55:44Z",
|
||||
"plugin_version": "0.0.4",
|
||||
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#nginx",
|
||||
"source": "devbox-search",
|
||||
"version": "1.30.5",
|
||||
"systems": {
|
||||
"aarch64-darwin": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/81a75xq2ilmn8dnrb1b7m8siyprmaq94-nginx-1.30.5",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "doc",
|
||||
"path": "/nix/store/s9zq3wyd2bdfwb58rk2648yf2wsryvhj-nginx-1.30.5-doc"
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/81a75xq2ilmn8dnrb1b7m8siyprmaq94-nginx-1.30.5"
|
||||
},
|
||||
"aarch64-linux": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/7yvpd3svx846fybmc2d5ddxq3jxf94qm-nginx-1.30.5",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "doc",
|
||||
"path": "/nix/store/skp8nki2v0li5h44zyp1gp8s2ahz3g4j-nginx-1.30.5-doc"
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/7yvpd3svx846fybmc2d5ddxq3jxf94qm-nginx-1.30.5"
|
||||
},
|
||||
"x86_64-linux": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/6k4rgdzx05z7yk2l98r28p6wrbnlv63z-nginx-1.30.5",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "doc",
|
||||
"path": "/nix/store/d8v365rflmpicpcnxjqfxbbzlpk0q844-nginx-1.30.5-doc"
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/6k4rgdzx05z7yk2l98r28p6wrbnlv63z-nginx-1.30.5"
|
||||
}
|
||||
}
|
||||
},
|
||||
"nim@2": {
|
||||
"last_modified": "2026-10-02T22:55:44Z",
|
||||
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#nim",
|
||||
"source": "devbox-search",
|
||||
"version": "2.2.12",
|
||||
"systems": {
|
||||
"aarch64-darwin": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/h055h3lxxsm8kql0mannw3706x740x7f-arm64-apple-darwin-nim-wrapper-2.2.12",
|
||||
"default": true
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/h055h3lxxsm8kql0mannw3706x740x7f-arm64-apple-darwin-nim-wrapper-2.2.12"
|
||||
},
|
||||
"aarch64-linux": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/2fh7rg634j8969c1r394llrsjmmhaip7-aarch64-unknown-linux-gnu-nim-wrapper-2.2.12",
|
||||
"default": true
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/2fh7rg634j8969c1r394llrsjmmhaip7-aarch64-unknown-linux-gnu-nim-wrapper-2.2.12"
|
||||
},
|
||||
"x86_64-linux": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/0cbdz34lsakfirycixckf6ypsd8hazhg-x86_64-unknown-linux-gnu-nim-wrapper-2.2.12",
|
||||
"default": true
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/0cbdz34lsakfirycixckf6ypsd8hazhg-x86_64-unknown-linux-gnu-nim-wrapper-2.2.12"
|
||||
}
|
||||
}
|
||||
},
|
||||
"nimble@latest": {
|
||||
"last_modified": "2026-10-02T22:55:44Z",
|
||||
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#nimble",
|
||||
"source": "devbox-search",
|
||||
"version": "0.24.1",
|
||||
"systems": {
|
||||
"aarch64-darwin": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/clxsxdsqjfcc43rfd7rad733nd0ndrkf-nimble-0.24.1",
|
||||
"default": true
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/clxsxdsqjfcc43rfd7rad733nd0ndrkf-nimble-0.24.1"
|
||||
},
|
||||
"aarch64-linux": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/c5d0r4a8qi1vqs8q82pr3c652q8d6jv7-nimble-0.24.1",
|
||||
"default": true
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/c5d0r4a8qi1vqs8q82pr3c652q8d6jv7-nimble-0.24.1"
|
||||
},
|
||||
"x86_64-linux": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/8f5wx2s80gnw0lkmdpbl63n1xlilcfxi-nimble-0.24.1",
|
||||
"default": true
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/8f5wx2s80gnw0lkmdpbl63n1xlilcfxi-nimble-0.24.1"
|
||||
}
|
||||
}
|
||||
},
|
||||
"nodejs@latest": {
|
||||
"last_modified": "2026-10-08T19:21:32Z",
|
||||
"plugin_version": "0.0.2",
|
||||
"resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#nodejs_26",
|
||||
"source": "devbox-search",
|
||||
"version": "26.11.1",
|
||||
"systems": {
|
||||
"aarch64-darwin": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/42hvw959dvc16w7p79xns4p4sgfx2wiv-nodejs-26.11.1",
|
||||
"default": true
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/42hvw959dvc16w7p79xns4p4sgfx2wiv-nodejs-26.11.1"
|
||||
},
|
||||
"aarch64-linux": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/zzx8zal1hmjkamrp8y9k6mjim08pzwz8-nodejs-26.11.1",
|
||||
"default": true
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/zzx8zal1hmjkamrp8y9k6mjim08pzwz8-nodejs-26.11.1"
|
||||
},
|
||||
"x86_64-linux": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/m7vfpzl1rjwjpwlcsqs166jn3lywzpq1-nodejs-26.11.1",
|
||||
"default": true
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/m7vfpzl1rjwjpwlcsqs166jn3lywzpq1-nodejs-26.11.1"
|
||||
}
|
||||
}
|
||||
},
|
||||
"sqlite@latest": {
|
||||
"last_modified": "2026-10-08T19:21:32Z",
|
||||
"resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#sqlite",
|
||||
"source": "devbox-search",
|
||||
"version": "3.53.3",
|
||||
"systems": {
|
||||
"aarch64-darwin": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "bin",
|
||||
"path": "/nix/store/9miwmq08y0pg4m97ws8b2gcqxrbr8d2c-sqlite-3.53.3-bin",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "man",
|
||||
"path": "/nix/store/wlwc2gz7r5884rdmfjnqjk38lwv94qsy-sqlite-3.53.3-man",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "doc",
|
||||
"path": "/nix/store/p6bsmbp6a5dz55isxvfr7941wbfjmjvf-sqlite-3.53.3-doc"
|
||||
},
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/0k4r9hnfbnyngn5f3j31siddfs0iglwl-sqlite-3.53.3"
|
||||
},
|
||||
{
|
||||
"name": "dev",
|
||||
"path": "/nix/store/r9cljv2bvqi3ci3n6m0z0wi3ldpvlyzq-sqlite-3.53.3-dev"
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/9miwmq08y0pg4m97ws8b2gcqxrbr8d2c-sqlite-3.53.3-bin"
|
||||
},
|
||||
"aarch64-linux": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "bin",
|
||||
"path": "/nix/store/kw0mkd9znldi5l0s4jygygdh4p9sms8r-sqlite-3.53.3-bin",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "man",
|
||||
"path": "/nix/store/9q84sy842rw7k4z4jdsb4hkbiapr7pm0-sqlite-3.53.3-man",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "debug",
|
||||
"path": "/nix/store/q39crs8z0dafx19dv0l2y4jxc8ahvy03-sqlite-3.53.3-debug"
|
||||
},
|
||||
{
|
||||
"name": "dev",
|
||||
"path": "/nix/store/74r7ps7mmjw10fl23xsgcp7ss09jrkjr-sqlite-3.53.3-dev"
|
||||
},
|
||||
{
|
||||
"name": "doc",
|
||||
"path": "/nix/store/g4f5y9laa7l7lbriv8x05clyi9x7w14z-sqlite-3.53.3-doc"
|
||||
},
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/2lyx0wc6ccabpdwpviksww3x5xhsmnvk-sqlite-3.53.3"
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/kw0mkd9znldi5l0s4jygygdh4p9sms8r-sqlite-3.53.3-bin"
|
||||
},
|
||||
"x86_64-linux": {
|
||||
"outputs": [
|
||||
{
|
||||
"name": "bin",
|
||||
"path": "/nix/store/iy2zkfn4l0w24xabv6ryi0vh7bpjvqm6-sqlite-3.53.3-bin",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "man",
|
||||
"path": "/nix/store/is1ld1bxvwqqjwv89kl6vcnlpypbkg5r-sqlite-3.53.3-man",
|
||||
"default": true
|
||||
},
|
||||
{
|
||||
"name": "doc",
|
||||
"path": "/nix/store/l778wamidjdrjyahinx63c7n50fwh0il-sqlite-3.53.3-doc"
|
||||
},
|
||||
{
|
||||
"name": "out",
|
||||
"path": "/nix/store/9x0m6s73sg89fv5awb95vsac2mbns8n0-sqlite-3.53.3"
|
||||
},
|
||||
{
|
||||
"name": "debug",
|
||||
"path": "/nix/store/1vbdchnss15n90chl72l80z16shxjp7l-sqlite-3.53.3-debug"
|
||||
},
|
||||
{
|
||||
"name": "dev",
|
||||
"path": "/nix/store/xrcjl59yi7zswbv0vzm8cmvw4vplsbgj-sqlite-3.53.3-dev"
|
||||
}
|
||||
],
|
||||
"store_path": "/nix/store/iy2zkfn4l0w24xabv6ryi0vh7bpjvqm6-sqlite-3.53.3-bin"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
|
||||
types {
|
||||
text/html html htm shtml;
|
||||
text/css css;
|
||||
text/xml xml;
|
||||
image/gif gif;
|
||||
image/jpeg jpeg jpg;
|
||||
application/javascript js;
|
||||
application/atom+xml atom;
|
||||
application/rss+xml rss;
|
||||
|
||||
text/mathml mml;
|
||||
text/plain txt;
|
||||
text/vnd.sun.j2me.app-descriptor jad;
|
||||
text/vnd.wap.wml wml;
|
||||
text/x-component htc;
|
||||
|
||||
image/avif avif;
|
||||
image/png png;
|
||||
image/svg+xml svg svgz;
|
||||
image/tiff tif tiff;
|
||||
image/vnd.wap.wbmp wbmp;
|
||||
image/webp webp;
|
||||
image/x-icon ico;
|
||||
image/x-jng jng;
|
||||
image/x-ms-bmp bmp;
|
||||
|
||||
font/woff woff;
|
||||
font/woff2 woff2;
|
||||
|
||||
application/java-archive jar war ear;
|
||||
application/json json;
|
||||
application/mac-binhex40 hqx;
|
||||
application/msword doc;
|
||||
application/pdf pdf;
|
||||
application/postscript ps eps ai;
|
||||
application/rtf rtf;
|
||||
application/vnd.apple.mpegurl m3u8;
|
||||
application/vnd.google-earth.kml+xml kml;
|
||||
application/vnd.google-earth.kmz kmz;
|
||||
application/vnd.ms-excel xls;
|
||||
application/vnd.ms-fontobject eot;
|
||||
application/vnd.ms-powerpoint ppt;
|
||||
application/vnd.oasis.opendocument.graphics odg;
|
||||
application/vnd.oasis.opendocument.presentation odp;
|
||||
application/vnd.oasis.opendocument.spreadsheet ods;
|
||||
application/vnd.oasis.opendocument.text odt;
|
||||
application/vnd.openxmlformats-officedocument.presentationml.presentation
|
||||
pptx;
|
||||
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
|
||||
xlsx;
|
||||
application/vnd.openxmlformats-officedocument.wordprocessingml.document
|
||||
docx;
|
||||
application/vnd.wap.wmlc wmlc;
|
||||
application/wasm wasm;
|
||||
application/x-7z-compressed 7z;
|
||||
application/x-cocoa cco;
|
||||
application/x-java-archive-diff jardiff;
|
||||
application/x-java-jnlp-file jnlp;
|
||||
application/x-makeself run;
|
||||
application/x-perl pl pm;
|
||||
application/x-pilot prc pdb;
|
||||
application/x-rar-compressed rar;
|
||||
application/x-redhat-package-manager rpm;
|
||||
application/x-sea sea;
|
||||
application/x-shockwave-flash swf;
|
||||
application/x-stuffit sit;
|
||||
application/x-tcl tcl tk;
|
||||
application/x-x509-ca-cert der pem crt;
|
||||
application/x-xpinstall xpi;
|
||||
application/xhtml+xml xhtml;
|
||||
application/xspf+xml xspf;
|
||||
application/zip zip;
|
||||
|
||||
application/octet-stream bin exe dll;
|
||||
application/octet-stream deb;
|
||||
application/octet-stream dmg;
|
||||
application/octet-stream iso img;
|
||||
application/octet-stream msi msp msm;
|
||||
|
||||
audio/midi mid midi kar;
|
||||
audio/mpeg mp3;
|
||||
audio/ogg ogg;
|
||||
audio/x-m4a m4a;
|
||||
audio/x-realaudio ra;
|
||||
|
||||
video/3gpp 3gpp 3gp;
|
||||
video/mp2t ts;
|
||||
video/mp4 mp4;
|
||||
video/mpeg mpeg mpg;
|
||||
video/quicktime mov;
|
||||
video/webm webm;
|
||||
video/x-flv flv;
|
||||
video/x-m4v m4v;
|
||||
video/x-mng mng;
|
||||
video/x-ms-asf asx asf;
|
||||
video/x-ms-wmv wmv;
|
||||
video/x-msvideo avi;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
# run via `devbox run nginx`; prefix = project root, all temp/log paths in run/
|
||||
daemon off;
|
||||
pid run/nginx.pid;
|
||||
error_log run/error.log warn;
|
||||
events {}
|
||||
http {
|
||||
access_log run/access.log;
|
||||
client_body_temp_path run/temp/client_body;
|
||||
proxy_temp_path run/temp/proxy;
|
||||
fastcgi_temp_path run/temp/fastcgi;
|
||||
uwsgi_temp_path run/temp/uwsgi;
|
||||
scgi_temp_path run/temp/scgi;
|
||||
server_tokens off;
|
||||
include ../nginx/mime.types; # relative to the generated run/nginx.conf
|
||||
map $http_upgrade $conn_up { default upgrade; '' close; }
|
||||
server {
|
||||
listen NGX_PORT; # sed-substituted from $PORT (default 8080); NGX_BACKEND from $BACKEND_PORT (default 9000)
|
||||
server_name localhost;
|
||||
root client/dist;
|
||||
index index.html;
|
||||
location /join/ { proxy_pass http://127.0.0.1:NGX_BACKEND; }
|
||||
location /tiles/ { proxy_pass http://127.0.0.1:NGX_BACKEND; }
|
||||
location /ws {
|
||||
proxy_pass http://127.0.0.1:NGX_BACKEND;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $conn_up;
|
||||
proxy_read_timeout 1h;
|
||||
}
|
||||
# only reachable via X-Accel-Redirect from Nim after its access check
|
||||
location /_tiles/ { internal; alias data/tiles/; add_header Cache-Control "private, no-cache"; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
--path:"src"
|
||||
--threads:on
|
||||
--mm:orc
|
||||
@@ -0,0 +1,11 @@
|
||||
version = "0.1.0"
|
||||
author = "proto"
|
||||
description = "Throwaway: server-authoritative vision prototype"
|
||||
license = "MIT"
|
||||
srcDir = "src"
|
||||
bin = @["server"]
|
||||
|
||||
requires "nim >= 2.0"
|
||||
# no tags upstream: pin exact commit
|
||||
requires "mummy#01deb1ff694988635c7bf0f24f6088a0bdf6db5d"
|
||||
requires "db_connector"
|
||||
@@ -0,0 +1,116 @@
|
||||
## 2D vision geometry. Pure, no deps.
|
||||
import std/[math, algorithm]
|
||||
|
||||
type
|
||||
Vec* = tuple[x, y: float]
|
||||
Wall* = object
|
||||
a*, b*: Vec
|
||||
door*, open*: bool
|
||||
|
||||
const
|
||||
Eps = 1e-9 # geometric tolerance (px)
|
||||
RayEps = 1e-4 # angular nudge past endpoints (rad)
|
||||
|
||||
proc blocks*(w: Wall): bool = not (w.door and w.open)
|
||||
|
||||
proc cross(a, b: Vec): float = a.x * b.y - a.y * b.x
|
||||
proc `-`(a, b: Vec): Vec = (a.x - b.x, a.y - b.y)
|
||||
|
||||
proc rayHit(o, d: Vec, a, b: Vec): float =
|
||||
## smallest t > Eps where o + t*d hits segment ab (end-inclusive), else Inf
|
||||
let e = b - a
|
||||
let den = cross(d, e)
|
||||
if abs(den) < 1e-12: return Inf # parallel/collinear: grazing, other rays cover it
|
||||
let ao = a - o
|
||||
let t = cross(ao, e) / den
|
||||
let u = cross(ao, d) / den
|
||||
if t > Eps and u >= -Eps and u <= 1 + Eps: t else: Inf
|
||||
|
||||
proc visibilityPolygon*(o: Vec, walls: openArray[Wall], radius: float,
|
||||
circleSegs = 64): seq[Vec] =
|
||||
## CCW polygon of what `o` sees, bounded by an inscribed circleSegs-gon of `radius`.
|
||||
var segs: seq[(Vec, Vec)]
|
||||
var angles: seq[float]
|
||||
for i in 0 ..< circleSegs:
|
||||
let a0 = 2 * PI * i.float / circleSegs.float
|
||||
let a1 = 2 * PI * (i + 1).float / circleSegs.float
|
||||
segs.add(((o.x + radius * cos a0, o.y + radius * sin a0),
|
||||
(o.x + radius * cos a1, o.y + radius * sin a1)))
|
||||
angles.add arctan2(sin a0, cos a0) # same (-pi,pi] range as the wall angles, else the sort scrambles the fan
|
||||
for w in walls:
|
||||
if not w.blocks: continue
|
||||
# shortcut: walls beyond the circle are only culled by ray clipping, O(rays*walls); upgrade: spatial grid
|
||||
if max(w.a.x, w.b.x) < o.x - radius or min(w.a.x, w.b.x) > o.x + radius or
|
||||
max(w.a.y, w.b.y) < o.y - radius or min(w.a.y, w.b.y) > o.y + radius: continue
|
||||
segs.add((w.a, w.b))
|
||||
for p in [w.a, w.b]:
|
||||
if abs(p.x - o.x) < Eps and abs(p.y - o.y) < Eps: continue # token on endpoint
|
||||
let ang = arctan2(p.y - o.y, p.x - o.x)
|
||||
angles.add ang
|
||||
angles.add ang - RayEps
|
||||
angles.add ang + RayEps
|
||||
angles.sort
|
||||
for ang in angles:
|
||||
let d: Vec = (cos ang, sin ang)
|
||||
var best = Inf
|
||||
for s in segs: best = min(best, rayHit(o, d, s[0], s[1]))
|
||||
if best < Inf: result.add((o.x + d.x * best, o.y + d.y * best))
|
||||
|
||||
proc segsCross(p, q, a, b: Vec): bool =
|
||||
## inclusive segment intersection (touching and collinear overlap count)
|
||||
proc orient(a, b, c: Vec): int =
|
||||
let v = cross(b - a, c - a)
|
||||
if v > Eps: 1 elif v < -Eps: -1 else: 0
|
||||
proc onSeg(a, b, c: Vec): bool = # c collinear with ab: within bbox?
|
||||
c.x >= min(a.x, b.x) - Eps and c.x <= max(a.x, b.x) + Eps and
|
||||
c.y >= min(a.y, b.y) - Eps and c.y <= max(a.y, b.y) + Eps
|
||||
let o1 = orient(p, q, a); let o2 = orient(p, q, b)
|
||||
let o3 = orient(a, b, p); let o4 = orient(a, b, q)
|
||||
if o1 != o2 and o3 != o4: return true
|
||||
(o1 == 0 and onSeg(p, q, a)) or (o2 == 0 and onSeg(p, q, b)) or
|
||||
(o3 == 0 and onSeg(a, b, p)) or (o4 == 0 and onSeg(a, b, q))
|
||||
|
||||
proc segDist(p, a, b: Vec): float =
|
||||
let e = b - a
|
||||
let l2 = e.x * e.x + e.y * e.y
|
||||
let t = if l2 < Eps: 0.0 else: clamp(((p.x - a.x) * e.x + (p.y - a.y) * e.y) / l2, 0.0, 1.0)
|
||||
hypot(p.x - a.x - t * e.x, p.y - a.y - t * e.y)
|
||||
|
||||
proc moveBlocked*(walls: openArray[Wall], a, b: Vec, r = 0.0): bool =
|
||||
## true if travelling a->b touches any blocking wall (touching counts: no leaking through shared vertices)
|
||||
## or the token circle (radius r) at b overlaps one. Only b is checked for clearance, so a token
|
||||
## already overlapping (legacy position, door closed on it) can still leave to a clear spot.
|
||||
## shortcut: a token standing exactly on a wall can't move off it; server must keep tokens off walls.
|
||||
for w in walls:
|
||||
if w.blocks and (segsCross(a, b, w.a, w.b) or segDist(b, w.a, w.b) < r): return true
|
||||
|
||||
proc inside*(poly: openArray[Vec], p: Vec): bool =
|
||||
## even-odd point-in-polygon (boundary ambiguous)
|
||||
var j = poly.len - 1
|
||||
for i in 0 ..< poly.len:
|
||||
if (poly[i].y > p.y) != (poly[j].y > p.y) and
|
||||
p.x < (poly[j].x - poly[i].x) * (p.y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x:
|
||||
result = not result
|
||||
j = i
|
||||
|
||||
proc cellsTouched*(poly: openArray[Vec], cell: float): seq[(int, int)] =
|
||||
## grid cells (ix, iy) overlapped by the polygon (area overlap, boundary touch included), sorted.
|
||||
if poly.len < 3: return
|
||||
var x0, y0 = Inf
|
||||
var x1, y1 = -Inf
|
||||
for p in poly:
|
||||
x0 = min(x0, p.x); x1 = max(x1, p.x); y0 = min(y0, p.y); y1 = max(y1, p.y)
|
||||
for iy in int(floor(y0 / cell)) .. int(floor(y1 / cell)):
|
||||
for ix in int(floor(x0 / cell)) .. int(floor(x1 / cell)):
|
||||
let (cx0, cy0, cx1, cy1) = (ix.float * cell, iy.float * cell, (ix + 1).float * cell, (iy + 1).float * cell)
|
||||
let c = [(cx0, cy0), (cx1, cy0), (cx1, cy1), (cx0, cy1)]
|
||||
# no edge crosses => cell wholly inside poly (a corner decides) or poly wholly inside cell (a vertex decides) or disjoint
|
||||
var hit = inside(poly, c[0]) or
|
||||
(poly[0].x >= cx0 and poly[0].x <= cx1 and poly[0].y >= cy0 and poly[0].y <= cy1)
|
||||
if not hit:
|
||||
for i in 0 ..< poly.len:
|
||||
let p = poly[i]; let q = poly[(i + 1) mod poly.len]
|
||||
for k in 0 .. 3:
|
||||
if segsCross(p, q, c[k], c[(k + 1) mod 4]): hit = true; break
|
||||
if hit: break
|
||||
if hit: result.add (ix, iy)
|
||||
@@ -0,0 +1,324 @@
|
||||
## Server-authoritative vision. Players are untrusted: only what is in their vision reaches them.
|
||||
## One global Lock: validate -> mutate -> recompute vision -> persist -> send, so gseq order == send order.
|
||||
import std/[json, tables, sets, locks, os, monotimes, times, strutils, sysrand, strformat]
|
||||
import mummy, db_connector/db_sqlite
|
||||
import geometry
|
||||
|
||||
type
|
||||
Tok = object
|
||||
id, name, kind: string
|
||||
pos: Vec
|
||||
gmOnly: bool
|
||||
Role = ref object # per player: shared by all that player's connections
|
||||
polys: seq[seq[Vec]]
|
||||
ver: int # bumped when polys change
|
||||
explored: HashSet[int]
|
||||
fresh: seq[int] # cells added by the current mutation
|
||||
Conn = ref object
|
||||
ws: WebSocket
|
||||
role: string # "gm" | "A" | "B"
|
||||
ver: int
|
||||
known: Table[string, Vec] # tokens this client currently has
|
||||
bytes: int
|
||||
Ev = object # what the current mutation was
|
||||
door: int
|
||||
doorOpen: bool
|
||||
moved, by: string
|
||||
reqId: int
|
||||
Stat = object
|
||||
n: int
|
||||
sum, worst: float
|
||||
|
||||
# nginx public port; 8080 per spec, PORT overrides when taken
|
||||
let origin = "http://localhost:" & getEnv("PORT", "8080")
|
||||
# RUN_DIR: db/invites dir (tools/withserver.sh sets run/test); BACKEND_PORT: mummy listen port (nginx proxies to it)
|
||||
let runDir = getEnv("RUN_DIR", "run")
|
||||
let backendPort = parseInt(getEnv("BACKEND_PORT", "9000"))
|
||||
|
||||
var
|
||||
lk: Lock
|
||||
db: DbConn
|
||||
walls: seq[Wall] # index == wall id
|
||||
toks: seq[Tok]
|
||||
worldW, worldH, tileSize, cell, cw: int
|
||||
radius, tokRadius: float
|
||||
roles: Table[string, Role]
|
||||
secrets: Table[string, string] # secret -> "gm"|"A"|"B"
|
||||
conns: Table[string, Conn]
|
||||
gseq: int
|
||||
vstat, bstat: Table[string, Stat]
|
||||
nMut: int
|
||||
lk.initLock
|
||||
|
||||
proc add(s: var Stat, v: float) = inc s.n; s.sum += v; s.worst = max(s.worst, v)
|
||||
|
||||
proc printStats() =
|
||||
for k, s in vstat: echo &"STATS vision_ms {k}: n={s.n} avg={s.sum / s.n.float:.3f} worst={s.worst:.3f}"
|
||||
for k, s in bstat: echo &"STATS bytes/delivery {k}: n={s.n} avg={s.sum / s.n.float:.1f} worst={s.worst:.0f}"
|
||||
stdout.flushFile
|
||||
|
||||
# shortcut: WebSocket has no ==/hash and private fields; key by raw bytes, fine while the layout is plain POD
|
||||
proc key(ws: WebSocket): string =
|
||||
result = newString(sizeof(ws)); copyMem(addr result[0], unsafeAddr ws, sizeof(ws))
|
||||
|
||||
proc owns(role, id: string): bool = role == "gm" or role == id
|
||||
proc pt(v: Vec): JsonNode = %[%v.x, %v.y]
|
||||
proc tokIdx(id: string): int =
|
||||
for i, t in toks:
|
||||
if t.id == id: return i
|
||||
-1
|
||||
|
||||
proc send(c: Conn, t: string, j: JsonNode) =
|
||||
j["t"] = %t; j["gseq"] = %gseq
|
||||
let s = $j
|
||||
c.bytes += s.len
|
||||
c.ws.send(s)
|
||||
|
||||
proc err(c: Conn, msg: string) = c.send("error", %*{"msg": msg})
|
||||
|
||||
proc recompute(rn: string) =
|
||||
let r = roles[rn]
|
||||
var np: seq[seq[Vec]]
|
||||
for t in toks:
|
||||
if owns(rn, t.id): np.add visibilityPolygon(t.pos, walls, radius)
|
||||
if np == r.polys: return
|
||||
r.polys = np; inc r.ver
|
||||
for p in np:
|
||||
for (ix, iy) in cellsTouched(p, cell.float):
|
||||
if ix >= 0 and iy >= 0 and ix < cw and iy < cw:
|
||||
let k = iy * cw + ix
|
||||
if not r.explored.containsOrIncl(k): r.fresh.add k
|
||||
|
||||
proc persistCells(rn: string) =
|
||||
for k in roles[rn].fresh: db.exec(sql"INSERT OR IGNORE INTO exp VALUES (?,?)", rn, k)
|
||||
|
||||
proc sync(c: Conn, ev: Ev, initial: bool) =
|
||||
## bring one client up to date; diff against what it already has
|
||||
let player = c.role != "gm"
|
||||
var r: Role
|
||||
if player:
|
||||
r = roles[c.role]
|
||||
if c.ver != r.ver:
|
||||
c.ver = r.ver
|
||||
var ps = newJArray()
|
||||
for p in r.polys:
|
||||
var a = newJArray()
|
||||
for v in p: a.add pt(v)
|
||||
ps.add a
|
||||
c.send("vision", %*{"polys": ps})
|
||||
var cells = newJArray()
|
||||
if initial:
|
||||
for k in r.explored: cells.add %[k mod cw, k div cw]
|
||||
else:
|
||||
for k in r.fresh: cells.add %[k mod cw, k div cw]
|
||||
if cells.len > 0: c.send("explored", %*{"cells": cells})
|
||||
elif ev.door >= 0:
|
||||
c.send("door", %*{"id": ev.door, "open": ev.doorOpen})
|
||||
for t in toks:
|
||||
var vis = c.role == "gm" or t.id == c.role
|
||||
if not vis:
|
||||
for p in r.polys:
|
||||
if inside(p, t.pos): vis = true; break
|
||||
if vis:
|
||||
if c.known.getOrDefault(t.id, (-1.0, -1.0)) != t.pos or initial:
|
||||
c.known[t.id] = t.pos
|
||||
let j = %*{"id": t.id, "name": t.name, "kind": t.kind, "pos": pt(t.pos), "mine": owns(c.role, t.id)}
|
||||
if t.id == ev.moved and ev.reqId >= 0: j["by"] = %ev.by; j["reqId"] = %ev.reqId
|
||||
c.send("token", j)
|
||||
elif c.known.hasKey(t.id):
|
||||
c.known.del t.id
|
||||
c.send("remove", %*{"id": t.id})
|
||||
|
||||
proc finish(ev: Ev, kind: string, visMs: float, mover: Conn = nil) =
|
||||
## send phase of a mutation (caller holds lk, DB already committed)
|
||||
for c in conns.values:
|
||||
if c != mover: c.bytes = 0
|
||||
sync(c, ev, false)
|
||||
for r in roles.values: r.fresh.setLen 0
|
||||
vstat.mgetOrPut(kind, Stat()).add visMs
|
||||
var line = &"MUT gseq={gseq} {kind} vision_ms={visMs:.3f}"
|
||||
for c in conns.values:
|
||||
if c.bytes > 0: bstat.mgetOrPut(kind & " " & c.role, Stat()).add c.bytes.float # only recipients that got something
|
||||
line.add &" {c.role}:{c.bytes}B"
|
||||
echo line
|
||||
inc nMut
|
||||
if nMut mod 5000 == 0: printStats()
|
||||
stdout.flushFile
|
||||
|
||||
proc handleMove(c: Conn, m: JsonNode) =
|
||||
let p = m{"pos"}
|
||||
if m{"reqId"}.isNil or m["reqId"].kind != JInt or m{"id"}.isNil or m["id"].kind != JString or
|
||||
p.isNil or p.kind != JArray or p.len != 2 or p[0].kind notin {JInt, JFloat} or p[1].kind notin {JInt, JFloat}:
|
||||
c.err("bad move"); return
|
||||
let id = m["id"].getStr
|
||||
let ti = tokIdx(id)
|
||||
if ti < 0 or not owns(c.role, id): c.err("not yours"); return # no pos echoed: could leak unseen tokens
|
||||
let reqId = m["reqId"].getInt
|
||||
let np: Vec = (p[0].getFloat, p[1].getFloat)
|
||||
let old = toks[ti].pos
|
||||
if np.x < 0 or np.y < 0 or np.x > worldW.float or np.y > worldH.float or moveBlocked(walls, old, np, tokRadius):
|
||||
c.send("moveAck", %*{"reqId": reqId, "ok": false, "pos": pt(old)}); return
|
||||
toks[ti].pos = np
|
||||
inc gseq
|
||||
for x in conns.values: x.bytes = 0
|
||||
let t0 = getMonoTime()
|
||||
if roles.hasKey(id): recompute(id)
|
||||
let visMs = (getMonoTime() - t0).inNanoseconds.float / 1e6
|
||||
db.exec(sql"BEGIN")
|
||||
db.exec(sql"INSERT OR REPLACE INTO tok VALUES (?,?,?)", id, np.x, np.y)
|
||||
if roles.hasKey(id): persistCells(id)
|
||||
db.exec(sql"COMMIT")
|
||||
c.send("moveAck", %*{"reqId": reqId, "ok": true, "pos": pt(np)})
|
||||
finish(Ev(door: -1, moved: id, by: c.role, reqId: reqId), (if roles.hasKey(id): "move-player" else: "move-monster"), visMs, c)
|
||||
|
||||
proc handleDoor(c: Conn, m: JsonNode) =
|
||||
if c.role != "gm": c.err("gm only"); return
|
||||
if m{"id"}.isNil or m["id"].kind != JInt or m{"open"}.isNil or m["open"].kind != JBool:
|
||||
c.err("bad door"); return
|
||||
let id = m["id"].getInt
|
||||
if id < 0 or id >= walls.len or not walls[id].door: c.err("not a door"); return
|
||||
let open = m["open"].getBool
|
||||
if walls[id].open == open: return
|
||||
walls[id].open = open
|
||||
inc gseq
|
||||
for x in conns.values: x.bytes = 0
|
||||
let t0 = getMonoTime()
|
||||
for rn in roles.keys: recompute(rn)
|
||||
let visMs = (getMonoTime() - t0).inNanoseconds.float / 1e6
|
||||
db.exec(sql"BEGIN")
|
||||
db.exec(sql"INSERT OR REPLACE INTO door VALUES (?,?)", id, ord(open))
|
||||
for rn in roles.keys: persistCells(rn)
|
||||
db.exec(sql"COMMIT")
|
||||
finish(Ev(door: id, doorOpen: open, moved: "", reqId: -1), "door", visMs, c)
|
||||
|
||||
proc openConn(ws: WebSocket, role: string) =
|
||||
let c = Conn(ws: ws, role: role, ver: -1)
|
||||
conns[key(ws)] = c
|
||||
let ids = newJArray()
|
||||
for t in toks:
|
||||
if owns(role, t.id): ids.add %t.id
|
||||
c.send("hello", %*{"role": (if role == "gm": "gm" else: "player"), "tokens": ids,
|
||||
"world": {"w": worldW, "h": worldH}, "tileSize": tileSize, "exploredCell": cell, "tokenRadius": tokRadius})
|
||||
if role == "gm":
|
||||
var ws = newJArray()
|
||||
for i, w in walls: ws.add %*{"id": i, "a": pt(w.a), "b": pt(w.b), "door": w.door, "open": w.open}
|
||||
c.send("walls", %*{"walls": ws})
|
||||
sync(c, Ev(door: -1, reqId: -1), true)
|
||||
|
||||
proc wsHandler(ws: WebSocket, event: WebSocketEvent, message: Message) {.gcsafe.} =
|
||||
{.gcsafe.}:
|
||||
withLock lk:
|
||||
case event
|
||||
of MessageEvent:
|
||||
let c = conns.getOrDefault(key(ws))
|
||||
if c.isNil or message.kind != TextMessage: return
|
||||
try:
|
||||
let m = parseJson(message.data)
|
||||
case m{"t"}.getStr
|
||||
of "move": handleMove(c, m)
|
||||
of "door": handleDoor(c, m)
|
||||
else: c.err("unknown type")
|
||||
except CatchableError:
|
||||
c.err("malformed")
|
||||
of CloseEvent, ErrorEvent: conns.del key(ws)
|
||||
else: discard
|
||||
|
||||
proc cookieSecret(request: Request): string =
|
||||
for (k, v) in request.headers:
|
||||
if k.toLowerAscii == "cookie":
|
||||
for part in v.split(';'):
|
||||
let p = part.strip
|
||||
if p.startsWith("sid="): return p[4 .. ^1]
|
||||
|
||||
proc handler(request: Request) {.gcsafe.} =
|
||||
{.gcsafe.}:
|
||||
let path = request.path
|
||||
if path.startsWith("/join/") and request.httpMethod == "GET":
|
||||
let s = path[6 .. ^1]
|
||||
withLock lk:
|
||||
if s notin secrets: request.respond(403); return
|
||||
var h: HttpHeaders
|
||||
h["Location"] = "/"
|
||||
h["Set-Cookie"] = &"sid={s}; Path=/; HttpOnly; SameSite=Strict"
|
||||
request.respond(302, h)
|
||||
elif path == "/ws":
|
||||
withLock lk:
|
||||
let s = cookieSecret(request)
|
||||
if s notin secrets: request.respond(403); return
|
||||
openConn(request.upgradeToWebSocket(), secrets[s])
|
||||
elif path.startsWith("/tiles/") and path.endsWith(".png"):
|
||||
let parts = path[7 .. ^5].split('_')
|
||||
if parts.len != 2 or parts[0].len notin 1..3 or parts[1].len notin 1..3 or
|
||||
not parts[0].allCharsInSet(Digits) or not parts[1].allCharsInSet(Digits):
|
||||
request.respond(404); return
|
||||
let (tx, ty) = (parseInt(parts[0]), parseInt(parts[1]))
|
||||
if tx >= worldW div tileSize or ty >= worldH div tileSize: request.respond(404); return
|
||||
var ok = false
|
||||
withLock lk:
|
||||
let s = cookieSecret(request)
|
||||
if s in secrets:
|
||||
let rn = secrets[s]
|
||||
ok = rn == "gm"
|
||||
if not ok:
|
||||
let per = tileSize div cell # shortcut: assumes tileSize % exploredCell == 0
|
||||
for cy in ty * per ..< (ty + 1) * per:
|
||||
for cx in tx * per ..< (tx + 1) * per:
|
||||
if (cy * cw + cx) in roles[rn].explored: ok = true
|
||||
if ok:
|
||||
var h: HttpHeaders
|
||||
h["X-Accel-Redirect"] = &"/_tiles/{tx}_{ty}.png"
|
||||
request.respond(200, h)
|
||||
else: request.respond(403)
|
||||
else: request.respond(404)
|
||||
|
||||
proc loadState() =
|
||||
let sc = parseFile("data/scene.json")
|
||||
worldW = sc["world"]["w"].getInt; worldH = sc["world"]["h"].getInt
|
||||
tileSize = sc["tileSize"].getInt; cell = sc["exploredCell"].getInt
|
||||
radius = sc["visionRadius"].getFloat
|
||||
tokRadius = sc["tokenRadius"].getFloat
|
||||
cw = (worldW + cell - 1) div cell
|
||||
for w in sc["walls"]:
|
||||
walls.add Wall(a: (w["a"][0].getFloat, w["a"][1].getFloat), b: (w["b"][0].getFloat, w["b"][1].getFloat),
|
||||
door: w["door"].getBool, open: w["open"].getBool)
|
||||
for t in sc["tokens"]:
|
||||
toks.add Tok(id: t["id"].getStr, name: t["name"].getStr, kind: t["kind"].getStr,
|
||||
pos: (t["pos"][0].getFloat, t["pos"][1].getFloat), gmOnly: t["gmOnly"].getBool)
|
||||
createDir runDir
|
||||
db = open(runDir / "state.db", "", "", "")
|
||||
discard db.getAllRows(sql"PRAGMA journal_mode=WAL")
|
||||
for s in ["CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT)",
|
||||
"CREATE TABLE IF NOT EXISTS tok (id TEXT PRIMARY KEY, x REAL, y REAL)",
|
||||
"CREATE TABLE IF NOT EXISTS door (id INTEGER PRIMARY KEY, open INTEGER)",
|
||||
"CREATE TABLE IF NOT EXISTS exp (role TEXT, c INTEGER, PRIMARY KEY (role, c))"]:
|
||||
db.exec(sql(s))
|
||||
for r in db.getAllRows(sql"SELECT id,x,y FROM tok"):
|
||||
toks[tokIdx(r[0])].pos = (parseFloat(r[1]), parseFloat(r[2]))
|
||||
for r in db.getAllRows(sql"SELECT id,open FROM door"): walls[parseInt(r[0])].open = r[1] == "1"
|
||||
var invites = ""
|
||||
for rn in ["gm", "A", "B"]:
|
||||
var s = db.getValue(sql"SELECT v FROM meta WHERE k=?", rn)
|
||||
if s == "":
|
||||
for b in urandom(16): s.add toHex(b.int, 2).toLowerAscii
|
||||
db.exec(sql"INSERT INTO meta VALUES (?,?)", rn, s)
|
||||
secrets[s] = rn
|
||||
invites.add &"{rn} {origin}/join/{s}\n"
|
||||
if rn != "gm":
|
||||
roles[rn] = Role(ver: 0)
|
||||
for r in db.getAllRows(sql"SELECT c FROM exp WHERE role=?", rn): roles[rn].explored.incl parseInt(r[0])
|
||||
echo invites
|
||||
writeFile(runDir / "invites.txt", invites)
|
||||
db.exec(sql"BEGIN")
|
||||
for rn in roles.keys:
|
||||
recompute(rn); persistCells(rn); roles[rn].fresh.setLen 0
|
||||
db.exec(sql"COMMIT")
|
||||
|
||||
loadState()
|
||||
setControlCHook(proc() {.noconv.} =
|
||||
{.gcsafe.}:
|
||||
printStats() # shortcut: reads stats without the lock; fine at exit
|
||||
quit 0)
|
||||
let server = newServer(handler, wsHandler, workerThreads = 8)
|
||||
echo "listening 127.0.0.1:" & $backendPort
|
||||
stdout.flushFile
|
||||
server.serve(Port(backendPort), "127.0.0.1")
|
||||
@@ -0,0 +1,177 @@
|
||||
import std/[unittest, json, os]
|
||||
import geometry
|
||||
|
||||
proc W(ax, ay, bx, by: float, door = false, open = false): Wall =
|
||||
Wall(a: (ax, ay), b: (bx, by), door: door, open: open)
|
||||
|
||||
proc box(x0, y0, x1, y1: float): seq[Wall] =
|
||||
@[W(x0, y0, x1, y0), W(x1, y0, x1, y1), W(x1, y1, x0, y1), W(x0, y1, x0, y0)]
|
||||
|
||||
proc sees(walls: openArray[Wall], o, p: Vec, r = 500.0): bool =
|
||||
visibilityPolygon(o, walls, r).inside(p)
|
||||
|
||||
suite "visibility":
|
||||
test "open space is a circle":
|
||||
let poly = visibilityPolygon((0.0, 0.0), @[], 100)
|
||||
check poly.inside((60.0, 0.0))
|
||||
check not poly.inside((101.0, 0.0))
|
||||
check poly.inside((0.0, -95.0))
|
||||
|
||||
test "wall blocks":
|
||||
let w = @[W(50, -50, 50, 50)]
|
||||
check not sees(w, (0.0, 0.0), (80.0, 0.0))
|
||||
check sees(w, (0.0, 0.0), (40.0, 0.0))
|
||||
|
||||
test "shared endpoint: no leak at the vertex":
|
||||
# L corner at (50,0); point diagonally behind the vertex
|
||||
let w = @[W(50, -50, 50, 0), W(50, 0, 100, 0)]
|
||||
check not sees(w, (0.0, -20.0), (70.0, -20.0))
|
||||
check sees(w, (0.0, 20.0), (70.0, 20.0))
|
||||
|
||||
test "shared endpoint: closed corner of box has no crack":
|
||||
let w = box(-100, -100, 100, 100)
|
||||
check not sees(w, (0.0, 0.0), (130.0, 130.0), 1000)
|
||||
check not sees(w, (-90.0, -90.0), (-130.0, -130.0), 1000)
|
||||
|
||||
test "collinear walls act as one":
|
||||
let w = @[W(50, -50, 50, 0), W(50, 0, 50, 50)]
|
||||
check not sees(w, (0.0, 0.0), (80.0, 0.0)) # ray through the join
|
||||
check not sees(w, (0.0, 30.0), (80.0, 30.0))
|
||||
|
||||
test "collinear walls with a gap let light through":
|
||||
let w = @[W(50, -50, 50, -5), W(50, 5, 50, 50)]
|
||||
check sees(w, (0.0, 0.0), (80.0, 0.0))
|
||||
check not sees(w, (0.0, 0.0), (80.0, 30.0))
|
||||
|
||||
test "T-junction: no leak and correct shadow":
|
||||
# horizontal y=0 from x=-100..100, vertical stem from (0,0) up to (0,-100)
|
||||
let w = @[W(-100, 0, 100, 0), W(0, 0, 0, -100)]
|
||||
check not sees(w, (-30.0, -30.0), (30.0, -30.0)) # stem blocks
|
||||
check not sees(w, (-30.0, -30.0), (-30.0, 30.0)) # base blocks
|
||||
check sees(w, (-30.0, -30.0), (-80.0, -60.0))
|
||||
check not sees(w, (-30.0, -30.0), (10.0, -5.0), 500)
|
||||
|
||||
test "pillar mid-room casts a shadow, sides visible":
|
||||
var w = box(-200, -200, 200, 200)
|
||||
w.add box(-10, -10, 10, 10)
|
||||
check not sees(w, (-100.0, 0.0), (100.0, 0.0))
|
||||
check sees(w, (-100.0, 0.0), (100.0, 50.0))
|
||||
check sees(w, (-100.0, 0.0), (0.0, 50.0))
|
||||
check not sees(w, (-100.0, 0.0), (50.0, 3.0))
|
||||
|
||||
test "closed door blocks, open door passes":
|
||||
let closed = @[W(50, -50, 50, -10), W(50, -10, 50, 10, true, false), W(50, 10, 50, 50)]
|
||||
var opened = closed
|
||||
opened[1].open = true
|
||||
check not sees(closed, (0.0, 0.0), (90.0, 0.0))
|
||||
check sees(opened, (0.0, 0.0), (90.0, 0.0))
|
||||
check not sees(opened, (0.0, 0.0), (90.0, 40.0))
|
||||
|
||||
test "token exactly at wall endpoint":
|
||||
let w = @[W(0, 0, 100, 0), W(0, 0, 0, 100)] # corner, token on it
|
||||
let poly = visibilityPolygon((0.0, 0.0), w, 200)
|
||||
check poly.len > 3
|
||||
check poly.inside((-50.0, -50.0)) # open outward quadrant
|
||||
check poly.inside((100.0, -30.0))
|
||||
|
||||
test "token at endpoint of free-standing wall sees along it":
|
||||
let w = @[W(0, 0, 100, 0)]
|
||||
check sees(w, (0.0, 0.0), (50.0, -20.0))
|
||||
check sees(w, (0.0, 0.0), (-50.0, 20.0))
|
||||
check sees(w, (0.0, 0.0), (50.0, 20.0))
|
||||
|
||||
test "long thin corridor":
|
||||
# 1000 long, 20 wide, token at one end; radius 2000
|
||||
let w = @[W(0, -10, 1000, -10), W(0, 10, 1000, 10), W(1000, -10, 1000, 10)]
|
||||
check sees(w, (5.0, 0.0), (990.0, 0.0), 2000)
|
||||
check not sees(w, (5.0, 0.0), (500.0, 15.0), 2000)
|
||||
check not sees(w, (5.0, 0.0), (1010.0, 0.0), 2000)
|
||||
check sees(w, (5.0, 0.0), (900.0, 8.0), 2000)
|
||||
|
||||
test "wall endpoints behind the viewer: fan stays angularly ordered":
|
||||
# regression: circle angles in [0,2pi) were sorted against atan2 angles in (-pi,pi] -> bow-tie polygon
|
||||
let w = box(600, 600, 680, 680) & @[W(1024, 256, 1024, 608)]
|
||||
check sees(w, (908.66, 672.03), (789.36, 584.65), 400)
|
||||
check sees(w, (789.36, 584.65), (908.66, 672.03), 400)
|
||||
|
||||
test "radius clips":
|
||||
check not sees(@[], (0.0, 0.0), (300.0, 0.0), 200)
|
||||
|
||||
suite "moves":
|
||||
let wall = W(0, -50, 0, 50)
|
||||
test "crossing blocked, parallel ok":
|
||||
check moveBlocked([wall], (-10.0, 0.0), (10.0, 0.0))
|
||||
check not moveBlocked([wall], (-10.0, 0.0), (-10.0, 30.0))
|
||||
check not moveBlocked([wall], (-10.0, 60.0), (10.0, 60.0)) # passes beyond the end
|
||||
test "grazing an endpoint is blocked":
|
||||
check moveBlocked([wall], (-10.0, 50.0), (10.0, 50.0))
|
||||
check moveBlocked([wall], (-10.0, -60.0), (10.0, -40.0)) # crosses
|
||||
test "no leak through shared vertex":
|
||||
let w = [W(0, -50, 0, 0), W(0, 0, 0, 50)]
|
||||
check moveBlocked(w, (-10.0, 0.0), (10.0, 0.0))
|
||||
test "diagonal squeeze through corner vertex of L":
|
||||
let w = [W(0, 0, 50, 0), W(0, 0, 0, 50)]
|
||||
check moveBlocked(w, (10.0, -10.0), (-10.0, 10.0))
|
||||
test "moving along a collinear wall is blocked":
|
||||
check moveBlocked([wall], (0.0, -100.0), (0.0, 100.0))
|
||||
test "doors":
|
||||
var d = W(0, -10, 0, 10, true, false)
|
||||
check moveBlocked([d], (-5.0, 0.0), (5.0, 0.0))
|
||||
d.open = true
|
||||
check not moveBlocked([d], (-5.0, 0.0), (5.0, 0.0))
|
||||
test "zero-length move":
|
||||
check not moveBlocked([wall], (-5.0, 0.0), (-5.0, 0.0))
|
||||
|
||||
suite "cells":
|
||||
test "square polygon":
|
||||
let sq = [(10.0, 10.0), (50.0, 10.0), (50.0, 50.0), (10.0, 50.0)]
|
||||
check cellsTouched(sq, 32) == @[(0, 0), (1, 0), (0, 1), (1, 1)]
|
||||
test "tiny polygon inside one cell":
|
||||
check cellsTouched([(1.0, 1.0), (5.0, 1.0), (3.0, 5.0)], 32) == @[(0, 0)]
|
||||
test "polygon spanning a cell with no vertex in it":
|
||||
# thin horizontal strip crossing 3 cells
|
||||
let strip = [(1.0, 10.0), (95.0, 10.0), (95.0, 12.0), (1.0, 12.0)]
|
||||
check cellsTouched(strip, 32) == @[(0, 0), (1, 0), (2, 0)]
|
||||
test "big polygon includes fully covered interior cells":
|
||||
let big = [(0.0, 0.0), (200.0, 0.0), (200.0, 200.0), (0.0, 200.0)]
|
||||
check (3, 3) in cellsTouched(big, 32)
|
||||
|
||||
suite "seed":
|
||||
test "every token in seed sees itself and is not walled in":
|
||||
let sp = currentSourcePath().parentDir / ".." / "data" / "scene.json"
|
||||
if not fileExists(sp): skip()
|
||||
else:
|
||||
let j = parseFile(sp)
|
||||
var walls: seq[Wall]
|
||||
for w in j["walls"]:
|
||||
walls.add Wall(a: (w["a"][0].getFloat, w["a"][1].getFloat), b: (w["b"][0].getFloat, w["b"][1].getFloat),
|
||||
door: w{"door"}.getBool, open: w{"open"}.getBool)
|
||||
for t in j["tokens"]:
|
||||
let p: Vec = (t["pos"][0].getFloat, t["pos"][1].getFloat)
|
||||
let poly = visibilityPolygon(p, walls, j["visionRadius"].getFloat)
|
||||
check poly.len > 8
|
||||
check cellsTouched(poly, j["exploredCell"].getFloat).len > 0
|
||||
check not moveBlocked(walls, p, p, j["tokenRadius"].getFloat)
|
||||
|
||||
suite "token clearance (r=20)":
|
||||
const r = 20.0
|
||||
test "near pillar: circle overlapping blocked, clear ok":
|
||||
let pil = box(600, 600, 680, 680)
|
||||
check moveBlocked(pil, (500.0, 640.0), (585.0, 640.0), r) # center outside, circle inside wall
|
||||
check not moveBlocked(pil, (500.0, 640.0), (570.0, 640.0), r) # 30 away
|
||||
test "near closed door blocks, open door passes":
|
||||
let cl = @[W(0, 0, 0, 64, door = true)]
|
||||
check moveBlocked(cl, (-50.0, 32.0), (10.0, 32.0), r) # dest 10 from the wall
|
||||
check moveBlocked(cl, (-50.0, 32.0), (-10.0, 32.0), r)
|
||||
let op = @[W(0, 0, 0, 64, door = true, open = true)]
|
||||
check not moveBlocked(op, (-50.0, 32.0), (50.0, 32.0), r)
|
||||
test "64px corridor and doorway passable on centerline":
|
||||
let c = @[W(0, 0, 500, 0), W(0, 64, 500, 64)]
|
||||
check not moveBlocked(c, (10.0, 32.0), (490.0, 32.0), r)
|
||||
check not moveBlocked(c, (10.0, 32.0), (11.0, 32.0), r)
|
||||
let door = @[W(0, -200, 0, -32), W(0, 32, 0, 200)]
|
||||
check not moveBlocked(door, (-30.0, 0.0), (30.0, 0.0), r)
|
||||
test "legacy overlap can escape, not stay overlapped":
|
||||
let w = @[W(0, 0, 100, 0)]
|
||||
check not moveBlocked(w, (50.0, 5.0), (50.0, 40.0), r)
|
||||
check moveBlocked(w, (50.0, 5.0), (50.0, 15.0), r)
|
||||
@@ -0,0 +1,29 @@
|
||||
## Vision microbench: nim c -d:release -r tools/bench.nim (devbox run bench)
|
||||
import std/[json, monotimes, times, strformat]
|
||||
import geometry
|
||||
let j = parseFile("data/scene.json")
|
||||
var walls: seq[Wall]
|
||||
for w in j["walls"]:
|
||||
walls.add Wall(a: (w["a"][0].getFloat, w["a"][1].getFloat), b: (w["b"][0].getFloat, w["b"][1].getFloat), door: w["door"].getBool, open: w["open"].getBool)
|
||||
let r = j["visionRadius"].getFloat
|
||||
var ps: seq[Vec]
|
||||
for t in j["tokens"]: ps.add (t["pos"][0].getFloat, t["pos"][1].getFloat)
|
||||
proc bench(name: string, n: int, f: proc(i: int)) =
|
||||
var sum, worst = 0.0
|
||||
for i in 0 ..< n:
|
||||
let t0 = getMonoTime(); f(i)
|
||||
let ms = (getMonoTime() - t0).inNanoseconds.float / 1e6
|
||||
sum += ms; worst = max(worst, ms)
|
||||
echo &"{name}: n={n} avg={sum / n.float:.3f}ms worst={worst:.3f}ms"
|
||||
var sink = 0
|
||||
bench("1 poly (jittered start positions)", 2000, proc(i: int) =
|
||||
let p = ps[i mod 8]; sink += visibilityPolygon((p.x + float(i mod 50), p.y), walls, r).len)
|
||||
bench("6 polys (one 6-token party)", 500, proc(i: int) =
|
||||
for k in 0 ..< 6:
|
||||
let p = ps[k + 2]; sink += visibilityPolygon((p.x + float(i mod 50), p.y), walls, r).len)
|
||||
bench("1 poly + cellsTouched", 2000, proc(i: int) =
|
||||
let p = ps[i mod 8]; sink += cellsTouched(visibilityPolygon((p.x + float(i mod 50), p.y), walls, r), 32).len)
|
||||
bench("6 polys + cellsTouched", 300, proc(i: int) =
|
||||
for k in 0 ..< 6:
|
||||
let p = ps[k + 2]; sink += cellsTouched(visibilityPolygon((p.x + float(i mod 50), p.y), walls, r), 32).len)
|
||||
echo "(sink ", sink, ")"
|
||||
@@ -0,0 +1,82 @@
|
||||
// A, B, GM hammer the server concurrently (moves every 20-50 ms per token, GM toggles doors), then compare views to fresh connections.
|
||||
import { connect, sleep } from './lib.mjs'
|
||||
const DUR = (process.env.DUR ?? 60) * 1000
|
||||
const fails = []
|
||||
const check = (c, m) => { if (!c) { fails.push(m); console.log('FAIL', m) } }
|
||||
const sendT = new Map(), lat = { self: [], other: [] }
|
||||
|
||||
function mkState(name) {
|
||||
const st = { name, toks: new Map(), doors: new Map(), explored: new Set(), poly: '[]', last: -1, backwards: 0, msgs: 0, bytes: 0, errors: 0, sent: 0, acks: 0, nack: 0, pending: new Set(), req: 0 }
|
||||
st.on = (m, b) => {
|
||||
st.msgs++; st.bytes += b
|
||||
if (m.gseq < st.last) st.backwards++
|
||||
st.last = m.gseq
|
||||
switch (m.t) {
|
||||
case 'hello': st.toks.clear(); st.explored.clear(); st.doors.clear(); st.poly = '[]'; break
|
||||
case 'walls': for (const w of m.walls) if (w.door) st.doors.set(w.id, w.open); break
|
||||
case 'door': st.doors.set(m.id, m.open); break
|
||||
case 'vision': st.poly = JSON.stringify(m.polys); break
|
||||
case 'explored': for (const c of m.cells) st.explored.add(c + ''); break
|
||||
case 'token':
|
||||
st.toks.set(m.id, m.pos + '')
|
||||
if (m.reqId !== undefined) { const t0 = sendT.get(m.by + ':' + m.reqId); if (t0 && m.by !== st.name) lat.other.push(performance.now() - t0) }
|
||||
break
|
||||
case 'remove': st.toks.delete(m.id); break
|
||||
case 'moveAck': st.acks++; st.pending.delete(m.reqId); if (!m.ok) st.nack++; st.onAck?.(m); break
|
||||
case 'error': st.errors++; break
|
||||
}
|
||||
}
|
||||
return st
|
||||
}
|
||||
const S = { gm: mkState('gm'), A: mkState('A'), B: mkState('B') }
|
||||
const C = {}
|
||||
for (const r of ['gm', 'A', 'B']) C[r] = await connect(r, S[r].on)
|
||||
|
||||
// random walkers: [client, token id, box]
|
||||
const walkers = [['A', 'A', [300, 300, 980, 980], [400, 400]], ['B', 'B', [300, 2100, 980, 2780], [400, 2200]],
|
||||
['gm', 'M1', [300, 300, 980, 980], [900, 900]], ['gm', 'M2', [1600, 300, 2250, 980], [1920, 640]], ['gm', 'M3', [2870, 300, 3530, 980], [3400, 500]],
|
||||
['gm', 'M4', [300, 2100, 980, 2780], [900, 2700]], ['gm', 'M5', [1600, 2100, 2250, 2780], [1920, 2400]], ['gm', 'M6', [2870, 2100, 3530, 2780], [3200, 2400]]]
|
||||
let running = true
|
||||
const rnd = (a, b) => a + Math.random() * (b - a)
|
||||
const loops = walkers.map(async ([who, id, [x0, y0, x1, y1], p]) => {
|
||||
const st = S[who]
|
||||
while (running) {
|
||||
p = [Math.min(x1, Math.max(x0, p[0] + rnd(-40, 40))), Math.min(y1, Math.max(y0, p[1] + rnd(-40, 40)))]
|
||||
const r = ++st.req; st.pending.add(r); st.sent++
|
||||
sendT.set(who + ':' + r, performance.now())
|
||||
st.onAck = m => { const t0 = sendT.get(who + ':' + m.reqId); if (t0) lat.self.push(performance.now() - t0); if (!m.ok) p = m.pos } // blocked: resync to server pos (shortcut: GM shares one onAck, only the last walker resyncs)
|
||||
C[who].ws.send(JSON.stringify({ t: 'move', reqId: r, id, pos: p }))
|
||||
await sleep(rnd(20, 50))
|
||||
}
|
||||
})
|
||||
const doorLoop = (async () => { let o = true; while (running) { await sleep(rnd(1000, 3000)); o = !o; C.gm.ws.send(JSON.stringify({ t: 'door', id: 10, open: o })); C.gm.ws.send(JSON.stringify({ t: 'door', id: 27, open: !o })) } })()
|
||||
const t0 = performance.now()
|
||||
await sleep(DUR)
|
||||
running = false
|
||||
await Promise.all([...loops, doorLoop])
|
||||
for (let i = 0; i < 100 && Object.values(S).some(s => s.pending.size); i++) await sleep(100)
|
||||
await sleep(500)
|
||||
|
||||
// quiesced: compare against fresh connections
|
||||
const F = {}
|
||||
for (const r of ['gm', 'A', 'B']) { F[r] = mkState(r); await connect(r, F[r].on) }
|
||||
const sig = m => JSON.stringify([...m].sort())
|
||||
for (const r of ['gm', 'A', 'B']) {
|
||||
const s = S[r], f = F[r]
|
||||
check(s.pending.size === 0, `${r}: ${s.pending.size} moves never acked`)
|
||||
check(s.sent === s.acks, `${r}: sent ${s.sent} acks ${s.acks}`)
|
||||
check(s.backwards === 0, `${r}: gseq went backwards ${s.backwards}x`)
|
||||
check(s.errors === 0, `${r}: ${s.errors} error msgs`)
|
||||
check(sig(s.toks) === sig(f.toks), `${r}: token view != fresh snapshot`)
|
||||
check(sig(s.doors) === sig(f.doors), `${r}: doors != fresh`)
|
||||
check(s.poly === f.poly, `${r}: vision != fresh`)
|
||||
check(sig(s.explored) === sig(f.explored), `${r}: explored != fresh (${s.explored.size} vs ${f.explored.size})`)
|
||||
}
|
||||
const q = (a, p) => a.length ? a.slice().sort((x, y) => x - y)[Math.min(a.length - 1, Math.floor(a.length * p))] : NaN
|
||||
const st = a => `n=${a.length} avg=${(a.reduce((x, y) => x + y, 0) / a.length).toFixed(2)}ms p95=${q(a, 0.95).toFixed(2)}ms worst=${Math.max(...a).toFixed(2)}ms`
|
||||
const secs = (performance.now() - t0) / 1000
|
||||
for (const r of ['gm', 'A', 'B']) console.log(`${r}: sent ${S[r].sent} moves (${(S[r].sent / secs).toFixed(0)}/s), acks ${S[r].acks} (nack ${S[r].nack}), recv ${S[r].msgs} msgs ${(S[r].bytes / 1024).toFixed(0)} KiB, final gseq ${S[r].last}, tokens in view ${S[r].toks.size}`)
|
||||
console.log('latency intent->ack (sender):', st(lat.self))
|
||||
console.log('latency intent->arrival at other clients:', st(lat.other))
|
||||
console.log(fails.length ? `FAILED ${fails.length}` : 'concurrency: PASS')
|
||||
process.exit(fails.length ? 1 : 0)
|
||||
@@ -0,0 +1,106 @@
|
||||
// One command: node tools/genmap.mjs -> data/scene.json (source of truth) + data/tiles/<x>_<y>.png
|
||||
// `--from-seed` skips scene generation and re-renders tiles from the existing data/scene.json.
|
||||
// Deterministic: layout is hand-authored (no RNG) so the seed edge cases are guaranteed.
|
||||
import fs from 'node:fs'
|
||||
import zlib from 'node:zlib'
|
||||
|
||||
const SIZE = 4096, TILE = 256, DIR = new URL('../data/', import.meta.url).pathname
|
||||
const seedPath = DIR + 'scene.json'
|
||||
|
||||
function build() {
|
||||
const walls = []
|
||||
const add = (a, b, extra = {}) => walls.push({ id: walls.length, a, b, door: false, open: false, ...extra })
|
||||
const H = (y, x0, x1, e) => add([x0, y], [x1, y], e)
|
||||
const V = (x, y0, y1, e) => add([x, y0], [x, y1], e)
|
||||
// split [lo,hi] by gaps [a,b,door?]; plain gap = opening, door gap = door segment
|
||||
const side = (lo, hi, gaps, emit) => {
|
||||
let c = lo
|
||||
for (const [a, b, d] of [...gaps].sort((p, q) => p[0] - q[0])) {
|
||||
if (a > c) emit(c, a)
|
||||
if (d) emit(a, b, { door: true, open: d === 'open' })
|
||||
c = b
|
||||
}
|
||||
if (c < hi) emit(c, hi)
|
||||
}
|
||||
const room = (x0, y0, x1, y1, g = {}) => {
|
||||
side(x0, x1, g.n ?? [], (a, b, e) => H(y0, a, b, e))
|
||||
side(x0, x1, g.s ?? [], (a, b, e) => H(y1, a, b, e))
|
||||
side(y0, y1, g.w ?? [], (a, b, e) => V(x0, a, b, e))
|
||||
side(y0, y1, g.e ?? [], (a, b, e) => V(x1, a, b, e))
|
||||
}
|
||||
const rooms = [
|
||||
[256, 256, 1024, 1024, { e: [[608, 672]], s: [[608, 672]] }], // R1 (pillar)
|
||||
[1536, 256, 2304, 1024, { w: [[608, 672, 'closed']], e: [[608, 672]], s: [[1888, 1952]] }], // R2: door 1
|
||||
[2816, 256, 3584, 1024, { w: [[608, 672]], s: [[3168, 3232]] }], // R3 (T-junction, split north wall)
|
||||
[256, 2048, 1024, 2816, { n: [[608, 672]], e: [[2400, 2464]] }], // R4
|
||||
[1536, 2048, 2304, 2816, { n: [[1888, 1952, 'open']], w: [[2400, 2464]], e: [[2400, 2464]] }], // R5: door 2
|
||||
[2816, 2048, 3584, 2816, { n: [[3168, 3232]], w: [[2400, 2464]] }], // R6
|
||||
]
|
||||
const floors = rooms.map(r => r.slice(0, 4))
|
||||
rooms.forEach(r => room(...r))
|
||||
// collinear: split R3's north wall into two touching pieces at x=3200
|
||||
const n3 = walls.find(w => w.a[0] === 2816 && w.a[1] === 256 && w.b[0] === 3584 && w.b[1] === 256)
|
||||
n3.b = [3200, 256]; H(256, 3200, 3584)
|
||||
// corridors: two parallel walls + floor
|
||||
const hc = (y0, y1, x0, x1) => { H(y0, x0, x1); H(y1, x0, x1); floors.push([x0, y0, x1, y1]) }
|
||||
const vc = (x0, x1, y0, y1) => { V(x0, y0, y1); V(x1, y0, y1); floors.push([x0, y0, x1, y1]) }
|
||||
hc(608, 672, 1024, 1536); hc(608, 672, 2304, 2816) // R1-R2 (door at R2 end), R2-R3
|
||||
hc(2400, 2464, 1024, 1536); hc(2400, 2464, 2304, 2816) // R4-R5, R5-R6
|
||||
vc(1888, 1952, 1024, 2048) // R2-R5: 1024 long, 64 wide (long thin)
|
||||
vc(3168, 3232, 1024, 2048); vc(608, 672, 1024, 2048) // R3-R6, R1-R4
|
||||
// pillar mid-room R1 (centre 640,640)
|
||||
H(600, 600, 680); H(680, 600, 680); V(600, 600, 680); V(680, 600, 680)
|
||||
// T-junction: partition ends mid-way on R3's south wall piece (2816..3168) at x=3000
|
||||
V(3000, 700, 1024)
|
||||
const tok = (id, kind, name, pos, gmOnly) => ({ id, kind, name, pos, gmOnly })
|
||||
const tokens = [
|
||||
tok('A', 'player', 'Player A', [400, 400], false),
|
||||
tok('B', 'player', 'Player B', [400, 2200], false),
|
||||
...[[900, 900], [1920, 640], [3400, 500], [900, 2700], [1920, 2400], [3200, 2400]]
|
||||
.map((p, i) => tok(`M${i + 1}`, 'monster', `Monster ${i + 1}`, p, true)),
|
||||
]
|
||||
return { world: { w: SIZE, h: SIZE }, tileSize: TILE, visionRadius: 400, tokenRadius: 20, exploredCell: 32, walls, floors, tokens }
|
||||
}
|
||||
|
||||
// --- raster ---
|
||||
const crcT = Uint32Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0 })
|
||||
const crc = b => { let c = ~0; for (const x of b) c = crcT[(c ^ x) & 255] ^ (c >>> 8); return ~c >>> 0 }
|
||||
const chunk = (t, d) => { const b = Buffer.alloc(12 + d.length); b.writeUInt32BE(d.length); b.write(t, 4); d.copy(b, 8); b.writeUInt32BE(crc(b.subarray(4, 8 + d.length)), 8 + d.length); return b }
|
||||
function png(rgb, w, h) {
|
||||
const raw = Buffer.alloc((w * 3 + 1) * h)
|
||||
for (let y = 0; y < h; y++) rgb.copy(raw, y * (w * 3 + 1) + 1, y * w * 3, (y + 1) * w * 3)
|
||||
const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2
|
||||
return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))])
|
||||
}
|
||||
|
||||
function render(scene) {
|
||||
const img = Buffer.alloc(SIZE * SIZE * 3)
|
||||
const fill = (x0, y0, x1, y1, [r, g, b]) => {
|
||||
for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) { const i = (y * SIZE + x) * 3; img[i] = r; img[i + 1] = g; img[i + 2] = b }
|
||||
}
|
||||
fill(0, 0, SIZE, SIZE, [24, 22, 28])
|
||||
for (const [x0, y0, x1, y1] of scene.floors) fill(x0, y0, x1, y1, [120, 112, 100])
|
||||
const HALF = 4
|
||||
for (const w of scene.walls) {
|
||||
const [ax, ay] = w.a, [bx, by] = w.b
|
||||
// door look is state-independent: tiles must not reveal or go stale on open/closed
|
||||
const col = w.door ? [150, 80, 30] : [10, 10, 12]
|
||||
const dx = bx - ax, dy = by - ay, L2 = dx * dx + dy * dy
|
||||
for (let y = Math.max(0, Math.min(ay, by) - HALF); y <= Math.min(SIZE - 1, Math.max(ay, by) + HALF); y++)
|
||||
for (let x = Math.max(0, Math.min(ax, bx) - HALF); x <= Math.min(SIZE - 1, Math.max(ax, bx) + HALF); x++) {
|
||||
const t = Math.max(0, Math.min(1, ((x - ax) * dx + (y - ay) * dy) / L2))
|
||||
if (Math.hypot(x - ax - t * dx, y - ay - t * dy) <= HALF) { const i = (y * SIZE + x) * 3; img[i] = col[0]; img[i + 1] = col[1]; img[i + 2] = col[2] }
|
||||
}
|
||||
}
|
||||
fs.rmSync(DIR + 'tiles', { recursive: true, force: true }); fs.mkdirSync(DIR + 'tiles', { recursive: true })
|
||||
const tile = Buffer.alloc(TILE * TILE * 3)
|
||||
for (let ty = 0; ty < SIZE / TILE; ty++) for (let tx = 0; tx < SIZE / TILE; tx++) {
|
||||
for (let y = 0; y < TILE; y++) img.copy(tile, y * TILE * 3, ((ty * TILE + y) * SIZE + tx * TILE) * 3, ((ty * TILE + y) * SIZE + (tx + 1) * TILE) * 3)
|
||||
fs.writeFileSync(`${DIR}tiles/${tx}_${ty}.png`, png(tile, TILE, TILE))
|
||||
}
|
||||
}
|
||||
|
||||
fs.mkdirSync(DIR, { recursive: true })
|
||||
if (!process.argv.includes('--from-seed')) fs.writeFileSync(seedPath, JSON.stringify(build(), null, 1))
|
||||
render(JSON.parse(fs.readFileSync(seedPath, 'utf8')))
|
||||
console.log('scene.json + 256 tiles ->', DIR)
|
||||
@@ -0,0 +1,65 @@
|
||||
// Leak test driver: scripted walk of A, GM + B as ground truth/noise. Writes run/leak-transcript.jsonl; tools/leakcheck.nim verifies it.
|
||||
// SUBJECT=A|B (default A) is the player whose tile sweeps/view are checked (leakcheck reads the same env); the other walks as noise.
|
||||
// Everything is sequential (one actor at a time) so every tile sweep sees a quiescent server at a known gseq.
|
||||
import fs from 'node:fs'
|
||||
import { O, RUN, connect, sleep } from './lib.mjs'
|
||||
const out = fs.createWriteStream(`${RUN}/leak-transcript.jsonl`)
|
||||
const log = o => out.write(JSON.stringify(o) + '\n')
|
||||
let gmG = 0
|
||||
const S = process.env.SUBJECT ?? 'A'
|
||||
const acks = new Map(), req = { A: 0, B: 0, GM: 0 }
|
||||
const mk = who => connect(who === 'GM' ? 'gm' : who, m => {
|
||||
log({ k: 'msg', who, m })
|
||||
if (who === 'GM') gmG = m.gseq
|
||||
if (m.t === 'moveAck') acks.get(who + m.reqId)?.(m)
|
||||
})
|
||||
const [gm, A, B] = [await mk('GM'), await mk('A'), await mk('B')]
|
||||
const cl = { GM: gm, A, B }
|
||||
const pos = { A: [400, 400], B: [400, 2200], M1: [900, 900], M2: [1920, 640], M5: [1920, 2400] }
|
||||
const owner = id => (id === 'A' || id === 'B' ? id : 'GM')
|
||||
const mv = (id, p) => new Promise(res => { const w = owner(id), r = ++req[w]; acks.set(w + r, res); cl[w].ws.send(JSON.stringify({ t: 'move', reqId: r, id, pos: p })) })
|
||||
const tiles = Object.keys(Array.from({ length: 256 })).map(i => [i % 16, Math.floor(i / 16)])
|
||||
async function sweep(label) {
|
||||
await sleep(40)
|
||||
const g = gmG
|
||||
for (let i = 0; i < tiles.length; i += 32)
|
||||
await Promise.all(tiles.slice(i, i + 32).map(async ([x, y]) => {
|
||||
const r = await fetch(`${O}/tiles/${x}_${y}.png`, { headers: { Cookie: cl[S].cookie } })
|
||||
await r.arrayBuffer(); log({ k: 'tile', g, x, y, s: r.status, label })
|
||||
}))
|
||||
}
|
||||
const acts = []
|
||||
const cur = { ...pos }
|
||||
const walk = (id, to, expectFail = false) => {
|
||||
const [x, y] = cur[id], d = Math.hypot(to[0] - x, to[1] - y), n = Math.ceil(d / 40)
|
||||
for (let i = 1; i <= n; i++) acts.push({ id, p: [x + (to[0] - x) * i / n, y + (to[1] - y) * i / n], fail: expectFail && i === n })
|
||||
if (!expectFail) cur[id] = to
|
||||
}
|
||||
const door = (id, open) => acts.push({ door: [id, open] })
|
||||
const sw = label => acts.push({ sweep: label })
|
||||
sw('start')
|
||||
walk('B', [700, 2300])
|
||||
walk('A', [400, 800]); walk('A', [800, 800]); sw('M1 in view')
|
||||
walk('A', [800, 640]); walk('A', [1000, 640]); walk('A', [1510, 640])
|
||||
walk('A', [1540, 640], true); sw('closed door blocks')
|
||||
walk('M2', [1700, 640]); sw('M2 behind closed door')
|
||||
door(10, true); sw('door open'); walk('A', [1700, 640]); walk('M2', [1900, 700]); walk('A', [1900, 640]); sw('M2 close')
|
||||
walk('M2', [2200, 300]); sw('M2 left'); walk('M1', [900, 640]); walk('M1', [1200, 640]); sw('M1 into corridor')
|
||||
walk('A', [1920, 900]); walk('A', [1920, 1900]); sw('corridor')
|
||||
door(27, false); sw('door 27 closed'); walk('A', [1920, 2020]); walk('A', [1920, 2060], true); sw('blocked'); door(27, true); sw('door 27 open')
|
||||
walk('A', [1920, 2300]); sw('R5')
|
||||
walk('B', [700, 2430]); walk('B', [1400, 2430]); walk('B', [1700, 2430]); sw('B visible?'); walk('B', [1000, 2430]); sw('B away')
|
||||
walk('A', [1920, 2500]); sw('M5 in view'); walk('M5', [2200, 2700]); sw('M5 away'); walk('A', [1700, 2700]); sw('end')
|
||||
let nA = 0, bad = 0
|
||||
for (const a of acts) {
|
||||
if (a.sweep) { await sweep(a.sweep); continue }
|
||||
if (a.door) { cl.GM.ws.send(JSON.stringify({ t: 'door', id: a.door[0], open: a.door[1] })); await sleep(40); continue }
|
||||
const m = await mv(a.id, a.p)
|
||||
if (m.ok === !!a.fail) { bad++; console.log('unexpected ack', a, m) }
|
||||
if (a.id === S && ++nA % 5 === 0) await sweep('walk'); else await sleep(15)
|
||||
}
|
||||
await sleep(200)
|
||||
for (const c of [gm, A, B]) c.ws.close()
|
||||
out.end()
|
||||
console.log(`driver done: ${acts.length} actions, ${bad} unexpected acks, final gseq ${gmG}`)
|
||||
process.exit(bad ? 1 : 0)
|
||||
@@ -0,0 +1,140 @@
|
||||
## Leak checker: replays run/leak-transcript.jsonl. Ground truth = GM socket (tokens+doors per gseq);
|
||||
## subject (SUBJECT env, A|B)'s vision/explored are recomputed with geometry.nim, never taken from A's own messages.
|
||||
import std/[json, tables, sets, strutils, os, math]
|
||||
import geometry
|
||||
|
||||
let me = getEnv("SUBJECT", "A") # subject whose view is checked; the other player is noise
|
||||
let other = if me == "A": "B" else: "A"
|
||||
type Side = enum Out, Amb, In
|
||||
var fails = 0
|
||||
proc fail(s: string) =
|
||||
inc fails
|
||||
if fails <= 20: echo "FAIL ", s
|
||||
|
||||
# boundary is ambiguous in inside(): In/Out only if the point and its 0.5px neighbours agree
|
||||
proc side(poly: seq[Vec], p: Vec): Side =
|
||||
var n = 0
|
||||
for d in [(0.0, 0.0), (0.5, 0.0), (-0.5, 0.0), (0.0, 0.5), (0.0, -0.5)]:
|
||||
if poly.inside((p.x + d[0], p.y + d[1])): inc n
|
||||
if n == 0: Out elif n == 5: In else: Amb
|
||||
|
||||
proc vec(j: JsonNode): Vec = (j[0].getFloat, j[1].getFloat)
|
||||
const banned = ["walls", "door", "open", "a", "b", "segments", "segs", "wall"]
|
||||
const allowed = ["hello", "vision", "explored", "token", "remove", "moveAck"]
|
||||
proc scan(j: JsonNode, t: string) =
|
||||
if j.kind == JObject:
|
||||
for k, v in j:
|
||||
if k in banned: fail "A msg " & t & " has wall-like key " & k
|
||||
scan(v, t)
|
||||
elif j.kind == JArray:
|
||||
for v in j: scan(v, t)
|
||||
|
||||
var gm, am: seq[JsonNode]
|
||||
var tiles: seq[JsonNode]
|
||||
for line in lines(getEnv("RUN_DIR", "run") / "leak-transcript.jsonl"):
|
||||
let j = parseJson(line)
|
||||
if j["k"].getStr == "tile": tiles.add j
|
||||
elif j["who"].getStr == "GM": gm.add j["m"]
|
||||
elif j["who"].getStr == me: am.add j["m"]
|
||||
# the other player's transcript is deliberately unused: it is only noise
|
||||
|
||||
let radius = parseFile("data/scene.json")["visionRadius"].getFloat
|
||||
var walls: seq[Wall]
|
||||
var truth: Table[string, Vec]
|
||||
var tileSize, cell, cw: int
|
||||
var firstG: Table[int, int] # explored cell -> gseq it first became explored (independent)
|
||||
var view: Table[string, Vec] # what A has been told
|
||||
var aExp: HashSet[int]
|
||||
var ai, removes, groups, expN: int
|
||||
var seen: HashSet[string]
|
||||
|
||||
proc finalize(g: int) =
|
||||
inc groups
|
||||
let poly = visibilityPolygon(truth[me], walls, radius)
|
||||
# independent oracle (segment tests, not the ray fan): clear straight line to a point in range => point is in the polygon
|
||||
for i in 0 ..< 64:
|
||||
for k in [0.3, 0.6, 0.95]:
|
||||
let o = truth[me]
|
||||
let p: Vec = (o.x + k * radius * cos(2 * PI * i.float / 64), o.y + k * radius * sin(2 * PI * i.float / 64))
|
||||
if not moveBlocked(walls, o, p) and side(poly, p) == Out: fail "polygon misses clear-LOS point " & $p & " at g=" & $g
|
||||
for (ix, iy) in cellsTouched(poly, cell.float):
|
||||
if ix >= 0 and iy >= 0 and ix < cw and iy < cw and (iy * cw + ix) notin firstG:
|
||||
firstG[iy * cw + ix] = g; inc expN
|
||||
while ai < am.len and am[ai]["gseq"].getInt <= g:
|
||||
let m = am[ai]; inc ai
|
||||
let t = m["t"].getStr
|
||||
if t == "error": fail "A got error " & $m
|
||||
if t notin allowed: fail "A got forbidden type " & t; continue
|
||||
if t == "moveAck": continue
|
||||
scan(m, t)
|
||||
if m["gseq"].getInt != g: fail "A msg gseq " & $m["gseq"] & " not in GM log (group " & $g & ")"
|
||||
if t notin ["token", "remove"] and "\"" & other & "\"" in $m: fail other & " mentioned in " & $m
|
||||
case t
|
||||
of "hello": (if m["tokens"] != %[me]: fail "hello tokens " & $m["tokens"])
|
||||
of "token":
|
||||
let id = m["id"].getStr
|
||||
if id notin truth: fail "unknown token " & id; continue
|
||||
if vec(m["pos"]) != truth[id]: fail "token " & id & " pos != truth at g=" & $g
|
||||
if m["mine"].getBool != (id == me): fail "mine flag " & id
|
||||
if id != other and m{"by"}.getStr == other: fail other & " leak via by on " & id
|
||||
if id != me and side(poly, truth[id]) == Out: fail "LEAK token " & id & " outside A vision at g=" & $g
|
||||
view[id] = vec(m["pos"]); seen.incl id
|
||||
of "remove":
|
||||
let id = m["id"].getStr
|
||||
if id notin view: fail "remove of unknown " & id
|
||||
if id in truth and side(poly, truth[id]) == In: fail "remove of token still visible " & id
|
||||
view.del id; inc removes
|
||||
of "vision":
|
||||
let ps = m["polys"]
|
||||
if ps.len != 1 or ps[0].len != poly.len: fail "vision shape at g=" & $g; continue
|
||||
for i in 0 ..< poly.len:
|
||||
let p = ps[0][i]
|
||||
if abs(p[0].getFloat - poly[i].x) > 1e-6 or abs(p[1].getFloat - poly[i].y) > 1e-6: fail "vision vertex differs at g=" & $g; break
|
||||
of "explored":
|
||||
for c in m["cells"]:
|
||||
let k = c[1].getInt * cw + c[0].getInt
|
||||
if firstG.getOrDefault(k, int.high) > g: fail "LEAK explored cell not yet explored " & $c
|
||||
aExp.incl k
|
||||
else: discard
|
||||
if aExp.len != expN: fail "explored count at g=" & $g & ": A " & $aExp.len & " expected " & $expN
|
||||
for id, p in truth:
|
||||
let s = side(poly, p)
|
||||
if s == Amb and id != me: continue
|
||||
let want = id == me or s == In
|
||||
if want != (id in view): fail "view mismatch " & id & " want=" & $want & " at g=" & $g
|
||||
elif want and view[id] != p: fail "view pos stale " & id & " at g=" & $g
|
||||
|
||||
var curG = -1
|
||||
for m in gm:
|
||||
let g = m["gseq"].getInt
|
||||
if curG >= 0 and g != curG: finalize(curG)
|
||||
curG = g
|
||||
case m["t"].getStr
|
||||
of "hello": tileSize = m["tileSize"].getInt; cell = m["exploredCell"].getInt; cw = (m["world"]["w"].getInt + cell - 1) div cell
|
||||
of "walls":
|
||||
for w in m["walls"]: walls.add Wall(a: vec(w["a"]), b: vec(w["b"]), door: w["door"].getBool, open: w["open"].getBool)
|
||||
of "door": walls[m["id"].getInt].open = m["open"].getBool
|
||||
of "token": truth[m["id"].getStr] = vec(m["pos"])
|
||||
else: discard
|
||||
finalize(curG)
|
||||
if ai < am.len: fail "A messages after last GM gseq: " & $am[ai]
|
||||
|
||||
var n200, n403, nOther: int
|
||||
for t in tiles:
|
||||
let g = t["g"].getInt
|
||||
var exp = false
|
||||
let per = tileSize div cell
|
||||
for cy in t["y"].getInt * per ..< (t["y"].getInt + 1) * per:
|
||||
for cx in t["x"].getInt * per ..< (t["x"].getInt + 1) * per:
|
||||
if firstG.getOrDefault(cy * cw + cx, int.high) <= g: exp = true
|
||||
let s = t["s"].getInt
|
||||
if s == 200: inc n200 elif s == 403: inc n403 else: inc nOther
|
||||
if s != (if exp: 200 else: 403): fail "tile " & $t["x"] & "_" & $t["y"] & " g=" & $g & " (" & t["label"].getStr & ") status " & $s & " expected " & (if exp: "200" else: "403")
|
||||
|
||||
# coverage: the scripted path must actually exercise enter/leave
|
||||
for id in (if me == "A": @["M1", "M2", "B", "M5"] else: @["A", "M5"]):
|
||||
if id notin seen: fail "scenario never showed A token " & id
|
||||
if removes < (if me == "A": 3 else: 1): fail "only " & $removes & " removes"
|
||||
echo "leakcheck: ", groups, " gseq groups, A msgs ", am.len, ", tokens seen ", seen.len - 1, " others, removes ", removes,
|
||||
", tiles ", tiles.len, " (200:", n200, " 403:", n403, " other:", nOther, "), explored cells ", expN, ", failures ", fails
|
||||
quit(if fails > 0: 1 else: 0)
|
||||
@@ -0,0 +1,17 @@
|
||||
// shared by leak.mjs / concurrency.mjs. Node 22 WebSocket (undici) accepts {headers}.
|
||||
import fs from 'node:fs'
|
||||
export const RUN = process.env.RUN_DIR ?? 'run'
|
||||
export const O = `http://localhost:${process.env.PORT ?? 8080}`
|
||||
export const inv = Object.fromEntries(fs.readFileSync(`${RUN}/invites.txt`, 'utf8').trim().split('\n').map(l => l.split(' ')))
|
||||
export const sleep = ms => new Promise(r => setTimeout(r, ms))
|
||||
export const login = async role => (await fetch(inv[role], { redirect: 'manual' })).headers.get('set-cookie').split(';')[0]
|
||||
// resolves once hello+initial state arrived (socket quiet for 300 ms)
|
||||
export async function connect(role, onMsg) {
|
||||
const cookie = await login(role)
|
||||
const ws = new WebSocket(O.replace('http', 'ws') + '/ws', { headers: { Cookie: cookie } })
|
||||
let last = Date.now()
|
||||
ws.onmessage = e => { last = Date.now(); onMsg(JSON.parse(e.data), Buffer.byteLength(e.data)) }
|
||||
await new Promise((res, rej) => { ws.onopen = res; ws.onerror = rej })
|
||||
while (Date.now() - last < 300) await sleep(50)
|
||||
return { ws, cookie }
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// node tools/smoke.mjs [pos] -- needs server+nginx up. Node 22 WebSocket (undici) accepts {headers}.
|
||||
import fs from 'node:fs'
|
||||
const O = `http://localhost:${process.env.PORT ?? 8080}`
|
||||
const RUN = process.env.RUN_DIR ?? 'run'
|
||||
const inv = Object.fromEntries(fs.readFileSync(`${RUN}/invites.txt`, 'utf8').trim().split('\n').map(l => l.split(' ')))
|
||||
const ok = (c, m) => { console.log(c ? 'PASS' : 'FAIL', m); if (!c) process.exitCode = 1 }
|
||||
const join = async u => { const r = await fetch(u, { redirect: 'manual' }); return r }
|
||||
const ws = (cookie, ms = 800) => new Promise(res => {
|
||||
const msgs = [], s = new WebSocket(O.replace('http', 'ws') + '/ws', { headers: cookie ? { Cookie: cookie } : {} })
|
||||
s.onmessage = e => msgs.push(JSON.parse(e.data))
|
||||
s.onerror = () => res({ s, msgs, failed: true })
|
||||
setTimeout(() => res({ s, msgs, failed: false }), ms)
|
||||
})
|
||||
const nextAck = (s, reqId) => new Promise(res => s.addEventListener('message', function f(e) { const m = JSON.parse(e.data); if (m.t === 'moveAck' && m.reqId === reqId) { s.removeEventListener('message', f); res(m) } }))
|
||||
|
||||
const r1 = await join(inv.A.replace('A ', ''))
|
||||
const cookie = r1.headers.get('set-cookie')?.split(';')[0]
|
||||
if (process.argv[2] === 'pos') {
|
||||
const a = await ws(cookie); console.log('A pos', a.msgs.find(m => m.t === 'token' && m.id === 'A').pos); process.exit()
|
||||
}
|
||||
ok(r1.status === 302 && /HttpOnly/i.test(r1.headers.get('set-cookie')) && /SameSite=Strict/i.test(r1.headers.get('set-cookie')), 'join A: 302 + HttpOnly SameSite cookie')
|
||||
ok((await join(`${O}/join/deadbeef`)).status === 403, 'bad secret 403')
|
||||
ok((await ws(null)).failed, 'ws without cookie refused')
|
||||
ok((await ws('sid=nope')).failed, 'ws bad cookie refused')
|
||||
const a = await ws(cookie)
|
||||
const types = a.msgs.map(m => m.t)
|
||||
console.log('player A msgs:', types.join(','))
|
||||
ok(types[0] === 'hello' && a.msgs[0].role === 'player' && a.msgs[0].tokens[0] === 'A', 'hello first, player owns A')
|
||||
ok(!types.includes('walls') && !types.includes('door'), 'no walls/door to player')
|
||||
ok(types.includes('vision') && types.includes('explored'), 'vision + explored sent')
|
||||
const toks = a.msgs.filter(m => m.t === 'token')
|
||||
ok(toks.length === 1 && toks[0].id === 'A' && toks[0].mine, 'only own token visible')
|
||||
const get = (p, c = cookie) => fetch(O + p, { headers: { Cookie: c } })
|
||||
const t1 = await get('/tiles/1_1.png'); const b1 = await t1.arrayBuffer()
|
||||
ok(t1.status === 200 && b1.byteLength > 100 && !t1.headers.get('x-accel-redirect'), `explored tile 200, ${b1.byteLength} bytes`)
|
||||
ok((await get('/tiles/15_15.png')).status === 403, 'unexplored tile 403')
|
||||
ok((await fetch(`${O}/tiles/1_1.png`)).status === 403, 'tile without cookie 403')
|
||||
ok((await fetch(`${O}/_tiles/1_1.png`, { headers: { Cookie: cookie } })).status === 404, '/_tiles not reachable directly')
|
||||
ok([400, 404].includes((await get('/tiles/..%2f..%2fscene.json')).status), 'path trick rejected')
|
||||
const gmc = (await join(inv.gm)).headers.get('set-cookie').split(';')[0]
|
||||
ok((await get('/tiles/15_15.png', gmc)).status === 200, 'GM gets any tile')
|
||||
a.s.send(JSON.stringify({ t: 'move', reqId: 1, id: 'B', pos: [1, 1] }))
|
||||
a.s.send(JSON.stringify({ t: 'door', id: 10, open: true }))
|
||||
a.s.send('garbage{')
|
||||
await new Promise(r => setTimeout(r, 300))
|
||||
ok(a.msgs.filter(m => m.t === 'error').length === 3, 'steal/door/garbage -> 3 errors')
|
||||
let p = nextAck(a.s, 2); a.s.send(JSON.stringify({ t: 'move', reqId: 2, id: 'A', pos: [1100, 400] }))
|
||||
ok(!(await p).ok, 'move through wall rejected')
|
||||
p = nextAck(a.s, 3); a.s.send(JSON.stringify({ t: 'move', reqId: 3, id: 'A', pos: [500, 450] }))
|
||||
const ack = await p; ok(ack.ok && ack.pos[0] === 500, 'legal move acked')
|
||||
const g = await ws(gmc)
|
||||
ok(g.msgs.some(m => m.t === 'walls') && !g.msgs.some(m => m.t === 'explored') && g.msgs.filter(m => m.t === 'token').length === 8, 'GM: walls, all 8 tokens, no explored')
|
||||
process.exit()
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
# usage: tools/withserver.sh cmd... isolated stack in run/test (own DB/invites/nginx conf+logs/binary), own ports TEST_PORT (nginx, 18088) + TEST_BACKEND_PORT (server, 19000); never touches live run/ or :8088/:9000. SIGINT => server prints STATS
|
||||
cd "$(dirname "$0")/.." || exit 1
|
||||
export RUN_DIR=run/test PORT=${TEST_PORT:-18088} BACKEND_PORT=${TEST_BACKEND_PORT:-19000}
|
||||
R=$RUN_DIR
|
||||
case "$PORT:$BACKEND_PORT" in 8088:*|*:9000|*:8088) echo "withserver: refusing live port (8088/9000)" >&2; exit 1;; esac
|
||||
mkdir -p $R/temp client/dist
|
||||
rm -f $R/state.db* $R/invites.txt
|
||||
nim c -d:release --hints:off --nimblePath:"${NIMBLE_DIR:-.devbox/nimble}/pkgs2" -o:$R/server src/server.nim >/dev/null || exit 1
|
||||
sed -e "s/NGX_PORT/$PORT/" -e "s/NGX_BACKEND/$BACKEND_PORT/" -e "s#run/#$R/#g" -e "s#\.\./nginx/mime#$PWD/nginx/mime#" nginx/nginx.conf > $R/nginx.conf
|
||||
./$R/server > $R/server.log 2>&1 & S=$!
|
||||
nginx -p "$PWD/" -c $R/nginx.conf -e $R/error.log > $R/nginx.out 2>&1 & N=$!
|
||||
trap 'kill -INT $S; sleep 1; kill $N 2>/dev/null' EXIT
|
||||
for i in $(seq 50); do [ -s $R/invites.txt ] && curl -s -o /dev/null "localhost:$PORT/" && break; sleep 0.2; done
|
||||
"$@"
|
||||
Reference in New Issue
Block a user