How it runs so smoothly
Ooh Bubbles simulates up to a couple of hundred soap bubbles — each with its own film thickness, wobble, colour, and pop — and draws them at your screen’s full native sharpness, aiming for 60 frames a second (or 120 Hz on supported displays) in an ordinary browser tab. When a device can’t hold pace, it sheds bubbles rather than lowering resolution.
On this page
Off-thread physics worker & native WebGPU render loop
Page thread
- Input · Audio · UI chrome
- Native-pixel governor
- WebGPU / WGSL (+ WebGL2)
- 1-pass HDR · 6 HDRI worlds
Draws every frame smoothly
CommandRing (SAB)
Page → Worker · lock-free
Binary snapshots
Worker → Page · 181 KB rows
Physics worker
- Rust → WASM (libm only)
- SIMD128 & Relaxed-SIMD
- Deterministic thread pool
- Contacts · Wobble · Smoke
Steps world at 1:1 real time
Physics in Rust, compiled to WebAssembly
The simulation began in TypeScript. As real physics accumulated (thin films, contact clusters, solenoidal wind, volumetric smoke, rupture events, methane combustion, and freezing), hot loops began eating the frame. Moving the core numerical kernels into pure Rust compiled to WebAssembly with SIMD delivered large, measured wins: the wind field dropped from 26–28% of a busy main thread to 6–7% at 300 bubbles; bubble wobble fell from 11–15% to 2–3.5%; and a single field-filling kernel dropped from 4.3 ms to 0.98 ms.
Keeping physics completely free of renderer imports also lets it run off the page thread on a deterministic thread pool — scheduling only changes which helper computes a chunk, never item order or floating-point arithmetic within it.
- Pure Rust core:
crates/bubbles-core(strict#![no_std], zero heap allocations) andwasm/hold the kernels: solenoidal wind with SIMD bubble-to-bubble wakes, internal 3D smoke convection and CFL-bounded vorticity confinement, film thickness and soap chemistry, Lamb wobble, Weber aerodynamic breakup, contacts (broad phase, small QP solver, warm starts), thin-shell ice buckling and shock fracture, methane combustion, and the rupture/spray event engine. Its only dependency islibm, built with full LTO and a single codegen unit. - Pinned, reproducible builds: Nothing compiled is committed to Git.
scripts/build-wasm.mjspins rustc, verifies rustup downloads by SHA-256 on Cloudflare Pages, requires SIMD128, and post-optimises with pinned Binaryenwasm-opt. - Capability-dispatched flavours: Builds emit serial and threaded variants in both baseline SIMD128 and hardware FMA Relaxed SIMD. A tiny 42-byte
WebAssembly.validateprobe selects the single fastest variant your browser supports, so only one kernel ever downloads. - Cross-origin isolated shared memory: Every response sets COOP
same-originand COEPrequire-corpto unlockSharedArrayBufferand WASM threads. Every worker carries a-coep-filename marker verified by the release gate. Commands flow through a lock-free ring buffer and compact snapshots return cleanly (rows shrank from 1.29 MB to 181 KB). - Deterministic checkpoints: Versioned state snapshots let us capture a chaotic scene once and replay it bit-identically when benchmarking a change.
Native WebGPU, WGSL & lightweight WebGL2 fallback
Early builds rendered through Three.js and WebGL2. In PR #279 the primary renderer moved to raw WebGPU with hand-written, Naga-validated WGSL shaders on a single shared GPU device — deleting Three.js completely and cutting the median 3840×2160 Studio frame with 200 bubbles from 28.2 ms to 21.4 ms. For browsers without WebGPU, the engine ships a lightweight 22-shader WebGL2 fallback (still zero Three.js).
By default, a frame runs as a tight 1-pass HDR pipeline (drawing the studio backdrop or active 360° photographic HDRI directly inside the bubble MRT pass whenever lens effects are off, with analytical silhouette anti-aliasing instead of costly MSAA): thin-film colour lookup tables computed on the GPU (rebuilding asynchronously only on soap-recipe switch for Lorentz–Lorenz glycerol dispersion, 0.00 ms/frame steady state), 1-pass octahedral film compute with buoyant marginal-regeneration plumes and ice-rigidity locking, reflections and particle spray sharing render passes on mobile tile GPUs, lazy-loaded volumetric fireballs and GPU-deposited 3D smoke (with mobile worker budget caps) only when active, optional half-resolution depth of field and multi-level bloom, and final AgX tone mapping with dither.
Measuring the GPU honestly & testing shaders
- Timestamp queries: Pass markers use tiny compute dispatches so Safari on iPhone records real timings (empty timestamp passes return zero on iOS WebKit).
- Distrusting lying timers: Some GPU driver stacks report 2–10× real cost. If 90% of frames arrive on time while GPU timestamps claim an overrun across two consecutive 120-frame windows, the engine marks the timer untrusted (
timerTrusted = false) and steers by wall clock instead. - Headed runs on real displays: Headless browsers distort frame pacing. Measurements run in visible browsers on real 60 Hz and 120 Hz screens, alternating baseline and candidate variants in the same run while asserting that pixel ratio and canvas dimensions never drift.
- Optical & WGSL verification: GPU tests pin the thin-film lookup table within
0.005per channel of a 64-band spectral reference (0.02across crossed films) and within2/255after final sRGB composite. Every WGSL module and specialization constant is validated through Naga (MSL, SPIR-V, HLSL) in CI.
The governor: shed bubbles, never pixels
When hardware falls behind, many web apps silently shrink the canvas and upscale it into mush. Ooh Bubbles never lowers resolution: it always draws at your screen’s full native pixel ratio. Instead, a pacing governor watches sustained medians (at least a second of frames, counting a frame late past 1.25 budgets) and sheds work in strict priority order:
- local soap-flow surface detail on the most prominent bubbles,
- post-processing effects, step by step,
- off-screen bubbles,
- visible bubbles, down to a device-class floor.
Recovery runs in reverse, slowly and gently, so a single OS hiccup never causes oscillating quality. When a frame’s CPU budget cannot afford every nominal 1/240 s physics tick, FrameStepper smoothly coalesces ticks (up to 1/60 s) so motion keeps 1:1 real-world time instead of slipping into slow motion.
| Device class | Starts with | Probes up to | Sheds down to |
|---|---|---|---|
| Phone | 55 | 120 | 45 |
| Tablet | 100 | 180 | 100 |
| Desktop | 60 | 225 | 55 |
| Strong desktop GPU | 100 | 250 | 55 |
Ceilings tighten automatically on ultra-high-pixel displays: on a 5K desktop monitor, 225 bubbles held 87–98% of frames on time whereas 300 managed 29–88%, setting the desktop cap. Phones are identified by coarse touch pointer plus short screen side rather than GPU feature flags (because iPhone Safari exposes desktop-like features). If a phone still struggles at its floor with effects off, a one-way lite tier keeps full native sharpness while switching to a slim thin-film pipeline and dropping bloom.
Starting fast, and beating Safari’s freezes
WebGPU pipelines must compile before drawing, and full thin-film optics shaders are substantial. To get live bubbles on screen immediately:
- The initial HTML preloads the engine script, capability-matched WASM kernel, and physics worker in parallel during parsing.
- The zero-blur Prismatic Studio Aperture wand loader (
< 12 KBinlined) paints from frame zero and dissolves smoothly via GPU-only opacity and transform once live bubbles are ready. - A slim fast-start pipeline renders full-resolution bubbles first while full-optics specializations and optional passes (bloom, depth of field, fireballs) compile progressively in the background.
Deep dive: Safari compile fencing & cutting iPhone cold start from 25 s to 5.7 s
The Safari freeze: Early tests on a real iPhone ran smoothly at 60 Hz for 11–13 seconds, then collapsed to 0.2 fps with multi-second stalls. Safari blocks the GPU process on every shader compile — even async ones — taking ~4 s per full-optics variant. Every stall tricked the governor into stepping down, which triggered even more compiles. The fix is compile fencing: on serialized-compile browsers, startup compiles a single optics tier paced one compile per presented frame, lower tiers reuse it, and no surprise variants compile mid-play.
Cutting cold start: Uncached cold WebKit previously waited on 2 fast pipelines plus 9 full ones (~25 s on a real iPhone). Splitting startup timing diagnostics (#1398), booting physics before the first-light GPU fence (#1400), and pruning full-optics shaders into one shared general program (#1407) cut cold iPhone reveal from ~25 s to ~5.7 s, while later cold-Metal specialization work (#1939, #1945), per-bubble birth-shader pinning (#1988), and desktop mode-switch compile elimination (#2004) brought real-device iPhone cold reveal down toward ~3.2 s with zero mid-session compile freezes. Opening any page with ?bootReport=1 captures a real-device startup timeline.
Keeping it small: release gates & Brotli budgets
Every production build ends with scripts/check-dist.mjs, a hard release gate that blocks deployment if any cached asset in assets/ lacks a content hash, any worker lacks -coep-, WebAssembly is embedded in JavaScript, or 32 KiB+ of code is duplicated across chunks. Brotli transfer budgets are tracked as warnings so correctness and 60 fps performance always win:
| Transfer budget (Brotli) | Target limit |
|---|---|
Player page initial JS (index.html) |
57 KiB |
| Player page initial JS, CSS & fonts | 210 KiB |
Engine initial JS (simulation/index.html) |
685 KiB |
| Engine initial transfer | 690 KiB |
| Startup WebAssembly (single selected variant) | 410 KiB |
These Field Guide pages live completely outside the simulator’s module graph and share the player’s already-cached variable fonts, adding zero bytes to the simulator’s startup path.
How we got here
- 22 SepFirst commit: physically based soap bubble simulator ray-traced in WebGL.
- 1–2 OctWind and wobble move to Rust/WebAssembly; Cloudflare Pages builds compile Rust from source (#28).
- 6–7 OctBatched SIMD kernels, dedicated physics worker, and deterministic thread pool (−17.7% frame time with 4 threads).
- 12 OctGovernor fixed to require real late frames (5K on-time frames 51–77% → 100%, #233); GPU thin-film lookup table (−26% frame time, #237).
- 13 OctRaw WebGPU & WGSL replace WebGL/Three.js (#279); single startup kernel download (#333); Binaryen optimisation (#352); sustained-median governor (#368).
- 15–18 OctNative pixels always (#1029), wand loader & fast-start pipeline (#1121, #1128), Safari compile fencing (#1153), and dedicated phone & lite tiers (#1169, #1185).
- 20–22 OctSpray capture by neighbouring bubbles (#1393); iPhone cold start slashed from 25 s to 5.7 s (#1398, #1400, #1407).
- Nov 2026Composable Smoke, Fire & Frost physics pillars, Oval Wand Rayleigh–Plateau pinch-off, six CC0 360° photographic HDRI worlds, and lightweight 22-shader WebGL2 fallback.
- 30 Nov–1 DecRelaxed-SIMD FMA kernels (#1922), qualified 273–313 K PG/water aerosol chemistry (#1927), GPU-resident smoke deposit (#1897), and cold-Metal TTI / frost GPU / dense-foam breakthroughs (#1939, #1945).
- 2 DecFirst-principles physics wave & zero-freeze compiles: per-bubble birth-shader pinning (#1988), desktop mode-switch compile elimination (#2004), full −30 °C T/P thermodynamics, Bergeron–Findeisen hoarfrost, Zoelly–Timoshenko/Pogorelov ice buckling & flame plumes (#1997), calibrated pursed-lip Blow round jet & Weber breakup (#2009), Lorentz–Lorenz glycerol optics & buoyant marginal-regeneration plumes (#2010), direct Thermal Herder playability & contextual cues (#2011), continuous 3D internal smoke swirl & Taylor–Culick burst vortex rings (#2014), speed-of-sound acoustic shockwaves (#2012), and SIMD bubble-to-bubble aerodynamic wakes (#2017).