# Mixwell Analytic 2D Fluid-Brush Mixing & Zero-Blur Marbling in Three.js (WebGL 2)

> Evaluate progressive physics-based 2D fluid mixing and paper marbling analytically in a single WebGL 2 fragment shader in Three.js r183 by composing inverse potential-flow brush warps (SIGGRAPH 2026 Mixwell principles) with zero grid solvers, zero ping-pong targets, and zero numerical diffusion.

- **Canonical page:** https://gamecrew.ai/techniques/three/mixwell-analytic-fluid-paint
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Three.js
- **Category:** shaders
- **Tags:** `fluid`, `mixing`, `marbling`, `paint`, `potential-flow`, `shader`, `inverse-advection`, `mixwell`, `siggraph`, `webgl2`
- **Verification:** Compile-verified pattern
- **Revision:** 1 (2026-11-30)
- **Demo:** No demo

## When to Use (and When Not To)

Traditional Eulerian grid fluid solvers resample dye textures on every frame, causing sharp pigment ribbons to smear into muddy gray after just a few brush strokes. **Mixwell-style analytical inverse advection** replaces grid advection with a closed-form stack of inverse potential-flow warps evaluated directly inside a single WebGL 2 fragment shader:

- **Use this technique** for alchemy/potion mixing, marbling and painting minigames, stylized ink puddles, magic pools, or resolution-independent swirled surface shaders that must stay razor-sharp under arbitrary camera zoom.
- **Skip this technique** for turbulent buoyancy smoke plumes or splashing free-surface waves with arbitrary wall bounces — use a grid/particle solver there.

## Mathematical & Algorithmic Core

1. **Reverse Composition of Inverse Flow Maps ($\Phi^{-1}$)**:
   - Store a bounded stroke list $\mathcal{S} = \{s_0, \dots, s_{N-1}\}$ (`MAX_STROKES = 20`) in `vec4` uniforms (`startXY, endXY` and `radius, strength, swirl, pigment`).
   - For each screen UV $\mathbf{x}$, walk strokes **backward** ($k = N-1 \to 0$) applying each stroke's inverse displacement $\mathbf{x} \leftarrow \Phi_k^{-1}(\mathbf{x})$, then evaluate the crisp procedural pigment bands and medallions **once** at the final warped coordinate.
2. **Cylindrical-Tine Dipole Drift + Lamb–Oseen Endpoint Swirl**:
   - Project $\mathbf{x}$ onto stroke direction $\hat{\mathbf{d}}$ and normal $\hat{\mathbf{n}}$ with distance $r^2 = (s - \mathrm{clamp}(s, 0, L))^2 + n^2$ to the swept segment.
   - Pull coordinates backward along $\hat{\mathbf{d}}$ using the dipole drift profile $a^2 / (a^2 + 1.15 r^2)$ shaped by a smooth wake envelope, optionally followed by an incompressible rotational swirl $\theta = -c \cdot 0.72\, e^{-\|\mathbf{x}-\mathbf{p}_1\|^2 / (3.8 a^2)}$ around the stroke endpoint.
   - Because no intermediate texture resampling occurs, **filaments remain mathematically crisp even after 15–20 overlapping strokes**.
3. **Wet-Paint Meniscus Specular**:
   - Evaluate two finite-difference neighbors of the warped luminance height to reconstruct a subtle glossy surface normal for specular highlights and Fresnel sheen.

## Engine Implementation (`Assets/Game/mixwellFluidPaint.ts`)

```ts
import * as THREE from 'three';

export const MAX_MIXWELL_STROKES = 20;

export interface MixwellStroke {
  startX: number;
  startY: number;
  endX: number;
  endY: number;
  /** Effective cylindrical tine radius in UV space (e.g. 0.04..0.18). */
  radius: number;
  /** Advection drag factor along the stroke axis (0.4..1.8). */
  strength: number;
  /** Optional incompressible endpoint vortex swirl (-1.5..1.5). */
  swirl: number;
  /** Optional pigment ribbon tint blend (0 = pure advection, 1..4 = pigment dye). */
  pigment: number;
}

export interface MixwellCanvasHandle {
  mesh: THREE.Mesh;
  material: THREE.ShaderMaterial;
  uniforms: {
    uStrokePos: { value: THREE.Vector4[] };
    uStrokeMeta: { value: THREE.Vector4[] };
    uStrokeCount: { value: number };
    uTime: { value: number };
    uLightDir: { value: THREE.Vector3 };
    uPalette: { value: THREE.Color[] };
  };
  strokes: MixwellStroke[];
  addStroke: (stroke: MixwellStroke) => number;
  setStrokes: (strokes: readonly MixwellStroke[]) => void;
  clearStrokes: () => void;
  dispose: () => void;
}

/**
 * CPU reference mirror of the GLSL Mixwell analytical inverse potential-flow warp.
 * Composes strokes in reverse order (N-1 -> 0) so base pigment bands stay razor-sharp with zero grid diffusion.
 */
export function evaluateMixwellInverseWarp(
  uvX: number,
  uvY: number,
  strokes: readonly MixwellStroke[]
): [number, number] {
  let px = uvX;
  let py = uvY;
  const count = Math.min(MAX_MIXWELL_STROKES, strokes.length);

  for (let i = count - 1; i >= 0; i--) {
    const st = strokes[i];
    const dx = st.endX - st.startX;
    const dy = st.endY - st.startY;
    const len = Math.hypot(dx, dy);
    if (len < 1e-5) continue;

    const dirX = dx / len;
    const dirY = dy / len;
    const perpX = -dirY;
    const perpY = dirX;

    const relX = px - st.startX;
    const relY = py - st.startY;
    const s = relX * dirX + relY * dirY;
    const n = relX * perpX + relY * perpY;

    const a = Math.max(0.015, st.radius);
    const a2 = a * a;
    // Smooth longitudinal window covering the swept tine trajectory + dipole wake decay
    const sClamped = Math.max(0, Math.min(len, s));
    const ds = s - sClamped;
    const r2 = ds * ds + n * n;
    const dipoleKernel = a2 / (a2 + r2 * 1.15);
    const wakeEnvelope = Math.exp(-r2 / (a2 * 6.5));
    const drag = Math.min(len * 1.45, len * st.strength * dipoleKernel * (0.45 + 0.55 * wakeEnvelope));

    // Inverse advection pulls lookup coordinates backward along the stroke vector
    px -= dirX * drag;
    py -= dirY * drag;

    // Optional incompressible rotational Lamb-Oseen swirl around stroke tip
    if (Math.abs(st.swirl) > 1e-4) {
      const ex = px - st.endX;
      const ey = py - st.endY;
      const er2 = ex * ex + ey * ey;
      const theta = -st.swirl * 0.72 * Math.exp(-er2 / (a2 * 3.8));
      const c = Math.cos(theta);
      const sn = Math.sin(theta);
      px = st.endX + ex * c - ey * sn;
      py = st.endY + ex * sn + ey * c;
    }
  }
  return [px, py];
}

/** Curated classical paper-marbling comb + S-scroll stroke choreography for instant zero-blur beauty. */
export function buildDefaultMarblingStrokes(): MixwellStroke[] {
  const strokes: MixwellStroke[] = [];
  // 1. Parallel rake / comb passes pulling alternating opposing bands
  for (let i = 0; i < 6; i++) {
    const y = 0.14 + i * 0.145;
    const forward = i % 2 === 0;
    strokes.push({
      startX: forward ? 0.08 : 0.92,
      startY: y,
      endX: forward ? 0.92 : 0.08,
      endY: y + (forward ? 0.03 : -0.03),
      radius: 0.075,
      strength: 0.78,
      swirl: forward ? 0.35 : -0.35,
      pigment: 0,
    });
  }
  // 2. Cross-sweeps carving feathery chevron plumes across the horizontal ribbons
  for (let i = 0; i < 4; i++) {
    const x = 0.2 + i * 0.2;
    const up = i % 2 === 0;
    strokes.push({
      startX: x,
      startY: up ? 0.12 : 0.88,
      endX: x + (up ? 0.06 : -0.06),
      endY: up ? 0.88 : 0.12,
      radius: 0.065,
      strength: 0.72,
      swirl: up ? 0.65 : -0.65,
      pigment: 0,
    });
  }
  // 3. Central focal double-vortex flourish
  strokes.push(
    { startX: 0.28, startY: 0.36, endX: 0.68, endY: 0.64, radius: 0.095, strength: 0.92, swirl: 1.15, pigment: 0 },
    { startX: 0.72, startY: 0.34, endX: 0.34, endY: 0.66, radius: 0.085, strength: 0.85, swirl: -1.1, pigment: 0 }
  );
  return strokes;
}

const VERTEX_SHADER = /* glsl */ `
  varying vec2 vUv;
  varying vec3 vWorldPos;
  void main() {
    vUv = uv;
    vec4 wp = modelMatrix * vec4(position, 1.0);
    vWorldPos = wp.xyz;
    gl_Position = projectionMatrix * viewMatrix * wp;
  }
`;

const FRAGMENT_SHADER = /* glsl */ `
  precision highp float;

  #define MAX_STROKES 20

  uniform vec4 uStrokePos[MAX_STROKES];
  uniform vec4 uStrokeMeta[MAX_STROKES];
  uniform int uStrokeCount;
  uniform float uTime;
  uniform vec3 uLightDir;
  uniform vec3 uPalette[5];

  varying vec2 vUv;
  varying vec3 vWorldPos;

  vec2 mixwellInverseWarp(vec2 uv) {
    vec2 p = uv;
    for (int i = MAX_STROKES - 1; i >= 0; i--) {
      if (i >= uStrokeCount) continue;
      vec4 sp = uStrokePos[i];
      vec4 sm = uStrokeMeta[i];
      vec2 d = sp.zw - sp.xy;
      float len = length(d);
      if (len < 1e-5) continue;

      vec2 dir = d / len;
      vec2 perp = vec2(-dir.y, dir.x);
      vec2 rel = p - sp.xy;
      float s = dot(rel, dir);
      float n = dot(rel, perp);

      float a = max(0.015, sm.x);
      float a2 = a * a;
      float sClamped = clamp(s, 0.0, len);
      float ds = s - sClamped;
      float r2 = ds * ds + n * n;
      float dipole = a2 / (a2 + r2 * 1.15);
      float env = exp(-r2 / (a2 * 6.5));
      float drag = min(len * 1.45, len * sm.y * dipole * (0.45 + 0.55 * env));
      p -= dir * drag;

      if (abs(sm.z) > 1e-4) {
        vec2 e = p - sp.zw;
        float er2 = dot(e, e);
        float theta = -sm.z * 0.72 * exp(-er2 / (a2 * 3.8));
        float c = cos(theta);
        float sn = sin(theta);
        p = sp.zw + vec2(e.x * c - e.y * sn, e.x * sn + e.y * c);
      }
    }
    return p;
  }

  vec3 samplePigmentField(vec2 p, out float ridgeHeight) {
    // Crisp layered base pigment drops & alternating marbling bands evaluated ONCE after exact inverse warp
    float bandCoord = p.y * 5.2 + sin(p.x * 3.14159265 * 2.0 + uTime * 0.12) * 0.18;
    float f = fract(bandCoord);

    // Three sharp concentric pigment drops dropped onto the bath before combing
    float d0 = length(p - vec2(0.32, 0.48));
    float d1 = length(p - vec2(0.68, 0.52));
    float d2 = length(p - vec2(0.50, 0.30));

    vec3 col = uPalette[0];
    col = mix(col, uPalette[1], smoothstep(0.18, 0.20, f) * (1.0 - smoothstep(0.42, 0.44, f)));
    col = mix(col, uPalette[2], smoothstep(0.44, 0.46, f) * (1.0 - smoothstep(0.68, 0.70, f)));
    col = mix(col, uPalette[3], smoothstep(0.70, 0.72, f) * (1.0 - smoothstep(0.86, 0.88, f)));
    col = mix(col, uPalette[4], smoothstep(0.88, 0.90, f));

    // Concentric marbled pigment medallions with sharp analytical borders
    float m0 = 1.0 - smoothstep(0.145, 0.155, d0);
    float m0Ring = (1.0 - smoothstep(0.082, 0.090, d0));
    col = mix(col, uPalette[3], m0);
    col = mix(col, uPalette[4], m0Ring);

    float m1 = 1.0 - smoothstep(0.150, 0.160, d1);
    float m1Ring = (1.0 - smoothstep(0.088, 0.096, d1));
    col = mix(col, uPalette[2], m1);
    col = mix(col, uPalette[0], m1Ring);

    float m2 = 1.0 - smoothstep(0.115, 0.124, d2);
    col = mix(col, uPalette[1], m2);

    ridgeHeight = dot(col, vec3(0.299, 0.587, 0.114));
    return col;
  }

  void main() {
    vec2 warped = mixwellInverseWarp(vUv);
    float hC = 0.0;
    vec3 albedo = samplePigmentField(warped, hC);

    // Subtle glossy wet-paint meniscus specular via finite difference on warped pigment height
    float eps = 0.0022;
    float hX = 0.0;
    float hY = 0.0;
    samplePigmentField(mixwellInverseWarp(vUv + vec2(eps, 0.0)), hX);
    samplePigmentField(mixwellInverseWarp(vUv + vec2(0.0, eps)), hY);
    vec3 normal = normalize(vec3((hC - hX) * 0.55, 1.0, (hC - hY) * 0.55));

    vec3 L = normalize(uLightDir);
    vec3 V = normalize(cameraPosition - vWorldPos);
    vec3 H = normalize(L + V);
    float ndl = max(0.0, dot(normal, L));
    float spec = pow(max(0.0, dot(normal, H)), 64.0) * 0.36;
    float fresnel = pow(1.0 - max(0.0, dot(normal, V)), 4.0) * 0.16;

    // Gentle vignette inside the ceramic tray border
    vec2 edge = abs(vUv - 0.5) * 2.0;
    float rim = 1.0 - smoothstep(0.91, 1.0, max(edge.x, edge.y)) * 0.22;

    vec3 lit = albedo * (0.42 + 0.64 * ndl) * rim + vec3(1.0, 0.97, 0.92) * (spec + fresnel);
    gl_FragColor = vec4(clamp(lit, 0.0, 1.0), 1.0);
  }
`;

/**
 * Creates a resolution-independent Mixwell analytical 2D fluid-brush marbling surface in Three.js r183 WebGL 2.
 * Zero grid solver and zero ping-pong diffusion: every brush stroke composes analytically in fragment shader space.
 */
export function createMixwellFluidCanvas(
  width = 7.4,
  depth = 5.4,
  initialStrokes: readonly MixwellStroke[] = buildDefaultMarblingStrokes()
): MixwellCanvasHandle {
  const strokePos: THREE.Vector4[] = [];
  const strokeMeta: THREE.Vector4[] = [];
  for (let i = 0; i < MAX_MIXWELL_STROKES; i++) {
    strokePos.push(new THREE.Vector4(0, 0, 0, 0));
    strokeMeta.push(new THREE.Vector4(0.08, 0.8, 0, 0));
  }

  const uniforms = {
    uStrokePos: { value: strokePos },
    uStrokeMeta: { value: strokeMeta },
    uStrokeCount: { value: 0 },
    uTime: { value: 0 },
    uLightDir: { value: new THREE.Vector3(0.45, 0.82, -0.35).normalize() },
    uPalette: {
      value: [
        new THREE.Color(0xf6efe0), // warm ivory bath
        new THREE.Color(0x1b4578), // ultramarine cobalt
        new THREE.Color(0xc93b34), // vermilion crimson
        new THREE.Color(0xe3a83b), // ochre gold
        new THREE.Color(0x1f7a6e), // deep teal viridian
      ],
    },
  };

  const strokes: MixwellStroke[] = [];
  const syncUniforms = () => {
    const n = Math.min(MAX_MIXWELL_STROKES, strokes.length);
    uniforms.uStrokeCount.value = n;
    for (let i = 0; i < n; i++) {
      const s = strokes[i];
      strokePos[i].set(s.startX, s.startY, s.endX, s.endY);
      strokeMeta[i].set(s.radius, s.strength, s.swirl, s.pigment);
    }
  };

  for (const s of initialStrokes.slice(0, MAX_MIXWELL_STROKES)) strokes.push({ ...s });
  syncUniforms();

  const geo = new THREE.PlaneGeometry(width, depth, 1, 1);
  geo.rotateX(-Math.PI / 2);
  const material = new THREE.ShaderMaterial({
    uniforms,
    vertexShader: VERTEX_SHADER,
    fragmentShader: FRAGMENT_SHADER,
  });
  const mesh = new THREE.Mesh(geo, material);
  mesh.name = 'MixwellFluidCanvas';

  return {
    mesh,
    material,
    uniforms,
    strokes,
    addStroke(stroke: MixwellStroke): number {
      if (strokes.length >= MAX_MIXWELL_STROKES) strokes.shift();
      strokes.push({ ...stroke });
      syncUniforms();
      return strokes.length;
    },
    setStrokes(next: readonly MixwellStroke[]) {
      strokes.length = 0;
      for (const s of next.slice(0, MAX_MIXWELL_STROKES)) strokes.push({ ...s });
      syncUniforms();
    },
    clearStrokes() {
      strokes.length = 0;
      syncUniforms();
    },
    dispose() {
      geo.dispose();
      material.dispose();
    },
  };
}
```

## Performance, Browser & Software-Renderer Budgets

- **Zero render targets & zero VRAM growth**: The entire fluid-mixing state fits in `40` `vec4` uniforms (`640 bytes`), compiling cleanly in WebGL 2 with fixed `#define MAX_STROKES 20` loop bounds.
- **No per-frame allocations**: `addStroke()` reuses pre-allocated `THREE.Vector4` uniform slots in place.
- **Mobile tuning**: Drop the 2 extra finite-difference normal taps on ultra-low-end mobile tiers to cut fragment ALU cost by `66%` while keeping identical sharp pigment marbling.

## Integration & Verification Checklist

1. Map pointer or stylus drag paths on the marbling surface into `[0..1]` UV coordinates and pass them to `mixwell.addStroke(...)`.
2. Unit-test `evaluateMixwellInverseWarp` for centerline backward advection, far-field dipole decay, and finite output across multi-stroke compositions.
3. Capture wide and close views to verify razor-sharp pigment filament boundaries with zero grid blur.

## Official references

- Doug L. James & Ethan James (SIGGRAPH 2026 Best Paper — Mixwell: Sharp 2D Fluid Brushes for Progressive Physics-Based Mixing)
- James Clerk Maxwell (1870 — On the Displacement in a Case of Fluid Motion)
- Three.js r183 ShaderMaterial Reference
