feat(walls): player markers — emission, opaque ids, storage, resync (#59)
A wall that is player_marker:true and derives window sends a player one anchor (the drawn midpoint, integer px) and an opaque per-player 12-char id once any point of its segment enters that player's vision polygon. Markers live in PlayerVision like explored, persist to marker_seen in the same derived-memory transaction, load before the first connection and resync as a full set after explored; the GM and other players never receive one. - markers.nim: emission gate, visible-extent test, id mint, anchor, marker_seen I/O. - views/main: PlayerView markers + full/diff frames, refresh sync, startup load. - markers.test.mjs: window preset, switch off, solid wall, any-part anchor, walk-away/door/lost sight, full-after-explored, per-player privacy, GM none. - leakcheck: marker allowed type + independent visible-extent oracle with a positive control (a marked window the subject sees). - restart: marked window in the fixture; marker set and marker_seen rows identical before/after SIGTERM and SIGKILL. - protocol/tviews: catalogue and frame order pin the 16th message. Retraction, re-earning and MARKER_* faults are #60. Ref #59
This commit is contained in:
+48
-25
@@ -39,7 +39,7 @@ import std/typedthreads
|
||||
import db_connector/db_sqlite
|
||||
import mummy, mummy/routers
|
||||
import config, db, eventlog, crypto, auth, conns, instancelock, protocol, world, jsonbound
|
||||
import characters, geometry, props, text, tiles, tokens, vision, views, explored, worldmap, faults, moverules
|
||||
import characters, geometry, markers, props, text, tiles, tokens, vision, views, explored, worldmap, faults, moverules
|
||||
|
||||
const
|
||||
CookieName* = "fff_session"
|
||||
@@ -191,9 +191,11 @@ proc refreshPlayer(pid: int) =
|
||||
## Recompute one player's polygons and explored cells (4.2 step 5). Caller holds the lock. The
|
||||
## sight state is created on first use, so a player who never connected still gets one the moment
|
||||
## they do (nothing is stale from startup, 4.1). The table entry is passed by reference: reading it
|
||||
## into a `var` would copy it and the update would be lost.
|
||||
## into a `var` would copy it and the update would be lost. The same refresh mints the player's
|
||||
## markers (5.8): the polygon is the gate, so it must run after `refresh`.
|
||||
if pid == GmControlled: return
|
||||
app.visions.mgetOrPut(pid, PlayerVision()).refresh(app.scene, app.tokens, pid)
|
||||
discard markers.syncMarkers(app.visions.mgetOrPut(pid, PlayerVision()), app.scene)
|
||||
|
||||
proc refreshAll() =
|
||||
## A wall or door changed: every player's sight changes (4.2 step 5).
|
||||
@@ -229,11 +231,11 @@ proc recordEncounters() =
|
||||
app.encountered.mgetOrPut(pid, initTable[string, characters.EncounteredEntry]())[e.entityId] = e
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# Explored persistence (DESIGN 4.2 step 6, 4.4; M3 slice 6 / #21). The grid lives in memory; this is
|
||||
# the only place it reaches the DB. One rule: a mutation writes exactly the chunks its refresh
|
||||
# dirtied, never the whole grid, and the write rides in the mutation's transaction so an ack cannot
|
||||
# precede the cells it reports. NORMAL durability (Q12): explored is derived and monotone, not
|
||||
# GM-authored content.
|
||||
# Derived player memory persistence: explored cells and player markers (DESIGN 4.2 step 6, 4.4, 5.8;
|
||||
# M3 slice 6 / #21, #59). Both live in memory and reach the DB only here. One rule: a mutation writes
|
||||
# exactly the explored chunks its refresh dirtied and the markers it minted, never the whole state,
|
||||
# and the write rides in the mutation's transaction so an ack cannot precede what it reports. NORMAL
|
||||
# durability (Q12): both are derived and monotone (a marker only grows in r1), not GM-authored.
|
||||
|
||||
proc dirtyExplored(pids: openArray[int]): seq[explored.Chunk] =
|
||||
## The chunks the last refresh dirtied, for the named players. Caller holds the lock and has
|
||||
@@ -247,16 +249,27 @@ proc dirtyExplored(pids: openArray[int]): seq[explored.Chunk] =
|
||||
app.visions.mgetOrPut(pid, PlayerVision()).explored, fresh):
|
||||
result.add c
|
||||
|
||||
proc persistExplored(pids: openArray[int]) =
|
||||
## Writes the dirtied chunks. No transaction of its own: the caller wraps it together with the
|
||||
## mutation's own row writes (db.withTransaction).
|
||||
proc persistMarkers(pids: openArray[int]) =
|
||||
## The marker half alone, for a connect where the explored grid must stay exactly as it was (a
|
||||
## schema-4/7 database rebuilds its grid on connect and stores nothing until a mutation): a marker
|
||||
## minted at the resync is still durable before it is sent (5.8, 4.2 step 6).
|
||||
for pid in pids:
|
||||
if pid == GmControlled: continue
|
||||
discard markers.writeNew(app.db, app.scene.id, pid,
|
||||
app.visions.mgetOrPut(pid, PlayerVision()).markerFresh)
|
||||
|
||||
proc persistDerived(pids: openArray[int]) =
|
||||
## Writes the dirtied explored chunks and the markers the same refresh minted (5.8: a marker insert
|
||||
## is in the same derived-memory transaction as the explored chunks, after the wall row commits).
|
||||
## No transaction of its own: the caller wraps it together with the mutation's row writes.
|
||||
let chunks = dirtyExplored(pids)
|
||||
if chunks.len > 0: discard explored.writeChunks(app.db, app.scene.id, chunks)
|
||||
persistMarkers(pids)
|
||||
|
||||
proc persistAllExplored() =
|
||||
## After `refreshAll` (a wall or door changed): every player whose grid grew, in one transaction.
|
||||
proc persistAllDerived() =
|
||||
## After `refreshAll` (a wall or door changed): every player whose grid grew or markers changed.
|
||||
app.db.withTransaction:
|
||||
persistExplored(app.visions.keys.toSeq)
|
||||
persistDerived(app.visions.keys.toSeq)
|
||||
|
||||
proc egressAll() =
|
||||
## One pass over every live connection: build that recipient's view, diff it against what the
|
||||
@@ -331,7 +344,13 @@ proc resync(connId: int, named: bool, player: Player) =
|
||||
# This is the moment a connection starts receiving state, so the player's own sight is computed
|
||||
# here: a connection opened while unnamed never had a refresh, and `player.setname` resyncs on the
|
||||
# same socket (6.1). Idempotent: a refresh that changes nothing only costs the polygon pass.
|
||||
if not isGm and named: refreshPlayer(player.id)
|
||||
if not isGm and named:
|
||||
refreshPlayer(player.id)
|
||||
# A marker minted here (a window the player had not seen before connecting) must be durable like
|
||||
# any other derived memory before the resync sends it (5.8, 4.2 step 6). Only markers: the
|
||||
# explored grid keeps its own existing connect behaviour (nothing is stored here).
|
||||
app.db.withTransaction:
|
||||
persistMarkers(@[player.id])
|
||||
# A token visible right now is a sighting: record it before the `encountered` list is built (the
|
||||
# player may have been offline while something walked into their sight).
|
||||
recordEncounters()
|
||||
@@ -1183,7 +1202,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
app.tokens.add created.token
|
||||
refreshPlayer(created.token.owner)
|
||||
app.db.withTransaction:
|
||||
persistExplored(@[created.token.owner])
|
||||
persistDerived(@[created.token.owner])
|
||||
# The record copy (`created`, and the world's own) must die under this lock, and so must
|
||||
# the ack's `id`: settle inside the critical section, then carry only fresh scalars out.
|
||||
createdId = detachedString(created.token.id)
|
||||
@@ -1319,7 +1338,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
refreshPlayer(oldOwner)
|
||||
refreshPlayer(candidate.owner)
|
||||
app.db.withTransaction:
|
||||
persistExplored(@[oldOwner, candidate.owner])
|
||||
persistDerived(@[oldOwner, candidate.owner])
|
||||
# A plain-token rename or a link change keeps every encountered snapshot of this token
|
||||
# in step with its subject - the descriptive name, the character link and the actual
|
||||
# name this player may know - in the DB and in memory at once (8; #29, #30). A linked
|
||||
@@ -1386,7 +1405,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
app.db.withTransaction:
|
||||
discard writePosition(app.db, app.tokens[idx.get])
|
||||
writeStatuses(app.db, app.tokens[idx.get])
|
||||
persistExplored(@[app.tokens[idx.get].owner])
|
||||
persistDerived(@[app.tokens[idx.get].owner])
|
||||
case kind
|
||||
of mkError:
|
||||
ackErr(conn, env.reqId, if conn.role == prGm: CodeNotFound else: CodeNotAllowed)
|
||||
@@ -1416,7 +1435,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
app.tokens.delete idx.get
|
||||
refreshPlayer(owner)
|
||||
app.db.withTransaction:
|
||||
persistExplored(@[owner])
|
||||
persistDerived(@[owner])
|
||||
if not removed:
|
||||
ackErr(conn, env.reqId, CodeNotFound)
|
||||
return
|
||||
@@ -1462,7 +1481,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
app.tokens[idx.get] = rec
|
||||
refreshPlayer(rec.owner)
|
||||
app.db.withTransaction:
|
||||
persistExplored(@[rec.owner])
|
||||
persistDerived(@[rec.owner])
|
||||
if outcome == toNotFound:
|
||||
ackErr(conn, env.reqId, CodeNotFound)
|
||||
return
|
||||
@@ -2018,7 +2037,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
app.scene = candidate
|
||||
for (i, rec) in tokenChanges: app.tokens[i] = rec
|
||||
refreshAll()
|
||||
persistAllExplored()
|
||||
persistAllDerived()
|
||||
recordEncounters()
|
||||
ackOk(conn, env.reqId)
|
||||
resyncEveryone()
|
||||
@@ -2074,7 +2093,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
discard moverules.addWall(mr, ruleWall(added.get))
|
||||
discard applyRuleOutcome(mr)
|
||||
refreshAll() # 4.2 step 5: a wall change moves every player's sight
|
||||
persistAllExplored() # step 6: the chunks the new wall revealed, before the ack
|
||||
persistAllDerived() # step 6: the chunks the new wall revealed, before the ack
|
||||
addedId = added.get.id
|
||||
addedKind = derivedKind(added.get)
|
||||
# The wall frame references `added.flags`; build it and fan it out here, before the record
|
||||
@@ -2130,7 +2149,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
discard moverules.updateWall(mr, idx, ruleWall(updated.get))
|
||||
discard applyRuleOutcome(mr)
|
||||
refreshAll()
|
||||
persistAllExplored()
|
||||
persistAllDerived()
|
||||
updatedKind = derivedKind(updated.get)
|
||||
# Frame and record copy both live and die inside this lock (ANALYSIS 4.1).
|
||||
settleWorldLocked(conn, env.reqId, wallFrame(sceneId, wallObjectOf(updated.get)))
|
||||
@@ -2164,7 +2183,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
discard moverules.removeWall(mr, idx.get)
|
||||
discard applyRuleOutcome(mr)
|
||||
refreshAll()
|
||||
persistAllExplored()
|
||||
persistAllDerived()
|
||||
if outcome == waNotFound:
|
||||
ackErr(conn, env.reqId, CodeNotFound)
|
||||
return
|
||||
@@ -2201,7 +2220,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
if idx.isSome: discard moverules.setDoor(mr, idx.get, open)
|
||||
discard applyRuleOutcome(mr)
|
||||
refreshAll()
|
||||
persistAllExplored()
|
||||
persistAllDerived()
|
||||
# Frame and record copy both live and die inside this lock (ANALYSIS 4.1).
|
||||
settleWorldLocked(conn, env.reqId, wallFrame(sceneId, wallObjectOf(updated.get)))
|
||||
ok = true
|
||||
@@ -2426,6 +2445,9 @@ proc runServer(cfg: Config): int =
|
||||
# 4.4 startup / slice 6: the players' explored grids come back from their chunk rows. Polygons are
|
||||
# never stored; the sight state is rebuilt from the loaded walls on the player's first refresh.
|
||||
state.visions = explored.restore(conn, state.scene)
|
||||
# 5.8 (#59): the per-player marker memory comes back with the explored state, before the first
|
||||
# connection, so a reconnecting player gets the full set they had.
|
||||
markers.restore(conn, state.scene, state.visions)
|
||||
let gm = gmPlayer(conn)
|
||||
if gm.isSome: state.gmPlayerId = gm.get.id
|
||||
lg.log(lvInfo, "scene_loaded", [("scene", $state.scene.id), ("walls", $state.scene.walls.len),
|
||||
@@ -2433,7 +2455,8 @@ proc runServer(cfg: Config): int =
|
||||
("characters", $state.characters.len),
|
||||
("next_wall_id", $state.scene.nextWallId)])
|
||||
lg.log(lvInfo, "explored_loaded", [("players", $state.visions.len),
|
||||
("chunks", $explored.chunkCount(conn, state.scene.id))])
|
||||
("chunks", $explored.chunkCount(conn, state.scene.id)),
|
||||
("markers", $markers.markerCount(conn, state.scene.id))])
|
||||
lg.log(lvInfo, "names_loaded", [("reveals", $state.reveals.pairs.len),
|
||||
("encountered_players", $state.encountered.len)])
|
||||
appHandle = cast[pointer](state)
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
## Player marker emission and persistence (DESIGN 5.8, 6.1, 6.3, 8; ADR-0015, #59).
|
||||
##
|
||||
## A marker exists for a player exactly when a wall is both `player_marker:true` and derives
|
||||
## `window`, and any point of the wall's visible extent has been inside one of that player's vision
|
||||
## polygons. In this round the visible extent is the drawn segment (thickness is inert, 5.10), so the
|
||||
## test is: an endpoint inside the polygon, or the segment crossing one of its edges. The gate is the
|
||||
## player's own polygon, the same one that decides token visibility (5.1), so nothing behind a
|
||||
## sight-blocking wall qualifies and the check never needs a second vision implementation.
|
||||
##
|
||||
## The marker is per-player memory like explored: it is minted once, gets that player's own opaque
|
||||
## 12-character id (never the wall id), keeps the wall's drawn midpoint rounded once as its anchor,
|
||||
## and is persisted in `marker_seen` as part of the same derived-memory transaction as the explored
|
||||
## chunks (4.2 step 6). `vision.PlayerVision.markers` holds it in memory and `restore` loads it at
|
||||
## startup, before the first connection (4.4). This round only adds: retraction (wall removed, switch
|
||||
## off, no longer a window, geometry moved), re-earning a fresh id and the marker fault classes are
|
||||
## #60; `sync` is the seam where that lifetime rule lands.
|
||||
##
|
||||
## No DB transaction control here: the caller owns it, exactly like explored.nim.
|
||||
import std/[math, options, strutils, tables]
|
||||
import db_connector/db_sqlite
|
||||
import geometry, tokens, vision, world
|
||||
|
||||
proc anchorOf*(w: WallRec): (int, int) =
|
||||
## The wall's drawn midpoint, rounded once to integer px and fixed for the wall (5.8, 6.1).
|
||||
(int(round((w.a.x + w.b.x) / 2.0)), int(round((w.a.y + w.b.y) / 2.0)))
|
||||
|
||||
proc extentSeen*(pv: PlayerVision, a, b: Vec): bool =
|
||||
## True when any point of the wall's visible extent (the segment in this round) is inside one of
|
||||
## the player's polygons: an endpoint inside, or the segment crossing a polygon edge. Boundary
|
||||
## contacts are inclusive, which is the generous side of "any point" and cannot admit anything
|
||||
## behind a sight blocker (the polygon itself stops there).
|
||||
for poly in pv.polys:
|
||||
if poly.pts.len < 3: continue
|
||||
if inside(poly.pts, a) or inside(poly.pts, b): return true
|
||||
for i in 0 ..< poly.pts.len:
|
||||
if segsCross(a, b, poly.pts[i], poly.pts[(i + 1) mod poly.pts.len]): return true
|
||||
|
||||
proc qualifies*(pv: PlayerVision, w: WallRec): bool =
|
||||
## The complete emission gate of 5.8: the switch on, the derived shape label a window, and part of
|
||||
## the visible extent seen. A solid wall with `player_marker:true` fails the kind gate.
|
||||
w.playerMarker and derivedKind(w) == "window" and pv.extentSeen(w.a, w.b)
|
||||
|
||||
proc markerIdTaken(pv: PlayerVision, id: string): bool =
|
||||
for marker in pv.markers.values:
|
||||
if marker.id == id: return true
|
||||
|
||||
proc freshMarkerId(pv: PlayerVision): string =
|
||||
result = newTokenId()
|
||||
var tries = 0
|
||||
while markerIdTaken(pv, result) and tries < 64:
|
||||
result = newTokenId()
|
||||
inc tries
|
||||
|
||||
proc syncMarkers*(pv: var PlayerVision, sc: SceneRec): int =
|
||||
## Adds one marker per wall that now qualifies and is not in this player's memory yet; returns how
|
||||
## many were minted. Add-only by design in this round (#59): a marker that stops qualifying stays,
|
||||
## so walking away, a door closing and lost sight never retract it. The retraction/re-earn rule is
|
||||
## #60 and belongs here, next to this loop.
|
||||
for w in sc.walls:
|
||||
if w.id in pv.markers: continue
|
||||
if not pv.qualifies(w): continue
|
||||
let (x, y) = anchorOf(w)
|
||||
let marker = Marker(id: freshMarkerId(pv), x: x, y: y)
|
||||
pv.markers[w.id] = marker
|
||||
pv.markerFresh.add (w.id, marker)
|
||||
inc result
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# Persistence (marker_seen, migration step 8; the caller owns the transaction)
|
||||
|
||||
const InsertSql = """INSERT INTO marker_seen (player_id, scene_id, wall_id, marker_id)
|
||||
VALUES (?, ?, ?, ?)"""
|
||||
|
||||
proc writeNew*(db: DbConn, sceneId, playerId: int, fresh: var seq[(int, Marker)]): int =
|
||||
## Inserts the markers the last refresh minted for one player and clears the buffer. Called inside
|
||||
## the mutation's transaction, after the wall row (for a wall write) committed and before the ack:
|
||||
## a marker can never precede the wall that causes it (5.8, 4.2 step 6).
|
||||
if fresh.len == 0: return 0
|
||||
let ps = db.prepare(InsertSql)
|
||||
try:
|
||||
for (wallId, marker) in fresh:
|
||||
db.exec(ps, playerId, sceneId, wallId, marker.id)
|
||||
inc result
|
||||
finally:
|
||||
finalize(ps)
|
||||
fresh.setLen(0)
|
||||
|
||||
proc restore*(db: DbConn, sc: SceneRec, visions: var Table[int, PlayerVision]) =
|
||||
## Startup (4.4): every `marker_seen` row back into its player's memory, before the first
|
||||
## connection, with the anchor recomputed from the loaded wall (the anchor is derived, not stored).
|
||||
## A row whose wall is missing cannot exist (the composite FK cascades); skipping one defensively
|
||||
## keeps a hand-edited DB from crashing startup.
|
||||
for row in db.getAllRows(sql"""
|
||||
SELECT player_id, wall_id, marker_id FROM marker_seen WHERE scene_id = ?""", sc.id):
|
||||
let pid = parseInt(row[0])
|
||||
let wallId = parseInt(row[1])
|
||||
let wall = sc.wallById(wallId)
|
||||
if wall.isNone: continue
|
||||
let (x, y) = anchorOf(wall.get)
|
||||
visions.mgetOrPut(pid, PlayerVision()).markers[wallId] =
|
||||
Marker(id: row[2], x: x, y: y)
|
||||
|
||||
proc markerCount*(db: DbConn, sceneId: int): int =
|
||||
## Scene-wide marker rows: an O(1) startup log number (11.3) and a test probe.
|
||||
parseInt(db.getValue(sql"SELECT count(*) FROM marker_seen WHERE scene_id = ?", sceneId))
|
||||
+58
-2
@@ -104,6 +104,12 @@ type
|
||||
name*: string
|
||||
grey*: bool
|
||||
|
||||
MarkerView* = object
|
||||
## One player marker (DESIGN 5.8, 6.1): the player's own opaque id and the wall's drawn midpoint
|
||||
## in integer px. There is deliberately no wall id, kind, state, label or switch here.
|
||||
id*: string
|
||||
x*, y*: int
|
||||
|
||||
GmEncounteredView* = object
|
||||
player*: int
|
||||
entries*: seq[EncounteredView]
|
||||
@@ -117,6 +123,7 @@ type
|
||||
tokens*: seq[PlayerTokenView]
|
||||
characters*: seq[PlayerCharacterView]
|
||||
encountered*: seq[EncounteredView]
|
||||
markers*: seq[MarkerView]
|
||||
polys*: seq[Poly]
|
||||
fresh*: seq[(int, int)]
|
||||
|
||||
@@ -151,6 +158,7 @@ type
|
||||
tokens*: Table[string, JsonNode]
|
||||
characters*: Table[string, JsonNode]
|
||||
encountered*: Table[string, JsonNode] ## GM: "<player>/<token>"; player: "<token>"
|
||||
markers*: Table[string, JsonNode] ## player: marker id -> the `{id,pos}` entry sent
|
||||
vision*: string ## the last `vision` payload sent, "" = never
|
||||
visionSent*: bool
|
||||
|
||||
@@ -291,8 +299,7 @@ proc playerView*(ctx: Context, playerId: int): PlayerView =
|
||||
result.encountered.add EncounteredView(id: eid, name: e.entryName, grey: eid notin visible)
|
||||
when defined(leakfault):
|
||||
# Negative controls (DESIGN 10.3): add what the honest rule just refused, so the harness proves
|
||||
# it would notice. Never a second copy of the visibility rule.
|
||||
# The two "add a token the honest rule refused" controls build the frame exactly as the honest
|
||||
# it would notice. Never a second copy of the visibility rule. # The two "add a token the honest rule refused" controls build the frame exactly as the honest
|
||||
# path would, so the class they report stays the one they were built for (a bucket mismatch here
|
||||
# would add an OWNER_PROP/CHAR_OWNER_PROP class and blunt the assertion).
|
||||
proc leakedView(t: TokenRec): PlayerTokenView =
|
||||
@@ -367,6 +374,12 @@ proc playerView*(ctx: Context, playerId: int): PlayerView =
|
||||
if ch.isNone or ch.get.owner == playerId: continue
|
||||
for v in result.tokens.mitems:
|
||||
if v.id == t.id: v.cpropsPublic = objectOf(ch.get.props[pbOwner])
|
||||
result.markers = newSeqOfCap[MarkerView](pv[].markers.len)
|
||||
for _, marker in pv[].markers.pairs:
|
||||
result.markers.add MarkerView(id: marker.id, x: marker.x, y: marker.y)
|
||||
# Deterministic order by the opaque id: the full set is compared byte-for-byte on resync, and the
|
||||
# order must not reveal wall order or count (the ids are random, 5.8).
|
||||
result.markers.sort(proc (a, b: MarkerView): int = cmp(a.id, b.id))
|
||||
result.polys = pv[].polys
|
||||
result.fresh = pv[].fresh
|
||||
|
||||
@@ -504,6 +517,22 @@ proc exploredFreshFrame*(cells: seq[(int, int)]): JsonNode =
|
||||
for (cx, cy) in cells: list.add %*[cx, cy]
|
||||
%*{"t": "explored", "full": false, "cells": list}
|
||||
|
||||
proc markerEntryJson(m: MarkerView): JsonNode =
|
||||
## One entry of a `marker` set: only the opaque id and the integer-px anchor (5.8, 6.1).
|
||||
%*{"id": m.id, "pos": [m.x, m.y]}
|
||||
|
||||
proc markerFrame*(entries: seq[MarkerView], full: bool, del: seq[string]): JsonNode =
|
||||
## `marker {full, set:[{id, pos}], del:[id]}` (DESIGN 6.1). `full:true` replaces the whole set on
|
||||
## connect/resync and carries no `del`; a diff carries additions in `set` and retractions in `del`,
|
||||
## never both for one id. Retraction emission is #60; this builder already has the shape.
|
||||
var set: JsonNode = newJArray()
|
||||
for m in entries: set.add markerEntryJson(m)
|
||||
result = %*{"t": "marker", "full": full, "set": set}
|
||||
if not full:
|
||||
var removals = newJArray()
|
||||
for id in del: removals.add %id
|
||||
result["del"] = removals
|
||||
|
||||
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,
|
||||
@@ -562,6 +591,27 @@ proc diffEncountered(known: var Known, key: string, entries: seq[EncounteredView
|
||||
del.sort()
|
||||
encounteredFrame(set, full, del, player)
|
||||
|
||||
proc diffMarkers(known: var Known, markers: seq[MarkerView], full: bool): JsonNode =
|
||||
## One `marker` message or nil (DESIGN 5.8, 6.1): on connect/resync `full:true` with the whole set
|
||||
## (after `explored`, 6.3); afterwards only new ids in `set`. The `del` path exists in the frame
|
||||
## shape but the r1 map is add-only: retraction is #60, so it stays empty here.
|
||||
var seen = initHashSet[string]()
|
||||
var set: seq[MarkerView]
|
||||
var del: seq[string]
|
||||
for m in markers:
|
||||
seen.incl m.id
|
||||
let frame = markerEntryJson(m)
|
||||
if full or known.markers.getOrDefault(m.id) != frame:
|
||||
known.markers[m.id] = frame
|
||||
set.add m
|
||||
for id in known.markers.keys.toSeq:
|
||||
if id in seen: continue
|
||||
known.markers.del id
|
||||
if not full: del.add id
|
||||
if full or set.len > 0 or del.len > 0:
|
||||
del.sort()
|
||||
return markerFrame(set, full, del)
|
||||
|
||||
proc egressFrames*(r: Recipient, ctx: Context, known: var Known, resync = false): seq[JsonNode] =
|
||||
## Ordered like the 6.3 resync sequence: characters, encountered, then vision/explored and the
|
||||
## tokens. Empty = nothing changed for this recipient, which is what keeps hidden mutations
|
||||
@@ -624,6 +674,12 @@ proc egressFrames*(r: Recipient, ctx: Context, known: var Known, resync = false)
|
||||
fresh.add other.exploredFull(ctx.scene)
|
||||
result.add exploredFreshFrame(fresh)
|
||||
|
||||
# 6.3: `marker` (full) sits after `explored` because it is the same kind of memory and the client
|
||||
# draws it over the fog `explored` just rebuilt. A diff follows the explored diff for the same
|
||||
# reason. The GM never reaches this branch (3.1, 5.8).
|
||||
let markerMsg = diffMarkers(known, view.markers, resync)
|
||||
if not markerMsg.isNil: result.add markerMsg
|
||||
|
||||
var seen = initHashSet[string]()
|
||||
for v in view.tokens:
|
||||
seen.incl v.id
|
||||
|
||||
+14
-1
@@ -20,7 +20,12 @@
|
||||
##
|
||||
## 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]
|
||||
##
|
||||
## Player markers (DESIGN 5.8, ADR-0015, #59) are per-player memory like explored: `markers` maps a
|
||||
## wall id to that player's own opaque marker id and its fixed anchor (integer px). The map only grows
|
||||
## in this round; retraction and re-earning are #60. `markerFresh` holds the markers minted by the
|
||||
## current refresh so the mutation's transaction can persist them (server/markers.nim).
|
||||
import std/[algorithm, math, sets, tables]
|
||||
import tokens, worldmap, geometry, world, faults
|
||||
|
||||
type
|
||||
@@ -28,11 +33,19 @@ type
|
||||
tokenId*: string
|
||||
pts*: seq[Vec]
|
||||
|
||||
Marker* = object
|
||||
## One player's marker memory for one wall (DESIGN 5.8, 6.1). The id is opaque and per player;
|
||||
## the anchor is the wall's drawn midpoint, rounded once at mint time and never updated.
|
||||
id*: string
|
||||
x*, y*: int
|
||||
|
||||
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
|
||||
markers*: Table[int, Marker] ## wall id -> this player's marker (5.8, #59)
|
||||
markerFresh*: seq[(int, Marker)] ## markers minted by the last refresh, awaiting the DB write
|
||||
|
||||
proc cols*(sc: SceneRec): int =
|
||||
## Cells across the scene (DESIGN 8: ceil(w / cell)).
|
||||
|
||||
Reference in New Issue
Block a user