## Characters, name reveals and the per-player encountered list (DESIGN 3.1, 4.1, 6.1, 8; M3 ## slice 8, issue #23). ## ## A character is its own record, separate from the tokens that figure it (FIXED #14): one owner - a ## real player id, and the GM owns through its own player id - two names, `reveal_all` and the three ## property buckets. `TokenRec.characterId` is the link; a token linked to a character carries no ## names of its own, because the character's names are the ones a client sees. A token's *controller* ## is set on the token and is independent of the character's owner: `character.reassign` never ## touches it (6.1, DESIGN 8). ## ## Names [FIXED #14, DESIGN 8]: every character and every plain token has a `descriptive_name` (what ## a player sees) and an `actual_name` (what the GM knows). A player sees the actual name only when ## the subject is a character they own, or the GM revealed it to them, or `reveal_all` is set. That ## one rule lives in `knowsActual`/`visibleName` and nothing else in the server re-derives it: the ## token frame, the character frame and the encountered entry all call it. ## ## Reveals are stored per `(player, subject)` in `name_reveal`, where the subject is a character id or ## a plain token id. Token and character ids share one alphabet *and one uniqueness namespace* ## (`freshId` is called with both lists), so a subject id is never ambiguous. A reveal is never ## revoked and is not dropped when the character changes owner (8); `reveal_all` is a flag on the ## subject, so a player who joins later is covered without a row per player. ## ## Encountered [FIXED #14, DESIGN 8]: per player, one entry per token that player ever saw, holding ## the *snapshot* of the name that player knows (`actual_name` NULL = not known). Entries are never ## removed automatically - not on token removal, not on a `gm_only` flip, not on a scene change - ## only by `encountered.remove`. The entry is added the moment the token enters that player's view ## (main.recordEncounters); a rename updates the snapshot; a reveal fills in the actual name. ## ## This module does no locking (the caller holds the global lock, 4.3) and no wire shapes (that is ## server/views.nim); it owns the records and their SQLite rows. import std/[algorithm, json, options, sets, strutils, tables, times] import db_connector/db_sqlite import props, text, tokens, world type CharacterRec* = object id*: string owner*: int ## a real player id, the GM's included; never GmControlled descriptiveName*: string actualName*: string revealAll*: bool props*: Props ## three buckets, never nil CharacterOutcome* = enum coOk coInvalid ## a name or a prop value is off: `invalid` coNotFound ## no such character (or owner player): `not-found` coInUse ## a token still figures it: `in-use` (6.5) NameSubject* = enum nsCharacter = "character" nsToken = "token" Reveals* = object ## `(playerId, subjectId)` pairs, i.e. one row of `name_reveal` each. A set because every ## question asked of it is a membership test; the per-subject player list is a bounded scan. pairs*: HashSet[(int, string)] EncounteredEntry* = object entityId*: string characterId*: Option[string] ## none = the entry belongs to a plain token descriptiveName*: string actualName*: Option[string] ## none = this player was never told the actual name Encountered* = Table[int, Table[string, EncounteredEntry]] ## playerId -> entityId -> the entry. Per player by construction, so no egress path can hand one ## player another player's list by accident. SubjectNames* = object ## What the name rule needs about one subject (a character, or a plain token). id*: string ## the reveal subject id: the character id when linked, else the token id descriptive*: string actual*: string revealAll*: bool owner*: int ## the player who always knows the actual name; 0 = nobody characterId*: Option[string] ## set when the subject is character-backed const MaxOwnerlessName* = 64 ## Characters follow the token name rule of 6.5: 1..64 code points (text.validText). # --------------------------------------------------------------------------------------------------- # The name rule (DESIGN 8). One copy, used by every frame builder. proc knowsActual*(isOwner, revealAll, revealed: bool): bool = ## A player is told the actual name of a subject when they own it, when the GM revealed it to ## everyone, or when the GM revealed it to them (8; reveals are never revoked). isOwner or revealAll or revealed proc visibleName*(descriptive, actual: string, knowsActual: bool): string = ## The one name a recipient sees for a subject (6.1 `token.name`). if knowsActual: actual else: descriptive proc isRevealed*(r: Reveals, player: int, subject: string): bool = (player, subject) in r.pairs proc revealedPlayers*(r: Reveals, subject: string): seq[int] = ## The `revealed:[player ids]` list of a GM frame, ascending so the frame is deterministic. for (player, subj) in r.pairs: if subj == subject: result.add player result.sort() proc withReveal*(r: var Reveals, player: int, subject: string) = r.pairs.incl (player, subject) proc withoutRevealsOf*(r: var Reveals, player: int) = ## `player.remove`: that player's reveal rows go with it (6.1). var doomed: seq[(int, string)] for pair in r.pairs: if pair[0] == player: doomed.add pair for pair in doomed: r.pairs.excl pair # --------------------------------------------------------------------------------------------------- # Lookups and the subject view proc characterIndex*(chars: openArray[CharacterRec], id: string): Option[int] = for i, c in chars: if c.id == id: return some(i) proc characterById*(chars: openArray[CharacterRec], id: string): Option[CharacterRec] = let i = characterIndex(chars, id) if i.isSome: return some(chars[i.get]) proc validCharacterName*(s: string): bool = validText(s, MaxOwnerlessName) proc parseSubject*(raw: string): Option[NameSubject] = for s in NameSubject: if $s == raw: return some(s) proc normalize*(c: CharacterRec): CharacterRec = result = c result.props = props.normalize(result.props) proc validCharacter*(c: CharacterRec): bool = validCharacterName(c.descriptiveName) and validCharacterName(c.actualName) and c.owner > 0 and props.valid(c.props) proc subjectNamesOf*(c: CharacterRec): SubjectNames = ## A character as the name rule sees it: its owner always knows the actual name. SubjectNames(id: c.id, descriptive: c.descriptiveName, actual: c.actualName, revealAll: c.revealAll, owner: c.owner, characterId: some(c.id)) proc subjectNamesOf*(t: TokenRec, chars: openArray[CharacterRec]): SubjectNames = ## A token as the name rule sees it: a linked token borrows the character's names (so one reveal ## covers every token of that character), a plain token uses its own and owns nobody's trust. if t.characterId.isSome: let c = characterById(chars, t.characterId.get) if c.isSome: return subjectNamesOf(c.get) # A dangling link cannot exist (the FK and `in-use` forbid it); fall back to "no name" rather # than crash a live connection. return SubjectNames(id: t.characterId.get, descriptive: "", actual: "", owner: 0, characterId: t.characterId) SubjectNames(id: t.id, descriptive: t.descriptiveName, actual: t.actualName, revealAll: t.revealAll, owner: 0, characterId: none(string)) proc nameFor*(n: SubjectNames, player: int, reveals: Reveals): string = ## The name `player` sees for this subject (6.1 `token.name`, `encountered.name`). visibleName(n.descriptive, n.actual, knowsActual(n.owner == player and n.owner > 0, n.revealAll, reveals.isRevealed(player, n.id))) # --------------------------------------------------------------------------------------------------- # Encountered entries (DESIGN 8) proc entryName*(e: EncounteredEntry): string = ## The name this player knows: the actual one once it was revealed, else the descriptive one. if e.actualName.isSome: e.actualName.get else: e.descriptiveName proc newEntry*(entityId: string, n: SubjectNames, knowsActual: bool): EncounteredEntry = ## The snapshot a first sighting records: the names as they are now, and whether the player was ## already allowed to know the actual one (a later reveal fills it in). EncounteredEntry(entityId: entityId, characterId: n.characterId, descriptiveName: n.descriptive, actualName: (if knowsActual: some(n.actual) else: none(string))) proc renamed*(e: EncounteredEntry, descriptive, actual: string): EncounteredEntry = ## After `character.update` or a plain-token rename: the snapshot follows the subject. A player who ## was never told the actual name stays not-told. result = e result.descriptiveName = descriptive if e.actualName.isSome: result.actualName = some(actual) proc revealed*(e: EncounteredEntry, actual: string): EncounteredEntry = result = e result.actualName = some(actual) # --------------------------------------------------------------------------------------------------- # Persistence (write-through; GM authoring runs in the caller's FULL transaction, 4.4/Q12) proc insertRow(db: DbConn, c: CharacterRec) = db.exec(sql"""INSERT INTO character (id, owner_player_id, descriptive_name, actual_name, reveal_all, props_public, props_owner, props_gm, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""", c.id, c.owner, c.descriptiveName, c.actualName, (if c.revealAll: 1 else: 0), $c.props[pbPublic], $c.props[pbOwner], $c.props[pbGm], now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'")) proc replaceRow(db: DbConn, c: CharacterRec) = db.exec(sql"""UPDATE character SET owner_player_id = ?, descriptive_name = ?, actual_name = ?, reveal_all = ?, props_public = ?, props_owner = ?, props_gm = ? WHERE id = ?""", c.owner, c.descriptiveName, c.actualName, (if c.revealAll: 1 else: 0), $c.props[pbPublic], $c.props[pbOwner], $c.props[pbGm], c.id) proc addCharacter*(db: DbConn, candidate: CharacterRec, takenIds: openArray[string]): tuple[outcome: CharacterOutcome, character: CharacterRec] = ## `character.create`: validates, assigns a fresh id from the shared token/character namespace and ## persists. The caller appends the record to memory after the transaction (4.2 step 6). var stored = normalize(candidate) if not validCharacter(stored): return (coInvalid, stored) stored.id = freshId(takenIds) authoringTransaction(db): insertRow(db, stored) (coOk, stored) proc storeCharacter*(db: DbConn, candidate: CharacterRec): CharacterOutcome = ## `character.update`, `character.reassign`, `name.reveal_all`, `prop.*` on a character: one full ## replacement of the row (GM authoring, FULL), so one change is one transaction. let stored = normalize(candidate) if not validCharacter(stored): return coInvalid authoringTransaction(db): replaceRow(db, stored) coOk proc removeCharacter*(db: DbConn, id: string): bool = var removed = false authoringTransaction(db): removed = db.execAffectedRows(sql"DELETE FROM character WHERE id = ?", id) > 0 removed proc tokensLinkedTo*(tokens: openArray[TokenRec], characterId: string): int = ## `character.remove` is refused with `in-use` while any token still figures the character (6.5). for t in tokens: if t.characterId.isSome and t.characterId.get == characterId: inc result proc transferToGm*(db: DbConn, playerId, gmId: int) = ## `player.remove` (DESIGN 3.2): that player's characters pass to the GM. Runs before the player ## DELETE, because `character.owner_player_id` refuses to dangle (no cascade on purpose). db.exec(sql"UPDATE character SET owner_player_id = ? WHERE owner_player_id = ?", gmId, playerId) proc addReveal*(db: DbConn, player: int, subject: string) = ## One `name_reveal` row; a repeated reveal is a no-op (`ok`, and nothing changes). db.exec(sql"""INSERT OR IGNORE INTO name_reveal (player_id, subject_id, created_at) VALUES (?, ?, ?)""", player, subject, now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'")) proc deleteRevealsOf*(db: DbConn, player: int) = db.exec(sql"DELETE FROM name_reveal WHERE player_id = ?", player) proc deleteRevealsFor*(db: DbConn, subject: string) = ## `character.remove`: the reveal rows of a subject that no longer exists. (Rows of a *token* that ## was removed are left alone: the token id is never reused, so they can never be read again, and ## keeping them costs one row.) db.exec(sql"DELETE FROM name_reveal WHERE subject_id = ?", subject) proc writeEncountered*(db: DbConn, player: int, e: EncounteredEntry) = ## One `encountered` row per (player, token), upserted: the snapshot is a small value, not a log. db.exec(sql"""INSERT INTO encountered (player_id, entity_id, character_id, descriptive_name, actual_name, created_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (player_id, entity_id) DO UPDATE SET character_id = excluded.character_id, descriptive_name = excluded.descriptive_name, actual_name = excluded.actual_name""", player, e.entityId, (if e.characterId.isSome: e.characterId.get else: ""), e.descriptiveName, (if e.actualName.isSome: e.actualName.get else: ""), now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'")) proc deleteEncountered*(db: DbConn, player: int, entityId: string): bool = db.execAffectedRows(sql"DELETE FROM encountered WHERE player_id = ? AND entity_id = ?", player, entityId) > 0 proc renameEncountered*(db: DbConn, characterId: string, descriptive, actual: string) = ## `character.update`: every snapshot of this character follows the new names. A player who was ## never told the actual name keeps not knowing it (an unknown actual name is stored as `''`). db.exec(sql"""UPDATE encountered SET descriptive_name = ? WHERE character_id = ?""", descriptive, characterId) db.exec(sql"""UPDATE encountered SET actual_name = ? WHERE character_id = ? AND actual_name <> ''""", actual, characterId) proc revealEncountered*(db: DbConn, characterId: string, actual: string) = db.exec(sql"UPDATE encountered SET actual_name = ? WHERE character_id = ?", actual, characterId) proc revealEncounteredToken*(db: DbConn, entityId: string, actual: string) = db.exec(sql"UPDATE encountered SET actual_name = ? WHERE entity_id = ?", actual, entityId) proc renameEncounteredToken*(db: DbConn, entityId, descriptive, actual: string) = db.exec(sql"UPDATE encountered SET descriptive_name = ? WHERE entity_id = ?", descriptive, entityId) db.exec(sql"""UPDATE encountered SET actual_name = ? WHERE entity_id = ? AND actual_name <> ''""", actual, entityId) # --------------------------------------------------------------------------------------------------- # Loading (4.4 startup: load everything into memory once) proc parseObject(s: string): JsonNode = try: result = parseJson(s) except CatchableError: result = newJObject() if result.isNil or result.kind != JObject: result = newJObject() proc rowToCharacter(row: Row): CharacterRec = var p = newProps() p[pbPublic] = parseObject(row[5]) p[pbOwner] = parseObject(row[6]) p[pbGm] = parseObject(row[7]) CharacterRec(id: row[0], owner: parseInt(row[1]), descriptiveName: row[2], actualName: row[3], revealAll: row[4] == "1", props: p) proc loadCharacters*(db: DbConn): seq[CharacterRec] = ## Every character, in creation order (rowid), which is the order egress walks them. for row in db.getAllRows(sql""" SELECT id, owner_player_id, descriptive_name, actual_name, reveal_all, props_public, props_owner, props_gm FROM character ORDER BY rowid"""): result.add rowToCharacter(row) proc loadReveals*(db: DbConn): Reveals = for row in db.getAllRows(sql"SELECT player_id, subject_id FROM name_reveal"): result.pairs.incl (parseInt(row[0]), row[1]) proc loadEncountered*(db: DbConn): Encountered = ## Every entry, in creation order: the order a player's `encountered full` list arrives in. for row in db.getAllRows(sql""" SELECT player_id, entity_id, character_id, descriptive_name, actual_name FROM encountered ORDER BY rowid"""): let player = parseInt(row[0]) result.mgetOrPut(player, initTable[string, EncounteredEntry]())[row[1]] = EncounteredEntry(entityId: row[1], characterId: (if row[2].len == 0: none(string) else: some(row[2])), descriptiveName: row[3], actualName: (if row[4].len == 0: none(string) else: some(row[4])))