Files
_Tools/Itch/itch_screens.mjs
2026-11-13 00:38:47 +01:00

87 lines
5.3 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Real screenshots of an HTML game for itch.io - headless Edge over the DevTools protocol,
// no Playwright needed. Each shot loads the page fresh (own query string), runs its steps
// (keys, clicks, JS, waits) and saves a PNG at the exact size.
//
// node D:\Oculusquest\Projekt\_Tools\Itch\itch_screens.mjs docs\itchio\shots.json
//
// shots.json (paths relative to the json file's project = cwd):
// {
// "page": "game/index.html", // or "release/x.html", or "http://localhost:5173/"
// "size": "1920x1080", // viewport = image size
// "out": "docs/itchio/screenshots",
// "shots": [
// { "name": "01_menu", "wait": 1500 },
// { "name": "02_play", "query": "?play&level=3", "steps": [
// { "key": "ArrowRight", "hold": 900 }, { "key": " " }, { "click": [960, 540] },
// { "eval": "Kit.audio && 0" }, { "wait": 700 } ] }
// ]
// }
// Step "key": name as in KeyboardEvent.key; "hold" ms keeps it pressed. "eval" runs JS in the
// page (e.g. set a level, give coins - only to reach a real scene faster, never to fake one).
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
const specFile = process.argv[2];
if (!specFile) { console.error('usage: node itch_screens.mjs <shots.json>'); process.exit(2); }
const spec = JSON.parse(fs.readFileSync(specFile, 'utf8').replace(/^/, '')); // PowerShell writes a BOM
const root = process.cwd();
const [W, H] = (spec.size || '1920x1080').split('x').map(Number);
const outDir = path.resolve(root, spec.out || 'docs/itchio/screenshots');
fs.mkdirSync(outDir, { recursive: true });
const pageUrl = /^https?:/.test(spec.page) ? spec.page : pathToFileURL(path.resolve(root, spec.page)).href;
const EDGE = ['C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', 'C:/Program Files/Microsoft/Edge/Application/msedge.exe'].find(fs.existsSync);
if (!EDGE) { console.error('Microsoft Edge nicht gefunden'); process.exit(1); }
const PORT = 9300 + Math.floor(Math.random() * 500);
const sleep = ms => new Promise(r => setTimeout(r, ms));
const KEYCODES = { ArrowLeft: 37, ArrowUp: 38, ArrowRight: 39, ArrowDown: 40, Enter: 13, Escape: 27, ' ': 32, Tab: 9, Shift: 16, Control: 17 };
const codeOf = k => k === ' ' ? 'Space' : k.startsWith('Arrow') || k.length > 1 ? k : /[a-z]/i.test(k) ? 'Key' + k.toUpperCase() : /\d/.test(k) ? 'Digit' + k : k;
const prof = fs.mkdtempSync(path.join(os.tmpdir(), 'itchshots-'));
const edge = spawn(EDGE, ['--headless=new', `--remote-debugging-port=${PORT}`, `--user-data-dir=${prof}`, '--allow-file-access-from-files',
'--autoplay-policy=no-user-gesture-required', '--hide-scrollbars', '--mute-audio', `--window-size=${W},${H}`, 'about:blank']);
const cleanup = () => { try { edge.kill(); } catch {} setTimeout(() => fs.rmSync(prof, { recursive: true, force: true }), 500); };
try {
let targets;
for (let i = 0; i < 60 && !targets; i++) { try { targets = await (await fetch(`http://127.0.0.1:${PORT}/json/list`)).json(); } catch { await sleep(200); } }
const ws = new WebSocket(targets.find(t => t.type === 'page').webSocketDebuggerUrl);
await new Promise(r => ws.addEventListener('open', r));
let id = 0; const pending = {}; const errors = [];
ws.addEventListener('message', ev => {
const m = JSON.parse(ev.data);
if (m.id && pending[m.id]) { pending[m.id](m); delete pending[m.id]; }
if (m.method === 'Runtime.exceptionThrown') errors.push(m.params.exceptionDetails.exception?.description || m.params.exceptionDetails.text);
});
const send = (method, params = {}) => new Promise(r => { const i = ++id; pending[i] = r; ws.send(JSON.stringify({ id: i, method, params })); });
await send('Runtime.enable');
await send('Emulation.setDeviceMetricsOverride', { width: W, height: H, deviceScaleFactor: 1, mobile: false });
const key = async (k, type) => send('Input.dispatchKeyEvent', { type, key: k, code: codeOf(k), windowsVirtualKeyCode: KEYCODES[k] ?? k.toUpperCase().charCodeAt(0), text: type === 'keyDown' && k.length === 1 ? k : undefined });
for (const shot of spec.shots) {
errors.length = 0;
await send('Page.navigate', { url: pageUrl + (shot.query || '') });
await sleep(shot.load ?? 1200);
for (const s of shot.steps || []) {
if (s.wait) await sleep(s.wait);
if (s.key) { await key(s.key, 'keyDown'); await sleep(s.hold ?? 60); await key(s.key, 'keyUp'); }
if (s.click) for (const type of ['mousePressed', 'mouseReleased']) await send('Input.dispatchMouseEvent', { type, x: s.click[0], y: s.click[1], button: 'left', clickCount: 1 });
if (s.eval) await send('Runtime.evaluate', { expression: s.eval, awaitPromise: true });
if (s.after) await sleep(s.after);
}
await sleep(shot.wait ?? 300);
const r = await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
const file = path.join(outDir, `${shot.name}.png`);
fs.writeFileSync(file, Buffer.from(r.result.data, 'base64'));
console.log(`${shot.name}.png${errors.length ? ` (Fehler im Spiel: ${errors[0].split('\n')[0]})` : ''}`);
}
ws.close();
console.log(`Fertig: ${spec.shots.length} Screenshots in ${outDir} (${W}x${H})`);
} catch (e) {
console.error('FAIL', e.message || e);
process.exitCode = 1;
} finally { cleanup(); }