diff --git a/README.md b/README.md index 279a8bc..da2c4b9 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,43 @@ Re-running prints the same key. `gm-key --new` rotates it and revokes every GM s in-browser way to become GM and no first-visitor claim: without the key you only ever see the sign-in page. +### Import the map + +The map is a source image plus a tiled copy the server gates per player. One offline command slices +the image and updates the scene; the server must be **stopped** for it (it reads the scene once at +startup) and restarted afterwards. ImageMagick comes from the root devbox. + +```sh +# stop the server first, then: +devbox run -- ./run/fff-vtt import --state-dir=run --image=/path/to/map.png --tile-size=64 +# restart the server with the usual command +``` + +| argument | meaning | +|---|---| +| `--image=` | source PNG or WebP (required); tiles are always PNG | +| `--tile-size=` | tile edge, default the scene's current tile size; must be a positive multiple of the 32 px explored cell (so 32 or the 64 px fallback) | +| `--scene=` | target scene; v1 has exactly one, id 1 | +| `--state-dir=` | the same state dir as the server (default `run`) | + +Tiles land in `/tiles/1/v/_.png`, origin at the world origin, which is +exactly what the gate parses and nginx's internal `/_tiles/` alias serves. The command sets the +scene's width, height and tile size from the image. Importing again grows `art_version` and writes a +new `v` directory, so browsers never keep a stale tile; old versions stay on disk until the M6 +cleanup. Any problem exits non-zero and writes nothing: a missing/unreadable source or state dir, an +unsupported or multi-frame image, a scene other than 1, a tile size that is not a multiple of the +cell, or a server still holding the state-dir lock (exit 3). + +**A 16384 px scene with 50 tokens (the phone-playtest target).** + +1. Prepare a 16384×16384 PNG or WebP. `--tile-size=64` is the designed fallback and gives 256×256 = + 65,536 tiles (32 px would give 262,144 files); ImageMagick keeps the source in a disk-backed + pixel cache, so allow temp space and a few minutes rather than gigabytes of RAM. +2. Stop the server, run the import above, restart it. +3. Create the 50 tokens with the GM token panel (or the `token.create` intent); tokens, walls and + explored state are untouched by the import. +4. Point nginx's `/_tiles/` alias at `/tiles` as shown below. + ### Start the server ```sh @@ -116,11 +153,11 @@ backup timer) exists in the repo yet; that is M6. count toward the cap. 3. **Map.** Only one scene exists. It is seeded at 4096×4096 px with 32 px tiles and cells, a 400 px default vision radius, a 20 px default token radius and no grid (the grid toggle exists, but the - seeded grid size is 0 and only `scene.set` can change it). There is **no map upload and no - import command yet**: browser upload is post-v1 and the map import CLI is M6. Today you put the - tile images in `/tiles/1/v1/_.png` yourself (32 px PNGs, `x` left to right and - `y` top to bottom from the world origin, no leading zeros). A player is served a tile only after - they have explored a cell that overlaps it; the GM + seeded grid size is 0 and only `scene.set` can change it). Replace the map with the offline + import CLI described under *Import the map* (`fff-vtt import`, server stopped first, restarted + after): it writes the tile tree under `/tiles/1/v/` and sets the width, + height and tile size. There is still **no browser upload** (post-v1). A player is served a tile + only after they have explored a cell that overlaps it; the GM always gets every tile. Because one 32 px cell is the unit of disclosure, do not paint secret doors, traps or notes into map art near places players can reach — keep secrets as GM-only tokens. 4. **Tokens.** *Create token* takes a kind, a descriptive name, an actual name, a position, a radius @@ -153,7 +190,7 @@ you write to the wire yourself: Still missing entirely: -- map upload or an import command (browser upload is post-v1, the import CLI is M6); +- browser map upload (post-v1; the offline `fff-vtt import` CLI exists); - wall thickness, height, see-over and wall placement (built after the phone playtest, ADR-0012); - the graded who-sees-it fraction (needs wall heights); - the NixOS module, systemd unit and backup timer (M6); diff --git a/devbox.json b/devbox.json index 9bbe868..3dbc789 100644 --- a/devbox.json +++ b/devbox.json @@ -17,7 +17,8 @@ }, "nginx": "latest", "openssl": "latest", - "chromium": "latest" + "chromium": "latest", + "imagemagick": "latest" }, "shell": { "init_hook": [], diff --git a/devbox.lock b/devbox.lock index 3c461fb..8267862 100644 --- a/devbox.lock +++ b/devbox.lock @@ -456,6 +456,68 @@ } } }, + "imagemagick@latest": { + "last_modified": "2026-10-07T09:43:42Z", + "resolved": "github:NixOS/nixpkgs/39ad350a0602fa0a58a544344e3e9187526ea45c#imagemagick", + "source": "devbox-search", + "version": "7.1.2-31", + "systems": { + "aarch64-darwin": { + "outputs": [ + { + "name": "out", + "path": "/nix/store/w943n99gba8wqiznbvl3v1a5bz1aj1hs-imagemagick-7.1.2-31", + "default": true + }, + { + "name": "dev", + "path": "/nix/store/h5381l00wa4a8l42d5wf20f1i6nzsbdi-imagemagick-7.1.2-31-dev" + }, + { + "name": "doc", + "path": "/nix/store/rqwrgqsbh8jgximpzd8cnixhpfscss1k-imagemagick-7.1.2-31-doc" + } + ], + "store_path": "/nix/store/w943n99gba8wqiznbvl3v1a5bz1aj1hs-imagemagick-7.1.2-31" + }, + "aarch64-linux": { + "outputs": [ + { + "name": "out", + "path": "/nix/store/jwa4dla37chizyjlhafhq5dz4bkfchgq-imagemagick-7.1.2-31", + "default": true + }, + { + "name": "dev", + "path": "/nix/store/mpd89rd3lxyjc4fpb9jzqr55ik57r8nk-imagemagick-7.1.2-31-dev" + }, + { + "name": "doc", + "path": "/nix/store/8bm6yz8yy86sai52vnfcd4a6n7z7adnf-imagemagick-7.1.2-31-doc" + } + ], + "store_path": "/nix/store/jwa4dla37chizyjlhafhq5dz4bkfchgq-imagemagick-7.1.2-31" + }, + "x86_64-linux": { + "outputs": [ + { + "name": "out", + "path": "/nix/store/s13s3r3pi67vj27s6ca7pbrxs2z4zjf6-imagemagick-7.1.2-31", + "default": true + }, + { + "name": "dev", + "path": "/nix/store/6b18lsv6dy2vss0adl6n9zrjgx1r3ixg-imagemagick-7.1.2-31-dev" + }, + { + "name": "doc", + "path": "/nix/store/pjx3bsd4p2qssg4gaph70x7qz9vzzb9p-imagemagick-7.1.2-31-doc" + } + ], + "store_path": "/nix/store/s13s3r3pi67vj27s6ca7pbrxs2z4zjf6-imagemagick-7.1.2-31" + } + } + }, "nginx@latest": { "last_modified": "2026-10-02T22:55:44Z", "plugin_version": "0.0.4", diff --git a/docs/DESIGN-history.md b/docs/DESIGN-history.md index e48ec23..597f661 100644 --- a/docs/DESIGN-history.md +++ b/docs/DESIGN-history.md @@ -870,6 +870,21 @@ radius starts blank (scene default), on create and on edit. No wire default chan follows the existing `'{}'` reading rather than choosing "vision on for a player-controlled token". See current 8. +Owner also decided 2026-11-21 [FIXED (owner-delegated, 2026-11-21, #79; recorded here in the +decision log that continues the old §C)]: **the map import CLI moves from M6 to M4.** It is the +designed CLI of 11.1, not a throwaway seeder: `fff-vtt import --image= [--scene=1] +[--tile-size=] [--state-dir=]` writes `/tiles//v/_.png` +(origin at the world origin) and updates the one scene row's `w`, `h`, `tile_size` and `art_version`. +A re-import for art that already exists grows `art_version`; old versions stay until M6 cleanup. It +takes the state-dir lock (a live server refuses it, exit 3) because the server reads the scene at +startup, so the operator stops the server, imports and restarts. `--tile-size` defaults to the +scene's tile size and must be a positive multiple of the explored cell (64 px fallback). Decoding +uses ImageMagick from the root devbox with disk-backed pixel-cache limits, so a 16384 px source is +memory-sane; no Nim/npm image dependency is added and the FIXED stack (2) is unchanged. This note +supersedes #63's "map import CLI (M6)" Out-of-Scope line for the CLI only; NixOS deployment, the +production vhost and tile-version cleanup stay M6. See current 3.3, 6.1, 11.1, 13 and TESTING 3.3 / +10.3. + ## D. Superseded statements removed from the current spec Each entry quotes the superseded statement (excerpt) and names the surviving rule. diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 57c27df..c6ee39b 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -306,9 +306,9 @@ Notes: error, not a leak. - Tile URLs include the scene's `art_version` so that re-imported art does not hit stale caches [FIXED, owner decision 2026-11-14, #7]: from M3 on, always `1` in M3. The gate reads - `/tiles//v/` (layout fixed in M3; writing versions and cleanup are M6, - 11.1). Response `Cache-Control: private` [FIXED, owner decision 2026-11-14, #7], not the - prototype's `no-store`. + `/tiles//v/` (layout fixed in M3; writing versions is the import CLI of + 11.1, pulled forward to M4 by #79; cleanup remains M6). Response `Cache-Control: private` [FIXED, + owner decision 2026-11-14, #7], not the prototype's `no-store`. - **URL grammar and status split [FIXED (owner-delegated), 2026-11-15, #24].** Every numeric component is canonical decimal: digits only, no sign, no space, **no leading zero** (`0` alone is the only zero), bounded at 9 digits for `` and `` (`v` + digits) and 5 digits @@ -1393,7 +1393,7 @@ on any G-only intent is implied and not repeated. | t | fields | who | ack ok / extra codes | effects and recipients | |---|---|---|---|---| -| `scene.set` | `scene`; any of `name, grid_size, vision_radius_default, token_radius_default, extra` (at least one) | G | `{}`; `invalid`, `not-found` | `hello` plus full resync to **every** connection (hello-equivalent reset; no `scene.activate`, Q3). `token_radius_default` change resizes tokens using the default with grow push (5.6): `token` updates per view, `vision`/`explored` as needed. `w, h, tile_size, cell, art_version` are not settable on the wire (import is M6 CLI) | +| `scene.set` | `scene`; any of `name, grid_size, vision_radius_default, token_radius_default, extra` (at least one) | G | `{}`; `invalid`, `not-found` | `hello` plus full resync to **every** connection (hello-equivalent reset; no `scene.activate`, Q3). `token_radius_default` change resizes tokens using the default with grow push (5.6): `token` updates per view, `vision`/`explored` as needed. `w, h, tile_size, cell, art_version` are not settable on the wire (import is the offline CLI, 11.1) | | `wall.add` | `scene, a:[x,y], b:[x,y]`; geometry `thickness?` (px, 0..256, default 0), `position?` (`center|left|right`, default `center`), `height?` (metres, `>0`..`<=100`, `null`/absent = full height); then either a preset name (`preset:"wall"|"door"|"window"|"one_way"`) or the raw 5.8 switches (`blocks_sight?, blocks_movement?, sight_dir?, player_marker?, door?, open?, secret?, locked?`); `label?`, `flags?` | G | `{id}`; `invalid`, `not-found` | `wall` to GM; vision recompute for all players (`vision`, `explored`, `token` as their views change); tokens whose circle overlaps get `stuck` source `walls` (5.5): `token` per view; a newly seen marker (5.8) to the players who see it | | `wall.update` | `scene, id`; any of `a, b, thickness, position, height (null = full height)`, a preset name or the raw switches, `label` (`null` clears), `flags` | G | `{}`; `not-found`, `invalid` | as `wall.add` (update = remove + add for the status rules, 5.5; PROPOSED there); a marker whose cause changed is retracted, a moved one is re-earned (5.8) | | `wall.remove` | `scene, id` | G | `{}`; `not-found` | `wall_gone` to GM; recompute; `walls`-sourced entries re-evaluated (Keep/Clear, 5.5) | @@ -1503,7 +1503,7 @@ switches, never `thickness`, `position` or `height` (#50). - `extra`: a JSON object, stored verbatim and never interpreted; the GM sees it in `hello`. It carries the same opaque caps as wall `flags` [FIXED (owner-delegated), 2026-11-20, #35]: 8 KB serialized, 64 keys per object, depth 8; over a cap is `invalid` and applies none of the patch. -- `w`, `h`, `tile_size`, `cell` and `art_version` are **not** patch fields (import is the M6 CLI): +- `w`, `h`, `tile_size`, `cell` and `art_version` are **not** patch fields (import is the offline CLI, 11.1): they are unknown fields and ignored (6.2), so a patch carrying only one of them has no field at all and is `invalid`. - Persistence: one `FULL` transaction writes the scene row and every token whose effective radius @@ -2263,10 +2263,23 @@ See TESTING §10.4 (Node 26 black-box harnesses, built-ins only, `devbox run tes - No `limit_req` on `/join` (owner, #6: no rate limit on key entry; ~100-bit key space). - Prototype nginx config (`docs/archive/prototypes/server-vision/nginx/nginx.conf`) is the functional reference; its `listen` has no address (binds all) and its temp/log paths are dev-only. -- Map import: offline CLI that slices an image into `tile_size` PNG/WebP tiles into - `/tiles//v/` and registers/updates the scene (prototype: - `tools/genmap.mjs`, deterministic, hand-authored, not reusable as the importer). Browser upload is - post-v1; CLI-only import in v1 (Q5 FIXED). +- Map import [FIXED (owner-delegated), 2026-11-21, #79; pulled forward from M6]: offline CLI + `fff-vtt import --image= [--scene=1] [--tile-size=] [--state-dir=]` slices + one source image into `tile_size` PNG tiles into `/tiles//v/` and + registers/updates the scene row's `w`, `h`, `tile_size` and `art_version`; the tile grid origin is + the world origin and names are the gate's `_.png` (3.3). `art_version` grows on a re-import + for a scene that already has art, so browsers never serve a stale cached tile; older versions stay + on disk (cleanup remains M6). `--tile-size` defaults to the scene's current tile size and must be a + positive multiple of the explored cell, so 64 px is the designed fallback. The state-dir lock of + 3.2/11.1 is taken (a live server refuses the import, exit 3): the server reads the scene at startup + (4.1), so the operator stops it, imports and restarts. Invalid input, an unsupported/multi-frame + image, a scene other than the one v1 scene, a bad tile size, a missing/unreadable state dir or DB + and a held lock all exit non-zero with a message and write nothing. Decoding is ImageMagick from + the root devbox (`imagemagick`); it is run with `-limit memory 256MiB -limit map 512MiB` so its + pixel cache is disk-backed and a 16384 px source stays memory-sane. No Nim/npm image dependency is + added, the FIXED stack (2) is unchanged, and the archived prototype's deterministic + `docs/archive/prototypes/server-vision/tools/genmap.mjs` fixture generator is not reused. Browser + upload is post-v1; CLI-only import in v1 (Q5 FIXED). ### 11.2 Backups [PROPOSED] - SQLite: systemd timer running an online backup (`.backup` or `VACUUM INTO`) to a dated file in a @@ -2338,6 +2351,9 @@ columns with today's defaults) lands complete now, so the later build needs no m prediction/rollback, DOM overlay, reconnect backoff, reducer tests; `prototype-*` archived under `docs/archive/prototypes/` (Q24). Thickness and height controls are not in M4 (build order above; 5.7, 5.10). + - **Map import CLI** [FIXED (owner-delegated), 2026-11-21, #79; moved here from M6]: the designed + offline importer of 11.1 is built in M4 because the gate needs a 16384 px tiled scene and + `scene.set` cannot set `w`, `h`, `tile_size`, `cell` or `art_version` (6.1). - Accept: headless e2e (fog pixel checks, player traffic audit clean, reconnect restores) - met by `devbox run e2e` including `client/e2e/audit.test.mjs`; the manual run on laptop and Note 10 at 60 fps with 50 tokens on a 16384 px tiled map (test target PROPOSED, Q2) with fog active is @@ -2358,7 +2374,8 @@ columns with today's defaults) lands complete now, so the later build needs no m timeout; stats computation outside the lock. - **M6 - NixOS deployment.** `nix/` per Q20 (`lock.json`, `package.nix`, `module.nix` with `services.fffVtt`), client build, nginx vhost, systemd hardening, backups timer and restore drill, - map import CLI. Accept: deployed behind HTTPS; direct `/_tiles/` 404; WS upgrade works; phone + tile-version cleanup. The map import CLI moved to M4 (#79, 2026-11-21); M6 keeps only its cleanup + and deployment fit. Accept: deployed behind HTTPS; direct `/_tiles/` 404; WS upgrade works; phone sign-in works; no secret in the access log; backup and restore drill passes. - **M7 - Real-world pass.** Real-network latency/throughput run, iOS/Safari check if available, one real session with the owner's table, SLOW lines collected. Accept: documented numbers, defects diff --git a/docs/TESTING.md b/docs/TESTING.md index 62f6d27..3140095 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -57,6 +57,13 @@ built against glibc 2.44 while this host (NixOS) runs 2.42, so a 2.44-built `lib - Slice 9 (#24) pins the full status split of DESIGN §3.3: `404` also for another scene or a stale art version, `403` also for a missing or unknown session (one response with "unexplored"), and `Cache-Control: private`. The proving group is §10.3 Tiles (`tools/tiles.test.mjs`). +- Map import (#79) writes the tree this gate parses: `tools/import.test.mjs` runs the real binary's + `fff-vtt import`, checks the exact `_.png` set and per-tile geometry, then starts the real + server and test nginx and proves a player with an explored overlapping cell gets `200` (and an + unexplored tile `403`, another art version `404`). A re-import grows `art_version` and the + restarted server serves the `v` tree. Every refused import (bad/absent image, unsupported or + multi-frame format, scene ≠ 1, `tile_size % cell ≠ 0`, absent state dir or DB, held lock) exits + non-zero and leaves no tile tree. This is §10.3 Tiles evidence. ### 3.4 Threat list @@ -412,6 +419,17 @@ from the prototype, what was missing, what the M3 build added, and the tools it answer carries `X-Accel-Redirect: /_tiles/1/v1/_.png`, `Cache-Control: private` and an empty body. Fixture tiles are 32 px PNGs written by `tools/tilefixture.mjs` under the state dir at test time; the test asserts the repo tracks no `.png` at all. +- **Map import CLI (#79)**: `tools/import.test.mjs` is the black-box harness for the offline + `fff-vtt import` subcommand (DESIGN 11.1, 3.3). It writes a real fixture PNG at test time, runs + the binary, and asserts the exact gate tree (`tiles/1/v1/_.png`, row-major, 4x3 at 64 px), + each tile's 64x64 geometry, the scene row via `hello.scene` (w, h, tile_size, art_version), and a + player with an explored overlapping cell getting `200` through the real nginx+server stack while + an unexplored tile gets `403` and a stale version `404`. A second import must grow `art_version` + and a restarted server must serve the `v` tree (the persisted explored grid still allows it). + Negative cases each exit non-zero and leave no tile tree: missing/unsupported/multi-frame image, + `--scene` other than 1, `tile_size % cell != 0`, absent state dir, state dir without `state.db`, + and a running server holding the state-dir lock (exit 3). `tools/groups.mjs` registers the first + title as Tiles evidence. - **Probing test (T8)**: M2, in-process against the move-rules module (DESIGN §5.5): arbitrary far moves; assertion: facts about walls/doors beyond LOS recoverable from replies <= a bounded amount (step cap), and uniform nack shape. M3: same test over WS with a hostile client (moved from M2). diff --git a/server/importer.nim b/server/importer.nim new file mode 100644 index 0000000..1f1098e --- /dev/null +++ b/server/importer.nim @@ -0,0 +1,280 @@ +## 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 +## `/tiles//v/` (origin at the world origin, names `_.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 (Q16-HDRI stores it in ImageMagick's *disk-backed* pixel cache under the +## explicit `-limit memory/-limit map` below, so RSS stays bounded). 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. +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). + ImportUsage* = """fff-vtt import --image= [options] + +Slice a map image into the scene's tile tree and register the scene dimensions. + +Options: + --image= Source image (PNG or WebP). Required. + --tile-size= 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. + --scene= Target scene. v1 has exactly one scene, id 1. + --state-dir= Directory holding state.db and tiles (default: run). The server must be + stopped: the state-dir lock is refused (exit 3), like gm-key --new. + +Tiles land in /tiles//v/_.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] + +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 state dir and the source before touching either one: an error changes nothing. + if not dirExists(a.cfg.stateDir): + return failImport("state dir \"" & a.cfg.stateDir & + "\" does not exist or is not readable; create it by running the server or gm-key once", 1) + if not fileExists(a.cfg.dbPath): + return failImport("no state.db in \"" & a.cfg.stateDir & + "\"; create it by running the server or gm-key once", 1) + if not fileExists(a.image): + return failImport("source image \"" & a.image & "\" does not exist", 1) + let imagePath = expandFilename(a.image) + + # Identify: dimensions and one format only. 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", imagePath]) + if ident.status != 0: + return failImport("cannot read image \"" & a.image & "\": " & lastLine(ident.output), 1) + let parts = ident.output.splitWhitespace + if parts.len != 3: + 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: int + try: + imgW = parseInt(parts[0]) + imgH = parseInt(parts[1]) + 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) + + 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 + try: + conn = openDatabase(a.cfg.dbPath) + except CatchableError as e: + return failImport("cannot open " & a.cfg.dbPath & ": " & e.msg, 1) + defer: close(conn) + + let loaded = loadScene(conn) + if loaded.isNone: + return failImport("state.db has no scene " & $DefaultSceneId & + "; start the server once to migrate and seed it", 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 is the designed fallback)", 2) + + 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): 256 MiB heap and a 512 MiB map cap push ImageMagick's pixel + # cache to disk, so a 16384 px source never needs a whole-image buffer in RAM. `-crop` with + # `+repage` emits tiles in row-major order; `tile_%d.png` is renamed below to the gate's exact + # `_.png` spelling (no leading zeros). + 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 diff --git a/server/main.nim b/server/main.nim index ca1039e..849225d 100644 --- a/server/main.nim +++ b/server/main.nim @@ -45,7 +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 +import importer, sessions const CookieName* = "fff_session" @@ -2019,7 +2019,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = of "scene.set": # DESIGN 6.1, slice 10 / #25: a hello-equivalent reset of every connection (the client resets on # `hello`, 6.1) after a GM edit of the settable scene fields. `w`, `h`, `tile_size`, `cell` and - # `art_version` are not patch fields (import is the M6 CLI) and are ignored as unknown fields + # `art_version` are not patch fields (import is the offline CLI, 11.1) and are ignored as unknown fields # (6.2); a patch carrying only those has no field and is `invalid`. if not sceneOk(conn, env): return var patchOpt = parseScenePatch(env.node) @@ -2366,6 +2366,7 @@ proc cliUsage(): string = Usage: fff-vtt [options] fff-vtt gm-key [--new] [options] + fff-vtt import --image= [--scene=] [--tile-size=] [options] Options: --public-origin= Browser origin the site is served from (default: http://localhost:8080). @@ -2378,6 +2379,9 @@ Commands: gm-key Create the single GM if needed and print the GM key (same key on re-run). gm-key --new Rotate the GM key and revoke all GM sessions. Refused while the server holds the state-dir lock (stop the server first). + import Slice a PNG/WebP map into the scene's tile tree and update the scene row. + Stop the server first (it reads the scene at startup); restart it after. + Run `fff-vtt import --help` for the import arguments. The bind address is fixed at 127.0.0.1 and is not a key: put nginx (or another TLS proxy) in front. """ @@ -2533,6 +2537,8 @@ proc main() = let args = commandLineParams() if args.len > 0 and args[0] == "gm-key": quit runGmKey(if args.len > 1: args[1 .. ^1] else: @[]) + if args.len > 0 and args[0] == "import": + quit runImport(if args.len > 1: args[1 .. ^1] else: @[]) var cfg: Config try: diff --git a/server/world.nim b/server/world.nim index b55fb12..82d7e26 100644 --- a/server/world.nim +++ b/server/world.nim @@ -116,7 +116,7 @@ type ScenePatch* = object ## `scene.set` (DESIGN 6.1): every field is optional; an absent field keeps its value. - ## `w`, `h`, `tile_size`, `cell` and `art_version` are not patch fields (import is the M6 CLI): + ## `w`, `h`, `tile_size`, `cell` and `art_version` are not patch fields (import is the offline CLI, 11.1): ## they are unknown fields and ignored (6.2), so a patch with only one of them has no field at ## all and is `invalid`. name*: Option[string] diff --git a/tools/groups.mjs b/tools/groups.mjs index 3f7641b..b7d994a 100644 --- a/tools/groups.mjs +++ b/tools/groups.mjs @@ -31,7 +31,7 @@ export const GROUPS = { ], }, tiles: { - files: ['tiles.test.mjs', 'oneway.test.mjs'], + files: ['tiles.test.mjs', 'oneway.test.mjs', 'import.test.mjs'], evidence: [ { file: 'tiles.test.mjs', test: 'tile gate: leak check (d) matches the independent explored oracle', @@ -43,6 +43,10 @@ export const GROUPS = { { file: 'tiles.test.mjs', test: 'tile gate: revocation is immediate and sessions survive a restart (#65)', minAsserts: 6, requires: ['rawUpgrade'] }, + // #79: the map import CLI writes the tree this gate parses, and a restarted server serves it. + { file: 'import.test.mjs', + test: 'map import CLI: a fixture slices into v1 tiles, the scene row and a 200 through the gate', + minAsserts: 12, requires: ['runImport'] }, { file: 'oneway.test.mjs', test: 'one-way sight: the blind side sees nothing across, the seeing side does (#58)', minAsserts: 12, requires: ['withOneWayStack'] }, diff --git a/tools/import.test.mjs b/tools/import.test.mjs new file mode 100644 index 0000000..21a467e --- /dev/null +++ b/tools/import.test.mjs @@ -0,0 +1,213 @@ +// #79: the map import CLI (DESIGN 11.1 "Map import", 3.3, 13 M4; pulled forward from M6). This is +// the black-box harness for the offline command, in the same style as the other tools/*.test.mjs: +// it runs the real binary's `import` subcommand against an isolated state dir, inspects the tile +// tree the gate parses, then starts the real server (+ test nginx, 11.1) and proves a player with +// explored cells is served a new tile through the gate. It also pins the re-import art_version bump +// and the "refused import changes nothing" cases (bad image/format, wrong scene, bad tile size, +// absent state dir, no schema, and the state-dir lock held by a running server). +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { spawnSync } from 'node:child_process' +import { createPlayer, freePort, httpsBaseUrl, namePlayer } from './lib.mjs' +import { buildServer, gmKeyOf, makeStateDir, openAs, startServer, stopServer } from './withserver.mjs' +import { startTestNginx, stopTestNginx } from './nginx.mjs' +import { isPng, pngBytesWH, pngSize } from './tilefixture.mjs' + +function runImport(stateDir, args) { + const r = spawnSync(buildServer(), ['import', `--state-dir=${stateDir}`, ...args], + { encoding: 'utf8' }) + return { status: r.status, stdout: r.stdout, stderr: r.stderr } +} + +// A 256x192 fixture: 4x3 tiles at 64 px, every pixel's colour derived from its coordinates, so the +// source is real image data (not a blank canvas) and the slice positions are distinct files. +function writeFixtureImage(file) { + fs.writeFileSync(file, pngBytesWH(256, 192, (x, y) => [x & 0xff, y & 0xff, 128])) + return file +} + +function tileNames(dir) { + return fs.readdirSync(dir).filter(n => n.endsWith('.png')).sort() +} + +async function withGateStack(stateDir, fn) { + const nginxPort = await freePort() + const s = await startServer({ stateDir, publicOrigin: httpsBaseUrl(nginxPort) }) + let ngx + try { + ngx = await startTestNginx({ backendPort: s.port, stateDir, port: nginxPort }) + return await fn({ s, ngx }) + } finally { + await stopTestNginx(ngx) + await stopServer(s) + } +} + +async function tileStatus(origin, version, x, y, cookie) { + const r = await fetch(`${origin}/tiles/1/v${version}/${x}_${y}.png`, { headers: { Cookie: cookie } }) + return { status: r.status, body: Buffer.from(await r.arrayBuffer()) } +} + +// A GM, a named player and one vision token at (30, 30) with radius 100: tile 0_0 is explored, +// tile 3_2 is not. Returns the connections the gate assertions use. +async function sceneWithPlayer(origin, gmKey) { + const gm = await openAs(origin, gmKey) + await gm.ws.waitText('hello') + await gm.ws.waitText('walls') + const player = await createPlayer(gm.ws) + await namePlayer(origin, player.key, 'Alice') + const created = await gm.ws.request({ t: 'token.create', scene: 1, kind: 'pc', pos: [30, 30], + flags: { vision: true }, vision_radius: 100, + controller: player.id, descriptive_name: 'Alice', + actual_name: 'Alice' }) + assert.equal(created.ok, true, JSON.stringify(created)) + const seen = await openAs(origin, player.key) + await seen.ws.waitText('hello') + await seen.ws.waitFor(m => m.t === 'explored' && m.full === true) + return { gm, seen, player } +} + +test('map import CLI: a fixture slices into v1 tiles, the scene row and a 200 through the gate', async () => { + const stateDir = makeStateDir() + const gmKey = gmKeyOf(stateDir) + const img = writeFixtureImage(path.join(stateDir, 'map.png')) + let playerKey + try { + const first = runImport(stateDir, [`--image=${img}`, '--tile-size=64']) + assert.equal(first.status, 0, first.stderr) + assert.match(first.stdout, /256x192 px, tile 64 px, 4x3 tiles/) + const dir1 = path.join(stateDir, 'tiles', '1', 'v1') + const names = tileNames(dir1) + assert.deepEqual(names, [ + '0_0.png', '0_1.png', '0_2.png', '1_0.png', '1_1.png', '1_2.png', + '2_0.png', '2_1.png', '2_2.png', '3_0.png', '3_1.png', '3_2.png', + ], 'the tree is the gate grammar: _.png, row-major origin at the world origin') + for (const n of names) assert.deepEqual(pngSize(path.join(dir1, n)), { width: 64, height: 64 }) + assert.equal(fs.readdirSync(path.join(stateDir, 'tiles', '1')).some(n => n.startsWith('.import-')), + false, 'no temporary directory is left behind') + + await withGateStack(stateDir, async ({ ngx }) => { + const { gm, seen, player } = await sceneWithPlayer(ngx.origin, gmKey) + playerKey = player.key + const hello = gm.ws.messages.find(m => m.t === 'hello' && m.scene) + assert.equal(hello.scene.w, 256, 'the scene row follows the image width') + assert.equal(hello.scene.h, 192, 'the scene row follows the image height') + assert.equal(hello.scene.tile_size, 64, 'tile_size is the import argument (64 px fallback)') + assert.equal(hello.scene.art_version, 1, 'a first import keeps the seeded version') + const allowed = await tileStatus(ngx.origin, 1, 0, 0, seen.cookie) + assert.equal(allowed.status, 200, 'a player with an explored overlapping cell gets the tile') + assert.ok(isPng(allowed.body), 'nginx serves the imported tile bytes through the internal alias') + assert.equal((await tileStatus(ngx.origin, 1, 3, 2, seen.cookie)).status, 403, + 'an unexplored tile is still refused') + assert.equal((await tileStatus(ngx.origin, 1, 3, 2, gm.cookie)).status, 200, + 'the GM is always allowed an in-range tile') + assert.equal((await tileStatus(ngx.origin, 2, 0, 0, seen.cookie)).status, 404, + 'a version that is not the scene art_version does not exist') + gm.ws.close(); seen.ws.close() + }) + + // Re-import: the existing v1 art means the scene must advertise v2, so no client cache serves + // the old tiles. v1 stays on disk (cleanup is M6), and the restarted server serves v2. + const second = runImport(stateDir, [`--image=${img}`, '--tile-size=64']) + assert.equal(second.status, 0, second.stderr) + assert.match(second.stdout, /art_version 2/) + assert.equal(tileNames(path.join(stateDir, 'tiles', '1', 'v2')).length, 12) + assert.equal(tileNames(path.join(stateDir, 'tiles', '1', 'v1')).length, 12, + 'the previous version is untouched') + + await withGateStack(stateDir, async ({ ngx }) => { + const gm = await openAs(ngx.origin, gmKey) + await gm.ws.waitText('hello') + const hello = gm.ws.messages.find(m => m.t === 'hello' && m.scene) + assert.equal(hello.scene.art_version, 2, 'a restart loads the re-imported scene row') + const signed = await openAs(ngx.origin, playerKey) + await signed.ws.waitText('hello') + const allowed = await tileStatus(ngx.origin, 2, 0, 0, signed.cookie) + assert.equal(allowed.status, 200, 'the persisted explored grid still allows the new tile') + assert.ok(isPng(allowed.body)) + assert.equal((await tileStatus(ngx.origin, 1, 0, 0, signed.cookie)).status, 404, + 'the stale version is no longer the scene art_version') + gm.ws.close(); signed.ws.close() + }) + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }) + } +}) + +test('map import CLI: every refused import exits non-zero with a message and changes nothing', + async () => { + const stateDir = makeStateDir() + gmKeyOf(stateDir) + const img = writeFixtureImage(path.join(stateDir, 'map.png')) + const tiles = path.join(stateDir, 'tiles') + const gif = path.join(stateDir, 'tiny.gif') + fs.writeFileSync(gif, Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64')) + const corrupt = path.join(stateDir, 'corrupt.png') + fs.writeFileSync(corrupt, 'not an image') + try { + const cases = [ + [[`--image=${path.join(stateDir, 'missing.png')}`], /does not exist/], + [[`--image=${gif}`], /unsupported format GIF/], + [[`--image=${corrupt}`], /cannot read image/], + [[`--image=${img}`, '--tile-size=48'], /multiple of the scene's explored cell/], + [[`--image=${img}`, '--tile-size=0'], /must be positive/], + [[`--image=${img}`, '--scene=2'], /exactly one scene, id 1/], + [[`--image=${img}`, '--tile-size=abc'], /whole number/], + [[], /--image is required/], + ] + for (const [args, message] of cases) { + const r = runImport(stateDir, args) + assert.notEqual(r.status, 0, `must fail: ${args.join(' ')}`) + assert.match(r.stderr, message, `clear message for: ${args.join(' ')}`) + assert.equal(fs.existsSync(tiles), false, `nothing written for: ${args.join(' ')}`) + } + + const help = runImport(stateDir, ['--help']) + assert.equal(help.status, 0, help.stderr) + assert.match(help.stdout, /--image=/) + assert.match(help.stdout, /state-dir lock is refused/) + + const ghost = path.join(os.tmpdir(), `fffvtt-absent-${process.pid}-${Date.now()}`) + const absent = runImport(ghost, [`--image=${img}`]) + assert.notEqual(absent.status, 0) + assert.match(absent.stderr, /does not exist/) + assert.equal(fs.existsSync(ghost), false, 'an absent state dir is not created') + + const empty = makeStateDir() + const noDb = runImport(empty, [`--image=${img}`]) + assert.notEqual(noDb.status, 0) + assert.match(noDb.stderr, /no state\.db/) + assert.equal(fs.existsSync(path.join(empty, 'tiles')), false) + fs.rmSync(empty, { recursive: true, force: true }) + + // An unreadable DB (the state-dir contents cannot be opened) is a clear runtime error, not a + // migration attempt or a partial import. + const dbFile = path.join(stateDir, 'state.db') + fs.chmodSync(dbFile, 0o000) + try { + const unreadable = runImport(stateDir, [`--image=${img}`]) + assert.notEqual(unreadable.status, 0) + assert.match(unreadable.stderr, /cannot open/) + assert.equal(fs.existsSync(tiles), false) + } finally { + fs.chmodSync(dbFile, 0o600) + } + + // The state-dir lock of 3.2/11.1: a live server blocks the import (like gm-key --new), so a + // running process cannot keep serving the old in-memory scene while the row changes. + const s = await startServer({ stateDir }) + try { + const locked = runImport(stateDir, [`--image=${img}`, '--tile-size=64']) + assert.equal(locked.status, 3, locked.stderr) + assert.match(locked.stderr, /server is running.*state-dir lock held/) + assert.equal(fs.existsSync(tiles), false, 'a locked import writes no tile') + } finally { + await stopServer(s) + } + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }) + } + }) diff --git a/tools/tilefixture.mjs b/tools/tilefixture.mjs index 2013dd0..0de7015 100644 --- a/tools/tilefixture.mjs +++ b/tools/tilefixture.mjs @@ -36,29 +36,46 @@ function chunk(type, data) { // A solid-colour 8-bit RGB PNG of `size` x `size` (filter 0 on every scanline). export function pngBytes(size, rgb) { + return pngBytesWH(size, size, () => rgb) +} + +// A width x height 8-bit RGB PNG; `colourAt(x, y)` returns [r,g,b] (filter 0 on every scanline). +export function pngBytesWH(width, height, colourAt) { const ihdr = Buffer.alloc(13) - ihdr.writeUInt32BE(size, 0) - ihdr.writeUInt32BE(size, 4) + ihdr.writeUInt32BE(width, 0) + ihdr.writeUInt32BE(height, 4) ihdr[8] = 8 // bit depth ihdr[9] = 2 // colour type: truecolour (RGB) ihdr[10] = 0 // compression ihdr[11] = 0 // filter ihdr[12] = 0 // interlace - const row = Buffer.alloc(1 + size * 3) - for (let x = 0; x < size; x++) { - row[1 + x * 3] = rgb[0] - row[2 + x * 3] = rgb[1] - row[3 + x * 3] = rgb[2] + const rows = [] + for (let y = 0; y < height; y++) { + const row = Buffer.alloc(1 + width * 3) + for (let x = 0; x < width; x++) { + const rgb = colourAt(x, y) + row[1 + x * 3] = rgb[0] + row[2 + x * 3] = rgb[1] + row[3 + x * 3] = rgb[2] + } + rows.push(row) } - const raw = Buffer.concat(Array.from({ length: size }, () => row)) return Buffer.concat([ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk('IHDR', ihdr), - chunk('IDAT', zlib.deflateSync(raw, { level: 6 })), + chunk('IDAT', zlib.deflateSync(Buffer.concat(rows), { level: 6 })), chunk('IEND', Buffer.alloc(0)), ]) } +// The width/height of a PNG file from its IHDR (the import test checks the sliced geometry). +export function pngSize(file) { + const buf = fs.readFileSync(file) + if (!isPng(buf) || buf.length < 24) throw new Error(`${file}: not a PNG`) + return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) } +} + + export function isPng(buf) { return Buffer.isBuffer(buf) && buf.length > 8 && buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))