Skip to content

176 web animation techniques, each a live demo with plain settings and a ready-made prompt for your AI assistant. No dependencies, no build step.

fix: GPGPU Particle System steps its particles and fades its trails by elapsed time, so it runs at the same speed on every screen

matin0668f8a722d5
diff --git a/animations/06-3d-advanced/gpgpu-particle-system/README.md b/animations/06-3d-advanced/gpgpu-particle-system/README.md
index f4e0cab5..30db8d96 100644
--- a/animations/06-3d-advanced/gpgpu-particle-system/README.md
+++ b/animations/06-3d-advanced/gpgpu-particle-system/README.md
@@ -20,7 +20,7 @@ precision highp float;
uniform sampler2D uPos; // read previous frame's positions
uniform float uTime, uSpeed;
uniform int uBehavior;
-uniform float uStep; // 1, or 1/3 in slow motion
+uniform float uStep; // steps of 1/60 s since the last frame: 1 at 60 Hz, a third of that in slow motion
out vec4 outColor; // write new positions
float hash(float n) { return fract(sin(n) * 43758.5); }
@@ -50,7 +50,9 @@ void main() {
}
```
-**Texture ping-pong** — alternate which texture is the read source each frame:
+**Time step** — the page passes `uStep`, the time since the last drawn frame counted in steps of 1/60 s (capped at 50 ms, and a third of it in slow motion), so the particles move at the same speed on a 30, 60 or 144 Hz screen. A long frame is run as several passes of about one step each, two on a 30 Hz screen: the attractor pulls hard near the middle, and one long step there lets particles overshoot and keep circling instead of settling. The damping `pow(0.985, uStep)` is the right amount for a step of any length, and the trail fade is scaled the same way.
+
+**Texture ping-pong** — alternate which texture is the read source each pass:
```js
// Physics pass: read tex0, write to fbo1 (which wraps tex1)
@@ -86,12 +88,13 @@ void main() {
|-----------|---------|--------|
| Movement | Flow | Flow follows a shifting field of currents; Swirl circles the middle; Attract pulls everything toward the middle; Orbit sweeps the particles round in rings |
| Number of particles | 65,000 | 16,000, 65,000 or 100,000 particles, one pixel each of a texture 128, 256 or 320 pixels square; phones start with 16,000 |
-| Speed | Normal | How hard the rule pushes each frame: slow is 0.35, normal 0.6 and fast 1 |
+| Speed | Normal | How hard the rule pushes for every sixtieth of a second: slow is 0.35, normal 0.6 and fast 1 |
| Color | One color | One blue, a color from each particle's speed, or colors that slowly shift |
| Trails | off | Fades the last picture instead of clearing it, so each particle leaves a streak |
## Production notes
- **WebGL2 required**: `RGBA32F` float framebuffer targets require WebGL2 (or the `WEBGL_color_buffer_float` extension in WebGL1, which is less reliably available). WebGL2 is supported in all modern browsers (Chrome 56+, Firefox 51+, Safari 15+).
+- **Time, not frames**: a fixed step per frame would move the particles twice as fast on a 120 Hz screen and half as fast on a 30 Hz phone, and fade the trails at the same wrong rate. Scale the step and the fade by the time since the last frame, cap that time (this demo uses 50 ms), and split a long frame into passes of about one step so a strong pull near a point stays stable.
- **Three.js `GPUComputationRenderer`**: Three.js includes `GPUComputationRenderer` (in the `three/examples/jsm` path) which encapsulates the entire ping-pong texture pattern. It's the idiomatic production approach.
- **WebGPU compute shaders**: WebGPU provides proper `@compute` shader stages for GPGPU, eliminating the "fragment shader as compute" workaround. As of 2024, WebGPU is available in Chrome 113+ but not yet in Firefox stable or Safari.
- **Wrap only survives a divergence-free field**: this demo's flow field pushes particles away from the x-axis, so it has a net outward drift. An earlier version wrapped at ±1.2 while only ±1.0 is visible; particles drifted into that invisible ring faster than they came back and the canvas faded to black after about ten seconds. Tightening the wrap to ±1.0 only moved the symptom — a divergent field teleports the escapee straight back to the edge it just left, so the particles crust along the top and bottom instead. Respawning escapees at a random point near the middle is the fix, and it is what keeps the population steady here. Nothing throws in either failure, and the first second looks correct in all three versions, so this class of bug is only visible if you leave the demo running.
diff --git a/animations/06-3d-advanced/gpgpu-particle-system/index.html b/animations/06-3d-advanced/gpgpu-particle-system/index.html
index e1f6d193..b4d0f2fe 100644
--- a/animations/06-3d-advanced/gpgpu-particle-system/index.html
+++ b/animations/06-3d-advanced/gpgpu-particle-system/index.html
@@ -165,7 +165,7 @@ void main(){
float x=p.x,y=p.y,vx=p.z,vy=p.w;
float age=fract(p.w*0.01+uT*0.001); // reuse w channel for age
float spd=uSpd*.0002;
- // uStep is 1, or 1/3 in slow motion: every change of velocity and every move is scaled by it
+ // uStep counts steps of 1/60 s (1 at 60 Hz, 2 at 30 Hz, a third of that in slow motion): every change of velocity and every move is scaled by it
if(uBehavior==0){// flow field
float angle=sin(x*2.+uT*.3)*cos(y*2.+uT*.2)+atan(y,x)*.5;
vx+=cos(angle)*spd*uStep;vy+=sin(angle)*spd*uStep;
@@ -215,10 +215,10 @@ void main(){
const RENDER_FS=`#version 300 es
precision mediump float;in vec4 vCol;out vec4 fragColor;
void main(){fragColor=vCol;}`;
-// Trails: a translucent full-screen quad fades the previous frame instead of clearing it
+// Trails: a translucent full-screen quad fades the previous frame instead of clearing it; uA is how much of it the quad covers
const FADE_FS=`#version 300 es
-precision mediump float;out vec4 fragColor;
-void main(){fragColor=vec4(.024,.039,.063,.12);}`;
+precision mediump float;uniform float uA;out vec4 fragColor;
+void main(){fragColor=vec4(.024,.039,.063,uA);}`;
const stage=document.getElementById('stage'),cvs=document.getElementById('cvs'),noWgl2=document.getElementById('no-wgl2');
const slowTog=document.getElementById('slow-tog');
@@ -299,15 +299,25 @@ function resize(){
return true;
}
-// The loop keeps exactly one pending frame in raf. The clock adds up the time of each drawn frame (at most 50 ms, and a
-// third of it while Slow motion is on), so a pause never makes the particles jump.
+// One step is 1/60 s: the rule moves the particles by uSpd x 0.0002 in that time, whatever the screen's refresh rate.
+const FRAME=1000/60;
+// The loop keeps exactly one pending frame in raf. Each drawn frame moves the particles by the time since the last drawn one
+// (a gap counts for at most 50 ms), and by a third of that while Slow motion is on; the clock adds up the same time, so a
+// pause never makes the particles jump. A frame longer than 1.5 steps (a 30 Hz screen) is moved in several passes of about
+// one step each: the Attract rule pulls hard near the middle, and one long step there lets the particles overshoot and keep
+// circling instead of settling. The Trails fade covers the same share of the old picture per second at any refresh rate.
+// At most one picture is drawn per 12 ms. A tab that comes back to the front starts again from its next frame, so the time
+// away adds no step.
function render(ts){
raf=requestAnimationFrame(render);
if(last===null){last=ts;return;} // the first frame after a start only takes the time
- const dt=ts-last;if(dt<12)return;
+ const gap=ts-last;if(gap<12)return;
last=ts;
- simT+=Math.min(dt,50)/1000/(slowTog.checked?3:1);
- physics(simT);paint(simT);
+ const dt=Math.min(gap,50),slow=slowTog.checked;
+ const steps=dt/FRAME*(slow?1/3:1),passes=Math.max(1,Math.round(steps)),clock=dt/1000/(slow?3:1);
+ for(let i=1;i<=passes;i++)physics(simT+clock*i/passes,steps/passes);
+ simT+=clock;
+ paint(simT,false,dt/FRAME);
}
// ── Physics pass (render to texture) ──
@@ -333,13 +343,15 @@ function physics(t,step){
function settle(){for(let i=0;i<120;i++){simT+=1/60;physics(simT,1);}}
// ── Render pass (draw points). A picture drawn on its own starts from a cleared canvas ("fresh"): with Trails on, a
-// normal frame only lays a thin fade over the last one, which would leave the old picture showing under a new setting. ──
-function paint(t,fresh){
+// normal frame only lays a thin fade over the last one, which would leave the old picture showing under a new setting.
+// steps is the length of the frame in steps of 1/60 s; the fade covers .12 of the old picture per step. ──
+function paint(t,fresh,steps=1){
gl.bindFramebuffer(gl.FRAMEBUFFER,null);
gl.viewport(0,0,W,H);
if(TRAILS&&!fresh){// fade the previous frame instead of clearing it
gl.enable(gl.BLEND);gl.blendFunc(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA);
gl.useProgram(fadeProg);gl.bindBuffer(gl.ARRAY_BUFFER,qBuf);
+ gl.uniform1f(gl.getUniformLocation(fadeProg,'uA'),1-Math.pow(1-.12,steps));
const fa=gl.getAttribLocation(fadeProg,'a');gl.enableVertexAttribArray(fa);gl.vertexAttribPointer(fa,2,gl.FLOAT,false,0,0);
gl.drawArrays(gl.TRIANGLE_STRIP,0,4);
}else{gl.clearColor(0.024,0.039,0.063,1);gl.clear(gl.COLOR_BUFFER_BIT);}
@@ -359,6 +371,7 @@ function paint(t,fresh){
// Play carries on from the clock and the particles where they stopped; it never stacks a second loop.
function start(){if(raf!==null||!gl)return;last=null;raf=requestAnimationFrame(render);}
+document.addEventListener('visibilitychange',()=>{last=null;});
// While paused a setting or a resize draws the picture again (no physics step), so the change shows without anything moving.
function repaint(){if(paused&&gl)paint(simT,true);}