223 lines
10 KiB
TypeScript
223 lines
10 KiB
TypeScript
/**
|
||
* The last step of the pipeline (docs/ART.md §3, step 6): a picture Mark accepted on the
|
||
* board becomes optimised WebP in art/final/. A sprite sheet is cut along its grid here.
|
||
* It refuses rather than guesses: a sheet with an empty cell or a painted background is
|
||
* refused whole, because a cut that "mostly worked" ships a broken picture.
|
||
*/
|
||
import sharp from 'sharp';
|
||
import type { Asset, Manifest } from './manifest.js';
|
||
import { cellSize, cutLines } from './prompt.js';
|
||
|
||
/** Bytes per final file (docs/ART.md §4). The app precaches every one. */
|
||
export const BUDGET: Record<Asset['type'] | 'cell', number> = {
|
||
sheet: 400_000,
|
||
spritesheet: 0, // never written whole: its cells are
|
||
layer: 350_000,
|
||
icon: 120_000,
|
||
sprite: 120_000,
|
||
cell: 120_000
|
||
};
|
||
|
||
const QUALITIES = [82, 72, 62];
|
||
const ALPHA = 16;
|
||
|
||
export interface FinalFile {
|
||
readonly id: string;
|
||
readonly data: Buffer;
|
||
readonly width: number;
|
||
readonly height: number;
|
||
}
|
||
|
||
export interface Accepted {
|
||
readonly files: readonly FinalFile[];
|
||
/** Things Mark or Claude should know, none of them a reason to refuse. */
|
||
readonly notes: readonly string[];
|
||
}
|
||
|
||
export class Refused extends Error {
|
||
override readonly name = 'Refused';
|
||
}
|
||
|
||
interface Target {
|
||
readonly asset: Asset;
|
||
/** Set when `id` names one cell of a sprite sheet, made on its own. */
|
||
readonly cell?: string;
|
||
}
|
||
|
||
export function findTarget(m: Manifest, id: string): Target {
|
||
for (const asset of m.assets) {
|
||
if (asset.id === id) return { asset };
|
||
if (asset.cells?.some((c) => c.id === id)) return { asset, cell: id };
|
||
}
|
||
throw new Refused(`"${id}" is not a picture in art/manifest.json`);
|
||
}
|
||
|
||
async function encode(img: sharp.Sharp, budget: number, id: string): Promise<{ data: Buffer; width: number; height: number }> {
|
||
for (const quality of QUALITIES) {
|
||
const { data, info } = await img.clone().webp({ quality, alphaQuality: 90, effort: 5 }).toBuffer({ resolveWithObject: true });
|
||
if (data.length <= budget) return { data, width: info.width, height: info.height };
|
||
}
|
||
throw new Refused(`${id}: over its budget of ${Math.round(budget / 1000)} KB even at WebP quality ${QUALITIES.at(-1)}. Ask for a simpler picture, or raise the budget in docs/ART.md §4 with a reason.`);
|
||
}
|
||
|
||
interface Coverage {
|
||
readonly drawn: number;
|
||
readonly seeThrough: number;
|
||
readonly touches: boolean;
|
||
}
|
||
|
||
/** How much of a region is drawn, and whether the drawing reaches its edge (two pixels or more). */
|
||
function coverage(px: Buffer, width: number, x0: number, y0: number, x1: number, y1: number): Coverage {
|
||
let drawn = 0, edge = 0;
|
||
for (let y = y0; y < y1; y++) {
|
||
for (let x = x0; x < x1; x++) {
|
||
if ((px[(y * width + x) * 4 + 3] ?? 0) >= ALPHA) {
|
||
drawn++;
|
||
if (x === x0 || x === x1 - 1 || y === y0 || y === y1 - 1) edge++;
|
||
}
|
||
}
|
||
}
|
||
const area = (x1 - x0) * (y1 - y0);
|
||
return { drawn: drawn / area, seeThrough: Math.round(100 * (1 - drawn / area)), touches: edge >= 2 };
|
||
}
|
||
|
||
/** The largest region of the given shape in the middle of a width × height picture. */
|
||
function middle(width: number, height: number, shape: number): sharp.Region {
|
||
if (width / height > shape) {
|
||
const w = Math.round(height * shape);
|
||
return { left: Math.floor((width - w) / 2), top: 0, width: w, height };
|
||
}
|
||
const h = Math.round(width / shape);
|
||
return { left: 0, top: Math.floor((height - h) / 2), width, height: h };
|
||
}
|
||
|
||
async function rgba(input: Buffer): Promise<{ px: Buffer; width: number; height: number }> {
|
||
const { data, info } = await sharp(input).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
|
||
return { px: data, width: info.width, height: info.height };
|
||
}
|
||
|
||
/** Where a cell's drawing lies, as shares of the cell (0–1), or null when nothing is drawn. */
|
||
interface Extent {
|
||
readonly x0: number;
|
||
readonly y0: number;
|
||
readonly x1: number;
|
||
readonly y1: number;
|
||
}
|
||
|
||
function extent(px: Buffer, width: number, x0: number, y0: number, x1: number, y1: number): Extent | null {
|
||
let lx = Infinity, ly = Infinity, hx = -Infinity, hy = -Infinity;
|
||
for (let y = y0; y < y1; y++) {
|
||
for (let x = x0; x < x1; x++) {
|
||
if ((px[(y * width + x) * 4 + 3] ?? 0) < ALPHA) continue;
|
||
lx = Math.min(lx, x); hx = Math.max(hx, x); ly = Math.min(ly, y); hy = Math.max(hy, y);
|
||
}
|
||
}
|
||
if (lx === Infinity) return null;
|
||
const w = x1 - x0, h = y1 - y0;
|
||
return { x0: (lx - x0) / w, y0: (ly - y0) / h, x1: (hx + 1 - x0) / w, y1: (hy + 1 - y0) / h };
|
||
}
|
||
|
||
/**
|
||
* How far a layer may reach past its guide's figure, as a share of the cell: hair and a hat may
|
||
* be a little fuller than the guide's braids and straw hat, never somewhere else.
|
||
*/
|
||
export const REGISTER = 0.08;
|
||
|
||
/** The guide's cells, as accepted into art/final/: cell id → its WebP. */
|
||
export type Guide = ReadonlyMap<string, Buffer>;
|
||
|
||
async function guideExtent(guide: Guide, cell: string): Promise<Extent | null> {
|
||
const file = guide.get(cell);
|
||
if (!file) return null;
|
||
const { px, width, height } = await rgba(file);
|
||
return extent(px, width, 0, 0, width, height);
|
||
}
|
||
|
||
export async function acceptPicture(input: Buffer, id: string, m: Manifest, guide?: Guide): Promise<Accepted> {
|
||
const target = findTarget(m, id);
|
||
const a = target.asset;
|
||
if (a.over && target.cell) {
|
||
throw new Refused(`${id}: a layer is painted whole over its guide (${a.over}), never one picture at a time; the parts would not line up. Accept ${a.id} whole.`);
|
||
}
|
||
const guideCells = a.over && a.grid ? (m.assets.find((g) => g.id === a.over)?.cells ?? []) : [];
|
||
if (a.over && guideCells.some((c) => !guide?.has(c.id))) {
|
||
throw new Refused(`${id}: its guide ${a.over} is not in art/final/ yet. Accept the guide first: every layer is checked against it.`);
|
||
}
|
||
const notes: string[] = [];
|
||
const { px, width, height } = await rgba(input).catch((e: unknown) => {
|
||
throw new Refused(`${id}: the file could not be read as a picture (${String(e)})`);
|
||
});
|
||
|
||
if (a.type === 'spritesheet') {
|
||
const { width: cw, height: ch } = cellSize(a);
|
||
const fitCell = (img: sharp.Sharp): sharp.Sharp =>
|
||
img.resize(cw, ch, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 }, withoutEnlargement: true });
|
||
|
||
if (target.cell) {
|
||
const corners = [[0, 0], [width - 1, 0], [0, height - 1], [width - 1, height - 1]] as const;
|
||
if (corners.some(([x, y]) => (px[(y * width + x) * 4 + 3] ?? 0) >= ALPHA)) {
|
||
throw new Refused(`${id}: the background is not transparent. Ask for a transparent PNG.`);
|
||
}
|
||
if (coverage(px, width, 0, 0, width, height).touches) notes.push(`${id}: the drawing touches the edge; something may be cut off.`);
|
||
const out = await encode(fitCell(sharp(input)), BUDGET.cell, id);
|
||
return { files: [{ id, ...out }], notes };
|
||
}
|
||
|
||
const g = a.grid ?? { cols: 1, rows: 1 };
|
||
if (Math.abs(width / height - a.width / a.height) > 0.02) {
|
||
notes.push(`${id}: made at ${width} × ${height}, not ${a.width} × ${a.height}; cut by its ${g.cols} × ${g.rows} grid anyway.`);
|
||
}
|
||
const xs = cutLines(width, g.cols), ys = cutLines(height, g.rows);
|
||
const cells = a.cells ?? [];
|
||
const empty: string[] = [], painted: string[] = [];
|
||
const regions = cells.map((c, i) => {
|
||
const col = i % g.cols, row = Math.floor(i / g.cols);
|
||
const x0 = xs[col] ?? 0, x1 = xs[col + 1] ?? width, y0 = ys[row] ?? 0, y1 = ys[row + 1] ?? height;
|
||
const cov = coverage(px, width, x0, y0, x1, y1);
|
||
if (cov.drawn < 0.005) empty.push(c.id);
|
||
else if (cov.seeThrough < 5) painted.push(c.id);
|
||
else if (cov.touches) notes.push(`${c.id}: the drawing touches its cell's edge; a neighbour may spill in.`);
|
||
return { id: c.id, left: x0, top: y0, width: x1 - x0, height: y1 - y0 };
|
||
});
|
||
if (empty.length) throw new Refused(`${id}: nothing drawn in ${empty.join(', ')}. The whole sheet is refused.`);
|
||
if (painted.length) throw new Refused(`${id}: painted on a background in ${painted.join(', ')}. The whole sheet is refused.`);
|
||
if (a.over && guide) {
|
||
// In register: each picture's part lies on the guide's figure in the same cell (STYLE.md §3b).
|
||
const off: string[] = [];
|
||
for (const [i, r] of regions.entries()) {
|
||
const mine = extent(px, width, r.left, r.top, r.left + r.width, r.top + r.height);
|
||
const under = await guideExtent(guide, guideCells[i]?.id ?? '');
|
||
if (!mine || !under) continue;
|
||
const out = Math.max(under.x0 - mine.x0, under.y0 - mine.y0, mine.x1 - under.x1, mine.y1 - under.y1);
|
||
if (out > REGISTER) off.push(`${r.id} (${Math.round(out * 100)} % of the cell outside the guide's figure)`);
|
||
}
|
||
if (off.length) throw new Refused(`${id}: not in register with ${a.over} in ${off.join(', ')}. Paint it over the guide again; the whole sheet is refused.`);
|
||
}
|
||
const files: FinalFile[] = [];
|
||
for (const r of regions) {
|
||
const out = await encode(fitCell(sharp(input).extract({ left: r.left, top: r.top, width: r.width, height: r.height })), BUDGET.cell, r.id);
|
||
files.push({ id: r.id, ...out });
|
||
}
|
||
return { files, notes };
|
||
}
|
||
|
||
if (a.background === 'transparent') {
|
||
// A garden layer is opaque below its horizon: only the top edge must be clear.
|
||
const row = a.type === 'layer' ? coverage(px, width, 0, 0, width, 1).drawn : null;
|
||
const corners = [[0, 0], [width - 1, 0], [0, height - 1], [width - 1, height - 1]] as const;
|
||
const clear = row === null ? corners.every(([x, y]) => (px[(y * width + x) * 4 + 3] ?? 0) < ALPHA) : row < 0.02;
|
||
if (!clear) throw new Refused(`${id}: the ${a.type === 'layer' ? 'sky' : 'background'} is not transparent. Ask for a transparent PNG.`);
|
||
}
|
||
if (Math.abs(width / height - a.width / a.height) > 0.02) {
|
||
notes.push(`${id}: made at ${width} × ${height}, not ${a.width} × ${a.height}; ${a.background === 'full' ? 'cropped from the middle' : 'fitted inside with clear edges'}.`);
|
||
}
|
||
if (width < a.width) notes.push(`${id}: only ${width} px wide; kept at that size, never blown up.`);
|
||
// Never blown up, so the shape comes first: a full picture is cropped from the middle to the
|
||
// target shape, then only ever shrunk. Resizing with cover would skip the crop on a small one.
|
||
const img = a.background === 'full'
|
||
? sharp(input).extract(middle(width, height, a.width / a.height)).resize(a.width, a.height, { fit: 'inside', withoutEnlargement: true })
|
||
: sharp(input).resize(a.width, a.height, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 }, withoutEnlargement: true });
|
||
const out = await encode(img, BUDGET[a.type], id);
|
||
return { files: [{ id, ...out }], notes };
|
||
}
|