How it works
These beads are 3000 particles of liquid simulated with SPH (smoothed-particle hydrodynamics) in its position-based form, the family that includes Position Based Fluids (PBF). It runs on the CPU in plain JavaScript, in about 2.1ms per frame. The idea that makes it look like liquid metal is surface tension: the particles pull on each other wherever the liquid is thin. A bead that your cursor cuts in two snaps into two rounder beads, wobbles, rolls back into its dimple in the tray and merges again. Where liquid ends up lying across the ridge between two dimples, the ridge parts it, so the tray keeps all of its beads however long you play. Your cursor is also a small lamp over the tray: every bead reflects it, and the liquid you pass drifts after it. The GPU does only the rendering. It turns the particles into a smooth metaball height field and lights it like chrome in a photo studio, or like a water drop acting as a lens on linen.
Pipeline (per frame)
CPU · typed arrays · lengths in h, the SPH kernel radius JS ≈ 2.1ms at 3000 particles
pointer wake: liquid near this frame's path eased toward the pointer's velocity (a capped blend)
lamp: a critically damped follower of the pointer, about 0.15s behind
dimples 7 drifting Gaussian bowls (5–6 below 2850 particles), soft-max'd so ridges part them;
each bowl's depth follows its deficit against a target share → force grid 48×28 → bilinear
bridges a bead with ≥6% of itself in a second bowl's basin: its particles pulled to their own dimple,
and those with a neighbour across the ridge marked for the ridge knife
┌ substep ×2 at 60 Hz (Δt = 1/120s), ×1.5 with Extra substeps; more when k·max(1,τ)·Δt²·ρ0^1.5 > 0.9 ┐
│ at most 10000 particle-substeps per frame: beyond that the frame simulates less time (slow motion) │
│ integrate v += Δt·dimple pull, × tray friction; x_prev = x; x += Δt·v │
│ grid counting sort into h×h cells (≈60×34); half stencil → ≈67k neighbour entries │
│ relax Gauss-Seidel, per particle: ρ = Σ(1−r)² ρn = Σ(1−r)³ Clavet 2005 │
│ P = k(ρ−ρ0), ×tension where negative (cohesion); Pn = 0.4k·ρn (always repulsive) │
│ each neighbour pair moves ½·Δt²(P·q + Pn·q²) apart, half each way (q = 1−r) │
│ knife strip of half-width R + pointed nose 3R long: particles eased sideways │
│ ridge marked ridge-line particles eased apart at 2.5 h/s, each toward its own dimple │
│ walls; v = (x − x_prev)/Δt │
└────────────────────────────────────────────────────────────────────────────────────────────────────┘
XSPH once per frame, every neighbour pair blends toward its mean velocity Monaghan 1992
clusters union-find on the neighbour lists: beads under ~10 particles fade; each bead → a dimple
depth surface = density deficit + lopsided neighbourhood; 3 sweeps of d = min(d, d_j + r_ij)
upload (x, y, depth, weight) per particle, Float32 → instanced vertex buffer (48 KB)
GPU · canvas 2560×1440 (DPR 2) 11 draws on Mercury/Gold, 5 on Water
SPLAT fine N octagons, r = 3.2 spacings (50px), additive, MRT ─▶ F RGBA16F 1280×720 (w, ∇w)
─▶ D RGBA16F 1280×720 (w·d, d·∇w)
SPLAT coarse N octagons, r = 159px ─▶ G RGBA16F 160×90 (w, ∇w)
BROAD DOME H+V 9-tap blur of ∇G, σ = 5.5% of short side ─▶ G′ RGBA16F 160×90 (w, ∇w + 0.9·blur)
DISPLAY edge distance (f−iso)/|∇f|, smooth-min'd with the depth D/F → rim + G′ dome → normal
chrome/gold: perspective reflection of a procedural studio and the cursor lamp, every
light filtered to the pixel footprint, Fresnel, sun glint, soft shoulder
─▶ RGBA8 2560×1440 + excess
water: refract the tray (mipmapped weave), Fresnel, dark far rim, caustic ─▶ canvas
tray: weave 512² RGBA8, shadow + AO from G′ (B-spline), skipped where no bead is near
BRIGHT ¼ res: 4×4 box of the display's over-white excess ─▶ RGBA16F 640×360 (dark only)
BLUR ×4 H+V 9-tap linear-sampled Gaussian, radii 1.6 and 3.3 texels × short side / 1440
COMPOSITE display + bloom × Glints, ±½ LSB dither ─▶ canvas RGBA8
The ideas that matter
- SPH, solved on positions. Classic SPH (Müller et al. 2003) computes a pressure force from density and integrates it. Near water’s incompressibility that needs very small time steps, or the liquid bounces. Position Based Fluids (Macklin & Müller 2013) instead treats “density = rest density” as a constraint and corrects positions with Lagrange multipliers over 2–4 Jacobi iterations. It adds an artificial pressure,
s_corr, that stops clumping and gives a surface-tension look. This page uses the older relative of PBF: Clavet, Beaudoin & Poulin’s double-density relaxation (2005). Each substep is one Gauss-Seidel sweep. A far densityΣ(1−r)²gives a pressure that turns negative where the liquid is thin, and that negative pressure is the cohesion. A near densityΣ(1−r)³gives an always-repulsive pressure that doess_corr’s job. Velocities come from the position change, so the sim is stable at 1/120s steps. Viscosity is XSPH, applied pair by pair so momentum is conserved, once per frame with the frame’s time step. - Why the research picked FLIP/APIC for the GPU, and why CPU SPH works here. WebGL2 has no compute shaders and no atomics. Finding each particle’s neighbours on the GPU means sorting particles by grid cell with a sorting network drawn in fragment passes: k(k+1)/2 passes for 2k particles, which is 136 render passes for 65,536. Each pass is a Metal render pass under ANGLE and a tile-memory flush on phones. The research estimates 2–4ms per sort per step (see
research/particle-fluids.md). FLIP, APIC and MPM avoid neighbour search entirely. They scatter particles to a grid with additive point blending and gather back with bilinear fetches, which is how WebGL FLIP reaches about 100k particles. That is the right tool for a full-screen ink wake. Beads are different. A few thousand particles is enough because the renderer smooths the surface, and surface tension, the one behaviour this effect needs, comes naturally to SPH and not to the grid methods. At this size the CPU is the better neighbour-search machine. A counting sort into a uniform grid is O(N). The half-stencil pass finds every pair once, about 34k pairs per substep, in about 0.27ms. Sequential Gauss-Seidel, which converges fastest, is natural in a loop and awkward on a GPU. Only 48 KB per frame (one vec4 per particle) crosses to the GPU. - Enough neighbours to be a liquid. At about 12–16 neighbours per particle the particles lock into a lattice and the “liquid” is an elastic solid. In a test, a 3:1 bead relaxed to 2.1:1 and stopped there, even with viscosity and friction off. Long tails dragged out by the cursor never retracted. At rest density 4 (≈22 neighbours) the same bead is round (1.15:1) within 1s and wobbles, and the tails pull back in. Rest density is a slider from 3.4, just above the strand regime, to 5. Higher values give smaller, smoother beads and cost more CPU: above about 4.3 the stability limit below asks for a third substep.
- Enough particles in every bead. A bead of about 100–120 particles packs into a hex crystal: near-heptagons with flat sides and diamond-shaped reflections, which no amount of smoothing in the renderer rounds off. So the tray has as many dimples as the particle count can fill with at least 190 particles each: all seven from about 2850 particles, six down to about 2280, and five below that, which covers the phone default (2000), the gallery thumbnail (1600) and the slider’s minimum (1500). Phones also default to slightly more surface tension (1.2), which rounds small pieces faster.
- A knife, not a brush. The cursor is a moving kinematic obstacle: a thin strip of half-width R along this substep’s stretch of the pointer’s path. Particles inside are moved out sideways. A round-nosed capsule was tried first. It shoved particles on the stroke axis a full radius in one substep (≈150 h/s) and plowed them ahead, so cut beads became long slugs and spray. A pointed nose 3R long eases particles aside by about a third of the blade’s travel per substep, so a bead parts cleanly. Speed matters, as it does with real mercury: a fast stroke (about one screen width per second) splits a bead in two, and a slow one only parts it and the liquid heals behind the cursor. The intro ghost stroke is fast for that reason, and it runs through the two biggest beads and the one between them. A still cursor is a small disc, so the liquid flows around what you are pointing at and never covers it. The blade is a fraction of the screen’s short side, a little wider on phones, where the beads hold fewer particles and a thinner blade slipped between them.
- The cursor is felt everywhere, not only where it cuts. Most of the tray is open, so moving through it used to change nothing. Now the cursor is a small lamp hovering over the tray. It follows the pointer about 0.15s behind (a critically damped spring), and every mirror bead shows it as a small highlight that slides around the bead as you move, wherever the cursor is. A faint pool of its light trails it across the dark tray. Liquid within about a tenth of the screen of the cursor’s path is also eased toward the pointer’s velocity, a capped blend rather than a push (the same rule as the reference fluid’s grip), so the beads you pass lean and drift after the cursor as a wake before their dimples roll them home.
- Gravity is a dimpled tray, with ridges. Seen from above, “gravity” is the pull of seven shallow bowls, sampled from a coarse force grid. The first version summed the bowls, so the tray between two dimples was a flat saddle. A bead dragged across it stretched into a dumbbell with a lobe in each dimple and never broke. Now each point of the tray slopes toward whichever dimple is deepest there (a soft-max of the bowls,
Σ w⁴·F / Σ w⁴), so dimples are separated by real ridges. Each dimple also has a target share of the liquid. Every bead, found as a connected cluster, counts toward the dimple nearest its centre. The smoothed deficit deepens an emptied dimple and makes an over-full one shallower, which moves the ridge into the over-full bead. Pieces you cut still roll home and merge. Over the 2.2s before the loop’s 8s idle stop, the tray’s friction ramps up, so the beads settle instead of freezing mid-wobble. - Ridges cut bridges. Ridges alone were not enough once the beads grew to fill more of the screen. In 2D a liquid neck never pinches off by itself, because its surface tension does not weaken as it thins (there is no Rayleigh–Plateau instability in a plane), and the cohesion here acts like a stiff constraint, roughly a thousand times stronger than the dimple pull. A gentle force, even one pulling each lobe toward its own dimple, could not beat it. In 20s of fast sweeps across the whole tray, the beads merged into a few big dumbbells and puddles that held for good, leaving three to six dimples empty. So the tray now cuts its own bridges. Every frame, each particle is assigned to the basin of the bowl that is deepest where it sits. A bead with at least 6% of itself in a second basin is a bridge. Its particles are drawn toward their own dimples, and the ones with a neighbour across the ridge are eased apart at 2.5 h/s each substep: a slow knife along the ridge. Liquid spilling over a ridge from an over-full bead is cut off the same way and rolls into the emptier dimple. In six runs of the same 20s test the tray came back to all seven beads within 3–8s, each within about a third of its share, most within a quarter. While a bridge is being parted the loop stays awake (for up to 30s after the last input) and the calm before the idle stop waits for it.
- Domes from the particle graph. Shading needs to know how far each pixel is from the bead’s edge. Near the silhouette,
(f − iso)/|∇f|from the metaball field is exact. Deeper in, it overshoots as the field saturates, and the whole rim gets squeezed into a few pixels, which shows up as a hairline outline. So the CPU also computes each particle’s distance to the surface through the neighbour graph. Surface particles are the ones with a density deficit and a lopsided neighbourhood, so a momentary low-density pocket inside a bead does not dent it. Three sweeps ofd = min(d, d_j + r_ij)carry that distance inward. It is splatted as a weighted average, smooth-min’d with the edge distance, and fed into a rim profilesin θ = (1 − u)1.6. That profile is vertical at the contact line, like a real bead, and meets the top without a crease. - A broad dome, so big beads are balls, not dishes. On top of the rim, the bead is domed by the slope of the coarse field. But that slope fades inside any bead much wider than the coarse kernel, so the middle of a big bead was a flat plateau. A mirror shows a plateau ringed by its tilted edge as a dimple, like a blood cell, and it showed the softbox as a grey satin patch. Now the coarse field’s gradient is blurred once more (σ = 5.5% of the screen’s short side) and 0.9 of it is added to itself, so even the biggest bead is domed all the way to its middle. That costs two passes over a 160×90 texture. A first try blurred the field’s value and took screen-space derivatives of it. Half-float precision made those derivatives noisy, and the softbox’s edges came out frayed, so the gradient itself is blurred instead.
- Analytic gradients. Every splat writes its kernel
(1 − q²)³and the kernel’s exact gradient. Normals therefore come straight from the summed field, with no finite differences and no texel-sized facets, which a mirror would show plainly. The coarse field is upsampled 16× with a cubic B-spline built from four bilinear taps (Sigg & Hadwiger), so its dome and shadows have no texel diamonds. Splats are octagons drawn as six triangles around the kernel’s disc, which covers 17% fewer fragments than a quad. - Chrome is a studio, not a colour. A mirror bead shows its surroundings, mapped from the centre outward: an overhead softbox, the dark ceiling, a soft wall band above the horizon, then the tray right at the edge. That gives the bright window, the dark body and the dark contact line that read as liquid metal. A hot key light and a tall strip light add the glint and the crescent on the right edge. Gold uses the same studio, warmer, with F0 = (1, .77, .4) and a dimmer key. Several details keep the studio from looking computer-made. The camera has a slight perspective, so each bead sees the softbox from where it sits, and the window lands in a different place on every bead. The softbox is a crisp window with rounded corners, as a real diffuser frame photographs, hotter at the key-light end and falling off across its diffuser inside a wide, dim spill. Reflections above 0.8 pass through a soft, hue-keeping shoulder, so a gold highlight stays gold instead of clipping to a white disc. The tray seen in the contact line stays close to the tray’s own tone, and the occlusion ring is kept tight on the dark trays, so the beads do not look outlined.
- Thin reflections are filtered, not sampled. Near a bead’s edge the normal turns through 60° in a few pixels, so the strip light and the horizon band shrink to about 1.4px at DPR 1.5. Sampled as hard-edged boxes, they broke into dashes that crawl as the bead moves. Every light’s edge is now widened to the pixel footprint of the reflection,
fwidth(R.xy / R.z), taken before any branch so the derivatives are valid. Once that footprint is larger than a light, the light also dims by its size over the footprint. Without that, the widened boxes all smeared to about 0.5 at the silhouette and added up to a bright hairline. The sun glint and the cursor lamp are Gaussian lobes widened the same way, with their energy kept. At DPR 2 nothing changes. At DPR 1 to 1.5 the rims become soft, continuous lines. - Bloom from the picture, not from a second render. The glow used to come from re-shading the beads at ¼ resolution. There a thin rim highlight is sampled at full strength, so phones showed a grey halo beside highlights that the full-resolution image barely had. Now the display writes HDR with the “brighter than white” excess in alpha. A ¼-res pass averages each 4×4 block of it with four bilinear taps, so a highlight too small to see is too small to glow. Two H+V blur passes give it a round falloff, and their radii scale with the screen’s short side, so a phone’s small beads get a glow to match. The glow cannot appear where the image has no highlight, and the dark tray never hazes.
- Water is a lens. The drop refracts the linen under it toward its own centre, which magnifies the weave and compresses it at the rim. Those lookups jump between distant texels where the lens compresses the view, so the weave is mipmapped and sampled with
textureGrad, with derivatives taken before the branch. The first version still showed wobbly weave in big drops. That was not noise: plotting the offset field showed it was smooth but reached 60px, so any curvature in the dome bent the threads. The offset is now at most about 0.6 rim widths, and inside the drop it follows the coarse field’s smooth dome normal instead of the rim’s. Clear water also should not look grey. Absorption is a faint Beer–Lambert term, about 2% in the thickest drop with the near-white default tint, so drops keep the linen’s colour. The cloth under a drop gathers a little focused light, so the centre reads slightly brighter than the open cloth. Light passes through water, so the shadow and AO belong outside the footprint. A crescent of focused light (the caustic) sits just inside the far rim and spills into the shadow beyond. The rim is dark on that far side and catches light on the near side. On a dark tray clear water shows only by what it reflects, so there its reflections are boosted; the Water material is made for the light linen. - No dust. A few particles flung off a bead would render as specks on the dark tray. After each frame, a union-find over the neighbour lists finds every connected cluster (about 0.2ms). A particle’s splat weight eases toward
smoothstep(4.5, 10, cluster size), so a cluster of a handful of particles drops cleanly below the iso level. A droplet that touches a bead swells in over about 0.2s instead of popping. The same clusters tell the tray which bead belongs to which dimple. Every particle starts inside a dimple’s bead, so the first frame has no stray droplets. - Stable at any setting. Every slider extreme is safe. The solver adds substeps whenever
k·max(1, tension)·Δt²·ρ0^1.5would pass 0.9, a limit found by stress tests. It is dt-based throughout, so a 120 Hz display runs one substep per frame instead of two, at the same speed. The Extra substeps control runs 1.5× as many at any refresh rate. A frame does at most 10000 particle-substeps (3 substeps at 3000 particles, 2 at 4000). When a slow frame or the stiffest settings ask for more, it simulates less time at the stable step instead: a moment of slow motion rather than an explosion, and the cost never snowballs into the next frame. Surface tension stops at 0.2: below that, nothing holds the liquid together and it expands like a gas until it is too thin to see. Bead depth stops at 0.25, where a bead is still a shallow lens; at 0 it was a flat disc. - One dead end worth knowing. Akinci-style curvature surface tension,
−γ Σ(ni − nj), was added and then removed. It always pushes surface particles into the bulk, which rounds convex drops but grows any void. Paired with the soft pressure here, it turned the liquid into foam. Cohesion that also closes voids has to be an attraction, which here is the negative pressure.
Parameters
Presets
Performance & compatibility
- Measured by the harness (Chrome, ANGLE-Metal, Apple M5 Mac, 1280×720 at DPR 2, so a 2560×1440 canvas) during its pointer sweep, on the default Mercury preset: GPU 2.5–5.1ms mean / 4.0–7.0ms p95, JS 2.6–3.3ms mean, a steady 60 fps. The range covers six full runs made one after another on a machine shared with other builds (load average 2.2–4.0); p95 stayed under the 8ms bar in all of them. An interleaved A/B against the previous version of this page (16 rounds under the same load) measured the same cost, 4.7ms GPU and 2.7ms JS mean for both, even though the beads now cover 17% of the tray instead of 12%. The coarse field at 1/16 resolution, octagon splats, two bloom blur passes instead of three, and skipping the shadow lookups on open tray paid for the bigger beads. Per-preset sweeps, interleaved, mean / p95: Mercury GPU 3.5 / 6.1ms, Gold 3.2 / 6.2ms, Water beads 3.9 / 7.6ms, JS 2.5–2.6ms.
- Where the JS goes (300 frames of solver work timed synchronously in the page, 3000 particles, 2 substeps): per substep the neighbour grid 0.27ms and the relaxation about 0.28ms, then XSPH once per frame 0.2ms, the speck clusters 0.22ms, surface depth 0.25ms, dimple forces and bridges 0.1ms, and 0.27ms to fill the vertex buffer and issue the draws. That is about 2.1ms in all. The pointer’s blade, wake and lamp and the shell’s own bookkeeping make up the rest of the harness figure. Cost grows with the work: 1.0ms at 1500 particles, 1.4ms at 2000 (the phone default), 2.8ms at 4000 (the maximum). Extra substeps and stiffness 3000 each cost 2.3–2.4ms and rest density 5 costs 3.0ms, because each needs a third substep. The costliest corner, 4000 particles at rest density 5, is 3.4ms. With every Liquid slider at its maximum the solver would need 7 substeps a frame; the work cap runs 2, so that liquid moves at 2/7 speed for about 2.2ms, instead of about 8ms at full speed.
- What the GPU spends. The fine splat rasterises about 6M fragments into two RGBA16F targets, and the coarse splat under 1M into a 160×90 target. Two passes run at full resolution. The display does about 14 texture fetches per pixel for metal, 7 on open tray far from every bead (no shadow can reach there, so those lookups are skipped), and about 48 for water drop pixels, which evaluate the tray twice, once through the lens. The composite (dark metal only) does 2 fetches per pixel. The display writes an RGBA8 image with the bloom excess in alpha, so the extra full-resolution round trip moves 15 MB, not 30 MB. Memory is about 35 MB: two 1280×720 RGBA16F fields, three 160×90 coarse fields, the 2560×1440 RGBA8 image, two 640×360 bloom targets and a 1.4 MB mipmapped weave.
- Requirements. WebGL2 with
EXT_color_buffer_float, for additive blending into half-float targets with two attachments (MRT). Nothing needs 32-bit float blending (EXT_float_blend), which many mobile GPUs lack. Without either, the page shows a message card over the poster frame. - Mobile. Drag to slice. On coarse pointers the canvas is capped at 1.5× DPR (585px wide on a 390px phone) and the default is 2000 particles in five dimples, so the smallest bead still holds about 310 particles and stays round. Surface tension defaults to 1.2 and the blade to 2.4% of the short side there, and the lamp shines only while a finger is down. Sizes follow the short side, so a portrait tray keeps its bead sizes, and its dimples rotate to run down the long axis. Highlights are filtered to the pixel footprint, so the rims stay continuous at 1.5× DPR, and the bloom radius shrinks with the short side to match the smaller beads. The harness measured a 55 fps touch drag at 390px. It emulates the phone on the desktop CPU and GPU, so this measures the pipeline at phone size, not phone hardware.
- Resize. Lengths are in h, the physics scale, so a resize never stretches the liquid. Each bead moves rigidly so that its centre keeps its place in the tray, and on a landscape/portrait flip the liquid is transposed along with the dimples.
- Idle and visibility. The loop stops 8s after the last movement (measured: idle at 8.04–8.09s, zero frames after). Friction eases in over the last 2.2s, so the beads come to rest first. While the ridges are still parting a bridge, the loop stays on, for up to 30s after the last input. It pauses off-screen and in hidden tabs. The gallery embed runs the ghost stroke forever at DPR 1 with at most 1600 particles in five dimples. Its tray is a little fuller (19% covered instead of 17%) and its centre glow a little brighter, so the beads fill the small frame.
- Reduced motion. The fast intro slice and 1.9s of merge-back are simulated off-screen and shown as one still frame, with a “Play anyway” button. That is 4.5s of physics, about half a second of main-thread work. The still is rebuilt after a resize or a control change; while a slider is being dragged it is rebuilt once, on release, instead of on every step.
References & credits
- Simon Clavet, Philippe Beaudoin, Pierre Poulin, “Particle-based Viscoelastic Fluid Simulation”, SCA 2005: double-density relaxation, the solver used here. doi.org/10.1145/1073368.1073400 (paper).
- Miles Macklin, Matthias Müller, “Position Based Fluids”, SIGGRAPH 2013: the density constraint,
s_corrand XSPH in the position-based setting. mmacklin.com/pbf_sig_preprint.pdf (paper). - Matthias Müller, David Charypar, Markus Gross, “Particle-Based Fluid Simulation for Interactive Applications”, SCA 2003: interactive SPH. matthias-research.github.io/…/sca03.pdf (paper).
- J. J. Monaghan, “Smoothed Particle Hydrodynamics”, Annu. Rev. Astron. Astrophys. 1992: SPH, including the XSPH velocity correction. doi.org/10.1146/annurev.aa.30.090192.002551 (paper).
- Simon Green, “Particle Simulation using CUDA”, NVIDIA 2008: uniform-grid neighbour search by sorting particles into cells. developer.download.nvidia.com/…/particles.pdf (whitepaper).
- Logan Zartman, Wavescape: the WebGL2 SPH (odd-even merge sort in fragment passes) behind the GPU cost comparison. github.com/loganzartman/wavescape, MIT. Not used here.
- Christian Sigg, Markus Hadwiger, “Fast Third-Order Texture Filtering”, GPU Gems 2 ch. 20: the B-spline from four bilinear taps. developer.nvidia.com/gpugems (book text, free online).
- Daniel Rákos, “Efficient Gaussian blur with linear sampling”, 2010: the 9-tap bloom weights. rastergrid.com/blog/… (article).
- Inigo Quilez, “Smooth minimum”: the polynomial smooth-min that blends the two edge distances. iquilezles.org/articles/smin (article).
- Dither hash: Dave Hoskins, “Hash without Sine”. shadertoy.com/view/4djSRW, MIT.
- Research in this library:
research/particle-fluids.md(the SPH/PBF and FLIP/APIC cost analysis and thepbf-mercury-beadsbrief) andresearch/rd-metaballs-sdf.md(metaball edges, chrome studio and Fresnel values). Engine lessons come from the stable-fluids cursor trail in the Russ Hype Machine page: dt-based steps, a splat along the pointer’s segment, crisp edges with no haze, and dither. All code on this page is written from the papers; none is copied.