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.
This commit is contained in:
2026-11-21 22:37:34 +01:00
parent 52ab50d765
commit a79d809394
22 changed files with 515 additions and 193 deletions
+83 -27
View File
@@ -20,6 +20,12 @@
## 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
@@ -39,11 +45,16 @@ const
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), so 64 is the
designed fallback.
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
@@ -130,6 +141,36 @@ 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
@@ -312,31 +353,10 @@ proc runImport*(rawArgs: seq[string]): int =
# 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)
let imagePath = expandFilename(a.image)
var imagePath = expandFilename(a.image)
# Identify: dimensions, one format, and the sample layout the streaming slice feeds raw to
# `magick` (type/depth). Multi-frame input (animated PNG/WebP) would break the one-tile-per-
# coordinate tree, so it is refused rather than silently importing frame zero.
let ident = runMagick(@["identify", "-ping", "-format", "%w %h %m %[type] %z", imagePath])
if ident.status != 0:
return failImport("cannot read image \"" & a.image & "\": " & lastLine(ident.output), 1)
let parts = ident.output.splitWhitespace
if parts.len != 5:
return failImport("multi-frame image \"" & a.image &
"\" is not supported; import a single-frame PNG or WebP", 2)
if parts[2].toUpperAscii notin ImportedFormats:
return failImport("unsupported format " & parts[2] &
": the source must be PNG or WebP (tiles are always PNG)", 2)
var imgW, imgH, srcDepth: int
try:
imgW = parseInt(parts[0])
imgH = parseInt(parts[1])
srcDepth = parseInt(parts[4])
except ValueError:
return failImport("cannot read image dimensions from \"" & a.image & "\"", 1)
if imgW <= 0 or imgH <= 0:
return failImport("image \"" & a.image & "\" has no pixels", 1)
let plan = slicePlan(parts[3], srcDepth)
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
@@ -375,7 +395,43 @@ proc runImport*(rawArgs: seq[string]): int =
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 is the designed fallback)", 2)
$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)))
+8
View File
@@ -2493,6 +2493,14 @@ proc runServer(cfg: Config): int =
lg.log(lvError, "scene_missing", [("path", cfg.dbPath), ("scene", $DefaultSceneId)])
return 1
state.scene = loaded.get
# #85: a scene imported before the Full HD cap is left as it is on disk, but the operator is
# told once at startup that the map is above the product maximum and should be re-imported.
if exceedsMapCap(state.scene.w, state.scene.h):
lg.log(lvWarn, "map_above_cap", [
("w", $int(state.scene.w)), ("h", $int(state.scene.h)),
("cap", $MapCapLongSide & "x" & $MapCapShortSide),
("detail", "map is " & $int(state.scene.w) & "x" & $int(state.scene.h) &
", above the Full HD cap; re-import to shrink")])
state.tokens = loadTokens(conn, state.scene.id)
# 8 / slice 8: the characters, the per-player reveals and the encountered snapshots.
state.characters = characters.loadCharacters(conn)
+20
View File
@@ -131,6 +131,11 @@ type
const
DefaultSceneId* = 1
## The seeded v1 scene (migration step 3). Exactly one scene exists in v1 (Q3).
MapCapLongSide* = 1920
MapCapShortSide* = 1080
## The Full HD map cap (FIXED owner decision 2026-11-21, #85): at most this many px on the
## long side and on the short side, either orientation. The import shrinks a larger source;
## a scene row above it is never rewritten, only warned about at startup.
WallPositions* = [wpCenter, wpLeft, wpRight]
SightDirs* = [sdBoth, sdLeft, sdRight]
Presets* = [pwWall, pwDoor, pwWindow, pwOneWay]
@@ -139,6 +144,21 @@ const
WallLabelMaxLen* = 64
## `wall.label`: the 6.5 text rule, 1..64 code points, trimmed, no control characters (#55).
proc exceedsMapCap*(w, h: float): bool =
## True when a scene/image is larger than the Full HD cap, either orientation (#85). Written so
## NaN compares false (a corrupt dimension is not quietly "over the cap").
w > 0 and h > 0 and (max(w, h) > float(MapCapLongSide) or min(w, h) > float(MapCapShortSide))
proc cappedMapSize*(w, h: int): tuple[w, h: int] =
## The dimensions a source larger than the cap is shrunk to, preserving proportions and rounding
## to whole pixels: `4000x3000 -> 1440x1080`, `16384x16384 -> 1080x1080`. A source at or below
## the cap is returned unchanged (no upscaling).
result = (w, h)
if w <= 0 or h <= 0 or not exceedsMapCap(float(w), float(h)): return
let scale = min(1.0, min(float(MapCapLongSide) / max(float(w), float(h)),
float(MapCapShortSide) / min(float(w), float(h))))
result = (max(1, int(round(float(w) * scale))), max(1, int(round(float(h) * scale))))
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).