Files
vpinball/lib/pinball/usePinballInstance.ts
T
valknarandClaude Sonnet 5 35fb68c916 Add ROM upload, local table library, engine bump, and UX/responsiveness fixes
- Bump @valknar/vpinball-wasm to 0.3.2 (PinMAME ROM support, MsgBox fix)
- Add optional PinMAME ROM .zip upload alongside .vpx tables
- Persist uploaded tables/ROMs in IndexedDB so users don't have to
  re-upload on later visits, with a library list on the landing page
- Fix Insert Coin key mismatch with the engine's real coin-door gating
  (now bound to 4, matching the shared table scripts) and surface it
  in the controls legend and "Tap to Start" hint
- Make the landing page, staging panel, and in-game HUD responsive for
  portrait phone widths; drop the landscape hint since portrait plays fine
- Replace the separate STATS HUD toggle with an FPS row in the info panel

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N9JmzRBZenapVkFWjw9jmG
2026-08-23 20:15:41 +02:00

123 lines
4.3 KiB
TypeScript

"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import type { LoadPinballOptions, PinballInstance } from "@valknar/vpinball-wasm";
import { hasWebGL2 } from "./webglSupport";
// Served as a plain static file, not bundled — loadPinball() internally does
// a dynamic import(`${baseUrl}/vpinball.js`) with a template-literal path
// that webpack can't statically resolve, so the whole engine must stay
// outside webpack's module graph (see scripts/copy-engine-assets.mjs).
const ENGINE_BASE_URL = "/vendor/vpinball-wasm";
export type PinballStatus = "idle" | "loading" | "ready" | "running" | "error";
interface EngineModule {
loadPinball(options: LoadPinballOptions): Promise<PinballInstance>;
}
async function loadEngineModule(): Promise<EngineModule> {
return (await import(
/* webpackIgnore: true */ `${ENGINE_BASE_URL}/index.js`
)) as EngineModule;
}
export interface UsePinballInstanceResult {
status: PinballStatus;
/** 0-1 download progress, only meaningful while status is "loading". */
progress: number;
error: string | null;
loadTimeMs: number | null;
instanceRef: React.RefObject<PinballInstance | null>;
/** Call from a user-gesture handler (audio autoplay / fullscreen policy). */
start: () => void;
}
export interface RomSelection {
gameName: string;
romData: ArrayBuffer;
}
export function usePinballInstance(
canvasRef: React.RefObject<HTMLCanvasElement | null>,
tableData: ArrayBuffer | undefined,
rom: RomSelection | undefined,
): UsePinballInstanceResult {
// Computed once at mount (not inside the effect below) so the WebGL2-
// unsupported case is derived initial state rather than a setState call
// that an effect makes only to immediately return.
const [webgl2Supported] = useState(hasWebGL2);
const [status, setStatus] = useState<PinballStatus>(webgl2Supported ? "idle" : "error");
const [progress, setProgress] = useState(0);
const [error, setError] = useState<string | null>(
webgl2Supported ? null : "Your browser doesn't support WebGL2, which this pinball engine requires.",
);
const [loadTimeMs, setLoadTimeMs] = useState<number | null>(null);
const instanceRef = useRef<PinballInstance | null>(null);
const disposedRef = useRef(false);
useEffect(() => {
disposedRef.current = false;
const canvas = canvasRef.current;
if (!canvas || !webgl2Supported) return;
setStatus("loading");
const startedAt = performance.now();
(async () => {
try {
const { loadPinball } = await loadEngineModule();
const instance = await loadPinball({
canvas,
baseUrl: ENGINE_BASE_URL,
tableData,
onProgress: (fraction) => {
if (!disposedRef.current) setProgress(fraction);
},
});
if (disposedRef.current) {
instance.dispose();
return;
}
if (rom) {
try {
// Must run before start() — Controller.Run() reads the ROM
// file synchronously at table-init time. A bad/mismatched ROM
// zip fails cleanly inside the engine rather than here, so this
// is defensive against loadRom() itself throwing (e.g. a
// corrupt zip), not something expected to fire routinely.
instance.loadRom(rom.gameName, rom.romData);
} catch (err) {
console.error("Failed to load ROM:", err);
}
}
instanceRef.current = instance;
setLoadTimeMs(performance.now() - startedAt);
setStatus("ready");
} catch (err) {
if (!disposedRef.current) {
setStatus("error");
setError(err instanceof Error ? err.message : "Failed to load the pinball engine.");
}
}
})();
return () => {
disposedRef.current = true;
instanceRef.current?.dispose();
instanceRef.current = null;
};
// Intentionally run once: PlayView mounts a fresh PinballCanvasImpl
// (via `key`) per table rather than swapping tableData in place.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const start = useCallback(() => {
if (!instanceRef.current) return;
instanceRef.current.start();
setStatus("running");
}, []);
return { status, progress, error, loadTimeMs, instanceRef, start };
}