Files
FFF_vtt_frozen/server/explored.nim
T
SirStone 22014a36dc server: the chunked explored store (#21)
Migration step 5 creates explored_chunk: one 512-byte bitmap per (player, scene, 64x64-cell
chunk), both FKs cascading. server/explored.nim owns the format (row-major, LSB-first bits),
dirty-chunk detection, the upsert and the startup restore. tests/texplored.nim pins the layout,
the whole-chunk encoding, the upsert replacement, the per-player keying, the restore and the
write cost (0.015 ms avg / 0.035 ms p99); tests/tdb.nim covers step 5 and a schema-4 fixture.
2026-11-15 09:58:16 +01:00

151 lines
7.0 KiB
Nim

## Chunked explored persistence (DESIGN 4.4, 8; M3 slice 6, issue #21). The in-memory explored set
## lives in vision.PlayerVision; this module owns its shape on disk and nothing else: no locking, no
## wire shapes, no mutations.
##
## Format [FIXED (owner-delegated), #21]: one row per (player, scene, chunk) in `explored_chunk`
## (migration step 5). A chunk is 64x64 cells = 512 B, exactly DESIGN 4.4's size: the v1 scene is
## 4096 px / 32 px = 128x128 cells, so 2x2 chunk rows hold a whole map, and a 16384 px map is
## 8x8. Bit layout is pinned: row-major inside the chunk, least-significant bit first, so cell
## (cx, cy) is bit `(cy mod 64) * 64 + (cx mod 64)`, i.e. byte `bit div 8`, mask `1 shl (bit mod 8)`.
## Little-endian bits are what a future client-side or tool-side reader will guess from the byte
## stream; the layout test pins it so a refactor cannot silently swap axes.
##
## Write policy: only the chunks a mutation dirtied. A dirty chunk is encoded from the *whole*
## explored set (a bitmap is a value, not a delta: writing just the new cells would erase the rest).
## Durability is NORMAL (Q12): explored is derived and monotone, unlike GM-authored content, and the
## caller puts these upserts in the mutation's transaction (4.2 step 6) so an ack never precedes the
## cells it reports.
##
## Load: every chunk row of the scene goes back into its player's set at startup (4.4). Polygons are
## not stored (they are recomputed, 8), so a restored player starts with its explored history and no
## sight until the next refresh.
import std/[sets, strutils, tables]
import db_connector/db_sqlite
import vision, world
const
ChunkCells* = 64
## Cells per chunk side (DESIGN 4.4: "e.g. 64x64 cells = 512 B").
ChunkBytes* = ChunkCells * ChunkCells div 8
## 512 B per chunk.
type
Chunk* = object
## One dirty chunk ready to upsert: the player it belongs to, its chunk coordinates and the
## 512-byte bitmap. `playerId` rides along so a mutation can collect chunks for several players
## (a wall change refreshes everyone) and write them in one statement loop.
playerId*: int
cx*, cy*: int
bits*: seq[byte]
# ---------------------------------------------------------------------------------------------------
# Geometry of a chunk
proc chunkCoord*(cell: int): int {.inline.} =
## The chunk coordinate of a cell coordinate (a cell is not a chunk: 64 cells per chunk).
cell div ChunkCells
proc chunkCols*(sc: SceneRec): int =
max(1, (sc.cols + ChunkCells - 1) div ChunkCells)
proc chunkRows*(sc: SceneRec): int =
max(1, (sc.rows + ChunkCells - 1) div ChunkCells)
proc bitOf*(cx, cy: int): int {.inline.} =
## The pinned bit position of a cell inside its chunk (row-major, LSB first).
((cy mod ChunkCells) * ChunkCells) + (cx mod ChunkCells)
# ---------------------------------------------------------------------------------------------------
# Encode / decode
proc encodeChunk*(sc: SceneRec, explored: var HashSet[int], ccx, ccy: int): seq[byte] =
## The whole 512-byte bitmap of one chunk. Cells outside the scene stay 0 (the last chunk row or
## column of a map whose size is not a multiple of 64 is partial).
result = newSeq[byte](ChunkBytes)
let cols = sc.cols
let x0 = ccx * ChunkCells
let y0 = ccy * ChunkCells
for ly in 0 ..< ChunkCells:
let cy = y0 + ly
if cy >= sc.rows: break
for lx in 0 ..< ChunkCells:
let cx = x0 + lx
if cx >= cols: break
if sc.cellIndex(cx, cy) in explored:
let bit = bitOf(cx, cy)
result[bit shr 3] = result[bit shr 3] or byte(1 shl (bit and 7))
proc decodeChunk*(sc: SceneRec, ccx, ccy: int, bits: openArray[byte]): seq[int] =
## Cell indices (`cy * cols + cx`) a chunk bitmap holds, skipping anything outside the scene and
## any bit a short row cannot hold (defensive: a hand-edited DB must not crash the server).
let cols = sc.cols
for ly in 0 ..< ChunkCells:
let cy = ccy * ChunkCells + ly
if cy >= sc.rows: break
for lx in 0 ..< ChunkCells:
let cx = ccx * ChunkCells + lx
if cx >= cols: break
let bit = bitOf(cx, cy)
if bit shr 3 >= bits.len: continue
if (bits[bit shr 3] and byte(1 shl (bit and 7))) != 0:
result.add sc.cellIndex(cx, cy)
# ---------------------------------------------------------------------------------------------------
# Dirty chunks of one mutation
proc dirtyChunks*(sc: SceneRec, playerId: int, explored: var HashSet[int],
cells: openArray[(int, int)]): seq[Chunk] =
## One chunk per distinct chunk coordinate touched by `cells` (the mutation's fresh cells), each
## encoded from the whole explored set. Caller holds the lock and has already refreshed the vision.
var seen = initHashSet[int]()
for (cx, cy) in cells:
if cx < 0 or cy < 0 or cx >= sc.cols or cy >= sc.rows: continue
let ccx = chunkCoord(cx)
let ccy = chunkCoord(cy)
let key = ccy * sc.chunkCols + ccx
if key in seen: continue
seen.incl key
result.add Chunk(playerId: playerId, cx: ccx, cy: ccy,
bits: encodeChunk(sc, explored, ccx, ccy))
# ---------------------------------------------------------------------------------------------------
# Store and load
const UpsertSql = """INSERT INTO explored_chunk (player_id, scene_id, cx, cy, bits)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(player_id, scene_id, cx, cy) DO UPDATE SET bits = excluded.bits"""
## db_connector's exec() inlines its arguments as SQL text, so a BLOB cannot ride that path; the
## prepared form binds a real blob (last argument is openArray[byte]).
proc writeChunks*(db: DbConn, sceneId: int, chunks: openArray[Chunk]): int =
## Upserts every dirty chunk. No transaction control: the caller wraps this in the mutation's
## transaction (4.2 step 6). Returns how many rows were written.
if chunks.len == 0: return 0
let ps = db.prepare(UpsertSql)
try:
for c in chunks:
db.exec(ps, c.playerId, sceneId, c.cx, c.cy, c.bits)
inc result
finally:
finalize(ps)
proc toBytes(s: string): seq[byte] =
## A stored BLOB comes back through getAllRows as a raw byte string (db_connector copies SQLITE_BLOB
## bytes straight into the Nim string); decode wants bytes.
result = newSeq[byte](s.len)
if s.len > 0: copyMem(addr result[0], unsafeAddr s[0], s.len)
proc restore*(db: DbConn, sc: SceneRec): Table[int, PlayerVision] =
## Startup (4.4): every stored chunk of the scene back into its player's explored set. A player
## with no chunks gets no entry at all (its sight state is created on first use, as in slice 5).
for row in db.getAllRows(sql"""
SELECT player_id, cx, cy, bits FROM explored_chunk WHERE scene_id = ?""", sc.id):
let pid = parseInt(row[0])
let cells = decodeChunk(sc, parseInt(row[1]), parseInt(row[2]), toBytes(row[3]))
for idx in cells:
result.mgetOrPut(pid, PlayerVision()).explored.incl idx
proc chunkCount*(db: DbConn, sceneId: int): int =
## How many rows the scene's explored stores occupy: an O(1) startup log number (11.3).
parseInt(db.getValue(sql"SELECT count(*) FROM explored_chunk WHERE scene_id = ?", sceneId))