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
fix(examples): restore audio preferences across game restarts
yhh8f1641e9e54f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 06a2e0dad..79fd71f6d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,8 @@ published separately; it ships inside the editor.### Fixed+- **Audio preferences survive game restart.** Audio-demo saves and restores master, music and SFX volumes through engine storage, validates saved values, and restores the displayed percentages and actual bus gains at startup. Golden verification uses independent browser processes with a stable origin and isolated profile, cycles master volume to mute and verifies that both the label and silent output survive restart.+- **Authored sound is verified in a packaged game.** Audio-demo's existing spatial source starts through its authored Playing flag. A separate launch unlocks browser audio away from every sound control and reads all spectrum bars, proving output from the scene source while preserving the Beat toggle's independent API and fade demonstration. The golden registry requires this measured run before certifying authored sound.- **Package verification resolves output folders consistently.** Relative work and screenshot paths are resolved before child tools launch, so the editor and package runners write into the same requested folder instead of resolving paths against their own working directories.diff --git a/examples/audio-demo/src/main.ts b/examples/audio-demo/src/main.tsindex 7afdee1c7..eb8dd182a 100644--- a/examples/audio-demo/src/main.ts+++ b/examples/audio-demo/src/main.ts@@ -8,10 +8,11 @@ import { preloadSystem } from './systems/preload';import { sfxSystem } from './systems/sfx';import { beatSystem } from './systems/beat';import { orbitSystem } from './systems/orbit';-import { volumeSystem } from './systems/volume';+import { volumeSystem, restoreVolumeSystem } from './systems/volume';import { visualizerSystem } from './systems/visualizer';addStartupSystem(preloadSystem);+addStartupSystem(restoreVolumeSystem);addSystemToSchedule(Schedule.Update, sfxSystem);addSystemToSchedule(Schedule.Update, beatSystem);addSystemToSchedule(Schedule.Update, orbitSystem);diff --git a/examples/audio-demo/src/settings.ts b/examples/audio-demo/src/settings.tsnew file mode 100644index 000000000..93d4ccaf8--- /dev/null+++ b/examples/audio-demo/src/settings.ts@@ -0,0 +1,13 @@+import { Storage } from 'esengine';++import { parseBusVolumes, type BusVolumes } from './volumeSettings';+export type { BusVolumes } from './volumeSettings';+const KEY = 'audio-demo.volumes';++export function loadBusVolumes(): BusVolumes {+ return parseBusVolumes(Storage.getJSON<unknown>(KEY));+}++export function saveBusVolumes(volumes: BusVolumes): void {+ Storage.setJSON(KEY, volumes);+}diff --git a/examples/audio-demo/src/systems/volume.ts b/examples/audio-demo/src/systems/volume.tsindex fd4d75ddb..dabc50883 100644--- a/examples/audio-demo/src/systems/volume.ts+++ b/examples/audio-demo/src/systems/volume.ts@@ -4,6 +4,8 @@ import {import type { UIEventQueue, AudioAPI } from 'esengine';import { VolumeKnob, VolumeLabel } from '../components';import { VOLUME_STEPS } from '../config';+import { loadBusVolumes, saveBusVolumes, type BusVolumes } from '../settings';+import { VOLUME_BUSES, type VolumeBus } from '../volumeSettings';function applyBusVolume(audio: AudioAPI, bus: string, v: number): void {if (bus === 'master') audio.setMasterVolume(v);@@ -13,6 +15,22 @@ function applyBusVolume(audio: AudioAPI, bus: string, v: number): void {const cap = (s: string): string => s.charAt(0).toUpperCase() + s.slice(1);+export const restoreVolumeSystem = defineSystem(+ [Res(Audio), Query(Mut(VolumeKnob)), Query(Mut(Text), VolumeLabel)],+ (audio: AudioAPI, knobs, labels) => {+ const volumes = loadBusVolumes();+ for (const [, knob] of knobs) {+ if (!VOLUME_BUSES.includes(knob.bus as VolumeBus)) continue;+ knob.volume = volumes[knob.bus as keyof BusVolumes];+ applyBusVolume(audio, knob.bus, knob.volume);+ }+ for (const [, text, label] of labels) {+ text.content = `${cap(label.bus)} ${Math.round((volumes[label.bus as keyof BusVolumes] ?? 1) * 100)}%`;+ }+ },+ { name: 'RestoreVolumeSystem' },+);+// Clicking a knob steps its bus volume through VOLUME_STEPS; labels mirror each// bus's current level.export const volumeSystem = defineSystem(@@ -31,6 +49,7 @@ export const volumeSystem = defineSystem(vol[knob.bus] = knob.volume;}if (changed) {+ saveBusVolumes({ master: vol.master ?? 1, music: vol.music ?? 1, sfx: vol.sfx ?? 1 });for (const [, text, label] of labels) {text.content = `${cap(label.bus)} ${Math.round((vol[label.bus] ?? 1) * 100)}%`;}diff --git a/examples/audio-demo/src/volumeSettings.ts b/examples/audio-demo/src/volumeSettings.tsnew file mode 100644index 000000000..c82de28a6--- /dev/null+++ b/examples/audio-demo/src/volumeSettings.ts@@ -0,0 +1,15 @@+export const VOLUME_BUSES = ['master', 'music', 'sfx'] as const;+export type VolumeBus = typeof VOLUME_BUSES[number];+export type BusVolumes = Record<VolumeBus, number>;++export function parseBusVolumes(stored: unknown): BusVolumes {+ const volumes = { master: 1, music: 1, sfx: 1 };+ if (!stored || typeof stored !== 'object' || Array.isArray(stored)) return volumes;+ for (const bus of VOLUME_BUSES) {+ const value = (stored as Partial<BusVolumes>)[bus];+ if (typeof value === 'number' && Number.isFinite(value)) {+ volumes[bus] = Math.max(0, Math.min(1, value));+ }+ }+ return volumes;+}diff --git a/pipeline/src/runtime/gameHost.ts b/pipeline/src/runtime/gameHost.tsindex 44d3b6a16..098c78df0 100644--- a/pipeline/src/runtime/gameHost.ts+++ b/pipeline/src/runtime/gameHost.ts@@ -354,9 +354,9 @@ async function boot(): Promise<void> {probe(names: string[] = []): {scene: string | null;transitioning: boolean;- at: Record<string, { x: number; y: number; z?: number; w?: number; h?: number }>;+ at: Record<string, { x: number; y: number; z?: number; w?: number; h?: number; text?: string }>;} {- const at: Record<string, { x: number; y: number; z?: number; w?: number; h?: number }> = {};+ const at: Record<string, { x: number; y: number; z?: number; w?: number; h?: number; text?: string }> = {};for (const name of names) {const entity = app.world.findEntityByName(name);if (entity === null || !app.world.has(entity, Transform)) continue;@@ -367,6 +367,8 @@ async function boot(): Promise<void> {// z as well: a 3D driver asking where something is cannot be answered// by the plane, and a character walking a ramp moves in all three.at[name] = { x: p.x, y: p.y, z: p.z ?? 0 };+ const text = optionalRead(app, entity, 'Text');+ if (typeof text?.content === 'string') at[name].text = text.content;// A node's own size, for a claim about a value the game COMPUTED rather// than about where it ended up — a spectrum bar barely moves while its// height carries the whole answer.diff --git a/sdk/tests/audio-demo-settings.test.ts b/sdk/tests/audio-demo-settings.test.tsnew file mode 100644index 000000000..5d17a426f--- /dev/null+++ b/sdk/tests/audio-demo-settings.test.ts@@ -0,0 +1,21 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { expect, it } from 'vitest';+import { parseBusVolumes } from '../../examples/audio-demo/src/volumeSettings';++it('restores all three bus settings and preserves mute', () => {+ expect(parseBusVolumes({ master: 0, music: .33, sfx: .66 })).toEqual({ master: 0, music: .33, sfx: .66 });+});+it('rejects malformed values and bounds stored volumes', () => {+ expect(parseBusVolumes({ master: -1, music: 2, sfx: 'muted' })).toEqual({ master: 0, music: 1, sfx: 1 });+ expect(parseBusVolumes({ master: NaN, music: Infinity })).toEqual({ master: 1, music: 1, sfx: 1 });+});+it('uses defaults when no settings have been saved', () => {+ for (const stored of [undefined, null, [], false, 'bad data']) {+ expect(parseBusVolumes(stored)).toEqual({ master: 1, music: 1, sfx: 1 });+ }+});+it('retains saved values through a JSON round trip', () => {+ const values = { master: 0, music: .33, sfx: .66 };+ expect(parseBusVolumes(JSON.parse(JSON.stringify(values)))).toEqual(values);+});diff --git a/tools/check-golden.mjs b/tools/check-golden.mjsindex 6e72739e6..f72a6de08 100644--- a/tools/check-golden.mjs+++ b/tools/check-golden.mjs@@ -60,6 +60,7 @@ const NEEDS_RUN = {'texture-atlas': 'atlas',audio: 'audio','authored-sound': 'authoredAudio',+ settings: 'settings','safe-area': 'safeArea','pause-resume': 'suspend','hot-update': 'runBy',diff --git a/tools/goldenProjects.mjs b/tools/goldenProjects.mjsindex dace63e82..53da633ea 100644--- a/tools/goldenProjects.mjs+++ b/tools/goldenProjects.mjs@@ -696,11 +696,7 @@ export const EVIDENCE = {* the hole is visible in the gate's output instead of being mistaken for* coverage — the same bargain check-project-settings strikes.*/-export const KNOWN_GAPS = {- // Present in the engine and shown by non-golden samples, but never carried- // through the chain by a project the release argues from.- settings: 'Celestial Heights persists language, effects and key bindings and reads them back at boot; volume waits on the game having sound',-};+export const KNOWN_GAPS = {};/*** The corpus. `certifies` is the claim, `targets` the packages that must build@@ -1055,7 +1051,7 @@ export const GOLDEN = [},{id: 'audio-demo',- certifies: ['audio', 'authored-sound'],+ certifies: ['audio', 'authored-sound', 'settings'],targets: ['web', 'desktop'],tier: 'release',interactGap: 'a pad plays a sound and draws nothing of its own — the audio block below is the run that reads the result',@@ -1064,6 +1060,8 @@ export const GOLDEN = [// read the bar the visualizer writes from an analyser bin.audio: { toggle: { x: 0.5, y: 0.41 }, bar: 'Bar0', floor: 6, frames: 60 },authoredAudio: { unlock: { x: 0.02, y: 0.02 }, bars: Array.from({ length: 16 }, (_, i) => `Bar${i}`), floor: 6, frames: 60 },+ settings: { control: { x: 0.275, y: 0.513333 }, unlock: { x: 0.02, y: 0.02 }, label: 'MasterLabel',+ expected: ['Master 66%', 'Master 33%', 'Master 0%'], bars: Array.from({ length: 16 }, (_, i) => `Bar${i}`), floor: 6, w: 800, h: 600, frames: 60 },},];@@ -1105,7 +1103,8 @@ export function atTier(tier) {*/export function sharesOf(projects, n, owned) {const weight = (g) => g.targets.filter((t) => owned.has(t)).length- * (1 + [interactFor(g), audioFor(g), g.authoredAudio, safeAreaFor(g), atlasFor(g)].filter(Boolean).length + (suspendFor(g) ? 3 : 0));+ * (1 + [interactFor(g), audioFor(g), g.authoredAudio, safeAreaFor(g), atlasFor(g)].filter(Boolean).length+ + (g.settings ? g.settings.expected.length + 1 : 0) + (suspendFor(g) ? 3 : 0));const bins = Array.from({ length: n }, () => ({ projects: [], load: 0 }));for (const g of [...projects].sort((a, b) => weight(b) - weight(a))) {const bin = bins.reduce((least, b) => (b.load < least.load ? b : least));diff --git a/tools/launchers/launch-export.mjs b/tools/launchers/launch-export.mjsindex 22b85fd05..e9d702936 100644--- a/tools/launchers/launch-export.mjs+++ b/tools/launchers/launch-export.mjs@@ -23,6 +23,7 @@* --frame-ms <n> simulated time per render frame (default 1000/60; 0 = real time)* --timeout <ms> how long to wait for the first frame (default 30000)* --scene <name> boot this named scene instead of the package's entry+ * --port <n> serve on a fixed loopback port for same-origin restart tests* --allow-flat accept a single-colour frame (a deliberately blank scene)* --input <json> drive it: {"keys":["ArrowRight"]} or {"pointer":{"x":.5,"y":.5}}* --touch present as a touch device (maxTouchPoints > 0), so a@@ -156,7 +157,7 @@ const MIME = {/** Serve the export directory. Range requests are not implemented: a build that* needs them (video seek) would read as a broken asset here, not a broken server. */-function serve(root, safeArea, frameMs, compress) {+function serve(root, safeArea, frameMs, compress, port = 0) {const server = http.createServer(async (req, res) => {try {let rel = decodeURIComponent(new URL(req.url, 'http://x').pathname).replace(/^\/+/, '');@@ -195,7 +196,10 @@ function serve(root, safeArea, frameMs, compress) {res.writeHead(404).end();}});- return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server)));+ return new Promise((resolve, reject) => {+ server.once('error', reject);+ server.listen(port, '127.0.0.1', () => resolve(server));+ });}/** Is more than one colour on screen? The question a boot-to-black build fails. */@@ -231,7 +235,7 @@ const AI = flag('ai', '');const RENDER = has('render');/** Boot a named scene from the package instead of its entry. */const SCENE = flag('scene', '');- const server = await serve(DIR, flag('safe-area', ''), Number(flag('frame-ms', String(1000 / 60))), !!THROTTLE);+ const server = await serve(DIR, flag('safe-area', ''), Number(flag('frame-ms', String(1000 / 60))), !!THROTTLE, Number(flag('port', '0')));const query = new URLSearchParams();if (PROBE || GAMEPLAY || PARTICLES || COMBAT || AI || RENDER || FACTS || RENDER_FACTS || STREAMING) query.set('headless', '');if (SCENE) query.set('scene', SCENE);diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex d49657dfe..83c80c86f 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'fix(examples): restore audio preferences across game restarts':+ { note: 'Audio preferences survive game restart.' },'test(audio): certify authored source playback after packaging':{ note: 'Authored sound is verified in a packaged game.' },'fix(test): resolve golden output paths before spawning tools':diff --git a/tools/verify-golden.mjs b/tools/verify-golden.mjsindex 817d403f7..212a1c17c 100644--- a/tools/verify-golden.mjs+++ b/tools/verify-golden.mjs@@ -423,6 +423,15 @@ for (const { id, target } of pairs) {// that starts the sound redraws itself either way. So drive the toggle and read// the height the game wrote from an analyser bin — silence leaves it on its floor.const audio = audioFor(golden);+ if (golden.settings && target === 'web') {+ const run = spawnSync(process.execPath, [path.join(ROOT, 'tools/verify-settings.mjs'),+ '--dir', out, '--spec', JSON.stringify(golden.settings)], { cwd: ROOT, encoding: 'utf8' });+ const ok = run.status === 0;+ results.push({ id, target, stage: 'settings', ok, why: ok ? '' : String(run.stderr || run.stdout || 'settings verifier did not complete') });+ console.log(`${ok ? '✓' : '✗'} ${id} ${target} — settings process restart`);+ for (const line of (run.stdout || '').trim().split('\n')) if (line) console.log(` ${line}`);+ if (!ok) for (const line of (run.stderr || '').trim().split('\n').slice(-8)) if (line) console.log(` ${line}`);+ }const authoredAudio = golden.authoredAudio;if (authoredAudio && target === 'web') {// This gesture only unlocks browser audio. It avoids every pad and thediff --git a/tools/verify-settings.mjs b/tools/verify-settings.mjsnew file mode 100644index 000000000..7a9697034--- /dev/null+++ b/tools/verify-settings.mjs@@ -0,0 +1,50 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import path from 'node:path';+import net from 'node:net';+import { mkdtempSync, rmSync } from 'node:fs';+import os from 'node:os';+import { runElectron } from './lib/electronRun.mjs';+import { fileURLToPath } from 'node:url';++const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const args = process.argv.slice(2);+const flag = name => { const i = args.indexOf('--' + name); return i < 0 ? undefined : args[i + 1]; };+const dir = flag('dir'), specArg = flag('spec');+if (!dir || !specArg) throw new Error('verify-settings requires --dir and --spec');+const spec = JSON.parse(specArg);+const server = net.createServer();+await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });+const port = server.address().port;+await new Promise(resolve => server.close(resolve));+// One new profile and one stable origin, reused across independent processes.+const profile = mkdtempSync(path.join(os.tmpdir(), 'estella-settings-'));+const names = [spec.label, ...spec.bars];+try {+ for (let i = 0; i <= spec.expected.length; i++) {+ const restart = i === spec.expected.length;+ const pointer = restart ? spec.unlock : spec.control;+ const run = runElectron(['--user-data-dir=' + profile, path.join(root, 'tools/launchers/launch-export.mjs'),+ '--dir', path.resolve(dir), '--port', String(port), '--w', String(spec.w), '--h', String(spec.h),+ '--input', JSON.stringify({ pointer, frames: spec.frames ?? 60 }), '--probe', names.join(',')], { cwd: root, encoding: 'utf8' });+ if (run.status !== 0) throw new Error((run.stdout || '') + (run.stderr || ''));+ const match = /probe: (\{.*\})/.exec(run.stdout || '');+ if (!match) throw new Error('settings launch produced no probe');+ const at = JSON.parse(match[1]).at;+ const expected = spec.expected[restart ? i - 1 : i];+ if (at?.[spec.label]?.text !== expected) throw new Error(`settings label was ${at?.[spec.label]?.text}, expected ${expected}`);+ const heights = spec.bars.map(name => at?.[name]?.h);+ if (!heights.length || heights.some(h => typeof h !== 'number' || !Number.isFinite(h))) throw new Error('settings spectrum probe was incomplete');+ const peak = Math.max(...heights);+ if (i >= spec.expected.length - 1 && peak !== spec.floor) throw new Error(`restored mute still produced output: ${peak}`);+ if (i === 0 && peak <= spec.floor) throw new Error('settings test began with no audible output');+ console.log(`settings restart ${i}: ${expected}, spectrum peak ${peak}`);+ }+ console.log('✓ settings survived process restart and restored mute affects output');+} finally {+ const resolved = path.resolve(profile);+ if (path.dirname(resolved) !== path.resolve(os.tmpdir()) || !path.basename(resolved).startsWith('estella-settings-')) {+ throw new Error('unexpected settings profile path');+ }+ rmSync(resolved, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });+}