valknarandClaude Sonnet 5 ef20b0d6c3
CI / Build wasm engine (push) Failing after 2m14s
CI / Publish to npm registry (push) Skipped
Fix CI: vendor-fetch commit fails with no git identity configured
scripts/setup.sh's fetch_pinned() creates a fresh git repo per vendored
dependency and commits it with --author set, but --author alone doesn't
satisfy git's separate committer-identity requirement - it works on a
dev machine with ~/.gitconfig already set, but fails outright in a
clean CI container with no git identity anywhere (confirmed: Gitea
Actions failed at exactly this step with "Committer identity unknown").
Fixed by scoping user.name/user.email via -c flags to just this commit
invocation, verified to succeed even with HOME pointed at an empty
directory and no inherited git env vars.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-22 18:17:41 +02:00

vpinball-wasm

Visual Pinball's real engine, compiled to WebAssembly — real .vpx tables, real VBScript table logic, real WebGL2 rendering, in the browser.

This project ports Visual Pinball (the C++ pinball table simulator) to WebAssembly via Emscripten. It is a source-level port of the actual engine — not a reimplementation — so table compatibility, physics behavior, and scripting semantics come from the real codebase real tables already run against today.

Status: a real, playable table, live in the browser — keyboard and audio confirmed

The patched engine, running in a real browser via this project's build, renders and plays a real, interactive, physically-simulated pinball table from a real .vpx file — lit flippers that respond to Left/Right Shift, slingshots, bumpers, targets, a plunger, drain detection, and audible sound effects — all driven by a real per-frame game loop, not a static screenshot. This has been confirmed by hands-on manual testing in Chrome, not just code review. Concretely, verified end-to-end:

  • Loads a real .vpx file and parses it completely (OLE/BIFF container, all game items, images, sounds metadata).
  • Compiles all of vpinball's real, unmodified .glfx shaders (80 shaders across UI/Basic/Ball/DMD/Flasher/Light/Framebuffer) against WebGL2/GLES3, computes environment map radiance (HDR/IBL), and runs the static pre-render pass.
  • Runs the real physics engine and the real VBScript scripting engine (libwinevbs) — confirmed by pressing a physical key and watching a table-script-driven flipper (Table1_KeyDownLeftFlipper.RotateToEnd) actually move.
  • Runs a real per-frame game loop (Player::EmscriptenStepFrame(), driven by emscripten_set_main_loop) stepping input, physics, and rendering every frame, with a clean stop()~Player() teardown mid-session and no crash or hang.
  • Keyboard input and audio, confirmed by ear and by hand against the bundled default table (see below) — the full DOM → SDL3 → InputManager → VBScript-dispatch pipeline, and the full audio pipeline, both work.
  • Ships the bundled default table (exampleTable.vpx, a real playable demo table with working gameplay logic) at ~34MB total (vpinball.wasm + vpinball.data + vpinball.js) after trimming ~52MB of editor-only content never used by the player runtime (bundled native-editor templates and a Monaco code editor) — see Roadmap.

Getting here required finding and fixing four real, previously-unknown bugs in the upstream engine (not just adding a new CMake target) — see patches/vpinball/0003-*, 0004-* and 0005-* for the exact fixes:

  1. RenderDevice::WaitForVSync() unconditionally spawned a real std::thread every frame, even on __STANDALONE__ builds — a hard crash under Emscripten's single-threaded runtime, independent of and encountered before the main-loop-yielding problem below.
  2. The desktop game loop (FramePacingGameLoop/GPUQueueStuffingGameLoop) is a blocking native while loop with manual uSleep throttling — incompatible with a single-threaded WASM main thread, which must yield control back to the browser every frame. This project adds a new Player::EmscriptenStepFrame() (one frame, no internal loop) driven by emscripten_set_main_loop, plus new JS-callable lifecycle entry points (vpinball_wasm_start/stop/dispose/eval_script in src/core/EmscriptenBridge.cpp) that don't route through the desktop main()/WinMain() chain at all, since that chain assumes the whole process runs exactly one table to completion then exits.
  3. The window's OpenGL back buffer was created with the window's logical (CSS) pixel size instead of its device pixel size — on any browser tab with devicePixelRatio != 1 (essentially all HiDPI displays), the GL viewport only covered a fraction of the canvas's actual backing buffer, rendering anchored to one corner (GL's viewport origin) instead of filling the canvas.
  4. Window::OnResized() (called on every SDL resize event, including entering/leaving browser fullscreen) updated the window's own tracked pixel size but never propagated it to the window's back buffer render target — so toggling fullscreen resized the canvas but rendering stayed pinned to the pre-resize viewport size.

Why a source-level port, not a reimplementation

Projects like vpx-js reimplement Visual Pinball's physics and a VBScript-to-JavaScript transpiler from scratch in TypeScript. That approach has to independently re-derive correct behavior for every physics quirk and every VBScript language feature — and in vpx-js's case, its own test suite documents that it never achieved compatibility with core.vbs, the shared script library nearly all real tables depend on.

This project instead compiles the actual C++ engine and the actual VBScript interpreter (libwinevbs, extracted from Wine, the same interpreter real tables already run against on macOS/Linux/iOS/Android today) to WebAssembly. Table compatibility and scripting correctness come from code that's already correct, not from independently re-deriving it.

Architecture

 .vpx file (OLE/BIFF)  →  vpinball's own loader (POLE-based, unmodified)
                               │
        ┌──────────────────────┴───────────────────────┐
        │                                               │
   Physics engine                                  Rendering
   (unmodified C++)                          SDL3 → WebGL2/GLES3 (glad)
        │                                        real .glfx shaders
        │                                               │
   VBScript table logic  ←──────────────────────  libwinevbs
   (real Wine-derived interpreter, compiled to wasm32)
                               │
                    emscripten_set_main_loop
                    (Player::EmscriptenStepFrame, one frame per callback)

This project's own contribution is glue, not a rewrite: a new PLATFORM=emscripten CMake target modeled on vpinball's existing Linux build, wasm32 builds of its SDL3/SDL3_image/SDL3_ttf/FreeImage/libwinevbs dependencies, a small number of source patches fixing genuine first-32-bit-target and first-wasm-target issues, and the new game-loop/lifecycle bridge described above — see patches/ for the exact diffs, each with an explanatory comment.

Full research and two isolated feasibility spikes (proving real VBScript execution and real WebGL2 rendering work under Emscripten, independently, before this project existed) live in the companion research repository:

  • VBScript-in-WASM spike: proves libwinevbs compiles and correctly runs real VBScript (classes, Scripting.Dictionary, error handling) under wasm32.
  • SDL3/WebGL2 spike: proves SDL3's Emscripten backend creates a real WebGL2 context and GLSL ES 3.00 rendering works.
  • Feasibility reports covering the native engine, vpx-js, and libwinevbs specifically.

Roadmap

Proven working (independent spikes, before this project's own build existed):

  • Real VBScript execution under wasm32 (libwinevbs).
  • Real WebGL2/GLES3 rendering under Emscripten (SDL3).

Proven working (in this project's own build, in a real browser, by hands-on manual testing):

  • .vpx file loading and parsing; SDL3 audio/video/window initialization.
  • Compilation of all of vpinball's real, unmodified .glfx shaders against WebGL2; environment map/HDR radiance computation; static pre-render pass.
  • The full input pipeline: a real physical keypress → SDL3 → InputManager::PushButtonEventPinTable::FireDispID(DISPID_GameEvents_KeyDown) → the table's own VBScript KeyDown handler → LeftFlipper.RotateToEnd — confirmed by watching a flipper actually respond to Left/Right Shift.
  • Audio, confirmed audible by ear.
  • A real, running per-frame game loop (emscripten_set_main_loop-driven), with clean JS-controllable start()/stop() lifecycle and normal C++ teardown (~Player()) on stop — see Status above.
  • Correct rendering at any canvas size/DPI, including entering/leaving fullscreen — two real GL back-buffer sizing bugs found and fixed (see Status).
  • A bundled default table (exampleTable.vpx) with real, working gameplay logic (flippers, slingshots, bumpers, targets, a plunger, drain detection) — swapped in from an earlier choice (test000-default-table.vpx) that turned out to be upstream's own rendering/component regression-test fixture with no gameplay script at all (confirmed by diffing a screenshot against vpinball's own official reference image for that table).
  • Editor-only content (bundled native-editor example/template tables, a Monaco code editor) excluded from the asset payload — never used by the player runtime — see patches/vpinball/0001-*.
  • A full loading → play flow in a real page (examples/basic/index.html): a byte-level download progress bar, a user-gesture "Start" button (required for both audio autoplay and fullscreen to work), a working fullscreen button, and responsive canvas sizing that fills its container correctly.
  • Browser file-loading for self-contained tables: picking a .vpx file, mounting it via FS.writeFile, and starting the engine against it — verified end-to-end (PinTable::LoadGameFromFilename /tables/uploaded.vpx in the boot log, followed by a normal render).
  • A JS-callable evalScript() debug/utility hook (pinball.evalScript(script)) that runs arbitrary VBScript against the live table via the same entry point the interpreter's own debug console uses.

Not yet validated (should work, per code review and by analogy to already-proven mechanisms, but unconfirmed end-to-end):

  • Gamepad/joystick input during real gameplay (keyboard input uses the identical InputManager pipeline and is confirmed working; gamepad support is code-complete but untested on real hardware).
  • Touch-control overlay (attachTouchControls) actually flipping a flipper on a real touch device — implemented and included in the example (synthesizes the real default keyboard scancodes on window), not yet confirmed on physical touch hardware.
  • DMD rendering via a script-driven Flasher/ScriptGlobalTable::put_DMDPixels. This is native, core-engine functionality requiring no new code (src/core/ScriptGlobalTable.cpp:886-937, src/parts/flasher.cpp:1312-1341), and rides the exact same ScriptInterpreter::Evaluate() VBScript-dispatch path already confirmed working by the flipper test above — but the bundled default table has no DMD-configured Flasher, so a full visual confirmation needs a real DMD-equipped table (uploadable via the file picker) or authoring one, neither done yet.

Explicitly out of scope for now (browser-sandbox constraints or a real infrastructure-cost tradeoff, not a technical dead end — could be revisited):

  • Multi-threading (pthreads/SharedArrayBuffer): would require mandatory Cross-Origin-Opener-Policy/Cross-Origin-Embedder-Policy headers on every page hosting this widget, a coi-serviceworker-style workaround for static hosts that can't set custom headers, and real risk of breaking unrelated cross-origin embeds on host pages — a poor tradeoff for something meant to be embeddable in arbitrary third-party pages. ThreadPool's one-off parallel work (e.g. parallel .vpx item deserialization) already runs synchronously instead (patches/vpinball/0002-*). Revisit only if real-world profiling shows single-threaded performance is genuinely insufficient.
  • The heavy plugin ecosystem (PinMAME real ROM emulation — copyrighted ROMs, can't legally bundle; DOF/AltSound/PUP/FlexDMD/Serum — real-cabinet-hardware or FFmpeg-dependent; b2slegacy — a ~11,000-line legacy VB6-COM compatibility layer). Excluded via a single CMake guard; zero core-engine impact.
  • The modern plugins/b2s backglass plugin — explicitly assessed and declined for now, not just left undone. B2SServer itself has no browser-incompatible networking (it's built on vpinball's own in-process plugin messaging bus, not real sockets), but our emscripten build currently excludes the entire plugin subsystem outright (CMakeLists_plugins.txt isn't included at all), so wiring B2S in means new static-linking plumbing modeled on iOS/Android's __LIBVPINBALL__ path, which this project's __STANDALONE__ build doesn't share — a genuinely multi-hour undertaking, and one with no way to confirm it actually renders anything without a real .directb2s-equipped test table, which isn't available. Revisit if/when such a table is available to validate against.
  • Raw HID device input (OpenPinDevHandler/hidapi) — no browser equivalent for real-hardware nudge/plunger boards. Permanent, not a "for now."

Further follow-up work:

  • Real-device gamepad and touch-control validation (see above).
  • Visual confirmation of DMD rendering against a real DMD-equipped table (see above).
  • Pointer-lock UI wiring (fullscreen is done; pointer-lock isn't needed for this game's input model but noted here in case a future feature wants it).
  • Real-world table support beyond self-contained single-file uploads: tables with an external .vbs script override or a Music/ folder are a documented, known-unsupported gap.
  • Further binary-size tuning (the .wasm itself is still ~13MB with -O2; --closure 1 was tried but silently stripped FS.writeFile/readFile/mkdir down to low-level node ops - a real Emscripten/Closure interaction bug worth root-causing before re-enabling, since it broke runtime table loading with no compile-time warning. -sFORCE_FILESYSTEM=1/broad EXPORTED_RUNTIME_METHODS also pull in more than strictly needed. The default table itself is now ~18MB of the ~34MB total, since a real playable demo table is larger than the rendering-test fixture used before).
  • A browser-based (Puppeteer) CI smoke test that actually loads a table and checks for a rendered frame, replacing today's compile-only CI check.

Build

Requires: bison ≥ 3.8.2, curl, git, cmake ≥ 3.25, python3 (for the dev server), a POSIX shell. Emscripten itself is installed automatically by setup.sh. Expect a multi-gigabyte emsdk/ + build/ footprint and a first build in the tens of minutes (subsequent builds are much faster, especially with CI caching).

./scripts/setup.sh        # installs emsdk + bison check, fetches vpinball + libwinevbs at pinned commits, applies patches/
source emsdk/emsdk_env.sh
./scripts/build-deps.sh   # builds SDL3/SDL3_image/SDL3_ttf/FreeImage/libwinevbs for wasm32
./scripts/build.sh        # configures + builds vpinball itself -> dist/vpinball.{js,wasm,data}
./scripts/dev-server.sh   # serves dist/ locally for manual testing

scripts/build.sh --debug produces a build with assertions and runtime-exit-on-return enabled, useful for diagnosing engine startup issues (this is exactly how the current game-loop blocker above was diagnosed).

npm usage

import { loadPinball, attachTouchControls } from '@valknar/vpinball-wasm';

const canvas = document.querySelector('canvas');
const pinball = await loadPinball({
	canvas,
	onProgress: (fraction) => updateMyLoadingBar(fraction),
});

// start() (and requestFullscreen()) must be called from within a user
// gesture, e.g. a click handler - browsers block audio autoplay and
// fullscreen requests otherwise.
startButton.addEventListener('click', () => {
	pinball.start();
	if ('ontouchstart' in window) attachTouchControls({ container: canvas.parentElement });
});

// Optional debug/utility hook: runs arbitrary VBScript against the live
// table, via the same entry point the interpreter's own debug console uses.
pinball.evalScript('DMDWidth = 128 : DMDHeight = 32');

See examples/basic/index.html for a complete working page (loading progress, file upload, touch controls, fullscreen). The published package name/registry (@valknar/vpinball-wasm on this project's Gitea npm registry) is a placeholder pending the first real release — see package.json.

Known limitations

  • Single-threaded only (no pthreads/SharedArrayBuffer) — a deliberate tradeoff, not a gap; see Roadmap.
  • No heavy plugin ecosystem (PinMAME/DOF/FlexDMD/etc.), and the modern plugins/b2s backglass plugin specifically assessed and declined for now (no plugin subsystem wired for this build, no test table to validate against) — see Roadmap.
  • No raw hardware input (real cabinet nudge/plunger boards) — permanent, no browser equivalent.
  • Keyboard input, audio, and VBScript-driven gameplay are confirmed working end-to-end by hands-on manual testing (not just code review). Gamepad input and the touch-control overlay are code-complete and use the identical input pipeline, but are not yet confirmed on real gamepad/touch hardware — see Roadmap.
  • DMD rendering is native, code-complete functionality riding the same proven VBScript-dispatch path, but not yet visually confirmed since the bundled default table has no DMD-configured Flasher — see Roadmap.
  • .wasm/asset size is ~34MB total (a real playable default table is larger than the rendering-test fixture used earlier in development) and not fully tuned — see Roadmap.

Licensing

Visual Pinball itself is under a mixed license: the project has been migrating file-by-file from a legacy "old MAME"-like license to GPLv3+ since October 2020; each GPLv3+ file is marked // license:GPLv3+ at its top, and any file without that marking remains under the legacy license. See vendor/vpinball/LICENSE (fetched by setup.sh) for the authoritative text — do not treat this README as a substitute for reading it before redistributing built artifacts. libwinevbs is LGPL-2.1 (Wine-derived) with a handful of small ATL header stubs of less certain provenance (see its own README.md). This project's own glue code (CMake integration, patches, npm wrapper) has no license conflict with either, but the combined built artifact's distribution terms are governed by vpinball's and libwinevbs's licenses, not just this repository's.

Attribution

  • Visual Pinball — the engine this project ports.
  • libwinevbs — the real VBScript interpreter (Wine-derived), compiled here to wasm32.
  • Wine — original source of the VBScript/OLE Automation engine libwinevbs extracts and packages.
S
Description
Visual Pinball's real engine, compiled to WebAssembly — real .vpx tables, real VBScript table logic, real WebGL2 rendering, in the browser.
Readme
133 KiB
Languages
Shell 58.8%
TypeScript 41.2%