@wasm-gaming/blastem-wasm 0.1.3 → 0.2.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.
@@ -379,4 +379,2222 @@ export class EngineSDKBase {
379
379
  return this;
380
380
  }
381
381
  }
382
+ /** Keyboard → action (`KeyboardEvent.key`). */
383
+ export const UI_KEYMAP = Object.freeze({
384
+ ArrowUp: 'up',
385
+ ArrowDown: 'down',
386
+ ArrowLeft: 'left',
387
+ ArrowRight: 'right',
388
+ Enter: 'accept',
389
+ ' ': 'accept',
390
+ Escape: 'back',
391
+ Backspace: 'back',
392
+ Tab: 'more',
393
+ v: 'more',
394
+ V: 'more',
395
+ ContextMenu: 'more',
396
+ q: 'prev',
397
+ Q: 'prev',
398
+ e: 'next',
399
+ E: 'next',
400
+ F1: 'menu',
401
+ });
402
+ /**
403
+ * Gamepad button index (W3C "standard" mapping) → action. A = 0, B = 1, X = 2, Y = 3,
404
+ * LB = 4, RB = 5, Select = 8, Start = 9, d-pad = 12–15. Select + Start together is
405
+ * `menu` as well (see {@link createInput}).
406
+ */
407
+ export const UI_PADMAP = Object.freeze({
408
+ 0: 'accept',
409
+ 1: 'back',
410
+ 2: 'more',
411
+ 3: 'more',
412
+ 4: 'prev',
413
+ 5: 'next',
414
+ 9: 'menu',
415
+ 12: 'up',
416
+ 13: 'down',
417
+ 14: 'left',
418
+ 15: 'right',
419
+ });
420
+ /** Hold-to-repeat for directions: first repeat after `delay` ms, then every `interval` ms. */
421
+ export const UI_REPEAT = Object.freeze({ delay: 380, interval: 110, axis: 0.6 });
422
+ const DIRECTIONS = new Set(['up', 'down', 'left', 'right']);
423
+ const isEditable = (target) => {
424
+ const element = target;
425
+ if (!element)
426
+ return false;
427
+ if (element.isContentEditable)
428
+ return true;
429
+ return element.tagName === 'INPUT' || element.tagName === 'TEXTAREA' || element.tagName === 'SELECT';
430
+ };
431
+ /**
432
+ * The scheme's runtime: keyboard and gamepads become {@link UiAction}s.
433
+ *
434
+ * Keyboard: `keydown` mapped through {@link UI_KEYMAP} (keys typed into form fields
435
+ * are left alone). Gamepads: polled each frame through {@link UI_PADMAP} and the left
436
+ * stick; directions repeat with {@link UI_REPEAT}; Select + Start together is `menu`
437
+ * (and then neither fires on its own). While {@link UiInput.suspend | suspended} (in
438
+ * game) the game gets every input except the menu combo: Select + Start and the
439
+ * `menuKeys` (Escape, F1) still arrive, as `menu`, so the pause menu can always open.
440
+ */
441
+ export function createInput(options = {}) {
442
+ const target = options.target ?? globalThis;
443
+ const capture = options.capture ?? true;
444
+ const swallow = options.swallow ?? true;
445
+ const keymap = options.keymap ?? UI_KEYMAP;
446
+ const menuKeys = new Set(options.menuKeys ?? ['Escape', 'F1']);
447
+ const padmap = options.padmap ?? UI_PADMAP;
448
+ const now = options.now ?? (() => globalThis.performance?.now() ?? Date.now());
449
+ const gamepads = options.gamepads ??
450
+ (() => (globalThis.navigator?.getGamepads?.() ?? []));
451
+ const schedule = options.schedule === undefined
452
+ ? (globalThis.requestAnimationFrame?.bind(globalThis) ?? null)
453
+ : options.schedule;
454
+ const listeners = new Set();
455
+ const suspendListeners = new Set();
456
+ let suspended = false;
457
+ let destroyed = false;
458
+ let polling = false;
459
+ let muted = 0;
460
+ const held = new Map();
461
+ // Slots (positions in getGamepads()) whose Y was pressed as part of Select + Y.
462
+ const comboY = new Set();
463
+ // A snapshot: a listener that subscribes another one (a screen opening the next)
464
+ // must not hand it the same action — a Set also visits entries added while it is
465
+ // being iterated, so one Enter would open a screen and activate its focused item.
466
+ // A listener removed by an earlier one in the same dispatch is skipped.
467
+ const fire = (action, detail) => {
468
+ for (const listener of [...listeners]) {
469
+ if (listeners.has(listener))
470
+ listener(action, detail);
471
+ }
472
+ };
473
+ const onKey = (event) => {
474
+ if (destroyed || muted > 0)
475
+ return;
476
+ const key = event;
477
+ if (suspended) {
478
+ if (!menuKeys.has(key.key) || key.repeat)
479
+ return;
480
+ key.preventDefault();
481
+ key.stopPropagation();
482
+ fire('menu', { source: 'keyboard', repeat: false });
483
+ return;
484
+ }
485
+ if (isEditable(key.target) && key.key !== 'Escape')
486
+ return;
487
+ const action = keymap[key.key];
488
+ if (!action)
489
+ return;
490
+ if (swallow) {
491
+ key.preventDefault();
492
+ key.stopPropagation();
493
+ }
494
+ fire(action, { source: 'keyboard', repeat: key.repeat === true });
495
+ };
496
+ const pressed = (pad, slot) => {
497
+ const actions = new Set();
498
+ if (pad.buttons[3]?.pressed !== true)
499
+ comboY.delete(slot);
500
+ const select = pad.buttons[8]?.pressed === true;
501
+ const start = pad.buttons[9]?.pressed === true;
502
+ if (select && start)
503
+ actions.add('menu');
504
+ pad.buttons.forEach((button, index) => {
505
+ if (!button.pressed)
506
+ return;
507
+ if ((index === 8 || index === 9) && select && start)
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
+ }
515
+ const action = padmap[index];
516
+ if (action)
517
+ actions.add(action);
518
+ });
519
+ const [x = 0, y = 0] = pad.axes;
520
+ if (x < -UI_REPEAT.axis)
521
+ actions.add('left');
522
+ if (x > UI_REPEAT.axis)
523
+ actions.add('right');
524
+ if (y < -UI_REPEAT.axis)
525
+ actions.add('up');
526
+ if (y > UI_REPEAT.axis)
527
+ actions.add('down');
528
+ return actions;
529
+ };
530
+ const poll = () => {
531
+ if (destroyed)
532
+ return;
533
+ const t = now();
534
+ const active = new Set();
535
+ gamepads().forEach((pad, slot) => {
536
+ if (pad)
537
+ for (const action of pressed(pad, slot))
538
+ active.add(action);
539
+ });
540
+ for (const action of active) {
541
+ const state = held.get(action);
542
+ if (!state) {
543
+ held.set(action, { since: t, last: t });
544
+ // In game only the Select + Start combo gets through (plain Start is the game's).
545
+ const combo = action === 'menu' && gamepads().some((p) => p?.buttons[8]?.pressed && p.buttons[9]?.pressed);
546
+ if (muted > 0)
547
+ continue;
548
+ if (!suspended || combo)
549
+ fire(action, { source: 'gamepad', repeat: false });
550
+ }
551
+ else if (DIRECTIONS.has(action) &&
552
+ t - state.since >= UI_REPEAT.delay &&
553
+ t - state.last >= UI_REPEAT.interval) {
554
+ state.last = t;
555
+ if (!suspended && muted === 0)
556
+ fire(action, { source: 'gamepad', repeat: true });
557
+ }
558
+ }
559
+ for (const action of [...held.keys()])
560
+ if (!active.has(action))
561
+ held.delete(action);
562
+ };
563
+ const loop = () => {
564
+ if (destroyed || !schedule)
565
+ return;
566
+ poll();
567
+ schedule(loop);
568
+ };
569
+ const startPolling = () => {
570
+ if (polling || !schedule)
571
+ return;
572
+ polling = true;
573
+ schedule(loop);
574
+ };
575
+ const setSuspended = (value) => {
576
+ if (destroyed || suspended === value)
577
+ return;
578
+ suspended = value;
579
+ for (const listener of [...suspendListeners]) {
580
+ if (suspendListeners.has(listener))
581
+ listener(value);
582
+ }
583
+ };
584
+ target.addEventListener('keydown', onKey, { capture });
585
+ target.addEventListener('gamepadconnected', startPolling);
586
+ if (gamepads().some(Boolean))
587
+ startPolling();
588
+ return {
589
+ on(listener) {
590
+ listeners.add(listener);
591
+ return () => listeners.delete(listener);
592
+ },
593
+ suspend() {
594
+ setSuspended(true);
595
+ },
596
+ resume() {
597
+ setSuspended(false);
598
+ },
599
+ get suspended() {
600
+ return suspended;
601
+ },
602
+ onSuspend(listener) {
603
+ suspendListeners.add(listener);
604
+ return () => suspendListeners.delete(listener);
605
+ },
606
+ trigger(action, detail = { source: 'touch', repeat: false }) {
607
+ if (destroyed || muted > 0)
608
+ return;
609
+ if (suspended && action !== 'menu')
610
+ return;
611
+ fire(action, detail);
612
+ },
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
+ },
624
+ destroy() {
625
+ destroyed = true;
626
+ listeners.clear();
627
+ suspendListeners.clear();
628
+ held.clear();
629
+ target.removeEventListener('keydown', onKey, { capture });
630
+ target.removeEventListener('gamepadconnected', startPolling);
631
+ },
632
+ };
633
+ }
634
+ /**
635
+ * Spatial navigation: the candidate a direction leads to from `from`, or null.
636
+ *
637
+ * Only candidates whose centre lies ahead in that direction count; among them the
638
+ * nearest wins, with sideways distance weighted double so "down" prefers the item
639
+ * straight below over a closer one off to the side.
640
+ */
641
+ export function nextFocus(from, candidates, direction) {
642
+ const centre = (el) => {
643
+ const r = el.getBoundingClientRect();
644
+ return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
645
+ };
646
+ const origin = centre(from);
647
+ let best = null;
648
+ let bestScore = Infinity;
649
+ for (const candidate of candidates) {
650
+ if (candidate === from)
651
+ continue;
652
+ const c = centre(candidate);
653
+ const dx = c.x - origin.x;
654
+ const dy = c.y - origin.y;
655
+ const ahead = direction === 'up' ? -dy : direction === 'down' ? dy : direction === 'left' ? -dx : dx;
656
+ if (ahead <= 0.5)
657
+ continue;
658
+ const side = direction === 'up' || direction === 'down' ? Math.abs(dx) : Math.abs(dy);
659
+ const score = ahead + side * 2;
660
+ if (score < bestScore) {
661
+ bestScore = score;
662
+ best = candidate;
663
+ }
664
+ }
665
+ return best;
666
+ }
667
+ /**
668
+ * The look every menu shares, as CSS custom properties: the focus ring, radii, type
669
+ * faces, colours and spacing. Apps read them with `var(--wg-…)`; {@link uiTokensCss}
670
+ * writes them into a stylesheet.
671
+ */
672
+ export const UI_TOKENS = Object.freeze({
673
+ '--wg-bg': '#07080c',
674
+ '--wg-surface': 'rgb(18 20 28 / 0.78)',
675
+ '--wg-line': 'rgb(255 255 255 / 0.12)',
676
+ '--wg-text': '#f4f6fb',
677
+ '--wg-muted': '#8e97a9',
678
+ '--wg-ok': '#4ade80',
679
+ '--wg-danger': '#f87171',
680
+ '--wg-focus': '#ffffff',
681
+ '--wg-focus-ring': '0 0 0 3px #ffffff',
682
+ '--wg-radius': '22px',
683
+ '--wg-radius-small': '12px',
684
+ '--wg-gap': '16px',
685
+ '--wg-font-display': "'Unbounded Variable', 'Unbounded', system-ui, sans-serif",
686
+ '--wg-font-ui': "'Inter Variable', 'Inter', system-ui, -apple-system, 'Segoe UI', sans-serif",
687
+ '--wg-ease': 'cubic-bezier(0.2, 0.8, 0.2, 1)',
688
+ '--wg-safe-top': 'env(safe-area-inset-top, 0px)',
689
+ '--wg-safe-bottom': 'env(safe-area-inset-bottom, 0px)',
690
+ });
691
+ /** `UI_TOKENS` as a CSS rule, e.g. for a `<style>` an app injects. */
692
+ export function uiTokensCss(selector = ':root') {
693
+ const body = Object.entries(UI_TOKENS)
694
+ .map(([name, value]) => ` ${name}: ${value};`)
695
+ .join('\n');
696
+ return `${selector} {\n${body}\n}\n`;
697
+ }
698
+ /** Standard-mapping indices the pad uses. */
699
+ const PAD = Object.freeze({ up: 12, down: 13, left: 14, right: 15 });
700
+ const PAD_BUTTONS = 17;
701
+ const PAD_AXES = 4;
702
+ /**
703
+ * One layout per system. Each label presses the standard button that the system's
704
+ * emulator binds to that console button by default, so no emulator is reconfigured:
705
+ *
706
+ * - Mega Drive (BlastEm `default.cfg`): A=0, B=1, C=5 (right shoulder), X=2, Y=3,
707
+ * Z=4 (left shoulder), Mode=8, Start=9. Six buttons: the launcher plugs 6-button
708
+ * pads, and a 3-button game ignores X Y Z.
709
+ * - Neo Geo (FBNeo: "fire N" is joystick button N-1): A=0, B=1, C=2, D=3 — drawn
710
+ * as the Neo Geo CD pad's diamond (A bottom, B right, C left, D top), which is
711
+ * where those indices sit on a standard pad.
712
+ * - SNES (snes9x, by position): B=0, A=1, Y=2, X=3, L=4, R=5.
713
+ * - GBA / GBC / GB (mGBA): A=0, B=1, L=4, R=5.
714
+ *
715
+ * Everywhere Select = 8 and Start = 9.
716
+ */
717
+ export const TOUCH_LAYOUTS = Object.freeze({
718
+ megadrive: {
719
+ system: 'megadrive',
720
+ title: 'Mega Drive',
721
+ aspect: 4 / 3,
722
+ faces: [
723
+ { label: 'X', index: 2, x: 0.18, y: 0.32, size: 0.25 },
724
+ { label: 'Y', index: 3, x: 0.5, y: 0.26, size: 0.25 },
725
+ { label: 'Z', index: 4, x: 0.82, y: 0.2, size: 0.25 },
726
+ { label: 'A', index: 0, x: 0.18, y: 0.7, size: 0.3 },
727
+ { label: 'B', index: 1, x: 0.5, y: 0.64, size: 0.3 },
728
+ { label: 'C', index: 5, x: 0.82, y: 0.58, size: 0.3 },
729
+ ],
730
+ start: { label: 'Start', index: 9 },
731
+ },
732
+ neogeo: {
733
+ system: 'neogeo',
734
+ title: 'Neo Geo',
735
+ aspect: 4 / 3,
736
+ faces: [
737
+ // The Neo Geo CD pad's diamond: D top, C left, B right, A bottom.
738
+ { label: 'D', index: 3, x: 0.5, y: 0.18, size: 0.32, color: '#3b82f6' },
739
+ { label: 'C', index: 2, x: 0.18, y: 0.5, size: 0.32, color: '#22c55e' },
740
+ { label: 'B', index: 1, x: 0.82, y: 0.5, size: 0.32, color: '#facc15' },
741
+ { label: 'A', index: 0, x: 0.5, y: 0.82, size: 0.32, color: '#ef4444' },
742
+ ],
743
+ select: { label: 'Select', index: 8 },
744
+ start: { label: 'Start', index: 9 },
745
+ },
746
+ snes: {
747
+ system: 'snes',
748
+ title: 'Super Nintendo',
749
+ aspect: 4 / 3,
750
+ faces: [
751
+ { label: 'X', index: 3, x: 0.5, y: 0.18, size: 0.32, color: '#3b82f6' },
752
+ { label: 'Y', index: 2, x: 0.18, y: 0.5, size: 0.32, color: '#22c55e' },
753
+ { label: 'A', index: 1, x: 0.82, y: 0.5, size: 0.32, color: '#ef4444' },
754
+ { label: 'B', index: 0, x: 0.5, y: 0.82, size: 0.32, color: '#facc15' },
755
+ ],
756
+ l: { label: 'L', index: 4 },
757
+ r: { label: 'R', index: 5 },
758
+ select: { label: 'Select', index: 8 },
759
+ start: { label: 'Start', index: 9 },
760
+ },
761
+ gba: {
762
+ system: 'gba',
763
+ title: 'Game Boy Advance',
764
+ aspect: 3 / 2,
765
+ faces: [
766
+ { label: 'B', index: 1, x: 0.28, y: 0.64, size: 0.38 },
767
+ { label: 'A', index: 0, x: 0.72, y: 0.4, size: 0.38 },
768
+ ],
769
+ l: { label: 'L', index: 4 },
770
+ r: { label: 'R', index: 5 },
771
+ select: { label: 'Select', index: 8 },
772
+ start: { label: 'Start', index: 9 },
773
+ },
774
+ gbc: {
775
+ system: 'gbc',
776
+ title: 'Game Boy Color',
777
+ aspect: 10 / 9,
778
+ faces: [
779
+ { label: 'B', index: 1, x: 0.28, y: 0.64, size: 0.38 },
780
+ { label: 'A', index: 0, x: 0.72, y: 0.4, size: 0.38 },
781
+ ],
782
+ select: { label: 'Select', index: 8 },
783
+ start: { label: 'Start', index: 9 },
784
+ },
785
+ gb: {
786
+ system: 'gb',
787
+ title: 'Game Boy',
788
+ aspect: 10 / 9,
789
+ faces: [
790
+ { label: 'B', index: 1, x: 0.28, y: 0.64, size: 0.38 },
791
+ { label: 'A', index: 0, x: 0.72, y: 0.4, size: 0.38 },
792
+ ],
793
+ select: { label: 'Select', index: 8 },
794
+ start: { label: 'Start', index: 9 },
795
+ },
796
+ });
797
+ /** Smallest touch target (UX.md rule 8). */
798
+ const TOUCH_MIN = 48;
799
+ /** The d-pad is drawn at this fraction of its slot, centred; the buttons fill theirs. */
800
+ const DPAD_SCALE = 0.8;
801
+ /** A square of `fraction` of `slot`'s side, centred in it. */
802
+ const shrink = (slot, fraction) => {
803
+ const side = Math.round(slot.width * fraction);
804
+ return rect(slot.x + (slot.width - side) / 2, slot.y + (slot.height - side) / 2, side, side);
805
+ };
806
+ const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
807
+ const rect = (x, y, width, height) => ({
808
+ x: Math.round(x),
809
+ y: Math.round(y),
810
+ width: Math.round(width),
811
+ height: Math.round(height),
812
+ });
813
+ /**
814
+ * Lays a pad out. **Portrait**: the pad takes the bottom half — shoulders and the
815
+ * pause button along its top, the d-pad left, the buttons right, Select / Start
816
+ * along its bottom — and the game gets the top half. **Landscape**: the game is
817
+ * centred and the controls sit on its sides — L and the d-pad and Select on the
818
+ * left; pause, R, the buttons and Start on the right. When sides wide enough would
819
+ * shrink the game below `minGameScale` of the screen's height (a 4:3 tablet), the
820
+ * game keeps the whole screen and the controls overlay its edges.
821
+ */
822
+ export function placeTouchPad(layout, viewport, options = {}) {
823
+ const scale = clamp(options.scale ?? 1, 0.75, 1.4);
824
+ const minGameScale = options.minGameScale ?? 0.7;
825
+ const { width: W, height: H } = viewport;
826
+ const safe = viewport.safe ?? { top: 0, right: 0, bottom: 0, left: 0 };
827
+ const faces = (cluster) => layout.faces.map((face) => ({
828
+ label: face.label,
829
+ index: face.index,
830
+ cx: Math.round(cluster.x + face.x * cluster.width),
831
+ cy: Math.round(cluster.y + face.y * cluster.height),
832
+ r: Math.round((face.size * cluster.width) / 2),
833
+ ...(face.color ? { color: face.color } : {}),
834
+ }));
835
+ const key = (id, spec, at) => (spec ? [{ id, label: spec.label, index: spec.index, rect: at }] : []);
836
+ if (H >= W) {
837
+ // ---- portrait: the bottom half
838
+ const half = Math.round(H / 2);
839
+ const zone = rect(0, half, W, H - half);
840
+ const inner = rect(safe.left, half, W - safe.left - safe.right, H - half - safe.bottom);
841
+ const m = Math.round(clamp(inner.width * 0.04, 10, 24));
842
+ const rowH = TOUCH_MIN;
843
+ const top = inner.y + m;
844
+ const bottom = inner.y + inner.height - m - rowH;
845
+ const middleTop = top + rowH + Math.round(m / 2);
846
+ const middleH = bottom - Math.round(m / 2) - middleTop;
847
+ // The d-pad and the cluster are squares of the same side: as big as the half
848
+ // allows, capped for tablets, then scaled — never beyond the room there is.
849
+ const side = Math.round(Math.min(middleH, inner.width * 0.47, Math.min(middleH, inner.width * 0.44, 240) * scale));
850
+ const dpad = shrink(rect(inner.x + m, middleTop + (middleH - side) / 2, side, side), DPAD_SCALE);
851
+ const cluster = rect(inner.x + inner.width - m - side, middleTop + (middleH - side) / 2, side, side);
852
+ const shoulderW = clamp(inner.width * 0.28, 88, 160);
853
+ const pillW = clamp(inner.width * 0.2, 72, 112);
854
+ const pauseW = 56;
855
+ const centre = inner.x + inner.width / 2;
856
+ return {
857
+ orientation: 'portrait',
858
+ overlay: false,
859
+ gameArea: rect(safe.left, safe.top, W - safe.left - safe.right, half - safe.top),
860
+ zones: [zone],
861
+ dpad,
862
+ cluster,
863
+ faces: faces(cluster),
864
+ keys: [
865
+ ...key('l', layout.l, rect(inner.x + m, top, shoulderW, rowH)),
866
+ ...key('r', layout.r, rect(inner.x + inner.width - m - shoulderW, top, shoulderW, rowH)),
867
+ { id: 'pause', label: 'Pause', index: null, rect: rect(centre - pauseW / 2, top, pauseW, rowH) },
868
+ ...key('select', layout.select, rect(centre - 8 - pillW, bottom, pillW, rowH)),
869
+ ...key('start', layout.start, rect(layout.select ? centre + 8 : centre - pillW / 2, bottom, pillW, rowH)),
870
+ ],
871
+ };
872
+ }
873
+ // ---- landscape: the sides
874
+ const fullH = H - safe.top - safe.bottom;
875
+ const usableW = W - safe.left - safe.right;
876
+ const m = Math.round(clamp(fullH * 0.035, 8, 20));
877
+ const rowH = TOUCH_MIN;
878
+ const control = Math.round(clamp(Math.min(fullH * 0.42, 200), 112, 200) * scale);
879
+ const sideNeeded = control + 2 * m;
880
+ const gameWFull = Math.min(usableW, fullH * layout.aspect);
881
+ let gameW = gameWFull;
882
+ let overlay = false;
883
+ if ((usableW - gameWFull) / 2 < sideNeeded) {
884
+ const shrunkW = usableW - 2 * sideNeeded;
885
+ const shrunkScale = shrunkW / layout.aspect / fullH;
886
+ if (shrunkScale >= minGameScale)
887
+ gameW = shrunkW;
888
+ else
889
+ overlay = true;
890
+ }
891
+ const sideW = overlay ? sideNeeded : (usableW - gameW) / 2;
892
+ const gameH = overlay ? fullH : Math.min(fullH, gameW / layout.aspect);
893
+ const gameArea = overlay
894
+ ? rect(safe.left, safe.top, usableW, fullH)
895
+ : rect(safe.left + sideW, safe.top + (fullH - gameH) / 2, gameW, gameH);
896
+ const leftX = safe.left;
897
+ const rightX = W - safe.right - sideW;
898
+ const top = safe.top + m;
899
+ const bottom = H - safe.bottom - m - rowH;
900
+ // The top row always exists — it holds the pause button, and the shoulders when
901
+ // the console has them.
902
+ const middleTop = top + rowH + m;
903
+ const middleH = bottom - m - middleTop;
904
+ const side = Math.round(Math.min(control, middleH, sideW - 2 * m));
905
+ const dpad = shrink(rect(leftX + (sideW - side) / 2, middleTop + (middleH - side) / 2, side, side), DPAD_SCALE);
906
+ const cluster = rect(rightX + (sideW - side) / 2, middleTop + (middleH - side) / 2, side, side);
907
+ const pauseW = 48;
908
+ const shoulderW = clamp(sideW - 2 * m - (pauseW + m), 64, 140);
909
+ const pillW = clamp(sideW * 0.5, 72, 112);
910
+ return {
911
+ orientation: 'landscape',
912
+ overlay,
913
+ gameArea,
914
+ zones: [rect(0, 0, leftX + sideW, H), rect(rightX, 0, W - rightX, H)],
915
+ dpad,
916
+ cluster,
917
+ faces: faces(cluster),
918
+ keys: [
919
+ ...key('l', layout.l, rect(leftX + m, top, shoulderW, rowH)),
920
+ ...key('r', layout.r, rect(rightX + m, top, shoulderW, rowH)),
921
+ { id: 'pause', label: 'Pause', index: null, rect: rect(rightX + sideW - m - pauseW, top, pauseW, rowH) },
922
+ ...key('select', layout.select, rect(leftX + (sideW - pillW) / 2, bottom, pillW, rowH)),
923
+ ...key('start', layout.start, rect(rightX + (sideW - pillW) / 2, bottom, pillW, rowH)),
924
+ ],
925
+ };
926
+ }
927
+ /** The pad's `Gamepad.id`. */
928
+ export const TOUCH_PAD_ID = 'wasm-gaming touch pad (STANDARD GAMEPAD)';
929
+ /** A finger landing this close to a key (px) still takes it. */
930
+ const KEY_SLOP = 8;
931
+ /** Standard d-pad indices for a point, from its angle around the d-pad's centre. */
932
+ export function touchDpadAt(dpad, x, y) {
933
+ const dx = x - (dpad.x + dpad.width / 2);
934
+ const dy = y - (dpad.y + dpad.height / 2);
935
+ // A dead zone in the middle: resting the thumb on the hub presses nothing.
936
+ if (Math.hypot(dx, dy) < dpad.width * 0.11)
937
+ return [];
938
+ // Eight sectors of 45°, the cardinal ones centred on their axis.
939
+ const sector = (Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) + 8) % 8;
940
+ return [
941
+ [PAD.right],
942
+ [PAD.right, PAD.down],
943
+ [PAD.down],
944
+ [PAD.down, PAD.left],
945
+ [PAD.left],
946
+ [PAD.left, PAD.up],
947
+ [PAD.up],
948
+ [PAD.up, PAD.right],
949
+ ][sector];
950
+ }
951
+ /**
952
+ * Face buttons under a point. Each takes a circle a little larger than it is drawn
953
+ * (never under the 48 px minimum), so the gap between two neighbours presses both —
954
+ * the arcade "roll" — and a thumb slides from one to the next without lifting.
955
+ */
956
+ export function touchFacesAt(placement, x, y) {
957
+ const out = [];
958
+ for (const face of placement.faces) {
959
+ const reach = Math.max(face.r * 1.18, TOUCH_MIN / 2);
960
+ if (Math.hypot(x - face.cx, y - face.cy) <= reach)
961
+ out.push(face.index);
962
+ }
963
+ return out;
964
+ }
965
+ const inside = (r, x, y, slop = 0) => x >= r.x - slop && x <= r.x + r.width + slop && y >= r.y - slop && y <= r.y + r.height + slop;
966
+ const grow = (r, by) => ({
967
+ x: r.x - r.width * by,
968
+ y: r.y - r.height * by,
969
+ width: r.width * (1 + 2 * by),
970
+ height: r.height * (1 + 2 * by),
971
+ });
972
+ export function createTouchPadCore(options = {}) {
973
+ const now = options.now ?? (() => globalThis.performance?.now() ?? Date.now());
974
+ const minHold = options.minHold ?? 50;
975
+ const gamepad = {
976
+ id: TOUCH_PAD_ID,
977
+ index: 0,
978
+ connected: false,
979
+ mapping: 'standard',
980
+ timestamp: 0,
981
+ buttons: Array.from({ length: PAD_BUTTONS }, () => ({ pressed: false, touched: false, value: 0 })),
982
+ axes: Array.from({ length: PAD_AXES }, () => 0),
983
+ vibrationActuator: null,
984
+ };
985
+ let placement = null;
986
+ const fingers = new Map();
987
+ /** When each pressed index went down. */
988
+ const since = new Map();
989
+ /** Latched: released early, held until then. */
990
+ const latched = new Map();
991
+ const changeListeners = new Set();
992
+ const pauseListeners = new Set();
993
+ const live = () => {
994
+ const set = new Set();
995
+ for (const finger of fingers.values())
996
+ for (const index of finger.indices)
997
+ set.add(index);
998
+ return set;
999
+ };
1000
+ const sync = () => {
1001
+ const t = now();
1002
+ const held = live();
1003
+ for (const [index, until] of [...latched])
1004
+ if (until <= t || held.has(index))
1005
+ latched.delete(index);
1006
+ for (const index of [...since.keys()]) {
1007
+ if (held.has(index))
1008
+ continue;
1009
+ const start = since.get(index) ?? t;
1010
+ if (t < start + minHold)
1011
+ latched.set(index, start + minHold);
1012
+ since.delete(index);
1013
+ }
1014
+ const effective = new Set([...held, ...latched.keys()]);
1015
+ const wentDown = [];
1016
+ let changed = false;
1017
+ gamepad.buttons.forEach((button, index) => {
1018
+ const on = effective.has(index);
1019
+ if (on === button.pressed)
1020
+ return;
1021
+ changed = true;
1022
+ button.pressed = on;
1023
+ button.touched = on;
1024
+ button.value = on ? 1 : 0;
1025
+ if (on)
1026
+ wentDown.push(index);
1027
+ });
1028
+ for (const index of held)
1029
+ if (!since.has(index))
1030
+ since.set(index, t);
1031
+ if (!changed)
1032
+ return;
1033
+ gamepad.timestamp = t;
1034
+ for (const listener of [...changeListeners])
1035
+ listener(wentDown);
1036
+ };
1037
+ const indicesFor = (control, x, y) => {
1038
+ if (!placement)
1039
+ return [];
1040
+ if (control === 'dpad')
1041
+ return touchDpadAt(placement.dpad, x, y);
1042
+ if (control === 'cluster')
1043
+ return touchFacesAt(placement, x, y);
1044
+ const key = placement.keys.find((k) => k.id === control);
1045
+ if (!key || key.index === null)
1046
+ return [];
1047
+ return inside(key.rect, x, y, KEY_SLOP) ? [key.index] : [];
1048
+ };
1049
+ const controlAt = (x, y) => {
1050
+ if (!placement)
1051
+ return null;
1052
+ for (const key of placement.keys)
1053
+ if (inside(key.rect, x, y, KEY_SLOP))
1054
+ return key.id;
1055
+ const { dpad, cluster } = placement;
1056
+ const nearDpad = inside(grow(dpad, 0.2), x, y);
1057
+ const nearCluster = inside(grow(cluster, 0.12), x, y) || touchFacesAt(placement, x, y).length > 0;
1058
+ if (nearDpad && nearCluster) {
1059
+ // On a narrow phone the two margins meet: the nearer one, by its own size.
1060
+ const reach = (r) => Math.hypot(x - (r.x + r.width / 2), y - (r.y + r.height / 2)) / (r.width / 2);
1061
+ return reach(dpad) <= reach(cluster) ? 'dpad' : 'cluster';
1062
+ }
1063
+ if (nearDpad)
1064
+ return 'dpad';
1065
+ if (nearCluster)
1066
+ return 'cluster';
1067
+ return null;
1068
+ };
1069
+ return {
1070
+ gamepad,
1071
+ get placement() {
1072
+ return placement;
1073
+ },
1074
+ place(next) {
1075
+ placement = next;
1076
+ // A new geometry is a clean slate: nothing latched survives it.
1077
+ fingers.clear();
1078
+ latched.clear();
1079
+ since.clear();
1080
+ sync();
1081
+ },
1082
+ down(pointerId, x, y) {
1083
+ const control = controlAt(x, y);
1084
+ if (!control)
1085
+ return null;
1086
+ fingers.set(pointerId, { control, indices: indicesFor(control, x, y) });
1087
+ if (control === 'pause')
1088
+ for (const listener of [...pauseListeners])
1089
+ listener();
1090
+ sync();
1091
+ return control;
1092
+ },
1093
+ move(pointerId, x, y) {
1094
+ const finger = fingers.get(pointerId);
1095
+ if (!finger || finger.control === 'pause')
1096
+ return;
1097
+ finger.indices = indicesFor(finger.control, x, y);
1098
+ sync();
1099
+ },
1100
+ up(pointerId) {
1101
+ if (!fingers.delete(pointerId))
1102
+ return;
1103
+ sync();
1104
+ },
1105
+ releaseAll() {
1106
+ fingers.clear();
1107
+ latched.clear();
1108
+ since.clear();
1109
+ sync();
1110
+ },
1111
+ pressed() {
1112
+ const set = new Set();
1113
+ gamepad.buttons.forEach((button, index) => button.pressed && set.add(index));
1114
+ return set;
1115
+ },
1116
+ get deadline() {
1117
+ return latched.size ? Math.min(...latched.values()) : null;
1118
+ },
1119
+ tick: sync,
1120
+ onChange(listener) {
1121
+ changeListeners.add(listener);
1122
+ return () => changeListeners.delete(listener);
1123
+ },
1124
+ onPause(listener) {
1125
+ pauseListeners.add(listener);
1126
+ return () => pauseListeners.delete(listener);
1127
+ },
1128
+ };
1129
+ }
1130
+ /**
1131
+ * Puts the pad in `navigator.getGamepads()`, at the first index no physical pad
1132
+ * holds (index 0 when there is none — snes9x and mGBA read only that one), and
1133
+ * announces it with `gamepadconnected`. Install it **before** the engine starts, so
1134
+ * SDL's start-up enumeration finds it. If a physical pad later takes its index, the
1135
+ * pad moves to the next free one (disconnected, then connected again).
1136
+ *
1137
+ * The events are plain `Event`s carrying a `gamepad` property — a `GamepadEvent`
1138
+ * cannot be built around an object that is not a real `Gamepad` — which is the shape
1139
+ * Emscripten's handler and `createInput()` read. Returns `release()`, which restores
1140
+ * `getGamepads` and announces the pad gone.
1141
+ */
1142
+ export function exposeAsGamepad(source, options = {}) {
1143
+ const pad = 'gamepad' in source ? source.gamepad : source;
1144
+ const nav = (options.navigator ?? globalThis.navigator);
1145
+ const target = options.target ?? globalThis;
1146
+ if (!nav)
1147
+ return () => { };
1148
+ const own = Object.getOwnPropertyDescriptor(nav, 'getGamepads');
1149
+ const original = nav.getGamepads ? nav.getGamepads.bind(nav) : () => [];
1150
+ const announce = (type) => {
1151
+ const event = new Event(type);
1152
+ Object.defineProperty(event, 'gamepad', { value: pad, enumerable: true });
1153
+ target.dispatchEvent(event);
1154
+ };
1155
+ const physical = () => Array.from(original() ?? [], (entry) => (entry === pad ? null : entry ?? null));
1156
+ const freeIndex = (pads) => {
1157
+ let index = 0;
1158
+ while (pads[index])
1159
+ index++;
1160
+ return index;
1161
+ };
1162
+ let moving = false;
1163
+ const wrapped = () => {
1164
+ const pads = physical();
1165
+ if (pads[pad.index] && !moving) {
1166
+ // A physical pad took our slot. Move, announcing outside the caller's poll.
1167
+ moving = true;
1168
+ queueMicrotask(() => {
1169
+ announce('gamepaddisconnected');
1170
+ pad.index = freeIndex(physical());
1171
+ moving = false;
1172
+ announce('gamepadconnected');
1173
+ });
1174
+ }
1175
+ const out = pads.slice();
1176
+ if (!moving) {
1177
+ while (out.length <= pad.index)
1178
+ out.push(null);
1179
+ out[pad.index] = pad;
1180
+ }
1181
+ return out;
1182
+ };
1183
+ pad.index = freeIndex(physical());
1184
+ pad.connected = true;
1185
+ Object.defineProperty(nav, 'getGamepads', { value: wrapped, configurable: true, writable: true });
1186
+ announce('gamepadconnected');
1187
+ let released = false;
1188
+ return () => {
1189
+ if (released)
1190
+ return;
1191
+ released = true;
1192
+ if (own)
1193
+ Object.defineProperty(nav, 'getGamepads', own);
1194
+ else
1195
+ delete nav.getGamepads;
1196
+ pad.connected = false;
1197
+ announce('gamepaddisconnected');
1198
+ };
1199
+ }
1200
+ const TOUCH_STYLE_ID = 'wg-touch-pad-style';
1201
+ const TOUCH_CSS = `
1202
+ .wg-tp { position: fixed; inset: 0; z-index: 9000; pointer-events: none; display: none;
1203
+ -webkit-user-select: none; user-select: none; -webkit-touch-callout: none;
1204
+ font-family: var(--wg-font-ui, system-ui, sans-serif); color: #fff; }
1205
+ .wg-tp.is-visible { display: block; }
1206
+ .wg-tp-zone { position: absolute; pointer-events: auto; touch-action: none; overscroll-behavior: none;
1207
+ -webkit-tap-highlight-color: transparent; }
1208
+ .wg-tp-art { position: absolute; inset: 0; opacity: var(--wg-tp-opacity, 0.6); }
1209
+ .wg-tp.is-overlay .wg-tp-art { opacity: calc(var(--wg-tp-opacity, 0.6) * 0.75); }
1210
+ .wg-tp-face, .wg-tp-key, .wg-tp-arm, .wg-tp-hub { position: absolute; box-sizing: border-box;
1211
+ background: rgb(255 255 255 / 0.12); border: 1.5px solid rgb(255 255 255 / 0.55);
1212
+ display: grid; place-items: center; font-weight: 700; letter-spacing: 0.02em;
1213
+ text-shadow: 0 1px 2px rgb(0 0 0 / 0.6); }
1214
+ .wg-tp-face { border-radius: 50%; --c: #ffffff; border-color: color-mix(in srgb, var(--c) 70%, white);
1215
+ background: color-mix(in srgb, var(--c) 22%, transparent); }
1216
+ .wg-tp-key { border-radius: 999px; font-size: 13px; font-weight: 600; }
1217
+ .wg-tp-key.is-shoulder { border-radius: 14px; font-size: 16px; font-weight: 700; }
1218
+ .wg-tp-key.is-pause::before, .wg-tp-key.is-pause::after { content: ''; position: absolute; top: 34%; bottom: 34%;
1219
+ width: 4px; border-radius: 2px; background: currentColor; }
1220
+ .wg-tp-key.is-pause::before { left: calc(50% - 7px); }
1221
+ .wg-tp-key.is-pause::after { right: calc(50% - 7px); }
1222
+ .wg-tp-arm { border-radius: 6px; }
1223
+ .wg-tp-hub { border-radius: 4px; border-width: 0; background: rgb(255 255 255 / 0.12); }
1224
+ .wg-tp .is-on { background: rgb(255 255 255 / 0.55); transform: scale(0.96); color: #0b0d12; text-shadow: none; }
1225
+ .wg-tp-face.is-on { background: color-mix(in srgb, var(--c) 70%, white); }
1226
+ `;
1227
+ /**
1228
+ * The touch pad: draws {@link TOUCH_LAYOUTS | a console's pad} over `target`'s
1229
+ * viewport and turns fingers into a {@link VirtualGamepad}. Pair it with
1230
+ * {@link exposeAsGamepad} (the engines) and {@link connectTouchPad} (the shared
1231
+ * input). Pointer Events, any number of fingers; a finger keeps the control it
1232
+ * landed on — it slides around the d-pad, or across the buttons — and every finger
1233
+ * is let go on blur, on a hidden page, and when the pad hides: never a stuck button.
1234
+ */
1235
+ export function createTouchPad(target, options) {
1236
+ const doc = target.ownerDocument;
1237
+ const win = doc.defaultView ?? globalThis;
1238
+ const resolve = (layout) => typeof layout === 'string' ? TOUCH_LAYOUTS[layout] : layout;
1239
+ let layout = resolve(options.layout);
1240
+ const haptics = options.haptics ?? true;
1241
+ const mode = options.mode ?? 'auto';
1242
+ const placeOptions = {
1243
+ ...(options.scale !== undefined ? { scale: options.scale } : {}),
1244
+ ...(options.minGameScale !== undefined ? { minGameScale: options.minGameScale } : {}),
1245
+ };
1246
+ const core = createTouchPadCore(options.minHold !== undefined ? { minHold: options.minHold } : {});
1247
+ if (!doc.getElementById(TOUCH_STYLE_ID)) {
1248
+ const style = doc.createElement('style');
1249
+ style.id = TOUCH_STYLE_ID;
1250
+ style.textContent = TOUCH_CSS;
1251
+ doc.head.appendChild(style);
1252
+ }
1253
+ const root = doc.createElement('div');
1254
+ root.className = 'wg-tp';
1255
+ root.style.setProperty('--wg-tp-opacity', String(clamp(options.opacity ?? 0.6, 0.2, 1)));
1256
+ const art = doc.createElement('div');
1257
+ art.className = 'wg-tp-art';
1258
+ // Reads `env(safe-area-inset-*)` back as pixels.
1259
+ const probe = doc.createElement('div');
1260
+ probe.style.cssText =
1261
+ 'position:fixed;inset:0;visibility:hidden;pointer-events:none;' +
1262
+ 'padding:env(safe-area-inset-top,0px) env(safe-area-inset-right,0px) env(safe-area-inset-bottom,0px) env(safe-area-inset-left,0px)';
1263
+ root.append(art, probe);
1264
+ target.appendChild(root);
1265
+ let shown = options.shown ?? false;
1266
+ let active = mode === 'always' || (win.matchMedia?.('(pointer: coarse)').matches ?? false);
1267
+ let destroyed = false;
1268
+ let zones = [];
1269
+ let arms = null;
1270
+ const parts = new Map();
1271
+ const layoutListeners = new Set();
1272
+ let timer = null;
1273
+ const visible = () => shown && active && !destroyed;
1274
+ const viewport = () => {
1275
+ const css = win.getComputedStyle(probe);
1276
+ const px = (value) => Number.parseFloat(value) || 0;
1277
+ return {
1278
+ width: win.innerWidth,
1279
+ height: win.innerHeight,
1280
+ safe: { top: px(css.paddingTop), right: px(css.paddingRight), bottom: px(css.paddingBottom), left: px(css.paddingLeft) },
1281
+ };
1282
+ };
1283
+ const gameArea = () => core.placement?.gameArea ?? { x: 0, y: 0, width: win.innerWidth, height: win.innerHeight };
1284
+ const box = (el, r) => {
1285
+ el.style.left = `${r.x}px`;
1286
+ el.style.top = `${r.y}px`;
1287
+ el.style.width = `${r.width}px`;
1288
+ el.style.height = `${r.height}px`;
1289
+ };
1290
+ const register = (index, el) => {
1291
+ parts.set(index, [...(parts.get(index) ?? []), el]);
1292
+ };
1293
+ const paint = () => {
1294
+ const on = core.pressed();
1295
+ for (const [index, els] of parts)
1296
+ for (const el of els)
1297
+ el.classList.toggle('is-on', on.has(index));
1298
+ if (arms) {
1299
+ arms.up.classList.toggle('is-on', on.has(PAD.up));
1300
+ arms.down.classList.toggle('is-on', on.has(PAD.down));
1301
+ arms.left.classList.toggle('is-on', on.has(PAD.left));
1302
+ arms.right.classList.toggle('is-on', on.has(PAD.right));
1303
+ }
1304
+ };
1305
+ const build = (placement) => {
1306
+ for (const zone of zones)
1307
+ zone.remove();
1308
+ art.replaceChildren();
1309
+ parts.clear();
1310
+ root.classList.toggle('is-overlay', placement.overlay);
1311
+ // The d-pad: a cross of four arms around a hub.
1312
+ const d = placement.dpad;
1313
+ const third = d.width / 3;
1314
+ const arm = (dir, x, y) => {
1315
+ const el = doc.createElement('div');
1316
+ el.className = 'wg-tp-arm';
1317
+ box(el, rect(d.x + x * third, d.y + y * third, third, third));
1318
+ art.appendChild(el);
1319
+ return el;
1320
+ };
1321
+ arms = { up: arm('up', 1, 0), left: arm('left', 0, 1), right: arm('right', 2, 1), down: arm('down', 1, 2) };
1322
+ const hub = doc.createElement('div');
1323
+ hub.className = 'wg-tp-hub';
1324
+ box(hub, rect(d.x + third, d.y + third, third, third));
1325
+ art.appendChild(hub);
1326
+ for (const face of placement.faces) {
1327
+ const el = doc.createElement('div');
1328
+ el.className = 'wg-tp-face';
1329
+ el.textContent = face.label;
1330
+ el.style.fontSize = `${Math.round(clamp(face.r * 0.7, 14, 28))}px`;
1331
+ if (face.color)
1332
+ el.style.setProperty('--c', face.color);
1333
+ box(el, rect(face.cx - face.r, face.cy - face.r, face.r * 2, face.r * 2));
1334
+ art.appendChild(el);
1335
+ register(face.index, el);
1336
+ }
1337
+ for (const key of placement.keys) {
1338
+ const el = doc.createElement('div');
1339
+ el.className = `wg-tp-key is-${key.id}${key.id === 'l' || key.id === 'r' ? ' is-shoulder' : ''}`;
1340
+ if (key.id === 'pause')
1341
+ el.setAttribute('aria-label', key.label);
1342
+ else
1343
+ el.textContent = key.label;
1344
+ box(el, key.rect);
1345
+ art.appendChild(el);
1346
+ if (key.index !== null)
1347
+ register(key.index, el);
1348
+ }
1349
+ zones = placement.zones.map((r) => {
1350
+ const zone = doc.createElement('div');
1351
+ zone.className = 'wg-tp-zone';
1352
+ box(zone, r);
1353
+ zone.addEventListener('pointerdown', onDown);
1354
+ // Cancelling the touch itself is what stops the browser's click after it.
1355
+ zone.addEventListener('touchstart', cancelTouch, { passive: false });
1356
+ zone.addEventListener('touchmove', cancelTouch, { passive: false });
1357
+ zone.addEventListener('touchend', cancelTouch, { passive: false });
1358
+ zone.addEventListener('pointermove', onMove);
1359
+ zone.addEventListener('pointerup', onUp);
1360
+ zone.addEventListener('pointercancel', onUp);
1361
+ zone.addEventListener('lostpointercapture', onUp);
1362
+ root.appendChild(zone);
1363
+ return zone;
1364
+ });
1365
+ };
1366
+ const relayout = () => {
1367
+ if (destroyed)
1368
+ return;
1369
+ root.classList.toggle('is-visible', visible());
1370
+ if (visible()) {
1371
+ const placement = placeTouchPad(layout, viewport(), placeOptions);
1372
+ core.place(placement);
1373
+ build(placement);
1374
+ }
1375
+ else {
1376
+ core.place(null);
1377
+ }
1378
+ paint();
1379
+ const area = gameArea();
1380
+ for (const listener of [...layoutListeners])
1381
+ listener(area, core.placement);
1382
+ };
1383
+ const schedule = () => {
1384
+ if (timer)
1385
+ clearTimeout(timer);
1386
+ timer = null;
1387
+ const due = core.deadline;
1388
+ if (due === null)
1389
+ return;
1390
+ timer = setTimeout(() => {
1391
+ timer = null;
1392
+ core.tick();
1393
+ paint();
1394
+ schedule();
1395
+ }, Math.max(0, due - (win.performance?.now() ?? Date.now())));
1396
+ };
1397
+ /**
1398
+ * Where and when the pad last handled a finger. A touch that opens a menu (the pause
1399
+ * button) hides the pad, and the click the browser sends after the lift would land on
1400
+ * whatever the menu put under the finger — and pick it. Clicks right there, right
1401
+ * then, are the pad's and are dropped.
1402
+ */
1403
+ let lastTouch = { at: -Infinity, x: 0, y: 0 };
1404
+ const now = () => win.performance?.now() ?? Date.now();
1405
+ const remember = (event) => {
1406
+ lastTouch = { at: now(), x: event.clientX, y: event.clientY };
1407
+ };
1408
+ const cancelTouch = (event) => {
1409
+ if (event.cancelable)
1410
+ event.preventDefault();
1411
+ };
1412
+ const dropGhostClick = (event) => {
1413
+ if (now() - lastTouch.at > 400)
1414
+ return;
1415
+ if (Math.hypot(event.clientX - lastTouch.x, event.clientY - lastTouch.y) > TOUCH_MIN)
1416
+ return;
1417
+ event.preventDefault();
1418
+ event.stopImmediatePropagation();
1419
+ };
1420
+ function onDown(event) {
1421
+ event.preventDefault();
1422
+ remember(event);
1423
+ const zone = event.currentTarget;
1424
+ if (core.down(event.pointerId, event.clientX, event.clientY) === null)
1425
+ return;
1426
+ try {
1427
+ zone.setPointerCapture(event.pointerId);
1428
+ }
1429
+ catch {
1430
+ /* a synthetic pointer cannot be captured; it still works, minus sliding off the zone */
1431
+ }
1432
+ paint();
1433
+ schedule();
1434
+ }
1435
+ function onMove(event) {
1436
+ core.move(event.pointerId, event.clientX, event.clientY);
1437
+ paint();
1438
+ }
1439
+ function onUp(event) {
1440
+ remember(event);
1441
+ core.up(event.pointerId);
1442
+ paint();
1443
+ schedule();
1444
+ }
1445
+ const releaseAll = () => {
1446
+ core.releaseAll();
1447
+ paint();
1448
+ };
1449
+ const onVisibility = () => {
1450
+ if (doc.visibilityState === 'hidden')
1451
+ releaseAll();
1452
+ };
1453
+ const onAnyPointer = (event) => {
1454
+ if (mode === 'auto' && event.pointerType === 'touch' && !active) {
1455
+ active = true;
1456
+ relayout();
1457
+ }
1458
+ };
1459
+ const onAnyKey = (event) => {
1460
+ // Only a real keyboard hides the pad: an SDK that drives its engine with synthetic key
1461
+ // events (jgenesis reads the keyboard only) must not hide the pad it is listening to.
1462
+ if (event?.type === 'keydown' && !event.isTrusted)
1463
+ return;
1464
+ if (mode === 'auto' && active) {
1465
+ active = false;
1466
+ relayout();
1467
+ }
1468
+ };
1469
+ const onPadConnected = (event) => {
1470
+ if (event.gamepad !== core.gamepad)
1471
+ onAnyKey();
1472
+ };
1473
+ let frame = 0;
1474
+ const onResize = () => {
1475
+ if (frame)
1476
+ return;
1477
+ frame = win.requestAnimationFrame(() => {
1478
+ frame = 0;
1479
+ if (visible())
1480
+ relayout();
1481
+ });
1482
+ };
1483
+ const preventMenu = (event) => event.preventDefault();
1484
+ core.onChange((wentDown) => {
1485
+ if (haptics && wentDown.length)
1486
+ win.navigator.vibrate?.(8);
1487
+ });
1488
+ win.addEventListener('blur', releaseAll);
1489
+ win.addEventListener('click', dropGhostClick, { capture: true });
1490
+ doc.addEventListener('visibilitychange', onVisibility);
1491
+ win.addEventListener('pointerdown', onAnyPointer, { capture: true, passive: true });
1492
+ win.addEventListener('keydown', onAnyKey, { capture: true, passive: true });
1493
+ win.addEventListener('gamepadconnected', onPadConnected);
1494
+ win.addEventListener('resize', onResize);
1495
+ win.addEventListener('orientationchange', onResize);
1496
+ root.addEventListener('contextmenu', preventMenu);
1497
+ relayout();
1498
+ return {
1499
+ gamepad: core.gamepad,
1500
+ get layout() {
1501
+ return layout;
1502
+ },
1503
+ setLayout(next) {
1504
+ layout = resolve(next);
1505
+ relayout();
1506
+ },
1507
+ show() {
1508
+ if (shown)
1509
+ return;
1510
+ shown = true;
1511
+ relayout();
1512
+ },
1513
+ hide() {
1514
+ if (!shown)
1515
+ return;
1516
+ shown = false;
1517
+ relayout();
1518
+ },
1519
+ get visible() {
1520
+ return visible();
1521
+ },
1522
+ get placement() {
1523
+ return core.placement;
1524
+ },
1525
+ get gameArea() {
1526
+ return gameArea();
1527
+ },
1528
+ onLayout(listener) {
1529
+ layoutListeners.add(listener);
1530
+ return () => layoutListeners.delete(listener);
1531
+ },
1532
+ onPause: (listener) => core.onPause(listener),
1533
+ destroy() {
1534
+ if (destroyed)
1535
+ return;
1536
+ destroyed = true;
1537
+ core.place(null);
1538
+ if (timer)
1539
+ clearTimeout(timer);
1540
+ if (frame)
1541
+ win.cancelAnimationFrame(frame);
1542
+ win.removeEventListener('blur', releaseAll);
1543
+ win.removeEventListener('click', dropGhostClick, { capture: true });
1544
+ doc.removeEventListener('visibilitychange', onVisibility);
1545
+ win.removeEventListener('pointerdown', onAnyPointer, { capture: true });
1546
+ win.removeEventListener('keydown', onAnyKey, { capture: true });
1547
+ win.removeEventListener('gamepadconnected', onPadConnected);
1548
+ win.removeEventListener('resize', onResize);
1549
+ win.removeEventListener('orientationchange', onResize);
1550
+ layoutListeners.clear();
1551
+ root.remove();
1552
+ },
1553
+ };
1554
+ }
1555
+ /**
1556
+ * The host's one-liner: the pad shows while the game has the controls (the shared
1557
+ * input is suspended) and hides while a menu is open, and its pause button opens
1558
+ * the menu. Returns the function that undoes it.
1559
+ */
1560
+ export function connectTouchPad(pad, input) {
1561
+ const follow = (suspended) => (suspended ? pad.show() : pad.hide());
1562
+ follow(input.suspended);
1563
+ const offSuspend = input.onSuspend(follow);
1564
+ const offPause = pad.onPause(() => input.trigger('menu', { source: 'touch', repeat: false }));
1565
+ return () => {
1566
+ offSuspend();
1567
+ offPause();
1568
+ };
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
+ }
382
2600
  //# sourceMappingURL=engine-specs.js.map