Files
FFF_vtt_frozen/server/moverules.nim
T
SirStone 38d8962f84 server: the status model, per-token radius and the grow push (#22)
moverules.nim replaces the M2 `blocked` bool with the 5.5 status model: the
rules own the `walls` source (`stuckWalls`, `squeezedWalls`) and take
`locked` (any entry, any source) as input, so a GM-sourced lock refuses a
player move without the rules ever knowing what caused it. Identity is kept
on KEEP, cleared on CLEAR, and only tokens the event touches change.

Every geometry path now uses the token's own radius (5.6): the overlap test,
the escape check, the capsule, the door push and the step cap's neighbour
rules. `resizeToken` implements 5.6: a shrink never pushes and clears the
walls entries only when the overlap ends, a grow that overlaps is displaced
by a deterministic greedy relaxation (radial off the first overlapped wall,
scene order, at most 16 rounds, one flipped-side pass) and a grow that cannot
be placed stays put and becomes squeezed(walls). A step whose centre path
would cross a wall ends the pass, so the relaxation never carries a token
through a wall.

worldmap.nim is the bridge: `ruleToken`/`ruleWall`/`moveScene` build the
rules' input from the records, `applyOutcome` copies the position, the
door-push history and the walls-sourced entries back, and `wallsStatuses`
does the same for a caller that writes its own row. All of them return fresh
sequences instead of mutating a shared one.
2026-11-15 11:02:29 +01:00

386 lines
19 KiB
Nim

## Move rules and the status model (DESIGN 5.5, 5.6). Pure and in-process: plain data in, plain data
## out, no IO, no clock. The WebSocket layer (M3) only maps `MoveResult` to `moveAck` and copies the
## outcome back into its records; nothing here knows about the wire or the database.
##
## Player move s -> d (checks in order, any failure = the same nack):
## 1. owner (else mkError, never an ack: an ack would echo an unseen position) and token not locked;
## 2. in bounds, and |d - s| <= stepCap (token vision radius if it has vision and sets one, else scene default);
## 3. per blocking wall W: start overlapping W (dist(s,W) < r, "escape"): allowed iff the path does not cross W
## farther than EscapeEps from s AND dist(d,W) >= r; otherwise swept circle: allowed iff dist(seg s->d, W) >= r.
## GM move: bounds only (no walls, no cap, ignores locks), then the placement rule (`placeToken`).
##
## Status model (DESIGN 5.5, FIXED #4 and 2026-11-14): a token holds `(status, source)` entries. This
## module owns the `walls` source only, as two booleans per token: `stuckWalls` and `squeezedWalls`.
## The caller owns the `GM` source (tokens.TokenRec.statuses) and tells this module whether the token
## is locked at all (`locked`, any entry, any source) - that is the only thing a player move needs.
## SET stuck(walls): a wall is added or updated over the token; the GM places or moves a token
## overlapping a blocking wall. squeezed(walls): a door close or a grow push fails.
## KEEP while ANY blocking wall still overlaps the token, its walls-sourced entries stay (opening
## a door does not free it if another wall overlaps). Identity is kept: a squeezed token
## stays squeezed, a stuck one stays stuck.
## CLEAR a wall is removed or a door opened and no blocking wall overlaps any more; a shrink ends
## the overlap; the GM moves the token to a position overlapping no blocking wall; or the GM
## clears the entry by hand (the caller removes it from the token, no rule runs here).
## Only tokens touched by the event change; an unrelated wall change never re-sets a GM-cleared token.
##
## Door closing on a token = PUSH, not stuck (owner 2026-11-08): each token with dist(centre, door) < r
## moves perpendicular to the door, to the side its centre is on, by the minimal distance that ends
## >= r (+ PushEps); if the projection falls past the door's end the perpendicular offset is
## sqrt(r^2 - e^2), e = along-axis overshoot. Centre exactly on the door line (|side| <= Eps): side of
## `prev`; no history or prev also on the line: the left side of a->b. Valid = in bounds and >= r from
## EVERY blocking wall; else try the opposite side; neither valid -> the token stays and gets
## squeezed(walls); opening that door later clears it per the CLEAR rule. A pushed token is clear of
## walls, so its walls-sourced entries clear. Pushes are returned (Push list), no step cap. Each token
## is pushed independently; tokens never block tokens (no token-token collision; `blocks_move` is not
## modelled), so pushed tokens may end overlapping each other.
##
## Grow push (DESIGN 5.6, FIXED #4): growing a token that overlaps a blocking wall displaces it by
## the displacement this module finds; shrinking never pushes. The search is a deterministic greedy
## relaxation and is pinned by tests:
## 1. Repeat at most MaxPushRounds (16) times: take the first blocking wall the token's circle
## overlaps, in scene order, and move the centre radially away from that wall's closest point by
## exactly the distance that ends at r + PushEps from it. A centre exactly on a wall (|v| <= Eps)
## uses the wall's normal on the side of `prev`, or the left normal of a->b with no history, and
## each side is tried in that order.
## 2. Stop as soon as no blocking wall is within r and the centre is in bounds. A step whose own
## centre path (radius 0) would cross a blocking wall ends the pass instead of being taken, so the
## relaxation never carries a token through a wall: a corridor narrower than the grown token
## squeezes rather than teleports.
## 3. If a pass does not end clear (a crossing, an out-of-bounds end, or 16 rounds without settling)
## the second pass starts by flipping the direction off the first overlapping wall; if neither
## pass ends clear, the grow fails: the token stays where it was and becomes squeezed(walls).
## The displacement is minimal for one wall and close to minimal in a corner; "minimal" is the
## owner's word, the exact search is ours (recorded FIXED owner-delegated, #22, in DESIGN 5.6).
##
## Thresholds (px unless noted):
## EscapeEps = 1e-6: a crossing this close to the start is "the token stands on the wall", not a crossing. A token
## within 1e-6 of a wall can only exist via GM placement/edit (a player move keeps dist >= r), so this cannot be
## used to tunnel; 1e-6 is far below one pixel and far above float noise at world scale (|coords| < 1e5, ~1e-11).
## geometry.Eps = 1e-9 (parallel/collinear/touch tolerance, shared with the vision code).
## PushEps = 1e-6: extra clearance so float noise never leaves a pushed token at dist < r.
## ResizeEps = 1e-9: a radius change this small is no change (a grow of 0 must not push).
## Interpretation notes: removing/opening affects only a BLOCKING wall (removing an open door changes nothing).
## removeWall shifts later wall indices down (dense ids); M3 owns id stability.
## Escape corner case (spec-normative): an escaping token may graze closer to W than it started, mid-path; only
## crossing and the destination are checked. Moving along the wall's own line counts as crossing.
## Not checked here: path crossing a wall W2 whose capsule distance is >= r is fine by definition.
import std/math
import geometry
const
EscapeEps* = 1e-6
NoOwner* = -1
PushEps* = 1e-6
ResizeEps* = 1e-9
MaxPushRounds* = 16
type
Role* = enum rolePlayer, roleGM
Actor* = object
role*: Role
player*: int # player id, meaningful for rolePlayer
Token* = object
pos*: Vec
owner*: int # player id or NoOwner (GM-controlled)
radius*: float # effective px, always > 0 (tokens.effectiveRadius, 5.6)
hasVision*: bool # `vision` flag
visionRadius*: float # <= 0: unset, use the scene default
locked*: bool # any (status, source) entry: the player cannot move it (5.5)
stuckWalls*: bool # walls-sourced `stuck`
squeezedWalls*: bool # walls-sourced `squeezed`
prev*: Vec # position before the most recent move/push (valid iff hasPrev); decides the door-push side
hasPrev*: bool
Push* = object # server-originated position change (M3: broadcast + recompute vision)
ti*: int
pos*: Vec
Scene* = object
w*, h*: float
visionDefault*: float
walls*: seq[Wall]
tokens*: seq[Token]
MoveKind* = enum mkAck, mkNack, mkError
MoveResult* = object
kind*: MoveKind
pos*: Vec # mkAck: destination; mkNack: the old position; mkError: (0,0), must not be sent
ResizeKind* = enum
rkUnchanged # no displacement: a shrink, a grow that already fits, or a radius that did not change
rkPushed # the grow pushed the token clear (new position applied)
rkSqueezed # the grow had no valid position: the token stays and gets squeezed(walls)
proc dot(a, b: Vec): float = a.x * b.x + a.y * b.y
proc segSegDist*(p, q, a, b: Vec): float =
## distance between segments pq and ab (0 if they touch or cross)
if segsCross(p, q, a, b): return 0.0
min(min(segDist(p, a, b), segDist(q, a, b)), min(segDist(a, p, q), segDist(b, p, q)))
proc pathCrosses*(s, d, a, b: Vec): bool =
## does the path s->d meet segment ab at a point farther than EscapeEps from s? Collinear overlap beyond that counts.
let m = d - s
let len = hypot(m.x, m.y)
if len <= EscapeEps: return false
let e = b - a
let le = hypot(e.x, e.y)
let sa = a - s
if le < Eps: # degenerate wall = a point
return segDist(a, s, d) < Eps and hypot(sa.x, sa.y) > EscapeEps
let den = cross(m, e)
if abs(den) <= 1e-12 * len * le: # parallel
if abs(cross(sa, e)) / le > Eps: return false # offset parallel
let ta = dot(sa, m) / len
let tb = dot(b - s, m) / len
return max(ta, tb) > EscapeEps and min(ta, tb) <= len
let t = cross(sa, e) / den # fraction along s->d
let u = cross(sa, m) / den # fraction along ab
t * len > EscapeEps and t <= 1 + Eps / len and u >= -Eps / le and u <= 1 + Eps / le
proc pathClear*(walls: openArray[Wall], s, d: Vec, r: float): bool =
## DESIGN 5.5 step 3 for a player move (no owner/cap checks)
let (bx0, bx1) = (min(s.x, d.x) - r, max(s.x, d.x) + r)
let (by0, by1) = (min(s.y, d.y) - r, max(s.y, d.y) + r)
for w in walls:
if not w.blocks: continue
# a wall whose bbox misses the capsule bbox can neither be within r of the path nor of s
if max(w.a.x, w.b.x) < bx0 or min(w.a.x, w.b.x) > bx1 or
max(w.a.y, w.b.y) < by0 or min(w.a.y, w.b.y) > by1: continue
if segDist(s, w.a, w.b) < r:
if pathCrosses(s, d, w.a, w.b) or segDist(d, w.a, w.b) < r: return false
elif segsCross(s, d, w.a, w.b) or segSegDist(s, d, w.a, w.b) < r: return false
true
proc stepCap*(sc: Scene, t: Token): float =
if t.hasVision and t.visionRadius > 0: t.visionRadius else: sc.visionDefault
proc inBounds(sc: Scene, p: Vec): bool = # written so NaN fails
p.x >= 0 and p.y >= 0 and p.x <= sc.w and p.y <= sc.h
proc overlaps*(sc: Scene, t: Token, w: Wall): bool =
## DESIGN 5.5 overlap: dist(centre, W) < r (strict; touching at exactly r is clear).
segDist(t.pos, w.a, w.b) < t.radius
proc overlapsAny*(sc: Scene, t: Token): bool =
for w in sc.walls:
if w.blocks and overlaps(sc, t, w): return true
proc clearWalls*(t: var Token) =
t.stuckWalls = false
t.squeezedWalls = false
proc nack(s: Vec): MoveResult = MoveResult(kind: mkNack, pos: s)
# ---- placement and the walls-sourced status bookkeeping ------------------------------------------
proc placeToken*(sc: var Scene, ti: int) =
## GM placement or GM move: no wall check, but the resulting position decides `stuck(walls)`.
## A move to a free spot clears every walls-sourced entry (5.5 CLEAR).
if ti < 0 or ti >= sc.tokens.len: return
sc.tokens[ti].clearWalls()
if overlapsAny(sc, sc.tokens[ti]): sc.tokens[ti].stuckWalls = true
proc applyAdded(sc: var Scene, w: Wall) =
if w.blocks:
for i in 0 ..< sc.tokens.len:
if overlaps(sc, sc.tokens[i], w): sc.tokens[i].stuckWalls = true
proc applyRemoved(sc: var Scene, w: Wall) =
if w.blocks:
for i in 0 ..< sc.tokens.len:
if overlaps(sc, sc.tokens[i], w):
# KEEP while any remaining blocking wall overlaps; otherwise CLEAR this token's walls entries
if not overlapsAny(sc, sc.tokens[i]): sc.tokens[i].clearWalls()
proc addWall*(sc: var Scene, w: Wall): int =
sc.walls.add w
applyAdded(sc, w)
sc.walls.high
proc removeWall*(sc: var Scene, id: int): bool =
if id < 0 or id >= sc.walls.len: return false
let w = sc.walls[id]
sc.walls.delete id
applyRemoved(sc, w)
true
proc updateWall*(sc: var Scene, id: int, w: Wall): bool =
## remove then add, id kept
if id < 0 or id >= sc.walls.len: return false
let old = sc.walls[id]
sc.walls[id] = w
applyRemoved(sc, old) # remaining set includes the new wall; applyAdded then covers tokens only the new wall touches
applyAdded(sc, w)
true
proc moveToken*(sc: var Scene, who: Actor, ti: int, d: Vec): MoveResult =
## validates and, on mkAck, applies the move. mkNack / mkError mutate nothing.
if ti < 0 or ti >= sc.tokens.len: return MoveResult(kind: mkError)
let s = sc.tokens[ti].pos
case who.role
of roleGM:
if not inBounds(sc, d): return nack(s)
of rolePlayer:
if sc.tokens[ti].owner != who.player: return MoveResult(kind: mkError)
# Locked = any status entry, whatever its source (5.5): the player's move is refused.
if sc.tokens[ti].locked or sc.tokens[ti].stuckWalls or sc.tokens[ti].squeezedWalls or
not inBounds(sc, d): return nack(s)
let dd = d - s
if hypot(dd.x, dd.y) > stepCap(sc, sc.tokens[ti]): return nack(s)
if not pathClear(sc.walls, s, d, sc.tokens[ti].radius): return nack(s)
sc.tokens[ti].prev = s; sc.tokens[ti].hasPrev = true
sc.tokens[ti].pos = d
if who.role == roleGM: sc.placeToken(ti)
MoveResult(kind: mkAck, pos: d)
proc addToken*(sc: var Scene, t: Token): int =
## GM placement: ignores walls; the walls-sourced status follows from the position (5.5 SET).
sc.tokens.add t
sc.placeToken(sc.tokens.high)
sc.tokens.high
proc gmClearBlocked*(sc: var Scene, ti: int) =
## The GM clears the walls-sourced entries by hand (5.5 CLEAR): the escape rule then applies again.
if ti >= 0 and ti < sc.tokens.len: sc.tokens[ti].clearWalls()
# ---- door closing: push aside ----------------------------------------------------------------
proc pushFrom(sc: Scene, t: Token, w: Wall): tuple[ok: bool, pos: Vec] =
## door-close push of t off w (see header); ok=false if neither side is valid
let e = w.b - w.a
let le = hypot(e.x, e.y)
let r = t.radius
var n: Vec = (0.0, 1.0) # degenerate door (a point): push along +y
var along = 0.0 # projection of the centre on the door axis, from a
var side = 1.0
if le >= Eps:
n = (-e.y / le, e.x / le) # left normal of a->b
along = dot(t.pos - w.a, e) / le
side = dot(t.pos - w.a, n)
if abs(side) <= Eps:
side = if t.hasPrev: dot(t.prev - w.a, n) else: 0.0
if abs(side) <= Eps: side = 1.0
let over = if along < 0: -along elif along > le: along - le else: 0.0
let perp = sqrt(max(0.0, r * r - over * over)) + PushEps
let foot: Vec = if le >= Eps: (w.a.x + e.x * along / le, w.a.y + e.y * along / le) else: w.a
for sg in [(if side > 0: 1.0 else: -1.0), (if side > 0: -1.0 else: 1.0)]:
let p: Vec = (foot.x + n.x * sg * perp, foot.y + n.y * sg * perp)
var tt = t
tt.pos = p
if inBounds(sc, p) and not overlapsAny(sc, tt): return (true, p)
(false, t.pos)
proc setDoor*(sc: var Scene, id: int, open: bool, pushed: var seq[Push]): bool =
## false if `id` is not a door. Closing pushes overlapped tokens aside (appended to `pushed`; those with no valid
## spot become squeezed(walls)); opening re-evaluates the walls-sourced entries per CLEAR.
if id < 0 or id >= sc.walls.len or not sc.walls[id].door: return false
if sc.walls[id].open == open: return true
if open:
let closed = sc.walls[id] # it blocked until now
sc.walls[id].open = true
applyRemoved(sc, closed)
else:
sc.walls[id].open = false
let w = sc.walls[id]
for i in 0 ..< sc.tokens.len:
if not overlaps(sc, sc.tokens[i], w): continue
let (ok, p) = pushFrom(sc, sc.tokens[i], w)
if ok:
sc.tokens[i].prev = sc.tokens[i].pos; sc.tokens[i].hasPrev = true
sc.tokens[i].pos = p
sc.tokens[i].clearWalls() # a pushed token is clear of every blocking wall
pushed.add Push(ti: i, pos: p)
else:
sc.tokens[i].squeezedWalls = true
true
proc setDoor*(sc: var Scene, id: int, open: bool): bool =
var ignored: seq[Push]
setDoor(sc, id, open, ignored)
# ---- resizing: shrink never pushes, grow pushes or squeezes -------------------------------------
proc clearOfWalls(sc: Scene, pos: Vec, r: float): bool =
## A position the whole circle fits in: in bounds and >= r from every blocking wall (5.6).
if not inBounds(sc, pos): return false
for w in sc.walls:
if w.blocks and segDist(pos, w.a, w.b) < r: return false
true
proc closestPoint(p, a, b: Vec): Vec =
## The point of segment ab closest to p (geometry.segDist's own projection, kept explicit so the
## push direction is derived from the same quantity the overlap test uses).
let e = b - a
let le2 = e.x * e.x + e.y * e.y
if le2 < Eps * Eps: return a
let t = min(1.0, max(0.0, dot(p - a, e) / le2))
(a.x + e.x * t, a.y + e.y * t)
proc awayFrom(t: Token, w: Wall, flip: bool): Vec =
## The unit displacement direction off wall w: radially away from its closest point. A centre
## exactly on the wall has no radial direction, so the wall normal decides, on the side of `prev`
## (no history: the left normal of a->b). `flip` asks for the other side (the second pass).
let cp = closestPoint(t.pos, w.a, w.b)
var u: Vec = (t.pos.x - cp.x, t.pos.y - cp.y)
let l = hypot(u.x, u.y)
if l > Eps:
u = (u.x / l, u.y / l)
else:
let e = w.b - w.a
let le = hypot(e.x, e.y)
var n: Vec = (0.0, 1.0)
if le >= Eps: n = (-e.y / le, e.x / le)
var side = if t.hasPrev: dot(t.prev - w.a, n) else: 0.0
if abs(side) <= Eps: side = 1.0
u = if side > 0: n else: (-n.x, -n.y)
if flip: u = (-u.x, -u.y)
u
proc pushOutOfWalls(sc: Scene, t: Token, flipFirst: bool): tuple[ok: bool, pos: Vec] =
## The greedy relaxation of the module header, one pass: at most MaxPushRounds walls, each move the
## exact distance that ends r from the first blocking wall the circle overlaps (scene order). A step
## whose own path (the centre, no radius) crosses a blocking wall is refused: the relaxation must
## not carry a token through a wall, so a corridor narrower than the token squeezes instead.
var cur = t
var flip = flipFirst
for _ in 0 ..< MaxPushRounds:
var hit = -1
for i, w in sc.walls:
if w.blocks and segDist(cur.pos, w.a, w.b) < cur.radius:
hit = i
break
if hit < 0:
if inBounds(sc, cur.pos): return (true, cur.pos)
return (false, t.pos)
let w = sc.walls[hit]
let u = awayFrom(cur, w, flip)
flip = false
let need = cur.radius + PushEps - segDist(cur.pos, w.a, w.b)
let next: Vec = (cur.pos.x + u.x * need, cur.pos.y + u.y * need)
if not pathClear(sc.walls, cur.pos, next, 0.0): return (false, t.pos)
cur.pos = next
if clearOfWalls(sc, cur.pos, cur.radius): return (true, cur.pos)
(false, t.pos)
proc resizeToken*(sc: var Scene, ti: int, radius: float): ResizeKind =
## `token.resize` (5.6): shrink never pushes and may clear walls-sourced entries; grow pushes the
## token clear of every blocking wall it overlaps, else the token stays and gets squeezed(walls).
## The caller has already written the new radius; this applies only the position and status effects.
if ti < 0 or ti >= sc.tokens.len: return rkUnchanged
let old = sc.tokens[ti].radius
let grew = radius > old + ResizeEps
sc.tokens[ti].radius = radius
if not overlapsAny(sc, sc.tokens[ti]):
sc.tokens[ti].clearWalls()
return rkUnchanged
if not grew:
# a shrink that still overlaps keeps the walls entries (CLEAR needs the overlap to end)
return rkUnchanged
for flipFirst in [false, true]:
let (ok, p) = pushOutOfWalls(sc, sc.tokens[ti], flipFirst)
if ok:
sc.tokens[ti].prev = sc.tokens[ti].pos
sc.tokens[ti].hasPrev = true
sc.tokens[ti].pos = p
sc.tokens[ti].clearWalls()
return rkPushed
sc.tokens[ti].squeezedWalls = true
rkSqueezed