diff --git a/.gitignore b/.gitignore index dde0e0c..2c6c885 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,5 @@ nimcache/ tests/t[a-z]* !tests/*.nim !tests/fixtures/ +tools/bench +tools/mkcorpus diff --git a/devbox.json b/devbox.json index d317b83..26bdb03 100644 --- a/devbox.json +++ b/devbox.json @@ -16,6 +16,9 @@ ], "mutation": [ "tools/mutation.sh" + ], + "bench": [ + "mkdir -p results; nim c -d:release --hints:off -r tools/bench.nim > results/bench.log 2>&1; rc=$?; cat results/bench.log; exit $rc" ] } }, diff --git a/results/bench.log b/results/bench.log new file mode 100644 index 0000000..5aed709 --- /dev/null +++ b/results/bench.log @@ -0,0 +1,17 @@ +== prototype scene (60 walls, 8 tokens, radius 400, cell 32) == +1 poly (jittered start positions): n=2000 avg=0.036ms worst=0.121ms +6 polys (one 6-token party): n=500 avg=0.204ms worst=0.264ms +1 poly + cellsTouched (scanline): n=2000 avg=0.049ms worst=0.339ms +6 polys + cellsTouched (scanline): n=300 avg=0.265ms worst=0.353ms +1 poly + cellsTouchedOld (prototype reference): n=500 avg=0.726ms worst=2.365ms +TARGET polygon+cells, prototype scene (prototype baseline 0.451): 0.049 ms vs <= 0.451 ms: PASS +== 5k sparse: genScene(world=16384., n=5000, seed=1), avg walls in vision bbox 15.6 == +1 poly, 5k sparse: n=2000 avg=0.082ms worst=0.127ms +1 poly + cellsTouched, 5k sparse: n=2000 avg=0.096ms worst=0.145ms +1 move check (pathClear, cap-length step), 5k sparse: n=20000 avg=0.010ms worst=0.131ms +TARGET polygon, 5k-wall scene: 0.082 ms vs <= 1.0 ms: PASS +== 5k dense: genScene(world=4096., n=5000, seed=1), avg walls in vision bbox 206.9 == +1 poly, 5k dense: n=2000 avg=1.282ms worst=3.079ms +1 poly + cellsTouched, 5k dense: n=2000 avg=1.319ms worst=2.817ms +1 move check (pathClear, cap-length step), 5k dense: n=20000 avg=0.009ms worst=0.116ms +(sink 6023672) diff --git a/results/nimble-test.log b/results/nimble-test.log index 16ca289..c3ff7a1 100644 --- a/results/nimble-test.log +++ b/results/nimble-test.log @@ -1,5 +1,7 @@ Info: Using the environment variable: NIMBLE_DIR='/home/davide/Projects/GDR/FFF_vtt/.devbox/nimble' Info: using /nix/store/0cbdz34lsakfirycixckf6ypsd8hazhg-x86_64-unknown-linux-gnu-nim-wrapper-2.2.12/bin/nim for compilation + Compiling /home/davide/Projects/GDR/FFF_vtt/tests/testutil (from package fff_vtt) using c backend + Success: Execution finished Compiling /home/davide/Projects/GDR/FFF_vtt/tests/tgeometry (from package fff_vtt) using c backend Nim Output [Suite] visibility ... [OK] open space is a circle @@ -20,7 +22,29 @@ ... [OK] long thin corridor ... [OK] wall endpoints behind the viewer: fan stays angularly ordered ... [OK] radius clips - ... [Suite] moves + ... [Suite] cells + ... [OK] square polygon + ... [OK] tiny polygon inside one cell + ... [OK] polygon spanning a cell with no vertex in it + ... [OK] big polygon includes fully covered interior cells + ... [OK] degenerate input: fewer than 3 vertices + ... [OK] touching a cell line: inclusive on the max side, not on the bbox minimum side + ... [OK] concave polygon: a notch cell is not filled + ... [Suite] seed + ... [OK] every token in seed sees itself and is not walled in + ... [Suite] corpus (prototype leak transcripts) + ... [OK] visibilityPolygon and cellsTouched equal the prototype results + ... [Suite] cellsTouched differential vs prototype + ... [OK] random visibility polygons: identical cell lists + ... [OK] random simple polygons (star-shaped, concave): identical cell lists + ... [OK] grid-aligned integer polygons (edges on cell lines): identical cell lists + ... [Suite] explored oracle (independent, tolerance 0.5 px) + ... [OK] prototype scene, all tokens, doors closed and opened + ... [OK] random wall fields, cell 32 and 25 + ... [OK] negative control: the oracle notices a missing and an invented cell + Success: Execution finished + Compiling /home/davide/Projects/GDR/FFF_vtt/tests/tmoverules (from package fff_vtt) using c backend + Nim Output [Suite] pathClear, r = 0 (ported prototype move tests) ... [OK] crossing blocked, parallel ok ... [OK] grazing an endpoint is blocked ... [OK] no leak through shared vertex @@ -28,20 +52,57 @@ ... [OK] moving along a collinear wall is blocked ... [OK] doors ... [OK] zero-length move - ... [Suite] cells - ... [OK] square polygon - ... [OK] tiny polygon inside one cell - ... [OK] polygon spanning a cell with no vertex in it - ... [OK] big polygon includes fully covered interior cells - ... [Suite] seed - ... [OK] every token in seed sees itself and is not walled in - ... [Suite] token clearance (r=20) - ... [OK] near pillar: circle overlapping blocked, clear ok - ... [OK] near closed door blocks, open door passes - ... [OK] 64px corridor and doorway passable on centerline - ... [OK] legacy overlap can escape, not stay overlapped - ... [Suite] door/wall closing on a token (M1 pins current behaviour) - ... [OK] door closed on a token: Q14 undecided, DESIGN 5.4 vs 12 H2 conflict - ... [OK] KNOWN LIMITATION: token exactly on a wall cannot move off it + ... [Suite] capsule (swept circle), r = 20 + ... [OK] near pillar: circle overlapping blocked, clear ok (ported) + ... [OK] closed door blocks near, open door passes (ported) + ... [OK] 64px corridor and doorway passable on the centreline (ported) + ... [OK] corner clipping: path passes the wall end closer than r though both ends are clear + ... [OK] parallel pass: r clear, just under r blocked (touching at exactly r is clear) + ... [OK] diagonal squeeze past an L corner with a gap narrower than 2r is blocked + ... [OK] leg of the path inside r of a non-start wall blocks even if start and end are clear + ... [Suite] token on / near a wall: escape (replaces the KNOWN LIMITATION pin) + ... [OK] exactly on a wall: can step off perpendicular, either side, to a clear spot + ... [OK] exactly on a wall: still refused when it would stay overlapped or run along/through + ... [OK] r = 0: standing on a wall is not an escape case (touch blocks), as the prototype + ... [OK] overlapping 10 px off: may leave away from the wall, not cross it, not stay overlapped + ... [OK] escaping one wall does not excuse another + ... [OK] escape from a closed door; an open door never needed an escape + ... [OK] overlapping at a wall end: leave past the end without crossing + ... [Suite] move rules: player vs GM, step cap, uniform nack + ... [OK] owner check: not yours is mkError, no position + ... [OK] GM-controlled token (no owner): players get mkError + ... [OK] step cap = scene default without vision, token vision radius with it + ... [OK] over-cap, blocked-by-wall, blocked-flag and out-of-bounds nacks are identical + ... [OK] an accepted move applies and echoes the destination + ... [OK] player move honours walls (capsule) via moveToken + ... [OK] GM: ignores walls, step cap and blocked; bounds still apply + ... [Suite] blocked flag + ... [OK] wall added within r of the circle (centre not on it) sets blocked; exactly r does not + ... [OK] GM-controlled tokens get the flag too; wall bbox does not matter, distance does + ... [OK] open door added or opened never sets; closing a door on a token does + ... [OK] blocked token: player moves refused, GM move allowed and does not clear + ... [OK] cleared by removing the wall; unrelated removals keep it + ... [OK] cleared by opening the door; a second open is a no-op + ... [OK] cleared by the GM; not re-set by itself + ... [OK] wall update = remove then add + ... [OK] GM placement and GM move onto a wall never set blocked, and the token can escape + ... [OK] Q14: a door closed 10 px from a token: token blocked, player refused, GM moves it, opening frees it + ... [OK] unconfirmed (b), pinned: opening a door clears blocked although another closed wall still overlaps + ... [Suite] seed scene + ... [OK] no escape hatch: a player cannot walk through any wall of a boxed room + Success: Execution finished + Compiling /home/davide/Projects/GDR/FFF_vtt/tests/tprobing (from package fff_vtt) using c backend + Nim Output [Suite] probing (T8) + ... [OK] P1: probes longer than the cap get one fixed nack regardless of the scene + ... [OK] P2: scenes differing only beyond the bound give identical replies over 3000 probes + ... [OK] P3 negative control: a wall inside the disc IS visible through replies (the harness can fail) + ... [OK] P4: probing cannot unflag or move a blocked token + ... [OK] doors beyond the bound: opening or closing them changes no reply + Success: Execution finished + Compiling /home/davide/Projects/GDR/FFF_vtt/tests/tscenegen (from package fff_vtt) using c backend + Nim Output [Suite] scenegen (bench scenes) + ... [OK] exactly n walls, deterministic per seed, seeds differ + ... [OK] doors are every 10th wall, all closed; walls stay inside the world (+- jitter) + ... [OK] walls are non-degenerate and axis-ish segments of room-edge length Success: Execution finished Success: All tests passed diff --git a/tests/tscenegen.nim b/tests/tscenegen.nim new file mode 100644 index 0000000..fd95809 --- /dev/null +++ b/tests/tscenegen.nim @@ -0,0 +1,23 @@ +import std/unittest +import std/math +import geometry +import ../tools/scenegen + +suite "scenegen (bench scenes)": + test "exactly n walls, deterministic per seed, seeds differ": + let a = genScene(16384, 5000, 1) + check a.len == 5000 + check a == genScene(16384, 5000, 1) + check a != genScene(16384, 5000, 2) + test "doors are every 10th wall, all closed; walls stay inside the world (+- jitter)": + let a = genScene(4096, 5000, 1) + var doors = 0 + for i, w in a: + check w.door == (i mod 10 == 9) + check not w.open + for p in [w.a, w.b]: check p.x >= -6 and p.x <= 4096 + 6 and p.y >= -6 and p.y <= 4096 + 6 + if w.door: inc doors + check doors == 500 + test "walls are non-degenerate and axis-ish segments of room-edge length": + for w in genScene(16384, 5000, 1): + check hypot(w.b.x - w.a.x, w.b.y - w.a.y) > 100 diff --git a/tools/bench.nim b/tools/bench.nim new file mode 100644 index 0000000..5a98794 --- /dev/null +++ b/tools/bench.nim @@ -0,0 +1,76 @@ +## Vision microbench: devbox run bench (nim c -d:release -r tools/bench.nim; log: results/bench.log). +## No timing code lives in server/: this harness times from outside with O(1) accumulators (sum, worst), no sample arrays. +## Targets (DESIGN 5.3 / 13 M2, PROPOSED): polygon + cells <= 0.451 ms avg on the prototype scene; polygon < 1 ms avg on 5k walls. +import std/[json, monotimes, times, strformat, os, math] +import geometry, moverules +import scenegen +import ../tests/[refold, testutil] + +let root = currentSourcePath().parentDir.parentDir +let j = parseFile(root / "tests" / "fixtures" / "scene.json") +var proto: seq[Wall] +for w in j["walls"]: + proto.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 radius = j["visionRadius"].getFloat +let cell = j["exploredCell"].getFloat +var toks: seq[Vec] +for t in j["tokens"]: toks.add (t["pos"][0].getFloat, t["pos"][1].getFloat) + +var sink = 0 +var misses = 0 +proc bench(name: string, n: int, f: proc(i: int)): float = + for i in 0 ..< 50: f(i) # warm-up + 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) + result = sum / n.float + echo &"{name}: n={n} avg={result:.3f}ms worst={worst:.3f}ms" +proc target(name: string, got, limit: float) = + let ok = got <= limit + if not ok: inc misses + echo &"TARGET {name}: {got:.3f} ms vs <= {limit} ms: {(if ok: \"PASS\" else: \"MISS\")}" + +echo "== prototype scene (60 walls, 8 tokens, radius 400, cell 32) ==" +discard bench("1 poly (jittered start positions)", 2000, proc(i: int) = + let p = toks[i mod 8]; sink += visibilityPolygon((p.x + float(i mod 50), p.y), proto, radius).len) +discard bench("6 polys (one 6-token party)", 500, proc(i: int) = + for k in 0 ..< 6: + let p = toks[k + 2]; sink += visibilityPolygon((p.x + float(i mod 50), p.y), proto, radius).len) +let pc = bench("1 poly + cellsTouched (scanline)", 2000, proc(i: int) = + let p = toks[i mod 8]; sink += cellsTouched(visibilityPolygon((p.x + float(i mod 50), p.y), proto, radius), cell).len) +discard bench("6 polys + cellsTouched (scanline)", 300, proc(i: int) = + for k in 0 ..< 6: + let p = toks[k + 2]; sink += cellsTouched(visibilityPolygon((p.x + float(i mod 50), p.y), proto, radius), cell).len) +discard bench("1 poly + cellsTouchedOld (prototype reference)", 500, proc(i: int) = + let p = toks[i mod 8]; sink += cellsTouchedOld(visibilityPolygon((p.x + float(i mod 50), p.y), proto, radius), cell).len) +target("polygon+cells, prototype scene (prototype baseline 0.451)", pc, 0.451) + +proc big(label: string, world: float) = + let walls = genScene(world, 5000, 1) + var inBox, nn = 0 + var r = Rng(s: 7) + for k in 0 ..< 200: # density: walls whose bbox meets the 800x800 vision box + let o: Vec = (r.uni(400, world - 400), r.uni(400, world - 400)) + for w in walls: + if not (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): inc inBox + inc nn + echo &"== {label}: genScene(world={world:.0f}, n=5000, seed=1), avg walls in vision bbox {inBox.float / nn.float:.1f} ==" + var rng = Rng(s: 99) + let po = bench(&"1 poly, {label}", 2000, proc(i: int) = + let o: Vec = (rng.uni(400, world - 400), rng.uni(400, world - 400)) + sink += visibilityPolygon(o, walls, radius).len) + discard bench(&"1 poly + cellsTouched, {label}", 2000, proc(i: int) = + let o: Vec = (rng.uni(400, world - 400), rng.uni(400, world - 400)) + sink += cellsTouched(visibilityPolygon(o, walls, radius), cell).len) + discard bench(&"1 move check (pathClear, cap-length step), {label}", 20000, proc(i: int) = + let o: Vec = (rng.uni(400, world - 400), rng.uni(400, world - 400)) + sink += int(pathClear(walls, o, (o.x + 300, o.y), 20))) + if label == "5k sparse": target("polygon, 5k-wall scene", po, 1.0) +big("5k sparse", 16384) +big("5k dense", 4096) +echo "(sink ", sink, ")" +quit(if misses == 0: 0 else: 1) diff --git a/tools/scenegen.nim b/tools/scenegen.nim new file mode 100644 index 0000000..3516753 --- /dev/null +++ b/tools/scenegen.nim @@ -0,0 +1,30 @@ +## Synthetic wall scenes for the wall-count scaling bench (DESIGN 5.3 / 13 M2, H3). +## Layout: a square world of `world` px split into G x G rooms, G = ceil(sqrt(n / 2)); every room owns its EAST and SOUTH +## edge (2 candidate walls per room, west/north belong to the neighbour), so an n = 5000 scene is exactly 50 x 50 rooms. +## Each edge becomes ONE wall segment covering 55..95 % of the edge at a random offset (the rest is a doorway gap, so vision +## really passes between rooms); endpoints are jittered by up to +-6 px (no axis-aligned degeneracy); every 10th wall is a +## closed door. Generation stops after exactly n walls (row-major). Fully determined by (world, n, seed): xorshift64. +## Density: walls per vision bbox (800 x 800, radius 400) ~= 2 * (800 / pitch)^2: pitch 327.68 (world 16384) -> ~12, +## pitch 81.92 (world 4096, "dense") -> ~190. +import std/math +import geometry +import ../tests/testutil # Rng + +proc genScene*(world: float, n: int, seed: uint64): seq[Wall] = + var r = Rng(s: seed) + let g = int(ceil(sqrt(n.float / 2))) + let pitch = world / g.float + proc jit(r: var Rng): float = r.uni(-6, 6) + for gy in 0 ..< g: + for gx in 0 ..< g: + for edge in 0 .. 1: # 0 = east edge (vertical), 1 = south edge (horizontal) + if result.len >= n: return + let frac = r.uni(0.55, 0.95) + let off = r.uni(0, 1 - frac) + let (x0, y0) = (gx.float * pitch, gy.float * pitch) + var a, b: Vec + if edge == 0: + a = (x0 + pitch + r.jit, y0 + off * pitch + r.jit); b = (x0 + pitch + r.jit, y0 + (off + frac) * pitch + r.jit) + else: + a = (x0 + off * pitch + r.jit, y0 + pitch + r.jit); b = (x0 + (off + frac) * pitch + r.jit, y0 + pitch + r.jit) + result.add Wall(a: a, b: b, door: result.len mod 10 == 9, open: false)