diff --git a/server/vision.nim b/server/vision.nim new file mode 100644 index 0000000..3fdad04 --- /dev/null +++ b/server/vision.nim @@ -0,0 +1,100 @@ +## Per-player vision and explored state (DESIGN 3.1, 4.1, 4.2, 5.1, 8; M3 slice 5, issue #20). +## Pure and in-process: no IO, no clock, no wire shapes. main.nim holds one `PlayerVision` per player +## id and calls `refresh` after every mutation that can change that player's sight. +## +## Vision (5.1): one visibility polygon per token the player controls that carries the `vision` flag, +## cast from the token centre against the scene's blocking walls with the token's range (Q7: the +## token's `vision_radius` if it sets one, else the scene's `vision_radius_default`). Open doors do +## not block; geometry.nim does the casting. +## +## Explored (5.1, 8): the union of the cells every polygon ever overlapped, per player, strictly +## per player (Q9 FIXED). It only grows: a wall edit or a door closing never un-explores. `cells` +## are `(cx, cy)` from the world origin, cell size = the scene's `cell` (= `tile_size` in v1, Q4). +## Persistence (chunked bitmaps, #21) is slice 6; this module owns the in-memory set only. +## +## Token visibility to a player (3.1): a token this player controls is always visible; any other +## token only while its centre is inside one of the player's polygons and it is not `gm_only`. +## `Poly` ids are token ids, which the controlling player already knows (`mine`). +## +## Change tracking: `ver` counts polygon changes (the client gets `vision` only when it changes, 6.4) +## and `fresh` holds the cells this mutation added (4.2 step 8: cleared after egress). +import std/[algorithm, math, sets] +import tokens, worldmap, geometry, world + +type + Poly* = object + tokenId*: string + pts*: seq[Vec] + + PlayerVision* = object + polys*: seq[Poly] + explored*: HashSet[int] ## cell index cy * cols + cx + ver*: int ## bumped when `polys` changes + fresh*: seq[(int, int)] ## cells added by the current mutation (cx, cy), sorted + +proc cols*(sc: SceneRec): int = + ## Cells across the scene (DESIGN 8: ceil(w / cell)). + max(1, int(ceil(sc.w / float(sc.cell)))) + +proc rows*(sc: SceneRec): int = + max(1, int(ceil(sc.h / float(sc.cell)))) + +proc cellIndex*(sc: SceneRec, cx, cy: int): int = cy * sc.cols + cx + +proc cellOf*(sc: SceneRec, idx: int): (int, int) = + let c = sc.cols + (idx mod c, idx div c) + +proc computePolys*(sc: SceneRec, tokens: seq[TokenRec], playerId: int): seq[Poly] = + ## One polygon per token of this player that has vision, in token order (a stable wire order). + if playerId <= 0: return + let walls = geometryWalls(sc) + for t in tokens: + if t.owner != playerId or not t.hasVision: continue + result.add Poly(tokenId: t.id, + pts: visibilityPolygon(t.pos, walls, visionRange(sc, t))) + +proc refresh*(pv: var PlayerVision, sc: SceneRec, tokens: seq[TokenRec], playerId: int) = + ## Recomputes the polygons, bumps `ver` when they changed, and folds every newly seen cell into + ## `explored`/`fresh`. Cells already explored are never re-announced. + let polys = computePolys(sc, tokens, playerId) + if polys != pv.polys: + pv.polys = polys + inc pv.ver + var added = initHashSet[int]() + for poly in pv.polys: + for (cx, cy) in cellsTouched(poly.pts, float(sc.cell)): + if cx < 0 or cy < 0 or cx >= sc.cols or cy >= sc.rows: continue + let idx = sc.cellIndex(cx, cy) + if idx in pv.explored or idx in added: continue + added.incl idx + pv.fresh.add (cx, cy) + for idx in added: pv.explored.incl idx + pv.fresh.sort() + +proc clearFresh*(pv: var PlayerVision) = + ## 4.2 step 8: after the egress fan-out every connection has the cells. + pv.fresh.setLen(0) + +proc exploredFull*(pv: PlayerVision, sc: SceneRec): seq[(int, int)] = + ## Every explored cell, sorted by (cy, cx): the connect/resync payload (6.1 `explored full`). + var idx = newSeq[int](pv.explored.len) + var i = 0 + for k in pv.explored: + idx[i] = k + inc i + idx.sort() + result = newSeqOfCap[(int, int)](idx.len) + for k in idx: result.add sc.cellOf(k) + +proc insideAny*(pv: PlayerVision, p: Vec): bool = + for poly in pv.polys: + if inside(poly.pts, p): return true + +proc visibleTo*(pv: PlayerVision, t: TokenRec, playerId: int): bool = + ## DESIGN 3.1: controlled tokens always, anything else only inside own LOS and not `gm_only`. + ## This is the only copy of the rule: the leak-fault builds add tokens that this returns false for + ## instead of re-implementing it, so a mutation here still breaks the clean path (DESIGN 10.3). + if t.owner == playerId: return true + if t.gmOnly: return false + pv.insideAny(t.pos) diff --git a/server/worldmap.nim b/server/worldmap.nim new file mode 100644 index 0000000..2b97b9d --- /dev/null +++ b/server/worldmap.nim @@ -0,0 +1,36 @@ +## Adapters between the authoritative records (`world.SceneRec`, `tokens.TokenRec`) and the pure +## inputs of the vision code (`geometry.nim`) and the move rules (`moverules.nim`). No IO, no locks, +## no wire shapes: main.nim builds these per mutation and copies the outcome back. +## +## The two modules below exist because the walls and tokens are stored as records with wire fields +## (kind, open, flags, owner) while geometry and moverules take narrow value types. Keeping the +## translation in one place is what makes "the rules never see the wire" checkable. +import std/options +import geometry, moverules, tokens, world + +proc geometryWalls*(sc: SceneRec): seq[Wall] = + ## The scene's walls as the vision code sees them: an open door does not block (5.1). + result = newSeqOfCap[Wall](sc.walls.len) + for w in sc.walls: + result.add Wall(a: w.a, b: w.b, door: w.kind == wkDoor, open: w.open) + +proc moveScene*(sc: SceneRec, tokens: seq[TokenRec]): moverules.Scene = + ## The scene as the move rules see it. One radius for every token in this slice: the per-token + ## radius is #4's `token.resize` (slice 7), so the scene default stands in for all of them. + result = moverules.Scene(w: sc.w, h: sc.h, tokenRadius: sc.tokenRadiusDefault, + visionDefault: sc.visionRadiusDefault, + walls: geometryWalls(sc)) + result.tokens = newSeqOfCap[moverules.Token](tokens.len) + for t in tokens: + result.tokens.add moverules.Token(pos: t.pos, owner: t.owner, + hasVision: t.hasVision, + visionRadius: (if t.visionRadius.isSome: t.visionRadius.get + else: 0.0), + blocked: false, prev: t.prev, hasPrev: t.hasPrev) + +proc copyPosition*(tokens: var seq[TokenRec], ti: int, mr: moverules.Token) = + ## Writes one token's position (and its door-push history) back after a rule ran. + if ti < 0 or ti >= tokens.len: return + tokens[ti].pos = mr.pos + tokens[ti].prev = mr.prev + tokens[ti].hasPrev = mr.hasPrev diff --git a/tests/tvision.nim b/tests/tvision.nim new file mode 100644 index 0000000..d1f73b6 --- /dev/null +++ b/tests/tvision.nim @@ -0,0 +1,168 @@ +## Per-player vision and explored (#20, DESIGN 3.1, 4.2, 5.1, 8): one polygon per controlled token +## with the `vision` flag, walls and open doors, the explored set that only grows, the fresh cells of +## one mutation, and the token-visibility rule (controlled always, LOS + not `gm_only` otherwise). +import std/[algorithm, json, math, options, sequtils, sets, unittest] +import geometry, tokens, vision, world + +proc sceneWith(walls: seq[WallRec]): SceneRec = + SceneRec(id: 1, name: "Scene", w: 4096, h: 4096, tileSize: 32, cell: 32, gridSize: 0, + visionRadiusDefault: 400, tokenRadiusDefault: 20, artVersion: 1, nextWallId: 1, + extra: newJObject(), walls: walls) + +proc wall(ax, ay, bx, by: float, kind = wkWall, open = false): WallRec = + WallRec(a: (ax, ay), b: (bx, by), kind: kind, open: open, flags: newJObject()) + +proc tok(id: string, x, y: float, owner: int, visionFlag = true, gmOnly = false): TokenRec = + TokenRec(id: id, scene: 1, kind: "pc", descriptiveName: id, actualName: id, pos: (x, y), + owner: owner, gmOnly: gmOnly, + flags: (if visionFlag: %*{"vision": true} else: %*{})) + +proc exploredCells(pv: PlayerVision, sc: SceneRec): int = pv.explored.len + +suite "polygons (5.1: one per controlled token with the `vision` flag)": + test "only the player's own vision tokens produce one, in token order": + let sc = sceneWith(@[]) + let tokens = @[tok("mine", 400, 400, 2), tok("noflag", 800, 800, 2, visionFlag = false), + tok("theirs", 1200, 1200, 3), tok("second", 1600, 1600, 2)] + let polys = computePolys(sc, tokens, 2) + check polys.len == 2 + check polys[0].tokenId == "mine" + check polys[1].tokenId == "second" + check polys[0].pts.len >= 3 + + test "a player with no vision token has no polygons at all": + let sc = sceneWith(@[]) + check computePolys(sc, @[tok("theirs", 100, 100, 3)], 2).len == 0 + check computePolys(sc, @[], 2).len == 0 + + test "the polygon is bounded by the token's range, and a closer wall cuts it": + let sc = sceneWith(@[wall(700, 0, 700, 4096)]) + let tokens = @[tok("me", 400, 400, 2)] + let free = computePolys(sceneWith(@[]), tokens, 2)[0].pts + # nothing reaches farther than the 400 px default radius (small tolerance for the 64-gon) + for p in free: check hypot(p.x - 400, p.y - 400) <= 401 + let cut = computePolys(sc, tokens, 2)[0].pts + for p in cut: check p.x <= 701 + check cut.anyIt(it.x > 690) # the wall is reached, not clipped short + + test "the token's own vision_radius overrides the scene default": + let sc = sceneWith(@[]) + var t = tok("me", 400, 400, 2) + t.visionRadius = some(120.0) + let pts = computePolys(sc, @[t], 2)[0].pts + for p in pts: check hypot(p.x - 400, p.y - 400) <= 121 + + test "an open door does not block; closing it does (5.1, 5.5)": + let closed = sceneWith(@[wall(700, 0, 700, 4096, wkDoor, open = false)]) + let open = sceneWith(@[wall(700, 0, 700, 4096, wkDoor, open = true)]) + let tokens = @[tok("me", 400, 400, 2)] + check computePolys(closed, tokens, 2)[0].pts.allIt(it.x <= 701) + check computePolys(open, tokens, 2)[0].pts.anyIt(it.x > 790) + +suite "explored (5.1, 8: strictly per player, only grows)": + test "the cells under the polygon are explored, and `fresh` reports them once": + let sc = sceneWith(@[]) + var pv: PlayerVision + pv.refresh(sc, @[tok("me", 400, 400, 2)], 2) + check pv.explored.len > 0 + check pv.fresh.len == pv.explored.len # first sight: everything is fresh + let first = pv.explored.len + pv.clearFresh() + check pv.fresh.len == 0 + pv.refresh(sc, @[tok("me", 400, 400, 2)], 2) # nothing moved + check pv.explored.len == first + check pv.fresh.len == 0 + + test "moving adds cells and never forgets the old ones": + let sc = sceneWith(@[]) + var pv: PlayerVision + pv.refresh(sc, @[tok("me", 400, 400, 2)], 2) + let first = pv.explored.len + pv.clearFresh() + pv.refresh(sc, @[tok("me", 1600, 1600, 2)], 2) + check pv.explored.len > first + check pv.fresh.len == pv.explored.len - first + # the old area stays explored even though it is no longer visible + let oldCell = sc.cellIndex(12, 12) + check oldCell in pv.explored + check not pv.insideAny((400.0, 400.0)) + + test "a closed door hides the cells behind it; opening it adds them": + var sc = sceneWith(@[wall(700, 0, 700, 4096, wkDoor, open = false)]) + var pv: PlayerVision + pv.refresh(sc, @[tok("me", 400, 400, 2)], 2) + let behind = sc.cellIndex(23, 12) # x ~ 750, past the closed door + check behind notin pv.explored + sc.walls[0].open = true + pv.clearFresh() + pv.refresh(sc, @[tok("me", 400, 400, 2)], 2) + check behind in pv.explored + check pv.fresh.len > 0 + + test "each player has their own set; nobody shares explored cells (Q9 FIXED)": + let sc = sceneWith(@[]) + var a, b: PlayerVision + a.refresh(sc, @[tok("a", 400, 400, 2), tok("b", 3000, 3000, 3)], 2) + b.refresh(sc, @[tok("a", 400, 400, 2), tok("b", 3000, 3000, 3)], 3) + check a.explored.len > 0 and b.explored.len > 0 + check sc.cellIndex(12, 12) in a.explored + check sc.cellIndex(12, 12) notin b.explored + check sc.cellIndex(93, 93) in b.explored + check sc.cellIndex(93, 93) notin a.explored + + test "the full payload is sorted by row and never contains a cell twice": + let sc = sceneWith(@[]) + var pv: PlayerVision + pv.refresh(sc, @[tok("me", 400, 400, 2)], 2) + let full = pv.exploredFull(sc) + check full.len == pv.explored.len + for i in 1 ..< full.len: + # sorted by row, then column: the RLE rows of 6.1 need contiguous columns per row + check (full[i - 1][1], full[i - 1][0]) < (full[i][1], full[i][0]) + for (cx, cy) in full: check sc.cellOf(sc.cellIndex(cx, cy)) == (cx, cy) + +suite "version counter (6.4: `vision` only on change)": + test "ver moves with the polygons and stands still without a change": + let sc = sceneWith(@[]) + var pv: PlayerVision + check pv.ver == 0 + pv.refresh(sc, @[tok("me", 400, 400, 2)], 2) + check pv.ver == 1 + pv.refresh(sc, @[tok("me", 400, 400, 2)], 2) + check pv.ver == 1 + pv.refresh(sc, @[tok("me", 401, 400, 2)], 2) + check pv.ver == 2 + pv.refresh(sc, @[], 2) # the token went away + check pv.ver == 3 + check pv.polys.len == 0 + +suite "token visibility (3.1)": + test "a controlled token is always visible, gm_only included": + let sc = sceneWith(@[]) + var pv: PlayerVision + pv.refresh(sc, @[tok("me", 400, 400, 2)], 2) + check pv.visibleTo(tok("me", 400, 400, 2), 2) + check pv.visibleTo(tok("hidden-own", 3000, 3000, 2, gmOnly = true), 2) + + test "another token needs to be inside the polygon": + let sc = sceneWith(@[wall(700, 0, 700, 4096)]) + var pv: PlayerVision + pv.refresh(sc, @[tok("me", 400, 400, 2)], 2) + check pv.visibleTo(tok("near", 600, 400, 3), 2) + check not pv.visibleTo(tok("behind", 900, 400, 3), 2) # past the wall + check not pv.visibleTo(tok("far", 3000, 3000, 3), 2) # beyond the range + + test "a gm_only token inside the LOS is not visible to anyone else": + let sc = sceneWith(@[]) + var pv: PlayerVision + pv.refresh(sc, @[tok("me", 400, 400, 2)], 2) + check not pv.visibleTo(tok("secret", 500, 500, 0, gmOnly = true), 2) + check pv.visibleTo(tok("plain", 500, 500, 0), 2) + + test "a player with no vision token sees only what they control": + let sc = sceneWith(@[]) + var pv: PlayerVision + pv.refresh(sc, @[tok("blind", 400, 400, 2, visionFlag = false)], 2) + check pv.polys.len == 0 + check pv.visibleTo(tok("blind", 400, 400, 2, visionFlag = false), 2) + check not pv.visibleTo(tok("nearby", 420, 420, 3), 2)