- door.set: opening a secret or locked door is invalid; closing either is allowed; a fixed window/non-door still has no open state. - new tools/doors.test.mjs: two fresh servers, one identical script, three equivalence pairs (secret/wall, secret+locked/wall, locked/closed door), canonicalised frame + full per-player tile sweeps, an open-door positive control and a pinned zero-thickness close-push. - secretgap fault hook (sight-only) makes the pair fail as exactly SECRETGAP; the clean pair passes and the shipped binary carries no fault hook. - docs/TESTING.md T2/T17 and the door-equivalence/10.3 sections: built. Ref #56
583 lines
26 KiB
Nim
583 lines
26 KiB
Nim
## Scene and wall state: the authoring half of the world (DESIGN 3.1, 4.1, 4.2, 4.4, 6.1, 8;
|
|
## M3 slice 4, issue #19). In-memory authoritative state, SQLite as write-through persistence: rows
|
|
## are read once at startup (`loadScene`) and never queried at runtime for reads.
|
|
##
|
|
## Walls (DESIGN 8, FIXED #3): per-scene ids from `scene.next_wall_id`, monotonic and never reused
|
|
## (a removal leaves the counter alone). Identity is `(scene, id)` in the DB, in memory and on the
|
|
## wire. Today a wall's sight/movement behaviour is still `blocks = not (door and open)` in
|
|
## geometry.Wall; the stored switches (`blocks_sight`, `blocks_movement`, `sight_dir`) gain their
|
|
## behaviour in the window/one-way rounds (#57/#58). `flags` is a free JSON object the server never
|
|
## interprets.
|
|
##
|
|
## Wire payload shapes are DESIGN 6.1; the parts it leaves open are fixed here (recorded FIXED
|
|
## owner-delegated, #19, in DESIGN 6.1/14):
|
|
## - `scene` is an integer id; in v1 it is always the one seeded scene (id 1), and any other value
|
|
## is `not-found` (no existence oracle either way: only the GM can send these intents).
|
|
## - `scene.set` (slice 10, #25): the patch rules of 6.1 ("Scene payload rules"); `w`, `h`,
|
|
## `tile_size`, `cell` and `art_version` are not patch fields. `patched`/`writeSceneRow` are pure
|
|
## and transaction-free so main.nim can commit the scene row with the tokens it resized.
|
|
## - `wall.add`/`wall.update`: either a 5.8 preset or raw switches, never both; `resolveWall` is
|
|
## the one expand-and-validate path, so a preset never touches geometry and an impossible
|
|
## switch set is `invalid` at every entry point. A raw create starts from the `wall` defaults;
|
|
## a raw update patches only the switches it names; `{door:false}` closes and de-secrets.
|
|
## - `wall.update` patches only what it names (geometry, the switches except `open`, `label`,
|
|
## `flags`); `open` belongs to `door.set`, so an `open` field here is an unknown field and is
|
|
## ignored, and at least one patch field is required, else `invalid`.
|
|
## - `a != b` (a zero-length wall is refused) and both endpoints inside `[0,w] x [0,h]`.
|
|
## - `flags` must be a JSON object; omitted = `{}`. Coordinates must be finite numbers.
|
|
##
|
|
## Persistence order (4.2 step 6): a wall write runs in one transaction with `synchronous=FULL`
|
|
## around it (Q12 FIXED: GM authoring is the expensive-to-lose data) and the in-memory state is
|
|
## updated only after COMMIT, so a failing write leaves memory and DB identical. This module does
|
|
## no locking: the caller holds the global lock (4.3).
|
|
import std/[json, math, options, strutils]
|
|
import db_connector/db_sqlite
|
|
import geometry, text
|
|
|
|
type
|
|
WallPosition* = enum
|
|
wpCenter = "center"
|
|
wpLeft = "left"
|
|
wpRight = "right"
|
|
|
|
SightDir* = enum
|
|
sdBoth = "both"
|
|
sdLeft = "left"
|
|
sdRight = "right"
|
|
|
|
Preset* = enum
|
|
## The four 5.8 presets. A preset is a named switch set, never storage: `expandPreset` turns it
|
|
## into switches before the one validation path runs (DESIGN 5.8, 6.1).
|
|
pwWall = "wall"
|
|
pwDoor = "door"
|
|
pwWindow = "window"
|
|
pwOneWay = "one_way"
|
|
|
|
WallSwitches* = object
|
|
## The raw switches a payload names. A field that is `none` is not patched, which is what makes
|
|
## a raw-switch `wall.update` patch-only and a raw-switch `wall.add` start from the `wall`
|
|
## defaults (DESIGN 6.1). `open` is collected only for `wall.add`; on an update it is an
|
|
## unknown field and `door.set` owns it.
|
|
blocksSight*, blocksMovement*, playerMarker*: Option[bool]
|
|
door*, open*, secret*, locked*: Option[bool]
|
|
sightDir*: Option[SightDir]
|
|
|
|
WallRec* = object
|
|
## The typed wall record of DESIGN 8. Every field is a column; `kind` is never stored and is
|
|
## derived from the switches (`derivedKind`) for the GM's frames (#54).
|
|
id*: int
|
|
a*, b*: Vec
|
|
thickness*: float
|
|
position*: WallPosition
|
|
blocksSight*, blocksMovement*: bool
|
|
sightDir*: SightDir
|
|
playerMarker*: bool
|
|
door*, open*, secret*, locked*: bool
|
|
height*: Option[float] ## metres; none = full height (DESIGN 5.7)
|
|
label*: Option[string] ## GM-only free text, 1..64 code points (DESIGN 5.8)
|
|
flags*: JsonNode ## JObject; never nil for a loaded or created wall
|
|
|
|
SceneRec* = object
|
|
## The one v1 scene (Q3 FIXED). Walls are kept in id order (ids only grow, appends only).
|
|
id*: int
|
|
name*: string
|
|
w*, h*: float
|
|
tileSize*, cell*: int
|
|
gridSize*: float
|
|
visionRadiusDefault*, tokenRadiusDefault*: float
|
|
artVersion*: int
|
|
nextWallId*: int
|
|
extra*: JsonNode
|
|
walls*: seq[WallRec]
|
|
|
|
WallApply* = enum
|
|
## Outcome of a persistent wall operation; main.nim maps it to the 6.5 codes.
|
|
waOk
|
|
waInvalid ## geometry/field semantics: `invalid`
|
|
waNotFound ## no such wall in the scene: `not-found`
|
|
waNotDoor ## door.set on a plain wall: `invalid`
|
|
|
|
WallPatch* = object
|
|
## The updatable fields of `wall.update` (DESIGN 6.1); none = the field keeps its value.
|
|
## `open` is not here: it belongs to `door.set` and is an unknown field in a wall update (#54).
|
|
## `height`/`label` use a separate `clear*` flag because an explicit JSON null is a real patch
|
|
## ("clear it"), while an absent field keeps the stored value.
|
|
a*, b*: Option[Vec]
|
|
thickness*: Option[float]
|
|
position*: Option[WallPosition]
|
|
height*: Option[float]
|
|
clearHeight*: bool
|
|
label*: Option[string]
|
|
clearLabel*: bool
|
|
preset*: Option[Preset] ## replaces the whole switch set; never with a raw switch
|
|
switches*: WallSwitches ## the raw switches present; patches only those
|
|
flags*: Option[JsonNode]
|
|
|
|
ScenePatch* = object
|
|
## `scene.set` (DESIGN 6.1): every field is optional; an absent field keeps its value.
|
|
## `w`, `h`, `tile_size`, `cell` and `art_version` are not patch fields (import is the M6 CLI):
|
|
## they are unknown fields and ignored (6.2), so a patch with only one of them has no field at
|
|
## all and is `invalid`.
|
|
name*: Option[string]
|
|
gridSize*: Option[float]
|
|
visionRadiusDefault*: Option[float]
|
|
tokenRadiusDefault*: Option[float]
|
|
extra*: Option[JsonNode]
|
|
|
|
SceneError* = object of CatchableError
|
|
## The DB and this build disagree about the scene (missing seed, unreadable row).
|
|
|
|
const
|
|
DefaultSceneId* = 1
|
|
## The seeded v1 scene (migration step 3). Exactly one scene exists in v1 (Q3).
|
|
WallPositions* = [wpCenter, wpLeft, wpRight]
|
|
SightDirs* = [sdBoth, sdLeft, sdRight]
|
|
Presets* = [pwWall, pwDoor, pwWindow, pwOneWay]
|
|
SceneNameMaxLen* = 64
|
|
## `scene.set.name`: the 6.5 text rule, same 64-code-point bound as character names (#25).
|
|
WallLabelMaxLen* = 64
|
|
## `wall.label`: the 6.5 text rule, 1..64 code points, trimmed, no control characters (#55).
|
|
|
|
proc defaultWall*(a, b: Vec): WallRec =
|
|
## The `wall` preset's switches: both blocks on, both-way sight, no marker, no door settings,
|
|
## zero thickness, centre placement and full height (DESIGN 5.8, 6.1).
|
|
WallRec(a: a, b: b, position: wpCenter, blocksSight: true, blocksMovement: true,
|
|
sightDir: sdBoth, flags: newJObject())
|
|
|
|
proc derivedKind*(w: WallRec): string =
|
|
## The GM-only shape label of DESIGN 5.8, derived in this order and never stored or accepted as
|
|
## input: window, one_way, door, wall, else custom. `secret`/`locked` never change it.
|
|
if not w.blocksSight and w.blocksMovement:
|
|
"window"
|
|
elif w.blocksSight and w.sightDir != sdBoth:
|
|
"one_way"
|
|
elif w.blocksSight and w.blocksMovement and w.door:
|
|
"door"
|
|
elif w.blocksSight and w.blocksMovement and not w.door and w.sightDir == sdBoth:
|
|
"wall"
|
|
else:
|
|
"custom"
|
|
|
|
# ---------------------------------------------------------------------------------------------------
|
|
# The one expand-and-validate path for wall writes (DESIGN 5.8, 6.1 FIXED #49/#55)
|
|
|
|
proc storable*(rec: WallRec): bool =
|
|
## The switch-set invariants of DESIGN 5.8, mirrored by the database CHECKs of db.nim step 8.
|
|
## The caller has already resolved presets and raw patches; this is the last semantic gate
|
|
## before SQLite (which stays the backstop for a write that bypasses the server).
|
|
# `open` without `door` cannot survive the resolve/normalize path (a named `open:true` is refused
|
|
# and a cleared `door` closes the row), so the parity rule lives in the DB CHECK alone.
|
|
if rec.secret and not rec.door: return false
|
|
if rec.locked and not rec.door: return false
|
|
if rec.secret and (rec.open or not rec.blocksSight or not rec.blocksMovement or
|
|
rec.sightDir != sdBoth): return false
|
|
if rec.open and (rec.secret or rec.locked): return false
|
|
if rec.sightDir != sdBoth and not rec.blocksSight: return false
|
|
true
|
|
|
|
proc hasAnySwitch*(sw: WallSwitches): bool =
|
|
## True when the payload named any raw switch (a preset may not appear with one).
|
|
sw.blocksSight.isSome or sw.blocksMovement.isSome or sw.playerMarker.isSome or
|
|
sw.door.isSome or sw.open.isSome or sw.secret.isSome or sw.locked.isSome or
|
|
sw.sightDir.isSome
|
|
|
|
proc expandPreset*(base: WallRec, preset: Preset): WallRec =
|
|
## A preset replaces the whole switch set and touches nothing else: `a`, `b`, thickness,
|
|
## position, height, label and flags are the base's (DESIGN 5.8 table, 6.1). `window` is the
|
|
## opening window (door set, closed) with the marker on; the fixed window is `door` turned off.
|
|
result = base
|
|
case preset
|
|
of pwWall, pwDoor:
|
|
result.blocksSight = true
|
|
result.blocksMovement = true
|
|
result.sightDir = sdBoth
|
|
of pwWindow:
|
|
result.blocksSight = false
|
|
result.blocksMovement = true
|
|
result.sightDir = sdBoth
|
|
of pwOneWay:
|
|
result.blocksSight = true
|
|
result.blocksMovement = true
|
|
result.sightDir = sdLeft
|
|
result.playerMarker = preset == pwWindow
|
|
result.door = preset in {pwDoor, pwWindow}
|
|
result.open = false
|
|
result.secret = false
|
|
result.locked = false
|
|
|
|
proc applySwitches(base: WallRec, sw: WallSwitches): Option[WallRec] =
|
|
## A raw-switch write patches only the switches it names. A door-only switch set to true on a
|
|
## non-door is `invalid` (never silently dropped); when the write clears `door`, inherited
|
|
## door-only settings are closed and de-secreted (DESIGN 5.8, 6.1).
|
|
var r = base
|
|
if sw.blocksSight.isSome: r.blocksSight = sw.blocksSight.get
|
|
if sw.blocksMovement.isSome: r.blocksMovement = sw.blocksMovement.get
|
|
if sw.playerMarker.isSome: r.playerMarker = sw.playerMarker.get
|
|
if sw.door.isSome: r.door = sw.door.get
|
|
if sw.open.isSome: r.open = sw.open.get
|
|
if sw.secret.isSome: r.secret = sw.secret.get
|
|
if sw.locked.isSome: r.locked = sw.locked.get
|
|
if sw.sightDir.isSome: r.sightDir = sw.sightDir.get
|
|
if not r.door:
|
|
if sw.open == some(true) or sw.secret == some(true) or sw.locked == some(true):
|
|
return none(WallRec)
|
|
r.open = false
|
|
r.secret = false
|
|
r.locked = false
|
|
some(r)
|
|
|
|
proc resolveWall*(base: WallRec, preset: Option[Preset],
|
|
sw: WallSwitches): Option[WallRec] =
|
|
## THE single path shared by `wall.add`, `wall.update` and the future UVTT importer: a preset is
|
|
## expanded before validation and may not appear with any raw switch; raw switches patch the
|
|
## base; the resulting switch set is then checked by `storable`. Geometry, height and label are
|
|
## validated by `validWall`; a preset never touches them (DESIGN 5.8, 6.1 FIXED #49/#55).
|
|
if preset.isSome:
|
|
if sw.hasAnySwitch: return none(WallRec)
|
|
result = some(expandPreset(base, preset.get))
|
|
else:
|
|
result = applySwitches(base, sw)
|
|
if result.isSome and not storable(result.get): result = none(WallRec)
|
|
|
|
# ---------------------------------------------------------------------------------------------------
|
|
# Field parsing (DESIGN 6.1 field notes: px floats, missing or wrongly typed -> `invalid`)
|
|
|
|
proc parsePosition*(raw: string): Option[WallPosition] =
|
|
for p in WallPositions:
|
|
if $p == raw: return some(p)
|
|
|
|
proc parseSightDir*(raw: string): Option[SightDir] =
|
|
for d in SightDirs:
|
|
if $d == raw: return some(d)
|
|
|
|
proc parsePreset*(raw: string): Option[Preset] =
|
|
for p in Presets:
|
|
if $p == raw: return some(p)
|
|
|
|
proc parseVec*(node: JsonNode): Option[Vec] =
|
|
## `a:[x,y]` / `b:[x,y]`: exactly two finite JSON numbers.
|
|
if node.isNil or node.kind != JArray or node.len != 2: return none(Vec)
|
|
var v: Vec
|
|
for i, field in [node[0], node[1]]:
|
|
var f: float
|
|
case field.kind
|
|
of JInt: f = float(field.getInt)
|
|
of JFloat: f = field.getFloat
|
|
else: return none(Vec)
|
|
if classify(f) in {fcNan, fcInf, fcNegInf}: return none(Vec)
|
|
if i == 0: v.x = f else: v.y = f
|
|
some(v)
|
|
|
|
proc parseFlags*(node: JsonNode): Option[JsonNode] =
|
|
## `flags?`: an object or absent (DESIGN 6.1). A non-object is `invalid`.
|
|
if node.isNil: return some(newJObject())
|
|
if node.kind != JObject: return none(JsonNode)
|
|
some(node)
|
|
|
|
proc fieldOrNull*(env: JsonNode, key: string): JsonNode =
|
|
## `undefined` and `null` are both "field absent" for the wall payloads.
|
|
if env.isNil: return nil
|
|
result = env{key}
|
|
if not result.isNil and result.kind == JNull: result = nil
|
|
|
|
proc parseFinite*(node: JsonNode): Option[float] =
|
|
## One finite JSON number (integers accepted; strings, booleans and null are not numbers).
|
|
if node.isNil: return none(float)
|
|
case node.kind
|
|
of JInt: result = some(float(node.getInt))
|
|
of JFloat:
|
|
let f = node.getFloat
|
|
if classify(f) in {fcNan, fcInf, fcNegInf}: return none(float)
|
|
result = some(f)
|
|
else: discard
|
|
|
|
proc parseScenePatch*(node: JsonNode): Option[ScenePatch] =
|
|
## `scene.set` payload (DESIGN 6.1, slice 10 / #25). At least one patch field is required and a
|
|
## present field must have its own shape: a `null` is a wrong type, not "absent", because the
|
|
## field was declared (the same reading `token.resize` gives a required `radius`).
|
|
## name: the 6.5 text rule (1..64 code points, no control characters)
|
|
## grid_size: a finite number >= 0 (0 = no grid)
|
|
## vision_radius_default, token_radius_default: a finite number > 0; no upper cap (#4, #25)
|
|
## extra: a JSON object, stored verbatim and never interpreted
|
|
if node.isNil or node.kind != JObject: return none(ScenePatch)
|
|
var p: ScenePatch
|
|
var any = false
|
|
if node.hasKey("name"):
|
|
let v = node["name"]
|
|
if v.kind != JString or not validText(v.getStr, SceneNameMaxLen): return none(ScenePatch)
|
|
p.name = some(v.getStr)
|
|
any = true
|
|
if node.hasKey("grid_size"):
|
|
let v = parseFinite(node["grid_size"])
|
|
if v.isNone or v.get < 0: return none(ScenePatch)
|
|
p.gridSize = v
|
|
any = true
|
|
if node.hasKey("vision_radius_default"):
|
|
let v = parseFinite(node["vision_radius_default"])
|
|
if v.isNone or v.get <= 0: return none(ScenePatch)
|
|
p.visionRadiusDefault = v
|
|
any = true
|
|
if node.hasKey("token_radius_default"):
|
|
let v = parseFinite(node["token_radius_default"])
|
|
if v.isNone or v.get <= 0: return none(ScenePatch)
|
|
p.tokenRadiusDefault = v
|
|
any = true
|
|
if node.hasKey("extra"):
|
|
let v = node["extra"]
|
|
if v.kind != JObject: return none(ScenePatch)
|
|
p.extra = some(v)
|
|
any = true
|
|
if not any: return none(ScenePatch)
|
|
some(p)
|
|
|
|
proc patched*(sc: SceneRec, patch: ScenePatch): SceneRec =
|
|
## The scene as `scene.set` would store it. The caller validates the result by construction: every
|
|
## patch field was already type- and range-checked by `parseScenePatch`.
|
|
result = sc
|
|
if patch.name.isSome: result.name = patch.name.get
|
|
if patch.gridSize.isSome: result.gridSize = patch.gridSize.get
|
|
if patch.visionRadiusDefault.isSome: result.visionRadiusDefault = patch.visionRadiusDefault.get
|
|
if patch.tokenRadiusDefault.isSome: result.tokenRadiusDefault = patch.tokenRadiusDefault.get
|
|
if patch.extra.isSome: result.extra = patch.extra.get
|
|
|
|
# ---------------------------------------------------------------------------------------------------
|
|
# In-memory rules (pure): validation, lookup and the id allocator
|
|
|
|
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 validWall*(sc: SceneRec, rec: WallRec): bool =
|
|
## DESIGN 6.1 `wall.*` validation: `a != b`, both endpoints in bounds, the geometry ranges, the
|
|
## 6.5 text rule for `label` and a switch set the schema can store. `flags` is checked by the
|
|
## parser, so a `WallRec` can only carry a valid one.
|
|
(rec.a.x != rec.b.x or rec.a.y != rec.b.y) and inBounds(sc, rec.a) and inBounds(sc, rec.b) and
|
|
rec.thickness >= 0 and rec.thickness <= 256 and
|
|
(rec.height.isNone or (rec.height.get > 0 and rec.height.get <= 100)) and
|
|
(rec.label.isNone or validText(rec.label.get, WallLabelMaxLen)) and
|
|
storable(rec)
|
|
|
|
proc normalize*(rec: WallRec): WallRec =
|
|
## A non-door stores no door-only settings (clearing `door` closes and de-secrets), and a missing
|
|
## flags object becomes `{}` (DESIGN 6.1).
|
|
result = rec
|
|
if not result.door:
|
|
result.open = false
|
|
result.secret = false
|
|
result.locked = false
|
|
if result.flags.isNil: result.flags = newJObject()
|
|
|
|
proc wallIndex*(sc: SceneRec, id: int): Option[int] =
|
|
for i, w in sc.walls:
|
|
if w.id == id: return some(i)
|
|
|
|
proc wallById*(sc: SceneRec, id: int): Option[WallRec] =
|
|
let i = wallIndex(sc, id)
|
|
if i.isSome: return some(sc.walls[i.get])
|
|
|
|
proc patched*(w: WallRec, patch: WallPatch): Option[WallRec] =
|
|
## `wall.update` candidate: the stored row with the patch applied and validated by the same path
|
|
## as `wall.add`. A patch is absolute and only touches what it names; `open` is never here
|
|
## (door.set owns it). `clearHeight`/`clearLabel` are an explicit null, distinct from an absent
|
|
## field. `none` means the resulting switch set is forbidden (DESIGN 5.8, 6.1).
|
|
var base = w
|
|
if patch.a.isSome: base.a = patch.a.get
|
|
if patch.b.isSome: base.b = patch.b.get
|
|
if patch.thickness.isSome: base.thickness = patch.thickness.get
|
|
if patch.position.isSome: base.position = patch.position.get
|
|
if patch.clearHeight: base.height = none(float)
|
|
elif patch.height.isSome: base.height = patch.height
|
|
if patch.clearLabel: base.label = none(string)
|
|
elif patch.label.isSome: base.label = patch.label
|
|
if patch.flags.isSome: base.flags = patch.flags.get
|
|
result = resolveWall(base, patch.preset, patch.switches)
|
|
if result.isSome:
|
|
result = some(normalize(result.get))
|
|
|
|
# ---------------------------------------------------------------------------------------------------
|
|
# Persistence (write-through, synchronous=FULL around the transaction, Q12)
|
|
|
|
proc flagsText(node: JsonNode): string =
|
|
if node.isNil: "{}" else: $node
|
|
|
|
proc sqlLitText*(value: string): string =
|
|
## A SQL text literal (DESIGN 4.4): single quotes doubled. Used for `label`, which is nullable.
|
|
"'" & value.replace("'", "''") & "'"
|
|
|
|
proc sqlLitReal*(value: float): string =
|
|
## A fixed, locale-free SQL number literal. Used for `height`, which is nullable.
|
|
$value
|
|
|
|
proc sqlLitTextOrNull*(value: Option[string]): string =
|
|
if value.isSome: sqlLitText(value.get) else: "NULL"
|
|
|
|
proc sqlLitRealOrNull*(value: Option[float]): string =
|
|
if value.isSome: sqlLitReal(value.get) else: "NULL"
|
|
|
|
template authoringTransaction*(db: DbConn, body: untyped) =
|
|
## GM authoring durability (Q12): `synchronous=FULL` for this transaction, `NORMAL` again
|
|
## afterwards, whether the body succeeded or raised. `PRAGMA synchronous` cannot change inside a
|
|
## transaction, so it brackets BEGIN/COMMIT; a failing body rolls back completely.
|
|
db.exec(sql"PRAGMA synchronous=FULL")
|
|
try:
|
|
db.exec(sql"BEGIN")
|
|
try:
|
|
body
|
|
db.exec(sql"COMMIT")
|
|
except CatchableError:
|
|
try: db.exec(sql"ROLLBACK")
|
|
except CatchableError: discard
|
|
raise
|
|
finally:
|
|
db.exec(sql"PRAGMA synchronous=NORMAL")
|
|
|
|
proc writeSceneRow*(db: DbConn, sc: SceneRec) =
|
|
## The `scene.set` columns, no transaction control: the caller owns the transaction (the scene row
|
|
## and the tokens its default radius resized commit together, #25).
|
|
db.exec(sql"""UPDATE scene SET name = ?, grid_size = ?, vision_radius_default = ?,
|
|
token_radius_default = ?, extra = ? WHERE id = ?""",
|
|
sc.name, $sc.gridSize, $sc.visionRadiusDefault, $sc.tokenRadiusDefault,
|
|
flagsText(sc.extra), sc.id)
|
|
|
|
proc storeScene*(db: DbConn, sc: SceneRec) =
|
|
## `scene.set` alone in memory (tests): one FULL authoring transaction (Q12).
|
|
authoringTransaction(db):
|
|
writeSceneRow(db, sc)
|
|
|
|
proc insertRow(db: DbConn, sceneId: int, w: WallRec) =
|
|
let height = sqlLitRealOrNull(w.height)
|
|
let label = sqlLitTextOrNull(w.label)
|
|
db.exec(sql("INSERT INTO wall (scene_id, id, ax, ay, bx, by, thickness, position, " &
|
|
"blocks_sight, blocks_movement, sight_dir, player_marker, door, open, secret, " &
|
|
"locked, height, label, flags) " &
|
|
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " & height & ", " &
|
|
label & ", ?)"),
|
|
sceneId, w.id, w.a.x, w.a.y, w.b.x, w.b.y, $w.thickness, $w.position,
|
|
(if w.blocksSight: 1 else: 0), (if w.blocksMovement: 1 else: 0), $w.sightDir,
|
|
(if w.playerMarker: 1 else: 0), (if w.door: 1 else: 0), (if w.open: 1 else: 0),
|
|
(if w.secret: 1 else: 0), (if w.locked: 1 else: 0), flagsText(w.flags))
|
|
|
|
proc replaceRow(db: DbConn, sceneId: int, w: WallRec) =
|
|
let height = sqlLitRealOrNull(w.height)
|
|
let label = sqlLitTextOrNull(w.label)
|
|
db.exec(sql("UPDATE wall SET ax = ?, ay = ?, bx = ?, by = ?, thickness = ?, position = ?, " &
|
|
"blocks_sight = ?, blocks_movement = ?, sight_dir = ?, player_marker = ?, " &
|
|
"door = ?, open = ?, secret = ?, locked = ?, height = " & height &
|
|
", label = " & label & ", flags = ? WHERE scene_id = ? AND id = ?"),
|
|
w.a.x, w.a.y, w.b.x, w.b.y, $w.thickness, $w.position,
|
|
(if w.blocksSight: 1 else: 0), (if w.blocksMovement: 1 else: 0), $w.sightDir,
|
|
(if w.playerMarker: 1 else: 0), (if w.door: 1 else: 0), (if w.open: 1 else: 0),
|
|
(if w.secret: 1 else: 0), (if w.locked: 1 else: 0), flagsText(w.flags), sceneId, w.id)
|
|
|
|
proc addWall*(db: DbConn, sc: var SceneRec, rec: WallRec): Option[int] =
|
|
## `wall.add`: assigns the scene's next wall id, persists and then appends to memory.
|
|
## none = invalid geometry (nothing written, nothing applied).
|
|
let candidate = normalize(rec)
|
|
if not validWall(sc, candidate): return none(int)
|
|
var stored = candidate
|
|
stored.id = max(1, sc.nextWallId)
|
|
authoringTransaction(db):
|
|
insertRow(db, sc.id, stored)
|
|
db.exec(sql"UPDATE scene SET next_wall_id = ? WHERE id = ?", stored.id + 1, sc.id)
|
|
sc.walls.add stored
|
|
sc.nextWallId = stored.id + 1
|
|
some(stored.id)
|
|
|
|
proc updateWall*(db: DbConn, sc: var SceneRec, rec: WallRec): WallApply =
|
|
## `wall.update` = full replacement of the patched row (`remove + add` for the 5.5 status rules,
|
|
## which slice 5 re-evaluates). Clearing the door switch closes and de-secrets the wall.
|
|
let idx = wallIndex(sc, rec.id)
|
|
if idx.isNone: return waNotFound
|
|
let stored = normalize(rec)
|
|
if not validWall(sc, stored): return waInvalid
|
|
authoringTransaction(db):
|
|
replaceRow(db, sc.id, stored)
|
|
sc.walls[idx.get] = stored
|
|
waOk
|
|
|
|
proc removeWall*(db: DbConn, sc: var SceneRec, id: int): WallApply =
|
|
## `wall.remove`: the row goes, `next_wall_id` does not move (ids are never reused).
|
|
let idx = wallIndex(sc, id)
|
|
if idx.isNone: return waNotFound
|
|
authoringTransaction(db):
|
|
db.exec(sql"DELETE FROM wall WHERE scene_id = ? AND id = ?", sc.id, id)
|
|
sc.walls.delete idx.get
|
|
waOk
|
|
|
|
proc setDoor*(db: DbConn, sc: var SceneRec, id: int, open: bool): WallApply =
|
|
## `door.set`: only a door has an open state (`invalid` on a plain wall or a fixed window). A
|
|
## secret door is always closed and a locked door only refuses opening, so `open:true` on either
|
|
## is `invalid`; closing either is allowed (it is already closed, DESIGN 5.8, 6.1, #56).
|
|
let idx = wallIndex(sc, id)
|
|
if idx.isNone: return waNotFound
|
|
let current = sc.walls[idx.get]
|
|
if current.door == false: return waNotDoor
|
|
if open and (current.secret or current.locked): return waInvalid
|
|
var stored = current
|
|
stored.open = open
|
|
authoringTransaction(db):
|
|
db.exec(sql"UPDATE wall SET open = ? WHERE scene_id = ? AND id = ?",
|
|
(if open: 1 else: 0), sc.id, id)
|
|
sc.walls[idx.get] = stored
|
|
waOk
|
|
|
|
# ---------------------------------------------------------------------------------------------------
|
|
# Loading (4.4 Startup: load everything into memory once)
|
|
|
|
proc rowToWall(row: Row): WallRec =
|
|
var flags: JsonNode
|
|
try:
|
|
flags = parseJson(row[17])
|
|
except CatchableError:
|
|
flags = newJObject()
|
|
if flags.isNil or flags.kind != JObject: flags = newJObject()
|
|
WallRec(id: parseInt(row[0]),
|
|
a: (parseFloat(row[1]), parseFloat(row[2])),
|
|
b: (parseFloat(row[3]), parseFloat(row[4])),
|
|
thickness: parseFloat(row[5]),
|
|
position: parseEnum[WallPosition](row[6]),
|
|
blocksSight: row[7] == "1",
|
|
blocksMovement: row[8] == "1",
|
|
sightDir: parseEnum[SightDir](row[9]),
|
|
playerMarker: row[10] == "1",
|
|
door: row[11] == "1",
|
|
open: row[12] == "1",
|
|
secret: row[13] == "1",
|
|
locked: row[14] == "1",
|
|
height: (if row[15].len == 0: none(float) else: some(parseFloat(row[15]))),
|
|
label: (if row[16].len == 0: none(string) else: some(row[16])),
|
|
flags: flags)
|
|
|
|
proc loadScene*(db: DbConn, sceneId = DefaultSceneId): Option[SceneRec] =
|
|
## The single scene and its walls, ordered by wall id. none = the scene row is missing (a DB that
|
|
## migration 3 did not seed): startup treats that as fatal.
|
|
for row in db.getAllRows(sql"""
|
|
SELECT id, name, w, h, tile_size, cell, grid_size, vision_radius_default,
|
|
token_radius_default, art_version, next_wall_id, extra
|
|
FROM scene WHERE id = ?""", sceneId):
|
|
var extra: JsonNode
|
|
try:
|
|
extra = parseJson(row[11])
|
|
except CatchableError:
|
|
extra = newJObject()
|
|
if extra.isNil: extra = newJObject()
|
|
result = some(SceneRec(id: parseInt(row[0]), name: row[1],
|
|
w: parseFloat(row[2]), h: parseFloat(row[3]),
|
|
tileSize: parseInt(row[4]), cell: parseInt(row[5]),
|
|
gridSize: parseFloat(row[6]),
|
|
visionRadiusDefault: parseFloat(row[7]),
|
|
tokenRadiusDefault: parseFloat(row[8]),
|
|
artVersion: parseInt(row[9]),
|
|
nextWallId: parseInt(row[10]),
|
|
extra: extra))
|
|
if result.isNone: return
|
|
var sc = result.get
|
|
for row in db.getAllRows(sql"""
|
|
SELECT id, ax, ay, bx, by, thickness, position, blocks_sight, blocks_movement, sight_dir,
|
|
player_marker, door, open, secret, locked, height, label, flags
|
|
FROM wall WHERE scene_id = ? ORDER BY id""", sceneId):
|
|
sc.walls.add rowToWall(row)
|
|
result = some(sc)
|
|
|
|
proc sceneCount*(db: DbConn): int =
|
|
parseInt(db.getValue(sql"SELECT count(*) FROM scene"))
|