SunUI
Founding$79 lifetime updates till Jan 11Claim a seat
FreeStoryPress

Cloth Curtain

A real WebGL cloth curtain on a rail: a Verlet mass-spring grid with anime cel shading in a deep wine-red by default (pass tones to recolour) that sways in the breeze, gathers into folds as it draws aside (single panel or a centre-parting pair), can follow a dragging hand, and has an adjustable see-through amount.

When to use it

  • Revealing a scene, chapter or hero behind a curtain that opens on a button or a story beat
  • Drag-to-reveal moments where the user pulls the cloth aside with a pointer (pass handRef)

Watch out

  • Each instance uses its own WebGL context, so avoid many curtains on one page
  • sheer is fixed when the simulation is built; use 0 when the curtain must fully hide a scene change

Let your agent add it

One copy holds the install command, when to use it, the props and the design rules. Paste it into Claude Code, Cursor or Codex.

Install with the CLI

Uses the shadcn CLI. The source is copied into your project, so you own every line.

$ npx shadcn@latest add https://sunui.synvize.com/r/cloth-curtain.json

Or install manually

  1. 1. Install the dependencies.
    $ npm install clsx tailwind-merge framer-motion
  2. 2. Add a cn helper at lib/utils.ts if you do not have one. Not using shadcn/ui? Also add sunui-theme.css for the colour tokens (how). Then copy the component.
    cloth-curtain.tsx
    "use client";
    
    import { useReducedMotion } from "framer-motion";
    import { useEffect, useRef, useState, type MutableRefObject, type ReactNode } from "react";
    
    import { cn } from "@/lib/utils";
    
    import { createClothRenderer, DEFAULT_CLOTH_TONES, type ClothTones } from "./cloth-renderer";
    import { createClothPanel, type ClothHand, type ClothPanel } from "./cloth-simulation";
    
    export type { ClothTones } from "./cloth-renderer";
    
    const MAX_PIXEL_RATIO = 2;
    const SETTLE_STEPS = 45;
    const MAX_STEPS_PER_FRAME = 2;
    const STEP_MS = 1000 / 60;
    /** The cloth hangs first and the wind rises slowly; on first appearance it must already be a drawn curtain. */
    const BREEZE_RISE_SECONDS = 2.5;
    const OPEN_FOLLOW = 0.075;
    const OPEN_DAMPING = 0.72;
    /** The cloth edges extend past the frame so no gap without cloth shows while it sways. */
    const BLEED = 0.14;
    
    export interface ClothCurtainProps {
      /** single: one piece, gathers to the right. pair: two pieces, part from the middle. */
      layout?: "single" | "pair";
      /** 0 is drawn shut, 1 is fully gathered off screen. */
      open: number;
      /** How see-through the cloth is. Use 0 for a transition that covers the whole screen, so the scene change behind it is not revealed. */
      sheer?: number;
      breeze?: number;
      /** A strong gust that lifts the curtain, 0 to 1. */
      gust?: number;
      /** Minimum seconds from fully closed to fully open. Neither wind nor hand should snatch the cloth away instantly. */
      openSeconds?: number;
      /** Hand position (viewport coordinates), undefined when released. */
      handRef?: MutableRefObject<{ clientX: number; clientY: number } | undefined>;
      /** Static curtain shown when the simulation does not run: reduced motion, or a device without WebGL. Falls back to the built-in striped curtain. */
      fallback?: ReactNode;
      /** Skip the simulation. When omitted, follows prefers-reduced-motion. */
      still?: boolean;
      /** Cel-shaded palette, a thick dark wine-red curtain by default. */
      tones?: ClothTones;
      className?: string;
    }
    
    function createPanels(layout: "single" | "pair", aspect: number): ClothPanel[] {
      if (layout === "single") {
        return [createClothPanel({ gatherSide: 1, leadX: -aspect - BLEED, edgeX: aspect + BLEED, aspect })];
      }
      return [
        createClothPanel({ gatherSide: -1, leadX: 0.16, edgeX: -aspect - BLEED, aspect }),
        createClothPanel({ gatherSide: 1, leadX: -0.16, edgeX: aspect + BLEED, aspect }),
      ];
    }
    
    /** Static curtain for reduced motion: a single piece uses wide translucent stripes, a pair uses thin opaque stripes, and opening switches directly. */
    function StaticCurtain({ layout, open, className }: { layout: "single" | "pair"; open: number; className?: string }) {
      if (layout === "single") {
        return (
          <div
            aria-hidden="true"
            className={cn("pointer-events-none absolute inset-0", className)}
            style={{
              transform: `translateX(${open * 100}%)`,
              background: "repeating-linear-gradient(90deg, rgb(115 46 38 / 92%) 0 5rem, rgb(92 37 31 / 92%) 5rem 9rem)",
            }}
          />
        );
      }
      const stripes = "repeating-linear-gradient(90deg, #7a3127 0 34px, #8a3a2e 34px 70px, #682a21 70px 96px)";
      return (
        <div aria-hidden="true" className={cn("pointer-events-none absolute inset-0 overflow-hidden", className)}>
          <div
            className="absolute inset-y-0 left-0 w-[52%] origin-top-left"
            style={{ background: stripes, transform: `translateX(${-104 * open}%) skewX(${4 * open}deg)` }}
          />
          <div
            className="absolute inset-y-0 right-0 w-[52%] origin-top-right"
            style={{ background: stripes, transform: `translateX(${104 * open}%) skewX(${-4 * open}deg)` }}
          />
        </div>
      );
    }
    
    /** A real-cloth curtain simulated in WebGL: a Verlet particle grid hung on a rod, blown by wind, pushed by hand, and gathering into folds when opened. */
    export function ClothCurtain({
      layout = "single",
      open,
      sheer = 0.1,
      breeze = 0.5,
      gust = 0,
      openSeconds = 1.5,
      handRef,
      fallback,
      still,
      tones = DEFAULT_CLOTH_TONES,
      className,
    }: ClothCurtainProps) {
      const reduce = useReducedMotion();
      const isStill = still ?? reduce ?? false;
      const canvasRef = useRef<HTMLCanvasElement>(null);
      const [unavailable, setUnavailable] = useState(false);
      const liveRef = useRef({ open, breeze, gust });
      liveRef.current = { open, breeze, gust };
      const tonesRef = useRef(tones);
      tonesRef.current = tones;
    
      useEffect(() => {
        const canvas = canvasRef.current;
        if (!canvas || isStill) return;
        const renderer = createClothRenderer(canvas, sheer, tonesRef.current);
        if (!renderer) {
          setUnavailable(true);
          return;
        }
    
        let panels: ClothPanel[] = [];
        let aspect = 1;
        let shownWidth = 0;
        let shownHeight = 0;
        let shownOpen = liveRef.current.open;
        let openVelocity = 0;
        let time = 0;
        let settleSeconds = 0;
    
        const stepAll = (hand?: ClothHand) => {
          const live = liveRef.current;
          const fastest = STEP_MS / 1000 / openSeconds;
          openVelocity = (openVelocity + (live.open - shownOpen) * OPEN_FOLLOW) * OPEN_DAMPING;
          openVelocity = Math.max(-fastest * 2, Math.min(fastest, openVelocity));
          shownOpen += openVelocity;
          time += STEP_MS / 1000;
          for (const panel of panels) {
            const breeze = live.breeze * Math.min(1, Math.max(0, time - settleSeconds) / BREEZE_RISE_SECONDS);
            panel.step(Math.max(0, shownOpen), { breeze, gust: live.gust, time, hand });
          }
        };
    
        const layoutToCanvas = () => {
          const { width, height } = canvas.getBoundingClientRect();
          if (width === 0 || height === 0 || (width === shownWidth && height === shownHeight)) return;
          shownWidth = width;
          shownHeight = height;
          const ratio = Math.min(window.devicePixelRatio || 1, MAX_PIXEL_RATIO);
          aspect = width / height;
          renderer.resize(Math.round(width * ratio), Math.round(height * ratio), aspect);
          panels = createPanels(layout, aspect);
          settleSeconds = time + (SETTLE_STEPS * STEP_MS) / 1000;
          for (let index = 0; index < SETTLE_STEPS; index += 1) stepAll();
        };
    
        const handInWorld = (): ClothHand | undefined => {
          const hand = handRef?.current;
          if (!hand) return undefined;
          const rect = canvas.getBoundingClientRect();
          return {
            x: (((hand.clientX - rect.left) / rect.width) * 2 - 1) * aspect,
            y: 1 - ((hand.clientY - rect.top) / rect.height) * 2,
          };
        };
    
        layoutToCanvas();
        renderer.draw(panels);
    
        // Pause the simulation while off screen or the tab is in the background; resume from the current state on return.
        let onScreen = true;
        let frame = 0;
        let last = performance.now();
        let owed = 0;
        const tick = (now: number) => {
          owed = Math.min(owed + now - last, STEP_MS * MAX_STEPS_PER_FRAME);
          last = now;
          const hand = handInWorld();
          while (owed >= STEP_MS) {
            stepAll(hand);
            owed -= STEP_MS;
          }
          renderer.draw(panels);
          frame = requestAnimationFrame(tick);
        };
        const run = () => {
          cancelAnimationFrame(frame);
          frame = 0;
          if (!onScreen || document.hidden) return;
          last = performance.now();
          frame = requestAnimationFrame(tick);
        };
        run();
    
        const observer = new ResizeObserver(layoutToCanvas);
        observer.observe(canvas);
        const visibility = new IntersectionObserver(([entry]) => {
          onScreen = entry?.isIntersecting ?? true;
          run();
        });
        visibility.observe(canvas);
        document.addEventListener("visibilitychange", run);
        return () => {
          cancelAnimationFrame(frame);
          observer.disconnect();
          visibility.disconnect();
          document.removeEventListener("visibilitychange", run);
          renderer.dispose();
        };
        // The simulation is rebuilt only when the layout or cloth changes; open/breeze/gust go through liveRef and do not rebuild.
        // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [isStill, layout, sheer, openSeconds]);
    
      if (isStill || unavailable) {
        return <>{fallback ?? <StaticCurtain layout={layout} open={open} className={className} />}</>;
      }
      return (
        <canvas
          ref={canvasRef}
          className={cn("pointer-events-none absolute inset-0 h-full w-full", className)}
          aria-hidden="true"
        />
      );
    }
    
    cloth-simulation.ts
    /**
     * Cloth hung on a rod: a Verlet particle grid. Pure computation, no DOM, easy to unit test.
     *
     * World coordinates take the frame height as 2: y runs from 1 (top edge) to -1 (bottom edge), x from -aspect to
     * aspect, and z points toward the camera. Column 0 is the cloth's leading edge (the side the hand pulls), and the last column gathers on the
     * gatherSide side.
     */
    export const CLOTH_COLUMNS = 72;
    export const CLOTH_ROWS = 38;
    
    const STEP_SECONDS = 1 / 60;
    const SOLVER_ITERATIONS = 7;
    const DAMPING = 0.982;
    const GRAVITY = 2.6;
    /** How much wider the cloth is than the window: a curtain is never flat, and the extra cloth is what hangs into folds. */
    const FULLNESS = 1.55;
    const COLUMNS_PER_FOLD = 7;
    const RAIL_Y = 1.1;
    const DROP_LENGTH = 2.42;
    /** How wide the gathered cloth still is when fully opened. */
    const GATHERED_WIDTH = 0.34;
    const OFFSCREEN_MARGIN = 0.3;
    const NORMAL_SMOOTHING_PASSES = 3;
    const HAND_RADIUS = 0.7;
    const HAND_PULL = 0.03;
    const HAND_LIFT = 0.1;
    
    export interface ClothPanelSpec {
      /** Which side the cloth gathers toward when opened. */
      gatherSide: 1 | -1;
      /** When drawn shut, the x of the leading edge and of the outer edge on the gathered side. */
      leadX: number;
      edgeX: number;
      /** Half the frame width, which decides how far the cloth must retreat after opening to count as off screen. */
      aspect: number;
    }
    
    export interface ClothHand {
      x: number;
      y: number;
    }
    
    export interface ClothForces {
      /** Strength of the current ambient wind. */
      breeze: number;
      /** A strong gust that lifts the curtain, 0 to 1. */
      gust: number;
      time: number;
      hand?: ClothHand;
    }
    
    export interface ClothPanel {
      readonly positions: Float32Array;
      readonly normals: Float32Array;
      readonly uvs: Float32Array;
      readonly indices: Uint16Array;
      step(open: number, forces: ClothForces): void;
    }
    
    function particle(column: number, row: number): number {
      return row * CLOTH_COLUMNS + column;
    }
    
    /** Folds are unevenly spaced: equally wide waves look like corrugated cardboard. */
    function foldPhase(column: number): number {
      return (column * Math.PI * 2) / COLUMNS_PER_FOLD + 0.8 * Math.sin(column * 0.21) + 0.45 * Math.sin(column * 0.53);
    }
    
    function foldWeight(column: number): number {
      return 0.8 + 0.2 * Math.sin(column * 0.37 + 1.3);
    }
    
    export function createClothPanel(spec: ClothPanelSpec): ClothPanel {
      const count = CLOTH_COLUMNS * CLOTH_ROWS;
      const positions = new Float32Array(count * 3);
      const previous = new Float32Array(count * 3);
      const normals = new Float32Array(count * 3);
      const smoothed = new Float32Array(count * 3);
      const uvs = new Float32Array(count * 2);
      const indices = new Uint16Array((CLOTH_COLUMNS - 1) * (CLOTH_ROWS - 1) * 6);
    
      const closedSpacing = Math.abs(spec.edgeX - spec.leadX) / (CLOTH_COLUMNS - 1);
      const clothSpacing = closedSpacing * FULLNESS;
      const rowSpacing = DROP_LENGTH / (CLOTH_ROWS - 1);
      const openLeadX = spec.aspect * spec.gatherSide + spec.gatherSide * OFFSCREEN_MARGIN;
      const openEdgeX = openLeadX + spec.gatherSide * GATHERED_WIDTH;
    
      const pinned = new Float32Array(CLOTH_COLUMNS * 3);
    
      /**
       * Attachment points on the rod. The cloth length is constant, so the closer the points sit, the deeper the folds must bulge:
       * a sine wave has mean segment length sqrt(s² + (Ak)²/2); set it equal to the cloth length and solve for A.
       */
      const placeRail = (open: number) => {
        const leadX = spec.leadX + (openLeadX - spec.leadX) * open;
        const edgeX = spec.edgeX + (openEdgeX - spec.edgeX) * open;
        const spacing = Math.abs(edgeX - leadX) / (CLOTH_COLUMNS - 1);
        const slack = Math.max(0, clothSpacing * clothSpacing - spacing * spacing);
        const amplitude = Math.sqrt(2 * slack) / ((Math.PI * 2) / COLUMNS_PER_FOLD);
        for (let column = 0; column < CLOTH_COLUMNS; column += 1) {
          const u = column / (CLOTH_COLUMNS - 1);
          pinned[column * 3] = leadX + (edgeX - leadX) * u;
          pinned[column * 3 + 1] = RAIL_Y;
          pinned[column * 3 + 2] = Math.sin(foldPhase(column)) * amplitude * foldWeight(column);
        }
      };
    
      placeRail(0);
      for (let row = 0; row < CLOTH_ROWS; row += 1) {
        for (let column = 0; column < CLOTH_COLUMNS; column += 1) {
          const index = particle(column, row);
          positions[index * 3] = pinned[column * 3];
          positions[index * 3 + 1] = RAIL_Y - row * rowSpacing;
          positions[index * 3 + 2] = pinned[column * 3 + 2];
          uvs[index * 2] = column / (CLOTH_COLUMNS - 1);
          uvs[index * 2 + 1] = row / (CLOTH_ROWS - 1);
        }
      }
      previous.set(positions);
    
      const firsts: number[] = [];
      const seconds: number[] = [];
      const lengths: number[] = [];
      const stiffnesses: number[] = [];
      const link = (a: number, b: number, stiffness: number) => {
        firsts.push(a);
        seconds.push(b);
        lengths.push(
          Math.hypot(
            positions[a * 3] - positions[b * 3],
            positions[a * 3 + 1] - positions[b * 3 + 1],
            positions[a * 3 + 2] - positions[b * 3 + 2]
          )
        );
        stiffnesses.push(stiffness);
      };
    
      for (let row = 0; row < CLOTH_ROWS; row += 1) {
        for (let column = 0; column < CLOTH_COLUMNS; column += 1) {
          const here = particle(column, row);
          if (column + 1 < CLOTH_COLUMNS) link(here, particle(column + 1, row), 1);
          if (row + 1 < CLOTH_ROWS) link(here, particle(column, row + 1), 1);
          if (column + 1 < CLOTH_COLUMNS && row + 1 < CLOTH_ROWS) {
            link(here, particle(column + 1, row + 1), 0.22);
            link(particle(column + 1, row), particle(column, row + 1), 0.22);
          }
          if (column + 2 < CLOTH_COLUMNS) link(here, particle(column + 2, row), 0.12);
          if (row + 2 < CLOTH_ROWS) link(here, particle(column, row + 2), 0.4);
        }
      }
      const linkFirst = Uint16Array.from(firsts);
      const linkSecond = Uint16Array.from(seconds);
      const linkLength = Float32Array.from(lengths);
      const linkStiffness = Float32Array.from(stiffnesses);
    
      let cursor = 0;
      for (let row = 0; row < CLOTH_ROWS - 1; row += 1) {
        for (let column = 0; column < CLOTH_COLUMNS - 1; column += 1) {
          const a = particle(column, row);
          const b = particle(column + 1, row);
          const c = particle(column, row + 1);
          const d = particle(column + 1, row + 1);
          indices.set([a, c, b, b, c, d], cursor);
          cursor += 6;
        }
      }
    
      const computeNormals = () => {
        normals.fill(0);
        for (let face = 0; face < indices.length; face += 3) {
          const a = indices[face] * 3;
          const b = indices[face + 1] * 3;
          const c = indices[face + 2] * 3;
          const ux = positions[b] - positions[a];
          const uy = positions[b + 1] - positions[a + 1];
          const uz = positions[b + 2] - positions[a + 2];
          const vx = positions[c] - positions[a];
          const vy = positions[c + 1] - positions[a + 1];
          const vz = positions[c + 2] - positions[a + 2];
          const nx = uy * vz - uz * vy;
          const ny = uz * vx - ux * vz;
          const nz = ux * vy - uy * vx;
          normals[a] += nx;
          normals[a + 1] += ny;
          normals[a + 2] += nz;
          normals[b] += nx;
          normals[b + 1] += ny;
          normals[b + 2] += nz;
          normals[c] += nx;
          normals[c + 1] += ny;
          normals[c + 2] += nz;
        }
        for (let index = 0; index < count * 3; index += 3) {
          const length =
            Math.sqrt(normals[index] ** 2 + normals[index + 1] ** 2 + normals[index + 2] ** 2) || 1;
          normals[index] /= length;
          normals[index + 1] /= length;
          normals[index + 2] /= length;
        }
      };
    
      /** Smooths the normals: cel-shading tone boundaries trace the normals directly, so the mesh's small creases would turn into jaggies. */
      const smoothNormals = () => {
        for (let pass = 0; pass < NORMAL_SMOOTHING_PASSES; pass += 1) {
          smoothed.set(normals);
          for (let row = 1; row < CLOTH_ROWS - 1; row += 1) {
            for (let column = 1; column < CLOTH_COLUMNS - 1; column += 1) {
              const i3 = particle(column, row) * 3;
              const up = i3 - CLOTH_COLUMNS * 3;
              const down = i3 + CLOTH_COLUMNS * 3;
              for (let axis = 0; axis < 3; axis += 1) {
                normals[i3 + axis] =
                  (smoothed[i3 + axis] * 2 +
                    smoothed[i3 - 3 + axis] +
                    smoothed[i3 + 3 + axis] +
                    smoothed[up + axis] +
                    smoothed[down + axis]) /
                  6;
              }
            }
          }
        }
      };
    
      computeNormals();
    
      const step = (open: number, forces: ClothForces) => {
        placeRail(open);
        const { breeze, gust, time, hand } = forces;
        const stepSquared = STEP_SECONDS * STEP_SECONDS;
    
        for (let index = 0; index < count; index += 1) {
          const i3 = index * 3;
          const x = positions[i3];
          const y = positions[i3 + 1];
          const z = positions[i3 + 2];
          const hang = uvs[index * 2 + 1];
    
          // Wind only pushes cloth facing it; sideways folds catch no wind, so the cloth billows instead of translating as a whole.
          const wave = Math.sin(x * 1.5 + time * 1.15 + y * 1.1) + 0.6 * Math.sin(x * 3.1 - time * 0.8 + y * 2.3);
          const windX = (0.05 * Math.sin(time * 0.6) + wave * 0.02) * breeze;
          const windZ = (0.1 + 0.11 * wave) * breeze + gust * (0.7 + 0.35 * wave);
          const facing = normals[i3] * windX + normals[i3 + 2] * windZ;
          const push = facing * (0.3 + hang * hang * 2.4);
    
          const velocityX = (x - previous[i3]) * DAMPING;
          const velocityY = (y - previous[i3 + 1]) * DAMPING;
          const velocityZ = (z - previous[i3 + 2]) * DAMPING;
          previous[i3] = x;
          previous[i3 + 1] = y;
          previous[i3 + 2] = z;
          positions[i3] = x + velocityX + normals[i3] * push * stepSquared * 60;
          positions[i3 + 1] = y + velocityY + (gust * hang * hang * 1.8 - GRAVITY) * stepSquared;
          positions[i3 + 2] = z + velocityZ + normals[i3 + 2] * push * stepSquared * 60;
    
          if (hand) {
            const distance = Math.sqrt((x - hand.x) ** 2 + (y - hand.y) ** 2);
            if (distance < HAND_RADIUS) {
              const grip = (1 - distance / HAND_RADIUS) ** 2;
              positions[i3] += (hand.x - x) * grip * HAND_PULL;
              positions[i3 + 1] += (hand.y - y) * grip * HAND_PULL * 0.6;
              positions[i3 + 2] += (HAND_LIFT - z) * grip * HAND_PULL;
            }
          }
        }
    
        for (let iteration = 0; iteration < SOLVER_ITERATIONS; iteration += 1) {
          for (let index = 0; index < linkFirst.length; index += 1) {
            const a = linkFirst[index] * 3;
            const b = linkSecond[index] * 3;
            const deltaX = positions[b] - positions[a];
            const deltaY = positions[b + 1] - positions[a + 1];
            const deltaZ = positions[b + 2] - positions[a + 2];
            const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ) || 1e-6;
            const correction = ((distance - linkLength[index]) / distance) * 0.5 * linkStiffness[index];
            positions[a] += deltaX * correction;
            positions[a + 1] += deltaY * correction;
            positions[a + 2] += deltaZ * correction;
            positions[b] -= deltaX * correction;
            positions[b + 1] -= deltaY * correction;
            positions[b + 2] -= deltaZ * correction;
          }
          positions.set(pinned);
        }
    
        computeNormals();
        smoothNormals();
      };
    
      return { positions, normals, uvs, indices, step };
    }
    
    cloth-renderer.ts
    import type { ClothPanel } from "./cloth-simulation";
    
    /** Distance from the camera to the z=0 plane. Points at z=0 land exactly on frame coordinates; only the depth of the folds produces perspective. */
    const CAMERA_DISTANCE = 3.2;
    
    const VERTEX_SHADER = `
    attribute vec3 aPosition;
    attribute vec3 aNormal;
    attribute vec2 aUv;
    uniform float uAspect;
    varying vec3 vPosition;
    varying vec3 vNormal;
    varying vec2 vUv;
    void main() {
      vPosition = aPosition;
      vNormal = aNormal;
      vUv = aUv;
      float w = (${CAMERA_DISTANCE.toFixed(1)} - aPosition.z) / ${CAMERA_DISTANCE.toFixed(1)};
      gl_Position = vec4(aPosition.x / uAspect, aPosition.y, -aPosition.z * 0.1, w);
    }
    `;
    
    /**
     * Anime-style cel shading to match the scene and character art: the cloth motion is physically simulated, but the colours are painted.
     * Only three tones (light, mid, dark), shadows shift toward blue-violet, and folds turned sideways get a thin line.
     * No fabric texture or continuous gradients: add either and it becomes realistic cloth, detached from the background.
     */
    const fragmentShader = (tones: ClothTones) => `
    precision highp float;
    uniform float uSheer;
    varying vec3 vPosition;
    varying vec3 vNormal;
    varying vec2 vUv;
    
    const vec3 LIGHT_TONE = ${vec3(tones.light)};
    const vec3 BASE_TONE = ${vec3(tones.base)};
    const vec3 SHADOW_TONE = ${vec3(tones.shadow)};
    const vec3 LINE_TONE = ${vec3(tones.line)};
    
    void main() {
      vec3 view = normalize(vec3(0.0, 0.0, ${CAMERA_DISTANCE.toFixed(1)}) - vPosition);
      vec3 normal = normalize(vNormal);
      if (dot(normal, view) < 0.0) normal = -normal;
    
      float facing = clamp(dot(normal, view), 0.0, 1.0);
      float lit = dot(normal, normalize(vec3(-0.62, 0.3, 0.72))) + vPosition.z * 0.9;
    
      vec3 color = mix(SHADOW_TONE, BASE_TONE, smoothstep(0.4, 0.46, lit));
      color = mix(color, LIGHT_TONE, smoothstep(0.8, 0.86, lit));
      color = mix(color, LINE_TONE, smoothstep(0.2, 0.14, facing));
    
      float hem = step(0.965, vUv.y) * (1.0 - step(0.972, vUv.y));
      color = mix(color, SHADOW_TONE, hem);
    
      float alpha = 1.0 - uSheer * smoothstep(0.4, 0.46, lit);
      gl_FragColor = vec4(color * alpha, alpha);
    }
    `;
    
    /** Colours of the three cel tones plus the outline, each an RGB in 0 to 1. Defaults to a thick dark wine-red curtain; the original pink can be passed back through tones. */
    export interface ClothTones {
      light: readonly [number, number, number];
      base: readonly [number, number, number];
      shadow: readonly [number, number, number];
      line: readonly [number, number, number];
    }
    
    export const DEFAULT_CLOTH_TONES: ClothTones = {
      light: [0.6, 0.27, 0.22],
      base: [0.45, 0.18, 0.15],
      shadow: [0.27, 0.11, 0.1],
      line: [0.14, 0.06, 0.06],
    };
    
    function vec3([r, g, b]: readonly [number, number, number]): string {
      return `vec3(${r.toFixed(3)}, ${g.toFixed(3)}, ${b.toFixed(3)})`;
    }
    
    export interface ClothRenderer {
      resize(pixelWidth: number, pixelHeight: number, aspect: number): void;
      draw(panels: ClothPanel[]): void;
      dispose(): void;
    }
    
    function compile(gl: WebGLRenderingContext, type: number, source: string): WebGLShader | null {
      const shader = gl.createShader(type);
      if (!shader) return null;
      gl.shaderSource(shader, source);
      gl.compileShader(shader);
      return gl.getShaderParameter(shader, gl.COMPILE_STATUS) ? shader : null;
    }
    
    /** Returns undefined when the device has no WebGL, so the caller draws a static curtain instead. */
    export function createClothRenderer(
      canvas: HTMLCanvasElement,
      sheer: number,
      tones: ClothTones = DEFAULT_CLOTH_TONES
    ): ClothRenderer | undefined {
      const gl = canvas.getContext("webgl", { alpha: true, antialias: true, premultipliedAlpha: true });
      if (!gl) return undefined;
    
      const vertex = compile(gl, gl.VERTEX_SHADER, VERTEX_SHADER);
      const fragment = compile(gl, gl.FRAGMENT_SHADER, fragmentShader(tones));
      const program = gl.createProgram();
      if (!vertex || !fragment || !program) return undefined;
      gl.attachShader(program, vertex);
      gl.attachShader(program, fragment);
      gl.linkProgram(program);
      if (!gl.getProgramParameter(program, gl.LINK_STATUS)) return undefined;
      gl.useProgram(program);
    
      const positionBuffer = gl.createBuffer();
      const normalBuffer = gl.createBuffer();
      const uvBuffer = gl.createBuffer();
      const indexBuffer = gl.createBuffer();
      const bindAttribute = (name: string, size: number, buffer: WebGLBuffer | null) => {
        const location = gl.getAttribLocation(program, name);
        gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
        gl.enableVertexAttribArray(location);
        gl.vertexAttribPointer(location, size, gl.FLOAT, false, 0, 0);
      };
    
      gl.uniform1f(gl.getUniformLocation(program, "uSheer"), sheer);
      const aspectLocation = gl.getUniformLocation(program, "uAspect");
    
      gl.enable(gl.DEPTH_TEST);
      gl.enable(gl.BLEND);
      gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
      gl.clearColor(0, 0, 0, 0);
    
      return {
        resize(pixelWidth, pixelHeight, aspect) {
          canvas.width = pixelWidth;
          canvas.height = pixelHeight;
          gl.viewport(0, 0, pixelWidth, pixelHeight);
          gl.uniform1f(aspectLocation, aspect);
        },
        draw(panels) {
          gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
          for (const panel of panels) {
            gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
            gl.bufferData(gl.ARRAY_BUFFER, panel.positions, gl.DYNAMIC_DRAW);
            bindAttribute("aPosition", 3, positionBuffer);
            gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);
            gl.bufferData(gl.ARRAY_BUFFER, panel.normals, gl.DYNAMIC_DRAW);
            bindAttribute("aNormal", 3, normalBuffer);
            gl.bindBuffer(gl.ARRAY_BUFFER, uvBuffer);
            gl.bufferData(gl.ARRAY_BUFFER, panel.uvs, gl.STATIC_DRAW);
            bindAttribute("aUv", 2, uvBuffer);
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
            gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, panel.indices, gl.STATIC_DRAW);
            gl.drawElements(gl.TRIANGLES, panel.indices.length, gl.UNSIGNED_SHORT, 0);
          }
        },
        dispose() {
          // Must not loseContext: when the same canvas remounts (StrictMode does this) it needs a usable context again.
          for (const buffer of [positionBuffer, normalBuffer, uvBuffer, indexBuffer]) gl.deleteBuffer(buffer);
          gl.deleteProgram(program);
          gl.deleteShader(vertex);
          gl.deleteShader(fragment);
        },
      };
    }