Files
SirStone a79d809394 feat(m4): cap map images at Full HD and shrink on import (#85)
The owner fixed the map cap at 1920 px on the long side and 1080 px on the
short side (either orientation). fff-vtt import now shrinks a larger source
with ImageMagick Lanczos before tiling (alpha kept, proportions preserved,
no upscaling), prints `scaled WxH -> WxH`, and records the shrunk w/h; a
source at or below the cap is untouched, so the pixel-identity tests still
hold. A scene row already above the cap is not rewritten: the server logs
`map_above_cap` at startup and serve prints the re-import advice.

Docs: ADR-0023, DESIGN 3.3/5.3/8/11.1/13/14, TESTING 5.3/13, README,
HANDOFF-M4, client README. The M4 phone gate and the fogbench measurement
now use the Full HD maximum; the 16384 px / 262144-cell bench and test rows
stay as labelled server stress references. import-scale now proves a 16384²
input is shrunk to 1080x1080 (289 tiles at 64 px) quickly and bounded.

Part of #63, #85. #77 is blocked by this issue.
2026-11-21 22:37:34 +01:00

523 lines
24 KiB
Nim
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
## Map import CLI (DESIGN 11.1 "Map import", 3.3 tiles, 13 M4; issue #79, pulled forward from M6).
##
## Offline, no browser: slice one source image into `tile_size` PNG tiles under
## `<state>/tiles/<scene>/v<art_version>/` (origin at the world origin, names `<x>_<y>.png`) and
## update the one v1 scene row's `w`, `h`, `tile_size` and `art_version`. The server keeps its
## in-memory scene from startup (4.1), so it must be stopped for an import and restarted after it;
## the state-dir lock of 3.2/11.1 is what makes that non-negotiable (the same lock `gm-key --new`
## honours). A re-import for a scene that already has art grows `art_version` so browsers never
## serve a tile from a stale cache (3.3).
##
## Decoding is delegated to ImageMagick (`magick` from the root devbox, `imagemagick`), the one
## reviewed source of PNG/WebP codecs here: a 16384 px source is far too large for a whole-image
## decoder in this process. A single `-crop 64x64 +adjoin` over the source materialises all 65,536
## tiles in one image list, and `-limit memory/-limit map` are *per image*, so that attempt needed
## 4.3 GB RSS and 65k file descriptors and died with "Too many open files" (#83). Slicing therefore
## streams: one `magick` decodes the source to raw samples (its own pixel cache is disk-backed under
## the `-limit` flags below, so RSS stays ~50 MB), this process reads it one tile row at a time and
## hands that band to a small pool of `magick` children, each of which only ever holds a single row
## band. Live caches and fds are bounded by the worker count, never by the tile count. No Nim or npm
## image dependency is added; the FIXED stack of DESIGN 2 is unchanged, and `tools/` keeps its
## built-ins-only rule (TESTING 10.4). The tile layout the gate parses is produced here, not by the
## prototype's deterministic fixture generator.
##
## Map images are capped at Full HD (FIXED owner decision 2026-11-21, #85): before tiling, a source
## larger than 1920 px on the long side or 1080 px on the short side is shrunk with ImageMagick's
## Lanczos filter (alpha kept, no upscaling) and the shrink is printed. The scene row gets the
## shrunk size; smaller images are imported byte-for-byte unchanged (the pixel-identity tests rely
## on that).
import std/[math, options, os, osproc, streams, strutils, times]
import db_connector/db_sqlite
import config, db, instancelock, world
const
ImportedFormats* = ["PNG", "WEBP"]
## Source formats accepted by the CLI. Output tiles are always PNG (the gate's URL suffix).
SliceCacheLimit = "32MiB"
## Per-image pixel-cache RAM cap for every `magick` of the slice. Large images spill to
## ImageMagick's disk cache instead of growing RSS (#83).
MaxSliceWorkers = 8
## Child `magick` count of the slice: half a 16-core box, and never more than the band count.
MaxBandBytes = 32 * 1024 * 1024
## Largest tile row handed to one child. A row band above this (a very large `--tile-size` on a
## wide source) falls back to the one-shot crop, whose image list is then small by construction.
ImportUsage* = """fff-vtt import --image=<path> [options]
Slice a map image into the scene's tile tree and register the scene dimensions.
The image is capped at Full HD: at most 1920 px on the long side and 1080 px on the short side
(either orientation). A larger source is shrunk with Lanczos before tiling and the shrink is
printed ("scaled 4000x3000 -> 1440x1080"); the scene's w/h become the shrunk size. A smaller
image is imported as-is (no upscaling).
Options:
--image=<path> Source image (PNG or WebP). Required.
--tile-size=<px> Tile edge in px (default: the scene's current tile_size). Must be a
positive multiple of the scene's explored cell (32 px); 64 is a common
larger choice.
--scene=<id> Target scene. v1 has exactly one scene, id 1.
--state-dir=<path> Directory holding state.db and tiles (default: run). A missing or empty
directory is created and migrated through the server's startup path, so
an import works before the first serve. The server must be stopped: the
state-dir lock is refused (exit 3), like gm-key --new.
Tiles land in <state-dir>/tiles/<scene>/v<art_version>/<x>_<y>.png, origin at the world origin.
A re-import for a scene that already has art grows art_version and writes a new v directory; the
server serves the new scene and tiles after a restart. The CLI never touches a status, wall or
token; create those through the GM panels/wire after the import.
"""
type
ImportArgs = object
cfg: Config
image: string
scene: int
tileSize: int
hasTileSize: bool
proc failImport(msg: string, code: int): int =
stderr.writeLine "fff-vtt import: " & msg
code
proc parseImportArgs(raw: seq[string], a: var ImportArgs): int =
## Recognise the import-only flags, hand everything else (state-dir, help) to `parseConfig`, so
## the state-dir key behaves exactly as it does for the server and `gm-key`.
a.scene = DefaultSceneId
var rest: seq[string]
var i = 0
while i < raw.len:
let arg = raw[i]
inc i
case arg
of "--image":
if i >= raw.len: return failImport("--image: missing value", 2)
a.image = raw[i]; inc i
of "--tile-size":
if i >= raw.len: return failImport("--tile-size: missing value", 2)
a.hasTileSize = true
try: a.tileSize = parseInt(raw[i].strip)
except ValueError: return failImport("--tile-size: expected a whole number of px", 2)
inc i
of "--scene":
if i >= raw.len: return failImport("--scene: missing value", 2)
try: a.scene = parseInt(raw[i].strip)
except ValueError: return failImport("--scene: expected a whole number", 2)
inc i
else:
if arg.startsWith("--image="):
a.image = arg["--image=".len .. ^1]
elif arg.startsWith("--tile-size="):
a.hasTileSize = true
try: a.tileSize = parseInt(arg["--tile-size=".len .. ^1].strip)
except ValueError: return failImport("--tile-size: expected a whole number of px", 2)
elif arg.startsWith("--scene="):
try: a.scene = parseInt(arg["--scene=".len .. ^1].strip)
except ValueError: return failImport("--scene: expected a whole number", 2)
else:
rest.add arg
try:
a.cfg = parseConfig(rest)
except ConfigError as e:
return failImport(e.msg, 2)
0
proc runMagick(args: seq[string], workingDir = ""): tuple[status: int, output: string] =
## One ImageMagick call, no shell. `poStdErrToStdOut` folds its diagnostics into the message a
## failed import prints; malformed output never reaches a path or a SQL statement. A missing
## `magick` is reported like any other decode failure instead of escaping as a stack trace.
try:
let p = startProcess("magick", workingDir = workingDir, args = args,
options = {poUsePath, poStdErrToStdOut})
try:
result.output = p.outputStream.readAll()
result.status = p.waitForExit()
finally:
p.close()
except OSError as e:
result.status = -1
result.output = "cannot run ImageMagick (magick): " & e.msg & "; run inside devbox"
proc lastLine(s: string): string =
var lines = s.strip.splitLines
if lines.len == 0: "" else: lines[^1]
type
IdentifiedImage = object
width, height, depth: int
imageType: string
proc identifyImage(path, label: string): tuple[rc: int, message: string, info: IdentifiedImage] =
## Dimensions, one format, and the sample layout the streaming slice feeds raw to `magick`.
## Multi-frame input (animated PNG/WebP) would break the one-tile-per-coordinate tree, so it is
## refused rather than silently importing frame zero. `label` is the user-facing source name
## (the shrunk intermediate is an implementation detail).
let ident = runMagick(@["identify", "-ping", "-format", "%w %h %m %[type] %z", path])
if ident.status != 0:
return (1, "cannot read image \"" & label & "\": " & lastLine(ident.output), IdentifiedImage())
let parts = ident.output.splitWhitespace
if parts.len != 5:
return (2, "multi-frame image \"" & label &
"\" is not supported; import a single-frame PNG or WebP", IdentifiedImage())
if parts[2].toUpperAscii notin ImportedFormats:
return (2, "unsupported format " & parts[2] &
": the source must be PNG or WebP (tiles are always PNG)", IdentifiedImage())
try:
result.info.width = parseInt(parts[0])
result.info.height = parseInt(parts[1])
result.info.depth = parseInt(parts[4])
except ValueError:
return (1, "cannot read image dimensions from \"" & label & "\"", IdentifiedImage())
if result.info.width <= 0 or result.info.height <= 0:
return (1, "image \"" & label & "\" has no pixels", IdentifiedImage())
result.info.imageType = parts[3]
type
SlicePlan = object
## How the decoded source is handed to the children as raw samples: the channel set follows
## the source's own type, so a plain RGB image still produces plain RGB tiles and an image with
## alpha keeps its alpha channel (pixel-identical tiles to the one-shot crop; PNG bytes can
## differ because the encoder sees raw samples instead of a decoded image's properties).
rawSpec: string
channels: int
sampleDepth: int
proc slicePlan(imgType: string, srcDepth: int): SlicePlan =
let t = imgType.toLowerAscii
let alpha = t.endsWith("alpha")
let gray = t.startsWith("gray") or t.startsWith("bilevel")
result.sampleDepth = if srcDepth > 8: 16 else: 8
result.channels = (if gray: 1 else: 3) + (if alpha: 1 else: 0)
result.rawSpec =
if gray: (if alpha: "graya:" else: "gray:")
else: (if alpha: "rgba:" else: "rgb:")
proc removeBands(dir: string) =
## Row bands are one-shot scratch files next to the tile temp dir: files first, then the dir.
if not dirExists(dir): return
for kind, path in walkDir(dir):
if kind in {pcFile, pcLinkToFile}:
try: removeFile(path)
except OSError: discard
try: removeDir(dir)
except OSError: discard
proc sliceRows(imagePath, tempDir: string, imgW, imgH, tileSize, cols, rows: int,
plan: SlicePlan): tuple[rc: int, message: string] =
## Stream the source once and cut one tile row (a band) per child `magick`, so live pixel caches
## stay bounded by the worker count and the fd count does not follow the tile count (#83). The
## decoder's own cache is disk-backed (`SliceCacheLimit`), a band file is a few MB, and every
## child only ever holds one band. Tiles are written as `tile_<global index>.png`; the caller
## renames them to the `<x>_<y>.png` gate grammar.
let sampleBytes = plan.sampleDepth div 8
let bandStride = imgW * plan.channels * sampleBytes
let workers = max(1, min(MaxSliceWorkers, min(countProcessors() div 2, rows)))
let total = cols * rows
let progressStep = max(1, rows div 20)
let bandDir = tempDir & "-bands"
stderr.writeLine "fff-vtt import: slicing " & $imgW & "x" & $imgH & " into " & $total &
" tiles at " & $tileSize & " px (" & $workers & " workers)"
removeBands(bandDir)
try: createDir(bandDir)
except OSError as e:
return (1, "cannot create scratch directory " & bandDir & ": " & e.msg)
let decode = try:
startProcess("magick", options = {poUsePath}, args = @[
"-limit", "memory", SliceCacheLimit, "-limit", "map", SliceCacheLimit,
imagePath, "-depth", $plan.sampleDepth, plan.rawSpec & "-"])
except OSError as e:
removeBands(bandDir)
return (1, "cannot run ImageMagick (magick): " & e.msg & "; run inside devbox")
var buf = newString(bandStride * tileSize)
var busy: seq[tuple[p: Process, row: int]]
proc reap(w: var tuple[p: Process, row: int]): int =
## Reap one child (its stderr already went straight to ours) and drop its band file.
result = try: w.p.waitForExit() except CatchableError: -1
w.p.close()
try: removeFile(bandDir / ("band_" & $w.row & ".raw"))
except OSError: discard
proc abortChildren() =
for i in 0 ..< busy.len:
try: busy[i].p.terminate()
except CatchableError: discard
discard reap(busy[i])
busy.setLen(0)
var row = 0
var handed = 0
var failure = ""
var gotShort = false
while row < rows and failure.len == 0:
let bandH = min(tileSize, imgH - row * tileSize)
let want = bandStride * bandH
var got = 0
while got < want:
var n = 0
try:
n = decode.outputStream.readData(addr buf[got], want - got)
except CatchableError:
n = 0
if n <= 0: break
got += n
if got < want:
gotShort = true
failure = "the decoder stopped after " & $got & " of " & $want & " bytes of row band " &
$row & " (source " & $imgW & "x" & $imgH & ")"
break
if busy.len >= workers:
var w = busy[0]
busy.delete(0)
if reap(w) != 0:
failure = "magick failed on the tiles of row " & $w.row & " (its message is above)"
break
let bandFile = bandDir / ("band_" & $row & ".raw")
try:
writeFile(bandFile, buf[0 ..< want])
except IOError as e:
failure = "cannot write row band " & $row & ": " & e.msg
break
let child = try:
# poParentStreams: the child needs no pipes at all (it reads the band file and writes tiles),
# so every magick's stderr lands on ours and no descriptors are inherited per child.
startProcess("magick", options = {poUsePath, poParentStreams}, args = @[
"-size", $imgW & "x" & $bandH, "-depth", $plan.sampleDepth, plan.rawSpec & bandFile,
"-crop", $tileSize & "x" & $tileSize, "+repage", "+adjoin",
"-scene", $(row * cols), tempDir / "tile_%d.png"])
except OSError as e:
failure = "cannot run ImageMagick (magick): " & e.msg & "; run inside devbox"
break
busy.add((child, row))
handed += cols
if (row + 1) mod progressStep == 0 or row + 1 == rows:
stderr.writeLine "fff-vtt import: rows " & $(row + 1) & "/" & $rows & ", tiles " &
$min(handed, total) & "/" & $total
inc row
# Every child must be reaped (and its status checked) before the tile tree is trusted.
while busy.len > 0 and failure.len == 0:
var w = busy[0]
busy.delete(0)
if reap(w) != 0:
failure = "magick failed on the tiles of row " & $w.row & " (its message is above)"
if failure.len > 0:
abortChildren()
# The decoder's own exit status matters even when every band arrived: a corrupt tail is exactly
# the case where the band loop stops short, and the error text lives on its stderr.
let decodeErr = try: decode.errorStream.readAll() except CatchableError: ""
let decodeRc = try: decode.waitForExit() except CatchableError: -1
decode.close()
removeBands(bandDir)
if failure.len == 0 and decodeRc != 0:
failure = "magick failed to decode \"" & imagePath & "\": " & lastLine(decodeErr)
elif failure.len > 0 and gotShort and decodeErr.len > 0:
# A short read is the decoder's failure: quote its own last line, not just our byte count.
failure.add ": " & lastLine(decodeErr)
if failure.len > 0: return (1, failure)
(0, "")
proc removeTemp(dir: string) =
## The slice temp dir holds only files (ImageMagick `+adjoin`); no recursive delete is needed.
if not dirExists(dir): return
for kind, path in walkDir(dir):
if kind in {pcFile, pcLinkToFile}:
try: removeFile(path)
except OSError: discard
try: removeDir(dir)
except OSError: discard
proc dirHasFiles(dir: string): bool =
if not dirExists(dir): return false
for kind, path in walkDir(dir):
if kind in {pcFile, pcLinkToFile}: return true
false
proc runImport*(rawArgs: seq[string]): int =
var a: ImportArgs
let parseRc = parseImportArgs(rawArgs, a)
if parseRc != 0: return parseRc
if a.cfg.help:
stdout.write ImportUsage
return 0
if a.image.len == 0:
return failImport("--image is required\n\n" & ImportUsage, 2)
if a.scene != DefaultSceneId:
return failImport("scene " & $a.scene & ": v1 has exactly one scene, id " & $DefaultSceneId, 2)
# Validate the source before touching the state dir: an error creates nothing.
if not fileExists(a.image):
return failImport("source image \"" & a.image & "\" does not exist", 1)
var imagePath = expandFilename(a.image)
let source = identifyImage(imagePath, a.image)
if source.rc != 0: return failImport(source.message, source.rc)
# A fresh or empty state dir is the normal case (#82): create and migrate through the same
# startup path as the server, under the same state-dir lock. The lock is taken before the DB is
# created, so a running server can never race an import.
if not dirExists(a.cfg.stateDir):
try: createDir(a.cfg.stateDir)
except OSError as e:
return failImport("cannot create state dir \"" & a.cfg.stateDir & "\": " & e.msg, 1)
var lock = tryAcquire(a.cfg.stateDir)
if not lock.held:
return failImport("the server is running on \"" & a.cfg.stateDir &
"\" (state-dir lock held); stop it first, then restart it after the import", 3)
var conn: DbConn
var applied: int
try:
let opened = openMigratedDatabase(a.cfg.dbPath)
conn = opened.db
applied = opened.applied
except CatchableError as e:
return failImport("cannot open or migrate " & a.cfg.dbPath & ": " & e.msg, 1)
defer: close(conn)
if applied > 0:
stderr.writeLine "fff-vtt import: created/migrated " & a.cfg.dbPath &
" (" & $applied & " schema step" & (if applied == 1: "" else: "s") & ")"
let loaded = loadScene(conn)
if loaded.isNone:
return failImport("state.db has no scene " & $DefaultSceneId &
" after migration; the database is inconsistent", 1)
let scene = loaded.get
var tileSize = if a.hasTileSize: a.tileSize else: scene.tileSize
if tileSize <= 0:
return failImport("--tile-size must be positive, got " & $tileSize, 2)
if tileSize mod scene.cell != 0:
return failImport("--tile-size " & $tileSize & " is not a multiple of the scene's explored cell " &
$scene.cell & " px; the gate requires tile_size % cell == 0 (64 px is a common larger choice)", 2)
# Full HD cap (FIXED owner decision 2026-11-21, #85). Shrink before tiling, with the same
# disk-backed pixel cache as the rest of the import, and keep alpha. A source at or below the
# cap stays byte-for-byte the same input to the slice, so its tiles remain pixel-identical.
var info = source.info
var shrinkDir = ""
defer:
if shrinkDir.len > 0: removeBands(shrinkDir)
if exceedsMapCap(float(info.width), float(info.height)):
let target = cappedMapSize(info.width, info.height)
shrinkDir = getTempDir() / ("fff-vtt-import-" & $getCurrentProcessId() & "-" &
$int(epochTime() * 1000.0))
try: createDir(shrinkDir)
except OSError as e:
return failImport("cannot create temporary directory " & shrinkDir & ": " & e.msg, 1)
let resizedPath = shrinkDir / "map.png"
let shrunk = runMagick(@["-limit", "memory", "256MiB", "-limit", "map", "512MiB",
imagePath, "-filter", "Lanczos", "-resize",
$target.w & "x" & $target.h & "!", resizedPath])
if shrunk.status != 0:
return failImport("magick failed to shrink \"" & a.image & "\" to " & $target.w & "x" &
$target.h & ": " & lastLine(shrunk.output), 1)
let resized = identifyImage(resizedPath, a.image)
if resized.rc != 0: return failImport("shrunk image cannot be read: " & resized.message, 1)
if resized.info.width != target.w or resized.info.height != target.h:
return failImport("magick shrank to " & $resized.info.width & "x" & $resized.info.height &
" instead of the expected " & $target.w & "x" & $target.h, 1)
imagePath = resizedPath
info = resized.info
stdout.writeLine "scaled " & $source.info.width & "×" & $source.info.height & " → " &
$target.w & "×" & $target.h
stdout.flushFile()
let imgW = info.width
let imgH = info.height
let plan = slicePlan(info.imageType, info.depth)
let cols = int(ceil(float(imgW) / float(tileSize)))
let rows = int(ceil(float(imgH) / float(tileSize)))
if cols > 99999 or rows > 99999:
return failImport("tile grid " & $cols & "x" & $rows & " exceeds the URL's 5-digit coordinates", 2)
# A scene that already has tiles for its current version must not answer from a stale cache:
# every re-import grows art_version and writes the next v directory (DESIGN 3.3).
let tileRoot = a.cfg.stateDir / "tiles" / $scene.id
var version = scene.artVersion
if dirHasFiles(tileRoot / ("v" & $version)): inc version
let finalDir = tileRoot / ("v" & $version)
if dirExists(finalDir):
if dirHasFiles(finalDir):
return failImport("tile directory " & finalDir & " already exists and is not empty", 1)
try: removeDir(finalDir)
except OSError as e:
return failImport("cannot clear empty tile directory " & finalDir & ": " & e.msg, 1)
if not dirExists(tileRoot):
try: createDir(tileRoot)
except OSError as e:
return failImport("cannot create " & tileRoot & ": " & e.msg, 1)
let tempDir = tileRoot / (".import-" & $getCurrentProcessId() & "-" & $int(epochTime()))
removeTemp(tempDir)
try: createDir(tempDir)
except OSError as e:
return failImport("cannot create temporary tile directory " & tempDir & ": " & e.msg, 1)
# Memory-sane slicing (DESIGN 11.1, #83). A single `-crop tile +adjoin` over a 16384 px source
# builds one image list of every tile and dies on fds/memory, so the normal path streams: one
# decode to raw samples, then one row band per child `magick` (bounded caches, bounded fds, and
# progress on stderr). Only a source whose single tile row is itself huge falls back to the
# one-shot crop, where the tile list is small by construction. `tile_%d.png` names use the global
# scene index, so the rename below to `<x>_<y>.png` is the same for both paths.
let bandBytes = imgW * plan.channels * (plan.sampleDepth div 8) * tileSize
if bandBytes <= MaxBandBytes:
let streamed = sliceRows(imagePath, tempDir, imgW, imgH, tileSize, cols, rows, plan)
if streamed.rc != 0:
removeTemp(tempDir)
return failImport(streamed.message, 1)
else:
let crop = $tileSize & "x" & $tileSize
let sliced = runMagick(@["-limit", "memory", "256MiB", "-limit", "map", "512MiB",
imagePath, "-crop", crop, "+repage", "+adjoin", "tile_%d.png"],
tempDir)
if sliced.status != 0:
removeTemp(tempDir)
return failImport("magick failed to slice \"" & a.image & "\": " & lastLine(sliced.output), 1)
for i in 0 ..< cols * rows:
let src = tempDir / ("tile_" & $i & ".png")
if not fileExists(src):
removeTemp(tempDir)
return failImport("magick produced no tile " & $i & " of " & $(cols * rows) &
" (source " & $imgW & "x" & $imgH & ", tile " & $tileSize & ")", 1)
let x = i mod cols
let y = i div cols
try:
moveFile(src, tempDir / ($x & "_" & $y & ".png"))
except OSError as e:
removeTemp(tempDir)
return failImport("cannot name tile " & $x & "_" & $y & ": " & e.msg, 1)
for kind, path in walkDir(tempDir):
if kind in {pcFile, pcLinkToFile} and path.extractFilename.startsWith("tile_"):
removeTemp(tempDir)
return failImport("magick produced more than the " & $(cols * rows) & " expected tiles", 1)
try:
moveDir(tempDir, finalDir)
except OSError as e:
removeTemp(tempDir)
return failImport("cannot publish " & finalDir & ": " & e.msg, 1)
# One FULL authoring transaction (Q12), like every other persisted authoring write. If the row
# update fails, the freshly published directory is removed so a failed import changes nothing.
try:
authoringTransaction(conn):
conn.exec(sql"""UPDATE scene SET w = ?, h = ?, tile_size = ?, art_version = ? WHERE id = ?""",
$imgW, $imgH, $tileSize, $version, scene.id)
except CatchableError as e:
removeTemp(finalDir)
return failImport("cannot update the scene row: " & e.msg, 1)
stdout.writeLine "imported " & a.image & ": " & $imgW & "x" & $imgH & " px, tile " & $tileSize &
" px, " & $cols & "x" & $rows & " tiles -> " & finalDir & " (art_version " & $version & ")"
stdout.flushFile()
0