Add vpinball: a browser Visual Pinball player

Next.js app that plays real .vpx tables via @valknar/vpinball-wasm
(WebAssembly Visual Pinball). Demo mode with the bundled default
table, drag-and-drop custom table upload, a cabinet-styled UI with a
coin-door HUD (fullscreen/stats/info/eject), a custom 404 page, PWA
support (hand-rolled service worker), and a static Docker Compose
deployment behind nginx.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012hQoM3jJT1Lx7CMTciMzvD
This commit is contained in:
2026-08-23 05:25:15 +02:00
co-authored by Claude Sonnet 5
commit e493a12e68
51 changed files with 5570 additions and 0 deletions
+44
View File
@@ -0,0 +1,44 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# vpinball-wasm engine assets, copied from node_modules at build time
/public/vendor/
# typescript
*.tsbuildinfo
next-env.d.ts
+3
View File
@@ -0,0 +1,3 @@
# @valknar/vpinball-wasm is published to a private Gitea npm registry.
# It's publicly readable, so no auth token is needed here.
@valknar:registry=https://dev.pivoine.art/api/packages/valknar/npm/
+9
View File
@@ -0,0 +1,9 @@
<!-- BEGIN:nextjs-agent-rules -->
# This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
<!-- END:nextjs-agent-rules -->
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+20
View File
@@ -0,0 +1,20 @@
# syntax=docker/dockerfile:1
FROM node:22-alpine AS base
ENV CI=true
RUN corepack enable
FROM base AS deps
WORKDIR /app
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml* .npmrc* ./
RUN pnpm install --frozen-lockfile --trust-lockfile
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN pnpm build
FROM nginx:1.27-alpine AS runner
COPY --from=builder /app/out /usr/share/nginx/html
COPY docker/nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
+117
View File
@@ -0,0 +1,117 @@
# vpinball
Play real `.vpx` pinball tables in your browser. Drop in your own table or try the bundled demo —
no plugins, no native install. Powered by [`@valknar/vpinball-wasm`](https://dev.pivoine.art/valknar/vpinball-wasm),
a WebAssembly build of the real [Visual Pinball](https://github.com/vpinball/vpinball) engine
(real physics, real VBScript table scripting, real WebGL2 rendering).
## Features
- **Play any self-contained `.vpx` table** — drag a file onto the landing page, or click to browse.
- **Demo mode** — a bundled table plays instantly with no upload required.
- **Fullscreen**, a live **FPS/stats** readout, and a **game info** panel (table name, size, load
time) in an in-game HUD styled after a pinball cabinet's coin door.
- **Installable as a PWA** — add it to your home screen or desktop; the engine is cached after
your first game so it's available offline afterward.
- **Deployable as a static site** via Docker Compose — no Node server at runtime, just nginx
serving prebuilt files.
## Prerequisites
- Node.js ≥ 20, [pnpm](https://pnpm.io) ≥ 11
- Docker + Docker Compose, for the containerized deploy
## Install
```bash
pnpm install --frozen-lockfile --trust-lockfile
```
`vpinball-wasm` is published to a private Gitea npm registry
(`https://dev.pivoine.art/api/packages/valknar/npm/`) under the `@valknar` scope. `.npmrc` maps
that scope to the registry; the package is publicly readable, so no auth token is needed to
install it.
To bump the engine to a newer published version:
```bash
pnpm add @valknar/vpinball-wasm@<version>
```
## Development
```bash
pnpm dev
```
`pnpm dev` copies the engine's build output into `public/vendor/vpinball-wasm/` first (via the
`predev` script) — it's gitignored and regenerated from `node_modules`, so this only needs
`pnpm install` to have completed. Re-run `pnpm run copy-engine-assets` by hand if you update the
dependency without restarting the dev server.
The dev server runs at `http://localhost:3000`.
## Build
```bash
pnpm build
```
Produces a fully static export in `out/` (`next.config.ts` sets `output: "export"`) — no Node
server needed to serve it.
## Docker deploy
```bash
docker compose build
docker compose up -d
```
Serves the static build via nginx on `http://localhost:8080`. No secrets or registry
authentication are required to build the image.
## PWA
The app can be installed from the browser's install prompt. A hand-rolled service worker
(`public/sw.js`) precaches the app shell; the engine's `.wasm`/`.data` files (~34 MB) are cached
on first visit to `/play`, not upfront, so installing the app doesn't force a large download
before anyone has actually played. After that first visit, offline reloads work.
When you ship a release that changes the app shell or updates the vendored engine build, bump the
cache version so returning visitors actually get the update:
```bash
pnpm run sw:bump
```
## Controls
| Key | Action |
| -------------- | ------------- |
| Left Shift | Left flipper |
| Right Shift | Right flipper |
| Enter | Plunger |
| 1 | Start game |
On touch devices, an on-screen control overlay appears automatically once a table is running.
## Limitations
Inherited from the underlying engine:
- Only self-contained `.vpx` tables are supported — tables that reference an external `.vbs`
script override or a `Music/` folder won't load correctly.
- No PinMAME, DOF, or FlexDMD plugin support.
- Single-threaded (no `SharedArrayBuffer`) — performance depends on your device's single-core
WebGL2 throughput.
- Initial engine download is ~34 MB (cached after the first visit).
- Gamepad input and DMD rendering are implemented but not yet confirmed on real hardware/tables.
- Raw cabinet hardware input (real nudge/plunger boards) has no browser equivalent.
## License
This app's own source has no license file yet — add one before distributing it. Separately, the
built output bundles the `@valknar/vpinball-wasm` engine and its default table, which redistribute
Visual Pinball source under a **mixed legacy/GPLv3+ license** (migrating file-by-file to GPLv3+
since October 2020) — see that package's own `LICENSE` for the authoritative terms before
distributing a build.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

+42
View File
@@ -0,0 +1,42 @@
@import "tailwindcss";
@theme {
/* Cabinet palette — grounded in real pinball-machine parts, not a generic dark theme. */
--color-ink: #0b0b0f; /* cabinet body / page background */
--color-ash: #1b1c22; /* panel surface */
--color-chrome: #a9aebb; /* metal bezel, borders, muted text */
--color-marquee: #ff7a29; /* GI lamp amber — primary accent, CTAs */
--color-arc: #4ce0d2; /* fluorescent-tube cyan — focus rings, secondary */
--color-paper: #f3efe6; /* aged-backglass cream — high-contrast body text */
--font-display: var(--font-big-shoulders), "Arial Narrow", sans-serif;
--font-body: var(--font-space-grotesk), system-ui, sans-serif;
--font-mono: var(--font-plex-mono), "IBM Plex Mono", ui-monospace, monospace;
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
body {
background: var(--color-ink);
color: var(--color-paper);
font-family: var(--font-body);
}
::selection {
background: var(--color-marquee);
color: var(--color-ink);
}
:focus-visible {
outline: 2px solid var(--color-arc);
outline-offset: 2px;
}
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

+45
View File
@@ -0,0 +1,45 @@
import type { Metadata, Viewport } from "next";
import { Big_Shoulders, Space_Grotesk, IBM_Plex_Mono } from "next/font/google";
import RegisterServiceWorker from "@/components/RegisterServiceWorker";
import "./globals.css";
const bigShoulders = Big_Shoulders({
variable: "--font-big-shoulders",
weight: ["700", "900"],
subsets: ["latin"],
});
const spaceGrotesk = Space_Grotesk({
variable: "--font-space-grotesk",
subsets: ["latin"],
});
const plexMono = IBM_Plex_Mono({
variable: "--font-plex-mono",
weight: ["400", "500", "600"],
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "vpinball — Visual Pinball in your browser",
description:
"Play real .vpx pinball tables in the browser, powered by a WebAssembly build of Visual Pinball. Drop in your own table or play the bundled demo.",
};
export const viewport: Viewport = {
themeColor: "#0b0b0f",
};
export default function RootLayout({ children }: LayoutProps<"/">) {
return (
<html
lang="en"
className={`${bigShoulders.variable} ${spaceGrotesk.variable} ${plexMono.variable} h-full antialiased`}
>
<body className="min-h-full flex flex-col bg-ink text-paper font-body">
{children}
<RegisterServiceWorker />
</body>
</html>
);
}
+28
View File
@@ -0,0 +1,28 @@
import type { MetadataRoute } from "next";
// Required under output: "export" — a manifest route has no per-request
// dynamic behavior anyway, so this just makes that explicit to the build.
export const dynamic = "force-static";
export default function manifest(): MetadataRoute.Manifest {
return {
name: "vpinball — Visual Pinball in your browser",
short_name: "vpinball",
description: "Play real .vpx pinball tables in the browser, powered by WebAssembly.",
start_url: "/",
display: "fullscreen",
background_color: "#0b0b0f",
theme_color: "#0b0b0f",
icons: [
{ src: "/icons/icon-192.png", sizes: "192x192", type: "image/png" },
{ src: "/icons/icon-512.png", sizes: "512x512", type: "image/png" },
{
src: "/icons/icon-512-maskable.png",
sizes: "512x512",
type: "image/png",
purpose: "maskable",
},
{ src: "/icons/icon.svg", sizes: "any", type: "image/svg+xml" },
],
};
}
+19
View File
@@ -0,0 +1,19 @@
import Link from "next/link";
import { buttonClassName } from "@/components/ui/Button";
export default function NotFound() {
return (
<main className="flex flex-1 flex-col items-center justify-center gap-6 px-4 py-24 text-center">
<p className="font-mono text-sm tracking-[0.3em] text-arc">TILT</p>
<h1 className="font-display text-5xl font-black tracking-wide text-marquee sm:text-7xl">
TABLE NOT FOUND
</h1>
<p className="max-w-md font-body text-chrome">
That page drained down the outlane. Head back to the cabinet and pick a table.
</p>
<Link href="/" className={buttonClassName("primary")}>
Back to Start
</Link>
</main>
);
}
+22
View File
@@ -0,0 +1,22 @@
import AttractHero from "@/components/landing/AttractHero";
export default function Home() {
return (
<main className="flex flex-1 flex-col items-center justify-center gap-8 px-4 py-16">
<AttractHero />
<p className="max-w-lg text-center font-mono text-xs text-chrome sm:hidden">
Pinball plays best in landscape or fullscreen rotate your device once a table loads.
</p>
<footer className="font-mono text-xs text-chrome/70">
Powered by{" "}
<a
href="https://github.com/vpinball/vpinball"
className="underline decoration-dotted underline-offset-2 hover:text-arc"
>
Visual Pinball
</a>
, compiled to WebAssembly.
</footer>
</main>
);
}
+9
View File
@@ -0,0 +1,9 @@
import PlayView from "@/components/pinball/PlayView";
export default function PlayPage() {
return (
<main className="h-dvh w-full">
<PlayView />
</main>
);
}
+62
View File
@@ -0,0 +1,62 @@
"use client";
import { useState, type ChangeEvent, type DragEvent, type ReactNode } from "react";
export const VPX_FILE_INPUT_ID = "vpx-file-input";
export interface FileDropZoneProps {
onFile: (file: File) => void;
onError: (message: string) => void;
children: ReactNode;
className?: string;
}
function validate(file: File | undefined, onFile: (file: File) => void, onError: (m: string) => void) {
if (!file) return;
if (!file.name.toLowerCase().endsWith(".vpx")) {
onError(`"${file.name}" isn't a .vpx file.`);
return;
}
onFile(file);
}
export default function FileDropZone({ onFile, onError, children, className = "" }: FileDropZoneProps) {
const [isDragging, setIsDragging] = useState(false);
const handleDrop = (e: DragEvent<HTMLDivElement>) => {
e.preventDefault();
setIsDragging(false);
validate(e.dataTransfer.files[0], onFile, onError);
};
const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
validate(e.target.files?.[0], onFile, onError);
e.target.value = "";
};
return (
<div
onDragOver={(e) => {
e.preventDefault();
setIsDragging(true);
}}
onDragLeave={() => setIsDragging(false)}
onDrop={handleDrop}
className={`relative ${className}`}
>
{children}
<input
id={VPX_FILE_INPUT_ID}
type="file"
accept=".vpx"
className="sr-only"
onChange={handleInputChange}
/>
{isDragging && (
<div className="pointer-events-none absolute inset-0 z-20 flex items-center justify-center rounded-lg bg-ink/85 font-display text-3xl tracking-wide text-arc ring-2 ring-arc">
DROP TO LOAD
</div>
)}
</div>
);
}
+38
View File
@@ -0,0 +1,38 @@
import { formatBytes, formatDuration } from "@/lib/format";
import { KEY_BINDINGS } from "@/lib/pinball/keyBindings";
import type { TableInfo } from "@/lib/pinball/types";
export interface GameInfoPanelProps {
tableInfo: TableInfo;
loadTimeMs: number | null;
}
export default function GameInfoPanel({ tableInfo, loadTimeMs }: GameInfoPanelProps) {
return (
<div className="w-72 space-y-4 rounded border border-chrome/30 bg-ash/95 p-4 font-mono text-sm text-paper shadow-xl">
<div>
<div className="text-xs tracking-widest text-chrome">TABLE</div>
<div className="truncate text-arc">{tableInfo.name}</div>
</div>
<dl className="grid grid-cols-2 gap-x-2 gap-y-1 text-xs">
<dt className="text-chrome">Source</dt>
<dd>{tableInfo.isDemo ? "Bundled demo" : "Your upload"}</dd>
<dt className="text-chrome">Size</dt>
<dd>{tableInfo.isDemo ? "—" : formatBytes(tableInfo.sizeBytes)}</dd>
<dt className="text-chrome">Load time</dt>
<dd>{loadTimeMs !== null ? formatDuration(loadTimeMs) : "—"}</dd>
</dl>
<div>
<div className="mb-1 text-xs tracking-widest text-chrome">CONTROLS</div>
<ul className="space-y-1 text-xs">
{KEY_BINDINGS.map((binding) => (
<li key={binding.action} className="flex justify-between gap-2">
<span className="text-chrome">{binding.action}</span>
<span className="text-paper">{binding.keys}</span>
</li>
))}
</ul>
</div>
</div>
);
}
+14
View File
@@ -0,0 +1,14 @@
"use client";
import { useEffect } from "react";
export default function RegisterServiceWorker() {
useEffect(() => {
if (!("serviceWorker" in navigator)) return;
navigator.serviceWorker.register("/sw.js").catch((err) => {
console.error("Service worker registration failed:", err);
});
}, []);
return null;
}
+102
View File
@@ -0,0 +1,102 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import type { PinballInstance } from "@valknar/vpinball-wasm";
import { useIdleTimer } from "./useIdleTimer";
import StatsReadout from "./StatsReadout";
import GameInfoPanel from "@/components/GameInfoPanel";
import type { TableInfo } from "@/lib/pinball/types";
export interface CoinDoorHudProps {
instanceRef: React.RefObject<PinballInstance | null>;
tableInfo: TableInfo;
loadTimeMs: number | null;
}
function HudButton({
label,
active,
onClick,
}: {
label: string;
active?: boolean;
onClick: () => void;
}) {
return (
<button
type="button"
onClick={onClick}
aria-pressed={active}
className={`rounded-sm border px-3 py-1.5 font-mono text-xs tracking-widest transition ${
active
? "border-marquee bg-marquee/20 text-marquee"
: "border-chrome/40 bg-black/30 text-chrome hover:border-arc hover:text-arc"
}`}
>
{label}
</button>
);
}
export default function CoinDoorHud({ instanceRef, tableInfo, loadTimeMs }: CoinDoorHudProps) {
const router = useRouter();
const isIdle = useIdleTimer(3000);
const [showStats, setShowStats] = useState(false);
const [showInfo, setShowInfo] = useState(false);
const [isFullscreen, setIsFullscreen] = useState(false);
useEffect(() => {
const onChange = () => setIsFullscreen(Boolean(document.fullscreenElement));
document.addEventListener("fullscreenchange", onChange);
return () => document.removeEventListener("fullscreenchange", onChange);
}, []);
const handleFullscreen = () => {
instanceRef.current?.requestFullscreen();
};
const handleEject = () => {
// dispose() (called by usePinballInstance's unmount cleanup, triggered by
// this navigation) tears the instance down immediately. Calling stop()
// here too raced it — stop() defers teardown to the engine's next
// internal step, and dispose() freeing WASM memory before that step runs
// hung the tab.
router.push("/");
};
return (
<>
<div
data-hud
className={`absolute inset-x-0 top-0 z-10 flex items-center justify-between gap-3 border-b border-chrome/30 bg-ash/90 px-4 py-2 backdrop-blur transition-opacity duration-300 ${
isIdle ? "pointer-events-none opacity-0" : "opacity-100"
}`}
>
<div className="flex items-center gap-2">
<span className="font-display text-lg tracking-wide text-marquee">VPINBALL</span>
<span className="hidden truncate font-mono text-xs text-chrome sm:inline">
{tableInfo.name}
</span>
</div>
<div className="flex items-center gap-2">
{showStats && <StatsReadout />}
<HudButton label="INFO" active={showInfo} onClick={() => setShowInfo((v) => !v)} />
<HudButton label="STATS" active={showStats} onClick={() => setShowStats((v) => !v)} />
<HudButton
label={isFullscreen ? "EXIT FS" : "FULLSCREEN"}
active={isFullscreen}
onClick={handleFullscreen}
/>
<HudButton label="EJECT" onClick={handleEject} />
</div>
</div>
{showInfo && (
<div className="absolute right-4 top-16 z-10">
<GameInfoPanel tableInfo={tableInfo} loadTimeMs={loadTimeMs} />
</div>
)}
</>
);
}
+35
View File
@@ -0,0 +1,35 @@
"use client";
import { useEffect, useState } from "react";
/** Self-contained rAF-based FPS counter — the engine exposes no perf API of its own. */
export default function StatsReadout() {
const [fps, setFps] = useState<number | null>(null);
useEffect(() => {
let frameCount = 0;
let windowStart = performance.now();
let raf = 0;
const tick = (now: number) => {
frameCount += 1;
const elapsed = now - windowStart;
if (elapsed >= 500) {
setFps(Math.round((frameCount * 1000) / elapsed));
frameCount = 0;
windowStart = now;
}
raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
}, []);
return (
<div className="flex items-baseline gap-2 rounded border border-chrome/30 bg-black/40 px-3 py-1.5 font-mono">
<span className="text-xs tracking-widest text-chrome">FPS</span>
<span className="text-lg tabular-nums text-arc">{fps ?? "--"}</span>
</div>
);
}
+33
View File
@@ -0,0 +1,33 @@
"use client";
import { useEffect, useRef, useState } from "react";
/** True once no pointer/keyboard activity has been seen for `timeoutMs`. */
export function useIdleTimer(timeoutMs = 3000): boolean {
const [isIdle, setIsIdle] = useState(false);
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
const reset = () => {
setIsIdle(false);
if (timerRef.current) clearTimeout(timerRef.current);
timerRef.current = setTimeout(() => setIsIdle(true), timeoutMs);
};
reset();
const events: Array<keyof WindowEventMap> = [
"mousemove",
"pointerdown",
"touchstart",
"keydown",
];
events.forEach((event) => window.addEventListener(event, reset, { passive: true }));
return () => {
if (timerRef.current) clearTimeout(timerRef.current);
events.forEach((event) => window.removeEventListener(event, reset));
};
}, [timeoutMs]);
return isIdle;
}
+70
View File
@@ -0,0 +1,70 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import Button, { buttonClassName } from "@/components/ui/Button";
import FileDropZone, { VPX_FILE_INPUT_ID } from "@/components/FileDropZone";
import { setPendingTable } from "@/lib/pinball/tableSelectionStore";
export default function AttractHero() {
const router = useRouter();
const [error, setError] = useState<string | null>(null);
const handleFile = (file: File) => {
setError(null);
setPendingTable(file);
router.push("/play");
};
return (
<FileDropZone onFile={handleFile} onError={setError} className="w-full max-w-4xl">
<div className="relative overflow-hidden rounded-t-3xl rounded-b-lg border-2 border-chrome/40 bg-ash shadow-2xl">
{/* Backglass glow — stands in for real playfield art; GI-lamp amber + a cyan tube accent. */}
<div
aria-hidden
className="pointer-events-none absolute inset-0 opacity-70"
style={{
background:
"radial-gradient(60% 50% at 30% 20%, rgba(255,122,41,0.35), transparent 70%), radial-gradient(45% 40% at 80% 70%, rgba(76,224,210,0.25), transparent 70%)",
}}
/>
<div
aria-hidden
className="pointer-events-none absolute inset-0"
style={{
backgroundImage:
"repeating-linear-gradient(0deg, rgba(255,255,255,0.03) 0px, rgba(255,255,255,0.03) 1px, transparent 1px, transparent 3px)",
}}
/>
<div className="relative flex flex-col items-center gap-6 px-8 py-20 text-center sm:py-28">
<p className="font-mono text-xs tracking-[0.3em] text-arc">WEBASSEMBLY · WEBGL2 · REAL .VPX TABLES</p>
<h1 className="font-display text-6xl font-black leading-none tracking-wide text-paper sm:text-8xl">
VPINBALL
</h1>
<p className="max-w-md font-body text-chrome">
Real Visual Pinball tables, playing in your browser. Drop in a{" "}
<code className="font-mono text-arc">.vpx</code> file, or try the bundled demo.
</p>
<div className="mt-4 flex flex-col items-center gap-3 sm:flex-row">
<Button type="button" variant="primary" onClick={() => router.push("/play")}>
Insert Coin Play Demo
</Button>
<label htmlFor={VPX_FILE_INPUT_ID} className={buttonClassName("outline", "cursor-pointer")}>
Load Your Table
</label>
</div>
<p className="font-mono text-xs text-chrome">or drag a .vpx file anywhere onto this panel</p>
{error && (
<p role="alert" className="font-mono text-sm text-marquee">
{error}
</p>
)}
</div>
</div>
</FileDropZone>
);
}
+14
View File
@@ -0,0 +1,14 @@
"use client";
import dynamic from "next/dynamic";
import type { PinballCanvasImplProps } from "./PinballCanvasImpl";
// The engine touches window/canvas/WebGL as soon as it mounts, so it's kept
// out of the server render entirely rather than just deferring to an effect.
const PinballCanvasImpl = dynamic<PinballCanvasImplProps>(() => import("./PinballCanvasImpl"), {
ssr: false,
});
export default function PinballCanvas(props: PinballCanvasImplProps) {
return <PinballCanvasImpl {...props} />;
}
+69
View File
@@ -0,0 +1,69 @@
"use client";
import { useRef } from "react";
import { usePinballInstance } from "@/lib/pinball/usePinballInstance";
import { useTouchControls } from "@/lib/pinball/useTouchControls";
import CoinDoorHud from "@/components/hud/CoinDoorHud";
import type { TableInfo } from "@/lib/pinball/types";
export interface PinballCanvasImplProps {
tableData?: ArrayBuffer;
tableInfo: TableInfo;
}
export default function PinballCanvasImpl({ tableData, tableInfo }: PinballCanvasImplProps) {
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const containerRef = useRef<HTMLDivElement | null>(null);
const { status, progress, error, loadTimeMs, instanceRef, start } = usePinballInstance(
canvasRef,
tableData,
);
useTouchControls(containerRef, status === "running");
return (
<div ref={containerRef} className="relative h-full w-full overflow-hidden bg-black">
{/* SDL3's Emscripten backend resolves its own window/GL-context target via
document.querySelector("#canvas") independently of Module.canvas — the
id is required or context creation silently no-ops (findCanvasEventTarget
returns null, emscripten_webgl_create_context returns handle 0, and the
engine crashes later reading an unset GL context). */}
<canvas id="canvas" ref={canvasRef} className="h-full w-full" />
{(status === "ready" || status === "running") && (
<CoinDoorHud instanceRef={instanceRef} tableInfo={tableInfo} loadTimeMs={loadTimeMs} />
)}
{status === "loading" && (
<div className="absolute inset-0 flex flex-col items-center justify-center gap-4 bg-ink/90 text-paper">
<div className="font-display text-2xl tracking-wide text-marquee">LOADING TABLE</div>
<div className="h-2 w-64 overflow-hidden rounded-full bg-ash">
<div
className="h-full bg-marquee transition-[width]"
style={{ width: `${Math.round(progress * 100)}%` }}
/>
</div>
<div className="font-mono text-sm text-chrome">{Math.round(progress * 100)}%</div>
</div>
)}
{status === "error" && (
<div className="absolute inset-0 flex flex-col items-center justify-center gap-2 bg-ink px-8 text-center text-paper">
<div className="font-display text-2xl text-marquee">TABLE NOT LOADING</div>
<p className="max-w-md font-body text-chrome">{error}</p>
</div>
)}
{status === "ready" && (
<div className="absolute inset-0 flex items-center justify-center bg-ink/80">
<button
type="button"
onClick={start}
className="rounded-full border-2 border-marquee bg-marquee/10 px-8 py-4 font-display text-2xl tracking-wide text-marquee shadow-[0_0_24px_rgba(255,122,41,0.5)] transition hover:bg-marquee/20"
>
TAP TO START
</button>
</div>
)}
</div>
);
}
+51
View File
@@ -0,0 +1,51 @@
"use client";
import { useEffect, useState } from "react";
import PinballCanvas from "./PinballCanvas";
import { takePendingTable } from "@/lib/pinball/tableSelectionStore";
import type { TableInfo } from "@/lib/pinball/types";
interface ResolvedTable {
tableData?: ArrayBuffer;
tableInfo: TableInfo;
}
export default function PlayView() {
const [resolved, setResolved] = useState<ResolvedTable | null>(null);
useEffect(() => {
let cancelled = false;
(async () => {
const file = takePendingTable();
if (file) {
const tableData = await file.arrayBuffer();
if (cancelled) return;
setResolved({
tableData,
tableInfo: { name: file.name, sizeBytes: file.size, isDemo: false },
});
return;
}
// No pending upload (fresh visit, or a hard refresh of /play) — fall
// back to the bundled demo table rather than dead-ending the route.
setResolved({
tableInfo: { name: "Demo table", sizeBytes: 0, isDemo: true },
});
})();
return () => {
cancelled = true;
};
}, []);
if (!resolved) {
return (
<div className="flex h-full w-full items-center justify-center bg-ink font-mono text-chrome">
Preparing table
</div>
);
}
return (
<PinballCanvas tableData={resolved.tableData} tableInfo={resolved.tableInfo} key={resolved.tableInfo.name} />
);
}
+22
View File
@@ -0,0 +1,22 @@
import type { ButtonHTMLAttributes } from "react";
export type ButtonVariant = "primary" | "outline" | "quiet";
const variantClasses: Record<ButtonVariant, string> = {
primary:
"border-2 border-marquee bg-marquee/10 text-marquee shadow-[0_0_24px_rgba(255,122,41,0.35)] hover:bg-marquee/20",
outline: "border-2 border-chrome/50 text-paper hover:border-arc hover:text-arc",
quiet: "border border-transparent text-chrome hover:text-paper",
};
export function buttonClassName(variant: ButtonVariant = "primary", className = ""): string {
return `inline-block rounded-full px-6 py-3 font-display text-lg tracking-wide transition ${variantClasses[variant]} ${className}`;
}
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
variant?: ButtonVariant;
}
export default function Button({ variant = "primary", className = "", ...props }: ButtonProps) {
return <button className={buttonClassName(variant, className)} {...props} />;
}
+10
View File
@@ -0,0 +1,10 @@
import type { HTMLAttributes } from "react";
export default function Panel({ className = "", ...props }: HTMLAttributes<HTMLDivElement>) {
return (
<div
className={`rounded-lg border border-chrome/30 bg-ash/80 shadow-lg ${className}`}
{...props}
/>
);
}
+6
View File
@@ -0,0 +1,6 @@
services:
web:
build: .
ports:
- "8080:80"
restart: unless-stopped
+49
View File
@@ -0,0 +1,49 @@
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
# nginx only sees its own container-internal port (80) and has no idea
# docker-compose maps that to some other host port — an absolute redirect
# (e.g. nginx's own trailing-slash directory redirect) would silently
# drop that external port from the Location header. A relative Location
# lets the browser resolve it against whatever host:port it's already on.
absolute_redirect off;
# The stock /etc/nginx/mime.types (included by the base image's own
# nginx.conf) already maps .wasm/.woff2/.html correctly. .webmanifest
# isn't in it, so it's set per-location below rather than via a
# server-level types{} block, which would replace that whole map instead
# of extending it. .data has no meaningful type of its own and correctly
# falls through to the base config's default_type (application/octet-stream).
location = /manifest.webmanifest {
default_type application/manifest+json;
add_header Cache-Control "no-cache";
}
location = /sw.js {
add_header Cache-Control "no-cache";
}
# Large, effectively-immutable engine binaries — keep gzip off so nginx
# can still serve byte-range/If-Range requests (on-the-fly gzip disables
# range serving), and cache them aggressively.
location /vendor/vpinball-wasm/ {
gzip off;
add_header Cache-Control "public, max-age=31536000, immutable";
}
# error_page preserves the 404 status while serving the prerendered
# not-found page's content — a bare `try_files ... /404.html;` fallback
# would serve that same content with a 200, since try_files treats an
# existing fallback file as a normal successful response.
error_page 404 /404.html;
location = /404.html {
internal;
}
location / {
try_files $uri $uri/ $uri.html =404;
}
}
+21
View File
@@ -0,0 +1,21 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
// Vendored vpinball-wasm build output (copied from node_modules at build
// time, see scripts/copy-engine-assets.mjs) — third-party, not our code.
"public/vendor/**",
]),
]);
export default eslintConfig;
+12
View File
@@ -0,0 +1,12 @@
export function formatBytes(bytes: number): string {
if (bytes === 0) return "0 B";
const units = ["B", "KB", "MB", "GB"];
const exponent = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
const value = bytes / 1024 ** exponent;
return `${exponent === 0 ? value : value.toFixed(1)} ${units[exponent]}`;
}
export function formatDuration(ms: number): string {
if (ms < 1000) return `${Math.round(ms)} ms`;
return `${(ms / 1000).toFixed(1)} s`;
}
+11
View File
@@ -0,0 +1,11 @@
export interface KeyBinding {
keys: string;
action: string;
}
export const KEY_BINDINGS: KeyBinding[] = [
{ keys: "Left Shift", action: "Left flipper" },
{ keys: "Right Shift", action: "Right flipper" },
{ keys: "Enter", action: "Plunger" },
{ keys: "1", action: "Start game" },
];
+15
View File
@@ -0,0 +1,15 @@
// In-memory handoff for a user-selected .vpx File between the landing page
// and /play — a File can't survive a URL-based navigation, and this is a
// single-shot value read once on mount, so module-level state is sufficient
// (no need for anything heavier than a plain variable).
let pendingFile: File | null = null;
export function setPendingTable(file: File): void {
pendingFile = file;
}
export function takePendingTable(): File | null {
const file = pendingFile;
pendingFile = null;
return file;
}
+5
View File
@@ -0,0 +1,5 @@
export interface TableInfo {
name: string;
sizeBytes: number;
isDemo: boolean;
}
+104
View File
@@ -0,0 +1,104 @@
"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 function usePinballInstance(
canvasRef: React.RefObject<HTMLCanvasElement | null>,
tableData: ArrayBuffer | 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;
}
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 };
}
+38
View File
@@ -0,0 +1,38 @@
"use client";
import { useEffect } from "react";
import type { attachTouchControls as AttachTouchControls } from "@valknar/vpinball-wasm";
const ENGINE_BASE_URL = "/vendor/vpinball-wasm";
function isTouchDevice(): boolean {
return typeof window !== "undefined" && ("ontouchstart" in window || navigator.maxTouchPoints > 0);
}
/** Attaches the engine's on-screen touch overlay to `containerRef` while `active` is true. */
export function useTouchControls(
containerRef: React.RefObject<HTMLElement | null>,
active: boolean,
): void {
useEffect(() => {
if (!active || !isTouchDevice()) return;
const container = containerRef.current;
if (!container) return;
let handle: { detach: () => void } | undefined;
let cancelled = false;
(async () => {
const { attachTouchControls } = (await import(
/* webpackIgnore: true */ `${ENGINE_BASE_URL}/index.js`
)) as { attachTouchControls: typeof AttachTouchControls };
if (cancelled) return;
handle = attachTouchControls({ container });
})();
return () => {
cancelled = true;
handle?.detach();
};
}, [containerRef, active]);
}
+9
View File
@@ -0,0 +1,9 @@
export function hasWebGL2(): boolean {
if (typeof window === "undefined") return false;
try {
const canvas = document.createElement("canvas");
return Boolean(canvas.getContext("webgl2"));
} catch {
return false;
}
}
+9
View File
@@ -0,0 +1,9 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: "export",
images: { unoptimized: true },
trailingSlash: true,
};
export default nextConfig;
+31
View File
@@ -0,0 +1,31 @@
{
"name": "vpinball",
"version": "0.1.0",
"private": true,
"scripts": {
"copy-engine-assets": "node scripts/copy-engine-assets.mjs",
"sw:bump": "node scripts/bump-sw-version.mjs",
"predev": "pnpm run copy-engine-assets",
"dev": "next dev",
"build": "pnpm run copy-engine-assets && next build",
"start": "next start",
"lint": "eslint"
},
"dependencies": {
"@valknar/vpinball-wasm": "0.2.0",
"next": "16.3.2",
"react": "19.2.8",
"react-dom": "19.2.8"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "16.3.2",
"tailwindcss": "^4",
"typescript": "^5"
},
"packageManager": "pnpm@11.21.0"
}
+4196
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
allowBuilds:
sharp: false
unrs-resolver: false
minimumReleaseAgeExclude:
- '@valknar/vpinball-wasm@0.2.0'
updateNotifier: false
+7
View File
@@ -0,0 +1,7 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

+7
View File
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<rect width="512" height="512" fill="#0b0b0f"/>
<circle cx="256" cy="256" r="200" fill="none" stroke="#4ce0d2" stroke-width="10" opacity="0.35"/>
<circle cx="256" cy="216" r="96" fill="#ff7a29"/>
<circle cx="222" cy="182" r="26" fill="#ffd7ad" opacity="0.55"/>
<path d="M 116 372 Q 256 300 396 372 L 396 392 Q 256 340 116 392 Z" fill="#a9aebb"/>
</svg>

After

Width:  |  Height:  |  Size: 426 B

+7
View File
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<rect width="512" height="512" fill="#0b0b0f"/>
<circle cx="256" cy="256" r="200" fill="none" stroke="#4ce0d2" stroke-width="10" opacity="0.35"/>
<circle cx="256" cy="216" r="96" fill="#ff7a29"/>
<circle cx="222" cy="182" r="26" fill="#ffd7ad" opacity="0.55"/>
<path d="M 116 372 Q 256 300 396 372 L 396 392 Q 256 340 116 392 Z" fill="#a9aebb"/>
</svg>

After

Width:  |  Height:  |  Size: 426 B

+77
View File
@@ -0,0 +1,77 @@
// Bump this on every release that changes the app shell or the vendored
// engine build — it's the only thing that invalidates old caches, since
// none of the cached URLs below are content-hashed by us.
const CACHE_VERSION = "v1";
const SHELL_CACHE = `shell-${CACHE_VERSION}`;
const ENGINE_CACHE = `engine-${CACHE_VERSION}`;
const SHELL_ASSETS = [
"/",
"/play/",
"/404.html",
"/manifest.webmanifest",
"/icons/icon-192.png",
"/icons/icon-512.png",
];
self.addEventListener("install", (event) => {
event.waitUntil(
caches
.open(SHELL_CACHE)
.then((cache) => cache.addAll(SHELL_ASSETS))
.then(() => self.skipWaiting()),
);
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches
.keys()
.then((keys) =>
Promise.all(
keys
.filter((key) => key !== SHELL_CACHE && key !== ENGINE_CACHE)
.map((key) => caches.delete(key)),
),
)
.then(() => self.clients.claim()),
);
});
self.addEventListener("fetch", (event) => {
const url = new URL(event.request.url);
if (event.request.method !== "GET" || url.origin !== self.location.origin) return;
// The engine's .wasm/.data/.js are large and effectively immutable per
// release (they aren't content-hashed), so once fetched they're served
// straight from cache — cache-busting happens by bumping CACHE_VERSION.
if (url.pathname.startsWith("/vendor/vpinball-wasm/")) {
event.respondWith(
caches.open(ENGINE_CACHE).then((cache) =>
cache.match(event.request).then(
(hit) =>
hit ??
fetch(event.request).then((response) => {
cache.put(event.request, response.clone());
return response;
}),
),
),
);
return;
}
event.respondWith(
caches.match(event.request).then(
(hit) =>
hit ??
fetch(event.request).then((response) => {
if (response.ok) {
const clone = response.clone();
caches.open(SHELL_CACHE).then((cache) => cache.put(event.request, clone));
}
return response;
}),
),
);
});
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env node
// Bumps public/sw.js's CACHE_VERSION so a deploy invalidates old caches —
// run this before cutting a release that changes the app shell or updates
// the vendored vpinball-wasm engine build.
import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
const rootDir = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const swPath = path.join(rootDir, "public", "sw.js");
const contents = await readFile(swPath, "utf8");
const match = contents.match(/CACHE_VERSION = "v(\d+)"/);
if (!match) {
console.error(`Couldn't find CACHE_VERSION in ${swPath}`);
process.exit(1);
}
const next = Number(match[1]) + 1;
const updated = contents.replace(/CACHE_VERSION = "v\d+"/, `CACHE_VERSION = "v${next}"`);
await writeFile(swPath, updated);
console.log(`Bumped service worker CACHE_VERSION to v${next}`);
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env node
// Copies the vpinball-wasm engine's build output into public/vendor/vpinball-wasm/
// so it's served as plain static files (see lib/pinball/usePinballInstance.ts for why:
// the package's own loadPinball() does a dynamic import() of its glue script that must
// never pass through webpack's module graph).
import { cp, mkdir, rm } from "node:fs/promises";
import { existsSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const rootDir = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const pkgDistDir = path.join(rootDir, "node_modules", "@valknar", "vpinball-wasm", "dist");
const targetDir = path.join(rootDir, "public", "vendor", "vpinball-wasm");
if (!existsSync(pkgDistDir)) {
console.error(
`vpinball-wasm not found at ${pkgDistDir} — run "pnpm install" first.`,
);
process.exit(1);
}
await rm(targetDir, { recursive: true, force: true });
await mkdir(targetDir, { recursive: true });
await cp(pkgDistDir, targetDir, { recursive: true });
console.log(`Copied vpinball-wasm engine assets to ${path.relative(rootDir, targetDir)}/`);
+34
View File
@@ -0,0 +1,34 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"]
}