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

374 lines
19 KiB
JavaScript
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.
// #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 path from 'node:path'
import { spawnSync } from 'node:child_process'
import { DatabaseSync } from 'node:sqlite'
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/)
// #83: a long import must say where it is, and the streamed slice reports one line per row
// band (the old one-shot crop printed nothing for minutes and looked hung).
assert.match(first.stderr, /slicing 256x192 into 12 tiles at 64 px/)
assert.match(first.stderr, /rows 1\/3, tiles 4\/12/)
assert.match(first.stderr, /rows 3\/3, tiles 12\/12/)
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: <x>_<y>.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: the streamed slice matches the one-shot crop pixel for pixel (#83)', () => {
// The #83 fix replaces one `-crop` over the whole source with one raw row band per child
// `magick`. The tile tree must be unchanged: same pixels in the same `<x>_<y>.png` files, for
// every source shape the CLI accepts. The reference is the old one-shot command itself.
const stateDir = makeStateDir()
try {
const magickRun = args => spawnSync('magick', args, { encoding: 'utf8' })
const cases = [
['rgb8-exact', 256, 192, f => fs.writeFileSync(
f, pngBytesWH(256, 192, (x, y) => [x & 0xff, y & 0xff, (x * y) & 0xff]))],
['rgb8-partial-edges', 250, 190, f => fs.writeFileSync(
f, pngBytesWH(250, 190, (x, y) => [x & 0xff, y & 0xff, 128]))],
['rgb16', null, null, f => magickRun(['-size', '130x300', 'gradient:blue-yellow',
'-depth', '16', f])],
['rgba8', null, null, f => magickRun(['-size', '100x100', 'plasma:fractal',
'-alpha', 'set', '-channel', 'A', '-evaluate',
'set', '60%', '+channel', 'PNG32:' + f])],
['gray8', null, null, f => magickRun(['-size', '64x96', 'gradient:',
'-colorspace', 'gray', '-depth', '8', f])],
]
for (const [name, w, h, make] of cases) {
const img = path.join(stateDir, `${name}.png`)
make(img)
const dims = w && h ? { width: w, height: h } : pngSize(img)
const state = path.join(stateDir, name)
const imported = runImport(state, [`--image=${img}`, '--tile-size=64'])
assert.equal(imported.status, 0, `${name}: ${imported.stderr}`)
const ref = fs.mkdtempSync(path.join(stateDir, 'ref-'))
const oneShot = magickRun([img, '-crop', '64x64', '+repage', '+adjoin',
path.join(ref, 'tile_%d.png')])
assert.equal(oneShot.status, 0, oneShot.stderr)
const cols = Math.ceil(dims.width / 64)
const rows = Math.ceil(dims.height / 64)
for (let i = 0; i < cols * rows; i++) {
const x = i % cols
const y = (i / cols) | 0
const got = path.join(state, 'tiles', '1', 'v1', `${x}_${y}.png`)
const want = path.join(ref, `tile_${i}.png`)
assert.equal(fs.existsSync(got), true, `${name}: tile ${x}_${y} exists`)
const same = magickRun(['compare', '-metric', 'AE', got, want, 'null:'])
assert.equal(same.status, 0,
`${name}: tile ${x}_${y} must be pixel-identical to the one-shot crop: ${same.stderr}`)
}
assert.equal(fs.readdirSync(path.join(state, 'tiles', '1', 'v1')).filter(n => n.endsWith('.png')).length,
cols * rows, `${name}: exactly the grid's tiles`)
}
} finally {
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
function sceneDims(stateDir) {
const db = new DatabaseSync(path.join(stateDir, 'state.db'), { readOnly: true })
try {
const row = db.prepare('SELECT w, h FROM scene WHERE id = 1').get()
return [row.w, row.h]
} finally {
db.close()
}
}
test('map import CLI: images above Full HD are shrunk to the cap, smaller ones untouched (#85)', () => {
const stateDir = makeStateDir()
try {
const cases = [
// [name, source w/h, expected scene w/h, expected stdout]
['landscape', 4000, 3000, 1440, 1080, 'scaled 4000×3000 → 1440×1080'],
['portrait', 3000, 4000, 1080, 1440, 'scaled 3000×4000 → 1080×1440'],
['square', 2000, 2000, 1080, 1080, 'scaled 2000×2000 → 1080×1080'],
['exactly-at-cap', 1920, 1080, 1920, 1080, null],
['one-px-over', 1921, 1080, 1920, 1079, 'scaled 1921×1080 → 1920×1079'],
['smaller', 256, 192, 256, 192, null],
]
for (const [name, w, h, wantW, wantH, scaled] of cases) {
const state = path.join(stateDir, name)
const img = path.join(state, `${name}.png`)
fs.mkdirSync(state, { recursive: true })
fs.writeFileSync(img, pngBytesWH(w, h, (x, y) => [x & 0xff, y & 0xff, 128]))
const imported = runImport(state, [`--image=${img}`, '--tile-size=64'])
assert.equal(imported.status, 0, `${name}: ${imported.stderr}`)
assert.deepEqual(sceneDims(state), [wantW, wantH], `${name}: scene row is the imported size`)
assert.match(imported.stdout, new RegExp(`${wantW}x${wantH} px, tile 64 px`),
`${name}: stdout reports the final size`)
if (scaled) assert.ok(imported.stdout.includes(scaled), `${name}: shrink is printed: ${imported.stdout}`)
else assert.equal(imported.stdout.includes('scaled '), false, `${name}: no needless resize`)
const cols = Math.ceil(wantW / 64)
const rows = Math.ceil(wantH / 64)
assert.equal(tileNames(path.join(state, 'tiles', '1', 'v1')).length, cols * rows,
`${name}: the tile grid follows the shrunk size`)
}
// Alpha survives the resize: a 50% transparent RGBA source is still RGBA at the cap size.
const alphaState = path.join(stateDir, 'alpha')
const alphaImg = path.join(alphaState, 'alpha.png')
fs.mkdirSync(alphaState, { recursive: true })
const made = spawnSync('magick', ['-size', '2000x1500', 'xc:rgba(255,0,0,0.5)',
'-depth', '8', alphaImg], { encoding: 'utf8' })
assert.equal(made.status, 0, made.stderr)
const alphaRun = runImport(alphaState, [`--image=${alphaImg}`, '--tile-size=64'])
assert.equal(alphaRun.status, 0, alphaRun.stderr)
assert.deepEqual(sceneDims(alphaState), [1440, 1080])
const tile = path.join(alphaState, 'tiles', '1', 'v1', '0_0.png')
const channels = spawnSync('magick', ['identify', '-format', '%[channels]', tile],
{ encoding: 'utf8' })
assert.equal(channels.status, 0, channels.stderr)
assert.match(channels.stdout, /a/, 'the tile still has an alpha channel')
const alphaMean = spawnSync('magick', [tile, '-format', '%[fx:mean.a]', 'info:'],
{ encoding: 'utf8' })
assert.equal(alphaMean.status, 0, alphaMean.stderr)
assert.ok(Math.abs(Number(alphaMean.stdout) - 0.50196) < 0.02,
`the alpha value survives the resize: ${alphaMean.stdout}`)
} finally {
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
test('map import CLI: a truncated source fails loudly and publishes nothing (#83)', () => {
// The streaming path reads the decoder's stdout band by band; a decode that dies mid-stream must
// surface magick's own message, not an empty tile tree or a byte-count mystery.
const stateDir = makeStateDir()
try {
const img = path.join(stateDir, 'truncated.png')
const full = pngBytesWH(256, 192, (x, y) => [x & 0xff, y & 0xff, 0])
fs.writeFileSync(img, full.subarray(0, full.length - 40))
const r = runImport(stateDir, [`--image=${img}`, '--tile-size=64'])
assert.notEqual(r.status, 0, 'a truncated source must not import')
assert.match(r.stderr, /cannot read image|decoder stopped|magick failed to decode/)
assert.equal(fs.existsSync(path.join(stateDir, 'tiles', '1', 'v1')), false,
'nothing is published')
assert.equal(fs.readdirSync(path.join(stateDir, 'tiles', '1'))
.some(n => n.startsWith('.import-')), false, 'no temp or band directory is left behind')
} finally {
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
test('map import CLI: a fresh/empty state dir is created, migrated and servable (#82)',
async () => {
const root = makeStateDir()
const stateDir = path.join(root, 'fresh')
const img = writeFixtureImage(path.join(root, 'map.png'))
try {
assert.equal(fs.existsSync(stateDir), false, 'the state dir starts absent')
const imported = runImport(stateDir, [`--image=${img}`, '--tile-size=64'])
assert.equal(imported.status, 0, imported.stderr)
assert.match(imported.stderr, /created\/migrated .*schema step/)
assert.match(imported.stdout, /256x192 px, tile 64 px, 4x3 tiles/)
assert.equal(fs.existsSync(path.join(stateDir, 'state.db')), true, 'the DB is created')
assert.equal(tileNames(path.join(stateDir, 'tiles', '1', 'v1')).length, 12,
'the imported tile tree exists without a prior server or gm-key run')
const gmKey = gmKeyOf(stateDir)
const s = await startServer({ stateDir })
try {
const gm = await openAs(s.origin, gmKey)
const hello = await gm.ws.waitText('hello')
assert.equal(hello.scene.w, 256, 'the server serves the imported scene')
assert.equal(hello.scene.h, 192)
assert.equal(hello.scene.tile_size, 64)
gm.ws.close()
} finally {
await stopServer(s)
}
} finally {
fs.rmSync(root, { 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=<path>/)
assert.match(help.stdout, /state-dir lock is refused/)
// 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 })
}
})