server: typed recipient views and the single egress (#20)

server/views.nim is the only place where world state becomes bytes: a Recipient
builds a GmTokenView or a PlayerTokenView first, and only then a frame. Player
frames carry the public props bucket (plus owner for the controller), the
controller's vision_radius, and never kind, controller, gm_only, flags, radius_own
or either raw name; the GM gets all of it plus both names. The per-connection Known
table diffs on the built frame, so token/token_gone are exactly the changes and the
vision frame is re-sent only when the polygons move.

server/faults.nim compiles the negative-control hook only with -d:leakfault; the
shipped binary contains no LEAK_FAULT string and tools/fault.test.mjs asserts it.

hello gains the scene block (and extra for the GM); the protocol's implemented set
now names the four token intents.
This commit is contained in:
2026-11-15 09:35:14 +01:00
parent e6b53e06f5
commit 5f5bf3293b
5 changed files with 542 additions and 8 deletions
+14
View File
@@ -0,0 +1,14 @@
## Test-only fault injection for the negative controls of the leak harness (DESIGN 10.1, 10.3).
## The hook is compiled in only with `-d:leakfault`, and every fault checks
## `LEAK_FAULT=<name>` from the environment: a normal build cannot fault, it contains no `LEAK_FAULT`
## string, and tools/fault.test.mjs asserts that the shipped binary's bytes lack it.
when defined(leakfault):
import std/os
proc faultActive*(name: string): bool =
## True only in a `-d:leakfault` build whose LEAK_FAULT equals `name`. Without the define this is
## the constant false, so the shipped server has no fault path at all.
when defined(leakfault):
getEnv("LEAK_FAULT") == name
else:
false
+11 -6
View File
@@ -81,9 +81,11 @@ const
] ]
ImplementedIntents* = ["conn.ping", "act.do", "key.create", "key.replace", "player.remove", ImplementedIntents* = ["conn.ping", "act.do", "key.create", "key.replace", "player.remove",
"wall.add", "wall.update", "wall.remove", "door.set"] "wall.add", "wall.update", "wall.remove", "door.set",
## What the built slices actually handle (slice 3 #18 plus slice 4 #19's walls and doors). "token.create", "token.update", "token.move", "token.remove"]
## The rest of the catalogue answers `unknown-type` until its slice lands (DESIGN 6.1 note). ## What the built slices actually handle (slice 3 #18, slice 4 #19's walls and doors, slice 5
## #20's tokens and sight). The rest of the catalogue answers `unknown-type` until its slice
## lands (DESIGN 6.1 note).
type type
Envelope* = object Envelope* = object
@@ -148,13 +150,16 @@ proc withN*(node: JsonNode, n: int): JsonNode =
result = node result = node
result["n"] = %n result["n"] = %n
proc helloFrame*(proto, n: int, role: string, playerId: int, name: JsonNode): JsonNode = proc helloFrame*(proto, n: int, role: string, playerId: int, name: JsonNode,
## DESIGN 6.1 `hello`. The `scene` block and the world fields arrive with slice 5; M3 slice 3 scene: JsonNode = nil, extra: JsonNode = nil): JsonNode =
## sends what exists: proto, role, me. ## DESIGN 6.1 `hello`. `scene` is the scene block (views.sceneBlock) and `extra` the scene's free
## object (GM only); both are absent for an unnamed player, which gets `proto, role, me` only.
var me = newJObject() var me = newJObject()
me["id"] = %playerId me["id"] = %playerId
me["name"] = name # null while the player has no name yet me["name"] = name # null while the player has no name yet
result = %*{"t": "hello", "proto": proto, "role": role, "me": me, "n": n} result = %*{"t": "hello", "proto": proto, "role": role, "me": me, "n": n}
if not scene.isNil: result["scene"] = scene
if not extra.isNil: result["extra"] = extra
proc ackFrame*(reqId, n: int, extra: JsonNode = nil): JsonNode = proc ackFrame*(reqId, n: int, extra: JsonNode = nil): JsonNode =
## `ack {reqId, ok:true, ...result fields}`; `extra` holds `id`, `key`, `pos`, `ts`. ## `ack {reqId, ok:true, ...result fields}`; `extra` holds `id`, `key`, `pos`, `ts`.
+276
View File
@@ -0,0 +1,276 @@
## The egress module: the one place where authoritative world state becomes bytes for a recipient
## (DESIGN 2 single egress rule, 3.1, 6.1, 6.3, 6.4; M3 slice 5, issue #20).
##
## A recipient is either the GM or one player, and the module builds a *typed* view for that
## recipient first (`GmView`, `PlayerView`) and only then turns it into frames. Raw world state never
## becomes JSON anywhere else: `main.nim` does not build a `token`, `token_gone`, `vision` or
## `explored` frame, and the record it holds (`TokenRec`) has no serializer.
##
## Rules encoded here (3.1):
## - GM: every token, all buckets, `statuses[].source`, controller/gm_only/flags/vision_radius and
## both names. No `vision`, no `explored` ever.
## - player: tokens they control (always) plus tokens inside their LOS that are not `gm_only`;
## `props` carries only the buckets they may read (public, plus owner for the controller);
## `vision_radius` only for the controller (it is the step cap, 5.5); `source` never.
## - a token's `name` is the descriptive name in this slice: the reveal machinery is slice 8 (#23),
## so no actual name has an egress path to a player at all.
##
## `Known` is the per-connection diff table (4.1/6.4): it holds the last frame sent for each token, so
## `token_gone` is sent only for a token this recipient did see, never for one it never knew. The
## comparison is on the built frame, so a coalesced state (M5) cannot desynchronise a client.
import std/[algorithm, json, math, options, sequtils, sets, tables]
import geometry, tokens, vision, world
import faults
type
Recipient* = object
isGm*: bool
playerId*: int
GmTokenView* = object
id*: string
scene*: int
name*: string
pos*: Vec
radius*: float
kind*: string
controller*: int
gmOnly*: bool
flags*: JsonNode
visionRadius*: Option[float]
radiusOwn*: Option[float]
descriptiveName*, actualName*: string
PlayerTokenView* = object
id*: string
scene*: int
name*: string
pos*: Vec
radius*: float
mine*: bool
includeVisionRadius*: bool
visionRadius*: Option[float]
GmView* = object
tokens*: seq[GmTokenView]
PlayerView* = object
tokens*: seq[PlayerTokenView]
polys*: seq[Poly]
fresh*: seq[(int, int)]
Context* = object
## Everything the egress needs, and nothing it may modify: the world plus every player's runtime
## sight state (read-only; the other players' entries are only reachable by a fault build).
scene*: SceneRec
tokens*: seq[TokenRec]
visions*: Table[int, PlayerVision]
Known* = object
## Per connection: what this recipient already has (4.1 `known`).
tokens*: Table[string, JsonNode]
vision*: string ## the last `vision` payload sent, "" = never
visionSent*: bool
# ---------------------------------------------------------------------------------------------------
# Typed views
proc gmView*(ctx: Context): GmView =
result.tokens = newSeqOfCap[GmTokenView](ctx.tokens.len)
for t in ctx.tokens:
result.tokens.add GmTokenView(id: t.id, scene: t.scene,
name: t.descriptiveName,
pos: t.pos, radius: effectiveRadius(ctx.scene, t),
kind: t.kind, controller: t.owner, gmOnly: t.gmOnly,
flags: t.flags, visionRadius: t.visionRadius,
radiusOwn: t.radius,
descriptiveName: t.descriptiveName,
actualName: t.actualName)
proc playerView*(ctx: Context, playerId: int): PlayerView =
var pv = ctx.visions.getOrDefault(playerId)
for t in ctx.tokens:
if not pv.visibleTo(t, playerId): continue
result.tokens.add PlayerTokenView(id: t.id, scene: t.scene,
name: t.descriptiveName, pos: t.pos,
radius: effectiveRadius(ctx.scene, t),
mine: t.owner == playerId,
includeVisionRadius: t.owner == playerId,
visionRadius: t.visionRadius)
when defined(leakfault):
# Negative controls (DESIGN 10.3): add the tokens the honest rule just refused, so the harness
# proves it would notice. Never a second copy of the visibility rule.
if faultActive("hidden"):
for t in ctx.tokens:
if t.owner != playerId and not t.gmOnly and not pv.insideAny(t.pos):
result.tokens.add PlayerTokenView(id: t.id, scene: t.scene, name: t.descriptiveName,
pos: t.pos, radius: effectiveRadius(ctx.scene, t),
mine: false, includeVisionRadius: false,
visionRadius: t.visionRadius)
if faultActive("gmOnly"):
for t in ctx.tokens:
if t.gmOnly and t.owner != playerId and pv.insideAny(t.pos):
result.tokens.add PlayerTokenView(id: t.id, scene: t.scene, name: t.descriptiveName,
pos: t.pos, radius: effectiveRadius(ctx.scene, t),
mine: false, includeVisionRadius: false,
visionRadius: t.visionRadius)
if faultActive("withhold") and result.tokens.len > 1:
for i in countdown(result.tokens.high, 0):
if not result.tokens[i].mine:
result.tokens.delete i
break
if faultActive("otherOwner"):
for t in result.tokens.mitems:
if not t.mine: t.mine = true; break
result.polys = pv.polys
result.fresh = pv.fresh
# ---------------------------------------------------------------------------------------------------
# Frames. These builders are the only producers of state frames in the server.
proc gmTokenFrame*(v: GmTokenView): JsonNode =
result = %*{
"t": "token", "id": v.id, "scene": v.scene, "name": v.name,
"pos": [v.pos.x, v.pos.y], "radius": v.radius, "mine": false,
"statuses": [], "props": {"public": newJObject(), "owner": newJObject(), "gm": newJObject()},
"kind": v.kind, "controller": (if v.controller == GmControlled: newJNull() else: %v.controller),
"gm_only": v.gmOnly, "flags": v.flags,
"vision_radius": (if v.visionRadius.isSome: %v.visionRadius.get else: newJNull()),
"radius_own": (if v.radiusOwn.isSome: %v.radiusOwn.get else: newJNull()),
"descriptive_name": v.descriptiveName, "actual_name": v.actualName
}
proc playerTokenFrame*(v: PlayerTokenView): JsonNode =
## One token as a player may see it. `statuses` carries no `source` (3.1: the cause is GM-only);
## `props` carries the `public` bucket, plus `owner` for the controller (6.1).
var props = newJObject()
props["public"] = newJObject()
if v.mine: props["owner"] = newJObject()
result = %*{
"t": "token", "id": v.id, "scene": v.scene, "name": v.name,
"pos": [v.pos.x, v.pos.y], "radius": v.radius, "mine": v.mine,
"statuses": [], "props": props
}
if v.includeVisionRadius:
result["vision_radius"] = if v.visionRadius.isSome: %v.visionRadius.get else: newJNull()
proc tokenGoneFrame*(id: string): JsonNode = %*{"t": "token_gone", "id": id}
proc visionPolyJson(polys: seq[Poly]): JsonNode =
## Integer px (DESIGN 6.4 FIXED Q16): halves the payload size; 0.5 px is the documented tolerance.
result = newJArray()
for p in polys:
var pts = newJArray()
for q in p.pts: pts.add %*[int(round(q.x)), int(round(q.y))]
result.add %*{"id": p.tokenId, "pts": pts}
proc visionFrame*(polys: seq[Poly]): JsonNode =
%*{"t": "vision", "polys": visionPolyJson(polys)}
proc exploredFullFrame*(cells: seq[(int, int)]): JsonNode =
## RLE rows: `[[cy, x0, len, x0, len, ...], ...]` (DESIGN 6.1, format PROPOSED accepted here).
var rows: seq[tuple[cy: int, runs: JsonNode]]
var i = 0
while i < cells.len:
let cy = cells[i][1]
var runs = newJArray()
var j = i
while j < cells.len and cells[j][1] == cy:
let start = cells[j][0]
var last = start
while j + 1 < cells.len and cells[j + 1][1] == cy and cells[j + 1][0] == last + 1:
inc j
last = cells[j][0]
runs.add %start
runs.add %(last - start + 1)
inc j
rows.add (cy: cy, runs: runs)
i = j
var rle = newJArray()
for row in rows:
var entry = newJArray()
entry.add %row.cy
for v in row.runs: entry.add v
rle.add entry
%*{"t": "explored", "full": true, "rle": rle}
proc exploredFreshFrame*(cells: seq[(int, int)]): JsonNode =
var list = newJArray()
for (cx, cy) in cells: list.add %*[cx, cy]
%*{"t": "explored", "full": false, "cells": list}
proc sceneBlock*(sc: SceneRec): JsonNode =
## The `scene` object inside `hello` (DESIGN 6.1, 3.1: no counts, no wall data, no owned ids).
%*{"id": sc.id, "name": sc.name, "w": sc.w, "h": sc.h, "tile_size": sc.tileSize,
"cell": sc.cell, "grid_size": sc.gridSize,
"vision_radius_default": sc.visionRadiusDefault,
"token_radius_default": sc.tokenRadiusDefault, "art_version": sc.artVersion}
# ---------------------------------------------------------------------------------------------------
# Egress: the frames one recipient needs after a mutation (or a full resync)
proc otherPlayerId(ctx: Context, me: int): int =
## A deterministic "somebody else" for the negative controls: the smallest other player id.
result = 0
for id in ctx.visions.keys:
if id != me and (result == 0 or id < result): result = id
proc egressFrames*(r: Recipient, ctx: Context, known: var Known, resync = false): seq[JsonNode] =
## Ordered like the 6.3 resync sequence: vision, explored, then the tokens. Empty = nothing changed
## for this recipient, which is what keeps hidden mutations invisible (T11).
if r.isGm:
let view = gmView(ctx)
var seen = initHashSet[string]()
for v in view.tokens:
seen.incl v.id
let frame = gmTokenFrame(v)
if known.tokens.getOrDefault(v.id) != frame:
known.tokens[v.id] = frame
result.add frame
for id in known.tokens.keys.toSeq:
if id notin seen:
known.tokens.del id
result.add tokenGoneFrame(id)
return
let view = playerView(ctx, r.playerId)
var polysJson = visionPolyJson(view.polys)
when defined(leakfault):
if faultActive("otherVision"):
let other = ctx.visions.getOrDefault(ctx.otherPlayerId(r.playerId))
for p in other.polys:
var pts = newJArray()
for q in p.pts: pts.add %*[int(round(q.x)), int(round(q.y))]
polysJson.add %*{"id": p.tokenId, "pts": pts}
if resync or not known.visionSent or $polysJson != known.vision:
known.vision = $polysJson
known.visionSent = true
result.add %*{"t": "vision", "polys": polysJson}
if resync:
result.add exploredFullFrame(ctx.visions.getOrDefault(r.playerId).exploredFull(ctx.scene))
elif view.fresh.len > 0:
var fresh = view.fresh
when defined(leakfault):
if faultActive("explored"):
fresh.add (ctx.scene.cols - 1, ctx.scene.rows - 1)
if faultActive("otherExplored"):
let other = ctx.visions.getOrDefault(ctx.otherPlayerId(r.playerId))
fresh.add other.exploredFull(ctx.scene)
result.add exploredFreshFrame(fresh)
var seen = initHashSet[string]()
for v in view.tokens:
seen.incl v.id
let frame = playerTokenFrame(v)
if known.tokens.getOrDefault(v.id) != frame:
known.tokens[v.id] = frame
result.add frame
var gone: seq[string]
for id in known.tokens.keys:
if id notin seen: gone.add id
gone.sort()
for id in gone:
known.tokens.del id
if not faultActive("noremove"):
result.add tokenGoneFrame(id)
+16 -2
View File
@@ -40,7 +40,7 @@ suite "envelope (6.5 step 2)":
test "the catalogue is the 29 intents of 6.1 and the built set is a subset": test "the catalogue is the 29 intents of 6.1 and the built set is a subset":
check IntentCatalogue.len == 29 check IntentCatalogue.len == 29
check ImplementedIntents.len == 9 # slice 3's five + slice 4's four wall intents check ImplementedIntents.len == 13 # slice 3's five + slice 4's four walls + slice 5's four token intents
for t in ImplementedIntents: for t in ImplementedIntents:
check t in IntentCatalogue check t in IntentCatalogue
check isCatalogueIntent(t) check isCatalogueIntent(t)
@@ -61,9 +61,13 @@ suite "envelope (6.5 step 2)":
for t in ["wall.add", "wall.update", "wall.remove", "door.set"]: for t in ["wall.add", "wall.update", "wall.remove", "door.set"]:
check isImplementedIntent(t) check isImplementedIntent(t)
check isGmOnlyIntent(t) # walls are GM-only (3.1, T2) check isGmOnlyIntent(t) # walls are GM-only (3.1, T2)
for t in ["token.create", "token.update", "token.move", "token.remove"]:
check isImplementedIntent(t)
check not isImplementedIntent("player.setname") check not isImplementedIntent("player.setname")
check not isImplementedIntent("scene.set") check not isImplementedIntent("scene.set")
check not isImplementedIntent("token.create") check not isImplementedIntent("token.resize")
check not isImplementedIntent("status.set")
check not isImplementedIntent("character.create")
suite "intent rate limit (6.4: 30/s, burst 100)": suite "intent rate limit (6.4: 30/s, burst 100)":
test "a fresh bucket allows exactly the burst, then refuses": test "a fresh bucket allows exactly the burst, then refuses":
@@ -137,6 +141,8 @@ suite "malformed flood (6.5 row 8: 10 inside any 10 s)":
suite "server frames (6.1)": suite "server frames (6.1)":
test "hello carries proto, role, me and n; an unnamed player's name is null": test "hello carries proto, role, me and n; an unnamed player's name is null":
let h = helloFrame(ProtoVersion, 1, "player", 4, newJNull()) let h = helloFrame(ProtoVersion, 1, "player", 4, newJNull())
check not h.hasKey("scene") # an unnamed player gets proto, role, me only (6.1)
check not h.hasKey("extra")
check h["t"].getStr == "hello" check h["t"].getStr == "hello"
check h["proto"].getInt == 1 check h["proto"].getInt == 1
check h["role"].getStr == "player" check h["role"].getStr == "player"
@@ -146,6 +152,14 @@ suite "server frames (6.1)":
let named = helloFrame(ProtoVersion, 2, "gm", 1, %"GM") let named = helloFrame(ProtoVersion, 2, "gm", 1, %"GM")
check named["me"]["name"].getStr == "GM" check named["me"]["name"].getStr == "GM"
test "a named recipient's hello carries the scene block, and the GM also `extra`":
let sceneJson = %*{"id": 1, "w": 4096}
let p = helloFrame(ProtoVersion, 3, "player", 4, %"Alice", sceneJson)
check p["scene"]["id"].getInt == 1
check not p.hasKey("extra")
let gm = helloFrame(ProtoVersion, 4, "gm", 1, %"GM", sceneJson, %*{})
check gm["extra"].kind == JObject
test "ack ok carries its result fields and never a code": test "ack ok carries its result fields and never a code":
let a = ackFrame(9, 3, %*{"key": "ABCD-EFGH"}) let a = ackFrame(9, 3, %*{"key": "ABCD-EFGH"})
check a["t"].getStr == "ack" check a["t"].getStr == "ack"
+225
View File
@@ -0,0 +1,225 @@
## Egress (#20, DESIGN 2 single egress rule, 3.1, 6.1, 6.3, 6.4): the typed per-recipient view, the
## per-connection diff that produces `token`/`token_gone`/`vision`/`explored`, and the field rules
## that keep GM-only data out of a player's frames. The black-box proof over a real socket is
## tools/leak.test.mjs with tools/leakcheck.nim.
import std/[algorithm, json, options, sequtils, sets, tables, unittest]
import geometry, tokens, views, vision, world
const Pid = 2 # the subject player
const Other = 3 # another player
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 tok(id: string, x, y: float, owner: int, gmOnly = false, visionFlag = true): TokenRec =
TokenRec(id: id, scene: 1, kind: "npc", descriptiveName: "a " & id, actualName: "Sir " & id,
pos: (x, y), owner: owner, gmOnly: gmOnly,
flags: (if visionFlag: %*{"vision": true} else: %*{}))
proc ctxOf(sc: SceneRec, tokens: seq[TokenRec], players: seq[int]): Context =
result = Context(scene: sc, tokens: tokens)
for pid in players:
var pv: PlayerVision
pv.refresh(sc, tokens, pid)
result.visions[pid] = pv
proc refreshAll(ctx: var Context) =
## What main.refreshAll does: recompute every player's sight in place, keeping explored cells.
for pid in ctx.visions.keys.toSeq: ctx.visions[pid].refresh(ctx.scene, ctx.tokens, pid)
proc pass(ctx: var Context, known: var Known, resync = false, player = Pid): seq[JsonNode] =
## One egress pass exactly as main runs it: build, diff, then clear the fresh cells (4.2 step 8).
result = egressFrames(Recipient(isGm: false, playerId: player), ctx, known, resync)
for pid in ctx.visions.keys.toSeq: ctx.visions[pid].clearFresh()
proc typesOf(frames: seq[JsonNode]): seq[string] = frames.mapIt(it["t"].getStr)
proc keysDeep(node: JsonNode): HashSet[string] =
result = initHashSet[string]()
if node.kind == JObject:
for k, v in node:
result.incl k
for inner in keysDeep(v): result.incl inner
elif node.kind == JArray:
for v in node:
for inner in keysDeep(v): result.incl inner
const ForbiddenToPlayers = ["walls", "wall", "wall_gone", "a", "b", "open", "kind", "controller",
"gm_only", "flags", "descriptive_name", "actual_name", "reveal_all",
"revealed", "source", "radius_own", "extra"]
suite "GM view (3.1: everything, with the GM-only extras)":
test "every token, in token order, with controller and both names":
let sc = sceneWith(@[])
let tokens = @[tok("a", 100, 100, 0), tok("b", 3000, 3000, Pid), tok("c", 2000, 2000, 0)]
let view = gmView(ctxOf(sc, tokens, @[Pid]))
check view.tokens.len == 3
check view.tokens.mapIt(it.id) == @["a", "b", "c"]
let frame = gmTokenFrame(view.tokens[1])
check frame["mine"].getBool == false # `mine` is a player-facing flag
check frame["controller"].getInt == Pid
check frame["kind"].getStr == "npc"
check frame["gm_only"].getBool == false
check frame["descriptive_name"].getStr == "a b"
check frame["actual_name"].getStr == "Sir b"
check frame["props"].len == 3 # public, owner, gm
check frame["radius"].getFloat == 20.0 # the scene default (#4, slice 7)
test "a GM-controlled token shows controller null":
let sc = sceneWith(@[])
let view = gmView(ctxOf(sc, @[tok("a", 100, 100, 0)], @[Pid]))
check gmTokenFrame(view.tokens[0])["controller"].kind == JNull
test "the GM never gets vision polygons or explored cells":
let sc = sceneWith(@[])
var known: Known
let frames = egressFrames(Recipient(isGm: true, playerId: 1), ctxOf(sc, @[tok("a", 100, 100, Pid)], @[Pid]), known, resync = true)
check typesOf(frames) == @["token"]
suite "player view (3.1: controlled always, LOS + not gm_only otherwise)":
test "the set of tokens follows the visibility rule":
let sc = sceneWith(@[])
let tokens = @[tok("mine", 400, 400, Pid), tok("near", 600, 400, 0),
tok("outside", 3000, 3000, 0), tok("secret", 500, 500, 0, gmOnly = true),
tok("theirs", 3500, 3500, Other)]
let view = playerView(ctxOf(sc, tokens, @[Pid, Other]), Pid)
check view.tokens.mapIt(it.id) == @["mine", "near"]
test "a player frame carries no GM-only field and no wall-like key":
let sc = sceneWith(@[])
let tokens = @[tok("mine", 400, 400, Pid), tok("near", 500, 400, 0)]
let view = playerView(ctxOf(sc, tokens, @[Pid]), Pid)
check view.tokens.len == 2
let frame = playerTokenFrame(view.tokens[1])
let keys = keysDeep(frame)
for key in ForbiddenToPlayers:
check key notin keys
check frame["name"].getStr == "a near" # the descriptive name (slice 5)
check frame["props"].keys.toSeq == @["public"]
check not frame.hasKey("vision_radius") # only the controller gets the field at all
test "the controller gets `mine`, the owner bucket and its vision_radius":
let sc = sceneWith(@[])
var mine = tok("mine", 400, 400, Pid)
mine.visionRadius = some(250.0)
let view = playerView(ctxOf(sc, @[mine], @[Pid]), Pid)
let frame = playerTokenFrame(view.tokens[0])
check frame["mine"].getBool
check frame["props"].keys.toSeq.sorted == @["owner", "public"]
check frame["vision_radius"].getFloat == 250.0
let other = playerView(ctxOf(sc, @[tok("mine", 400, 400, Pid), tok("x", 500, 400, 0)], @[Pid]), Pid)
check other.tokens[1].visionRadius.isNone
check other.tokens[1].includeVisionRadius == false
test "a scan of every player frame finds no wall-ish or GM-only key":
let sc = sceneWith(@[WallRec(a: (700, 0), b: (700, 4096), flags: newJObject())])
let tokens = @[tok("mine", 400, 400, Pid), tok("near", 600, 400, 0),
tok("secret", 500, 500, 0, gmOnly = true)]
var known: Known
let ctx = ctxOf(sc, tokens, @[Pid])
for f in egressFrames(Recipient(isGm: false, playerId: Pid), ctx, known, resync = true):
for key in ForbiddenToPlayers:
check key notin keysDeep(f)
suite "diff (6.4: only what changed)":
test "the first pass sends the resync order, then nothing changes and nothing is sent":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid)], @[Pid])
var known: Known
let first = pass(ctx, known, resync = true)
check typesOf(first) == @["vision", "explored", "token"]
check first[1]["full"].getBool
check typesOf(pass(ctx, known)) == newSeq[string]()
test "a token that moved sends one `token` frame with the new position":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid)], @[Pid])
var known: Known
discard pass(ctx, known, resync = true)
ctx.tokens[0].pos = (440.0, 400.0)
refreshAll(ctx)
let frames = pass(ctx, known)
check typesOf(frames) == @["vision", "explored", "token"]
check frames[2]["pos"][0].getFloat == 440.0
check frames[2]["id"].getStr == "mine"
test "leaving view sends `token_gone` once, and never for a token that was never sent":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid), tok("near", 500, 400, 0)], @[Pid])
var known: Known
let first = pass(ctx, known, resync = true)
check typesOf(first).contains("token")
ctx.tokens[1].pos = (3000.0, 3000.0) # far out of sight
refreshAll(ctx)
let frames = pass(ctx, known)
check typesOf(frames) == @["token_gone"]
check frames[0]["id"].getStr == "near"
check typesOf(pass(ctx, known)) == newSeq[string]()
test "a token becoming gm_only is taken away from a player who could see it (6.1)":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid), tok("near", 600, 400, 0)], @[Pid])
var known: Known
discard pass(ctx, known, resync = true)
ctx.tokens[1].gmOnly = true
refreshAll(ctx)
let frames = pass(ctx, known)
check typesOf(frames) == @["token_gone"]
check frames[0]["id"].getStr == "near"
test "vision is re-sent only when the polygons change":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid)], @[Pid])
var known: Known
discard pass(ctx, known, resync = true)
check typesOf(pass(ctx, known)) == newSeq[string]()
ctx.tokens[0].pos = (500.0, 400.0)
refreshAll(ctx)
let moved = pass(ctx, known)
check moved[0]["t"].getStr == "vision"
check moved[0]["polys"][0]["pts"].len > 60
test "a changed wall is enough to re-send vision":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid)], @[Pid])
var known: Known
discard pass(ctx, known, resync = true)
ctx.scene.walls = @[WallRec(a: (700, 0), b: (700, 4096), flags: newJObject())]
refreshAll(ctx)
let frames = pass(ctx, known)
check frames[0]["t"].getStr == "vision" # the polygons shrank
check typesOf(frames) == @["vision"] # no new cells: the wall only removed sight
suite "frames (6.1)":
test "explored full is RLE rows of contiguous columns":
let sc = sceneWith(@[])
var pv: PlayerVision
pv.refresh(sc, @[tok("mine", 400, 400, Pid)], Pid)
let frame = exploredFullFrame(pv.exploredFull(sc))
check frame["full"].getBool
for row in frame["rle"]:
check row.len >= 3
check row.len mod 2 == 1 # cy followed by (x0, len) pairs
var cx = row[1].getInt
for i in countup(1, row.len - 1, 2):
check row[i].getInt == cx
cx += row[i + 1].getInt
test "explored fresh is a list of [cx, cy]":
let frame = exploredFreshFrame(@[(3, 4), (5, 6)])
check frame["full"].getBool == false
check frame["cells"] == %*[[3, 4], [5, 6]]
test "the vision payload uses integer pixels (6.4, Q16 FIXED)":
let frame = visionFrame(@[Poly(tokenId: "abc", pts: @[(10.4, 20.6), (30.5, 40.5)])])
check frame["polys"][0]["id"].getStr == "abc"
for pt in frame["polys"][0]["pts"]:
check pt[0].kind == JInt and pt[1].kind == JInt
check frame["polys"][0]["pts"] == %*[[10, 21], [31, 41]]
test "the hello scene block carries the 6.1 fields and no counts":
let sceneJson = sceneBlock(sceneWith(@[]))
check sceneJson["id"].getInt == 1
check sceneJson["w"].getFloat == 4096.0
check sceneJson["cell"].getInt == 32
check sceneJson["vision_radius_default"].getFloat == 400.0
check sceneJson["token_radius_default"].getFloat == 20.0
check sceneJson["art_version"].getInt == 1
for key in ["walls", "tokens", "entities", "walls_count", "count"]:
check not sceneJson.hasKey(key)