129 lines
7.5 KiB
TypeScript
129 lines
7.5 KiB
TypeScript
// Store screenshots + Play feature graphic at exact pixel sizes, from raw game frames and per-language copy.
|
|
// crt-ship shots render [--lang en,tr] [--size ios69,play,feature] [--scenes 1,3] [--no-sheet] [--port 8792]
|
|
// Out: <shots.out>/<lang>/<size>/NN.png (24-bit RGB: Play rejects alpha / palette PNGs), <lang>/feature/1024x500.png,
|
|
// and <lang>/sheet.png (contact sheet of every size, for a quick review). Needs playwright + ffmpeg.
|
|
import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
|
|
import { join, relative } from 'node:path';
|
|
import { spawnSync } from 'node:child_process';
|
|
import type { Ctx } from '../lib/ctx';
|
|
import { need } from '../lib/ctx';
|
|
import { done, log, warn } from '../lib/log';
|
|
import { launch } from './browser';
|
|
import { type CopyFile, DEFAULT_PHONE, DEFAULT_TABLET, SIZES, copyText, palette, scriptFont, validateCopy } from './lib';
|
|
|
|
const TYPES: Record<string, string> = { html: 'text/html; charset=utf-8', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg',
|
|
webp: 'image/webp', woff2: 'font/woff2', css: 'text/css', svg: 'image/svg+xml' };
|
|
|
|
export async function run(ctx: Ctx): Promise<void> {
|
|
const { config, root, resolve } = ctx.loaded;
|
|
const shots = need(config.shots, 'shots');
|
|
const a = ctx.args;
|
|
const langs = a.list('lang').length ? a.list('lang') : config.languages.map(l => l.id);
|
|
const sizes = a.list('size').length ? a.list('size') : Object.keys(SIZES);
|
|
const sceneIds = a.list('scenes').length ? a.list('scenes') : shots.scenes.map(s => s.id);
|
|
for (const s of sizes) if (!SIZES[s]) throw new Error(`unknown size ${s} (${Object.keys(SIZES).join(', ')})`);
|
|
const copy = JSON.parse(readFileSync(resolve(shots.copy), 'utf8')) as CopyFile;
|
|
const problems = validateCopy(copy, shots, langs);
|
|
if (problems.length) throw new Error('shots copy:\n ' + problems.join('\n '));
|
|
const framesDir = resolve(shots.frames), outDir = resolve(shots.out);
|
|
const fontsDir = join(root, '.crt-ship', 'fonts');
|
|
if (!existsSync(join(fontsDir, 'fonts.css'))) warn('shots', 'no .crt-ship/fonts/fonts.css: run `crt-ship shots fonts` first (falling back to system fonts)');
|
|
const phone = { ...DEFAULT_PHONE, ...shots.phone }, tablet = { ...DEFAULT_TABLET, ...shots.tablet };
|
|
const rtl = new Map(config.languages.map(l => [l.id, !!l.rtl] as const));
|
|
const fonts = { title: shots.fonts?.title ?? 'Lilita One', body: shots.fonts?.body ?? 'Montserrat' };
|
|
const tpl = import.meta.dir;
|
|
|
|
const server = Bun.serve({
|
|
port: a.num('port', 8792), hostname: '127.0.0.1',
|
|
async fetch(req) {
|
|
const url = new URL(req.url);
|
|
const p = decodeURIComponent(url.pathname);
|
|
if (p === '/job.json') {
|
|
const lang = url.searchParams.get('lang') ?? '';
|
|
const text = copyText(lang, copy[lang]);
|
|
const script = scriptFont(lang, text);
|
|
const base = { phone, tablet, rtl: rtl.get(lang), logo: !!shots.logo, appName: config.app.name,
|
|
fonts: { ...fonts, script: script ? `Store ${script.slug}` : null } };
|
|
if (url.searchParams.has('feature'))
|
|
return Response.json({ ...base, frame: shots.feature?.frame ?? shots.scenes[0]!.frames[0]!.src, palette: palette(shots.feature?.palette ?? shots.scenes[0]!.palette) });
|
|
const sid = url.searchParams.get('s') ?? '';
|
|
const scene = shots.scenes.find(s => s.id === sid)!;
|
|
const number = shots.scenes.filter(s => !s.hero).indexOf(scene) + 1;
|
|
return Response.json({ ...base, scene, number, palette: palette(scene.palette), copy: copy[lang]?.[sid] ?? {} });
|
|
}
|
|
let file = '';
|
|
if (p === '/logo' && shots.logo) file = resolve(shots.logo);
|
|
else if (p.startsWith('/frames/')) file = join(framesDir, p.slice(8));
|
|
else if (p.startsWith('/fonts/')) file = join(fontsDir, p.slice(7));
|
|
else if (p.startsWith('/out/')) file = join(outDir, p.slice(5));
|
|
else if (/^\/(template|feature)\.html$/.test(p)) file = join(tpl, p.slice(1));
|
|
if (!file || file.includes('..')) return new Response('no', { status: 404 });
|
|
const f = Bun.file(file);
|
|
if (!(await f.exists())) return new Response('missing ' + p, { status: 404 });
|
|
return new Response(f, { headers: { 'content-type': TYPES[file.split('.').pop()!.toLowerCase()] ?? 'application/octet-stream' } });
|
|
},
|
|
});
|
|
const base = `http://127.0.0.1:${server.port}`;
|
|
const browser = await launch(root, { headless: true });
|
|
const page = await (await browser.newContext({ deviceScaleFactor: 1 })).newPage();
|
|
const errs: string[] = [];
|
|
page.on('pageerror', (e: Error) => errs.push(e.message));
|
|
page.on('response', (r: { status(): number; url(): string }) => { if (r.status() >= 400 && !r.url().includes('/fonts/')) errs.push(`${r.status()} ${r.url()}`); });
|
|
let warnings = 0;
|
|
|
|
async function shoot(url: string, w: number, h: number, out: string): Promise<void> {
|
|
errs.length = 0;
|
|
mkdirSync(join(out, '..'), { recursive: true });
|
|
await page.setViewportSize({ width: w, height: h });
|
|
await page.goto(url, { waitUntil: 'load' });
|
|
await page.waitForFunction("document.body.dataset.ready === '1'", null, { timeout: 30000 });
|
|
await page.waitForTimeout(200);
|
|
const tmp = out + '.tmp.png';
|
|
await page.screenshot({ path: tmp, clip: { x: 0, y: 0, width: w, height: h } });
|
|
const r = spawnSync('ffmpeg', ['-v', 'error', '-y', '-i', tmp, '-pix_fmt', 'rgb24', out]);
|
|
rmSync(tmp, { force: true });
|
|
if (r.status !== 0) throw new Error('ffmpeg: ' + r.stderr);
|
|
if (errs.length) warnings++;
|
|
log('shots', `${errs.length ? 'WARN ' : ''}${relative(root, out)}${errs.length ? ' ' + errs.join(' | ') : ''}`);
|
|
}
|
|
|
|
try {
|
|
for (const lang of langs) {
|
|
const rows: { size: string; files: string[] }[] = [];
|
|
for (const size of sizes) {
|
|
const s = SIZES[size]!;
|
|
if (s.feature) {
|
|
const f = join(outDir, lang, 'feature', '1024x500.png');
|
|
await shoot(`${base}/feature.html?lang=${encodeURIComponent(lang)}`, s.w, s.h, f);
|
|
rows.push({ size, files: [f] });
|
|
continue;
|
|
}
|
|
const files: string[] = [];
|
|
for (const [i, id] of sceneIds.entries()) {
|
|
const f = join(outDir, lang, size, `${String(i + 1).padStart(2, '0')}.png`);
|
|
await shoot(`${base}/template.html?s=${encodeURIComponent(id)}&w=${s.w}&h=${s.h}&lang=${encodeURIComponent(lang)}${s.device ? '&device=tablet' : ''}`, s.w, s.h, f);
|
|
files.push(f);
|
|
}
|
|
rows.push({ size, files });
|
|
}
|
|
if (!a.has('no-sheet') && rows.length) {
|
|
const H0 = 900, gap = 24;
|
|
let y = gap, W = 0, imgs = '';
|
|
for (const row of rows) {
|
|
const d = SIZES[row.size]!, h = d.feature ? H0 / 2 : H0, w = Math.round(h * d.w / d.h);
|
|
row.files.forEach((f, i) => { imgs += `<img src="/out/${relative(outDir, f)}" style="position:absolute;left:${gap + i * (w + gap)}px;top:${y}px;width:${w}px;height:${h}px;border-radius:14px">`; });
|
|
W = Math.max(W, gap + row.files.length * (w + gap)); y += h + gap;
|
|
}
|
|
const sheet = join(outDir, lang, '.sheet.html');
|
|
await Bun.write(sheet, `<!doctype html><body style="margin:0;background:#141418;width:${W}px;height:${y}px;position:relative">${imgs}
|
|
<script>Promise.all([...document.images].map(i=>i.decode())).then(()=>document.body.dataset.ready='1')</script></body>`);
|
|
await shoot(`${base}/out/${relative(outDir, sheet)}`, W, y, join(outDir, lang, 'sheet.png'));
|
|
rmSync(sheet, { force: true });
|
|
}
|
|
}
|
|
} finally {
|
|
await browser.close();
|
|
server.stop(true);
|
|
}
|
|
done('shots', `render done${warnings ? `, ${warnings} with warnings (missing frames or fonts?)` : ''}`);
|
|
}
|