server: the character and name intents, player names and the roster (#23)
This commit is contained in:
+26
-1
@@ -5,10 +5,13 @@
|
||||
## session(id, player_id FK, token_hash UNIQUE, created_at, last_seen) - never expires;
|
||||
## exactly one GM (partial unique index); max 6 non-GM players, unused keys count.
|
||||
## Keys are plaintext so the GM can re-show them (Q11); sessions store only SHA-256(token).
|
||||
## Names (#23, 6.1): `player.setname` fills a NULL name once, `player.rename` overwrites it, and both
|
||||
## go through `nameTaken` (case-insensitive, "GM" included) and text.validPlayerName. The name is the
|
||||
## only player field a player writes, and it is also what `roster` publishes to everyone (3.1, Q9).
|
||||
## This module does no locking: the caller serializes access to the one DbConn (4.3).
|
||||
import std/[options, strutils, times]
|
||||
import db_connector/db_sqlite
|
||||
import crypto
|
||||
import crypto, text
|
||||
|
||||
type
|
||||
PlayerRole* = enum
|
||||
@@ -54,6 +57,28 @@ proc playerCount*(db: DbConn): int =
|
||||
## Non-GM players, named or not (unused keys count toward the 6-player cap).
|
||||
parseInt(db.getValue(sql"SELECT count(*) FROM player WHERE role = 'player'"))
|
||||
|
||||
proc allPlayers*(db: DbConn): seq[Player] =
|
||||
## Every player row, in id order: the roster (6.1) and the GM's character list walk this.
|
||||
for row in db.getAllRows(sql"SELECT id, name, role, colour FROM player ORDER BY id"):
|
||||
result.add rowToPlayer(row)
|
||||
|
||||
proc nameTaken*(db: DbConn, name: string, exceptId = 0): bool =
|
||||
## 6.5 `name-taken`: a player name is unique regardless of case, and the GM's name ("GM") is a
|
||||
## name like any other - so taking it is refused here, not by a special case.
|
||||
for row in db.getAllRows(sql"SELECT id, name FROM player WHERE name IS NOT NULL"):
|
||||
if parseInt(row[0]) == exceptId: continue
|
||||
if sameName(row[1], name): return true
|
||||
|
||||
proc setName*(db: DbConn, playerId: int, name: string): bool =
|
||||
## `player.setname`: only while the player has no name yet (6.1). false = it already had one.
|
||||
db.execAffectedRows(sql"UPDATE player SET name = ? WHERE id = ? AND name IS NULL",
|
||||
name, playerId) > 0
|
||||
|
||||
proc renamePlayer*(db: DbConn, playerId: int, name: string): bool =
|
||||
## `player.rename` (GM only): a named or unnamed player takes the new name.
|
||||
db.execAffectedRows(sql"UPDATE player SET name = ? WHERE id = ?", name, playerId) > 0
|
||||
|
||||
|
||||
proc keyOf*(db: DbConn, playerId: int): Option[string] =
|
||||
let s = db.getValue(sql"SELECT secret FROM player_key WHERE player_id = ?", playerId)
|
||||
if s.len == 0: none(string) else: some(s)
|
||||
|
||||
@@ -117,6 +117,19 @@ proc activeCount*(c: Conns): int =
|
||||
withLock c.lock:
|
||||
result = c.active.len
|
||||
|
||||
proc markNamed*(c: Conns, playerId: int) =
|
||||
## `player.setname` succeeded: from now on that player's connections are fed state (6.3). Without
|
||||
## this an unnamed connection would keep receiving nothing but `hello` for ever.
|
||||
withLock c.lock:
|
||||
for i in 0 ..< c.active.len:
|
||||
if c.active[i].playerId == playerId: c.active[i].named = true
|
||||
|
||||
proc connectionsOf*(c: Conns, playerId: int): seq[Conn] =
|
||||
## Every live connection of one player, in activation order (6.1: `hello` + resync to each).
|
||||
withLock c.lock:
|
||||
for conn in c.active:
|
||||
if conn.playerId == playerId: result.add conn
|
||||
|
||||
proc activeCountFor*(c: Conns, playerId: int): int =
|
||||
withLock c.lock:
|
||||
result = c.playerConnIndices(playerId).len
|
||||
|
||||
+647
-40
@@ -18,6 +18,11 @@
|
||||
## `status.clear` with the `walls`|`GM` sources of 5.5 (`source` is GM-only on the wire), `prop.set` /
|
||||
## `prop.unset` under the bucket caps of server/props.nim, and the per-token radius, props and status
|
||||
## effects on `token.create`, `token.move`, `wall.*` and `door.set`.
|
||||
## M3 slice 8 (#23): characters and names - `character.create`/`update`/`remove`/`reassign`, the
|
||||
## per-player reveal of an actual name (`name.reveal`, `name.reveal_all`), the per-player encountered
|
||||
## list (`encountered.remove`, recorded on every sighting), character props through `prop.*`, and the
|
||||
## players/keys half that names a player: `player.setname`, `player.rename`, `key.show` and the
|
||||
## `roster` frame. The token link (`token.create`/`token.update` `character_id`) lands here too.
|
||||
## Close reasons (FIXED, owner decision #18): mummy 0.4.8 cannot put a code in the close frame, so
|
||||
## every server-initiated close is preceded by a `closing {reason, code}` message and the client
|
||||
## reads 1005 + that message (DESIGN 6.5).
|
||||
@@ -27,7 +32,7 @@ import std/typedthreads
|
||||
import db_connector/db_sqlite
|
||||
import mummy, mummy/routers
|
||||
import config, db, eventlog, crypto, auth, conns, instancelock, protocol, world
|
||||
import geometry, props, tokens, vision, views, explored, worldmap, faults, moverules
|
||||
import characters, geometry, props, text, tokens, vision, views, explored, worldmap, faults, moverules
|
||||
|
||||
const
|
||||
CookieName* = "fff_session"
|
||||
@@ -51,6 +56,12 @@ type
|
||||
visions: Table[int, PlayerVision]
|
||||
## Per-player sight state (4.1 PlayerState): polygons, explored cells, fresh cells. Created on
|
||||
## a player's first connection; the GM has no entry (the GM sees everything, 6.1).
|
||||
characters: seq[CharacterRec]
|
||||
## Every character, in creation order, loaded at startup (8; slice 8 / #23).
|
||||
reveals: Reveals
|
||||
## Per-player name reveals, `(player, subject)` rows (8; slice 8).
|
||||
encountered: Encountered
|
||||
## Per-player encountered lists, player id -> token id -> snapshot (8; slice 8).
|
||||
known: Table[int, views.Known]
|
||||
## Per-connection egress diff state (4.1 `known`), keyed by the app connId (H19). Pruned on
|
||||
## every egress pass, so a closed connection leaves nothing behind.
|
||||
@@ -138,10 +149,16 @@ proc sendToGms(frame: JsonNode) =
|
||||
# Egress (DESIGN 2 single egress rule, 4.2 step 7). Everything a recipient learns about tokens,
|
||||
# vision and explored goes through views.egressFrames; this section only moves the bytes.
|
||||
|
||||
proc allIds(): seq[string] =
|
||||
## Every id already in use, tokens and characters together: they share one namespace (8), so a new
|
||||
## character cannot collide with a token and a reveal subject is never ambiguous.
|
||||
app.tokens.mapIt(it.id) & app.characters.mapIt(it.id)
|
||||
|
||||
proc egressContext(): views.Context =
|
||||
## A read-only borrow of the world and every player's sight state. The seqs and tables are shared
|
||||
## by reference and only read before egressFrames returns, so no copy is needed.
|
||||
views.Context(scene: app.scene, tokens: app.tokens, visions: app.visions)
|
||||
views.Context(scene: app.scene, tokens: app.tokens, characters: app.characters,
|
||||
reveals: app.reveals, encountered: app.encountered, visions: app.visions)
|
||||
|
||||
proc pruneKnown() =
|
||||
## A closed connection's `known` table must not outlive it.
|
||||
@@ -162,6 +179,35 @@ proc refreshAll() =
|
||||
## A wall or door changed: every player's sight changes (4.2 step 5).
|
||||
for pid in app.visions.keys.toSeq: refreshPlayer(pid)
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# The encountered list (DESIGN 8, 6.1; slice 8 / #23). One rule: a token that a player can see is in
|
||||
# that player's list from then on, under the name that player knows at that moment. It is recorded
|
||||
# before the ack (like explored cells) and only ever grows except for `encountered.remove`.
|
||||
|
||||
proc recordEncounters() =
|
||||
## Adds every token now visible to a player that is not in that player's list yet. Cheap in the
|
||||
## steady state: a token already in the list costs one table lookup, and only an unknown token
|
||||
## runs the visibility rule. A player without sight state has no polygons and so sees only the
|
||||
## tokens it controls, which is the same rule `vision.visibleTo` applies.
|
||||
var fresh: seq[(int, characters.EncounteredEntry)]
|
||||
for pid in app.visions.keys.toSeq:
|
||||
if pid == GmControlled: continue
|
||||
let hasList = app.encountered.hasKey(pid)
|
||||
for t in app.tokens:
|
||||
if hasList and app.encountered[pid].hasKey(t.id): continue
|
||||
if not app.visions[pid].visibleTo(t, pid): continue
|
||||
let names = subjectNamesOf(t, app.characters)
|
||||
let knows = knowsActual(names.owner == pid and names.owner > 0, names.revealAll,
|
||||
app.reveals.isRevealed(pid, names.id))
|
||||
fresh.add (pid, newEntry(t.id, names, knows))
|
||||
if fresh.len == 0: return
|
||||
# NORMAL durability: a snapshot of where somebody has been is derived data, like explored cells
|
||||
# (Q12), and the ack is sent after this commit (4.2 step 7).
|
||||
app.db.withTransaction:
|
||||
for (pid, e) in fresh: writeEncountered(app.db, pid, e)
|
||||
for (pid, e) in fresh:
|
||||
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
|
||||
@@ -208,14 +254,63 @@ proc egressAll() =
|
||||
for pid in app.visions.keys.toSeq: app.visions[pid].clearFresh()
|
||||
pruneKnown()
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# The player roster (DESIGN 3.1, 6.1; Q9 FIXED: players see each other's names). Two variants are
|
||||
# built once per fan-out: the GM sees every player (`name: null` for an unused key), a player sees
|
||||
# named players only, so an unused key or the number of keys is not visible (6.1 leak note 4).
|
||||
|
||||
proc rosterFrames(): tuple[everyone: JsonNode, namedOnly: JsonNode] =
|
||||
var everyone: seq[JsonNode]
|
||||
var named: seq[JsonNode]
|
||||
for p in allPlayers(app.db):
|
||||
let connected = app.conns.activeCountFor(p.id) > 0
|
||||
let nameJson = if p.name.isSome: %p.name.get else: newJNull()
|
||||
everyone.add rosterEntry(p.id, nameJson, $p.role, p.colour, connected)
|
||||
if p.name.isSome: named.add rosterEntry(p.id, nameJson, $p.role, p.colour, connected)
|
||||
(rosterFrame(everyone), rosterFrame(named))
|
||||
|
||||
proc sendRoster() =
|
||||
## To every connection, each with its own `n` (a frame taking `n` is built per recipient here).
|
||||
let frames = rosterFrames()
|
||||
for c in app.conns.snapshot():
|
||||
if c.role != prGm and not c.named: continue # 6.3: an unnamed player gets `hello` only
|
||||
let n = nextN(c)
|
||||
if n > 0: c.ws.send($withN(if c.role == prGm: frames.everyone else: frames.namedOnly, n))
|
||||
|
||||
proc sendHello(connId: int, player: Player) =
|
||||
## The `hello` frame (6.1): the first frame on a connection, and again after `player.setname`
|
||||
## (which is why it lives in a proc both paths call). Keyed by the app connId so a caller holding
|
||||
## only the id (the upgrade handler) and one holding the record (the fan-out) share it.
|
||||
let named = player.name.isSome
|
||||
let me = if named: %player.name.get else: newJNull()
|
||||
var sceneJson: JsonNode
|
||||
if player.role == prGm or named: sceneJson = sceneBlock(app.scene)
|
||||
var extraJson: JsonNode
|
||||
if player.role == prGm: extraJson = app.scene.extra
|
||||
let helloN = app.conns.nextFrameNo(connId)
|
||||
let found = app.conns.connById(connId)
|
||||
if helloN <= 0 or found.isNone: return
|
||||
found.get.ws.send($helloFrame(ProtoVersion, helloN, $player.role, player.id, me, sceneJson,
|
||||
extraJson))
|
||||
|
||||
proc resync(connId: int, named: bool, player: Player) =
|
||||
## The 6.3 sequence after `hello`, for the parts this slice has: GM gets `walls` then every token;
|
||||
## a named player gets `vision`, `explored` (full) then every token it may see. An unnamed player
|
||||
## gets nothing beyond `hello`.
|
||||
## The 6.3 sequence after `hello`: `roster` first; GM gets `walls`, `character` for all,
|
||||
## `encountered` per player, then every token; a named player gets its own `character` records,
|
||||
## its `encountered` list, `vision`, `explored` (full) then every token it may see. An unnamed
|
||||
## player gets nothing beyond `hello`. `egressFrames` emits the character/encountered half in that
|
||||
## order, so this proc only has to put `roster` and the wall snapshot in front of it. The caller
|
||||
## holds the global lock (4.3), which is also why `recordEncounters` can write here.
|
||||
let isGm = player.role == prGm
|
||||
let found = app.conns.connById(connId)
|
||||
if found.isNone: return
|
||||
let conn = found.get
|
||||
# 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()
|
||||
if isGm or named:
|
||||
let frames = rosterFrames()
|
||||
let n = nextN(conn)
|
||||
if n > 0: conn.ws.send($withN(if isGm: frames.everyone else: frames.namedOnly, n))
|
||||
if isGm or faultActive("walls"):
|
||||
let snap = wallsSnapshot(app.scene)
|
||||
let n = nextN(conn)
|
||||
@@ -229,23 +324,30 @@ proc resync(connId: int, named: bool, player: Player) =
|
||||
let n = nextN(conn)
|
||||
if n > 0: conn.ws.send($withN(f, n))
|
||||
|
||||
proc settle(conn: Conn, reqId: int, extra: JsonNode = nil) =
|
||||
proc settle(conn: Conn, reqId: int, extra: JsonNode = nil, roster = false) =
|
||||
## 4.2 step 7 for a mutation: the ack and then every recipient's diff are enqueued under the global
|
||||
## lock, so no two threads touch a connection's `known` table at once and the ack always precedes
|
||||
## the effects that mutation caused. Every frame is built from the state at enqueue time, so a
|
||||
## mutation that runs between another mutation's transaction and its settle cannot send stale
|
||||
## state; the exact per-connection ordering of two concurrent mutations, and the coalescing that
|
||||
## makes it cheap, are the M5 outbox (4.3).
|
||||
## `recordEncounters` runs before the ack: a sighting is durable before the client is told about it
|
||||
## (the same rule explored cells follow, 4.2 step 6). `roster` = the player list changed.
|
||||
withLock app.dbLock:
|
||||
recordEncounters()
|
||||
ackOk(conn, reqId, extra)
|
||||
if roster: sendRoster()
|
||||
egressAll()
|
||||
|
||||
proc settleWorld(conn: Conn, reqId: int, wallEffect: JsonNode, extra: JsonNode = nil) =
|
||||
proc settleWorld(conn: Conn, reqId: int, wallEffect: JsonNode, extra: JsonNode = nil,
|
||||
roster = false) =
|
||||
## The same for a wall/door write: ack, the GM-only wall effect, then the per-recipient egress
|
||||
## (a wall change can reveal or hide tokens and always changes vision).
|
||||
withLock app.dbLock:
|
||||
recordEncounters()
|
||||
ackOk(conn, reqId, extra)
|
||||
sendToGms(wallEffect)
|
||||
if roster: sendRoster()
|
||||
egressAll()
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
@@ -275,6 +377,22 @@ proc applyRuleOutcome(mr: moverules.Scene): int =
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# Intent field helpers (DESIGN 6.1, 6.5 steps 7-8): shape first, then lookup.
|
||||
|
||||
type
|
||||
SetNameOutcome = enum
|
||||
snOk
|
||||
snTaken
|
||||
snNotAllowed
|
||||
|
||||
RenameOutcome = enum
|
||||
rnOk
|
||||
rnNotFound
|
||||
rnTaken
|
||||
|
||||
RevealOutcome = enum
|
||||
nrOk
|
||||
nrNotFound
|
||||
nrInvalid ## a token that has a character: reveal through the character (6.1)
|
||||
|
||||
type
|
||||
SceneCheck = enum
|
||||
scOk
|
||||
@@ -511,19 +629,12 @@ proc wsUpgrade(request: Request) {.gcsafe.} =
|
||||
|
||||
# `hello` is the first frame on the connection (n = 1). An unnamed player gets `proto, role, me`
|
||||
# and nothing else; a named player and the GM get the scene block (6.1: no counts, no wall data,
|
||||
# no owned ids; `mine` travels on `token`).
|
||||
let me = if playerRec.name.isSome: %playerRec.name.get else: newJNull()
|
||||
var sceneJson: JsonNode
|
||||
if role == prGm or named:
|
||||
sceneJson = sceneBlock(app.scene)
|
||||
var extraJson: JsonNode
|
||||
if role == prGm: extraJson = app.scene.extra
|
||||
let helloN = app.conns.nextFrameNo(activated.id)
|
||||
if helloN > 0: ws.send($helloFrame(ProtoVersion, helloN, $role, pid, me, sceneJson, extraJson))
|
||||
# no owned ids; `mine` travels on `token`, `roster` carries the player list).
|
||||
sendHello(activated.id, playerRec)
|
||||
# One Ping right away, then one every PingIntervalMs: the browser answers without JS (4.3).
|
||||
ws.send($nextPingSeq(), Ping)
|
||||
# The 6.3 order for the parts this slice has: GM: `walls` then every token; player: `vision`,
|
||||
# `explored` (full) then every token it may see. Players never receive wall data (3.1, T2).
|
||||
# The 6.3 order: `roster`, walls (GM), characters, encountered, then vision/explored and the
|
||||
# tokens. Players never receive wall data (3.1, T2).
|
||||
if role != prGm and named:
|
||||
refreshPlayer(pid)
|
||||
resync(activated.id, named, playerRec)
|
||||
@@ -561,6 +672,98 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
ackErr(conn, env.reqId, CodeNoRules)
|
||||
return
|
||||
|
||||
of "player.setname":
|
||||
# 6.1: a player fills their own name once. Their `hello` (with `me.name`), a full resync of every
|
||||
# connection of that player, and a `roster` to everyone follow (6.3, 3.1 Q9).
|
||||
if conn.role == prGm:
|
||||
ackErr(conn, env.reqId, CodeNotAllowed) # the GM's name is set by the CLI, not the wire
|
||||
return
|
||||
var raw: string
|
||||
if not stringField(env, "name", raw):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
let name = normalizedPlayerName(raw)
|
||||
if not validPlayerName(name):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
var outcome = snOk
|
||||
withLock app.dbLock:
|
||||
let current = playerById(app.db, conn.playerId)
|
||||
if current.isNone: outcome = snNotAllowed
|
||||
elif current.get.name.isSome: outcome = snNotAllowed # 6.1: only while own name is null
|
||||
elif nameTaken(app.db, name): outcome = snTaken
|
||||
elif setName(app.db, conn.playerId, name):
|
||||
let named = playerById(app.db, conn.playerId)
|
||||
outcome = snOk
|
||||
app.conns.markNamed(conn.playerId)
|
||||
# 6.1: every connection of that player gets `hello` with `me.name` set, then the full resync
|
||||
# (6.3); `roster` to all (Q9). The ack follows, so nothing is acked before it is durable.
|
||||
for c in app.conns.connectionsOf(conn.playerId):
|
||||
sendHello(c.id, named.get)
|
||||
resync(c.id, true, named.get)
|
||||
sendRoster()
|
||||
ackOk(conn, env.reqId)
|
||||
else: outcome = snNotAllowed
|
||||
if outcome == snTaken:
|
||||
ackErr(conn, env.reqId, CodeNameTaken)
|
||||
return
|
||||
if outcome != snOk:
|
||||
ackErr(conn, env.reqId, CodeNotAllowed)
|
||||
return
|
||||
app.lg.log(lvInfo, "player_setname", [("player", $conn.playerId)])
|
||||
return
|
||||
|
||||
of "player.rename":
|
||||
# 6.1 (G): a named or unnamed player takes a new name; `roster` to all (3.1 Q9).
|
||||
var id = 0
|
||||
if not intField(env, "id", id):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
var raw: string
|
||||
if not stringField(env, "name", raw):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
let name = normalizedPlayerName(raw)
|
||||
if not validPlayerName(name):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
var outcome = rnOk
|
||||
withLock app.dbLock:
|
||||
if playerById(app.db, id).isNone: outcome = rnNotFound
|
||||
elif nameTaken(app.db, name, exceptId = id): outcome = rnTaken
|
||||
elif not renamePlayer(app.db, id, name): outcome = rnNotFound
|
||||
if outcome == rnNotFound:
|
||||
ackErr(conn, env.reqId, CodeNotFound)
|
||||
return
|
||||
if outcome == rnTaken:
|
||||
ackErr(conn, env.reqId, CodeNameTaken)
|
||||
return
|
||||
app.lg.log(lvInfo, "player_rename", [("player", $id)])
|
||||
settle(conn, env.reqId, roster = true)
|
||||
return
|
||||
|
||||
of "key.show":
|
||||
# 6.1 (G): re-show a player key (Q11 FIXED: keys are stored plaintext so they can be re-shown).
|
||||
var id = 0
|
||||
if not intField(env, "id", id):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
var key: Option[string]
|
||||
var gmKey = false
|
||||
withLock app.dbLock:
|
||||
let target = playerById(app.db, id)
|
||||
if target.isNone: key = none(string)
|
||||
elif target.get.role == prGm: gmKey = true # the GM's key is CLI-only (3.2)
|
||||
else: key = keyOf(app.db, id)
|
||||
if gmKey:
|
||||
ackErr(conn, env.reqId, CodeNotAllowed)
|
||||
return
|
||||
if key.isNone:
|
||||
ackErr(conn, env.reqId, CodeNotFound)
|
||||
return
|
||||
ackOk(conn, env.reqId, %*{"key": key.get})
|
||||
return
|
||||
|
||||
of "key.create":
|
||||
var created: tuple[id: int, key: string]
|
||||
var capped = false
|
||||
@@ -572,7 +775,9 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
return
|
||||
app.lg.addSecret(created.key)
|
||||
app.lg.log(lvInfo, "key_created", [("player", $created.id)])
|
||||
ackOk(conn, env.reqId, %*{"id": created.id, "key": created.key})
|
||||
withLock app.dbLock:
|
||||
ackOk(conn, env.reqId, %*{"id": created.id, "key": created.key})
|
||||
sendRoster() # 6.1: the GM's roster gains the new (unnamed) entry
|
||||
return
|
||||
|
||||
of "key.replace":
|
||||
@@ -605,7 +810,9 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
for doomed in closed: closeGone(doomed, ReasonRevoked, CloseRevoked)
|
||||
app.lg.addSecret(key.get)
|
||||
app.lg.log(lvInfo, "key_replaced", [("player", $id), ("conns_closed", $closed.len)])
|
||||
ackOk(conn, env.reqId, %*{"key": key.get})
|
||||
withLock app.dbLock:
|
||||
ackOk(conn, env.reqId, %*{"key": key.get})
|
||||
sendRoster() # 6.1: `connected` flags change
|
||||
return
|
||||
|
||||
of "player.remove":
|
||||
@@ -624,7 +831,16 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
elif target.get.role == prGm:
|
||||
notAllowed = true
|
||||
else:
|
||||
removed = removePlayer(app.db, id)
|
||||
# DESIGN 3.2: that player's characters pass to the GM before the DELETE, because
|
||||
# `character.owner_player_id` refuses to dangle (no cascade on purpose); their reveal rows
|
||||
# and encountered list go with them through the FK cascade (6.1). A server without a GM row
|
||||
# cannot have players (key.create needs the GM role), so the guard is belt and braces.
|
||||
if app.gmPlayerId > 0:
|
||||
app.db.withTransaction:
|
||||
characters.transferToGm(app.db, id, app.gmPlayerId)
|
||||
removed = removePlayer(app.db, id)
|
||||
else:
|
||||
removed = removePlayer(app.db, id)
|
||||
if notFound:
|
||||
ackErr(conn, env.reqId, CodeNotFound)
|
||||
return
|
||||
@@ -640,9 +856,13 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
# the row; memory (and the `controller: null` the GM sees) follows here.
|
||||
for t in app.tokens.mitems:
|
||||
if t.owner == id: t.owner = GmControlled
|
||||
for c in app.characters.mitems:
|
||||
if c.owner == id: c.owner = app.gmPlayerId
|
||||
app.visions.del id
|
||||
app.reveals.withoutRevealsOf(id)
|
||||
app.encountered.del id
|
||||
app.lg.log(lvInfo, "player_removed", [("player", $id), ("conns_closed", $closed.len)])
|
||||
settle(conn, env.reqId)
|
||||
settle(conn, env.reqId, roster = true)
|
||||
return
|
||||
|
||||
of "token.create":
|
||||
@@ -651,19 +871,27 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
if not stringField(env, "kind", kind) or not validKind(kind):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
if not stringField(env, "descriptive_name", dname) or not validName(dname):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
if not stringField(env, "actual_name", aname) or not validName(aname):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
let pos = parseVec(fieldOrNull(env.node, "pos"))
|
||||
if pos.isNone:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
if present(env, "character_id"):
|
||||
# The character link is slice 8 (#23). A known-but-unbuilt field is refused `invalid`:
|
||||
# silently dropping a GM's field would lose data (6.1 token payload rules).
|
||||
# 6.1: a plain token carries its own two names; a token linked to a character carries none (the
|
||||
# character has them). Both or neither, so a GM's field is never silently dropped.
|
||||
var characterId: Option[string]
|
||||
let charNode = fieldOrNull(env.node, "character_id")
|
||||
if not charNode.isNil:
|
||||
if charNode.kind != JString:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
characterId = some(charNode.getStr)
|
||||
if characterId.isNone:
|
||||
if not stringField(env, "descriptive_name", dname) or not validName(dname):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
if not stringField(env, "actual_name", aname) or not validName(aname):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
elif present(env, "descriptive_name") or present(env, "actual_name"):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
var gmOnly = false
|
||||
@@ -688,13 +916,24 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
return
|
||||
var created: tuple[outcome: TokenOutcome, token: TokenRec]
|
||||
var controllerCheck = ccOk
|
||||
var characterMissing = false
|
||||
withLock app.dbLock:
|
||||
var candidate = TokenRec(kind: kind, descriptiveName: dname, actualName: aname,
|
||||
pos: pos.get, gmOnly: gmOnly, flags: flags.get,
|
||||
visionRadius: vr.get, radius: radius.get,
|
||||
props: tokenProps.get)
|
||||
controllerCheck = resolveController(env.node{"controller"}, candidate.owner)
|
||||
if controllerCheck == ccOk:
|
||||
props: tokenProps.get, characterId: characterId)
|
||||
if characterId.isSome:
|
||||
# 6.1: the default controller of a linked token is the character's owner; the GM's own id is
|
||||
# stored as GM-controlled like everywhere else. A missing character is `not-found`.
|
||||
let ch = characterById(app.characters, characterId.get)
|
||||
if ch.isNone: characterMissing = true
|
||||
else: candidate.owner = (if ch.get.owner == app.gmPlayerId: GmControlled
|
||||
else: ch.get.owner)
|
||||
# `controller` absent keeps the default (the character's owner for a linked token, the GM
|
||||
# otherwise); `null` is the GM and an integer is that player (6.1).
|
||||
if not characterMissing and env.node.hasKey("controller"):
|
||||
controllerCheck = resolveController(env.node{"controller"}, candidate.owner)
|
||||
if controllerCheck == ccOk and not characterMissing:
|
||||
# 5.5 SET: a GM placement ignores walls, but a position overlapping a blocking wall gives the
|
||||
# new token `stuck(walls)` right away. The rules compute it on a snapshot that already holds
|
||||
# the candidate as its last token, so the row is written once with its statuses.
|
||||
@@ -707,6 +946,9 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
refreshPlayer(created.token.owner)
|
||||
app.db.withTransaction:
|
||||
persistExplored(@[created.token.owner])
|
||||
if characterMissing:
|
||||
ackErr(conn, env.reqId, CodeNotFound) # no such character
|
||||
return
|
||||
if controllerCheck == ccInvalid:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
@@ -726,9 +968,15 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
if not stringField(env, "id", id):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
if present(env, "character_id"):
|
||||
ackErr(conn, env.reqId, CodeInvalid) # the character link is slice 8 (#23)
|
||||
return
|
||||
# 6.1: `character_id` is a string (link) or null (unlink); absent keeps the stored link.
|
||||
var characterDecl: Option[Option[string]]
|
||||
if declared(env, "character_id"):
|
||||
let raw = env.node{"character_id"}
|
||||
if raw.kind == JNull: characterDecl = some(none(string))
|
||||
elif raw.kind == JString: characterDecl = some(some(raw.getStr))
|
||||
else:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
var patch: TokenPatch
|
||||
var anyField = false
|
||||
if present(env, "kind"):
|
||||
@@ -776,6 +1024,18 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
anyField = true
|
||||
if characterDecl.isSome:
|
||||
# 6.1: "links with names; unlinking without both names" is `invalid`. The names travel with
|
||||
# the link change because a plain token must always carry its own two names.
|
||||
if characterDecl.get.isSome:
|
||||
if patch.descriptiveName.isSome or patch.actualName.isSome:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
elif patch.descriptiveName.isNone or patch.actualName.isNone:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
patch.characterId = characterDecl
|
||||
anyField = true
|
||||
if not anyField:
|
||||
# `token.update` changes at least one field (6.1); a fieldless update is invalid (6.5 step 7).
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
@@ -785,13 +1045,17 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
var updated: TokenRec
|
||||
var controllerCheck = ccOk
|
||||
var controller = GmControlled
|
||||
var characterMissing = false
|
||||
withLock app.dbLock:
|
||||
let current = tokenById(app.tokens, id)
|
||||
if current.isSome:
|
||||
if controllerSeen:
|
||||
if characterDecl.isSome and characterDecl.get.isSome and
|
||||
characterById(app.characters, characterDecl.get.get).isNone:
|
||||
characterMissing = true # 6.5 step 8: a missing GM target is `not-found`
|
||||
if controllerSeen and not characterMissing:
|
||||
controllerCheck = resolveController(env.node{"controller"}, controller)
|
||||
if controllerCheck == ccOk: patch.controller = some(controller)
|
||||
if controllerCheck == ccOk:
|
||||
if controllerCheck == ccOk and not characterMissing:
|
||||
let candidate = patched(current.get, patch)
|
||||
outcome = storeToken(app.db, app.scene, candidate)
|
||||
if outcome == toOk:
|
||||
@@ -802,6 +1066,16 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
refreshPlayer(updated.owner)
|
||||
app.db.withTransaction:
|
||||
persistExplored(@[oldOwner, updated.owner])
|
||||
# A plain token renamed here keeps its encountered snapshots in step with it (8); a
|
||||
# linked token's names live on the character, whose own handler does the same.
|
||||
if updated.characterId.isNone and
|
||||
(current.get.descriptiveName != updated.descriptiveName or
|
||||
current.get.actualName != updated.actualName):
|
||||
app.db.withTransaction:
|
||||
renameEncounteredToken(app.db, id, updated.descriptiveName, updated.actualName)
|
||||
if characterMissing:
|
||||
ackErr(conn, env.reqId, CodeNotFound)
|
||||
return
|
||||
if controllerCheck == ccInvalid:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
@@ -1054,7 +1328,36 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
ackErr(conn, env.reqId, CodeInvalid) # the registry refuses this key, kind or bucket
|
||||
return
|
||||
if target == "character":
|
||||
ackErr(conn, env.reqId, CodeNotFound)
|
||||
# Same caps and registry as a token (6.1): the character holds identity and base values, the
|
||||
# token holds the state of the figure (8), and the wire intents are shared.
|
||||
var charOutcome = coNotFound
|
||||
var capped = false
|
||||
withLock app.dbLock:
|
||||
let idx = characterIndex(app.characters, id)
|
||||
if idx.isSome:
|
||||
var rec = app.characters[idx.get]
|
||||
var p = props.clone(rec.props)
|
||||
if setting:
|
||||
if not p.setProp(bucket.get, key, value): capped = true
|
||||
else: rec.props = p
|
||||
else:
|
||||
discard p.unsetProp(bucket.get, key) # unsetting an absent key is ok (6.1)
|
||||
rec.props = p
|
||||
if not capped:
|
||||
charOutcome = storeCharacter(app.db, rec)
|
||||
if charOutcome == coOk: app.characters[idx.get] = rec
|
||||
if capped:
|
||||
ackErr(conn, env.reqId, CodeInvalid) # 64 keys per bucket (6.1, #22)
|
||||
return
|
||||
if charOutcome == coNotFound:
|
||||
ackErr(conn, env.reqId, CodeNotFound)
|
||||
return
|
||||
if charOutcome != coOk:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
app.lg.log(lvInfo, if setting: "prop_set" else: "prop_unset",
|
||||
[("character", id), ("bucket", $bucket.get)])
|
||||
settle(conn, env.reqId)
|
||||
return
|
||||
var outcome = toNotFound
|
||||
var capped = false
|
||||
@@ -1087,6 +1390,303 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
settle(conn, env.reqId)
|
||||
return
|
||||
|
||||
# --- characters, names, encountered (DESIGN 8, 6.1; slice 8 / #23) ---------------------------
|
||||
|
||||
of "character.create":
|
||||
# 6.1 (G): both names, an optional owner (default the GM) and optional props. The id comes from
|
||||
# the shared token/character namespace, so a reveal subject is never ambiguous.
|
||||
var dname, aname: string
|
||||
if not stringField(env, "descriptive_name", dname) or not validCharacterName(dname):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
if not stringField(env, "actual_name", aname) or not validCharacterName(aname):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
var owner = app.gmPlayerId
|
||||
if present(env, "owner") and not intField(env, "owner", owner):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
let charProps = props.parseProps(app.registry, fieldOrNull(env.node, "props"))
|
||||
if charProps.isNone:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
var created: tuple[outcome: CharacterOutcome, character: CharacterRec]
|
||||
var ownerMissing = false
|
||||
withLock app.dbLock:
|
||||
if playerById(app.db, owner).isNone:
|
||||
ownerMissing = true
|
||||
else:
|
||||
let candidate = CharacterRec(owner: owner, descriptiveName: dname, actualName: aname,
|
||||
props: charProps.get)
|
||||
created = addCharacter(app.db, candidate, allIds())
|
||||
if created.outcome == coOk: app.characters.add created.character
|
||||
if ownerMissing:
|
||||
ackErr(conn, env.reqId, CodeNotFound) # 6.5 step 8: no such owner player
|
||||
return
|
||||
if created.outcome != coOk:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
app.lg.log(lvInfo, "character_create", [("character", created.character.id),
|
||||
("owner", $created.character.owner)])
|
||||
settle(conn, env.reqId, %*{"id": created.character.id})
|
||||
return
|
||||
|
||||
of "character.update":
|
||||
# 6.1 (G): the two names only; props go through `prop.set`/`prop.unset`.
|
||||
var id: string
|
||||
if not stringField(env, "id", id):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
var patch = CharacterRec()
|
||||
var anyField = false
|
||||
if present(env, "descriptive_name"):
|
||||
if not stringField(env, "descriptive_name", patch.descriptiveName) or
|
||||
not validCharacterName(patch.descriptiveName):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
anyField = true
|
||||
if present(env, "actual_name"):
|
||||
if not stringField(env, "actual_name", patch.actualName) or
|
||||
not validCharacterName(patch.actualName):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
anyField = true
|
||||
if not anyField:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
var outcome = coNotFound
|
||||
var updated: CharacterRec
|
||||
withLock app.dbLock:
|
||||
let idx = characterIndex(app.characters, id)
|
||||
if idx.isSome:
|
||||
var candidate = app.characters[idx.get]
|
||||
if present(env, "descriptive_name"): candidate.descriptiveName = patch.descriptiveName
|
||||
if present(env, "actual_name"): candidate.actualName = patch.actualName
|
||||
outcome = storeCharacter(app.db, candidate)
|
||||
if outcome == coOk:
|
||||
updated = candidate
|
||||
app.characters[idx.get] = updated
|
||||
# 6.1: "encountered upserts for players who met it" - every snapshot of this character
|
||||
# follows the new names (a player who was never told the actual one keeps not knowing it).
|
||||
app.db.withTransaction:
|
||||
renameEncountered(app.db, id, updated.descriptiveName, updated.actualName)
|
||||
if outcome == coNotFound:
|
||||
ackErr(conn, env.reqId, CodeNotFound)
|
||||
return
|
||||
if outcome != coOk:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
app.lg.log(lvInfo, "character_update", [("character", id)])
|
||||
settle(conn, env.reqId)
|
||||
return
|
||||
|
||||
of "character.remove":
|
||||
# 6.1 (G): `in-use` while a token still links the character (the GM removes or unlinks those
|
||||
# tokens first, 6.5). Reads physically cascade the reveal rows of the subject.
|
||||
var id: string
|
||||
if not stringField(env, "id", id):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
var outcome = coNotFound
|
||||
withLock app.dbLock:
|
||||
let idx = characterIndex(app.characters, id)
|
||||
if idx.isSome:
|
||||
if tokensLinkedTo(app.tokens, id) > 0:
|
||||
outcome = coInUse
|
||||
elif removeCharacter(app.db, id):
|
||||
app.characters.delete idx.get
|
||||
# The reveal rows of a subject that no longer exists; a *token*'s rows are left alone
|
||||
# because a token id is never reused (8).
|
||||
app.db.withTransaction:
|
||||
deleteRevealsFor(app.db, id)
|
||||
outcome = coOk
|
||||
if outcome == coInUse:
|
||||
ackErr(conn, env.reqId, CodeInUse)
|
||||
return
|
||||
if outcome == coNotFound:
|
||||
ackErr(conn, env.reqId, CodeNotFound)
|
||||
return
|
||||
app.lg.log(lvInfo, "character_remove", [("character", id)])
|
||||
settle(conn, env.reqId)
|
||||
return
|
||||
|
||||
of "character.reassign":
|
||||
# 6.1 (G): the character changes hands; its tokens keep their controllers untouched (3.1, 8).
|
||||
var id: string
|
||||
if not stringField(env, "id", id):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
var owner = 0
|
||||
if not intField(env, "owner", owner):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
var outcome = coNotFound
|
||||
var updated: CharacterRec
|
||||
withLock app.dbLock:
|
||||
let idx = characterIndex(app.characters, id)
|
||||
if idx.isSome and playerById(app.db, owner).isSome:
|
||||
var candidate = app.characters[idx.get]
|
||||
candidate.owner = owner
|
||||
outcome = storeCharacter(app.db, candidate)
|
||||
if outcome == coOk:
|
||||
updated = candidate
|
||||
app.characters[idx.get] = updated
|
||||
if outcome == coNotFound:
|
||||
ackErr(conn, env.reqId, CodeNotFound) # no such character or owner
|
||||
return
|
||||
if outcome != coOk:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
when defined(leakfault):
|
||||
if faultActive("controllerChange"):
|
||||
# Negative control for the CONTROLLER_CHANGE class (DESIGN 10.3): a character owner change
|
||||
# drags its tokens' controllers along, which 3.1/8 forbid. Compiled out of every shipped
|
||||
# binary, like the other faults.
|
||||
withLock app.dbLock:
|
||||
for i in 0 ..< app.tokens.len:
|
||||
if app.tokens[i].characterId == some(id):
|
||||
var rec = app.tokens[i]
|
||||
rec.owner = (if updated.owner == app.gmPlayerId: GmControlled else: updated.owner)
|
||||
if storeToken(app.db, app.scene, rec) == toOk: app.tokens[i] = rec
|
||||
app.lg.log(lvInfo, "character_reassign", [("character", id), ("owner", $updated.owner)])
|
||||
settle(conn, env.reqId)
|
||||
return
|
||||
|
||||
of "name.reveal":
|
||||
# 6.1 (G): reveal one subject's actual name to one player. Never revoked (8): there is no
|
||||
# un-reveal intent in M3.
|
||||
var subjectRaw, id: string
|
||||
if not stringField(env, "subject", subjectRaw):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
let subject = parseSubject(subjectRaw)
|
||||
if subject.isNone:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
if not stringField(env, "id", id):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
var player = 0
|
||||
if not intField(env, "player", player):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
var outcome = nrNotFound
|
||||
var actual = ""
|
||||
var subjectId = id
|
||||
withLock app.dbLock:
|
||||
if playerById(app.db, player).isNone:
|
||||
outcome = nrNotFound
|
||||
elif subject.get == nsCharacter:
|
||||
let ch = characterById(app.characters, id)
|
||||
if ch.isNone: outcome = nrNotFound
|
||||
else:
|
||||
actual = ch.get.actualName
|
||||
outcome = nrOk
|
||||
else:
|
||||
let tok = tokenById(app.tokens, id)
|
||||
if tok.isNone: outcome = nrNotFound
|
||||
elif tok.get.characterId.isSome: outcome = nrInvalid # reveal through the character (6.1)
|
||||
else:
|
||||
actual = tok.get.actualName
|
||||
outcome = nrOk
|
||||
if outcome == nrInvalid:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
if outcome == nrNotFound:
|
||||
ackErr(conn, env.reqId, CodeNotFound)
|
||||
return
|
||||
withLock app.dbLock:
|
||||
addReveal(app.db, player, subjectId)
|
||||
app.reveals.withReveal(player, subjectId)
|
||||
# 6.1: the player's encountered list learns the actual name too (the snapshot, not a view).
|
||||
app.db.withTransaction:
|
||||
if subject.get == nsCharacter: revealEncountered(app.db, subjectId, actual)
|
||||
else: revealEncounteredToken(app.db, subjectId, actual)
|
||||
for eid, e in app.encountered.getOrDefault(player):
|
||||
if (subject.get == nsCharacter and e.characterId == some(subjectId)) or
|
||||
(subject.get == nsToken and eid == subjectId):
|
||||
app.encountered[player][eid] = e.revealed(actual)
|
||||
app.lg.log(lvInfo, "name_reveal", [("subject", subjectRaw), ("id", id), ("player", $player)])
|
||||
settle(conn, env.reqId)
|
||||
return
|
||||
|
||||
of "name.reveal_all":
|
||||
# 6.1 (G): set the subject's `reveal_all`; as `name.reveal` for every player, idempotent.
|
||||
var subjectRaw, id: string
|
||||
if not stringField(env, "subject", subjectRaw):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
let subject = parseSubject(subjectRaw)
|
||||
if subject.isNone:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
if not stringField(env, "id", id):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
var outcome = coNotFound
|
||||
var actual = ""
|
||||
withLock app.dbLock:
|
||||
if subject.get == nsCharacter:
|
||||
let idx = characterIndex(app.characters, id)
|
||||
if idx.isSome:
|
||||
var candidate = app.characters[idx.get]
|
||||
candidate.revealAll = true
|
||||
actual = candidate.actualName
|
||||
outcome = storeCharacter(app.db, candidate)
|
||||
if outcome == coOk: app.characters[idx.get] = candidate
|
||||
else:
|
||||
let idx = tokenIndex(app.tokens, id)
|
||||
if idx.isSome:
|
||||
var candidate = app.tokens[idx.get]
|
||||
candidate.revealAll = true
|
||||
actual = candidate.actualName
|
||||
# `reveal_all` on a plain token is the same flag a character carries, so it goes through
|
||||
# the token's own store; the two outcome enums differ only in name here.
|
||||
let stored = storeToken(app.db, app.scene, candidate)
|
||||
outcome = (if stored == toOk: coOk elif stored == toNotFound: coNotFound
|
||||
else: coInvalid)
|
||||
if outcome == coOk: app.tokens[idx.get] = candidate
|
||||
if outcome == coOk:
|
||||
app.db.withTransaction:
|
||||
if subject.get == nsCharacter: revealEncountered(app.db, id, actual)
|
||||
else: revealEncounteredToken(app.db, id, actual)
|
||||
for pid in app.encountered.keys.toSeq:
|
||||
for eid, e in app.encountered[pid]:
|
||||
if (subject.get == nsCharacter and e.characterId == some(id)) or
|
||||
(subject.get == nsToken and eid == id):
|
||||
app.encountered[pid][eid] = e.revealed(actual)
|
||||
if outcome == coNotFound:
|
||||
ackErr(conn, env.reqId, CodeNotFound)
|
||||
return
|
||||
if outcome != coOk:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
app.lg.log(lvInfo, "name_reveal_all", [("subject", subjectRaw), ("id", id)])
|
||||
settle(conn, env.reqId)
|
||||
return
|
||||
|
||||
of "encountered.remove":
|
||||
# 6.1 (G): the only way an entry leaves a player's list (8). The token itself is untouched.
|
||||
var player = 0
|
||||
if not intField(env, "player", player):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
var id: string
|
||||
if not stringField(env, "id", id):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
var removed = false
|
||||
withLock app.dbLock:
|
||||
if playerById(app.db, player).isSome:
|
||||
removed = deleteEncountered(app.db, player, id)
|
||||
if removed: app.encountered[player].del id
|
||||
if not removed:
|
||||
ackErr(conn, env.reqId, CodeNotFound) # no such player, or no such entry
|
||||
return
|
||||
app.lg.log(lvInfo, "encountered_remove", [("player", $player), ("token", id)])
|
||||
settle(conn, env.reqId)
|
||||
return
|
||||
|
||||
of "wall.add":
|
||||
if not sceneOk(conn, env): return
|
||||
let a = parseVec(fieldOrNull(env.node, "a"))
|
||||
@@ -1474,6 +2074,10 @@ proc runServer(cfg: Config): int =
|
||||
return 1
|
||||
state.scene = loaded.get
|
||||
state.tokens = loadTokens(conn, state.scene.id)
|
||||
# 8 / slice 8: the characters, the per-player reveals and the encountered snapshots.
|
||||
state.characters = characters.loadCharacters(conn)
|
||||
state.reveals = characters.loadReveals(conn)
|
||||
state.encountered = characters.loadEncountered(conn)
|
||||
# 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)
|
||||
@@ -1481,9 +2085,12 @@ proc runServer(cfg: Config): int =
|
||||
if gm.isSome: state.gmPlayerId = gm.get.id
|
||||
lg.log(lvInfo, "scene_loaded", [("scene", $state.scene.id), ("walls", $state.scene.walls.len),
|
||||
("tokens", $state.tokens.len),
|
||||
("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))])
|
||||
lg.log(lvInfo, "names_loaded", [("reveals", $state.reveals.pairs.len),
|
||||
("encountered_players", $state.encountered.len)])
|
||||
appHandle = cast[pointer](state)
|
||||
|
||||
createThread(heartbeatThread, heartbeat)
|
||||
|
||||
Reference in New Issue
Block a user