@wasm-gaming/sonic3air-wasm 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -456,7 +456,10 @@ export function createInput(options = {}) {
456
456
  let suspended = false;
457
457
  let destroyed = false;
458
458
  let polling = false;
459
+ let muted = 0;
459
460
  const held = new Map();
461
+ // Slots (positions in getGamepads()) whose Y was pressed as part of Select + Y.
462
+ const comboY = new Set();
460
463
  // A snapshot: a listener that subscribes another one (a screen opening the next)
461
464
  // must not hand it the same action — a Set also visits entries added while it is
462
465
  // being iterated, so one Enter would open a screen and activate its focused item.
@@ -468,7 +471,7 @@ export function createInput(options = {}) {
468
471
  }
469
472
  };
470
473
  const onKey = (event) => {
471
- if (destroyed)
474
+ if (destroyed || muted > 0)
472
475
  return;
473
476
  const key = event;
474
477
  if (suspended) {
@@ -490,8 +493,10 @@ export function createInput(options = {}) {
490
493
  }
491
494
  fire(action, { source: 'keyboard', repeat: key.repeat === true });
492
495
  };
493
- const pressed = (pad) => {
496
+ const pressed = (pad, slot) => {
494
497
  const actions = new Set();
498
+ if (pad.buttons[3]?.pressed !== true)
499
+ comboY.delete(slot);
495
500
  const select = pad.buttons[8]?.pressed === true;
496
501
  const start = pad.buttons[9]?.pressed === true;
497
502
  if (select && start)
@@ -501,6 +506,12 @@ export function createInput(options = {}) {
501
506
  return;
502
507
  if ((index === 8 || index === 9) && select && start)
503
508
  return;
509
+ // Select + Y is the fullscreen combo (createFullscreenToggle): Y stays quiet until
510
+ // it is let go, even if Select is let go first.
511
+ if (index === 3 && (select || comboY.has(slot))) {
512
+ comboY.add(slot);
513
+ return;
514
+ }
504
515
  const action = padmap[index];
505
516
  if (action)
506
517
  actions.add(action);
@@ -521,16 +532,19 @@ export function createInput(options = {}) {
521
532
  return;
522
533
  const t = now();
523
534
  const active = new Set();
524
- for (const pad of gamepads())
535
+ gamepads().forEach((pad, slot) => {
525
536
  if (pad)
526
- for (const action of pressed(pad))
537
+ for (const action of pressed(pad, slot))
527
538
  active.add(action);
539
+ });
528
540
  for (const action of active) {
529
541
  const state = held.get(action);
530
542
  if (!state) {
531
543
  held.set(action, { since: t, last: t });
532
544
  // In game only the Select + Start combo gets through (plain Start is the game's).
533
545
  const combo = action === 'menu' && gamepads().some((p) => p?.buttons[8]?.pressed && p.buttons[9]?.pressed);
546
+ if (muted > 0)
547
+ continue;
534
548
  if (!suspended || combo)
535
549
  fire(action, { source: 'gamepad', repeat: false });
536
550
  }
@@ -538,7 +552,7 @@ export function createInput(options = {}) {
538
552
  t - state.since >= UI_REPEAT.delay &&
539
553
  t - state.last >= UI_REPEAT.interval) {
540
554
  state.last = t;
541
- if (!suspended)
555
+ if (!suspended && muted === 0)
542
556
  fire(action, { source: 'gamepad', repeat: true });
543
557
  }
544
558
  }
@@ -590,13 +604,23 @@ export function createInput(options = {}) {
590
604
  return () => suspendListeners.delete(listener);
591
605
  },
592
606
  trigger(action, detail = { source: 'touch', repeat: false }) {
593
- if (destroyed)
607
+ if (destroyed || muted > 0)
594
608
  return;
595
609
  if (suspended && action !== 'menu')
596
610
  return;
597
611
  fire(action, detail);
598
612
  },
599
613
  poll,
614
+ mute() {
615
+ muted += 1;
616
+ let undone = false;
617
+ return () => {
618
+ if (undone)
619
+ return;
620
+ undone = true;
621
+ muted -= 1;
622
+ };
623
+ },
600
624
  destroy() {
601
625
  destroyed = true;
602
626
  listeners.clear();
@@ -1543,4 +1567,1034 @@ export function connectTouchPad(pad, input) {
1543
1567
  offPause();
1544
1568
  };
1545
1569
  }
1570
+ // ============================================================================
1571
+ // ---- Languages: English and Spanish, English when in doubt ----
1572
+ // ============================================================================
1573
+ //
1574
+ // Every screen of the ecosystem speaks English and Spanish and falls back to English.
1575
+ // Code and SDK error messages stay English: they are for developers.
1576
+ /** The languages every screen speaks. */
1577
+ export const LOCALES = ['en', 'es'];
1578
+ /** The text in `locale`, else in English. */
1579
+ export function localize(text, locale) {
1580
+ if (typeof text === 'string')
1581
+ return text;
1582
+ return text[locale] ?? text.en;
1583
+ }
1584
+ const isLocale = (value) => LOCALES.includes(value);
1585
+ /**
1586
+ * The language to speak: `preferred` (the host's) when it is one of {@link LOCALES},
1587
+ * else the first of the browser's languages that is (matched on the primary subtag,
1588
+ * so `es-419` is `es`), else English.
1589
+ */
1590
+ export function resolveLocale(preferred, languages = globalThis.navigator?.languages ?? []) {
1591
+ for (const tag of [preferred, ...languages]) {
1592
+ const primary = tag?.toLowerCase().split('-')[0];
1593
+ if (isLocale(primary))
1594
+ return primary;
1595
+ }
1596
+ return 'en';
1597
+ }
1598
+ /** What engine-specs' own screens say. Apps may reuse these keys. */
1599
+ export const UI_STRINGS = Object.freeze({
1600
+ 'settings.title': { en: 'Settings', es: 'Ajustes' },
1601
+ 'settings.group.video': { en: 'Video', es: 'Vídeo' },
1602
+ 'settings.group.audio': { en: 'Audio', es: 'Audio' },
1603
+ 'settings.group.emulation': { en: 'Emulation', es: 'Emulación' },
1604
+ 'settings.group.game': { en: 'Game', es: 'Juego' },
1605
+ 'settings.group.controls': { en: 'Controls', es: 'Controles' },
1606
+ 'settings.yes': { en: 'Yes', es: 'Sí' },
1607
+ 'settings.no': { en: 'No', es: 'No' },
1608
+ 'settings.restart': { en: 'Applies on restart', es: 'Se aplica al reiniciar' },
1609
+ 'settings.reset': { en: 'Reset to defaults', es: 'Restablecer' },
1610
+ 'settings.resetAsk': { en: 'Put every setting back to its default?', es: '¿Volver a dejar todos los ajustes como venían?' },
1611
+ 'settings.hints': { en: 'A / ◀ ▶ Change · Y Details · B Back', es: 'A / ◀ ▶ Cambiar · Y Detalles · B Volver' },
1612
+ 'controls.capture': { en: 'Press a key or a button… (Escape cancels)', es: 'Pulsa una tecla o un botón… (Escape cancela)' },
1613
+ 'controls.none': { en: '—', es: '—' },
1614
+ 'fullscreen.toggle': { en: 'Fullscreen', es: 'Pantalla completa' },
1615
+ 'perf.fps': { en: '{fps} fps', es: '{fps} fps' },
1616
+ 'perf.frame': { en: '{avg} ms (worst {worst})', es: '{avg} ms (peor {worst})' },
1617
+ 'perf.dropped': { en: '{dropped} dropped', es: '{dropped} perdidos' },
1618
+ });
1619
+ /** One of {@link UI_STRINGS} in `locale`, with `{name}` placeholders filled. */
1620
+ export function uiText(key, locale, params = {}) {
1621
+ return localize(UI_STRINGS[key], locale).replace(/\{(\w+)\}/g, (match, name) => name in params ? String(params[name]) : match);
1622
+ }
1623
+ // ============================================================================
1624
+ // ---- Settings: the player-facing properties, a model, storage and a screen ----
1625
+ // ============================================================================
1626
+ //
1627
+ // A setting is a property with a `label` (see PropertyDefinition). The model turns
1628
+ // the descriptors an SDK already returns into rows; the screen draws the rows and
1629
+ // follows UX.md; the app applies a live change and saves (per engine, in OPFS
1630
+ // `settings/<engineId>.json`, shared by all its games).
1631
+ /** The settings screen's sections, in the order they are shown. */
1632
+ export const SETTING_GROUPS = ['video', 'audio', 'emulation', 'game', 'controls'];
1633
+ const settingChoices = (descriptor) => {
1634
+ if (descriptor.enum && descriptor.enum.length > 0)
1635
+ return descriptor.enum;
1636
+ const sample = descriptor.value ?? descriptor.default;
1637
+ return typeof sample === 'boolean' ? [false, true] : undefined;
1638
+ };
1639
+ const choiceLabel = (descriptor, value, index, locale) => {
1640
+ const named = descriptor.valueLabels?.[index];
1641
+ if (named !== undefined)
1642
+ return localize(named, locale);
1643
+ if (typeof value === 'boolean')
1644
+ return uiText(value ? 'settings.yes' : 'settings.no', locale);
1645
+ return String(value);
1646
+ };
1647
+ /**
1648
+ * The settings screen's content: every property with a `label` and something to step
1649
+ * through (an `enum`, or a boolean), grouped in {@link SETTING_GROUPS} order. The
1650
+ * current value is the saved one, else the descriptor's `value`, else its `default`.
1651
+ * Properties without a `label`, or that cannot be stepped, are left out.
1652
+ */
1653
+ export function settingsModel(described, saved = {}, locale = 'en') {
1654
+ const sections = new Map();
1655
+ for (const [key, descriptor] of Object.entries(described)) {
1656
+ if (descriptor.label === undefined)
1657
+ continue;
1658
+ const choices = settingChoices(descriptor);
1659
+ if (!choices)
1660
+ continue;
1661
+ const group = descriptor.group ?? 'game';
1662
+ const current = key in saved ? saved[key] : (descriptor.value ?? descriptor.default ?? choices[0]);
1663
+ const choiceLabels = choices.map((choice, index) => choiceLabel(descriptor, choice, index, locale));
1664
+ const at = choices.indexOf(current);
1665
+ const row = {
1666
+ key,
1667
+ label: localize(descriptor.label, locale),
1668
+ group,
1669
+ value: current,
1670
+ valueLabel: choiceLabels[at] ?? String(current),
1671
+ choices,
1672
+ choiceLabels,
1673
+ live: descriptor.live === true,
1674
+ ...(descriptor.description ? { description: descriptor.description } : {}),
1675
+ };
1676
+ sections.set(group, [...(sections.get(group) ?? []), row]);
1677
+ }
1678
+ return SETTING_GROUPS.filter((group) => sections.has(group)).map((group) => ({
1679
+ group,
1680
+ title: uiText(`settings.group.${group}`, locale),
1681
+ rows: sections.get(group),
1682
+ }));
1683
+ }
1684
+ /**
1685
+ * The value a step takes a row to: `+1` forward, `-1` back. Enums and booleans wrap
1686
+ * around; an enum of numbers (a volume) stops at its ends.
1687
+ */
1688
+ export function stepSetting(row, direction) {
1689
+ const { choices } = row;
1690
+ if (choices.length === 0)
1691
+ return row.value;
1692
+ const at = choices.indexOf(row.value);
1693
+ if (at === -1)
1694
+ return choices[0];
1695
+ const numeric = choices.every((choice) => typeof choice === 'number');
1696
+ const next = at + direction;
1697
+ if (numeric)
1698
+ return choices[Math.min(choices.length - 1, Math.max(0, next))];
1699
+ return choices[(next + choices.length) % choices.length];
1700
+ }
1701
+ /** A row with another value, its label updated. */
1702
+ export function withSettingValue(row, value) {
1703
+ const at = row.choices.indexOf(value);
1704
+ return { ...row, value, valueLabel: row.choiceLabels[at] ?? String(value) };
1705
+ }
1706
+ /** The defaults of every setting (the properties with a `label` and a `default`), for "Reset". */
1707
+ export function settingsDefaults(described) {
1708
+ const defaults = {};
1709
+ for (const [key, descriptor] of Object.entries(described)) {
1710
+ if (descriptor.label !== undefined && descriptor.default !== undefined)
1711
+ defaults[key] = descriptor.default;
1712
+ }
1713
+ return defaults;
1714
+ }
1715
+ /**
1716
+ * The settings engine-specs itself provides, for an app to merge into what it shows:
1717
+ * the screen Wake Lock ({@link createWakeLock}) and the counter ({@link createPerfCounter}).
1718
+ */
1719
+ export const SHARED_SETTINGS = Object.freeze({
1720
+ keepScreenOn: {
1721
+ default: true,
1722
+ live: true,
1723
+ group: 'video',
1724
+ label: { en: 'Keep the screen on', es: 'Mantener la pantalla encendida' },
1725
+ description: 'Holds a screen Wake Lock while the game runs, released when it is paused or hidden.',
1726
+ },
1727
+ showPerformance: {
1728
+ default: false,
1729
+ live: true,
1730
+ group: 'video',
1731
+ label: { en: 'Show performance', es: 'Mostrar rendimiento' },
1732
+ description: 'An overlay with frames per second, frame time and dropped frames.',
1733
+ },
1734
+ });
1735
+ /** For an engine whose frame loop the app drives: what paces it ({@link createFrameClock}). */
1736
+ export const FRAME_SYNC_SETTING = Object.freeze({
1737
+ frameSync: {
1738
+ default: 'display',
1739
+ enum: ['display', 'audio'],
1740
+ valueLabels: [
1741
+ { en: 'Display', es: 'Pantalla' },
1742
+ { en: 'Audio', es: 'Audio' },
1743
+ ],
1744
+ live: true,
1745
+ group: 'emulation',
1746
+ label: { en: 'Sync', es: 'Sincronización' },
1747
+ description: 'What paces the frames: the display refresh, or the audio clock (steady on 120 Hz screens).',
1748
+ },
1749
+ });
1750
+ const emptySettings = () => ({ version: 1, values: {}, controls: {} });
1751
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
1752
+ /** A settings file's text, read leniently: missing or broken reads as "nothing saved". */
1753
+ export function parseSettings(text) {
1754
+ if (!text)
1755
+ return emptySettings();
1756
+ try {
1757
+ const data = JSON.parse(text);
1758
+ if (!isRecord(data))
1759
+ return emptySettings();
1760
+ const controls = {};
1761
+ if (isRecord(data.controls)) {
1762
+ for (const [id, binding] of Object.entries(data.controls)) {
1763
+ if (!isRecord(binding))
1764
+ continue;
1765
+ controls[id] = {
1766
+ ...(typeof binding.key === 'string' ? { key: binding.key } : {}),
1767
+ ...(typeof binding.code === 'string' ? { code: binding.code } : {}),
1768
+ ...(Number.isInteger(binding.button) ? { button: binding.button } : {}),
1769
+ };
1770
+ }
1771
+ }
1772
+ return { version: 1, values: isRecord(data.values) ? { ...data.values } : {}, controls };
1773
+ }
1774
+ catch {
1775
+ return emptySettings();
1776
+ }
1777
+ }
1778
+ const ENGINE_ID = /^[a-z0-9][a-z0-9._-]*$/i;
1779
+ const settingsRoot = async (root) => {
1780
+ if (root)
1781
+ return root;
1782
+ const storage = globalThis.navigator?.storage;
1783
+ if (!storage?.getDirectory)
1784
+ throw new Error('OPFS is not available');
1785
+ return (await storage.getDirectory());
1786
+ };
1787
+ /** The player's settings for an engine (OPFS `settings/<engineId>.json`). Never throws. */
1788
+ export async function loadSettings(engineId, root) {
1789
+ if (!ENGINE_ID.test(engineId))
1790
+ throw new Error(`Invalid engine id: ${engineId}`);
1791
+ try {
1792
+ const dir = await (await settingsRoot(root)).getDirectoryHandle('settings');
1793
+ const file = await (await dir.getFileHandle(`${engineId}.json`)).getFile();
1794
+ return parseSettings(await file.text());
1795
+ }
1796
+ catch {
1797
+ return emptySettings();
1798
+ }
1799
+ }
1800
+ /** Writes the player's settings for an engine. */
1801
+ export async function saveSettings(engineId, settings, root) {
1802
+ if (!ENGINE_ID.test(engineId))
1803
+ throw new Error(`Invalid engine id: ${engineId}`);
1804
+ const dir = await (await settingsRoot(root)).getDirectoryHandle('settings', { create: true });
1805
+ const writable = await (await dir.getFileHandle(`${engineId}.json`, { create: true })).createWritable();
1806
+ await writable.write(JSON.stringify({ version: 1, values: settings.values, controls: settings.controls }, null, 2));
1807
+ await writable.close();
1808
+ }
1809
+ /** The standard-mapping gamepad buttons by index, as UX.md names them. */
1810
+ export const PAD_BUTTON_NAMES = Object.freeze([
1811
+ 'A', 'B', 'X', 'Y', 'LB', 'RB', 'LT', 'RT', 'Select', 'Start', 'L3', 'R3', '↑', '↓', '←', '→', 'Home',
1812
+ ]);
1813
+ const KEY_NAMES = Object.freeze({
1814
+ ' ': 'Space',
1815
+ ArrowUp: '↑',
1816
+ ArrowDown: '↓',
1817
+ ArrowLeft: '←',
1818
+ ArrowRight: '→',
1819
+ Escape: 'Esc',
1820
+ });
1821
+ const CODE_NAMES = Object.freeze({
1822
+ ArrowUp: '↑',
1823
+ ArrowDown: '↓',
1824
+ ArrowLeft: '←',
1825
+ ArrowRight: '→',
1826
+ Escape: 'Esc',
1827
+ ShiftLeft: 'Shift (L)',
1828
+ ShiftRight: 'Shift (R)',
1829
+ ControlLeft: 'Ctrl (L)',
1830
+ ControlRight: 'Ctrl (R)',
1831
+ AltLeft: 'Alt (L)',
1832
+ AltRight: 'Alt (R)',
1833
+ MetaLeft: 'Meta (L)',
1834
+ MetaRight: 'Meta (R)',
1835
+ });
1836
+ /** How a physical key (`KeyboardEvent.code`) is written on screen: `KeyX` → `X`. */
1837
+ export function codeLabel(code) {
1838
+ if (code === undefined)
1839
+ return '';
1840
+ const named = CODE_NAMES[code];
1841
+ if (named !== undefined)
1842
+ return named;
1843
+ const match = /^(?:Key|Digit)(.)$/.exec(code);
1844
+ if (match?.[1])
1845
+ return match[1];
1846
+ if (code.startsWith('Numpad'))
1847
+ return `Num ${code.slice(6)}`;
1848
+ return code;
1849
+ }
1850
+ /** How a binding's key is written: by its `code` when it has one, else by its `key`. */
1851
+ export function bindingKeyLabel(binding) {
1852
+ return binding.code !== undefined ? codeLabel(binding.code) : keyLabel(binding.key);
1853
+ }
1854
+ /** How a key is written on screen. */
1855
+ export function keyLabel(key) {
1856
+ if (key === undefined)
1857
+ return '';
1858
+ const named = KEY_NAMES[key];
1859
+ if (named !== undefined)
1860
+ return named;
1861
+ return key.length === 1 ? key.toUpperCase() : key;
1862
+ }
1863
+ /** The controls rows: each button with its binding (saved, else default). */
1864
+ export function controlsModel(buttons, defaults, saved = {}, locale = 'en') {
1865
+ const none = uiText('controls.none', locale);
1866
+ return buttons.map(({ id, label }) => {
1867
+ const binding = { ...(defaults[id] ?? {}), ...(saved[id] ?? {}) };
1868
+ return {
1869
+ id,
1870
+ label: localize(label, locale),
1871
+ binding,
1872
+ keyLabel: bindingKeyLabel(binding) || none,
1873
+ buttonLabel: binding.button === undefined ? none : (PAD_BUTTON_NAMES[binding.button] ?? `#${binding.button}`),
1874
+ };
1875
+ });
1876
+ }
1877
+ /**
1878
+ * The bindings with `id` given a new key and / or button. Another button that had it
1879
+ * gets `id`'s old one in exchange, so no two buttons ever share a key or a button.
1880
+ * Keys are the same key when their `code`s match (or, without codes, their `key`s);
1881
+ * `key` and `code` move together.
1882
+ */
1883
+ export function bindControl(bindings, id, change) {
1884
+ const next = {};
1885
+ for (const [other, binding] of Object.entries(bindings))
1886
+ next[other] = { ...binding };
1887
+ const mine = (next[id] ??= {});
1888
+ const keyOf = (binding) => ({
1889
+ ...(binding.key !== undefined ? { key: binding.key } : {}),
1890
+ ...(binding.code !== undefined ? { code: binding.code } : {}),
1891
+ });
1892
+ const sameKey = (a, b) => a.code !== undefined && b.code !== undefined ? a.code === b.code : a.key !== undefined && a.key === b.key;
1893
+ const setKey = (binding, value) => {
1894
+ delete binding.key;
1895
+ delete binding.code;
1896
+ Object.assign(binding, value);
1897
+ };
1898
+ if (change.key !== undefined || change.code !== undefined) {
1899
+ const old = keyOf(mine);
1900
+ const value = keyOf(change);
1901
+ for (const [other, binding] of Object.entries(next)) {
1902
+ if (other !== id && sameKey(binding, value))
1903
+ setKey(binding, old);
1904
+ }
1905
+ setKey(mine, value);
1906
+ }
1907
+ if (change.button !== undefined) {
1908
+ const old = mine.button;
1909
+ for (const [other, binding] of Object.entries(next)) {
1910
+ if (other === id || binding.button !== change.button)
1911
+ continue;
1912
+ if (old === undefined)
1913
+ delete binding.button;
1914
+ else
1915
+ binding.button = old;
1916
+ }
1917
+ mine.button = change.button;
1918
+ }
1919
+ return next;
1920
+ }
1921
+ /**
1922
+ * The next key or gamepad button pressed, for a binding. Escape cancels (resolves
1923
+ * `undefined`), as does `signal`. Buttons held when it starts are ignored until let
1924
+ * go. The shared `input` is muted meanwhile ({@link UiInput.mute}), so the press
1925
+ * neither moves a menu nor opens one.
1926
+ */
1927
+ export function captureBinding(input, options = {}) {
1928
+ const target = options.target ?? globalThis;
1929
+ const gamepads = options.gamepads ??
1930
+ (() => (globalThis.navigator?.getGamepads?.() ?? []));
1931
+ const schedule = options.schedule === undefined ? (globalThis.requestAnimationFrame?.bind(globalThis) ?? null) : options.schedule;
1932
+ const unmute = input?.mute?.() ?? (() => undefined);
1933
+ return new Promise((resolve) => {
1934
+ let done = false;
1935
+ const ignored = new Set();
1936
+ for (const pad of gamepads())
1937
+ pad?.buttons.forEach((button, index) => button.pressed && ignored.add(index));
1938
+ const finish = (binding) => {
1939
+ if (done)
1940
+ return;
1941
+ done = true;
1942
+ target.removeEventListener('keydown', onKey, { capture: true });
1943
+ options.signal?.removeEventListener('abort', onAbort);
1944
+ unmute();
1945
+ resolve(binding);
1946
+ };
1947
+ const onKey = (event) => {
1948
+ const key = event;
1949
+ key.preventDefault();
1950
+ key.stopPropagation();
1951
+ if (key.repeat)
1952
+ return;
1953
+ finish(key.key === 'Escape' ? undefined : { key: key.key, ...(key.code ? { code: key.code } : {}) });
1954
+ };
1955
+ const onAbort = () => finish(undefined);
1956
+ const poll = () => {
1957
+ if (done)
1958
+ return;
1959
+ const down = new Set();
1960
+ for (const pad of gamepads())
1961
+ pad?.buttons.forEach((button, index) => button.pressed && down.add(index));
1962
+ for (const index of [...ignored])
1963
+ if (!down.has(index))
1964
+ ignored.delete(index);
1965
+ const fresh = [...down].find((index) => !ignored.has(index));
1966
+ if (fresh !== undefined)
1967
+ return finish({ button: fresh });
1968
+ schedule?.(poll);
1969
+ };
1970
+ if (options.signal?.aborted)
1971
+ return finish(undefined);
1972
+ options.signal?.addEventListener('abort', onAbort);
1973
+ target.addEventListener('keydown', onKey, { capture: true });
1974
+ schedule?.(poll);
1975
+ });
1976
+ }
1977
+ const SETTINGS_STYLE_ID = 'wg-settings-style';
1978
+ const SETTINGS_CSS = `
1979
+ .wg-settings { box-sizing: border-box; width: min(560px, 100%); max-height: 100%; overflow-y: auto;
1980
+ display: grid; gap: var(--wg-gap, 16px); padding: 20px; color: var(--wg-text, #f4f6fb);
1981
+ background: var(--wg-surface, rgb(18 20 28 / 0.92)); border: 1px solid var(--wg-line, rgb(255 255 255 / 0.12));
1982
+ border-radius: var(--wg-radius, 22px); font: 16px/1.4 var(--wg-font-ui, system-ui, sans-serif); }
1983
+ .wg-settings * { box-sizing: border-box; }
1984
+ .wg-settings h2 { margin: 0; font: 600 22px/1.2 var(--wg-font-display, system-ui, sans-serif); }
1985
+ .wg-settings h3 { margin: 4px 0 0; color: var(--wg-muted, #8e97a9); font-size: 13px; font-weight: 600;
1986
+ letter-spacing: 0.08em; text-transform: uppercase; }
1987
+ .wg-settings-list { display: grid; gap: 6px; }
1988
+ .wg-settings-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; width: 100%;
1989
+ min-height: 48px; padding: 8px 14px; border: 1px solid transparent; border-radius: var(--wg-radius-small, 12px);
1990
+ background: rgb(255 255 255 / 0.05); color: inherit; font: inherit; text-align: left; cursor: pointer;
1991
+ transition: transform 120ms var(--wg-ease, ease), box-shadow 120ms var(--wg-ease, ease); }
1992
+ .wg-settings-row:focus { outline: none; }
1993
+ .wg-settings-row.is-focused { box-shadow: var(--wg-focus-ring, 0 0 0 3px #fff); transform: scale(1.01); }
1994
+ .wg-settings-label { display: grid; gap: 2px; min-width: 0; }
1995
+ .wg-settings-note, .wg-settings-desc { color: var(--wg-muted, #8e97a9); font-size: 13px; }
1996
+ .wg-settings-value { flex: none; font-weight: 600; }
1997
+ .wg-settings-value::before { content: '◀ '; opacity: 0.5; }
1998
+ .wg-settings-value::after { content: ' ▶'; opacity: 0.5; }
1999
+ .wg-settings-binding { flex: none; display: flex; gap: 8px; font-weight: 600; }
2000
+ .wg-settings-binding span { min-width: 2.5em; padding: 2px 8px; border-radius: 8px; background: rgb(255 255 255 / 0.08); text-align: center; }
2001
+ .wg-settings-reset { color: var(--wg-danger, #f87171); }
2002
+ .wg-settings-ask { display: grid; gap: 10px; padding: 12px 14px; border-radius: var(--wg-radius-small, 12px); background: rgb(255 255 255 / 0.05); }
2003
+ .wg-settings-ask div { display: flex; gap: 8px; }
2004
+ .wg-settings-ask .wg-settings-row { justify-content: center; }
2005
+ .wg-settings-capture { padding: 10px 14px; border-radius: var(--wg-radius-small, 12px); background: rgb(255 255 255 / 0.08); }
2006
+ .wg-settings-hints { margin: 0; color: var(--wg-muted, #8e97a9); font-size: 13px; }
2007
+ `;
2008
+ /**
2009
+ * The settings screen, following UX.md: one row always focused; `up` / `down` move;
2010
+ * `left` / `right` / `accept` change a value (`accept` on a control row waits for the
2011
+ * new key or button); `more` shows a row's description; `back` closes. A last row
2012
+ * resets to the defaults after asking (No first). A tap on a row acts as `accept`.
2013
+ *
2014
+ * It changes nothing but its own rows: the app applies, saves and, after a reset,
2015
+ * calls `update()`.
2016
+ */
2017
+ export function createSettingsScreen(target, options) {
2018
+ const doc = target.ownerDocument;
2019
+ const locale = options.locale ?? 'en';
2020
+ const capture = options.capture ?? ((input) => captureBinding(input));
2021
+ if (!doc.getElementById(SETTINGS_STYLE_ID)) {
2022
+ const style = doc.createElement('style');
2023
+ style.id = SETTINGS_STYLE_ID;
2024
+ style.textContent = SETTINGS_CSS;
2025
+ doc.head.appendChild(style);
2026
+ }
2027
+ const root = doc.createElement('section');
2028
+ root.className = 'wg-settings';
2029
+ root.setAttribute('role', 'dialog');
2030
+ root.setAttribute('aria-label', uiText('settings.title', locale));
2031
+ target.appendChild(root);
2032
+ let sections = options.sections;
2033
+ let controls = options.controls ?? [];
2034
+ let focusAt = 0;
2035
+ let asking = false;
2036
+ let capturing = false;
2037
+ let details = false;
2038
+ let destroyed = false;
2039
+ let targets = [];
2040
+ const el = (tag, className, text) => {
2041
+ const node = doc.createElement(tag);
2042
+ if (className)
2043
+ node.className = className;
2044
+ if (text !== undefined)
2045
+ node.textContent = text;
2046
+ return node;
2047
+ };
2048
+ const render = () => {
2049
+ const focused = targets[focusAt];
2050
+ const focusKey = focused ? (focused.kind === 'setting' || focused.kind === 'control' ? focused.row.label : focused.kind) : undefined;
2051
+ root.replaceChildren();
2052
+ targets = [];
2053
+ root.append(el('h2', undefined, uiText('settings.title', locale)));
2054
+ const rowButton = (onClick) => {
2055
+ const button = el('button', 'wg-settings-row');
2056
+ button.type = 'button';
2057
+ button.tabIndex = -1;
2058
+ button.addEventListener('click', () => {
2059
+ if (capturing)
2060
+ return;
2061
+ focusAt = targets.findIndex((t) => t.el === button);
2062
+ onClick();
2063
+ });
2064
+ return button;
2065
+ };
2066
+ for (const section of sections) {
2067
+ root.append(el('h3', undefined, section.title));
2068
+ const list = el('div', 'wg-settings-list');
2069
+ for (const row of section.rows) {
2070
+ const button = rowButton(() => change(1));
2071
+ const label = el('span', 'wg-settings-label');
2072
+ label.append(el('span', undefined, row.label));
2073
+ if (!row.live)
2074
+ label.append(el('span', 'wg-settings-note', uiText('settings.restart', locale)));
2075
+ button.append(label, el('span', 'wg-settings-value', row.valueLabel));
2076
+ button.setAttribute('aria-label', `${row.label}: ${row.valueLabel}`);
2077
+ list.append(button);
2078
+ targets.push({ kind: 'setting', row, el: button });
2079
+ if (details && focusKey === row.label && row.description)
2080
+ list.append(el('p', 'wg-settings-desc', row.description));
2081
+ }
2082
+ root.append(list);
2083
+ }
2084
+ if (controls.length > 0) {
2085
+ root.append(el('h3', undefined, uiText('settings.group.controls', locale)));
2086
+ const list = el('div', 'wg-settings-list');
2087
+ for (const row of controls) {
2088
+ const button = rowButton(() => void rebind(row));
2089
+ const binding = el('span', 'wg-settings-binding');
2090
+ binding.append(el('span', undefined, row.keyLabel), el('span', undefined, row.buttonLabel));
2091
+ button.append(el('span', 'wg-settings-label', row.label), binding);
2092
+ list.append(button);
2093
+ targets.push({ kind: 'control', row, el: button });
2094
+ if (capturing && focusKey === row.label)
2095
+ list.append(el('p', 'wg-settings-capture', uiText('controls.capture', locale)));
2096
+ }
2097
+ root.append(list);
2098
+ }
2099
+ const reset = rowButton(() => ask());
2100
+ reset.classList.add('wg-settings-reset');
2101
+ reset.textContent = uiText('settings.reset', locale);
2102
+ root.append(reset);
2103
+ targets.push({ kind: 'reset', el: reset });
2104
+ if (asking) {
2105
+ const box = el('div', 'wg-settings-ask');
2106
+ box.append(el('span', undefined, uiText('settings.resetAsk', locale)));
2107
+ const buttons = el('div');
2108
+ const no = rowButton(() => answer(false));
2109
+ no.textContent = uiText('settings.no', locale);
2110
+ const yes = rowButton(() => answer(true));
2111
+ yes.textContent = uiText('settings.yes', locale);
2112
+ buttons.append(no, yes);
2113
+ box.append(buttons);
2114
+ root.append(box);
2115
+ targets.push({ kind: 'no', el: no }, { kind: 'yes', el: yes });
2116
+ }
2117
+ root.append(el('p', 'wg-settings-hints', uiText('settings.hints', locale)));
2118
+ // Keep the focus on the same row across a repaint.
2119
+ if (focusKey !== undefined) {
2120
+ const again = targets.findIndex((t) => t.kind === 'setting' || t.kind === 'control' ? t.row.label === focusKey : t.kind === focusKey);
2121
+ if (again !== -1)
2122
+ focusAt = again;
2123
+ }
2124
+ focusAt = Math.min(Math.max(0, focusAt), targets.length - 1);
2125
+ paintFocus();
2126
+ };
2127
+ const paintFocus = () => {
2128
+ targets.forEach((t, index) => t.el.classList.toggle('is-focused', index === focusAt));
2129
+ const current = targets[focusAt]?.el;
2130
+ current?.focus({ preventScroll: true });
2131
+ current?.scrollIntoView?.({ block: 'nearest' });
2132
+ };
2133
+ const change = (direction) => {
2134
+ const current = targets[focusAt];
2135
+ if (current?.kind !== 'setting')
2136
+ return;
2137
+ const value = stepSetting(current.row, direction);
2138
+ if (value === current.row.value)
2139
+ return;
2140
+ const row = withSettingValue(current.row, value);
2141
+ sections = sections.map((section) => ({ ...section, rows: section.rows.map((r) => (r.key === row.key ? row : r)) }));
2142
+ render();
2143
+ options.onChange(row.key, value, row);
2144
+ };
2145
+ const rebind = async (row) => {
2146
+ if (capturing)
2147
+ return;
2148
+ capturing = true;
2149
+ render();
2150
+ const binding = await capture(options.input);
2151
+ capturing = false;
2152
+ if (destroyed)
2153
+ return;
2154
+ if (binding) {
2155
+ const bindings = Object.fromEntries(controls.map((c) => [c.id, c.binding]));
2156
+ const next = bindControl(bindings, row.id, binding);
2157
+ controls = controls.map((c) => {
2158
+ const b = next[c.id] ?? {};
2159
+ const none = uiText('controls.none', locale);
2160
+ return {
2161
+ ...c,
2162
+ binding: b,
2163
+ keyLabel: bindingKeyLabel(b) || none,
2164
+ buttonLabel: b.button === undefined ? none : (PAD_BUTTON_NAMES[b.button] ?? `#${b.button}`),
2165
+ };
2166
+ });
2167
+ options.onControl?.(row.id, next[row.id] ?? {}, next);
2168
+ }
2169
+ render();
2170
+ };
2171
+ const ask = () => {
2172
+ asking = true;
2173
+ render();
2174
+ focusAt = targets.findIndex((t) => t.kind === 'no');
2175
+ paintFocus();
2176
+ };
2177
+ const answer = (yes) => {
2178
+ asking = false;
2179
+ render();
2180
+ focusAt = targets.findIndex((t) => t.kind === 'reset');
2181
+ paintFocus();
2182
+ if (yes)
2183
+ options.onReset();
2184
+ };
2185
+ const move = (direction) => {
2186
+ const next = focusAt + direction;
2187
+ if (asking) {
2188
+ const kinds = targets[next]?.kind;
2189
+ if (kinds === 'yes' || kinds === 'no')
2190
+ focusAt = next;
2191
+ }
2192
+ else if (targets[next] && targets[next].kind !== 'yes' && targets[next].kind !== 'no') {
2193
+ focusAt = next;
2194
+ if (details) {
2195
+ details = false;
2196
+ render();
2197
+ return;
2198
+ }
2199
+ }
2200
+ paintFocus();
2201
+ };
2202
+ const off = options.input.on((action) => {
2203
+ if (destroyed || capturing)
2204
+ return;
2205
+ const current = targets[focusAt];
2206
+ switch (action) {
2207
+ case 'up':
2208
+ return move(-1);
2209
+ case 'down':
2210
+ return move(1);
2211
+ case 'left':
2212
+ case 'right':
2213
+ if (asking)
2214
+ return move(action === 'left' ? -1 : 1);
2215
+ return change(action === 'left' ? -1 : 1);
2216
+ case 'accept':
2217
+ return current?.el.click();
2218
+ case 'more':
2219
+ if (current?.kind === 'setting' && current.row.description) {
2220
+ details = !details;
2221
+ render();
2222
+ }
2223
+ return;
2224
+ case 'back':
2225
+ if (asking)
2226
+ return answer(false);
2227
+ if (details) {
2228
+ details = false;
2229
+ return render();
2230
+ }
2231
+ return options.onClose();
2232
+ default:
2233
+ return;
2234
+ }
2235
+ });
2236
+ render();
2237
+ return {
2238
+ element: root,
2239
+ update(nextSections, nextControls) {
2240
+ sections = nextSections;
2241
+ if (nextControls)
2242
+ controls = nextControls;
2243
+ render();
2244
+ },
2245
+ destroy() {
2246
+ destroyed = true;
2247
+ off();
2248
+ root.remove();
2249
+ },
2250
+ };
2251
+ }
2252
+ /** macOS (and iPadOS) or anything else, from the user agent's platform. */
2253
+ export function platformOf(nav = globalThis.navigator) {
2254
+ const name = nav?.userAgentData?.platform || nav?.platform || '';
2255
+ return /mac|iphone|ipad|ipod/i.test(name) ? 'mac' : 'other';
2256
+ }
2257
+ /** The fullscreen key: Cmd+Enter on macOS, Alt+Enter elsewhere (the owner's choice). */
2258
+ export function fullscreenShortcut(platform = platformOf()) {
2259
+ return platform === 'mac' ? { key: 'Enter', meta: true } : { key: 'Enter', alt: true };
2260
+ }
2261
+ /** Select + Y (standard mapping 8 + 3). Select + Start stays the menu. */
2262
+ export const FULLSCREEN_PAD_COMBO = Object.freeze([8, 3]);
2263
+ /** Whether a keydown is `shortcut` (exact modifiers; never inside a text field). */
2264
+ export function isShortcut(event, shortcut) {
2265
+ if (isEditable(event.target ?? null))
2266
+ return false;
2267
+ return (event.key === shortcut.key &&
2268
+ event.altKey === Boolean(shortcut.alt) &&
2269
+ event.metaKey === Boolean(shortcut.meta) &&
2270
+ event.ctrlKey === Boolean(shortcut.ctrl) &&
2271
+ event.shiftKey === Boolean(shortcut.shift));
2272
+ }
2273
+ /**
2274
+ * The fullscreen toggle of an engine app: {@link fullscreenShortcut} on the keyboard
2275
+ * and {@link FULLSCREEN_PAD_COMBO} on any gamepad, in game and in menus. Browsers
2276
+ * allow fullscreen only from a user gesture; a pad press counts in Chromium but not
2277
+ * everywhere, which is why the pause menu has the entry too.
2278
+ */
2279
+ export function createFullscreenToggle(root, options = {}) {
2280
+ const doc = root.ownerDocument;
2281
+ const target = options.target ?? globalThis;
2282
+ const shortcut = options.shortcut ?? fullscreenShortcut();
2283
+ const combo = options.combo ?? FULLSCREEN_PAD_COMBO;
2284
+ const gamepads = options.gamepads ??
2285
+ (() => (globalThis.navigator?.getGamepads?.() ?? []));
2286
+ const schedule = options.schedule === undefined ? (globalThis.requestAnimationFrame?.bind(globalThis) ?? null) : options.schedule;
2287
+ const listeners = new Set();
2288
+ let destroyed = false;
2289
+ let polling = false;
2290
+ let held = false;
2291
+ const active = () => doc.fullscreenElement === root;
2292
+ const toggle = async () => {
2293
+ try {
2294
+ if (active())
2295
+ await doc.exitFullscreen();
2296
+ else
2297
+ await root.requestFullscreen();
2298
+ }
2299
+ catch {
2300
+ // Refused (no user gesture, or not allowed): nothing changes.
2301
+ }
2302
+ };
2303
+ const onKey = (event) => {
2304
+ const key = event;
2305
+ if (destroyed || key.repeat || !isShortcut(key, shortcut))
2306
+ return;
2307
+ key.preventDefault();
2308
+ key.stopPropagation();
2309
+ void toggle();
2310
+ };
2311
+ const onChange = () => {
2312
+ for (const listener of [...listeners])
2313
+ listener(active());
2314
+ };
2315
+ const poll = () => {
2316
+ if (destroyed)
2317
+ return;
2318
+ const down = gamepads().some((pad) => pad && combo.every((index) => pad.buttons[index]?.pressed));
2319
+ if (down && !held)
2320
+ void toggle();
2321
+ held = down;
2322
+ };
2323
+ const loop = () => {
2324
+ if (destroyed || !schedule)
2325
+ return;
2326
+ poll();
2327
+ schedule(loop);
2328
+ };
2329
+ const startPolling = () => {
2330
+ if (polling || !schedule)
2331
+ return;
2332
+ polling = true;
2333
+ schedule(loop);
2334
+ };
2335
+ target.addEventListener('keydown', onKey, { capture: true });
2336
+ target.addEventListener('gamepadconnected', startPolling);
2337
+ doc.addEventListener('fullscreenchange', onChange);
2338
+ if (gamepads().some(Boolean))
2339
+ startPolling();
2340
+ return {
2341
+ toggle,
2342
+ get active() {
2343
+ return active();
2344
+ },
2345
+ onChange(listener) {
2346
+ listeners.add(listener);
2347
+ return () => listeners.delete(listener);
2348
+ },
2349
+ poll,
2350
+ destroy() {
2351
+ destroyed = true;
2352
+ listeners.clear();
2353
+ target.removeEventListener('keydown', onKey, { capture: true });
2354
+ target.removeEventListener('gamepadconnected', startPolling);
2355
+ doc.removeEventListener('fullscreenchange', onChange);
2356
+ },
2357
+ };
2358
+ }
2359
+ /**
2360
+ * The screen kept on while playing: a Wake Lock held while `setActive(true)` and the
2361
+ * page is visible, taken again when it comes back into view (the browser drops it on
2362
+ * hide). Without the API it does nothing.
2363
+ */
2364
+ export function createWakeLock(options = {}) {
2365
+ const api = options.wakeLock ?? globalThis.navigator?.wakeLock;
2366
+ const doc = options.document ?? globalThis.document;
2367
+ let wanted = false;
2368
+ let destroyed = false;
2369
+ let sentinel = null;
2370
+ let pending = false;
2371
+ const visible = () => !doc || doc.visibilityState === 'visible';
2372
+ const acquire = async () => {
2373
+ if (!api || sentinel || pending || !wanted || !visible() || destroyed)
2374
+ return;
2375
+ pending = true;
2376
+ try {
2377
+ const lock = await api.request('screen');
2378
+ sentinel = lock;
2379
+ lock.addEventListener('release', () => {
2380
+ if (sentinel === lock)
2381
+ sentinel = null;
2382
+ });
2383
+ if (!wanted || destroyed)
2384
+ await release();
2385
+ }
2386
+ catch {
2387
+ // Refused (battery saver, not visible): try again on the next chance.
2388
+ }
2389
+ finally {
2390
+ pending = false;
2391
+ }
2392
+ };
2393
+ const release = async () => {
2394
+ const lock = sentinel;
2395
+ sentinel = null;
2396
+ await lock?.release().catch(() => undefined);
2397
+ };
2398
+ const onVisibility = () => {
2399
+ if (visible())
2400
+ void acquire();
2401
+ };
2402
+ doc?.addEventListener('visibilitychange', onVisibility);
2403
+ return {
2404
+ setActive(active) {
2405
+ wanted = active;
2406
+ if (active)
2407
+ void acquire();
2408
+ else
2409
+ void release();
2410
+ },
2411
+ get held() {
2412
+ return sentinel !== null;
2413
+ },
2414
+ destroy() {
2415
+ destroyed = true;
2416
+ wanted = false;
2417
+ doc?.removeEventListener('visibilitychange', onVisibility);
2418
+ void release();
2419
+ },
2420
+ };
2421
+ }
2422
+ /** The stats of frame timestamps (ms, ascending) — usually the last second's. */
2423
+ export function frameStats(times, expectedFps = 60) {
2424
+ if (times.length < 2)
2425
+ return { fps: 0, avg: 0, worst: 0, dropped: 0 };
2426
+ const expected = 1000 / expectedFps;
2427
+ let worst = 0;
2428
+ let dropped = 0;
2429
+ for (let i = 1; i < times.length; i++) {
2430
+ const gap = (times[i] ?? 0) - (times[i - 1] ?? 0);
2431
+ worst = Math.max(worst, gap);
2432
+ if (gap > expected * 1.5)
2433
+ dropped += Math.round(gap / expected) - 1;
2434
+ }
2435
+ const span = (times[times.length - 1] ?? 0) - (times[0] ?? 0);
2436
+ const avg = span / (times.length - 1);
2437
+ return { fps: avg > 0 ? 1000 / avg : 0, avg, worst, dropped };
2438
+ }
2439
+ /**
2440
+ * The "Show performance" overlay: frames per second, frame time (mean and worst over
2441
+ * the last second) and dropped frames, in a corner of `target`.
2442
+ */
2443
+ export function createPerfCounter(target, options = {}) {
2444
+ const doc = target.ownerDocument;
2445
+ const locale = options.locale ?? 'en';
2446
+ const expectedFps = options.expectedFps ?? 60;
2447
+ const now = options.now ?? (() => globalThis.performance?.now() ?? Date.now());
2448
+ const schedule = options.schedule === undefined ? (globalThis.requestAnimationFrame?.bind(globalThis) ?? null) : options.schedule;
2449
+ const box = doc.createElement('div');
2450
+ box.className = 'wg-perf';
2451
+ box.style.cssText =
2452
+ 'position:absolute;top:calc(8px + var(--wg-safe-top, 0px));left:8px;z-index:10;padding:4px 8px;border-radius:8px;' +
2453
+ 'background:rgb(0 0 0 / 0.65);color:#fff;font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;pointer-events:none;white-space:pre';
2454
+ box.hidden = true;
2455
+ target.appendChild(box);
2456
+ let times = [];
2457
+ let fed = false;
2458
+ let lastPaint = 0;
2459
+ let stats = { fps: 0, avg: 0, worst: 0, dropped: 0 };
2460
+ let destroyed = false;
2461
+ let looping = false;
2462
+ const paint = () => {
2463
+ if (box.hidden)
2464
+ return;
2465
+ box.textContent = [
2466
+ uiText('perf.fps', locale, { fps: stats.fps.toFixed(0) }),
2467
+ uiText('perf.frame', locale, { avg: stats.avg.toFixed(1), worst: stats.worst.toFixed(1) }),
2468
+ uiText('perf.dropped', locale, { dropped: stats.dropped }),
2469
+ ].join('\n');
2470
+ };
2471
+ const record = (t) => {
2472
+ times.push(t);
2473
+ const from = t - 1000;
2474
+ let cut = 0;
2475
+ while (cut < times.length && (times[cut] ?? 0) < from)
2476
+ cut++;
2477
+ if (cut > 0)
2478
+ times = times.slice(cut);
2479
+ if (t - lastPaint >= 250) {
2480
+ lastPaint = t;
2481
+ stats = frameStats(times, expectedFps);
2482
+ paint();
2483
+ }
2484
+ };
2485
+ const loop = () => {
2486
+ if (destroyed || box.hidden || !schedule) {
2487
+ looping = false;
2488
+ return;
2489
+ }
2490
+ if (!fed)
2491
+ record(now());
2492
+ schedule(loop);
2493
+ };
2494
+ return {
2495
+ frame() {
2496
+ fed = true;
2497
+ record(now());
2498
+ },
2499
+ show() {
2500
+ box.hidden = false;
2501
+ lastPaint = -Infinity;
2502
+ paint();
2503
+ if (!looping && schedule) {
2504
+ looping = true;
2505
+ schedule(loop);
2506
+ }
2507
+ },
2508
+ hide() {
2509
+ box.hidden = true;
2510
+ },
2511
+ get visible() {
2512
+ return !box.hidden;
2513
+ },
2514
+ get stats() {
2515
+ return stats;
2516
+ },
2517
+ destroy() {
2518
+ destroyed = true;
2519
+ box.remove();
2520
+ },
2521
+ };
2522
+ }
2523
+ /** How many frames are due after `elapsed` ms at `fps`, and the remainder carried to the next call. */
2524
+ export function framesDue(elapsed, fps, carried = 0) {
2525
+ const frame = 1000 / fps;
2526
+ const total = Math.max(0, elapsed) + carried;
2527
+ const frames = Math.floor(total / frame);
2528
+ return { frames, carried: total - frames * frame };
2529
+ }
2530
+ /**
2531
+ * The frame loop of an engine the app drives. `'display'` counts time on the page
2532
+ * clock; `'audio'` on the `AudioContext`'s, so the game runs at `fps` whatever the
2533
+ * screen's refresh rate, and stays in step with its sound.
2534
+ */
2535
+ export function createFrameClock(options = {}) {
2536
+ const fps = options.fps ?? 60;
2537
+ const maxFrames = options.maxFrames ?? 4;
2538
+ const now = options.now ?? (() => globalThis.performance?.now() ?? Date.now());
2539
+ const schedule = options.schedule === undefined ? (globalThis.requestAnimationFrame?.bind(globalThis) ?? null) : options.schedule;
2540
+ let mode = options.mode ?? 'display';
2541
+ let tick = null;
2542
+ let last = null;
2543
+ let carried = 0;
2544
+ let source = mode;
2545
+ const clock = () => {
2546
+ const audio = options.audioContext;
2547
+ if (mode === 'audio' && audio && audio.state === 'running')
2548
+ return { at: audio.currentTime * 1000, source: 'audio' };
2549
+ return { at: now(), source: 'display' };
2550
+ };
2551
+ const step = () => {
2552
+ if (!tick)
2553
+ return;
2554
+ const reading = clock();
2555
+ // A switch of clock (audio started or stopped, or the mode changed) restarts the count.
2556
+ if (last === null || reading.source !== source) {
2557
+ last = reading.at;
2558
+ source = reading.source;
2559
+ carried = 0;
2560
+ tick(0);
2561
+ return;
2562
+ }
2563
+ const due = framesDue(reading.at - last, fps, carried);
2564
+ last = reading.at;
2565
+ if (due.frames > maxFrames) {
2566
+ carried = 0;
2567
+ tick(maxFrames);
2568
+ }
2569
+ else {
2570
+ carried = due.carried;
2571
+ tick(due.frames);
2572
+ }
2573
+ };
2574
+ const loop = () => {
2575
+ if (!tick)
2576
+ return;
2577
+ step();
2578
+ schedule?.(loop);
2579
+ };
2580
+ return {
2581
+ start(next) {
2582
+ const running = tick !== null;
2583
+ tick = next;
2584
+ last = null;
2585
+ if (!running)
2586
+ schedule?.(loop);
2587
+ },
2588
+ stop() {
2589
+ tick = null;
2590
+ },
2591
+ get mode() {
2592
+ return mode;
2593
+ },
2594
+ set mode(value) {
2595
+ mode = value;
2596
+ },
2597
+ step,
2598
+ };
2599
+ }
1546
2600
  //# sourceMappingURL=engine-specs.js.map