[WebGPU] Moving Particles with Curl Noise Computed in a Compute Shader
Hello! I'm Fukasawa, an engineer on the hyper-casual games team.
I tried computing curl noise in a WebGPU compute shader and using it to update the positions of particles.
The screenshot shows a million particles moving on a MacBook Pro M1.
Click the image to go to the demo.
It's implemented with WebGPU, so it only runs on Chrome.
Demo URL: https://takumifukasawa.github.io/webgpu-particle-compute-shader-curl-noise-demo/
Repository
Motivation
Doesn't it look cool when huge numbers of particles each move as if swaying in the wind or flowing like a fluid, as in this video?
Simulating motion like this properly, following the fluid equations, inevitably means a heavy computational load.
In real-time rendering, you have to handle everything from setting the initial positions and velocities to updating them every frame as things move.
You might get away with tens or hundreds of particles, but as the count climbs into the thousands and tens of thousands, it gets harder and harder to pull off.
This is where a technique called curl noise gets you fluid-like motion without simulating a fluid.
I had never implemented curl noise myself, so I took the Advent Calendar as an opportunity to try it.
While I'm at it, I'll use WebGPU, which is now available by default in Chrome, and its compute shaders.
The same thing is possible in WebGL by using TransformFeedback.
Curl Noise
*Sorry if I've misunderstood anything!
Overview
It comes from a presentation of a pseudo-fluid algorithm at SIGGRAPH 2007. The paper/notes are here:
https://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph2007-curlnoise.pdf
It seems the technique was developed because existing simulations based on the equations of fluid motion produce realistic behavior but are slow to compute and hard to control through parameters.
The approach is to build a vector potential field in 2D or 3D space and derive the velocity from it.
First, picture a vector potential field as vectors scattered through space. I'll call it a vector field from here on.
Take wind as an example: outdoors, the wind blows sideways and trees sway, or leaves fly up into the air. In other words, picture forces pointing in various directions here and there throughout a space.
The 2D case: vectors scattered on a plane

- Take the gradient (explained later) of the vector at a given point in the vector field
- Treat the rotated value of that vector (rotation in the vector-calculus sense) as the velocity
- Updating the current position this way gives you swirling motion
That seems to be the core of curl noise.
Characteristics
One characteristic of curl noise is that it is "completely incompressible". Incompressible seems to mean the density is constant and the divergence is 0. In a velocity field, my understanding is that the input and output velocities are constant.
Calculation
∇ (= nabla) is the vector differential operator, and in this context, very roughly speaking, we treat it as "the gradient".
To calculate it, you get the vectors at positions slightly offset in x, y and z from the current position, and take the gradient.
Then, taking the cross product with nabla to rotate the vector gives the result of curl noise.
According to the various reference articles, the calculation looks like this.
(Sorry, I don't really have the background here, and my understanding is shaky.)

Also, the dot product of the rotated vector and the original vector is the "divergence".
From the incompressibility property, the divergence is 0 = the dot product is 0 = 90 degrees, so you could also put it as "the curl noise result is the vector rotated by 90 degrees in the vector-calculus sense".
...In short, there's a lot of the detailed math I don't understand,
but I take it to mean: generate a vector field, take the gradient, rotate the vector, and treat that as the velocity.
What this article covers / doesn't cover
The paper also covers boundary constraints (collision, range limits) and viscosity, but here I'll focus solely on computing the velocity.
The overall flow
Since the velocity is calculated in a compute shader, the positions are updated in the compute shader as well.
To render a large number of particles, I use GPU instancing on quads.
The reason for quads is that I wanted to draw them not as points but as billboards with a size, always facing the camera.
As for how the particle shader reads the instancing data: the plan is to update a buffer bound on the GPU from the compute shader, so if the particle shader shares and references that same buffer, the whole calculation stays on the GPU, with no CPU reads/writes or buffer rebinding, which should be efficient.
The RenderPipeline for drawing the particles is structured like this.
// pack position and velocity as vec4<f32> values
const instanceDataArray = new Float32Array([
0, 0, 0, 0, // position of instance 0
0, 0, 0, 0, // velocity of instance 0
...
]);
const particleInstancesBuffer = gDevice.createBuffer({
size: instanceDataArray.byteLength,
usage:
GPUBufferUsage.STORAGE |
GPUBufferUsage.VERTEX |
GPUBufferUsage.COPY_DST,
mappedAtCreation: true
});
new Float32Array(particleInstancesBuffer.getMappedRange()).set(instanceDataArray);
particleInstancesBuffer.unmap();
...
const particleRenderPipeline = gDevice.createRenderPipeline({
layout: 'auto',
vertex: {
module: gDevice.createShaderModule({
code: vertWGSL, // vertex shader
}),
entryPoint: 'main',
buffers: [
// buffer = 0
{
arrayStride: quadVertexSize, // size of the vertex data used for the quad, such as UVs
stepMode: 'vertex',
attributes: [
// data held by the vertex; set uv etc. as you like
{
shaderLocation: 0, // @location(0)
offset: quadPositionOffset,
format: 'float32x4'
},
{
shaderLocation: 1, // @location(1)
offset: quadColorOffset,
format: 'float32x4'
},
{
shaderLocation: 2, // @location(2)
offset: quadUVOffset,
format: 'float32x2'
}
]
},
// buffer = 1
{
arrayStride: instancingVertexSize, // size of the vertex data per instance
stepMode: 'instance', // treat the buffer as instancing data
attributes: [
// per-instance data; this time a buffer holding position and velocity
{
shaderLocation: 3, // @location(3)
offset: 0,
format: 'float32x4'
},
{
shaderLocation: 4, // @location(4)
offset: 4 * 4,
format: 'float32x4'
}
]
}
]
},
...
});
The vertex shader is structured like this.
struct Particle {
position: vec4<f32>,
velocity: vec4<f32>
};
@group(1) @binding(0)
var<storage, read> instanceData : array<Particle>;
...
@vertex
fn main(
// unpack the vertex data of buffer=0
@location(0) position : vec4<f32>, // billboard offset direction
@location(1) color : vec4<f32>,
// unpack the instance data of buffer=1
@location(2) uv: vec2<f32>,
@location(3) instancePosition: vec4<f32>,
@location(4) instanceVelocity: vec4<f32>
) -> VertexOutput {
...
If the buffer holding the quad's drawing information is particleVerticesBuffer and the one holding the instancing data is particleInstancesBuffer, you can register the buffers like this.
...
const renderPassEncoder = renderCommandEncoder.beginRenderPass(renderPassDescriptor);
renderPassEncoder.setPipeline(particleRenderPipeline);
... setting uniforms, etc.
renderPassEncoder.setVertexBuffer(0, particleVerticesBuffer); // register the vertex buffer with the quad info such as UVs at index=0
renderPassEncoder.setVertexBuffer(1, particleInstancesBuffer); // register the buffer packed with all the instancing data at index=1
// instanced drawing with indices
renderPassEncoder.setIndexBuffer(quadIndicesBuffer, 'uint16');
renderPassEncoder.drawIndexed(quadIndexArray.length, instanceNum);
Then this particleInstancesBuffer is updated directly from the compute shader.
Implementing it in a compute shader
Let's start with the compute shader's entry function.
The velocity is calculated from the result of a function called curlNoise.
struct Instance {
position: vec4<f32>,
velocity: vec4<f32>
};
@group(0) @binding(0)
var<uniform> uniforms : Uniforms;
@group(0) @binding(1)
var<storage, read_write> input : array<Instance>; // read the instance buffer and also use it as the write target
...
// the shader is written as a template literal in js, embedding workGroupSize
// with a single argument it is one-dimensional
@compute @workgroup_size(${workgroupSize})
fn main(
@builtin(global_invocation_id) global_invocation_id: vec3<u32>
) {
let id = global_invocation_id.x; // since it is one-dimensional, global_invocation_id can be used directly as the instance ID
if(id < arrayLength(&input)) {
let instance = input[id];
let currentPosition = instance.position.xyz;
let currentVelocity = instance.velocity.xyz;
let force = curlNoise(currentPosition.xyz * uniforms.noiseScale) - currentVelocity;
let newVelocity = force * uniforms.speed * uniforms.deltaTime;
let newPosition = currentPosition + newVelocity;
input[id].position = vec4<f32>(newPosition.xyz, 1.);
input[id].velocity = vec4<f32>(newVelocity.xyz, 1.);
}
}
The JavaScript side looks like this.
...
const computeBindGroup = gDevice.createBindGroup({
layout: computePipeline.getBindGroupLayout(0), // @group(0)
entries: [
{
binding: 0, // @binding(0)
resource: {
buffer: computeUniformBuffer
},
},
{
binding: 1, // @binding(1)
resource: {
buffer: particleInstancesBuffer
},
},
]
});
...
const computeCommandEncoder = gDevice.createCommandEncoder();
const computePassEncoder = computeCommandEncoder.beginComputePass();
computePassEncoder.setPipeline(computePipeline);
computePassEncoder.setBindGroup(0, computeBindGroup);
computePassEncoder.dispatchWorkgroups(dispatchGroupSize); // a single argument means one-dimensional execution
computePassEncoder.end();
gDevice.queue.submit([computeCommandEncoder.finish()]);
In this implementation, both the workgroup and the dispatch are one-dimensional, so
the number of threads executed is workgroup_size * the number of dispatchWorkgroups.
By making this number equal to the number of particles you want to draw, you can update every particle on screen.
Each has an upper limit, and you can get the values from the logical device.
For workGroupSize you get three dimensions, and for dispatchWorkgroup a single number (so I assume x, y and z all have the same value).
Here's some reference code.
const gAdapter = await navigator.gpu.requestAdapter(); // physical device
const gDevice = await gAdapter.requestDevice(); // logical device
// get the device limits
const limits = gDevice.limits;
// 256,64,64 on my MacBook Pro M1
console.log("Max Compute Workgroup Size:", {
x: limits.maxComputeWorkgroupSizeX,
y: limits.maxComputeWorkgroupSizeY,
z: limits.maxComputeWorkgroupSizeZ,
});
// 65536 on my MacBook Pro M1
console.log("Max Compute Workgroups Per Dimension:",
limits.maxComputeWorkgroupsPerDimension,
);
On my MacBook Pro they were x:256, y:64, z:64 and 65536 respectively.
So if you treat workGroupSize and dispatchWorkgroup as one-dimensional, you can handle 256 * 65536 = 16777216 threads at once.
Calculating curl noise
The paper uses Perlin noise to generate the vector field.
In this implementation I'll use simplex noise.
The simplex noise implementation is based on this one.
fn curlNoise(position: vec3<f32>) -> vec3<f32> {
let eps = 0.001;
let eps2 = 2.0 * eps;
let invEps2 = 1.0 / eps2;
let dx = vec3<f32>(eps, 0.0, 0.0);
let dy = vec3<f32>(0.0, eps, 0.0);
let dz = vec3<f32>(0.0, 0.0, eps);
// to compute the gradient, get the vectors at points offset by eps
let px0 = snoise3(position - dx);
let px1 = snoise3(position + dx);
let py0 = snoise3(position - dy);
let py1 = snoise3(position + dy);
let pz0 = snoise3(position - dz);
let pz1 = snoise3(position + dz);
// curl
let x = (py1.z - py0.z) - (pz1.y - pz0.y);
let y = (pz1.x - pz0.x) - (px1.z - px0.z);
let z = (px1.y - px0.y) - (py1.x - py0.x);
return vec3<f32>(x, y, z) * invEps2;
}
It takes the vectors from the vector field at positions slightly offset in x, y and z from the input coordinates, finds the gradient, and applies the rotation (curl) to the vector.
Adjusting the simplex noise
The original simplex noise implementation takes a vec3 argument and returns a float, so I assign a snoise result to each of x, y and z.
The key point here seems to be using noise values "offset by a large amount" so that they're less likely to be discontinuous.
I think this is probably to make them less affected by the pattern of the original noise.
fn snoise3(v: vec3<f32>) -> vec3<f32> {
return vec3<f32>(
snoise(v),
snoise(v + vec3<f32>(100., 200., 300.)), // apply an arbitrary offset
snoise(v + vec3<f32>(400., 500., 600.))
);
}
Going further
By using a volume texture, you can use a pre-generated vector field.
If you can use a volume texture generated in advance with some tool, it could make it easier for artists to control.
It might also reduce the computational load. Right now, snoise is computed 18 times per thread to update the position. That amount of computation scales with the number of particles.
The downsides of a volume texture are probably that its size grows in proportion to the number of grid cells in x, y and z, and that the motion pattern becomes more visible than when computing the noise in the shader.
Whether to compute everything in the shader or use a volume texture is a judgment call that depends on the actual use case.
In closing
WebGPU x compute shaders is fun!
WebGPU support across the major browsers still looks a way off, but I think you can already bring it in for small experiments or for making tools that take advantage of compute shaders, so the possibilities are exciting.
I drew on many articles for this one. Thank you.
KAYAC is looking for engineers who want to work with WebGL / WebGPU!

References
WebGPU
Introduction to WebGPU
WebGPU Fundamentals
ComputeShader with WebGPU #JavaScript - Qiita
WebGPU - All of the cores, none of the canvas (translation) - inzkyk.xyz
WebGPU Report
GLSL2WGSL
Curl noise
https://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph2007-curlnoise.pdf
GitHub - IndieVisualLab/UnityGraphicsProgramming2: sample code repository for the book "UnityGraphicsProgramming vol.2"
Implementing Curl Noise with Unity's Compute Shader (fluid edition) - e.blog
Incompressible flow - Wikipedia
Simplex noise
webgl-noise/src/noise3D.glsl at master · stegu/webgl-noise · GitHub
Math
rot [Butsuri no Kagi Shippo]
https://manabitimes.jp/physics/196
