import std/[unittest, json, os, math] import geometry, refold 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) proc hasVertex(poly: openArray[Vec], p: Vec): bool = for v in poly: if abs(v.x - p.x) < 1e-6 and abs(v.y - p.y) < 1e-6: return true 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): vertical arm (50,-50)-(50,0), horizontal arm (50,0)-(100,0) let w = @[W(50, -50, 50, 0), W(50, 0, 100, 0)] # viewer on the diagonal through the shared vertex: the ray touches both arms' endpoint let v: Vec = (0.0, -25.0) check visibilityPolygon(v, w, 500).hasVertex((50.0, 0.0)) check not sees(w, v, (70.0, 9.0)) # just below the ray through the vertex (y=10 at x=70): vertical arm shadows it check sees(w, v, (70.0, 11.0)) # just above the ray: past the vertex, the corner is not a crack # token on the line of the horizontal arm: a point just above the line is visible past the arm's end-on # edge, just below it is shadowed by the vertical arm check sees(w, (0.0, 0.0), (70.0, 5.0)) check not sees(w, (0.0, 0.0), (70.0, -5.0)) test "shared vertex: both arms required (mutation d1/d2)": # L corner at (50,0). The viewer's ray through the vertex splits the shadow: points above it are # shadowed only by the vertical arm, points below it only by the horizontal arm. Removing either arm # makes one assertion fail (tools/mutation.sh d1/d2 edit the SHARED-VERTEX line below). let arm1 = W(50, -50, 50, 0) # vertical let arm2 = W(50, 0, 100, 0) # horizontal let w = @[arm1, arm2] # SHARED-VERTEX let v: Vec = (0.0, 25.0) # ray v->(50,0) has slope -1/2: (70,-10) is on it check visibilityPolygon(v, w, 500).hasVertex((50.0, 0.0)) check not sees(w, v, (70.0, -11.0)) # above the vertex ray: crosses x=50 at y<0, only arm1 stops it check not sees(w, v, (70.0, -9.0)) # below the vertex ray: crosses y=0 at x>50, only arm2 stops it check sees(w, v, (70.0, 9.0)) # control: well clear of both arms, not a blanket "blocked" test "'<' apex: ray through the shared tip must not leak": for flip in [false, true]: # each wall in both directions: the tip is an upper end of one and a lower end of the other let w = if flip: @[W(100, 0, 50, -40), W(100, 0, 50, 40)] else: @[W(50, -40, 100, 0), W(50, 40, 100, 0)] check visibilityPolygon((0.0, 0.0), w, 500).hasVertex((100.0, 0.0)) check not sees(w, (0.0, 0.0), (150.0, 0.0)) check not sees(w, (0.0, 0.0), (300.0, 0.0)) check sees(w, (0.0, 0.0), (90.0, 0.0)) test "every segment endpoint is a polygon vertex (lower and upper end inclusive)": # free-standing wall, nothing else shares the endpoints: an exclusive end would drop the exact-endpoint ray let w = @[W(50, -30, 80, 10)] let poly = visibilityPolygon((0.0, 0.0), w, 500) check poly.hasVertex((50.0, -30.0)) # lower end (u = 0) check poly.hasVertex((80.0, 10.0)) # upper end (u = 1) let r = @[W(80, 10, 50, -30)] # same wall, ends swapped let pr = visibilityPolygon((0.0, 0.0), r, 500) check pr.hasVertex((50.0, -30.0)) check pr.hasVertex((80.0, 10.0)) test "rays nudged past a corner: area just beyond a wall end is visible": # viewer heights are chosen so the corner ray sits mid-way between two circle rays: no other ray can mask a missing nudge ray # wall (50,-50)-(50,0) seen from (0,7.4): the ray through the end (50,0) continues to (100,-7.4) let w = @[W(50, -50, 50, 0)] check sees(w, (0.0, 7.4), (100.0, -6.0)) # lit side of that ray check not sees(w, (0.0, 7.4), (100.0, -9.0)) # shadow side # mirror: wall (50,0)-(50,50) seen from (0,-7.4) let m = @[W(50, 0, 50, 50)] check sees(m, (0.0, -7.4), (100.0, 6.0)) check not sees(m, (0.0, -7.4), (100.0, 9.0)) # box (pillar) seen from (0,-24): the rays through corners (100,50) and (100,-50) continue to (200,124) and (200,-76) let b = box(100, -50, 150, 50) check sees(b, (0.0, -24.0), (200.0, 130.0)) check not sees(b, (0.0, -24.0), (200.0, 118.0)) check sees(b, (0.0, -24.0), (200.0, -85.0)) check not sees(b, (0.0, -24.0), (200.0, -70.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) check sees(w, (0.0, 0.0), (95.0, 95.0), 1000) # the corner itself is visible from inside check sees(w, (-90.0, -90.0), (90.0, 90.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)) check sees(w, (0.0, 0.0), (40.0, 0.0)) # in front of the join check sees(w, (0.0, 0.0), (-80.0, 0.0)) # behind the viewer check sees(w, (0.0, 0.0), (80.0, 100.0)) # past the far end of the line check not sees(w, (0.0, 0.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) check sees(w, (-30.0, -30.0), (-10.0, -5.0)) # same side of the stem, above the base check sees(w, (30.0, -30.0), (80.0, -60.0)) # mirror side check not sees(w, (30.0, -30.0), (-10.0, -5.0)) 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.inside((-50.0, -50.0)) # open outward quadrant check poly.inside((100.0, -30.0)) check poly.inside((50.0, 50.0)) # arms radiate from the token: the inner quadrant is open too check poly.inside((-50.0, 50.0)) check not poly.inside((150.0, 150.0)) # beyond the radius (212 > 200) check not poly.inside((0.0, 250.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)) check not sees(w, (0.0, 0.0), (600.0, 0.0)) # beyond the 500 radius 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) check not sees(w, (908.66, 672.03), (1100.0, 500.0), 400) # the x=1024 wall (y 256..608) is in the way test "radius clips": check not sees(@[], (0.0, 0.0), (300.0, 0.0), 200) 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) test "degenerate input: fewer than 3 vertices": check cellsTouched([(1.0, 1.0), (50.0, 50.0)], 32).len == 0 test "touching a cell line: inclusive on the max side, not on the bbox minimum side": let sq = [(32.0, 32.0), (64.0, 32.0), (64.0, 64.0), (32.0, 64.0)] # exactly cell (1,1) # (prototype-compatible: no cell on the low side of the bbox minimum lines) check cellsTouched(sq, 32) == @[(1, 1), (2, 1), (1, 2), (2, 2)] test "concave polygon: a notch cell is not filled": # U shape open at the top: notch x 60..100, y 0..80; cells (2,0) and (2,1) (x 64..96) lie wholly inside it let u = [(0.0, 0.0), (60.0, 0.0), (60.0, 80.0), (100.0, 80.0), (100.0, 0.0), (160.0, 0.0), (160.0, 128.0), (0.0, 128.0)] let c = cellsTouched(u, 32) check (2, 0) notin c and (2, 1) notin c check (2, 2) in c and (2, 3) in c # the bridge below the notch check (0, 0) in c and (4, 0) in c # ---- fixtures ---------------------------------------------------------------------------------------------------- type Scene = object walls: seq[Wall] tokens: seq[Vec] radius, cell, tokenRadius: float proc loadScene(): Scene = # fixtures are copies of prototype-server-vision/data/scene.json; a missing file fails, never skips let j = parseFile(currentSourcePath().parentDir / "fixtures" / "scene.json") for w in j["walls"]: result.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"]: result.tokens.add (t["pos"][0].getFloat, t["pos"][1].getFloat) result.radius = j["visionRadius"].getFloat result.cell = j["exploredCell"].getFloat result.tokenRadius = j["tokenRadius"].getFloat suite "seed": test "every token in seed sees itself and is not walled in": let sc = loadScene() for p in sc.tokens: let poly = visibilityPolygon(p, sc.walls, sc.radius) check poly.len > 8 check cellsTouched(poly, sc.cell).len > 0 for w in sc.walls: # token circle clear of every wall check segDist(p, w.a, w.b) >= sc.tokenRadius # ---- regression corpus: new == prototype output --------------------------------------------------------------- # tests/fixtures/corpus.jsonl (tools/mkcorpus.nim): every player `vision` message of the two prototype leak runs # (viewer position + open doors at that gseq + the polygon the OLD server computed). 5.5 "regression baseline". proc samePoly(a, b: openArray[Vec], tol = 1e-6): bool = if a.len != b.len: return false for i in 0 ..< a.len: if abs(a[i].x - b[i].x) > tol or abs(a[i].y - b[i].y) > tol: return false true suite "corpus (prototype leak transcripts)": test "visibilityPolygon and cellsTouched equal the prototype results": var sc = loadScene() let base = sc.walls var n, doorsSeen = 0 for line in lines(currentSourcePath().parentDir / "fixtures" / "corpus.jsonl"): let j = parseJson(line) var walls = base for w in walls.mitems: if w.door: w.open = false for id in j["open"]: walls[id.getInt].open = true; inc doorsSeen let o: Vec = (j["pos"][0].getFloat, j["pos"][1].getFloat) var rec: seq[Vec] for p in j["poly"]: rec.add (p[0].getFloat, p[1].getFloat) let poly = visibilityPolygon(o, walls, sc.radius) check samePoly(poly, rec) check cellsTouched(poly, sc.cell) == cellsTouchedOld(poly, sc.cell) check cellsTouched(rec, sc.cell) == cellsTouchedOld(rec, sc.cell) inc n check n >= 300 # corpus is not silently empty check doorsSeen > 0 # and exercises opened doors # ---- differential: scanline vs prototype per-cell --------------------------------------------------------------- # Tiny deterministic PRNG so the tests do not depend on std/random version behaviour. type Rng = object s: uint64 proc next(r: var Rng): uint64 = r.s = r.s xor (r.s shl 13); r.s = r.s xor (r.s shr 7); r.s = r.s xor (r.s shl 17); r.s proc uni(r: var Rng, lo, hi: float): float = lo + (hi - lo) * float(r.next shr 11) / float(1'u64 shl 53) proc randomWalls(r: var Rng, n: int, span: float): seq[Wall] = for i in 0 ..< n: let a: Vec = (r.uni(0, span), r.uni(0, span)) let ang = r.uni(0, 2 * PI) let l = r.uni(10, 300) result.add Wall(a: a, b: (a.x + l * cos ang, a.y + l * sin ang), door: i mod 7 == 0, open: i mod 14 == 0) suite "cellsTouched differential vs prototype": test "random visibility polygons: identical cell lists": var r = Rng(s: 0x9E3779B97F4A7C15'u64) var total = 0 for iter in 0 ..< 300: let walls = randomWalls(r, 5 + iter mod 40, 1200) let o: Vec = (r.uni(100, 1100), r.uni(100, 1100)) let cell = [32.0, 64.0, 25.0][iter mod 3] let poly = visibilityPolygon(o, walls, r.uni(50, 500)) let (a, b) = (cellsTouched(poly, cell), cellsTouchedOld(poly, cell)) check a == b total += a.len check total > 10000 test "random simple polygons (star-shaped, concave): identical cell lists": var r = Rng(s: 12345'u64) for iter in 0 ..< 300: let c: Vec = (r.uni(100, 500), r.uni(100, 500)) let n = 3 + iter mod 20 var poly: seq[Vec] for i in 0 ..< n: let a = 2 * PI * (i.float + r.uni(0, 0.9)) / n.float let rad = r.uni(2, 150) poly.add (c.x + rad * cos a, c.y + rad * sin a) check cellsTouched(poly, 32) == cellsTouchedOld(poly, 32) test "grid-aligned integer polygons (edges on cell lines): identical cell lists": var r = Rng(s: 777'u64) for iter in 0 ..< 300: let x0 = float(int(r.uni(0, 10))) * 16 let y0 = float(int(r.uni(0, 10))) * 16 let poly = [(x0, y0), (x0 + float(1 + int(r.uni(0, 8))) * 16, y0), (x0 + float(1 + int(r.uni(0, 8))) * 16, y0 + float(1 + int(r.uni(0, 8))) * 16), (x0, y0 + float(1 + int(r.uni(0, 8))) * 16)] check cellsTouched(poly, 32) == cellsTouchedOld(poly, 32) # ---- independent explored oracle --------------------------------------------------------------------------------- # Brute force over a point lattice with its own segment maths (nothing from visibilityPolygon / cellsTouched / the old # cell test). Tolerance TolPx = 0.5 px, as the leak checker (DESIGN T14, 5.5). # sure = cells holding a lattice point that is in range (inscribed 64-gon radius, minus TolPx) and sees the viewer # with every blocking wall farther than TolPx from the line of sight: must all be in cellsTouched (no missed cell) # maybe = cellsTouched cells must each hold a point that is visible when walls only block by PROPER crossing and the # point may move TolPx (no invented cell). 9x9 lattice per cell first, 65x65 (0.5 px) for slivers. const TolPx = 0.5 proc pSegDist(p, a, b: Vec): float = let (ex, ey) = (b.x - a.x, b.y - a.y) let l2 = ex * ex + ey * ey let t = if l2 == 0: 0.0 else: max(0.0, min(1.0, ((p.x - a.x) * ex + (p.y - a.y) * ey) / l2)) hypot(p.x - a.x - t * ex, p.y - a.y - t * ey) proc properCross(p, q, a, b: Vec): bool = proc o(a, b, c: Vec): float = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) let (d1, d2, d3, d4) = (o(p, q, a), o(p, q, b), o(a, b, p), o(a, b, q)) d1 * d2 < 0 and d3 * d4 < 0 proc segSegGap(p, q, a, b: Vec): float = # 0 when they cross if properCross(p, q, a, b): 0.0 else: min(min(pSegDist(p, a, b), pSegDist(q, a, b)), min(pSegDist(a, p, q), pSegDist(b, p, q))) proc oracleCheck(o: Vec, walls: openArray[Wall], radius, cell: float, touched: openArray[(int, int)]): tuple[sure, extra, miss: int] = var blocking: seq[Wall] for w in walls: if w.blocks: blocking.add w let rin = radius * cos(PI / 64) - TolPx # sure: every strictly visible lattice point's cell must be touched var y = o.y - radius + 1.3 while y < o.y + radius: var x = o.x - radius + 1.7 while x < o.x + radius: let p: Vec = (x, y) if hypot(x - o.x, y - o.y) <= rin: var clear = true for w in blocking: if segSegGap(o, p, w.a, w.b) <= TolPx: clear = false; break if clear: inc result.sure if (int(floor(x / cell)), int(floor(y / cell))) notin touched: inc result.miss x += 4 y += 4 # maybe: every touched cell must contain a (tolerantly) visible point proc visibleTol(p: Vec): bool = for (dx, dy) in [(0.0, 0.0), (TolPx, 0.0), (-TolPx, 0.0), (0.0, TolPx), (0.0, -TolPx)]: let q: Vec = (p.x + dx, p.y + dy) if hypot(q.x - o.x, q.y - o.y) > radius + TolPx: continue var clear = true for w in blocking: if properCross(o, q, w.a, w.b): clear = false; break if clear: return true for (ix, iy) in touched: var found = false for n in [8, 64]: for j in 0 .. n: for i in 0 .. n: if not found and visibleTol((ix.float * cell + cell * i.float / n.float, iy.float * cell + cell * j.float / n.float)): found = true if found: break if not found: inc result.extra proc oracleOf(o: Vec, walls: openArray[Wall], radius, cell: float): tuple[sure, extra, miss: int] = oracleCheck(o, walls, radius, cell, cellsTouched(visibilityPolygon(o, walls, radius), cell)) suite "explored oracle (independent, tolerance 0.5 px)": test "prototype scene, all tokens, doors closed and opened": let sc = loadScene() var opened = sc.walls for w in opened.mitems: if w.door: w.open = true var sure = 0 for walls in [sc.walls, opened]: for p in sc.tokens: let r = oracleOf((p.x + 7.3, p.y - 3.1), walls, sc.radius, sc.cell) check r.miss == 0 check r.extra == 0 sure += r.sure check sure > 100000 # the oracle really sampled test "random wall fields, cell 32 and 25": var r = Rng(s: 4242'u64) for iter in 0 ..< 6: let walls = randomWalls(r, 30, 1200) let o: Vec = (r.uni(200, 1000), r.uni(200, 1000)) let res = oracleOf(o, walls, 300, [32.0, 25.0][iter mod 2]) check res.miss == 0 check res.extra == 0 test "negative control: the oracle notices a missing and an invented cell": let sc = loadScene() let o = sc.tokens[0] let good = cellsTouched(visibilityPolygon(o, sc.walls, sc.radius), sc.cell) check oracleCheck(o, sc.walls, sc.radius, sc.cell, good).miss == 0 # drop a cell well inside the lit area let dropped = good[good.len div 2] var fewer: seq[(int, int)] for c in good: if c != dropped: fewer.add c check oracleCheck(o, sc.walls, sc.radius, sc.cell, fewer).miss > 0 # add a cell beyond the wall box that nothing can see check oracleCheck(o, sc.walls, sc.radius, sc.cell, good & @[(100, 100)]).extra > 0 # replace the polygon by a half-radius one: many clearly visible cells are missed check oracleCheck(o, sc.walls, sc.radius, sc.cell, cellsTouched(visibilityPolygon(o, sc.walls, sc.radius / 2), sc.cell)).miss > 0