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:
2026-11-19 23:27:26 +01:00
parent e989100f50
commit edd4437f7e
11 changed files with 599 additions and 47 deletions
+48 -25
View File
@@ -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)