## 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] BitMap* = object ## The explored grid as one bit per cell, row-major from the world origin (`cy * cols + cx`). ## This is the tile gate's read-side snapshot (issue #65): the gate asks "is this cell explored?" ## for a handful of indices instead of walking a `HashSet` under the global lock. The on-disk ## chunk bits use the same least-significant-bit-first convention, but per 64x64 chunk; this is ## the whole map flattened, which is what the gate's index arithmetic wants. cols*: int rows*: int bits*: seq[byte] proc newBitMap*(cols, rows: int): BitMap = result.cols = max(1, cols) result.rows = max(1, rows) result.bits = newSeq[byte]((result.cols * result.rows + 7) div 8) proc setBit*(bm: var BitMap, idx: int) {.inline.} = ## Idempotent: explored only grows, so setting a set bit costs one load and one store. if idx < 0 or idx >= bm.cols * bm.rows: return let byteIdx = idx shr 3 bm.bits[byteIdx] = bm.bits[byteIdx] or byte(1 shl (idx and 7)) proc bitMapOf*(sc: SceneRec, explored: HashSet[int]): BitMap = ## The whole explored set as a bitmap, for startup restore and tests. result = newBitMap(sc.cols, sc.rows) for idx in explored: result.setBit(idx) proc bitSet*(bits: openArray[byte], idx: int): bool {.inline.} = ## The gate's hot read: no copy, no refcount (the caller passes a borrowed `seq` as openArray). if idx < 0: return false let byteIdx = idx shr 3 byteIdx < bits.len and (bits[byteIdx] and byte(1 shl (idx and 7))) != 0 proc bitCount*(bm: BitMap): int = ## How many explored cells the snapshot holds (tests / diagnostics). for b in bm.bits: var v = b while v != 0: inc result v = v and (v - 1) # --------------------------------------------------------------------------------------------------- # 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))