## Tokens: the map figures (DESIGN 3.1, 4.1, 4.4, 6.1, 8; M3 slice 5, issue #20). The wire and the ## client say "token"; the DB table is `entity` (4.4's schema sketch), because the model is the FFF ## seam of section 9. In-memory authoritative state, SQLite write-through: rows are read once at ## startup (`loadTokens`) and never queried at runtime for reads. ## ## Ids (DESIGN 8, FIXED #3): random opaque 12 characters from `[A-Za-z0-9_-]`, from the OS CSPRNG, ## unique game-wide (not per scene) and collision-checked on create. Counted ids would leak hidden ## tokens through the gaps of the numbers a player does see. ## ## Scope of this slice (issue #20): plain tokens only. The character link, the name-reveal machinery ## and the three property buckets are slices 7-8 (#22, #23), and the per-token size is #4's ## `token.resize` (slice 7): a token's effective radius is always the scene's `token_radius_default` ## here, so a `radius` field on the wire intents is refused `invalid` rather than silently dropped. ## ## Owner (`entity.owner_player_id`) is the token *controller* (DESIGN 8: independent of any character ## owner). `GmControlled` (0) is SQL NULL; player ids start at 1. A controller that is the GM's own ## player id is stored as GM-controlled, so "the GM controls it" has one representation in memory and ## on the wire (`controller: null`). ## ## Persistence order (4.2 step 6): the row is written first and memory is updated only after the ## transaction, so a failed write leaves memory and DB identical. GM authoring (create/update/remove) ## runs with `synchronous=FULL` (Q12); a move - player or GM drag - runs with `NORMAL`, like explored ## cells: a position is not authored content. This module does no locking: the caller holds the ## server's global lock (4.3). import std/[json, options, strutils, times, unicode] import db_connector/db_sqlite import crypto, geometry, world import std/math except round type TokenRec* = object id*: string scene*: int kind*: string ## free string (pc, npc, item...); GM-only on the wire (6.1 leak note 1) descriptiveName*: string actualName*: string pos*: Vec radius*: Option[float] ## px; none = the scene default. Slice 7 (#4) fills this. owner*: int ## controller: player id, GmControlled = the GM gmOnly*: bool visionRadius*: Option[float] ## px; none = the scene default (Q7, the 5.5 step cap) flags*: JsonNode ## JObject, never nil; the `vision` flag lives here (DESIGN 8) prev*: Vec ## position before the most recent move/push (door-push side, 5.5) hasPrev*: bool TokenOutcome* = enum toOk toInvalid ## field/geometry semantics: `invalid` toNotFound ## no such token (or controller player): `not-found` TokenPatch* = object ## The `token.update` fields this slice can honour (6.1); none = keep the stored value. kind*: Option[string] descriptiveName*: Option[string] actualName*: Option[string] controller*: Option[int] ## GmControlled = GM gmOnly*: Option[bool] flags*: Option[JsonNode] visionRadius*: Option[Option[float]] const TokenIdLength* = 12 TokenIdAlphabet* = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-" ## 64 symbols = 6 bits per character, 72 bits per id (DESIGN 8). MaxNameLen* = 64 ## DESIGN 6.5: character and plain-token names are 1 to 64 code points. MaxKindLen* = 32 GmControlled* = 0 ## TokenRec.owner value for "no controller" (SQL NULL). Player ids are >= 1 (auth.nim). # --------------------------------------------------------------------------------------------------- # Field parsing and validation (DESIGN 6.1 field notes, 6.5) proc hasControlChar(s: string): bool = for r in s.runes: if r.int < 0x20 or r.int == 0x7f: return true proc validText*(s: string, maxLen: int): bool = ## Trimmed, 1..maxLen code points, no control characters (DESIGN 6.5). NFC normalisation and the ## per-player uniqueness rules arrive with the name machinery of slice 8 (#23). s.len > 0 and s == s.strip and s.runeLen in 1 .. maxLen and not hasControlChar(s) proc validName*(s: string): bool = validText(s, MaxNameLen) proc validKind*(s: string): bool = validText(s, MaxKindLen) proc parseVisionRadius*(node: JsonNode): Option[Option[float]] = ## `vision_radius`: a positive finite number, or null/absent (= the scene default). ## `some(none(float))` = explicitly cleared; `some(some(r))` = set; none = present but invalid. if node.isNil or node.kind == JNull: return some(none(float)) var f: float case node.kind of JInt: f = float(node.getInt) of JFloat: f = node.getFloat else: return none(Option[float]) if classify(f) in {fcNan, fcInf, fcNegInf} or f <= 0: return none(Option[float]) some(some(f)) proc newTokenId*(): string = ## 12 CSPRNG characters from a 64-symbol alphabet (uniform: 256 = 4 x 64, no rejection needed). result = newStringOfCap(TokenIdLength) while result.len < TokenIdLength: for b in randomBytes(TokenIdLength * 2): if result.len == TokenIdLength: break result.add TokenIdAlphabet[int(b) and 0x3f] proc freshId*(taken: openArray[string]): string = ## An id that collides with no token in `taken` (DESIGN 8: the server checks on create). while true: result = newTokenId() var clash = false for id in taken: if id == result: clash = true break if not clash: return proc normalize*(t: TokenRec): TokenRec = ## Stored-token invariants: `flags` is an object, and a controller never becomes a negative id. result = t if result.flags.isNil or result.flags.kind != JObject: result.flags = newJObject() if result.owner < 0: result.owner = GmControlled proc effectiveRadius*(sc: SceneRec, t: TokenRec): float = ## DESIGN 5.6/#4: the entity radius if set, else the scene's `token_radius_default`. if t.radius.isSome: t.radius.get else: sc.tokenRadiusDefault proc hasVision*(t: TokenRec): bool = ## Q7: the `vision` flag (DESIGN 8), carried in `flags`. Only these tokens get a polygon (4.1). t.flags.kind == JObject and t.flags.hasKey("vision") and t.flags["vision"].kind == JBool and t.flags["vision"].getBool proc visionRange*(sc: SceneRec, t: TokenRec): float = ## The vision range and the player step cap (5.5): the token's own radius when it has vision and ## sets one, else the scene default. if t.hasVision and t.visionRadius.isSome and t.visionRadius.get > 0: t.visionRadius.get else: sc.visionRadiusDefault proc inBounds(sc: SceneRec, p: Vec): bool = p.x >= 0 and p.y >= 0 and p.x <= sc.w and p.y <= sc.h # written so NaN fails proc validPlacement*(sc: SceneRec, pos: Vec): bool = inBounds(sc, pos) proc validToken*(sc: SceneRec, t: TokenRec): bool = validName(t.descriptiveName) and validName(t.actualName) and validKind(t.kind) and validPlacement(sc, t.pos) proc patched*(t: TokenRec, patch: TokenPatch): TokenRec = result = t if patch.kind.isSome: result.kind = patch.kind.get if patch.descriptiveName.isSome: result.descriptiveName = patch.descriptiveName.get if patch.actualName.isSome: result.actualName = patch.actualName.get if patch.controller.isSome: result.owner = patch.controller.get if patch.gmOnly.isSome: result.gmOnly = patch.gmOnly.get if patch.flags.isSome: result.flags = patch.flags.get if patch.visionRadius.isSome: result.visionRadius = patch.visionRadius.get result = normalize(result) # --------------------------------------------------------------------------------------------------- # Persistence (write-through). db_connector quotes every argument as text, so a SQL NULL cannot ride # an argument: the three nullable columns are emitted as literals built from numbers only (never from # user text), and every string value still goes through a `?` argument. proc sqlLit(v: Option[float]): string = if v.isSome: $v.get else: "NULL" proc sqlLitOwner(owner: int): string = if owner == GmControlled: "NULL" else: $owner proc insertRow(db: DbConn, t: TokenRec) = db.exec(sql("INSERT INTO entity (id, scene_id, kind, descriptive_name, actual_name, x, y, radius," & " owner_player_id, gm_only, vision_radius, flags, created_at) VALUES (" & "?, ?, ?, ?, ?, ?, ?, " & sqlLit(t.radius) & ", " & sqlLitOwner(t.owner) & ", ?, " & sqlLit(t.visionRadius) & ", ?, ?)"), t.id, t.scene, t.kind, t.descriptiveName, t.actualName, $t.pos.x, $t.pos.y, (if t.gmOnly: 1 else: 0), $t.flags, now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'")) proc replaceRow(db: DbConn, t: TokenRec) = db.exec(sql("UPDATE entity SET kind = ?, descriptive_name = ?, actual_name = ?, x = ?, y = ?," & " radius = " & sqlLit(t.radius) & ", owner_player_id = " & sqlLitOwner(t.owner) & ", gm_only = ?, vision_radius = " & sqlLit(t.visionRadius) & ", flags = ?" & " WHERE id = ?"), t.kind, t.descriptiveName, t.actualName, $t.pos.x, $t.pos.y, (if t.gmOnly: 1 else: 0), $t.flags, t.id) proc addToken*(db: DbConn, sc: SceneRec, candidate: TokenRec, takenIds: openArray[string]): tuple[outcome: TokenOutcome, token: TokenRec] = ## `token.create`: validates, assigns a fresh id, persists. The caller appends the returned record ## to the in-memory list after the transaction (4.2). var stored = normalize(candidate) stored.scene = sc.id if not validToken(sc, stored): return (toInvalid, stored) stored.id = freshId(takenIds) authoringTransaction(db): insertRow(db, stored) (toOk, stored) proc storeToken*(db: DbConn, sc: SceneRec, candidate: TokenRec): TokenOutcome = ## `token.update`: full replacement of the patched row (GM authoring, FULL). if not validToken(sc, candidate): return toInvalid var stored = normalize(candidate) authoringTransaction(db): replaceRow(db, stored) toOk proc writePosition*(db: DbConn, t: TokenRec): bool = ## One UPSERT of x,y (DESIGN 4.4). NORMAL durability: a position is not authored content (Q12). db.execAffectedRows(sql"UPDATE entity SET x = ?, y = ? WHERE id = ?", $t.pos.x, $t.pos.y, t.id) > 0 proc removeToken*(db: DbConn, id: string): bool = var removed = false authoringTransaction(db): removed = db.execAffectedRows(sql"DELETE FROM entity WHERE id = ?", id) > 0 removed proc clearOwnership*(db: DbConn, playerId: int) = ## player.remove (DESIGN 3.2): that player's controlled tokens pass to the GM. The FK's ON DELETE ## SET NULL does the same on the DELETE; this keeps an in-memory transfer explicit. db.exec(sql"UPDATE entity SET owner_player_id = NULL WHERE owner_player_id = ?", playerId) # --------------------------------------------------------------------------------------------------- # Loading (4.4 startup: load everything into memory once) proc optFloat(s: string): Option[float] = if s.len == 0: none(float) else: some(parseFloat(s)) proc rowToToken(row: Row): TokenRec = var flags: JsonNode try: flags = parseJson(row[11]) except CatchableError: flags = newJObject() TokenRec(id: row[0], scene: parseInt(row[1]), kind: row[2], descriptiveName: row[3], actualName: row[4], pos: (parseFloat(row[5]), parseFloat(row[6])), radius: optFloat(row[7]), owner: (if row[8].len == 0: GmControlled else: parseInt(row[8])), gmOnly: row[9] == "1", visionRadius: optFloat(row[10]), flags: flags) proc loadTokens*(db: DbConn, sceneId = DefaultSceneId): seq[TokenRec] = ## Every token of the scene, in creation order (rowid), which is the order egress walks. for row in db.getAllRows(sql""" SELECT id, scene_id, kind, descriptive_name, actual_name, x, y, radius, owner_player_id, gm_only, vision_radius, flags FROM entity WHERE scene_id = ? ORDER BY rowid""", sceneId): result.add rowToToken(row) proc tokenIndex*(tokens: openArray[TokenRec], id: string): Option[int] = for i, t in tokens: if t.id == id: return some(i) proc tokenById*(tokens: openArray[TokenRec], id: string): Option[TokenRec] = let i = tokenIndex(tokens, id) if i.isSome: return some(tokens[i.get])