A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(ci): make each golden package answer a keyboard, not just draw one
esengined13c8efac8e0
diff --git a/desktop/scripts/launch-export.mjs b/desktop/scripts/launch-export.mjsindex 3c6523e91..3a17044fb 100644--- a/desktop/scripts/launch-export.mjs+++ b/desktop/scripts/launch-export.mjs@@ -20,6 +20,7 @@* --settle <n> frames to let run before capturing (default 30)* --timeout <ms> how long to wait for the first frame (default 30000)* --allow-flat accept a single-colour frame (a deliberately blank scene)+ * --input <json> hold keys and run on: {"keys":["ArrowRight"],"frames":40}*/import { app, BrowserWindow } from 'electron';import http from 'node:http';@@ -45,6 +46,7 @@ const OUT = flag('out', '');const W = Number(flag('w', '640'));const H = Number(flag('h', '360'));const SETTLE = Number(flag('settle', '30'));+const INPUT = flag('input', '');const TIMEOUT = Number(flag('timeout', '30000'));const MIME = {@@ -134,6 +136,30 @@ async function main() {})`).catch((e) => { errors.push(String(e)); return false; });+ // Drive the game, then let it run on. Real DOM key events on the page the build+ // owns: a package has no automation hook, and the point is to exercise the path+ // a player's keyboard takes, not a back door around it.+ if (painted && INPUT) {+ const spec = JSON.parse(INPUT);+ const ran = await win.webContents.executeJavaScript(`+ (async () => {+ const raf = () => new Promise((r) => requestAnimationFrame(r));+ const keys = ${JSON.stringify(spec.keys ?? [])};+ const fire = (type, code) => {+ const e = new KeyboardEvent(type, { key: code, code, bubbles: true, cancelable: true });+ window.dispatchEvent(e);+ document.dispatchEvent(e);+ };+ for (const k of keys) fire('keydown', k);+ for (let i = 0; i < ${Number(spec.frames ?? 40)}; i++) await raf();+ for (const k of keys) fire('keyup', k);+ await raf();+ return keys.length;+ })()+ `).catch((e) => { errors.push(`input: ${e}`); return -1; });+ console.log(` input: ${ran} key(s) held for ${Number(spec.frames ?? 40)} frames`);+ }+const image = await win.webContents.capturePage();if (OUT) await writeFile(OUT, image.toPNG());stop();diff --git a/desktop/tests/frame-compare.test.ts b/desktop/tests/frame-compare.test.tsindex 6329a08c6..72f123072 100644--- a/desktop/tests/frame-compare.test.ts+++ b/desktop/tests/frame-compare.test.ts@@ -11,7 +11,7 @@import { describe, it, expect } from 'vitest';import { deflateSync } from 'node:zlib';// @ts-expect-error — plain-JS tool module, no d.ts-import { downsample, gridDistance, frameDistance, DEFAULT_INSET } from '../../tools/frameCompare.mjs';+import { downsample, gridDistance, cellMaxDistance, frameDistance, frameCellMax, DEFAULT_INSET } from '../../tools/frameCompare.mjs';interface Img { w: number; h: number; px(x: number, y: number): [number, number, number] }@@ -117,6 +117,40 @@ function png(w: number, h: number, c: [number, number, number]): Buffer {]);}+/**+ * The second question: not "is this the same game" but "did anything answer".+ * Measured on real packages — driven 0.37, undriven drift 0.04, input silently+ * dropped 0.09 — which is why the tolerance sits at 0.15 and not below it.+ */+describe('cellMaxDistance', () => {+ const field = (w: number, h: number) => solid(w, h, [30, 30, 30]);+ /** The same field with one small bright block, as a sprite at a position. */+ const withSprite = (w: number, h: number, sx: number) =>+ img(w, h, (x, y) => (x >= sx && x < sx + 4 && y >= 8 && y < 12 ? [255, 255, 255] : [30, 30, 30]));++ it('is zero against itself', () => {+ const g = downsample(withSprite(64, 32, 10), 16, 8);+ expect(cellMaxDistance(g, g)).toBe(0);+ });++ it('sees a small sprite move where the mean does not', () => {+ const a = downsample(withSprite(64, 32, 8), 16, 8);+ const b = downsample(withSprite(64, 32, 40), 16, 8);+ expect(gridDistance(a, b)).toBeLessThan(0.05); // averaged away+ expect(cellMaxDistance(a, b)).toBeGreaterThan(0.3); // the moved cell shows+ });++ it('stays near zero when nothing moved but the field is busy', () => {+ const a = downsample(field(64, 32), 16, 8);+ const b = downsample(img(64, 32, (x, y) => (((x + y) % 17 === 0) ? [34, 34, 34] : [30, 30, 30])), 16, 8);+ expect(cellMaxDistance(a, b)).toBeLessThan(0.05);+ });++ it('refuses grids of different sizes', () => {+ expect(() => cellMaxDistance(new Float64Array(3), new Float64Array(6))).toThrow(/mismatch/);+ });+});+describe('frameDistance', () => {it('scores two identical captures at zero', () => {expect(frameDistance(png(32, 18, [40, 80, 120]), png(32, 18, [40, 80, 120]))).toBe(0);@@ -134,4 +168,8 @@ describe('frameDistance', () => {it('insets by default, so a play border never counts as a difference', () => {expect(DEFAULT_INSET).toBeGreaterThan(0);});++ it('frameCellMax refuses mismatched sizes too — both reducers share the guard', () => {+ expect(() => frameCellMax(png(32, 18, [0, 0, 0]), png(64, 18, [0, 0, 0]))).toThrow(/differ in size/);+ });});diff --git a/tools/check-golden.mjs b/tools/check-golden.mjsindex 63be03e68..44631a0f0 100644--- a/tools/check-golden.mjs+++ b/tools/check-golden.mjs@@ -16,7 +16,7 @@ import { existsSync, readFileSync } from 'node:fs';import path from 'node:path';import {GOLDEN, CAPABILITIES, KNOWN_GAPS, TIERS, TARGETS,- atTier, uncoveredCapabilities, nonGoldenExamples, projectDir, parityFor,+ atTier, uncoveredCapabilities, nonGoldenExamples, projectDir, parityFor, interactFor,} from './goldenProjects.mjs';const problems = [];@@ -61,6 +61,15 @@ for (const g of GOLDEN) {fail(`"${g.id}" has parity ${g.parity} — expected a tolerance between 0 and 1`);}if (g.parity !== undefined && g.parityGap) fail(`"${g.id}" both sets a parity tolerance and opts out`);+ // Same bargain as parity: a project that cannot be driven says why.+ if (g.interactGap !== undefined && !(typeof g.interactGap === 'string' && g.interactGap.trim())) {+ fail(`"${g.id}" sets interactGap without a reason — say why nothing can be pressed`);+ }+ if (g.interact && g.interactGap) fail(`"${g.id}" both declares input and opts out of it`);+ if (!g.interact && !g.interactGap) {+ fail(`"${g.id}" neither declares input nor says why it has none — the chain has no interact step for it`);+ }+ if (g.interact && !(g.interact.keys?.length > 0)) fail(`"${g.id}" declares input with no keys to hold`);if (!g.certifies?.length) fail(`"${g.id}" certifies nothing — say what it is in the suite for`);for (const c of g.certifies ?? []) {if (!CAPABILITIES.includes(c)) fail(`"${g.id}" certifies "${c}", which is not a declared capability`);@@ -91,12 +100,14 @@ if (problems.length) {}const noParity = GOLDEN.filter((g) => parityFor(g) === null);+const driven = GOLDEN.filter((g) => interactFor(g) !== null);const gaps = Object.keys(KNOWN_GAPS).length;const pairs = TIERS.map((t) => `${t} ${atTier(t).length}`).join(' / ');console.log(`check-golden: ${GOLDEN.length} golden project(s) certify ${covered.size}/${CAPABILITIES.length} capabilities`+ `, ${gaps} declared gap(s) — ok (${pairs})`,);+console.log(` ${driven.length} project(s) drive their package with input; ${GOLDEN.length - driven.length} say why they cannot`);for (const g of noParity) console.log(` no editor/package comparison for ${g.id}: ${g.parityGap}`);const rest = nonGoldenExamples();if (rest.length) console.log(` ${rest.length} example(s) outside the corpus (smoke-tested, not certified)`);diff --git a/tools/frameCompare.mjs b/tools/frameCompare.mjsindex 5d99d9c39..485728cae 100644--- a/tools/frameCompare.mjs+++ b/tools/frameCompare.mjs@@ -54,6 +54,23 @@ export function downsample(img, cols, rows, inset = 0) {return out;}+/**+ * The WORST cell's difference, 0..1 — "did anything change anywhere".+ *+ * A sprite crossing the screen is a big change over a small area, which the mean+ * flattens away: driven against undriven, the mean scored 0.0115 vs a drift of+ * 0.0102, and this scored 0.38 vs 0.04.+ */+export function cellMaxDistance(a, b) {+ if (a.length !== b.length) throw new Error(`grid size mismatch: ${a.length} vs ${b.length}`);+ let worst = 0;+ for (let i = 0; i < a.length; i += 3) {+ const d = (Math.abs(a[i] - b[i]) + Math.abs(a[i + 1] - b[i + 1]) + Math.abs(a[i + 2] - b[i + 2])) / 3 / 255;+ if (d > worst) worst = d;+ }+ return worst;+}+/** Mean per-channel difference of two same-length grids, normalised to 0..1. */export function gridDistance(a, b) {if (a.length !== b.length) throw new Error(`grid size mismatch: ${a.length} vs ${b.length}`);@@ -67,11 +84,22 @@ export function gridDistance(a, b) {* rather than stretching: two shapes letterbox differently and put screen-space* UI elsewhere, so the score would measure the harness, not the game.*/-export function frameDistance(pngA, pngB, { cols = 48, rows = 27, inset = DEFAULT_INSET } = {}) {+export function frameDistance(pngA, pngB, opts = {}) {+ const [ga, gb] = grids(pngA, pngB, opts);+ return gridDistance(ga, gb);+}++/** How much the most-changed region moved between two captures, 0..1. */+export function frameCellMax(pngA, pngB, opts = {}) {+ const [ga, gb] = grids(pngA, pngB, opts);+ return cellMaxDistance(ga, gb);+}++function grids(pngA, pngB, { cols = 48, rows = 27, inset = DEFAULT_INSET } = {}) {const a = readPNG(pngA);const b = readPNG(pngB);if (a.w !== b.w || a.h !== b.h) {throw new Error(`captures differ in size (${a.w}x${a.h} vs ${b.w}x${b.h}) — compare like for like`);}- return gridDistance(downsample(a, cols, rows, inset), downsample(b, cols, rows, inset));+ return [downsample(a, cols, rows, inset), downsample(b, cols, rows, inset)];}diff --git a/tools/goldenProjects.mjs b/tools/goldenProjects.mjsindex 14b4a50d1..625e09d56 100644--- a/tools/goldenProjects.mjs+++ b/tools/goldenProjects.mjs@@ -35,6 +35,13 @@ export const TARGETS = ['web', 'playable', 'desktop', 'wechat', 'android', 'ios'*/export const DEFAULT_PARITY = 0.06;+/**+ * How much the most-changed region must move for input to count as having+ * reached the game. Measured: two undriven runs of one package differ by 0.04+ * and a driven one by 0.38, so this sits between them with room on both sides.+ */+export const DEFAULT_RESPONDS = 0.15;+/*** What the suite claims to cover. A capability here with no project behind it* is a hole in the release argument, so the gate fails on one that is not in@@ -76,6 +83,7 @@ export const KNOWN_GAPS = {** `parity` overrides {@link DEFAULT_PARITY} for a game whose opening seconds* move too much to compare that tightly; `parityGap` opts out with a reason.+ * `interact` is the input a package must visibly answer; `interactGap` opts out.*/export const GOLDEN = [{@@ -83,60 +91,73 @@ export const GOLDEN = [certifies: ['physics', 'input', 'animation'],targets: ['web', 'desktop', 'android'],tier: 'pr',+ interact: { keys: ['ArrowRight'], frames: 40 },},{id: 'space-shooter',certifies: ['ecs', 'particles', 'audio'],targets: ['web', 'desktop', 'android'],tier: 'pr',+ interact: { keys: ['ArrowLeft'], frames: 40 },},{id: 'ui-controls',certifies: ['ui-layout', 'text'],targets: ['web', 'desktop'],tier: 'pr',+ interactGap: 'widgets are pointer-driven; no keyboard path to hold',},{id: 'tilemap-demo',certifies: ['tilemap', 'tile-collision'],targets: ['web', 'desktop', 'android'],tier: 'pr',+ // Measured: the scene's own patrolling enemy moves as much as the player+ // does (drift 0.041 against a driven 0.100), so a pixel A/B cannot say the+ // key caused it. The keyboard is covered by platformer and input-actions.+ interactGap: 'an autonomous enemy moves as much as the input does; the A/B cannot attribute it',},{id: 'spine-demo',certifies: ['spine', 'material', 'asset-lifecycle'],targets: ['web', 'desktop', 'android', 'ios'],tier: 'nightly',+ interactGap: 'a showcase that cycles its own animations; nothing to press',},{id: 'save-load',certifies: ['persistence', 'save-versioning'],targets: ['web', 'desktop'],tier: 'nightly',+ interactGap: 'save slots are driven from the UI, not the keyboard',},{id: 'hot-update-demo',certifies: ['hot-update'],targets: ['web', 'android'],tier: 'nightly',+ interactGap: 'swaps an asset on a timer; no input path',},{id: 'multiplayer-arena',certifies: ['networking'],targets: ['web', 'desktop'],tier: 'nightly',+ interactGap: 'needs a listen server up before input means anything',},{id: 'video-puzzle',certifies: ['single-file'],targets: ['playable', 'web'],tier: 'nightly',+ interactGap: 'tiles are pointer-driven; no keyboard path',},{id: 'input-actions',certifies: ['input'],targets: ['web', 'desktop', 'wechat'],tier: 'release',+ interact: { keys: ['KeyD'], frames: 40 },},];@@ -177,6 +198,12 @@ export function parityFor(g) {return typeof g.parity === 'number' ? g.parity : DEFAULT_PARITY;}+/** The input a project's package must answer, or null when it opted out. */+export function interactFor(g) {+ if (g.interactGap || !g.interact) return null;+ return { keys: g.interact.keys ?? [], frames: g.interact.frames ?? 40, responds: g.interact.responds ?? DEFAULT_RESPONDS };+}+/** Absolute path to a golden project's directory. */export function projectDir(id) {return path.join(EXAMPLES, id);diff --git a/tools/verify-golden.mjs b/tools/verify-golden.mjsindex c95e9ff83..eab2a7e82 100644--- a/tools/verify-golden.mjs+++ b/tools/verify-golden.mjs@@ -1,7 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/**- * @file verify-golden.mjs — carry each golden project through package → launch → compare.+ * @file verify-golden.mjs — carry each golden project through package → launch → drive → compare.** The registry says which projects a tier certifies and for which targets; this* runs that matrix. Web and playable are driven here because both launch in the@@ -18,8 +18,8 @@import { spawnSync } from 'node:child_process';import { mkdirSync, rmSync, readFileSync, existsSync } from 'node:fs';import path from 'node:path';-import { atTier, projectDir, parityFor, ROOT } from './goldenProjects.mjs';-import { frameDistance, readPNG } from './frameCompare.mjs';+import { atTier, projectDir, parityFor, interactFor, ROOT } from './goldenProjects.mjs';+import { frameDistance, frameCellMax, readPNG } from './frameCompare.mjs';const argv = process.argv.slice(2);const flag = (n, d) => {@@ -145,10 +145,48 @@ for (const { id, target } of pairs) {console.log(`✗ ${id} ${target} — parity: ${e.message}`);continue;}- const ok = distance <= tolerance;- results.push({ id, target, stage: 'parity', ok, why: ok ? '' : `distance ${distance.toFixed(4)} > ${tolerance}` });- console.log(`${ok ? '✓' : '✗'} ${id} ${target} — parity ${distance.toFixed(4)} (limit ${tolerance})`);- if (!ok) console.log(` the package is not showing what the editor showed; compare ${editorPng} and ${packagePng}`);+ if (distance > tolerance) {+ results.push({ id, target, stage: 'parity', ok: false, why: `distance ${distance.toFixed(4)} > ${tolerance}` });+ console.log(`✗ ${id} ${target} — parity ${distance.toFixed(4)} (limit ${tolerance})`);+ console.log(` the package is not showing what the editor showed; compare ${editorPng} and ${packagePng}`);+ continue;+ }++ // Does the package answer a keyboard? An A/B against the undriven capture, not+ // a before/after: a game animates on its own, so only "it differs BECAUSE of+ // the key" is a claim. The worst-cell reducer is what sees a sprite move.+ const input = interactFor(golden);+ if (!input) {+ results.push({ id, target, stage: 'parity', ok: true });+ console.log(`✓ ${id} ${target} — parity ${distance.toFixed(4)}`);+ continue;+ }++ const drivenPng = path.join(WORK, `${id}-${target}-driven.png`);+ const drive = spawnSync('npx', [+ 'electron', path.join('scripts', 'launch-export.mjs'),+ '--dir', out, '--out', drivenPng,+ '--w', String(editor.w), '--h', String(editor.h),+ '--input', JSON.stringify({ keys: input.keys, frames: input.frames }),+ ], { encoding: 'utf8', cwd: DESKTOP });+ if (drive.status !== 0) {+ results.push({ id, target, stage: 'interact', ok: false, why: 'the driven launch failed' });+ console.log(`✗ ${id} ${target} — the driven launch failed`);+ continue;+ }++ let response;+ try {+ response = frameCellMax(readFileSync(packagePng), readFileSync(drivenPng));+ } catch (e) {+ results.push({ id, target, stage: 'interact', ok: false, why: e.message });+ console.log(`✗ ${id} ${target} — interact: ${e.message}`);+ continue;+ }+ const answered = response >= input.responds;+ results.push({ id, target, stage: 'interact', ok: answered, why: answered ? '' : `response ${response.toFixed(4)} < ${input.responds}` });+ console.log(`${answered ? '✓' : '✗'} ${id} ${target} — parity ${distance.toFixed(4)}, responds ${response.toFixed(4)} to ${input.keys.join('+')}`);+ if (!answered) console.log(` the package did not visibly answer the key; compare ${packagePng} and ${drivenPng}`);}const bad = results.filter((r) => !r.ok);