feat(walls): one-way sight per-viewer filter and ONEWAY fault (#58)
The vision fan blocks a sight-blocking one-way wall only for a viewer on its blind side (sight_dir names it; left is the (-dy,dx) normal of a->b), one sign test inline after the radius cull, so the hoisted wall list stays viewer-independent. Movement never reads the direction: one-way walls block both ways. Explored and tiles therefore differ by side and only ever grow. - geometry: WallDir + Wall.sightDir + blindTo, filter in visibilityPolygon. - worldmap: sight_dir mapping (movement mapping unchanged). - vision: the ONEWAY leak-fault build drops sight_dir player-side. - leakcheck: own side test for the fan and the clear-segment oracle; ONEWAY class detected against the sight_dir-dropped fan. - leak scenario gains a one-way wall the subject sees across; fault test asserts exactly ONEWAY. - oneway.test.mjs: both sides, tile sweep with its own oracle, flip with fixed endpoints, monotone explored/tiles, restart, two-way movement. - docs: DESIGN 5.8 mechanism sentence corrected; TESTING #58 markers built. - nginx harness: temp dirs created recursively (restart on one state dir).
This commit is contained in:
@@ -5,7 +5,8 @@
|
||||
//
|
||||
// Classes: HIDDEN_TOKEN, GMONLY_TOKEN, WALLDATA, WITHHELD, NO_REMOVE, OWN_VIEW, OTHER_PLAYER,
|
||||
// EXPLORED, from slice 7 (#22) OWNER_PROP, GM_PROP, STATUS_SOURCE, and from slice 8 (#23)
|
||||
// ACTUAL_NAME, CHAR_LIST, CONTROLLER_CHANGE, CHAR_OWNER_PROP. (The tile class lands with slice 9.)
|
||||
// ACTUAL_NAME, CHAR_LIST, CONTROLLER_CHANGE, CHAR_OWNER_PROP, and from Walls r1 (#58) ONEWAY.
|
||||
// (The tile class lands with slice 9.)
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
@@ -28,6 +29,7 @@ const FAULTS = {
|
||||
gmOnly: ['GMONLY_TOKEN', 'NO_REMOVE'],
|
||||
walls: ['WALLDATA'],
|
||||
wallHeight: ['WALLDATA'],
|
||||
oneWay: ['ONEWAY'],
|
||||
withhold: ['WITHHELD'],
|
||||
otherOwner: ['OTHER_PLAYER'],
|
||||
otherVision: ['OTHER_PLAYER'],
|
||||
|
||||
+3
-2
@@ -12,8 +12,9 @@ export const GROUPS = {
|
||||
],
|
||||
},
|
||||
tiles: {
|
||||
files: ['tiles.test.mjs'],
|
||||
evidence: [['tiles.test.mjs', 'tile gate: leak check (d) matches the independent explored oracle']],
|
||||
files: ['tiles.test.mjs', 'oneway.test.mjs'],
|
||||
evidence: [['tiles.test.mjs', 'tile gate: leak check (d) matches the independent explored oracle'],
|
||||
['oneway.test.mjs', 'one-way sight: the blind side sees nothing across, the seeing side does (#58)']],
|
||||
},
|
||||
probing: {
|
||||
files: ['probing.test.mjs'],
|
||||
|
||||
@@ -22,6 +22,8 @@
|
||||
// - slice 7 (#22): props written into all three buckets on a token the subject can see, a
|
||||
// GM-sourced status, a walls-sourced stuck from a new wall, a resize, and a prop.unset — every
|
||||
// frame of the group is checked for the bucket and the `source` it must not carry
|
||||
// - Walls r1 (#58): a one-way wall the subject sees across (`sight_dir` names the token's side
|
||||
// blind), the ONEWAY fault's positive source and the blind-side oracle's control
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
@@ -371,6 +373,16 @@ export async function runLeak({ origin, gmKey, stateDir, transcript, keepOpen =
|
||||
await group('A walks further south', async () => {
|
||||
expectAck(await move(A, ids.A, [560, 1300]), true)
|
||||
})
|
||||
// Walls r1 (#58): a one-way wall between the subject (west) and a token on its blind (east) side.
|
||||
// `sight_dir:"right"` names the east side blind, so the subject sees across; the ONEWAY fault
|
||||
// drops `sight_dir` and the same wall would hide E2 and shrink the subject's fan.
|
||||
await group('GM adds a one-way wall east of the subject', async () => {
|
||||
await addWall({ a: [700, 1200], b: [700, 1400], sight_dir: 'right' })
|
||||
})
|
||||
await group('GM puts a token behind the one-way wall (the subject sees across)', async () => {
|
||||
await createToken('E2', { kind: 'npc', pos: [800, 1300], descriptive_name: 'a sentry',
|
||||
actual_name: 'Sentry' })
|
||||
})
|
||||
await group('end', async () => { await sleep(0) })
|
||||
|
||||
// Let anything still queued arrive, then close politely.
|
||||
|
||||
+137
-45
@@ -26,8 +26,15 @@
|
||||
## CONTROLLER_CHANGE a token changed controller in a group that asked for no such thing (8)
|
||||
## CHAR_OWNER_PROP a character's owner bucket reached a player who does not own it (8)
|
||||
## GEOMETRY the recomputed polygon disagrees with the clear-segment oracle (sanity)
|
||||
## ONEWAY the subject's fan ignores `sight_dir` (the two-way fan; TESTING 10.3, #58)
|
||||
## PROTOCOL a frame the catalogue does not allow, a bad `n` sequence, a missing hello block
|
||||
##
|
||||
## One-way sight (DESIGN 5.8, TESTING 10.3): the checker reads `sight_dir` from the GM's frames and
|
||||
## applies its OWN side test (`blindTo`, the sign of the cross product with `(-dy, dx)`) to decide
|
||||
## whether a one-way wall is in a viewer's fan. It never calls `server/vision.nim`. Once the
|
||||
## subject's own `vision` frame proves the sight_dir-dropped fan (the ONEWAY fault), the oracles
|
||||
## evaluate that two-way perspective so the fault is reported as exactly ONEWAY.
|
||||
##
|
||||
## usage: leakcheck <transcript.jsonl> <SUBJECT> exit 0 = clean
|
||||
import std/[algorithm, json, math, options, os, sets, strutils, tables]
|
||||
import geometry
|
||||
@@ -87,6 +94,14 @@ proc fail(cls, s: string) =
|
||||
|
||||
proc vec(j: JsonNode): Vec = (j[0].getFloat, j[1].getFloat)
|
||||
|
||||
proc wallDir(j: JsonNode): WallDir =
|
||||
## The GM's wall frames carry `sight_dir` (proto 2, #54); the checker reads it as its own input.
|
||||
if j.kind != JString: return wdBoth
|
||||
case j.getStr
|
||||
of "left": wdLeft
|
||||
of "right": wdRight
|
||||
else: wdBoth
|
||||
|
||||
proc samePos(j: JsonNode, p: Vec): bool =
|
||||
## JSON numbers lose their int/float spelling on the wire round trip: compare numerically.
|
||||
j.kind == JArray and j.len == 2 and
|
||||
@@ -127,12 +142,13 @@ proc applyGmWalls(truth: var Truth, ids: var seq[int], m: JsonNode) =
|
||||
ids.setLen(0)
|
||||
for w in m["walls"]:
|
||||
truth.walls.add Wall(a: vec(w["a"]), b: vec(w["b"]),
|
||||
door: w["door"].getBool, open: w["open"].getBool)
|
||||
door: w["door"].getBool, open: w["open"].getBool,
|
||||
sightDir: wallDir(w["sight_dir"]))
|
||||
ids.add w["id"].getInt
|
||||
of "wall":
|
||||
let id = m["id"].getInt
|
||||
let w = Wall(a: vec(m["a"]), b: vec(m["b"]), door: m["door"].getBool,
|
||||
open: m["open"].getBool)
|
||||
open: m["open"].getBool, sightDir: wallDir(m["sight_dir"]))
|
||||
var found = false
|
||||
for i in 0 ..< ids.len:
|
||||
if ids[i] == id:
|
||||
@@ -193,9 +209,39 @@ proc applyGmCharacters(truth: var Truth, m: JsonNode) =
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# Independent oracles
|
||||
|
||||
var checkDir = true
|
||||
## False once the subject's own `vision` frame shows `sight_dir` dropped (the ONEWAY fault): from
|
||||
## then on the oracles evaluate the faulty perspective so the fault is reported as exactly ONEWAY,
|
||||
## not as a cascade of WITHHELD/OWN_VIEW/EXPLORED.
|
||||
|
||||
proc blindTo(w: Wall, o: Vec): bool =
|
||||
## The checker's OWN copy of the 5.8 side test, never `vision.nim`: cross(a->b, o - a) is the
|
||||
## signed distance along the `(-dy, dx)` normal of `a -> b`, positive = left. On the drawn line
|
||||
## both directions answer blind, so the predicate is never ambiguous.
|
||||
if w.sightDir == wdBoth: return false
|
||||
let s = cross(w.b - w.a, o - w.a)
|
||||
case w.sightDir
|
||||
of wdBoth: false
|
||||
of wdLeft: s >= -Eps
|
||||
of wdRight: s <= Eps
|
||||
|
||||
proc wallsFor(truth: Truth, o: Vec, honourDir: bool): seq[Wall] =
|
||||
## The wall list one viewer's fan gets. With `honourDir`, a sight-blocking one-way wall is kept
|
||||
## only for a viewer on its blind side (the checker's own side test); otherwise every `sight_dir`
|
||||
## is dropped, which is exactly the ONEWAY fault's two-way wall list.
|
||||
if honourDir:
|
||||
for w in truth.walls:
|
||||
if w.sightDir != wdBoth and not w.blindTo(o): continue
|
||||
result.add w
|
||||
else:
|
||||
result = truth.walls
|
||||
for w in result.mitems: w.sightDir = wdBoth
|
||||
|
||||
proc clearLine(walls: seq[Wall], o, p: Vec): bool =
|
||||
## The clear-segment oracle: no blocking wall between o and p (independent of the ray fan).
|
||||
## The clear-segment oracle: no blocking wall between o and p (independent of the ray fan). The
|
||||
## one-way filter is the checker's own side test, for the sample's viewer `o`.
|
||||
for w in walls:
|
||||
if checkDir and w.sightDir != wdBoth and not w.blindTo(o): continue
|
||||
if w.blocks and segsCross(o, p, w.a, w.b): return false
|
||||
true
|
||||
|
||||
@@ -203,13 +249,41 @@ proc rangeOf(sceneDefault: float, t: TruthToken): float =
|
||||
if t.hasVision and t.visionRadius.isSome and t.visionRadius.get > 0: t.visionRadius.get
|
||||
else: sceneDefault
|
||||
|
||||
proc polygonsOf(truth: Truth, controller: int, sceneDefault: float): seq[(string, seq[Vec])] =
|
||||
proc polygonsOf(truth: Truth, controller: int, sceneDefault: float,
|
||||
honourDir = true): seq[(string, seq[Vec])] =
|
||||
for id, t in truth.tokens:
|
||||
if t.controller != controller or not t.hasVision: continue
|
||||
result.add (id, visibilityPolygon(t.pos, truth.walls, rangeOf(sceneDefault, t)))
|
||||
result.add (id, visibilityPolygon(t.pos, wallsFor(truth, t.pos, honourDir),
|
||||
rangeOf(sceneDefault, t)))
|
||||
# deterministic order: by token id (the server keeps creation order; the checker sorts)
|
||||
result.sort(proc (a, b: (string, seq[Vec])): int = cmp(a[0], b[0]))
|
||||
|
||||
proc samePolySet(got, want: seq[(string, seq[Vec])], tol = 0.5): bool =
|
||||
## Every polygon present with the same id, vertex count and vertices within `tol` px (the wire's
|
||||
## integer rounding, 6.4). Used to tell the correct fan from the ONEWAY fault's two-way fan.
|
||||
if got.len != want.len: return false
|
||||
var used = newSeq[bool](want.len)
|
||||
for (gid, gpts) in got:
|
||||
var matched = false
|
||||
for i in 0 ..< want.len:
|
||||
if used[i] or want[i][0] != gid: continue
|
||||
used[i] = true
|
||||
matched = true
|
||||
let wpts = want[i][1]
|
||||
if gpts.len != wpts.len: return false
|
||||
for k in 0 ..< gpts.len:
|
||||
if abs(gpts[k].x - wpts[k].x) > tol + 1e-6 or
|
||||
abs(gpts[k].y - wpts[k].y) > tol + 1e-6: return false
|
||||
break
|
||||
if not matched: return false
|
||||
true
|
||||
|
||||
proc parsePolys(m: JsonNode): seq[(string, seq[Vec])] =
|
||||
for p in m["polys"]:
|
||||
var pts: seq[Vec]
|
||||
for q in p["pts"]: pts.add vec(q)
|
||||
result.add (p["id"].getStr, pts)
|
||||
|
||||
proc insideAny(polys: seq[(string, seq[Vec])], p: Vec): bool =
|
||||
for (_, pts) in polys:
|
||||
if inside(pts, p): return true
|
||||
@@ -322,14 +396,31 @@ proc main() =
|
||||
if me == 0: continue
|
||||
|
||||
let polys = polygonsOf(truth, me, sceneDefault)
|
||||
let otherPolys = if other != 0: polygonsOf(truth, other, sceneDefault) else: @[]
|
||||
var anyOneWay = false
|
||||
for w in truth.walls:
|
||||
if w.sightDir != wdBoth: anyOneWay = true
|
||||
# The fault's fan is only worth recomputing in a world that has a one-way wall at all.
|
||||
let faultPolys = if anyOneWay: polygonsOf(truth, me, sceneDefault, honourDir = false)
|
||||
else: polys
|
||||
# The subject's own `vision` frame decides the perspective this group is checked against: if it
|
||||
# matches the sight_dir-dropped fan and not the correct one, the ONEWAY fault is live. Then the
|
||||
# oracles evaluate that perspective, so the fault surfaces as exactly ONEWAY instead of a
|
||||
# cascade of WITHHELD/OWN_VIEW/EXPLORED.
|
||||
if anyOneWay:
|
||||
for m in g.subjMsgs:
|
||||
if m["t"].getStr != "vision": continue
|
||||
let got = parsePolys(m)
|
||||
if not samePolySet(got, polys) and samePolySet(got, faultPolys): checkDir = false
|
||||
let polysChecks = if checkDir: polys else: faultPolys
|
||||
let otherPolys = if other != 0: polygonsOf(truth, other, sceneDefault, honourDir = checkDir)
|
||||
else: @[]
|
||||
|
||||
# The encountered oracle, computed from the GM's truth and the subject's own polygons - never
|
||||
# from what the subject was sent: every token the subject can see right now is one it may have
|
||||
# met. It only grows, exactly like the server's list (8).
|
||||
var visibleNow = initHashSet[string]()
|
||||
for id, actual in truth.tokens:
|
||||
if actual.controller == me or (not actual.gmOnly and insideAny(polys, actual.pos)):
|
||||
if actual.controller == me or (not actual.gmOnly and insideAny(polysChecks, actual.pos)):
|
||||
visibleNow.incl id
|
||||
encounterable.incl id
|
||||
|
||||
@@ -441,9 +532,9 @@ proc main() =
|
||||
if got != want:
|
||||
fail "CHAR_OWNER_PROP", "token " & id & " cprops public bucket is not the truth"
|
||||
view[id] = m
|
||||
let visible = wantMine or (not actual.gmOnly and insideAny(polys, actual.pos))
|
||||
let visible = wantMine or (not actual.gmOnly and insideAny(polysChecks, actual.pos))
|
||||
if not visible:
|
||||
let cls = if actual.gmOnly and insideAny(polys, actual.pos): "GMONLY_TOKEN"
|
||||
let cls = if actual.gmOnly and insideAny(polysChecks, actual.pos): "GMONLY_TOKEN"
|
||||
else: "HIDDEN_TOKEN"
|
||||
leaked[id] = cls
|
||||
fail cls, "token " & id & " sent but not visible (group " & g.label & ")"
|
||||
@@ -458,7 +549,7 @@ proc main() =
|
||||
inc removes
|
||||
if id in truth.tokens:
|
||||
let actual = truth.tokens[id]
|
||||
if actual.controller == me or (not actual.gmOnly and insideAny(polys, actual.pos)):
|
||||
if actual.controller == me or (not actual.gmOnly and insideAny(polysChecks, actual.pos)):
|
||||
fail "WITHHELD", "token_gone for a token still visible: " & id
|
||||
of "character":
|
||||
# 6.1: a player gets only the characters it owns, with both names and the public/owner
|
||||
@@ -513,36 +604,37 @@ proc main() =
|
||||
if pl["name"].kind == JNull or pl["name"].getStr.len == 0:
|
||||
fail "PROTOCOL", "the roster handed a player an unnamed entry"
|
||||
of "vision":
|
||||
var got: seq[(string, seq[Vec])]
|
||||
for p in m["polys"]:
|
||||
var pts: seq[Vec]
|
||||
for q in p["pts"]: pts.add vec(q)
|
||||
got.add (p["id"].getStr, pts)
|
||||
let want = polys
|
||||
var haveIds = initHashSet[string]()
|
||||
for (id, pts) in got:
|
||||
haveIds.incl id
|
||||
var matched = false
|
||||
for (wid, wpts) in want:
|
||||
if wid != id: continue
|
||||
matched = true
|
||||
if pts.len != wpts.len:
|
||||
fail "OWN_VIEW", "polygon " & id & " has " & $pts.len & " of " & $wpts.len & " vertices"
|
||||
else:
|
||||
for i in 0 ..< pts.len:
|
||||
# integer px on the wire (6.4): 0.5 px is the documented tolerance
|
||||
if abs(pts[i].x - wpts[i].x) > 0.5 + 1e-6 or abs(pts[i].y - wpts[i].y) > 0.5 + 1e-6:
|
||||
fail "OWN_VIEW", "polygon " & id & " vertex " & $i & " is " & $pts[i] &
|
||||
" not " & $wpts[i]
|
||||
break
|
||||
if not matched:
|
||||
var theirs = false
|
||||
for (oid, _) in otherPolys:
|
||||
if oid == id: theirs = true
|
||||
fail (if theirs: "OTHER_PLAYER" else: "PROTOCOL"),
|
||||
"vision carries a polygon for a token this player does not control: " & id
|
||||
for (id, _) in want:
|
||||
if id notin haveIds: fail "OWN_VIEW", "vision is missing the polygon of " & id
|
||||
let got = parsePolys(m)
|
||||
if not samePolySet(got, polys):
|
||||
if anyOneWay and samePolySet(got, faultPolys):
|
||||
# TESTING 10.3: the fan behaves as if `sight_dir` were dropped (a two-way wall).
|
||||
fail "ONEWAY", "vision is the sight_dir-dropped fan (group " & g.label & ")"
|
||||
else:
|
||||
let want = polys
|
||||
var haveIds = initHashSet[string]()
|
||||
for (id, pts) in got:
|
||||
haveIds.incl id
|
||||
var matched = false
|
||||
for (wid, wpts) in want:
|
||||
if wid != id: continue
|
||||
matched = true
|
||||
if pts.len != wpts.len:
|
||||
fail "OWN_VIEW", "polygon " & id & " has " & $pts.len & " of " & $wpts.len & " vertices"
|
||||
else:
|
||||
for i in 0 ..< pts.len:
|
||||
# integer px on the wire (6.4): 0.5 px is the documented tolerance
|
||||
if abs(pts[i].x - wpts[i].x) > 0.5 + 1e-6 or abs(pts[i].y - wpts[i].y) > 0.5 + 1e-6:
|
||||
fail "OWN_VIEW", "polygon " & id & " vertex " & $i & " is " & $pts[i] &
|
||||
" not " & $wpts[i]
|
||||
break
|
||||
if not matched:
|
||||
var theirs = false
|
||||
for (oid, _) in otherPolys:
|
||||
if oid == id: theirs = true
|
||||
fail (if theirs: "OTHER_PLAYER" else: "PROTOCOL"),
|
||||
"vision carries a polygon for a token this player does not control: " & id
|
||||
for (id, _) in want:
|
||||
if id notin haveIds: fail "OWN_VIEW", "vision is missing the polygon of " & id
|
||||
of "explored":
|
||||
if m["full"].getBool:
|
||||
# a resync snapshot replaces the set; every cell must be one the recomputation has seen
|
||||
@@ -593,7 +685,7 @@ proc main() =
|
||||
# was legitimately seen and is now invisible is a missing withdrawal. `seenAny` decides,
|
||||
# so a `gm_only` flip after a legitimate sighting is not re-labelled as a gm_only leak.
|
||||
if leaked.hasKey(id): fail leaked[id], "leaked token still in view: " & id
|
||||
elif id notin seenAny and actual.gmOnly and insideAny(polys, actual.pos):
|
||||
elif id notin seenAny and actual.gmOnly and insideAny(polysChecks, actual.pos):
|
||||
fail "GMONLY_TOKEN", "gm_only token still in view: " & id
|
||||
else: fail "NO_REMOVE", "token left the view and was never withdrawn: " & id &
|
||||
" (group " & g.label & ")"
|
||||
@@ -605,7 +697,7 @@ proc main() =
|
||||
var recomputed: HashSet[int]
|
||||
let cols = int(ceil(sceneW / float(cell)))
|
||||
let rows = int(ceil(sceneW / float(cell)))
|
||||
for (_, pts) in polys:
|
||||
for (_, pts) in polysChecks:
|
||||
for (cx, cy) in cellsTouched(pts, float(cell)):
|
||||
# cells outside the world are not cells: the server drops them too (vision.refresh)
|
||||
if cx < 0 or cy < 0 or cx >= cols or cy >= rows: continue
|
||||
@@ -617,7 +709,7 @@ proc main() =
|
||||
if k in recomputedSoFar: continue
|
||||
let cx = k mod cols
|
||||
let cy = k div cols
|
||||
if definitelySeen(truth.walls, polys, sceneW, cell, cx, cy):
|
||||
if definitelySeen(truth.walls, polysChecks, sceneW, cell, cx, cy):
|
||||
recomputed.incl k # grazed cell the sampler does see: fine either way
|
||||
continue
|
||||
# attribution: a cell only the other player has explored is a presence leak, not a bad cell
|
||||
@@ -637,7 +729,7 @@ proc main() =
|
||||
if missing > 3:
|
||||
fail "EXPLORED", $missing & " recomputed explored cells were never sent"
|
||||
if getEnv("LEAK_DEBUG") != "":
|
||||
for (id, pts) in polys:
|
||||
for (id, pts) in polysChecks:
|
||||
var cx0 = 100000; var cx1 = -1; var cy0 = 100000; var cy1 = -1
|
||||
for (cx, cy) in cellsTouched(pts, float(cell)):
|
||||
cx0 = min(cx0, cx); cx1 = max(cx1, cx); cy0 = min(cy0, cy); cy1 = max(cy1, cy)
|
||||
@@ -645,7 +737,7 @@ proc main() =
|
||||
" group ", g.label, " cell ", cell, " sceneW ", sceneW
|
||||
|
||||
# --- the clear-segment oracle on the polygon itself -----------------------------------------
|
||||
for (id, pts) in polys:
|
||||
for (id, pts) in polysChecks:
|
||||
if pts.len < 3: continue
|
||||
var t: TruthToken
|
||||
for tid, tt in truth.tokens:
|
||||
|
||||
+3
-1
@@ -93,7 +93,9 @@ export async function startTestNginx({ backendPort, stateDir, port }) {
|
||||
if (!(await portIsFree(port))) throw new Error(`test nginx port ${port} is already in use`)
|
||||
const prefix = path.join(stateDir, 'nginx')
|
||||
fs.mkdirSync(prefix, { recursive: true })
|
||||
for (const d of ['client_body', 'proxy', 'fastcgi', 'uwsgi', 'scgi']) fs.mkdirSync(path.join(prefix, d))
|
||||
for (const d of ['client_body', 'proxy', 'fastcgi', 'uwsgi', 'scgi']) {
|
||||
fs.mkdirSync(path.join(prefix, d), { recursive: true })
|
||||
}
|
||||
const confPath = path.join(prefix, 'nginx.conf')
|
||||
fs.writeFileSync(confPath, config({ prefix, port, backendPort, stateDir }))
|
||||
const logFd = fs.openSync(path.join(prefix, 'stderr.log'), 'a')
|
||||
|
||||
@@ -0,0 +1,387 @@
|
||||
// Walls r1 (#58, DESIGN 5.8, TESTING 10.3): one-way sight over the real binary and the test nginx.
|
||||
// One scene, one full-height one-way wall and two players on its two sides:
|
||||
// - the player on the blind side gets no token, explored cell or tile across the wall;
|
||||
// - the player on the seeing side does (the positive control, so the oracle can fail);
|
||||
// - flipping `sight_dir` swaps the blind side without moving the endpoints and with no
|
||||
// normalisation: explored cells and allowed tiles only ever grow, never shrink;
|
||||
// - after a restart the direction and the walls are identical and nothing is revoked.
|
||||
// The oracle below is this file's OWN: it reads the GM's wall truth, applies its own side test
|
||||
// (cross product with the (-dy, dx) normal of `a -> b`) and samples clear segments per cell. It
|
||||
// never calls the server's vision or explored code.
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import { baseUrl, createPlayer, freePort, namePlayer, sleep } from './lib.mjs'
|
||||
import { gmKeyOf, makeStateDir, openAs, startServer, stopServer } from './withserver.mjs'
|
||||
import { startTestNginx, stopTestNginx } from './nginx.mjs'
|
||||
import { writeTileGrid } from './tilefixture.mjs'
|
||||
|
||||
const ALICE = 'Alice'
|
||||
const BOB = 'Bob'
|
||||
const CELL = 32 // v1 pins tile_size = cell (Q4); the oracle and the tile sweep both use it
|
||||
const WALL_X = 400
|
||||
const WALL = { a: [WALL_X, 0], b: [WALL_X, 4096], preset: 'one_way' } // sight_dir defaults to left
|
||||
// The first cell wholly east of the drawn line: the wall at x=400 sits inside cell 12.
|
||||
const EAST_EDGE = Math.ceil(WALL_X / CELL) * CELL
|
||||
const REGION = { x0: 5, x1: 17, y0: 5, y1: 12 }
|
||||
const Tol = 0.5
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// A stack: real server + test nginx in front (the production shape of 11.1).
|
||||
|
||||
async function withOneWayStack(fn) {
|
||||
const stateDir = makeStateDir()
|
||||
const gmKey = gmKeyOf(stateDir)
|
||||
const stack = { stateDir, gmKey }
|
||||
const boot = async () => {
|
||||
stack.nginxPort = await freePort()
|
||||
stack.server = await startServer({ stateDir, publicOrigin: baseUrl(stack.nginxPort) })
|
||||
stack.nginx = await startTestNginx({ backendPort: stack.server.port, stateDir,
|
||||
port: stack.nginxPort })
|
||||
stack.origin = stack.nginx.origin
|
||||
}
|
||||
const down = async () => {
|
||||
await stopTestNginx(stack.nginx)
|
||||
await stopServer(stack.server)
|
||||
}
|
||||
await boot()
|
||||
const api = {
|
||||
stateDir, gmKey, boot, down,
|
||||
get origin() { return stack.origin },
|
||||
}
|
||||
try {
|
||||
return await fn(api)
|
||||
} finally {
|
||||
await down()
|
||||
fs.rmSync(stateDir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
async function gmConnect(origin, gmKey) {
|
||||
const conn = await openAs(origin, gmKey)
|
||||
const hello = await conn.ws.waitText('hello')
|
||||
const walls = await conn.ws.waitText('walls')
|
||||
return { ...conn, scene: walls.scene, walls, art: hello.scene.art_version }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The independent oracle: the side test, the sight wall list and the per-cell clear-segment sample.
|
||||
|
||||
function blindTo(w, o) {
|
||||
// DESIGN 5.8: `sight_dir` names the blind side of `a -> b`; `left` is the (-dy, dx) normal. The
|
||||
// cross product of the a->b direction with (o - a) is the signed distance along that normal.
|
||||
if (w.sight_dir !== 'left' && w.sight_dir !== 'right') return false
|
||||
const dx = w.b[0] - w.a[0], dy = w.b[1] - w.a[1]
|
||||
const s = dx * (o.y - w.a[1]) - dy * (o.x - w.a[0])
|
||||
return w.sight_dir === 'left' ? s >= -1e-9 : s <= 1e-9
|
||||
}
|
||||
|
||||
function sightBlocking(wallsFrame, viewer) {
|
||||
// Today's blocking rule is `not (door and open)`, plus the one-way side test. A one-way wall is
|
||||
// in the viewer's fan only while the viewer stands on the blind side (a wall it sees across is
|
||||
// absent from the fan). This is the file's own copy, never server vision code.
|
||||
return wallsFrame.walls
|
||||
.filter(w => !(w.door && w.open) && !((w.sight_dir === 'left' || w.sight_dir === 'right') &&
|
||||
!blindTo(w, viewer)))
|
||||
.map(w => ({ a: { x: w.a[0], y: w.a[1] }, b: { x: w.b[0], y: w.b[1] } }))
|
||||
}
|
||||
|
||||
function segDist(p, a, b) {
|
||||
const ex = b.x - a.x
|
||||
const ey = b.y - a.y
|
||||
const l2 = ex * ex + ey * ey
|
||||
const t = l2 === 0 ? 0 : Math.max(0, Math.min(1, ((p.x - a.x) * ex + (p.y - a.y) * ey) / l2))
|
||||
return Math.hypot(p.x - a.x - t * ex, p.y - a.y - t * ey)
|
||||
}
|
||||
|
||||
function orient(a, b, c) {
|
||||
return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)
|
||||
}
|
||||
|
||||
function properCross(p, q, a, b) {
|
||||
const d1 = orient(p, q, a), d2 = orient(p, q, b), d3 = orient(a, b, p), d4 = orient(a, b, q)
|
||||
return d1 * d2 < 0 && d3 * d4 < 0
|
||||
}
|
||||
|
||||
function segGap(p, q, a, b) {
|
||||
if (properCross(p, q, a, b)) return 0
|
||||
return Math.min(segDist(p, a, b), segDist(q, a, b), segDist(a, p, q), segDist(b, p, q))
|
||||
}
|
||||
|
||||
// sure = a lattice point inside the inscribed 64-gon whose LOS is > Tol from every blocking wall;
|
||||
// maybe = a point within radius + Tol whose LOS no blocking wall properly crosses.
|
||||
function oracleCell({ o, radius, walls, cell, x, y }) {
|
||||
const rin = radius * Math.cos(Math.PI / 64) - Tol
|
||||
const x0 = x * cell, y0 = y * cell
|
||||
let sure = false, maybe = false
|
||||
const n = 16
|
||||
for (let j = 0; j <= n && !(sure && maybe); j++) {
|
||||
for (let i = 0; i <= n; i++) {
|
||||
const p = { x: x0 + (cell * i) / n, y: y0 + (cell * j) / n }
|
||||
const d = Math.hypot(p.x - o.x, p.y - o.y)
|
||||
if (!maybe && d <= radius + Tol) {
|
||||
let clear = true
|
||||
for (const w of walls) if (properCross(o, p, w.a, w.b)) { clear = false; break }
|
||||
if (clear) maybe = true
|
||||
}
|
||||
if (!sure && d <= rin) {
|
||||
let clear = true
|
||||
for (const w of walls) if (segGap(o, p, w.a, w.b) <= Tol) { clear = false; break }
|
||||
if (clear) sure = true
|
||||
}
|
||||
if (sure && maybe) break
|
||||
}
|
||||
}
|
||||
return { sure, maybe }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
function collectExplored(ws) {
|
||||
const cells = new Set()
|
||||
for (const m of ws.messages) {
|
||||
if (m.t !== 'explored') continue
|
||||
if (m.full) {
|
||||
for (const row of m.rle) {
|
||||
const cy = row[0]
|
||||
for (let i = 1; i < row.length; i += 2) {
|
||||
for (let k = 0; k < row[i + 1]; k++) cells.add(`${row[i] + k},${cy}`)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (const [cx, cy] of m.cells) cells.add(`${cx},${cy}`)
|
||||
}
|
||||
}
|
||||
return cells
|
||||
}
|
||||
|
||||
function assertSuperset(after, before, what) {
|
||||
for (const k of before) assert.ok(after.has(k), `${what} lost ${k} (explored/tiles never shrink)`)
|
||||
}
|
||||
|
||||
async function sweepTiles({ origin, cookie, scene, art, wallsFrame, o, radius, cell,
|
||||
strictMaybes = true }) {
|
||||
const walls = sightBlocking(wallsFrame, o)
|
||||
const allowed = new Set()
|
||||
let sure = 0
|
||||
for (let y = REGION.y0; y <= REGION.y1; y++) {
|
||||
for (let x = REGION.x0; x <= REGION.x1; x++) {
|
||||
const vis = oracleCell({ o, radius, walls, cell, x, y })
|
||||
if (vis.sure) sure++
|
||||
const r = await fetch(`${origin}/tiles/${scene}/v${art}/${x}_${y}.png`,
|
||||
{ headers: { Cookie: cookie } })
|
||||
const at = `tile ${x},${y} (sure=${vis.sure} maybe=${vis.maybe})`
|
||||
if (r.status === 200) {
|
||||
allowed.add(`${x},${y}`)
|
||||
// Explored only grows: once a cell was seen, its tile stays allowed even when a later flip
|
||||
// puts it on the blind side again. Only a fresh region may be checked for invented cells.
|
||||
if (strictMaybes) {
|
||||
assert.ok(vis.maybe, `${at}: allowed although the oracle cannot see any point in the cell`)
|
||||
}
|
||||
} else {
|
||||
assert.equal(r.status, 403, `${at}: unexpected status ${r.status}`)
|
||||
assert.ok(!vis.sure, `${at}: refused although the oracle is sure the cell is visible`)
|
||||
}
|
||||
}
|
||||
}
|
||||
return { allowed, sure }
|
||||
}
|
||||
|
||||
function eastOfWall(cells) {
|
||||
const out = []
|
||||
for (const k of cells) {
|
||||
const [cx, cy] = k.split(',').map(Number)
|
||||
if (cx * CELL >= EAST_EDGE) out.push(k)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
test('one-way sight: the blind side sees nothing across, the seeing side does (#58)', async () => {
|
||||
await withOneWayStack(async ({ origin, gmKey, stateDir }) => {
|
||||
const gm = await gmConnect(origin, gmKey)
|
||||
const ack = await gm.ws.request({ t: 'wall.add', scene: gm.scene, ...WALL })
|
||||
assert.equal(ack.ok, true, JSON.stringify(ack))
|
||||
const wall = await gm.ws.waitFor(m => m.t === 'wall' && m.id === ack.id)
|
||||
assert.equal(wall.sight_dir, 'left')
|
||||
assert.equal(wall.kind, 'one_way')
|
||||
assert.deepEqual(wall.a, WALL.a)
|
||||
assert.deepEqual(wall.b, WALL.b)
|
||||
const wallsFrame = { walls: [wall] }
|
||||
|
||||
const alice = await createPlayer(gm.ws)
|
||||
const bob = await createPlayer(gm.ws)
|
||||
await namePlayer(origin, alice.key, ALICE)
|
||||
await namePlayer(origin, bob.key, BOB)
|
||||
const mkToken = async (player, pos, name) => {
|
||||
const a = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'pc', pos,
|
||||
flags: { vision: true }, vision_radius: 400,
|
||||
controller: player.id, descriptive_name: name,
|
||||
actual_name: name })
|
||||
assert.equal(a.ok, true, JSON.stringify(a))
|
||||
return (await gm.ws.waitFor(m => m.t === 'token' && m.id === a.id)).id
|
||||
}
|
||||
const aliceToken = await mkToken(alice, [300, 300], ALICE) // west, the blind (left) side
|
||||
const bobToken = await mkToken(bob, [500, 400], BOB) // east, the seeing side
|
||||
|
||||
const a = await openAs(origin, alice.key)
|
||||
await a.ws.waitText('hello')
|
||||
await a.ws.waitFor(m => m.t === 'explored' && m.full === true)
|
||||
const b = await openAs(origin, bob.key)
|
||||
await b.ws.waitText('hello')
|
||||
await b.ws.waitFor(m => m.t === 'explored' && m.full === true)
|
||||
await sleep(100)
|
||||
|
||||
// Blind side: no token frame, no encountered entry, and no explored cell east of the wall.
|
||||
assert.equal(a.ws.messages.some(m => m.t === 'token' && m.id === bobToken), false,
|
||||
'the blind side received a token across the one-way wall')
|
||||
const encountered = a.ws.messages.filter(m => m.t === 'encountered')
|
||||
.flatMap(m => (m.set ?? []).map(e => e.id))
|
||||
assert.equal(encountered.includes(bobToken), false,
|
||||
'the blind side encountered a token across the one-way wall')
|
||||
const aliceExplored = collectExplored(a.ws)
|
||||
assert.deepEqual(eastOfWall(aliceExplored), [],
|
||||
'the blind side explored a cell east of the wall')
|
||||
assert.ok(aliceExplored.has('9,9'), 'the blind side did not explore its own cell (control)')
|
||||
|
||||
// Seeing side (positive control): the same wall lets Bob see Alice's token and west cells.
|
||||
assert.ok(b.ws.messages.some(m => m.t === 'token' && m.id === aliceToken),
|
||||
'the seeing side did not receive the token across the one-way wall')
|
||||
const bobExplored = collectExplored(b.ws)
|
||||
assert.ok(bobExplored.has('9,9'), 'the seeing side did not explore a cell west of the wall')
|
||||
|
||||
// Direction is sight only: the wall blocks movement both ways (story 22).
|
||||
const crossFromBlind = await a.ws.request({ t: 'token.move', id: aliceToken, pos: [450, 300] })
|
||||
assert.equal(crossFromBlind.ok, false, 'the blind side walked through the one-way wall')
|
||||
const crossFromSeeing = await b.ws.request({ t: 'token.move', id: bobToken, pos: [350, 400] })
|
||||
assert.equal(crossFromSeeing.ok, false, 'the seeing side walked through the one-way wall')
|
||||
|
||||
// Tiles, blind side: every allowed tile is oracle-maybe, every oracle-sure tile is allowed, and
|
||||
// the east shadow (full-height wall) is refused.
|
||||
const scene = gm.scene
|
||||
writeTileGrid(stateDir, { scene, artVersion: gm.art, size: CELL, ...REGION })
|
||||
const blind = await sweepTiles({ origin, cookie: a.cookie, scene, art: gm.art, wallsFrame,
|
||||
o: { x: 300, y: 300 }, radius: 400, cell: CELL })
|
||||
assert.ok(blind.sure > 15, `the blind-side oracle sampled too little (sure=${blind.sure})`)
|
||||
assert.ok(blind.allowed.size > 10, `the gate allowed too few blind-side tiles (${blind.allowed.size})`)
|
||||
for (let y = REGION.y0; y <= REGION.y1; y++) {
|
||||
for (let x = EAST_EDGE / CELL; x <= REGION.x1; x++) {
|
||||
const shadow = oracleCell({ o: { x: 300, y: 300 }, radius: 400,
|
||||
walls: sightBlocking(wallsFrame, { x: 300, y: 300 }),
|
||||
cell: CELL, x, y })
|
||||
assert.equal(shadow.maybe, false, `oracle says cell ${x},${y} east of the wall is visible`)
|
||||
assert.equal(blind.allowed.has(`${x},${y}`), false,
|
||||
`the blind side was allowed tile ${x},${y} behind the wall`)
|
||||
}
|
||||
}
|
||||
|
||||
// --- flip: same endpoints, other blind side ------------------------------------------------
|
||||
const upd = await gm.ws.request({ t: 'wall.update', scene, id: wall.id, sight_dir: 'right' })
|
||||
assert.equal(upd.ok, true, JSON.stringify(upd))
|
||||
const flipped = await gm.ws.waitFor(m => m.t === 'wall' && m.id === wall.id &&
|
||||
m.sight_dir === 'right')
|
||||
assert.deepEqual(flipped.a, WALL.a, 'the flip moved endpoint a')
|
||||
assert.deepEqual(flipped.b, WALL.b, 'the flip moved endpoint b')
|
||||
assert.equal(flipped.kind, 'one_way')
|
||||
|
||||
await a.ws.waitFor(m => m.t === 'token' && m.id === bobToken)
|
||||
await b.ws.waitFor(m => m.t === 'token_gone' && m.id === aliceToken)
|
||||
const aliceSaw = await a.ws.waitFor(m => m.t === 'explored' && m.full === false)
|
||||
assert.ok(aliceSaw.cells.length > 0, 'the newly seeing side explored no cell after the flip')
|
||||
|
||||
const aliceAfter = collectExplored(a.ws)
|
||||
assertSuperset(aliceAfter, aliceExplored, 'the flipped side')
|
||||
assert.ok(eastOfWall(aliceAfter).length > 0, 'the seeing side never explored across after the flip')
|
||||
const bobAfter = collectExplored(b.ws)
|
||||
assertSuperset(bobAfter, bobExplored, 'the side that lost sight')
|
||||
const flippedFrame = { walls: [flipped] }
|
||||
|
||||
// Tiles after the flip: previously allowed blind-side tiles stay allowed (no revoke) and the
|
||||
// newly seeing side gains at least one eastern tile (positive control).
|
||||
const seen = await sweepTiles({ origin, cookie: a.cookie, scene, art: gm.art,
|
||||
wallsFrame: flippedFrame, o: { x: 300, y: 300 }, radius: 400,
|
||||
cell: CELL })
|
||||
assertSuperset(seen.allowed, blind.allowed, 'tiles after the flip')
|
||||
assert.ok([...seen.allowed].some(k => Number(k.split(',')[0]) >= 13),
|
||||
'the seeing side gained no tile east of the wall after the flip')
|
||||
|
||||
// --- flip back: nothing is ever revoked ----------------------------------------------------
|
||||
const back = await gm.ws.request({ t: 'wall.update', scene, id: wall.id, sight_dir: 'left' })
|
||||
assert.equal(back.ok, true, JSON.stringify(back))
|
||||
const again = await gm.ws.waitFor(m => m.t === 'wall' && m.id === wall.id &&
|
||||
m.sight_dir === 'left')
|
||||
assert.deepEqual(again.a, WALL.a)
|
||||
assert.deepEqual(again.b, WALL.b)
|
||||
const blindAgain = await sweepTiles({ origin, cookie: a.cookie, scene, art: gm.art,
|
||||
wallsFrame: { walls: [again] }, o: { x: 300, y: 300 },
|
||||
radius: 400, cell: CELL, strictMaybes: false })
|
||||
assertSuperset(blindAgain.allowed, seen.allowed, 'tiles after the flip back')
|
||||
assertSuperset(collectExplored(a.ws), aliceAfter, 'explored after the flip back')
|
||||
|
||||
a.ws.close(); b.ws.close(); gm.ws.close()
|
||||
})
|
||||
})
|
||||
|
||||
test('one-way sight: the direction and the walls survive a restart (#58)', async () => {
|
||||
await withOneWayStack(async ctx => {
|
||||
let origin = ctx.origin
|
||||
const { gmKey, stateDir, boot, down } = ctx
|
||||
let gm = await gmConnect(origin, gmKey)
|
||||
const ack = await gm.ws.request({ t: 'wall.add', scene: gm.scene, ...WALL })
|
||||
assert.equal(ack.ok, true, JSON.stringify(ack))
|
||||
await gm.ws.waitFor(m => m.t === 'wall' && m.id === ack.id)
|
||||
const alice = await createPlayer(gm.ws)
|
||||
await namePlayer(origin, alice.key, ALICE)
|
||||
const mk = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'pc', pos: [300, 300],
|
||||
flags: { vision: true }, vision_radius: 400,
|
||||
controller: alice.id, descriptive_name: ALICE,
|
||||
actual_name: ALICE })
|
||||
assert.equal(mk.ok, true, JSON.stringify(mk))
|
||||
const bob = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'pc', pos: [500, 400],
|
||||
flags: { vision: true }, vision_radius: 400,
|
||||
descriptive_name: BOB, actual_name: BOB })
|
||||
assert.equal(bob.ok, true, JSON.stringify(bob))
|
||||
const scene = gm.scene
|
||||
const art = gm.art
|
||||
writeTileGrid(stateDir, { scene, artVersion: art, size: CELL, ...REGION })
|
||||
const wallsFrame = { walls: [await gm.ws.waitFor(m => m.t === 'wall' && m.id === ack.id)] }
|
||||
|
||||
let a = await openAs(origin, alice.key)
|
||||
await a.ws.waitText('hello')
|
||||
await a.ws.waitFor(m => m.t === 'explored' && m.full === true)
|
||||
await sleep(100)
|
||||
assert.equal(a.ws.messages.some(m => m.t === 'token' && m.id === bob.id), false)
|
||||
const before = collectExplored(a.ws)
|
||||
const beforeTiles = await sweepTiles({ origin, cookie: a.cookie, scene, art, wallsFrame,
|
||||
o: { x: 300, y: 300 }, radius: 400, cell: CELL })
|
||||
assert.ok(beforeTiles.allowed.size > 10)
|
||||
a.ws.close(); gm.ws.close()
|
||||
|
||||
// Restart in place: same state dir, real binary migrates/reopens, nothing is rebuilt by hand.
|
||||
await down()
|
||||
await boot()
|
||||
origin = ctx.origin
|
||||
|
||||
gm = await gmConnect(origin, gmKey)
|
||||
const snap = gm.walls
|
||||
assert.equal(snap.walls.length, 1)
|
||||
assert.equal(snap.walls[0].sight_dir, 'left')
|
||||
assert.equal(snap.walls[0].kind, 'one_way')
|
||||
assert.deepEqual(snap.walls[0].a, WALL.a)
|
||||
assert.deepEqual(snap.walls[0].b, WALL.b)
|
||||
|
||||
a = await openAs(origin, alice.key)
|
||||
await a.ws.waitText('hello')
|
||||
await a.ws.waitFor(m => m.t === 'explored' && m.full === true)
|
||||
await sleep(100)
|
||||
assertSuperset(collectExplored(a.ws), before, 'explored across the restart')
|
||||
assert.equal(a.ws.messages.some(m => m.t === 'token' && m.id === bob.id), false,
|
||||
'the restarted server let the blind side see across')
|
||||
const afterTiles = await sweepTiles({ origin, cookie: a.cookie, scene, art: art,
|
||||
wallsFrame: { walls: snap.walls }, o: { x: 300, y: 300 },
|
||||
radius: 400, cell: CELL, strictMaybes: false })
|
||||
assertSuperset(afterTiles.allowed, beforeTiles.allowed, 'tiles across the restart')
|
||||
a.ws.close(); gm.ws.close()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user