feat: session cache, explored bitmap and lock-free tile gate (#65)

The tile gate no longer takes dbLock or runs a SQL session JOIN per tile: a published
in-memory view (server/sessions.nim) holds token hashes -> player/role and one explored
bitmap per player. Sessions load from the DB at startup and are updated by join, key
replacement and player removal in the same lock as the write; refreshed cells publish
before the ack. The gate is one snapshot read (parse + session + bit test + redirect)
over scalar data only, so a tile burst is answered while a mutation holds dbLock.

Evidence: tests/tsessions.nim pins the cache/bitmap lifecycle and gate rule; tiles.test
adds the lock-held burst and the revocation/restart seam; auth.test adds the
LEAK_FAULT=sessioncache negative control (a stale entry makes the auth group fail);
mutation c5 keeps the cache drop load-bearing. Explored wire and persistence untouched.

Bench (devbox run bench, in-process): tile gate old 0.006 ms -> new 0.001 ms per
request; incremental explored mark 0.001 ms; snapshot build 2.0 ms at 262144 cells
(startup only).
This commit is contained in:
2026-11-21 00:10:39 +01:00
parent 3c0258ea31
commit 2727617db9
12 changed files with 664 additions and 56 deletions
+41
View File
@@ -38,6 +38,47 @@ type
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
+12
View File
@@ -19,6 +19,18 @@ proc crashNow*() =
when defined(leakfault):
quit(70)
when defined(leakfault):
var lockHoldFired = false
proc faultHoldLock*() =
## `-d:leakfault` only: hold the global lock for a moment at the start of `token.move`, so a test
## can prove a tile burst is answered while a mutation is still in flight (#65). Fires once per
## process; the caller already holds `dbLock`, which serializes the flag.
when defined(leakfault):
if not lockHoldFired and getEnv("LEAK_FAULT") == "lockhold":
lockHoldFired = true
sleep(1200)
when defined(dispfault):
var txnFaultFired = false
var ackFaultFired = false
+66 -34
View File
@@ -27,6 +27,11 @@
## server/tiles.nim: a strict canonical URL, the player's explored rule (the GM always), `404` for a
## tile that does not exist and a bodyless `200` with `X-Accel-Redirect` to the internal `/_tiles/`
## location, which nginx alone can serve (DESIGN 3.3, 6.6, 11.1).
## #65 (build item 6): the tile gate no longer takes `dbLock` or runs SQL per tile. `app.gate`
## (server/sessions.nim) is the published read-side view - token hash -> session entry, loaded from
## the DB at startup and kept current by join/replace/remove, plus one explored bitmap per player,
## updated by each refresh. `tileGate` is one snapshot read; `wall`/`token` mutations pay only a
## few-microsecond publish before the ack.
## M3 slice 10 (#25): the finish line - `scene.set` (the 29th catalogue intent: the settable scene
## fields, the token-radius-default resize through 5.6, and a hello + full resync of every
## connection), plus the restart and logs acceptance groups and the group checklist.
@@ -40,6 +45,7 @@ import db_connector/db_sqlite
import mummy, mummy/routers
import config, db, eventlog, crypto, auth, conns, instancelock, protocol, world, jsonbound
import characters, geometry, markers, props, text, tiles, tokens, vision, views, explored, worldmap, faults, moverules
import sessions
const
CookieName* = "fff_session"
@@ -57,6 +63,9 @@ type
db: DbConn
dbLock: Lock
## The one global lock (DESIGN 4.3): it serializes every mutation, the DB, and the world below.
gate: GateCache
## The tile gate's read-side view (#65): session entries and the explored bitmap, published
## under `dbLock` and read under the cache's own mutex. No tile request takes `dbLock`.
conns: Conns
instanceLock: InstanceLock
scene: SceneRec
@@ -201,8 +210,13 @@ proc refreshPlayer(pid: int) =
## into a `var` would copy it and the update would be lost. The same refresh mints the player's
## markers (5.8): the polygon is the gate, so it must run after `refresh`.
if pid == GmControlled: return
app.visions.mgetOrPut(pid, PlayerVision()).refresh(app.scene, app.tokens, pid)
discard markers.syncMarkers(app.visions.mgetOrPut(pid, PlayerVision()), app.scene)
# Borrow the entry: `let` would copy the whole PlayerVision (polygons, explored set, markers).
let pv = addr app.visions.mgetOrPut(pid, PlayerVision())
pv[].refresh(app.scene, app.tokens, pid)
discard markers.syncMarkers(pv[], app.scene)
# Publish the cells this refresh added to the tile gate's bitmap (#65). `fresh` is idempotent
# until the egress clears it, so a second refresh before the ack re-sets the same bits.
app.gate.markExplored(pid, app.scene, pv[].fresh)
proc refreshAll() =
## A wall or door changed: every player's sight changes (4.2 step 5).
@@ -752,7 +766,10 @@ proc join(request: Request) {.gcsafe.} =
player = findPlayerByKey(app.db, key)
if player.isSome:
token = randomSessionToken()
createSession(app.db, player.get.id, sha256Hex(token))
let hash = sha256Hex(token)
createSession(app.db, player.get.id, hash)
# #65: publish the new session before any tile or upgrade can ask for it.
app.gate.putSession(hash, player.get.id, player.get.role == prGm)
if player.isNone:
# No key, no body, no detail: a wrong key and an unknown key look the same (T9 discipline).
app.lg.log(lvInfo, "join_refused")
@@ -777,43 +794,32 @@ proc join(request: Request) {.gcsafe.} =
request.respond(303, headers)
proc tileGate(request: Request) {.gcsafe.} =
## GET /tiles/<scene>/v<art_version>/<x>_<y>.png (DESIGN 3.3, 6.6; slice 9 / #24). Order: parse
## the URL (malformed, out of range, another scene, stale art version -> 404 whatever the session),
## then the session (missing or unknown -> 403), then the explored grid (unexplored -> 403).
## The GM is always allowed. Nim never opens a tile file: a `200` carries `X-Accel-Redirect` to
## the internal `/_tiles/` location and `Cache-Control: private` (Q4), and nginx serves the bytes.
## GET /tiles/<scene>/v<art_version>/<x>_<y>.png (DESIGN 3.3, 6.6; slice 9 / #24, #65). Order:
## parse the URL (malformed, out of range, another scene, stale art version -> 404 whatever the
## session), then the session (missing or unknown -> 403), then the explored bitmap (unexplored ->
## 403). The GM is always allowed. Nim never opens a tile file: a `200` carries
## `X-Accel-Redirect` to the internal `/_tiles/` location and `Cache-Control: private` (Q4), and
## nginx serves the bytes.
##
## The scene is read exactly once, under the global lock (#31): `scene.set` reassigns `app.scene`
## under that same lock, so this request parses the URL, checks the explored grid and builds the
## redirect from ONE record. A second read could see a swapped scene whose `walls`/`artVersion`
## disagree with the parse (the old code read it three times, twice outside the lock).
## No `dbLock` (issue #65): the whole decision is one read of the gate's published snapshot, which
## holds the scalar scene record, the session table and the explored bitmap. A mutation holding
## the global lock for its write/COMMIT cannot delay a tile burst, and a tile never hashes a
## session or runs SQL. `gateTile` is the one record of the request (#31): parse, decision and
## redirect all come from the same snapshot.
let token = sessionCookie(request)
var parsed: tuple[outcome: TileOutcome, req: TileRequest]
var player: Option[Player]
var allowed = false
var redirect = ""
withLock app.dbLock:
let sc = app.scene # the one read of the request
parsed = parseTileRequest(request.pathParams["scene"], request.pathParams["version"],
request.pathParams["file"], sc)
if parsed.outcome == toTileOk:
if token.len > 0: player = sessionPlayer(app.db, sha256Hex(token))
if player.isSome:
allowed = player.get.role == prGm
if not allowed and app.visions.hasKey(player.get.id):
allowed = tileCoveredByExplored(sc, app.visions[player.get.id].explored,
parsed.req.x, parsed.req.y)
if allowed: redirect = tilePath(sc, parsed.req.x, parsed.req.y)
let hash = if token.len > 0: sha256Hex(token) else: ""
let decision = app.gate.gateTile(hash, request.pathParams["scene"],
request.pathParams["version"], request.pathParams["file"])
if parsed.outcome != toTileOk:
if decision.outcome != toTileOk:
request.respond(404, body = "")
return
if player.isNone or not allowed:
if not decision.session or not decision.allowed:
request.respond(403, body = "")
return
var headers: HttpHeaders
headers["X-Accel-Redirect"] = redirect
headers["X-Accel-Redirect"] = decision.redirect
headers["Cache-Control"] = "private"
request.respond(200, headers)
@@ -827,9 +833,17 @@ proc wsUpgrade(request: Request) {.gcsafe.} =
request.respond(401, body = "")
return
# #65: the session comes from the in-memory cache, so a key replacement or removal is visible
# here the moment it commits. The player record (name, role, colour) is still read from the DB
# under the lock, because a name change does not rewrite every session entry.
let hash = sha256Hex(token)
let cached = app.gate.sessionOf(hash)
if cached.isNone:
request.respond(401, body = "")
return
var player: Option[Player]
withLock app.dbLock:
player = sessionPlayer(app.db, sha256Hex(token))
player = playerById(app.db, cached.get.playerId)
if player.isNone:
request.respond(401, body = "")
return
@@ -874,8 +888,9 @@ proc wsUpgrade(request: Request) {.gcsafe.} =
withLock app.dbLock:
activated = app.conns.activate(pid, role, ws, named)
# Close the replacement race: a key.replace between the lookup and the activation must not
# leave a live connection on a revoked session.
if sessionPlayer(app.db, sha256Hex(token)).isNone:
# leave a live connection on a revoked session. Both this check and the drop run under
# `dbLock`, and the drop also publishes the cache change, so the answer is current.
if app.gate.sessionOf(hash).isNone:
if app.conns.connById(activated.id).isSome:
closeRegistered(app.conns.connById(activated.id).get, ReasonRevoked, CloseRevoked)
return
@@ -1050,6 +1065,9 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
notAllowed = true # the GM's own key rotates only through the CLI (DESIGN 3.2)
else:
key = replacePlayerKey(app.db, id)
if key.isSome:
# #65: the revoked sessions must be gone from the tile/upgrade cache before the ack.
app.gate.dropSessions(id)
if notFound:
ackErr(conn, env.reqId, CodeNotFound)
return
@@ -1094,6 +1112,10 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
removed = removePlayer(app.db, id)
else:
removed = removePlayer(app.db, id)
if removed:
# #65: revoke in the same lock as the DELETE, so no tile or upgrade can use the row
# between the commit and the cache drop.
app.gate.dropPlayer(id)
if notFound:
ackErr(conn, env.reqId, CodeNotFound)
return
@@ -1387,6 +1409,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
var kind = mkError
var resultPos: Vec
withLock app.dbLock:
faultHoldLock() # -d:leakfault only: prove the tile gate does not queue on dbLock
let idx = tokenIndex(app.tokens, id)
if idx.isNone:
# T9: a player gets one code for "unknown" and "not yours" (no existence oracle); a GM's
@@ -2472,6 +2495,13 @@ proc runServer(cfg: Config): int =
# 5.8 (#59): the per-player marker memory comes back with the explored state, before the first
# connection, so a reconnecting player gets the full set they had.
markers.restore(conn, state.scene, state.visions)
# #65: the tile gate's read-side view. Sessions come from the DB once (they never expire, Q10);
# explored bitmaps are the rows just restored. After this point a tile request touches neither the
# DB nor `dbLock`.
state.gate = newGateCache(state.scene)
sessions.loadSessions(state.gate, conn)
for pid in state.visions.keys.toSeq:
state.gate.setExplored(pid, explored.bitMapOf(state.scene, state.visions[pid].explored))
let gm = gmPlayer(conn)
if gm.isSome: state.gmPlayerId = gm.get.id
lg.log(lvInfo, "scene_loaded", [("scene", $state.scene.id), ("walls", $state.scene.walls.len),
@@ -2481,6 +2511,8 @@ proc runServer(cfg: Config): int =
lg.log(lvInfo, "explored_loaded", [("players", $state.visions.len),
("chunks", $explored.chunkCount(conn, state.scene.id)),
("markers", $markers.markerCount(conn, state.scene.id))])
lg.log(lvInfo, "gate_cache_loaded", [("sessions", $state.gate.sessionCount),
("explored_players", $state.gate.exploredPlayers)])
lg.log(lvInfo, "names_loaded", [("reveals", $state.reveals.pairs.len),
("encountered_players", $state.encountered.len)])
appHandle = cast[pointer](state)
+161
View File
@@ -0,0 +1,161 @@
## In-memory session cache and explored bitmap snapshot for the tile gate (DESIGN 3.3, 4.3, 6.6;
## issue #65, ANALYSIS-review build item 6).
##
## Why: the gate used to take the global `dbLock` and, inside it, hash the cookie and run a SQL
## `session JOIN player` per tile. A tile burst therefore queued behind every GM wall edit and its
## COMMIT. The gate now reads a published, in-memory view instead:
## * `sessions`: token hash -> (player id, role), loaded from `session`/`player` at startup,
## added by `POST /join`, dropped by key replacement and player removal;
## * `explored`: player id -> one bit per explored cell (`explored.BitMap`), set for the cells a
## refresh added, restored from the chunk rows at startup.
##
## Locking: one mutex guards this view. It is **not** `dbLock`. A mutation holds `dbLock` for its
## write and COMMIT, then publishes here for a handful of microseconds before the ack; a tile
## request holds only this mutex for a hash lookup and a bit test. The published data is deliberately
## refcount-free on the read path: `SessionEntry` is two ints and the bitmap is passed as a borrowed
## `openArray[byte]`, because ORC reference counts are not atomic and two readers must not touch the
## same `seq` header. `TileScene` (tiles.nim) is likewise all scalars.
##
## Revocation is explicit, never a TTL: `dropSessions` on key replacement, `dropPlayer` on removal
## (sessions and explored), `POST /join` adds. The database stays the source of truth across a
## restart (`loadSessions`). The lifecycle is proven by tests/tsessions.nim and the black-box
## auth/tiles groups; `LEAK_FAULT=sessioncache` keeps a revoked entry alive as the negative control.
import std/[locks, options, sequtils, strutils, tables]
import db_connector/db_sqlite
import explored, faults, tiles, vision, world
type
SessionEntry* = object
## The whole session fact the gate needs. No name, no colour: a tile decision never uses them,
## and keeping the entry ref-free makes the read path safe across worker threads.
playerId*: int
isGm*: bool
GateDecision* = object
## One tile request's answer, computed from one snapshot (URL parse included, 3.3/6.6).
outcome*: TileOutcome
session*: bool ## a live session was found for the cookie
gm*: bool
allowed*: bool
redirect*: string
GateView = object
scene: TileScene
sessions: Table[string, SessionEntry]
explored: Table[int, explored.BitMap]
GateCache* = ref object
lock: Lock
view: GateView
proc newGateCache*(sc: SceneRec): GateCache =
## Empty sessions and explored; the caller loads both before serving.
result = GateCache()
initLock(result.lock)
result.view.scene = tileScene(sc)
result.view.sessions = initTable[string, SessionEntry]()
result.view.explored = initTable[int, explored.BitMap]()
# ---------------------------------------------------------------------------------------------------
# Sessions
proc putSession*(g: GateCache, tokenHash: string, playerId: int, isGm: bool) =
## `POST /join` and the startup loader. A fresh sign-in always gets a fresh token hash, so an
## overwrite is either the same session or a harmless no-op.
if tokenHash.len == 0 or playerId <= 0: return
withLock g.lock:
g.view.sessions[tokenHash] = SessionEntry(playerId: playerId, isGm: isGm)
proc sessionOf*(g: GateCache, tokenHash: string): Option[SessionEntry] =
## The `/ws` upgrade lookup. Returns only scalars, so a caller never holds shared refcounted state.
if tokenHash.len == 0: return none(SessionEntry)
withLock g.lock:
let e = g.view.sessions.getOrDefault(tokenHash)
if e.playerId > 0: result = some(e)
proc dropSessions*(g: GateCache, playerId: int) =
## `key.replace`: every session of that player dies before the next real or tile request reads.
if playerId <= 0: return
if faultActive("sessioncache"): return # test-only negative control (#65)
withLock g.lock:
for h in g.view.sessions.keys.toSeq:
if g.view.sessions[h].playerId == playerId:
g.view.sessions.del h
proc dropPlayer*(g: GateCache, playerId: int) =
## `player.remove`: the key's sessions and the explored snapshot go with the player.
if playerId <= 0: return
if faultActive("sessioncache"): return # test-only negative control (#65)
withLock g.lock:
for h in g.view.sessions.keys.toSeq:
if g.view.sessions[h].playerId == playerId:
g.view.sessions.del h
g.view.explored.del playerId
proc loadSessions*(g: GateCache, db: DbConn) =
## Startup (4.4): the `session` rows are the source of truth, the cache their mirror. Every live
## session (sessions never expire, Q10) is available before the first request is served.
var rows: seq[(string, SessionEntry)]
for row in db.getAllRows(sql"""
SELECT s.token_hash, p.id, p.role
FROM session s JOIN player p ON p.id = s.player_id"""):
rows.add (row[0], SessionEntry(playerId: parseInt(row[1]), isGm: row[2] == "gm"))
withLock g.lock:
g.view.sessions.clear()
for (h, e) in rows: g.view.sessions[h] = e
proc sessionCount*(g: GateCache): int =
withLock g.lock:
result = g.view.sessions.len
# ---------------------------------------------------------------------------------------------------
# Explored bitmap
proc setExplored*(g: GateCache, playerId: int, bm: explored.BitMap) =
## Startup restore: the whole grid the player had before the restart.
withLock g.lock:
g.view.explored[playerId] = bm
proc markExplored*(g: GateCache, playerId: int, sc: SceneRec,
cells: openArray[(int, int)]) =
## One refresh's new cells (4.2 step 5). Explored only grows, so setting the bits in place under
## the mutex *is* the publish: a reader sees a cell before or after, never a torn byte.
if playerId <= 0 or cells.len == 0: return
withLock g.lock:
var bm = g.view.explored.mgetOrPut(playerId, newBitMap(sc.cols, sc.rows))
for (cx, cy) in cells:
bm.setBit(cy * bm.cols + cx)
g.view.explored[playerId] = bm
proc exploredPlayers*(g: GateCache): int =
withLock g.lock:
result = g.view.explored.len
# ---------------------------------------------------------------------------------------------------
# Scene and the gate itself
proc setScene*(g: GateCache, sc: SceneRec) =
## `scene.set` republishes the (unchanging) tile geometry. Kept for the one-record rule: a gate
## request parses, checks and builds its redirect from the same published record.
withLock g.lock:
g.view.scene = tileScene(sc)
proc gateTile*(g: GateCache, tokenHash, sceneRaw, versionRaw, fileRaw: string): GateDecision =
## DESIGN 3.3/6.6 in one snapshot read: parse the canonical URL first (malformed, out of range,
## another scene, stale art version -> 404 whatever the session), then the session, then the
## player's explored bit. The GM is always allowed. No `dbLock`, no SQL, no per-tile hash beyond
## the cookie's one SHA-256 (done by the caller).
withLock g.lock:
let sc = g.view.scene
let parsed = parseTileRequest(sceneRaw, versionRaw, fileRaw, sc)
result.outcome = parsed.outcome
if parsed.outcome != toTileOk: return
let e = if tokenHash.len > 0: g.view.sessions.getOrDefault(tokenHash) else: SessionEntry()
if e.playerId <= 0: return
result.session = true
result.gm = e.isGm
result.allowed = e.isGm or
(g.view.explored.hasKey(e.playerId) and
tileCoveredByBits(sc, g.view.explored[e.playerId].bits, parsed.req.x, parsed.req.y))
if result.allowed:
result.redirect = tilePath(sc, parsed.req.x, parsed.req.y)
+43 -11
View File
@@ -17,17 +17,27 @@
##
## Access rule [FIXED, Q4/3.3]: the GM is always allowed; a player is allowed iff at least one cell
## of that player's explored grid overlaps the tile rectangle (in v1 `tile_size == cell`, so one
## cell). Nothing here reads the world or a lock: main.nim hands in the scene and the player's
## explored set. A player with no sight state has explored nothing, so every tile is refused.
## cell). Nothing here reads the world, the DB or the global lock: these are pure functions over a
## `TileScene` and either an explored set (unit tests) or its bitmap (the published gate view,
## issue #65). A player with no sight state has explored nothing, so every tile is refused.
##
## Status split [FIXED (owner-delegated), #24]: a nonexistent tile is 404; an existing tile that the
## session may not have (no session, unknown session, or unexplored) is 403. The 403 is the same for
## "no session" and "unexplored" so the route never says whether a tile exists for an anonymous
## requester beyond the non-secret scene geometry (3.1: world size and cell size are not secret).
import std/[math, sets, strutils]
import vision, world
import explored, vision, world
type
TileScene* = object
## The tile gate's scalar copy of the scene (issue #65). The gate reads it from the published
## snapshot without the global lock; the value holds no `seq`/`ref`, so copying it across a
## thread boundary costs no ORC reference-count traffic. `w/h/tile_size/cell/art_version` never
## change at runtime (`scene.set` cannot patch them, 6.1), so a snapshot is stable for its life.
id*: int
w*, h*: float
tileSize*, cell*, cols*, rows*, artVersion*: int
TileOutcome* = enum
toTileOk
toTileMalformed ## a component that is not canonical or a suffix that is not `.png` -> 404
@@ -48,6 +58,12 @@ const
## 99999 tiles is far beyond any v1 scene (128 tiles per side at 4096 px); a longer component
## is malformed rather than parsed.
converter tileScene*(sc: SceneRec): TileScene =
## The one conversion point: existing callers keep passing a `SceneRec`; the gate publishes and
## consumes a `TileScene` (no refs). `cols`/`rows` come from `vision` (ceil(w / cell)).
TileScene(id: sc.id, w: sc.w, h: sc.h, tileSize: sc.tileSize, cell: sc.cell,
cols: sc.cols, rows: sc.rows, artVersion: sc.artVersion)
proc canonicalNumber*(raw: string, maxDigits: int, dest: var int): bool =
## The URL's number grammar (this module's header): digits only, 1..maxDigits, no leading zero.
## Nothing is parsed unless every rule holds, so an overflow cannot reach `parseInt`.
@@ -66,18 +82,18 @@ proc parseVersion*(raw: string, dest: var int): bool =
if raw.len < 2 or raw[0] != 'v': return false
canonicalNumber(raw[1 .. ^1], MaxVersionDigits, dest)
proc tileCols*(sc: SceneRec): int =
proc tileCols*(sc: TileScene): int =
## Tiles across the scene (DESIGN 3.3: the tile grid's origin is the world origin).
max(1, int(ceil(sc.w / float(sc.tileSize))))
proc tileRows*(sc: SceneRec): int =
proc tileRows*(sc: TileScene): int =
max(1, int(ceil(sc.h / float(sc.tileSize))))
proc tileInRange*(sc: SceneRec, x, y: int): bool =
proc tileInRange*(sc: TileScene, x, y: int): bool =
x >= 0 and y >= 0 and x < tileCols(sc) and y < tileRows(sc)
proc parseTileRequest*(sceneRaw, versionRaw, fileRaw: string,
sc: SceneRec): tuple[outcome: TileOutcome, req: TileRequest] =
sc: TileScene): tuple[outcome: TileOutcome, req: TileRequest] =
## Strict parse of the three route components (this module's header). `req` is only meaningful
## when `outcome == toTileOk`.
var sceneId, artVersion: int
@@ -106,7 +122,7 @@ proc parseTileRequest*(sceneRaw, versionRaw, fileRaw: string,
(toTileOk, TileRequest(scene: sceneId, artVersion: artVersion, x: x, y: y))
proc tileCoveredByExplored*(sc: SceneRec, explored: HashSet[int], tileX, tileY: int): bool =
proc tileCoveredByExplored*(sc: TileScene, explored: HashSet[int], tileX, tileY: int): bool =
## DESIGN 3.3: a tile is allowed iff at least one explored cell overlaps it. The tile rectangle is
## `[tileX*tile_size, (tileX+1)*tile_size) x ...`; a cell overlaps when its rectangle shares any
## point with it. General over `tile_size` and `cell` (v1 pins them equal, Q4, but a 64 px
@@ -120,16 +136,32 @@ proc tileCoveredByExplored*(sc: SceneRec, explored: HashSet[int], tileX, tileY:
for cy in cy0 .. cy1:
for cx in cx0 .. cx1:
if cx < 0 or cy < 0 or cx >= sc.cols or cy >= sc.rows: continue
if sc.cellIndex(cx, cy) in explored: return true
if cy * sc.cols + cx in explored: return true
false
proc tileAllowed*(sc: SceneRec, explored: HashSet[int], tileX, tileY: int,
proc tileCoveredByBits*(sc: TileScene, bits: openArray[byte], tileX, tileY: int): bool =
## The same overlap rule over the gate's explored bitmap (issue #65): cell index `cy * cols + cx`,
## bit `idx shr 3`, mask `1 shl (idx and 7)`, exactly `BitMap`/`cellIndex`. The bitmap is borrowed
## (openArray), so a gate read never copies or ref-counts the snapshot.
let x0 = tileX * sc.tileSize
let y0 = tileY * sc.tileSize
let cx0 = x0 div sc.cell
let cy0 = y0 div sc.cell
let cx1 = (x0 + sc.tileSize - 1) div sc.cell
let cy1 = (y0 + sc.tileSize - 1) div sc.cell
for cy in cy0 .. cy1:
for cx in cx0 .. cx1:
if cx < 0 or cy < 0 or cx >= sc.cols or cy >= sc.rows: continue
if bitSet(bits, cy * sc.cols + cx): return true
false
proc tileAllowed*(sc: TileScene, explored: HashSet[int], tileX, tileY: int,
isGm: bool): bool =
## The whole gate rule (3.3): the GM is always allowed; a player only through its explored grid.
if isGm: return true
tileCoveredByExplored(sc, explored, tileX, tileY)
proc tilePath*(sc: SceneRec, x, y: int): string =
proc tilePath*(sc: TileScene, x, y: int): string =
## The internal nginx path of a tile (3.3, 11.1): `/_tiles/<scene>/v<art_version>/<x>_<y>.png`.
## Built only from integers, never from request text, so no request can steer it.
"/_tiles/" & $sc.id & "/v" & $sc.artVersion & "/" & $x & "_" & $y & ".png"