A Browser Fluid Simulation Without Pressure Projection — Diffusion and Advection on a 100x60 Grid

This demo computes diffusion and semi-Lagrangian advection on a 100 by 60 grid and leaves out pressure projection. See what it computes, and what it skips, in the current code.

14 min read
SimulationPhysicsCanvas APIMath

What the demo does and does not compute

This browser fluid simulation demo, Fluid Simulation, runs on a Canvas 2D context. It computes diffusion and semi-Lagrangian advection on a 100 by 60 grid. It does not compute a pressure projection step.

In Jos Stam's 1999 paper Stable Fluids, a projection step after advection and diffusion makes the velocity field divergence-free. This demo leaves that step out, so it is not a full Navier-Stokes solver.

Because there is no pressure projection, the velocity field is not made divergence-free and incompressibility is not enforced. The code contains no Poisson solve.

Grid and buffers

The grid is 100 cells wide and 60 cells high, 6000 cells in total. There are no extra boundary (ghost) cells. The outermost row and column are the boundary, and the diffusion and advection loops cover cells 1 to GRID_W - 2 and 1 to GRID_H - 2.

A cell at (x, y) is stored at index y * GRID_W + x in flat Float32Array buffers, which hold 32-bit floats. The state is 10 buffers of 6000 values each: velocity (vx, vy), three dye channels (dyeR, dyeG, dyeB), and five temporary buffers (tmpVx, tmpVy, tmpR, tmpG, tmpB).

The dye is three colour channels, red, green and blue, each from 0 to 255. Density is not stored as a single scalar field.

function createFluidState(): FluidState {
  const size = GRID_W * GRID_H
  return {
    vx: new Float32Array(size),
    vy: new Float32Array(size),
    dyeR: new Float32Array(size),
    dyeG: new Float32Array(size),
    dyeB: new Float32Array(size),
    tmpR: new Float32Array(size),
    tmpG: new Float32Array(size),
    tmpB: new Float32Array(size),
    tmpVx: new Float32Array(size),
    tmpVy: new Float32Array(size),
  }
}

The order of one step

One simulation step runs in a fixed order: diffuse velocity, advect velocity, diffuse dye, advect dye, apply decay. Last, it sets the velocity to zero on the four edges.

function stepFluid(state: FluidState) {
  const { vx, vy, dyeR, dyeG, dyeB, tmpR, tmpG, tmpB, tmpVx, tmpVy } = state
  const dt = 1.0

  // Diffuse velocity
  tmpVx.set(vx)
  tmpVy.set(vy)
  diffuse(vx, tmpVx, DIFFUSION * 0.5)
  diffuse(vy, tmpVy, DIFFUSION * 0.5)

  // Advect velocity
  advect(tmpVx, vx, tmpVx, tmpVy, dt)
  advect(tmpVy, vy, tmpVx, tmpVy, dt)

  // Diffuse dye
  tmpR.set(dyeR)
  tmpG.set(dyeG)
  tmpB.set(dyeB)
  diffuse(dyeR, tmpR, DIFFUSION)
  diffuse(dyeG, tmpG, DIFFUSION)
  diffuse(dyeB, tmpB, DIFFUSION)

  // Advect dye
  advect(tmpR, dyeR, vx, vy, dt)
  advect(tmpG, dyeG, vx, vy, dt)
  advect(tmpB, dyeB, vx, vy, dt)

  // Decay velocity and dye
  for (let i = 0; i < vx.length; i++) {
    vx[i] *= VELOCITY_DECAY
    vy[i] *= VELOCITY_DECAY
    dyeR[i] *= DYE_DECAY
    dyeG[i] *= DYE_DECAY
    dyeB[i] *= DYE_DECAY
  }

  // Zero boundaries
  for (let x = 0; x < GRID_W; x++) {
    const top = idx(x, 0)
    const bot = idx(x, GRID_H - 1)
    vx[top] = vy[top] = vx[bot] = vy[bot] = 0
  }
  for (let y = 0; y < GRID_H; y++) {
    const left = idx(0, y)
    const right = idx(GRID_W - 1, y)
    vx[left] = vy[left] = vx[right] = vy[right] = 0
  }
}

Diffusion: 4 Gauss-Seidel iterations

Diffusion uses 4 Gauss-Seidel iterations. Each cell becomes (source + a × the sum of its 4 neighbours) / (1 + 4a). The neighbours are read from the buffer being updated.

The coefficient a depends on the field: 0.15 for dye (DIFFUSION) and half of that, 0.075, for velocity (DIFFUSION * 0.5).

function diffuse(src: Float32Array, dst: Float32Array, diff: number) {
  const a = diff
  const inv = 1 / (1 + 4 * a)
  // 4 Gauss-Seidel iterations
  for (let iter = 0; iter < 4; iter++) {
    for (let y = 1; y < GRID_H - 1; y++) {
      for (let x = 1; x < GRID_W - 1; x++) {
        const i = idx(x, y)
        dst[i] =
          (src[i] +
            a *
              (dst[idx(x - 1, y)] + dst[idx(x + 1, y)] + dst[idx(x, y - 1)] + dst[idx(x, y + 1)])) *
          inv
      }
    }
  }
}

Advection: trace back, then interpolate

Advection is semi-Lagrangian. For each cell, the solver traces back along the velocity to the position (x - dt * vx, y - dt * vy), clamps it to 0.5 .. GRID_W - 1.5 and 0.5 .. GRID_H - 1.5, and takes a bilinear interpolation of the four surrounding cells.

The time step dt is not measured from the clock. It is the constant 1.0 per step.

function advect(
  src: Float32Array,
  dst: Float32Array,
  vx: Float32Array,
  vy: Float32Array,
  dt: number,
) {
  for (let y = 1; y < GRID_H - 1; y++) {
    for (let x = 1; x < GRID_W - 1; x++) {
      const i = idx(x, y)
      // Trace back
      let bx = x - dt * vx[i]
      let by = y - dt * vy[i]
      bx = clamp(bx, 0.5, GRID_W - 1.5)
      by = clamp(by, 0.5, GRID_H - 1.5)

      const x0 = Math.floor(bx)
      const y0 = Math.floor(by)
      const x1 = x0 + 1
      const y1 = y0 + 1
      const sx = bx - x0
      const sy = by - y0

      dst[i] =
        (1 - sx) * (1 - sy) * src[idx(x0, y0)] +
        sx * (1 - sy) * src[idx(x1, y0)] +
        (1 - sx) * sy * src[idx(x0, y1)] +
        sx * sy * src[idx(x1, y1)]
    }
  }
}

What is left out: pressure projection, and the decay applied every step

There is no pressure projection in this demo: no step makes the velocity field divergence-free, and nothing solves a Poisson equation.

After diffusion and advection, every step multiplies the velocity by 0.97 (VELOCITY_DECAY) and each dye channel by 0.995 (DYE_DECAY).

How dragging injects velocity and dye

The canvas uses pointer events with pointer capture. A mouse, a pen or a touch can drive it. Pressing injects dye, and moving while pressed injects velocity as well. Both go into the cells within a radius of 3 cells (MOUSE_RADIUS) of the pointer. The strength falls off linearly: 1 - distance / 3.

The injected velocity is the pointer movement in grid cells since the previous event, times 0.4 (MOUSE_FORCE), times that strength.

The dye colour changes while you drag. The hue advances by 0.8 degrees on each injection and wraps at 360. The colour is HSL with saturation 0.9 and lightness 0.55, converted to RGB. Each channel adds colour × strength × 0.6 and is clamped to 255.

Rendering to the canvas

Rendering uses the 2D context of the Canvas API. An ImageData sized to the CSS size times devicePixelRatio, rounded, is filled so that each grid cell paints a rectangular block of pixels in its dye colour, with alpha 255.

putImageData is called once per frame. The ImageData object is reused across frames and rebuilt after a resize or when the loop restarts.

const cellW = pw / GRID_W
const cellH = ph / GRID_H

for (let gy = 0; gy < GRID_H; gy++) {
  const pyStart = Math.floor(gy * cellH)
  const pyEnd = Math.floor((gy + 1) * cellH)
  for (let gx = 0; gx < GRID_W; gx++) {
    const i = idx(gx, gy)
    const r = clamp(Math.round(state.dyeR[i]), 0, 255)
    const g = clamp(Math.round(state.dyeG[i]), 0, 255)
    const b = clamp(Math.round(state.dyeB[i]), 0, 255)

    const pxStart = Math.floor(gx * cellW)
    const pxEnd = Math.floor((gx + 1) * cellW)

    for (let py = pyStart; py < pyEnd; py++) {
      const rowOffset = py * pw
      for (let px = pxStart; px < pxEnd; px++) {
        const pi = (rowOffset + px) * 4
        pixels[pi] = r
        pixels[pi + 1] = g
        pixels[pi + 2] = b
        pixels[pi + 3] = 255
      }
    }
  }
}

ctx.putImageData(imgData, 0, 0)

The frame loop and the fixed time step

The loop uses requestAnimationFrame and runs one simulation step and one render per frame. It stops when less than 10% of the demo is visible.

The flow advances one step per frame and dt is fixed, so its apparent speed follows how often requestAnimationFrame fires. No frame rate was measured for this article.

How Fluid Pipes differs

Fluid Pipes is not a fluid solver. It is a separate demo on this site that grows pipes segment by segment along six axis directions on a 3D lattice with GRID_SIZE = 20. It computes no pressure and no flow.

Further reading

The full method, including the projection step, is in Jos Stam's paper Stable Fluids (1999).

Go deeper on this topic

Creative Coding

Mathematical simulations, nature visualization, and generative art in the browser

Article 2 of 13 in this series.

View topic page

Use the topic hub as a map, then continue to the next article in the series. New here? Start at the home hub →

FAQ

Does the demo solve the Navier-Stokes equations?

Not fully. It computes diffusion and semi-Lagrangian advection and has no pressure projection step, so the velocity field is not made divergence-free and incompressibility is not enforced. The code contains no Poisson solve.

How many iterations does diffusion use, and with which coefficients?

Diffusion uses 4 Gauss-Seidel iterations. Each cell becomes (source + a × the sum of its 4 neighbours in the buffer being updated) / (1 + 4a), where a is 0.15 for dye and 0.075 for velocity.

Is Fluid Pipes a fluid simulation?

No. Fluid Pipes is not a fluid solver. It grows pipes segment by segment along six axis directions on a 3D lattice with GRID_SIZE = 20, and computes no pressure and no flow.