• 01 - Games
  • 02 - Creative Instruments & Explorers
  • 03 - Language, Signals & Text
  • 04 - Developer & Web Utilities
  • 05 - Generators & Data
  • 06 - Colour Theory
  • 07 - Music 26
  • 08 - 3D, Shaders & Visuals
ARCHIVE
  • Pip
  • Great White
  • Canyon Run
  • Diamond Vessel
  • T-6 Jedi Shuttle
  • N1 Starfighter
  • Clawdia

CLAWDIA SOURCE CODE

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Clawdia the Lobster</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Fredoka:wght@400;500;600&display=swap">
<style>
  :root {
    box-sizing: border-box;
    padding-top: env(safe-area-inset-top, 0px);
    padding-bottom: env(safe-area-inset-bottom, 0px);
    color-scheme: light;
    --mode: 0;
    --water-top: #aef0ef;
    --water-mid: #53bdd3;
    --water-deep: #176fa0;
    --fog: #55b8cf;
    --sunlight: rgba(255, 252, 226, 0.9);
    --vignette: rgba(6, 52, 82, 0.26);
    --ink: #073a4f;
    --ink-soft: rgba(7, 58, 79, 0.74);
    --glass: rgba(255, 255, 255, 0.46);
    --glass-strong: rgba(255, 255, 255, 0.74);
    --glass-edge: rgba(255, 255, 255, 0.82);
    --accent: #ef8a25;
    --accent-ink: #ffffff;
  }
  @media (prefers-color-scheme: dark) {
    :root:not([data-theme="light"]) {
      color-scheme: dark;
      --mode: 1;
      --water-top: #143f69;
      --water-mid: #0b2748;
      --water-deep: #030916;
      --fog: #0c2848;
      --sunlight: rgba(150, 200, 255, 0.3);
      --vignette: rgba(0, 4, 12, 0.6);
      --ink: #e3f6ff;
      --ink-soft: rgba(227, 246, 255, 0.72);
      --glass: rgba(8, 30, 56, 0.5);
      --glass-strong: rgba(14, 44, 80, 0.82);
      --glass-edge: rgba(130, 200, 255, 0.26);
      --accent: #ffbe45;
      --accent-ink: #1c1203;
    }
  }
  :root[data-theme="dark"] {
    color-scheme: dark;
    --mode: 1;
    --water-top: #143f69;
    --water-mid: #0b2748;
    --water-deep: #030916;
    --fog: #0c2848;
    --sunlight: rgba(150, 200, 255, 0.3);
    --vignette: rgba(0, 4, 12, 0.6);
    --ink: #e3f6ff;
    --ink-soft: rgba(227, 246, 255, 0.72);
    --glass: rgba(8, 30, 56, 0.5);
    --glass-strong: rgba(14, 44, 80, 0.82);
    --glass-edge: rgba(130, 200, 255, 0.26);
    --accent: #ffbe45;
    --accent-ink: #1c1203;
  }
  html { height: 100%; scroll-padding-top: env(safe-area-inset-top, 0px); }
  body {
    height: 100%;
    margin: 0;
    overflow: hidden;
    background: linear-gradient(180deg, var(--water-top), var(--water-deep));
    color: var(--ink);
    font-family: "Fredoka", ui-rounded, "SF Pro Rounded", "Hiragino Maru Gothic ProN", "Arial Rounded MT Bold", system-ui, sans-serif;
    -webkit-font-smoothing: antialiased;
    -webkit-tap-highlight-color: transparent;
  }
  #stage {
    position: relative;
    width: 100%;
    height: 100%;
    overflow: hidden;
    background:
      radial-gradient(110% 60% at 28% -12%, var(--sunlight), transparent 62%),
      linear-gradient(180deg, var(--water-top) 0%, var(--water-mid) 44%, var(--water-deep) 100%);
  }
  #stage canvas {
    position: absolute;
    top: 0; left: 0;
    width: 100%; height: 100%;
    display: block;
    touch-action: none;
    outline: none;
  }
  .vignette {
    position: absolute;
    top: 0; left: 0; right: 0; bottom: 0;
    pointer-events: none;
    background: radial-gradient(130% 95% at 50% 38%, transparent 55%, var(--vignette) 100%);
  }
  .title {
    position: absolute;
    top: 42%;
    transform: translateY(-50%);
    left: clamp(16px, 3.4vw, 34px);
    pointer-events: none;
    user-select: none;
    -webkit-user-select: none;
  }
  .title h1 {
    margin: 0;
    font-weight: 600;
    font-size: clamp(30px, 5vw, 52px);
    line-height: 1;
  }
  .title p {
    margin: 6px 0 0;
    font-size: clamp(14px, 1.6vw, 17px);
    color: var(--ink-soft);
  }
  .bar {
    position: absolute;
    left: 0; right: 0; bottom: 0;
    padding: 0 clamp(12px, 3vw, 28px) clamp(12px, 3vw, 24px);
    display: flex;
    flex-wrap: wrap;
    align-items: flex-end;
    justify-content: space-between;
    gap: 10px;
    pointer-events: none;
  }
  .hint {
    margin: 0;
    padding: 9px 15px;
    border-radius: 18px;
    font-size: 15px;
    line-height: 1.3;
    max-width: 34em;
    background: var(--glass);
    border: 1px solid var(--glass-edge);
    -webkit-backdrop-filter: blur(10px);
    backdrop-filter: blur(10px);
    transition: opacity 0.7s ease, transform 0.7s ease;
  }
  .hint.gone { opacity: 0; transform: translateY(8px); }
  .actions { display: flex; gap: 8px; margin-left: auto; pointer-events: auto; }
  .btn {
    appearance: none;
    -webkit-appearance: none;
    font: inherit;
    font-size: 16px;
    font-weight: 500;
    color: var(--ink);
    background: var(--glass-strong);
    border: 1px solid var(--glass-edge);
    padding: 10px 18px;
    border-radius: 999px;
    cursor: pointer;
    -webkit-backdrop-filter: blur(10px);
    backdrop-filter: blur(10px);
    transition: transform 0.15s ease;
  }
  .btn:active { transform: translateY(1px) scale(0.97); }
  .btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
  .btn.primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
  .fallback {
    position: absolute;
    top: 0; left: 0; right: 0; bottom: 0;
    display: grid;
    place-items: center;
    padding: 32px;
    text-align: center;
    font-size: 17px;
  }
  @media (max-width: 767px) {
    .bar { padding: 0 24px 96px; }
  }
  @media (min-width: 768px) {
    .title { left: 80px; }
    .bar { padding: 0 80px 84px; }
  }
  @media (max-width: 520px) {
    .hint { font-size: 14px; }
    .btn { padding: 9px 15px; font-size: 15px; }
  }
  @media (prefers-reduced-motion: reduce) {
    .hint, .btn { transition: none; }
  }
</style>
</head>
<body>
<div id="stage">
  <div class="vignette" aria-hidden="true"></div>
  <header class="title">
    <h1>Clawdia</h1>
    <p>A snappy little reef lobster</p>
  </header>
  <div class="bar">
    <p class="hint" id="hint">Tap Clawdia to make her snap, or tap the sand to drop food.</p>
    <div class="actions">
      <button class="btn" id="feedBtn" type="button">Drop food</button>
      <button class="btn primary" id="snapBtn" type="button">Snap claws</button>
    </div>
  </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
(() => {
  'use strict';

  const stage = document.getElementById('stage');
  const hintEl = document.getElementById('hint');
  const snapBtn = document.getElementById('snapBtn');
  const feedBtn = document.getElementById('feedBtn');

  function fail(msg) {
    const d = document.createElement('div');
    d.className = 'fallback';
    d.textContent = msg;
    stage.appendChild(d);
    const bar = document.querySelector('.bar');
    if (bar) bar.style.display = 'none';
  }
  if (!window.THREE) { fail('The 3D library didn’t load. Check your connection and refresh the page.'); return; }

  let hintGone = false;
  const dismissHint = () => { if (!hintGone) { hintGone = true; hintEl.classList.add('gone'); } };

  // ─── Helpers ──────────────────────────────────────────────────────────
  const V3 = THREE.Vector3;
  const TAU = Math.PI * 2;
  const clamp = (v, a, b) => (v < a ? a : v > b ? b : v);
  const lerp = (a, b, t) => a + (b - a) * t;
  const damp = (a, b, k, dt) => lerp(a, b, 1 - Math.exp(-k * dt));
  const smoothstep = (a, b, x) => { const t = clamp((x - a) / (b - a), 0, 1); return t * t * (3 - 2 * t); };
  const wrapAngle = (a) => Math.atan2(Math.sin(a), Math.cos(a));
  const dampAngle = (a, b, k, dt) => a + wrapAngle(b - a) * (1 - Math.exp(-k * dt));
  let seed = 4021;
  const rand = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
  const rr = (a, b) => a + (b - a) * rand();
  const MOTION = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 0.5 : 1;

  // ─── Renderer, scene, camera, lights ──────────────────────────────────
  let renderer;
  try {
    renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, powerPreference: 'high-performance' });
  } catch (err) {
    fail('This little aquarium needs WebGL, which isn’t available in this browser.');
    return;
  }
  renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
  renderer.setClearColor(0x000000, 0);
  const canvas = renderer.domElement;
  canvas.setAttribute('role', 'img');
  canvas.setAttribute('aria-label', 'Clawdia, a cartoon lobster, walking across a coral reef floor');
  stage.insertBefore(canvas, stage.firstChild);

  const scene = new THREE.Scene();
  scene.fog = new THREE.Fog(0x55b8cf, 9, 34);
  const camera = new THREE.PerspectiveCamera(38, 1, 0.1, 120);
  const tanHalf = Math.tan(THREE.MathUtils.degToRad(camera.fov / 2));
  const camLook = new V3(0, -1.25, 0);
  let camDist = 7.3, viewHalfW = 4, viewTop = 2.5;

  const hemi = new THREE.HemisphereLight(0xc8f5ff, 0xe6cc98, 0.72);
  const key = new THREE.DirectionalLight(0xfff0cf, 0.85);
  key.position.set(-3, 8, 6);
  const rim = new THREE.DirectionalLight(0xa9f2ff, 0.5);
  rim.position.set(5, 2.5, -6);
  scene.add(hemi, key, rim);

  // ─── Sand height (shared by JS and the sand shader) ───────────────────
  const SAND_Y = -2.3;
  const duneH = (x, z) =>
    0.16 * Math.sin(x * 0.35 + 1.3) * Math.cos(z * 0.3) +
    0.07 * Math.sin(x * 0.9 + z * 0.6) +
    0.05 * Math.cos(z * 1.1 - x * 0.4);
  const sandAt = (x, z) => SAND_Y + duneH(x, z);

  // ─── Textures painted on 2D canvases ──────────────────────────────────
  const maxAniso = renderer.capabilities.getMaxAnisotropy();
  const makeCanvas = (w, h) => { const c = document.createElement('canvas'); c.width = w; c.height = h; return c; };
  const uvToDir = (u, v) => {
    const th = v * Math.PI, ph = u * TAU;
    return new V3(-Math.cos(ph) * Math.sin(th), Math.cos(th), Math.sin(ph) * Math.sin(th));
  };
  const dirToUV = (d) => ({
    u: ((Math.atan2(d.z, -d.x) / TAU) % 1 + 1) % 1,
    v: Math.acos(clamp(d.y, -1, 1)) / Math.PI,
  });

  // Mottled lobster shell: deep crimson back fading to a pale belly.
  function paintShell() {
    const W = 1024, H = 512;
    const cMap = makeCanvas(W, H), cGlow = makeCanvas(W, H);
    const g = cMap.getContext('2d'), gg = cGlow.getContext('2d');

    const grad = g.createLinearGradient(0, 0, 0, H);
    [[0, '#5d160c'], [0.16, '#84260f'], [0.32, '#b03c1b'], [0.46, '#d0612c'],
     [0.58, '#e79a55'], [0.72, '#f3c58c'], [1, '#fce4bd']]
      .forEach(([o, c]) => grad.addColorStop(o, c));
    g.fillStyle = grad;
    g.fillRect(0, 0, W, H);
    gg.fillStyle = '#000';
    gg.fillRect(0, 0, W, H);

    for (let i = 0; i < 1100; i++) {
      const u = rand(), v = Math.pow(rand(), 1.3) * 0.7;
      const s = Math.max(Math.sin(v * Math.PI), 0.12), r = rr(2, 10);
      g.fillStyle = `rgba(74,18,10,${rr(0.03, 0.11).toFixed(3)})`;
      g.beginPath(); g.ellipse(u * W, v * H, r / s, r, 0, 0, TAU); g.fill();
    }
    for (let i = 0; i < 900; i++) {
      const u = rand(), v = Math.pow(rand(), 1.2) * 0.58;
      const s = Math.max(Math.sin(v * Math.PI), 0.12), r = rr(0.8, 3);
      g.fillStyle = `rgba(255,216,164,${rr(0.04, 0.16).toFixed(3)})`;
      g.beginPath(); g.ellipse(u * W, v * H, r / s, r, 0, 0, TAU); g.fill();
    }

    const spots = [];
    for (let tries = 0; spots.length < 70 && tries < 5000; tries++) {
      const u = rand(), v = rr(0.06, 0.55);
      const a = rr(0.03, 0.062), d = uvToDir(u, v);
      if (spots.some((s) => d.angleTo(s.d) < a + s.a + 0.06)) continue;
      spots.push({ u, v, a, d });
    }
    for (const s of spots) {
      const ry = (s.a * H) / Math.PI;
      const rx = ry / Math.max(Math.sin(s.v * Math.PI), 0.12);
      for (const off of [-W, 0, W]) {
        const x = s.u * W + off, y = s.v * H;
        if (x + rx < 0 || x - rx > W) continue;
        g.fillStyle = 'rgba(255,236,196,0.7)';
        g.beginPath(); g.ellipse(x, y, rx, ry, 0, 0, TAU); g.fill();
        gg.fillStyle = '#ffffff';
        gg.beginPath(); gg.ellipse(x, y, rx * 0.8, ry * 0.8, 0, 0, TAU); gg.fill();
      }
    }

    const map = new THREE.CanvasTexture(cMap);
    const glow = new THREE.CanvasTexture(cGlow);
    map.anisotropy = glow.anisotropy = maxAniso;
    return { map, glow };
  }

  // Fine speckle used by the corals.
  function paintSpeckle() {
    const S = 256;
    const c = makeCanvas(S, S), g = c.getContext('2d');
    g.fillStyle = '#f2ece6';
    g.fillRect(0, 0, S, S);
    for (let i = 0; i < 1100; i++) {
      const x = rand() * S, y = rand() * S, r = rr(0.8, 3.4);
      g.globalAlpha = rr(0.06, 0.28);
      g.fillStyle = rand() < 0.55 ? '#5c3548' : '#ffffff';
      g.beginPath(); g.arc(x, y, r, 0, TAU); g.fill();
    }
    g.globalAlpha = 1;
    const t = new THREE.CanvasTexture(c);
    t.wrapS = t.wrapT = THREE.RepeatWrapping;
    t.repeat.set(3, 3);
    t.anisotropy = maxAniso;
    return t;
  }

  // Fan-shaped ribbed membrane (used for sea fans).
  function paintFin() {
    const N = 256;
    const c = makeCanvas(N, N), g = c.getContext('2d');
    const img = g.createImageData(N, N), d = img.data;
    for (let y = 0; y < N; y++) {
      for (let x = 0; x < N; x++) {
        const px = ((x + 0.5) / N) * 2 - 1, py = 1 - ((y + 0.5) / N) * 2;
        const r = Math.hypot(px, py), ang = Math.atan2(py, px);
        const ribC = Math.abs(Math.cos(ang * 9));
        const rib = Math.pow(ribC, 10);
        const edge = 0.84 + 0.12 * Math.pow(ribC, 3);
        let a = 1 - smoothstep(edge - 0.05, edge, r);
        a *= 0.5 + 0.35 * (1 - r) + 0.35 * rib;
        const shade = 1 - 0.32 * rib * smoothstep(0.1, 0.5, r);
        const i = (y * N + x) * 4;
        d[i] = d[i + 1] = d[i + 2] = Math.round(255 * shade);
        d[i + 3] = Math.round(255 * clamp(a, 0, 1));
      }
    }
    g.putImageData(img, 0, 0);
    const t = new THREE.CanvasTexture(c);
    t.anisotropy = maxAniso;
    return t;
  }

  // Soft vertical beam for the sun rays.
  function paintRay() {
    const W = 64, H = 256;
    const c = makeCanvas(W, H), g = c.getContext('2d');
    const img = g.createImageData(W, H), d = img.data;
    for (let y = 0; y < H; y++) {
      for (let x = 0; x < W; x++) {
        const u = ((x + 0.5) / W) * 2 - 1, v = (y + 0.5) / H;
        const prof = Math.exp(-u * u * 4.5) * (1 - smoothstep(0.85, 1, Math.abs(u)));
        const fall = Math.pow(1 - v, 1.6) * smoothstep(0, 0.08, v);
        const i = (y * W + x) * 4;
        d[i] = d[i + 1] = d[i + 2] = 255;
        d[i + 3] = Math.round(255 * prof * fall);
      }
    }
    g.putImageData(img, 0, 0);
    return new THREE.CanvasTexture(c);
  }

  // ─── Sand with animated caustics ──────────────────────────────────────
  const DUNE_GLSL = `
    float duneH(vec2 p) {
      return 0.16 * sin(p.x * 0.35 + 1.3) * cos(p.y * 0.3)
           + 0.07 * sin(p.x * 0.9 + p.y * 0.6)
           + 0.05 * cos(p.y * 1.1 - p.x * 0.4);
    }`;
  const sandVS = `
    varying vec3 vWorld;
    varying vec3 vN;
    varying float vDepth;
    #include <fog_pars_vertex>
    ${DUNE_GLSL}
    void main() {
      vec3 p = position;
      p.y += duneH(p.xz);
      float e = 0.06;
      float hx = duneH(p.xz + vec2(e, 0.0)) - duneH(p.xz - vec2(e, 0.0));
      float hz = duneH(p.xz + vec2(0.0, e)) - duneH(p.xz - vec2(0.0, e));
      vN = normalize(vec3(-hx, 2.0 * e, -hz));
      vec4 world = modelMatrix * vec4(p, 1.0);
      vWorld = world.xyz;
      vec4 mvPosition = viewMatrix * world;
      vDepth = -mvPosition.z;
      gl_Position = projectionMatrix * mvPosition;
      #include <fog_vertex>
    }`;
  const sandFS = `
    uniform float uTime;
    uniform vec3 uSand;
    uniform vec3 uSandDark;
    uniform vec3 uCaustic;
    uniform float uCausticStrength;
    uniform vec4 uShadow;
    uniform vec3 uLightDir;
    uniform vec2 uFade;
    uniform vec2 uDetail;
    varying vec3 vWorld;
    varying vec3 vN;
    varying float vDepth;
    #include <fog_pars_fragment>
    float hash1(vec2 p) { return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453); }
    vec2 hash2(vec2 p) {
      p = vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3)));
      return fract(sin(p) * 43758.5453);
    }
    float vnoise(vec2 p) {
      vec2 i = floor(p);
      vec2 f = fract(p);
      vec2 u = f * f * (3.0 - 2.0 * f);
      return mix(mix(hash1(i), hash1(i + vec2(1.0, 0.0)), u.x),
                 mix(hash1(i + vec2(0.0, 1.0)), hash1(i + vec2(1.0, 1.0)), u.x), u.y);
    }
    float caustic(vec2 p, float t) {
      vec2 ip = floor(p);
      vec2 fp = fract(p);
      float d1 = 8.0;
      float d2 = 8.0;
      for (int j = -1; j <= 1; j++) {
        for (int i = -1; i <= 1; i++) {
          vec2 g = vec2(float(i), float(j));
          vec2 o = hash2(ip + g);
          o = 0.5 + 0.42 * sin(t + 6.2831 * o);
          vec2 r = g + o - fp;
          float d = dot(r, r);
          if (d < d1) { d2 = d1; d1 = d; }
          else if (d < d2) { d2 = d; }
        }
      }
      float edge = sqrt(d2) - sqrt(d1);
      return pow(1.0 - smoothstep(0.0, 0.09, edge), 2.5);
    }
    void main() {
      vec2 p = vWorld.xz;
      float detail = 1.0 - smoothstep(uDetail.x, uDetail.y, vDepth);
      float n = vnoise(p * 0.55) * 0.65 + vnoise(p * 2.1 + 7.0) * 0.35;
      vec3 col = mix(uSandDark, uSand, n);
      col *= 1.0 + (hash1(floor(p * 70.0)) - 0.5) * 0.1 * detail;
      float diff = max(dot(normalize(vN), uLightDir), 0.0);
      col *= 0.7 + 0.4 * diff;
      float t = uTime;
      vec2 q = p + 0.45 * vec2(vnoise(p * 0.8 + t * 0.12), vnoise(p * 0.8 + 5.3 - t * 0.1));
      float c = caustic(q * 1.5 + vec2(t * 0.05, t * 0.03), t * 0.75);
      c = max(c * 0.75, caustic(q * 2.2 + vec2(3.7, 1.2) - vec2(t * 0.04, -t * 0.025), -t * 0.6) * 0.55);
      c *= detail;
      float sd = length(p - uShadow.xy);
      float sh = uShadow.z * (1.0 - smoothstep(0.0, uShadow.w, sd));
      col += uCaustic * c * uCausticStrength * (1.0 - sh);
      col *= 1.0 - sh * 0.6;
      gl_FragColor = vec4(col, 1.0);
      #include <fog_fragment>
      gl_FragColor.a = 1.0 - smoothstep(uFade.x, uFade.y, vDepth);
    }`;
  const sandGeo = new THREE.PlaneGeometry(90, 90, 180, 180);
  sandGeo.rotateX(-Math.PI / 2);
  const sandMat = new THREE.ShaderMaterial({
    uniforms: THREE.UniformsUtils.merge([THREE.UniformsLib.fog, {
      uTime: { value: 0 },
      uSand: { value: new THREE.Color('#e9d6ac') },
      uSandDark: { value: new THREE.Color('#c6ad7e') },
      uCaustic: { value: new THREE.Color('#fffbea') },
      uCausticStrength: { value: 0.6 },
      uShadow: { value: new THREE.Vector4(0, 0, 0, 1) },
      uLightDir: { value: new V3(-0.3, 1, 0.45).normalize() },
      uFade: { value: new THREE.Vector2(14, 40) },
      uDetail: { value: new THREE.Vector2(11, 26) },
    }]),
    vertexShader: sandVS,
    fragmentShader: sandFS,
    fog: true,
    transparent: true,
  });
  const sand = new THREE.Mesh(sandGeo, sandMat);
  sand.position.y = SAND_Y;
  sand.renderOrder = -1;
  scene.add(sand);

  // ─── Rocks ────────────────────────────────────────────────────────────
  function weldNormals(geo) {
    const pos = geo.attributes.position, nrm = geo.attributes.normal, groups = new Map();
    for (let i = 0; i < pos.count; i++) {
      const k = `${pos.getX(i).toFixed(3)},${pos.getY(i).toFixed(3)},${pos.getZ(i).toFixed(3)}`;
      let e = groups.get(k);
      if (!e) { e = { n: new V3(), idx: [] }; groups.set(k, e); }
      e.n.x += nrm.getX(i); e.n.y += nrm.getY(i); e.n.z += nrm.getZ(i);
      e.idx.push(i);
    }
    groups.forEach((e) => { e.n.normalize(); e.idx.forEach((i) => nrm.setXYZ(i, e.n.x, e.n.y, e.n.z)); });
    nrm.needsUpdate = true;
  }
  const rockBase = new THREE.Color('#7b8a8e'), rockDark = new THREE.Color('#4c5a63'), rockMoss = new THREE.Color('#6f9150');
  function rockGeometry(r, s) {
    const geo = new THREE.SphereGeometry(r, 36, 26);
    const pos = geo.attributes.position, v = new V3();
    for (let i = 0; i < pos.count; i++) {
      v.fromBufferAttribute(pos, i).normalize();
      const n = Math.sin(v.x * 2.1 + s) * Math.cos(v.y * 2.7 - s * 0.7) * 0.5 +
        Math.sin(v.z * 3.3 + v.x * 1.7 + s * 1.3) * 0.3 +
        Math.sin((v.x + v.y + v.z) * 6 + s) * 0.06;
      v.multiplyScalar(r * (1 + 0.2 * n));
      pos.setXYZ(i, v.x, v.y, v.z);
    }
    geo.computeVertexNormals();
    weldNormals(geo);
    const nrm = geo.attributes.normal, cols = new Float32Array(pos.count * 3), c = new THREE.Color();
    for (let i = 0; i < pos.count; i++) {
      const ny = nrm.getY(i);
      c.copy(rockBase).lerp(rockDark, smoothstep(0.2, -0.6, ny)).lerp(rockMoss, smoothstep(0.45, 0.95, ny) * 0.6);
      cols[i * 3] = c.r; cols[i * 3 + 1] = c.g; cols[i * 3 + 2] = c.b;
    }
    geo.setAttribute('color', new THREE.BufferAttribute(cols, 3));
    return geo;
  }
  const rockMat = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.92 });
  [
    [-6.6, -4.8, 1.1, 1.4, 0.75, 1.1], [-3.3, -3.7, 0.55, 1.2, 0.8, 1], [5.4, -3.0, 0.9, 1.3, 0.8, 1],
    [6.5, -2.1, 0.45, 1.2, 0.75, 1.1], [-1.4, -8.6, 1.4, 1.5, 0.7, 1.2], [2.8, -9.6, 1.0, 1.3, 0.8, 1],
    [-8.0, -7.2, 1.2, 1.3, 0.8, 1.1], [8.6, -7.6, 1.3, 1.2, 0.85, 1],
    [-2.6, 1.8, 0.22, 1.3, 0.7, 1], [2.3, 1.6, 0.28, 1.2, 0.7, 1.1], [3.1, 2.2, 0.16, 1.2, 0.8, 1],
    [-3.4, 3.4, 0.3, 1.3, 0.7, 1], [1.2, 4.6, 0.36, 1.2, 0.7, 1.2], [-5.2, 5.3, 0.42, 1.3, 0.75, 1],
  ].forEach(([x, z, r, sx, sy, sz], i) => {
    const m = new THREE.Mesh(rockGeometry(r, i * 1.7 + 0.3), rockMat);
    m.scale.set(sx, sy, sz);
    m.rotation.y = rr(0, TAU);
    m.position.set(x, sandAt(x, z) + r * sy * 0.25, z);
    scene.add(m);
  });

  // ─── Corals ───────────────────────────────────────────────────────────
  function bakeGeo(geo, matrix, color) {
    const g = geo.index ? geo.toNonIndexed() : geo.clone();
    if (matrix) g.applyMatrix4(matrix);
    const n = g.attributes.position.count;
    const col = new Float32Array(n * 3);
    for (let i = 0; i < n; i++) { col[i * 3] = color.r; col[i * 3 + 1] = color.g; col[i * 3 + 2] = color.b; }
    g.setAttribute('color', new THREE.BufferAttribute(col, 3));
    return g;
  }
  function mergeParts(parts) {
    let total = 0;
    for (const p of parts) total += p.attributes.position.count;
    const pos = new Float32Array(total * 3), nrm = new Float32Array(total * 3), col = new Float32Array(total * 3);
    const hasUV = parts.every((p) => p.attributes.uv);
    const uv = hasUV ? new Float32Array(total * 2) : null;
    let o = 0;
    for (const p of parts) {
      const n = p.attributes.position.count;
      pos.set(p.attributes.position.array, o * 3);
      nrm.set(p.attributes.normal.array, o * 3);
      col.set(p.attributes.color.array, o * 3);
      if (uv) uv.set(p.attributes.uv.array, o * 2);
      o += n;
    }
    const g = new THREE.BufferGeometry();
    g.setAttribute('position', new THREE.BufferAttribute(pos, 3));
    g.setAttribute('normal', new THREE.BufferAttribute(nrm, 3));
    g.setAttribute('color', new THREE.BufferAttribute(col, 3));
    if (uv) g.setAttribute('uv', new THREE.BufferAttribute(uv, 2));
    return g;
  }

  const coralTex = paintSpeckle();
  const coralMat = new THREE.MeshStandardMaterial({
    vertexColors: true, map: coralTex, roughness: 0.86, metalness: 0.02,
  });

  function buildBranchCoral(c0, c1, levels) {
    const parts = [];
    const ca = new THREE.Color(c0), cb = new THREE.Color(c1), tmp = new THREE.Color();
    function grow(mat, len, rad, depth) {
      const geo = new THREE.CylinderGeometry(rad * 0.68, rad, len, 6, 1, true);
      geo.translate(0, len / 2, 0);
      tmp.copy(ca).lerp(cb, (levels - depth) / (levels + 1));
      parts.push(bakeGeo(geo, mat, tmp));
      if (depth <= 0) return;
      const tip = new V3(0, len, 0).applyMatrix4(mat);
      const q = new THREE.Quaternion().setFromRotationMatrix(mat);
      const n = 2 + (rand() < 0.45 ? 1 : 0);
      for (let k = 0; k < n; k++) {
        const az = (k / n) * TAU + rr(-0.35, 0.35);
        const tilt = rr(0.3, 0.75);
        const e = new THREE.Euler(tilt * Math.cos(az), az, tilt * Math.sin(az));
        const cq = q.clone().multiply(new THREE.Quaternion().setFromEuler(e));
        const m = new THREE.Matrix4().compose(tip, cq, new V3(1, 1, 1));
        grow(m, len * rr(0.6, 0.78), rad * rr(0.6, 0.75), depth - 1);
      }
    }
    const rootQ = new THREE.Quaternion().setFromEuler(new THREE.Euler(rr(-0.12, 0.12), rand() * TAU, rr(-0.12, 0.12)));
    grow(new THREE.Matrix4().compose(new V3(0, 0, 0), rootQ, new V3(1, 1, 1)), rr(0.3, 0.45), rr(0.07, 0.1), levels);
    return mergeParts(parts);
  }

  function buildBrainCoral() {
    const g = new THREE.SphereGeometry(1, 40, 24);
    const pos = g.attributes.position, v = new V3();
    for (let i = 0; i < pos.count; i++) {
      v.fromBufferAttribute(pos, i);
      const n = Math.sin(v.x * 9 + v.y * 4) * Math.cos(v.z * 8 - v.x * 3) * 0.05 +
        Math.sin((v.x + v.z) * 14 + v.y * 5) * 0.025;
      v.multiplyScalar(1 + n);
      pos.setXYZ(i, v.x, v.y * 0.66, v.z);
    }
    g.computeVertexNormals();
    const cnt = pos.count, col = new Float32Array(cnt * 3);
    const cTop = new THREE.Color('#c98a6e'), cBot = new THREE.Color('#63465c'), c = new THREE.Color();
    for (let i = 0; i < cnt; i++) {
      const y = pos.getY(i);
      c.copy(cBot).lerp(cTop, smoothstep(-0.5, 0.6, y));
      col[i * 3] = c.r; col[i * 3 + 1] = c.g; col[i * 3 + 2] = c.b;
    }
    g.setAttribute('color', new THREE.BufferAttribute(col, 3));
    return g;
  }

  function buildTubes(c0, c1) {
    const parts = [];
    const n = 4 + Math.floor(rand() * 4);
    for (let i = 0; i < n; i++) {
      const h = rr(0.45, 1.35), r = rr(0.09, 0.17);
      const geo = new THREE.CylinderGeometry(r, r * 0.7, h, 10, 1, true);
      geo.translate(0, h / 2, 0);
      const az = rand() * TAU, tilt = rr(0, 0.22), rad = rr(0, 0.18);
      const q = new THREE.Quaternion().setFromEuler(new THREE.Euler(tilt * Math.cos(az), 0, tilt * Math.sin(az)));
      const pos = new V3(Math.cos(az) * rad, 0, Math.sin(az) * rad);
      const mat = new THREE.Matrix4().compose(pos, q, new V3(1, 1, 1));
      const col = new THREE.Color(c0).lerp(new THREE.Color(c1), rand());
      parts.push(bakeGeo(geo, mat, col));
      const disc = new THREE.CircleGeometry(r * 0.8, 12);
      disc.rotateX(-Math.PI / 2);
      const top = new V3(0, h, 0).applyMatrix4(mat);
      parts.push(bakeGeo(disc, new THREE.Matrix4().makeTranslation(top.x, top.y, top.z), new THREE.Color('#2a0c18')));
    }
    return mergeParts(parts);
  }

  function buildMushroom(color) {
    const parts = [];
    const stalk = new THREE.CylinderGeometry(0.055, 0.085, 0.3, 8);
    stalk.translate(0, 0.15, 0);
    parts.push(bakeGeo(stalk, null, new THREE.Color('#c9a98f')));
    const cap = new THREE.SphereGeometry(1, 28, 12, 0, TAU, 0, Math.PI * 0.5);
    const p = cap.attributes.position, v = new V3();
    for (let i = 0; i < p.count; i++) {
      v.fromBufferAttribute(p, i);
      const r = 1 + 0.09 * Math.sin(Math.atan2(v.z, v.x) * 7);
      v.x *= 0.4 * r; v.z *= 0.4 * r; v.y *= 0.16;
      p.setXYZ(i, v.x, v.y, v.z);
    }
    cap.computeVertexNormals();
    cap.translate(0, 0.3, 0);
    parts.push(bakeGeo(cap, null, new THREE.Color(color)));
    return mergeParts(parts);
  }

  function addCoral(geo, x, z, rotY, scale, sink = 0.06) {
    const m = new THREE.Mesh(geo, coralMat);
    m.position.set(x, sandAt(x, z) - sink, z);
    m.rotation.y = rotY;
    m.scale.setScalar(scale);
    scene.add(m);
    return m;
  }

  const branchPink = buildBranchCoral('#e2577e', '#ffd7b0', 3);
  const branchOrange = buildBranchCoral('#ff8c42', '#ffe3a8', 3);
  const branchViolet = buildBranchCoral('#a45ed0', '#ffd6f2', 3);
  const brainA = buildBrainCoral();
  const brainB = buildBrainCoral();
  const tubesA = buildTubes('#ff6f61', '#ffd166');
  const tubesB = buildTubes('#8e6bd4', '#ffb3d9');
  const mushA = buildMushroom('#ff9f68');
  const mushB = buildMushroom('#f26d9a');

  addCoral(branchPink, -5.6, -6.2, 0.4, 1.5);
  addCoral(branchOrange, 4.6, -7.2, 1.1, 1.6);
  addCoral(branchViolet, -1.2, -9.4, 2.3, 1.7);
  addCoral(branchPink, 7.2, -10.4, 0.8, 1.4);
  addCoral(branchOrange, -9.2, -8.6, 2.9, 1.5);
  addCoral(brainA, -3.4, -4.8, 0.3, 0.7);
  addCoral(brainB, 6.0, -5.4, 1.7, 0.8);
  addCoral(brainA, 0.6, -11.2, 0.9, 0.9);
  addCoral(tubesA, -7.0, -4.4, 0.5, 1.2);
  addCoral(tubesB, 2.4, -6.8, 1.9, 1.1);
  addCoral(mushA, -2.4, -6.0, 1.2, 1.3);
  addCoral(mushB, 3.8, -5.0, 2.4, 1.2);
  addCoral(mushA, 6.8, -8.4, 0.6, 1.4);
  addCoral(branchOrange, -2.2, -12.4, 1.5, 1.8);

  addCoral(branchViolet, 4.4, -1.6, 0.7, 0.95);
  addCoral(branchPink, -4.6, -0.8, 2.1, 1.0);
  addCoral(brainB, 3.8, 0.8, 0.4, 0.55);
  addCoral(brainA, -4.0, 1.2, 1.3, 0.6);
  addCoral(tubesA, 5.0, 1.8, 2.0, 0.85);
  addCoral(tubesB, -5.4, 0.4, 0.9, 0.8);
  addCoral(mushB, 3.4, -2.6, 1.6, 0.9);
  addCoral(mushA, -3.6, -2.8, 0.2, 0.85);

  addCoral(branchOrange, -6.8, 2.4, 1.1, 1.1);
  addCoral(branchPink, 6.6, 2.8, 2.6, 1.05);
  addCoral(mushB, 2.5, 3.8, 0.5, 0.8);
  addCoral(mushA, -2.6, 4.0, 1.9, 0.75);

  // ─── Sea fans ─────────────────────────────────────────────────────────
  const fanTex = paintFin();
  const fanMats = ['#ff8fb8', '#c07bff', '#ffb347', '#ff6b6b'].map((c) => new THREE.MeshStandardMaterial({
    map: fanTex, color: c, transparent: true, alphaTest: 0.06, side: THREE.DoubleSide,
    roughness: 0.78, depthWrite: false,
  }));
  const fans = [];
  function addSeaFan(x, z, radius, yaw) {
    const g = new THREE.Group();
    g.position.set(x, sandAt(x, z) - 0.04, z);
    g.rotation.y = yaw;
    const mesh = new THREE.Mesh(
      new THREE.CircleGeometry(radius, 30, Math.PI / 2 - 0.95, 1.9),
      fanMats[Math.floor(rand() * fanMats.length)]
    );
    mesh.position.y = radius * 0.02;
    g.add(mesh);
    scene.add(g);
    fans.push({ g, ph: rand() * TAU, yaw });
  }
  addSeaFan(-4.6, -3.6, 1.0, 0.3);
  addSeaFan(3.4, -4.0, 0.9, -0.4);
  addSeaFan(0.2, -7.8, 1.3, 0.1);
  addSeaFan(5.4, -7.0, 1.1, 0.8);
  addSeaFan(-7.8, -6.6, 1.2, -0.2);
  addSeaFan(-5.6, 3.2, 0.85, 0.5);
  addSeaFan(5.8, 3.4, 0.9, -0.6);
  function updateFans(t) {
    for (const f of fans) {
      f.g.rotation.y = f.yaw + Math.sin(t * 0.9 + f.ph) * 0.07 * MOTION;
      f.g.rotation.z = Math.sin(t * 0.6 + f.ph * 1.7) * 0.05 * MOTION;
    }
  }

  // ─── Anemones ─────────────────────────────────────────────────────────
  const ANEM_POS = [[-3.2, -3.4], [2.9, -3.6], [0.3, -8.6], [-6.2, 1.0]];
  const anemones = ANEM_POS.map(([x, z]) => ({ x, z, y: sandAt(x, z), r: rr(0.18, 0.26), ph: rand() * TAU }));
  const TENTS = [];
  const TENT_PER = 30;
  const anemoneDiscMat = new THREE.MeshStandardMaterial({ color: '#7a3b5e', roughness: 0.8 });
  for (const a of anemones) {
    for (let k = 0; k < TENT_PER; k++) {
      const ang = (k / TENT_PER) * TAU + rand() * 0.25;
      const rad = Math.sqrt(rand()) * a.r;
      TENTS.push({
        ax: a.x + Math.cos(ang) * rad,
        az: a.z + Math.sin(ang) * rad,
        ay: a.y + 0.06 + (1 - rad / a.r) * 0.09,
        out: new V3(Math.cos(ang), 0, Math.sin(ang)),
        len: rr(0.7, 1.25),
        ph: rand() * TAU,
      });
    }
    const disc = new THREE.Mesh(new THREE.SphereGeometry(1, 16, 8, 0, TAU, 0, Math.PI / 2), anemoneDiscMat);
    disc.scale.set(a.r, a.r * 0.5, a.r);
    disc.position.set(a.x, a.y + 0.02, a.z);
    scene.add(disc);
  }
  const tentGeo = new THREE.ConeGeometry(0.026, 0.36, 5, 1, false);
  tentGeo.translate(0, 0.18, 0);
  const tentMat = new THREE.MeshStandardMaterial({ roughness: 0.6, metalness: 0.02 });
  const tentMesh = new THREE.InstancedMesh(tentGeo, tentMat, TENTS.length);
  tentMesh.frustumCulled = false;
  scene.add(tentMesh);
  {
    const cA = new THREE.Color('#ffd0e0'), cB = new THREE.Color('#ff7aa2'), c = new THREE.Color();
    TENTS.forEach((tt, i) => {
      c.copy(cA).lerp(cB, rand());
      tentMesh.setColorAt(i, c);
    });
    if (tentMesh.instanceColor) tentMesh.instanceColor.needsUpdate = true;
  }
  const _aq = new THREE.Quaternion(), _am = new THREE.Matrix4(), _ap = new V3(), _as = new V3(), _ad = new V3();
  const UPV = new V3(0, 1, 0);
  function updateAnemones(t) {
    for (let i = 0; i < TENTS.length; i++) {
      const tt = TENTS[i];
      _ad.copy(tt.out)
        .multiplyScalar(0.55 + 0.22 * Math.sin(t * 1.1 + tt.ph * 2))
        .addScaledVector(UPV, 1.0 + 0.18 * Math.sin(t * 1.6 + tt.ph));
      _ad.normalize();
      _aq.setFromUnitVectors(UPV, _ad);
      _ap.set(tt.ax, tt.ay, tt.az);
      _as.set(1, tt.len, 1);
      _am.compose(_ap, _aq, _as);
      tentMesh.setMatrixAt(i, _am);
    }
    tentMesh.instanceMatrix.needsUpdate = true;
  }

  // ─── Rubble ───────────────────────────────────────────────────────────
  {
    const geo = new THREE.DodecahedronGeometry(0.09, 0);
    const mat = new THREE.MeshStandardMaterial({ roughness: 0.92 });
    const N = 260;
    const mesh = new THREE.InstancedMesh(geo, mat, N);
    const m4 = new THREE.Matrix4(), q = new THREE.Quaternion(), s = new V3(), p = new V3(), e = new THREE.Euler();
    const col = new THREE.Color();
    for (let i = 0; i < N; i++) {
      const x = rr(-13, 13), z = rr(-13, 6);
      p.set(x, sandAt(x, z) + 0.01, z);
      e.set(rand() * TAU, rand() * TAU, rand() * TAU);
      q.setFromEuler(e);
      s.setScalar(rr(0.4, 1.5));
      m4.compose(p, q, s);
      mesh.setMatrixAt(i, m4);
      col.setHSL(rr(0.02, 0.13), rr(0.15, 0.42), rr(0.33, 0.62));
      mesh.setColorAt(i, col);
    }
    mesh.instanceMatrix.needsUpdate = true;
    if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
    scene.add(mesh);
  }

  // ─── Soft coral whips ─────────────────────────────────────────────────
  const whipMat = new THREE.MeshStandardMaterial({ vertexColors: true, side: THREE.DoubleSide, roughness: 0.7 });
  const kelps = [];
  function addWhip(x, z, h, w, c0, c1) {
    const segs = 26;
    const geo = new THREE.BufferGeometry();
    const pos = new Float32Array((segs + 1) * 6), col = new Float32Array((segs + 1) * 6), idx = [];
    const a = new THREE.Color(c0), b = new THREE.Color(c1), c = new THREE.Color();
    for (let i = 0; i <= segs; i++) {
      c.copy(a).lerp(b, Math.pow(i / segs, 0.8));
      col.set([c.r, c.g, c.b, c.r, c.g, c.b], i * 6);
      if (i < segs) { const q = i * 2; idx.push(q, q + 1, q + 2, q + 1, q + 3, q + 2); }
    }
    geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
    geo.setAttribute('color', new THREE.BufferAttribute(col, 3));
    geo.setIndex(idx);
    const mesh = new THREE.Mesh(geo, whipMat);
    mesh.frustumCulled = false;
    scene.add(mesh);
    kelps.push({ geo, x, z, y0: sandAt(x, z) - 0.05, h, w, segs, ph: rand() * TAU, tw: rr(0.6, 1.6) });
  }
  const WHIP_A = ['#7a2f5e', '#ff9ecb'], WHIP_B = ['#8a3b23', '#ffc07a'], WHIP_C = ['#3d4f8a', '#9fd6ff'];
  [
    [-4.9, -4.6, 2.6, 0.24, WHIP_A], [-4.1, -5.0, 1.9, 0.2, WHIP_B],
    [4.2, -4.2, 2.4, 0.22, WHIP_C], [4.9, -4.8, 3.0, 0.26, WHIP_A],
    [-1.9, -7.4, 3.4, 0.3, WHIP_B], [-0.9, -7.6, 2.6, 0.24, WHIP_A],
    [3.4, -8.8, 3.2, 0.28, WHIP_C], [-6.9, -5.8, 3.0, 0.26, WHIP_A],
    [7.6, -6.2, 3.4, 0.3, WHIP_B], [-4.4, 2.6, 1.6, 0.2, WHIP_C],
    [4.4, 2.9, 1.5, 0.18, WHIP_A],
  ].forEach(([x, z, h, w, [c0, c1]]) => addWhip(x, z, h, w, c0, c1));
  function updateWhips(t) {
    for (const k of kelps) {
      const p = k.geo.attributes.position;
      for (let i = 0; i <= k.segs; i++) {
        const s = i / k.segs, bend = Math.pow(s, 1.5);
        const sx = (Math.sin(t * 0.9 + k.ph + s * 2.4) * 0.42 + Math.sin(t * 0.37 + k.ph * 2) * 0.28) * bend * MOTION;
        const sz = Math.cos(t * 0.7 + k.ph + s * 2) * 0.25 * bend * MOTION;
        const w = k.w * Math.pow(Math.max(Math.sin(Math.PI * (0.1 + 0.9 * s)), 0), 0.6) * (1 + 0.12 * Math.sin(s * 15 + k.ph));
        const ang = k.ph + s * k.tw + Math.sin(t * 0.5 + k.ph) * 0.3;
        const dx = Math.cos(ang) * w * 0.5, dz = Math.sin(ang) * w * 0.5;
        const cx = k.x + sx, cy = k.y0 + s * k.h, cz = k.z + sz;
        p.setXYZ(i * 2, cx - dx, cy, cz - dz);
        p.setXYZ(i * 2 + 1, cx + dx, cy, cz + dz);
      }
      p.needsUpdate = true;
      k.geo.computeVertexNormals();
    }
  }

  // ─── Sun rays ─────────────────────────────────────────────────────────
  const rayTex = paintRay();
  const rays = [];
  for (let i = 0; i < 6; i++) {
    const mat = new THREE.MeshBasicMaterial({
      map: rayTex, color: 0xffffff, transparent: true, opacity: 0.1,
      blending: THREE.AdditiveBlending, depthWrite: false, fog: false,
    });
    const m = new THREE.Mesh(new THREE.PlaneGeometry(rr(0.9, 2.2), 17), mat);
    m.position.set(-8 + i * 3.0 + rr(-0.8, 0.8), 3.6, rr(-9, -3));
    m.rotation.z = 0.3 + rr(-0.05, 0.05);
    scene.add(m);
    rays.push({ m, base: rr(0.07, 0.15), ph: rand() * TAU, sp: rr(0.25, 0.6), rot: m.rotation.z });
  }

  // ─── Drifting specks ──────────────────────────────────────────────────
  const SN = 340;
  const snGeo = new THREE.BufferGeometry();
  const snPos = new Float32Array(SN * 3), snSize = new Float32Array(SN), snPh = new Float32Array(SN);
  for (let i = 0; i < SN; i++) {
    snPos[i * 3] = rr(-16, 16); snPos[i * 3 + 1] = rr(SAND_Y, 7); snPos[i * 3 + 2] = rr(-16, 7);
    snSize[i] = rr(0.025, 0.07); snPh[i] = rand();
  }
  snGeo.setAttribute('position', new THREE.BufferAttribute(snPos, 3));
  snGeo.setAttribute('aSize', new THREE.BufferAttribute(snSize, 1));
  snGeo.setAttribute('aPh', new THREE.BufferAttribute(snPh, 1));
  const snMat = new THREE.ShaderMaterial({
    uniforms: {
      uTime: { value: 0 }, uScale: { value: 300 }, uColor: { value: new THREE.Color('#ffffff') },
      uOpacity: { value: 0.34 }, uTwinkle: { value: 0 },
    },
    vertexShader: `
      attribute float aSize;
      attribute float aPh;
      uniform float uTime;
      uniform float uScale;
      uniform float uTwinkle;
      varying float vA;
      void main() {
        vec4 mv = modelViewMatrix * vec4(position, 1.0);
        gl_Position = projectionMatrix * mv;
        float d = max(-mv.z, 0.1);
        gl_PointSize = max(aSize * uScale / d, 1.0);
        float tw = mix(1.0, 0.3 + 0.7 * (0.5 + 0.5 * sin(uTime * (0.7 + aPh) + aPh * 40.0)), uTwinkle);
        vA = tw * (1.0 - smoothstep(14.0, 30.0, d)) * smoothstep(0.5, 2.0, d);
      }`,
    fragmentShader: `
      uniform vec3 uColor;
      uniform float uOpacity;
      varying float vA;
      void main() {
        vec2 uv = gl_PointCoord * 2.0 - 1.0;
        float r2 = dot(uv, uv);
        if (r2 > 1.0) discard;
        gl_FragColor = vec4(uColor, exp(-r2 * 3.5) * vA * uOpacity);
      }`,
    transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
  });
  const snow = new THREE.Points(snGeo, snMat);
  snow.frustumCulled = false;
  scene.add(snow);
  function updateSnow(dt, t) {
    for (let i = 0; i < SN; i++) {
      const ph = snPh[i];
      let y = snPos[i * 3 + 1] - (0.04 + 0.05 * ph) * dt * MOTION;
      snPos[i * 3] += Math.sin(t * 0.25 + ph * 20) * 0.06 * dt * MOTION;
      if (y < SAND_Y) y += 10.3;
      snPos[i * 3 + 1] = y;
    }
    snGeo.attributes.position.needsUpdate = true;
  }

  // ─── Bubbles ──────────────────────────────────────────────────────────
  const BMAX = 200;
  const bGeo = new THREE.BufferGeometry();
  const bPos = new Float32Array(BMAX * 3), bSize = new Float32Array(BMAX), bAlpha = new Float32Array(BMAX);
  bGeo.setAttribute('position', new THREE.BufferAttribute(bPos, 3));
  bGeo.setAttribute('aSize', new THREE.BufferAttribute(bSize, 1));
  bGeo.setAttribute('aAlpha', new THREE.BufferAttribute(bAlpha, 1));
  const bMat = new THREE.ShaderMaterial({
    uniforms: { uScale: { value: 300 }, uColor: { value: new THREE.Color('#ffffff') } },
    vertexShader: `
      attribute float aSize;
      attribute float aAlpha;
      uniform float uScale;
      varying float vA;
      void main() {
        vec4 mv = modelViewMatrix * vec4(position, 1.0);
        gl_Position = projectionMatrix * mv;
        gl_PointSize = aSize * uScale / max(-mv.z, 0.1);
        vA = aAlpha;
      }`,
    fragmentShader: `
      uniform vec3 uColor;
      varying float vA;
      void main() {
        vec2 uv = gl_PointCoord * 2.0 - 1.0;
        float r = length(uv);
        if (r > 1.0 || vA <= 0.0) discard;
        float rim = smoothstep(0.62, 0.92, r) * (1.0 - smoothstep(0.92, 1.0, r));
        float hl = 1.0 - smoothstep(0.0, 0.3, length(uv - vec2(-0.34, -0.36)));
        float a = clamp(rim * 0.85 + hl * 0.95 + 0.12 * (1.0 - r), 0.0, 1.0);
        gl_FragColor = vec4(uColor, a * vA);
      }`,
    transparent: true, depthWrite: false,
  });
  const bubblePoints = new THREE.Points(bGeo, bMat);
  bubblePoints.frustumCulled = false;
  scene.add(bubblePoints);
  const bubbles = Array.from({ length: BMAX }, () => ({ on: false, p: new V3(), v: new V3(), s: 0, age: 0, life: 0, ph: 0 }));
  let bCursor = 0;
  function spawnBubble(p, size, vx, vy, vz) {
    for (let k = 0; k < BMAX; k++) {
      const i = (bCursor + k) % BMAX, b = bubbles[i];
      if (b.on) continue;
      b.on = true; b.p.copy(p); b.v.set(vx, vy, vz); b.s = size; b.age = 0; b.life = rr(5, 9); b.ph = rand() * TAU;
      bCursor = (i + 1) % BMAX;
      return;
    }
  }
  function updateBubbles(dt) {
    const top = 7.5;
    for (let i = 0; i < BMAX; i++) {
      const b = bubbles[i];
      if (!b.on) { bAlpha[i] = 0; bSize[i] = 0; continue; }
      b.age += dt;
      b.v.y = Math.min(b.v.y + 1.1 * dt, 0.75 + b.s * 3);
      b.v.x *= Math.exp(-1.5 * dt);
      b.v.z *= Math.exp(-1.5 * dt);
      b.p.x += (b.v.x + Math.sin(b.age * 7 + b.ph) * 0.12) * dt;
      b.p.y += b.v.y * dt;
      b.p.z += (b.v.z + Math.cos(b.age * 6 + b.ph) * 0.08) * dt;
      if (b.age > b.life || b.p.y > top) { b.on = false; bAlpha[i] = 0; bSize[i] = 0; continue; }
      bPos[i * 3] = b.p.x; bPos[i * 3 + 1] = b.p.y; bPos[i * 3 + 2] = b.p.z;
      bSize[i] = b.s * (1 + 0.15 * Math.min(b.age, 3) / 3) * (1 + 0.06 * Math.sin(b.age * 12 + b.ph));
      bAlpha[i] = smoothstep(0, 0.15, b.age) * (1 - smoothstep(top - 2, top, b.p.y)) * (1 - smoothstep(b.life - 1, b.life, b.age));
    }
    bGeo.attributes.position.needsUpdate = true;
    bGeo.attributes.aSize.needsUpdate = true;
    bGeo.attributes.aAlpha.needsUpdate = true;
  }
  const vents = [
    { x: -6.2, z: -4.4, t: 1.0, burst: 0 },
    { x: 4.6, z: -5.2, t: 3.0, burst: 0 },
    { x: 2.2, z: -9.0, t: 2.0, burst: 0 },
  ].map((v) => Object.assign(v, { y: sandAt(v.x, v.z) + 0.05 }));
  const tVent = new V3();
  function updateVents(dt) {
    for (const v of vents) {
      v.t -= dt;
      if (v.t > 0) continue;
      if (v.burst > 0) {
        spawnBubble(tVent.set(v.x + rr(-0.05, 0.05), v.y, v.z + rr(-0.05, 0.05)), rr(0.035, 0.08), 0, 0.2, 0);
        v.burst--;
        v.t = rr(0.06, 0.18);
      } else {
        v.burst = 4 + Math.floor(rand() * 7);
        v.t = rr(2.5, 6);
      }
    }
  }

  // ─── Distant school of tiny fish ──────────────────────────────────────
  const schoolMat = new THREE.MeshStandardMaterial({ color: '#3f86b3', roughness: 0.45, metalness: 0.15 });
  const schoolTailMat = new THREE.MeshStandardMaterial({ color: '#3f86b3', roughness: 0.5, side: THREE.DoubleSide });
  const smallBody = new THREE.SphereGeometry(1, 14, 10);
  const smallTail = new THREE.BufferGeometry();
  smallTail.setAttribute('position', new THREE.BufferAttribute(new Float32Array([0, 0, 0, 0, 0.13, -0.2, 0, -0.13, -0.2]), 3));
  smallTail.computeVertexNormals();
  const school = [];
  for (let i = 0; i < 9; i++) {
    const g = new THREE.Group();
    const b = new THREE.Mesh(smallBody, schoolMat);
    b.scale.set(0.075, 0.065, 0.22);
    g.add(b);
    const tail = new THREE.Group();
    tail.position.z = -0.19;
    tail.add(new THREE.Mesh(smallTail, schoolTailMat));
    g.add(tail);
    scene.add(g);
    school.push({ g, tail, off: new V3(rr(-0.7, 0.7), rr(-0.4, 0.4), rr(-0.7, 0.7)), lag: i * 0.03 + rr(0, 0.02), ph: rand() * TAU });
  }
  const tSchool = new V3();
  function updateSchool(t) {
    for (const f of school) {
      const a = t * 0.11 * MOTION - f.lag;
      const x = 15 * Math.cos(a) + f.off.x;
      const z = -15 + 4 * Math.sin(a) + f.off.z;
      const y = 0.5 + 0.45 * Math.sin(a * 1.7) + f.off.y + Math.sin(t * 2 + f.ph) * 0.05;
      f.g.position.set(x, y, z);
      f.g.lookAt(tSchool.set(x - 15 * Math.sin(a), y + 0.08 * Math.cos(a * 1.7), z + 4 * Math.cos(a)));
      f.tail.rotation.y = Math.sin(t * 11 + f.ph) * 0.45;
    }
  }

  // ─── Clawdia ──────────────────────────────────────────────────────────
  const lob = new THREE.Group();
  lob.rotation.order = 'YXZ';
  const bob = new THREE.Group();
  lob.add(bob);
  const core = new THREE.Group();
  core.scale.setScalar(0.78);
  bob.add(core);
  scene.add(lob);

  const unitSphere = new THREE.SphereGeometry(1, 24, 16);

  const shell = paintShell();
  const shellMat = new THREE.MeshStandardMaterial({
    map: shell.map, emissiveMap: shell.glow, emissive: 0x46f0ff, emissiveIntensity: 0,
    roughness: 0.48, metalness: 0.06,
  });
  const clawMat = new THREE.MeshStandardMaterial({
    map: shell.map, color: 0xffd9c2, emissiveMap: shell.glow, emissive: 0x46f0ff, emissiveIntensity: 0,
    roughness: 0.42, metalness: 0.08,
  });
  const limbMat = new THREE.MeshStandardMaterial({ color: '#c2452a', roughness: 0.55 });
  const darkMat = new THREE.MeshStandardMaterial({ color: '#2b120c', roughness: 0.35 });
  const eyeMat = new THREE.MeshStandardMaterial({ color: '#120806', roughness: 0.12, metalness: 0.1 });
  const shineMat = new THREE.MeshBasicMaterial({ color: '#ffffff' });

  // ── carapace
  const carapaceGeo = (() => {
    const g = new THREE.SphereGeometry(1, 56, 40);
    const pos = g.attributes.position, v = new V3();
    for (let i = 0; i < pos.count; i++) {
      v.fromBufferAttribute(pos, i);
      const front = smoothstep(-0.2, 1, v.z);
      v.x *= 1 - 0.32 * front;
      v.y *= 1 - 0.20 * front;
      if (v.y < 0) v.y *= 0.82;
      v.y += 0.03 * Math.cos(v.x * 3.0) * smoothstep(0.2, 0.9, v.y);
      pos.setXYZ(i, v.x, v.y, v.z);
    }
    g.computeVertexNormals();
    return g;
  })();
  const carapace = new THREE.Mesh(carapaceGeo, shellMat);
  carapace.scale.set(0.54, 0.52, 0.80);
  carapace.position.set(0, 0, 0.30);
  core.add(carapace);

  const rostrumGeo = new THREE.ConeGeometry(0.055, 0.34, 8);
  rostrumGeo.rotateX(Math.PI / 2);
  const rostrum = new THREE.Mesh(rostrumGeo, shellMat);
  rostrum.position.set(0, 0.20, 1.04);
  rostrum.rotation.x = -0.16;
  core.add(rostrum);

  const spineGeo = new THREE.ConeGeometry(0.045, 0.20, 7);
  spineGeo.translate(0, 0.10, 0);
  [
    [-0.20, 0.34, 0.72, -0.5, -0.7, 0.5], [0.20, 0.34, 0.72, -0.5, 0.7, 0.5],
    [-0.36, 0.10, 0.34, 0.0, -1.2, 0.2], [0.36, 0.10, 0.34, 0.0, 1.2, 0.2],
    [-0.30, -0.18, 0.60, 0.5, -1.0, 0.4], [0.30, -0.18, 0.60, 0.5, 1.0, 0.4],
  ].forEach(([x, y, z, rx, rz, ry]) => {
    const m = new THREE.Mesh(spineGeo, shellMat);
    m.position.set(x, y, z);
    m.rotation.set(rx, ry, rz);
    core.add(m);
  });

  // ── abdomen
  const abdomen = [];
  for (let i = 0; i < 6; i++) {
    const t = i / 5;
    const seg = new THREE.Mesh(unitSphere, shellMat);
    seg.scale.set(lerp(0.50, 0.27, t), lerp(0.40, 0.22, t), 0.145);
    seg.position.set(0, -0.02 - t * 0.14, -0.42 - i * 0.18);
    core.add(seg);
    abdomen.push(seg);
  }

  // ── tail fan
  const tail = new THREE.Group();
  tail.position.set(0, -0.16, -1.36);
  core.add(tail);
  for (let i = -2; i <= 2; i++) {
    const a = i * 0.40;
    const blade = new THREE.Mesh(unitSphere, shellMat);
    blade.scale.set(0.125, 0.028, i === 0 ? 0.40 : 0.34);
    blade.position.set(Math.sin(a) * 0.26, -0.02 - Math.abs(i) * 0.012, -Math.cos(a) * 0.26);
    blade.rotation.set(0.12, -a, 0);
    tail.add(blade);
  }

  // ── claws
  const claws = [];
  function buildClaw(side, size) {
    const root = new THREE.Group();
    root.rotation.order = 'YXZ';
    root.position.set(side * 0.34, -0.10, 0.54);
    const base = { x: 0.12, y: side * 0.66, z: side * 0.20 };
    root.rotation.set(base.x, base.y, base.z);
    root.scale.setScalar(size);
    core.add(root);

    const armGeo = new THREE.CylinderGeometry(0.115, 0.085, 0.44, 8, 1);
    armGeo.rotateX(Math.PI / 2);
    armGeo.translate(0, 0, 0.22);
    root.add(new THREE.Mesh(armGeo, limbMat));

    const hand = new THREE.Group();
    hand.position.z = 0.44;
    root.add(hand);

    const palm = new THREE.Mesh(unitSphere, clawMat);
    palm.scale.set(0.17, 0.21, 0.30);
    palm.position.set(0, 0.02, 0.20);
    hand.add(palm);

    const fixedGeo = new THREE.ConeGeometry(0.062, 0.30, 8);
    fixedGeo.rotateX(Math.PI / 2);
    fixedGeo.translate(0, 0, 0.15);
    const fixed = new THREE.Mesh(fixedGeo, clawMat);
    fixed.position.set(0, -0.07, 0.40);
    fixed.rotation.x = 0.10;
    hand.add(fixed);

    const dactyl = new THREE.Group();
    dactyl.position.set(0, 0.06, 0.34);
    hand.add(dactyl);
    const dGeo = new THREE.ConeGeometry(0.055, 0.30, 8);
    dGeo.rotateX(Math.PI / 2);
    dGeo.translate(0, 0, 0.15);
    const dMesh = new THREE.Mesh(dGeo, clawMat);
    dMesh.position.set(0, 0.02, 0);
    dMesh.rotation.x = 0.14;
    dactyl.add(dMesh);

    claws.push({ root, hand, dactyl, side, base, ph: side > 0 ? 0 : 1.3 });
  }
  buildClaw(-1, 0.96);
  buildClaw(1, 1.12);

  // ── walking legs
  const legSegGeo = new THREE.CylinderGeometry(0.036, 0.045, 1, 6, 1);
  legSegGeo.translate(0, 0.5, 0);
  const legs = [];
  for (const side of [-1, 1]) {
    for (let i = 0; i < 4; i++) {
      const hip = new THREE.Group();
      hip.position.set(side * 0.30, -0.20, 0.52 - i * 0.26);
      const baseX = (1.5 - i) * 0.16;
      hip.rotation.x = baseX;
      core.add(hip);

      const up = new THREE.Group();
      const upZ = -side * (Math.PI / 2 + 0.42);
      up.rotation.z = upZ;
      hip.add(up);
      const upMesh = new THREE.Mesh(legSegGeo, limbMat);
      upMesh.scale.set(1, 0.34, 1);
      up.add(upMesh);

      const low = new THREE.Group();
      low.position.y = 0.34;
      const lowZ = -side * 1.05;
      low.rotation.z = lowZ;
      up.add(low);
      const lowMesh = new THREE.Mesh(legSegGeo, limbMat);
      lowMesh.scale.set(0.7, 0.30, 0.7);
      low.add(lowMesh);

      legs.push({ hip, up, low, side, i, ph: i * 1.1 + (side > 0 ? 0 : 0.7), upZ, lowZ, baseX });
    }
  }

  // ── eyes on stalks (kept in a list so they can track food)
  const eyeStalks = [];
  for (const side of [-1, 1]) {
    const g = new THREE.Group();
    g.rotation.order = 'YXZ';
    g.position.set(side * 0.20, 0.26, 0.84);
    const baseX = -0.22, baseY = side * 0.42;
    g.rotation.set(baseX, baseY, 0);
    core.add(g);

    const stalkGeo = new THREE.CylinderGeometry(0.032, 0.045, 0.16, 8);
    stalkGeo.rotateX(Math.PI / 2);
    stalkGeo.translate(0, 0, 0.08);
    g.add(new THREE.Mesh(stalkGeo, limbMat));

    const ball = new THREE.Mesh(unitSphere, eyeMat);
    ball.scale.setScalar(0.095);
    ball.position.z = 0.17;
    g.add(ball);

    const hi = new THREE.Mesh(unitSphere, shineMat);
    hi.scale.setScalar(0.026);
    hi.position.set(-0.03 * side, 0.045, 0.235);
    g.add(hi);
    const hi2 = new THREE.Mesh(unitSphere, shineMat);
    hi2.scale.setScalar(0.013);
    hi2.position.set(0.032 * side, -0.03, 0.245);
    g.add(hi2);

    eyeStalks.push({ g, baseX, baseY });
  }

  // ── mandibles
  const mouth = new THREE.Group();
  mouth.position.set(0, -0.20, 0.86);
  core.add(mouth);
  const jaws = [];
  for (const side of [-1, 1]) {
    const j = new THREE.Mesh(unitSphere, darkMat);
    j.scale.set(0.055, 0.085, 0.05);
    j.position.set(side * 0.045, 0, 0);
    mouth.add(j);
    jaws.push({ m: j, side });
  }

  // ── antennae (tube meshes rewritten every frame)
  const ANT = [];
  function makeTubeGeo(segs, rad) {
    const count = (segs + 1) * rad;
    const pos = new Float32Array(count * 3);
    const idx = [];
    for (let i = 0; i < segs; i++) {
      for (let j = 0; j < rad; j++) {
        const a = i * rad + j;
        const b = i * rad + ((j + 1) % rad);
        const c = (i + 1) * rad + j;
        const d = (i + 1) * rad + ((j + 1) % rad);
        idx.push(a, b, c, b, d, c);
      }
    }
    const geo = new THREE.BufferGeometry();
    geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
    geo.setIndex(idx);
    return geo;
  }
  function addAntenna(side, long, bx, by, bz) {
    const segs = 14, rad = 6;
    const geo = makeTubeGeo(segs, rad);
    const mat = new THREE.MeshStandardMaterial({ color: long ? '#e87a45' : '#d2623c', roughness: 0.62 });
    const mesh = new THREE.Mesh(geo, mat);
    mesh.frustumCulled = false;
    core.add(mesh);
    ANT.push({
      geo, segs, rad, side, long,
      base: new V3(bx, by, bz),
      pts: Array.from({ length: segs + 1 }, () => new V3()),
      ph: rand() * TAU,
      r0: long ? 0.032 : 0.026, r1: 0.006,
    });
  }
  addAntenna(-1, true, -0.18, 0.12, 0.96);
  addAntenna(1, true, 0.18, 0.12, 0.96);
  addAntenna(-1, false, -0.10, 0.02, 1.00);
  addAntenna(1, false, 0.10, 0.02, 1.00);

  const _ta = new V3(), _tb = new V3();
  const _t0 = new V3(), _t1 = new V3(), _t2 = new V3(), _t3 = new V3();

  // focus (0..1) lifts the antennae off the ground and points them at the food
  function updateAntennae(t, P01, focus) {
    const ground = 1 - P01;
    for (const a of ANT) {
      const { geo, segs, rad, pts } = a;
      const reach = a.long ? 1.6 : 1.0;
      const sweep = Math.sin(t * 1.15 + a.ph + a.side * 0.6) *
        (a.long ? 0.55 : 0.35) * (0.6 + 0.4 * st.probe) * ground * (1 - 0.55 * focus);
      const tipX = a.base.x + a.side * (a.long ? 0.34 : 0.18) + sweep;
      const tipZ = a.base.z + reach * (1 + 0.28 * focus) + Math.sin(t * 0.8 + a.ph) * 0.10;
      const tap = Math.max(0, Math.sin(t * 3.4 + a.ph * 2)) * 0.04 * st.probe * (1 - focus);
      // while hunting the tips lift up and quiver excitedly
      const tipY = (a.long ? -0.55 : -0.46) * (1 - 0.6 * focus) + tap +
        Math.sin(t * 9 + a.ph) * 0.05 * focus;

      _ta.set(
        lerp(tipX, a.base.x + a.side * 0.6, P01),
        lerp(tipY, a.base.y + 0.7, P01),
        lerp(tipZ, a.base.z - 0.5, P01)
      );
      const A = a.base;
      _tb.set(
        (A.x + _ta.x) * 0.5,
        (A.y + _ta.y) * 0.5 + (a.long ? 0.5 : 0.28) * (0.4 + 0.6 * P01) + 0.15 + 0.18 * focus,
        (A.z + _ta.z) * 0.5
      );

      for (let i = 0; i <= segs; i++) {
        const s = i / segs, inv = 1 - s;
        pts[i].set(
          inv * inv * A.x + 2 * inv * s * _tb.x + s * s * _ta.x,
          inv * inv * A.y + 2 * inv * s * _tb.y + s * s * _ta.y + Math.sin(t * 4 + a.ph * 3 + s * 7) * 0.02 * s,
          inv * inv * A.z + 2 * inv * s * _tb.z + s * s * _ta.z
        );
      }

      const pos = geo.attributes.position;
      for (let i = 0; i <= segs; i++) {
        const s = i / segs;
        _t0.subVectors(pts[Math.min(segs, i + 1)], pts[Math.max(0, i - 1)]).normalize();
        _t1.set(0, 1, 0);
        if (Math.abs(_t0.dot(_t1)) > 0.9) _t1.set(1, 0, 0);
        _t2.crossVectors(_t0, _t1).normalize();
        _t3.crossVectors(_t2, _t0).normalize();
        const r = lerp(a.r0, a.r1, Math.pow(s, 0.7));
        for (let j = 0; j < rad; j++) {
          const ang = (j / rad) * TAU, ca = Math.cos(ang), sa = Math.sin(ang);
          pos.setXYZ(
            i * rad + j,
            pts[i].x + (_t2.x * ca + _t3.x * sa) * r,
            pts[i].y + (_t2.y * ca + _t3.y * sa) * r,
            pts[i].z + (_t2.z * ca + _t3.z * sa) * r
          );
        }
      }
      pos.needsUpdate = true;
      geo.computeVertexNormals();
    }
  }

  // ─── Food flakes ──────────────────────────────────────────────────────
  const foods = [];
  const foodGeo = new THREE.DodecahedronGeometry(0.08, 0);
  foodGeo.scale(1.1, 0.45, 0.9);
  const foodMats = ['#ff7a3d', '#ffb23f', '#8fd14f', '#ff5e7a'].map(
    (c) => new THREE.MeshStandardMaterial({ color: c, roughness: 0.6, flatShading: true }));
  const tFood = new V3();
  function dropFood(p) {
    const x = clamp(p.x, -bounds.x + 0.3, bounds.x - 0.3);
    const z = clamp(p.z, bounds.zMin + 0.3, bounds.zMax - 0.2);
    const gy = sandAt(x, z);
    const n = 1 + (rand() < 0.55 ? 1 : 0) + (rand() < 0.3 ? 1 : 0);
    for (let i = 0; i < n; i++) {
      if (foods.length >= 10) scene.remove(foods.shift().mesh);
      const m = new THREE.Mesh(foodGeo, foodMats[Math.floor(rand() * foodMats.length)]);
      m.position.set(x + rr(-0.2, 0.2), gy + rr(0.6, 1.1), z + rr(-0.2, 0.2));
      m.rotation.set(rand() * TAU, rand() * TAU, rand() * TAU);
      m.scale.setScalar(0.001);
      scene.add(m);
      foods.push({ mesh: m, t: 0, ph: rand() * TAU, spin: rr(-2, 2), landed: false, landT: 0 });
    }
    // she notices immediately: perks up and drops any guard pose
    st.foodReact = 1.9;
    st.alertTarget = 0;
    st.alertHold = 0;
    st.probe = 0;
    st.wanderT = Math.min(st.wanderT, 1.2);
    for (let i = 0; i < 3; i++) spawnBubble(tFood.set(x + rr(-0.1, 0.1), gy + 0.7, z), rr(0.04, 0.07), 0, 0.3, 0);
  }

  // ─── Light / dark theme ───────────────────────────────────────────────
  const PAL = {
    light: {
      sky: '#c8f5ff', ground: '#e6cc98', hemiI: 0.72, key: '#fff0cf', keyI: 0.85, rim: '#a9f2ff', rimI: 0.45,
      sand: '#e9d6ac', sandDark: '#c6ad7e', caustic: '#fffbea', causticI: 0.38, ray: '#ffffff', rayI: 1,
      snow: '#ffffff', snowI: 0.34, twinkle: 0, glow: 0, bubble: '#ffffff', small: '#3f86b3',
    },
    dark: {
      sky: '#5277b3', ground: '#0f1a30', hemiI: 0.85, key: '#a9c7ff', keyI: 0.62, rim: '#62f1ff', rimI: 0.9,
      sand: '#2f3f62', sandDark: '#1b2644', caustic: '#8ec6ff', causticI: 0.26, ray: '#7bafff', rayI: 0.5,
      snow: '#7ef9ff', snowI: 1, twinkle: 1, glow: 0.9, bubble: '#d4ecff', small: '#2a4f78',
    },
  };
  const PC = {};
  for (const k of Object.keys(PAL)) {
    PC[k] = {};
    for (const [n, v] of Object.entries(PAL[k])) PC[k][n] = typeof v === 'string' ? new THREE.Color(v) : v;
  }
  const mixC = (target, name, m) => target.copy(PC.light[name]).lerp(PC.dark[name], m);
  const mixN = (name, m) => lerp(PC.light[name], PC.dark[name], m);
  const theme = { m: 0, target: 0, fog: new THREE.Color('#55b8cf'), fogTarget: new THREE.Color('#55b8cf'), ready: false };

  function readTheme() {
    const cs = getComputedStyle(document.documentElement);
    theme.target = (parseFloat(cs.getPropertyValue('--mode')) || 0) > 0.5 ? 1 : 0;
    const f = cs.getPropertyValue('--fog').trim();
    if (f) theme.fogTarget.set(f);
    if (!theme.ready) { theme.m = theme.target; theme.fog.copy(theme.fogTarget); theme.ready = true; }
  }
  function applyTheme(t) {
    const m = theme.m;
    mixC(hemi.color, 'sky', m); mixC(hemi.groundColor, 'ground', m); hemi.intensity = mixN('hemiI', m);
    mixC(key.color, 'key', m); key.intensity = mixN('keyI', m);
    mixC(rim.color, 'rim', m); rim.intensity = mixN('rimI', m);
    scene.fog.color.copy(theme.fog);
    const u = sandMat.uniforms;
    mixC(u.uSand.value, 'sand', m); mixC(u.uSandDark.value, 'sandDark', m);
    mixC(u.uCaustic.value, 'caustic', m); u.uCausticStrength.value = mixN('causticI', m);
    const rayI = mixN('rayI', m);
    for (const r of rays) {
      mixC(r.m.material.color, 'ray', m);
      r.m.material.opacity = r.base * rayI * (0.6 + 0.4 * Math.sin(t * r.sp + r.ph));
      r.m.rotation.z = r.rot + Math.sin(t * 0.15 + r.ph) * 0.03 * MOTION;
    }
    mixC(snMat.uniforms.uColor.value, 'snow', m);
    snMat.uniforms.uOpacity.value = mixN('snowI', m);
    snMat.uniforms.uTwinkle.value = mixN('twinkle', m);
    mixC(bMat.uniforms.uColor.value, 'bubble', m);
    const glow = mixN('glow', m) * (0.7 + 0.3 * Math.sin(t * 1.8));
    shellMat.emissiveIntensity = glow;
    clawMat.emissiveIntensity = glow * 0.8;
    mixC(schoolMat.color, 'small', m);
    schoolTailMat.color.copy(schoolMat.color);
  }
  const darkQuery = window.matchMedia ? window.matchMedia('(prefers-color-scheme: dark)') : null;
  if (darkQuery) {
    if (darkQuery.addEventListener) darkQuery.addEventListener('change', readTheme);
    else if (darkQuery.addListener) darkQuery.addListener(readTheme);
  }
  new MutationObserver(readTheme).observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme', 'class', 'style'] });

  // ─── Layout ───────────────────────────────────────────────────────────
  const bounds = { x: 2.6, zMin: -2.6, zMax: 1.2 };
  function layout() {
    const w = Math.max(1, stage.clientWidth), h = Math.max(1, stage.clientHeight);
    renderer.setSize(w, h, false);
    camera.aspect = w / h;
    camDist = Math.max(2.5, 2.1 / camera.aspect) / tanHalf;
    camera.updateProjectionMatrix();
    const halfH = camDist * tanHalf;
    viewHalfW = halfH * camera.aspect;
    viewTop = camLook.y + halfH;
    bounds.x = Math.max(0.5, viewHalfW - 1.7);
    scene.fog.near = camDist + 2;
    scene.fog.far = camDist + 30;
    sandMat.uniforms.uFade.value.set(camDist + 8, camDist + 34);
    sandMat.uniforms.uDetail.value.set(camDist + 4, camDist + 19);
    const sc = renderer.domElement.height / (2 * tanHalf);
    bMat.uniforms.uScale.value = sc;
    snMat.uniforms.uScale.value = sc;
  }
  if (window.ResizeObserver) new ResizeObserver(layout).observe(stage);
  else window.addEventListener('resize', layout);
  layout();

  // ─── Clawdia's state ──────────────────────────────────────────────────
  const st = {
    pos: new V3(-(bounds.x + 3.0), sandAt(-(bounds.x + 3.0), -0.6) + 0.46, -0.6),
    vel: new V3(0.4, 0, 0), target: new V3(0, 0, 0.2),
    wanderT: 5, yaw: Math.PI / 2, pitch: 0, roll: 0, intro: true,
    alert: 0, alertV: 0, alertTarget: 0, alertHold: 0, deflate: 0,
    snap: 0, happy: 0, chomp: 0, gape: 0, probe: 0, foodReact: 0,
    bubbleIn: 3, gaitPh: 0, tailPh: 0,
  };
  function pickWander() {
    st.wanderT = rr(3, 7);
    st.target.set(rr(-bounds.x * 0.9, bounds.x * 0.9), 0, rr(bounds.zMin + 0.2, bounds.zMax - 0.1));
  }
  function snapClaws() {
    dismissHint();
    st.snap = 1;
    if (st.alertTarget === 1) { st.alertV += 3.0; st.alertHold = Math.max(st.alertHold, 1.8); return; }
    st.alertTarget = 1;
    st.alertHold = 2.6;
    st.alertV += 1.6;
  }

  // ─── Input ────────────────────────────────────────────────────────────
  const pointer = { ndc: new THREE.Vector2(), inside: false, active: 0, sx: 0, sy: 0 };
  const raycaster = new THREE.Raycaster();
  const sandPlane = new THREE.Plane(new V3(0, 1, 0), -(SAND_Y + 0.35));
  const hitSphere = new THREE.Sphere();
  const tHit = new V3();
  const coarse = window.matchMedia && window.matchMedia('(pointer: coarse)').matches;
  hintEl.textContent = coarse
    ? 'Tap Clawdia to make her snap, or tap the sand to drop food.'
    : 'Click Clawdia to make her snap, or click the sand to drop food.';

  function setNDC(e) {
    const r = canvas.getBoundingClientRect();
    pointer.ndc.set(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1);
  }
  function overLobster() {
    raycaster.setFromCamera(pointer.ndc, camera);
    carapace.getWorldPosition(hitSphere.center);
    hitSphere.radius = 1.05;
    return raycaster.ray.intersectsSphere(hitSphere);
  }
  let down = null;
  canvas.addEventListener('pointermove', (e) => {
    setNDC(e);
    pointer.inside = true;
    pointer.active = 2.5;
    if (e.pointerType === 'mouse') canvas.style.cursor = overLobster() ? 'pointer' : 'default';
  });
  canvas.addEventListener('pointerleave', () => { pointer.inside = false; });
  canvas.addEventListener('pointerdown', (e) => {
    setNDC(e);
    pointer.inside = true;
    pointer.active = 2.5;
    down = { x: e.clientX, y: e.clientY, t: performance.now() };
  });
  canvas.addEventListener('pointerup', (e) => {
    if (!down) return;
    const moved = Math.hypot(e.clientX - down.x, e.clientY - down.y), held = performance.now() - down.t;
    down = null;
    if (moved > 12 || held > 700) return;
    setNDC(e);
    dismissHint();
    if (overLobster()) { snapClaws(); return; }
    raycaster.setFromCamera(pointer.ndc, camera);
    if (raycaster.ray.intersectPlane(sandPlane, tHit)) {
      dropFood(tHit);
    } else {
      dropFood({ x: st.pos.x + rr(-1.2, 1.2), z: st.pos.z + rr(0.6, 1.6) });
    }
  });
  canvas.addEventListener('pointercancel', () => { down = null; });
  snapBtn.addEventListener('click', snapClaws);
  feedBtn.addEventListener('click', () => {
    dismissHint();
    dropFood({ x: st.pos.x + rr(-1.2, 1.2), z: st.pos.z + rr(0.5, 1.5) });
  });
  window.addEventListener('keydown', (e) => {
    const tag = e.target && e.target.tagName;
    if (tag === 'BUTTON' || tag === 'INPUT' || tag === 'TEXTAREA') return;
    if (e.key === ' ' || e.key === 'p' || e.key === 'P' || e.key === 's' || e.key === 'S') {
      e.preventDefault(); snapClaws();
    } else if (e.key === 'f' || e.key === 'F') feedBtn.click();
  });

  // ─── Per-frame update ─────────────────────────────────────────────────
  const tA = new V3(), tB = new V3(), tC = new V3(), mouthW = new V3(), fwd = new V3();
  let time = 0;

  function nearestFood() {
    let best = null, bd = Infinity;
    for (const f of foods) {
      const d = f.mesh.position.distanceToSquared(mouthW);
      if (d < bd) { bd = d; best = f; }
    }
    return best;
  }

  function update(dt) {
    time += dt;
    const t = time;

    theme.m = damp(theme.m, theme.target, 5, dt);
    theme.fog.lerp(theme.fogTarget, 1 - Math.exp(-5 * dt));
    applyTheme(t);

    // gentle parallax toward the pointer
    pointer.active = Math.max(0, pointer.active - dt);
    pointer.sx = damp(pointer.sx, pointer.inside ? pointer.ndc.x : 0, 1.8, dt);
    pointer.sy = damp(pointer.sy, pointer.inside ? pointer.ndc.y : 0, 1.8, dt);
    camera.position.set(pointer.sx * 0.45 * MOTION, SAND_Y + 2.45 + pointer.sy * 0.22 * MOTION, camDist);
    camera.lookAt(camLook);
    camera.updateMatrixWorld();

    // ── excitement after a food drop
    st.foodReact = Math.max(0, st.foodReact - dt);
    const reactK = smoothstep(0, 0.3, st.foodReact);

    // ── guard spring (bouncy up, softer down)
    if (st.alertHold > 0) {
      st.alertHold -= dt;
      if (st.alertHold <= 0) { st.alertTarget = 0; st.deflate = 1.4; }
    }
    const rising = st.alertTarget > 0.5;
    const K = rising ? 78 : 26, C = rising ? 7.5 : 9;
    st.alertV += (K * (st.alertTarget - st.alert) - C * st.alertV) * dt;
    st.alert += st.alertV * dt;
    const P = clamp(st.alert, -0.12, 1.3), P01 = clamp(P, 0, 1);
    const guarding = P > 0.35 || st.alertTarget > 0.5;
    const happyK = smoothstep(0, 0.3, st.happy);

    // ── walking goal
    const food = guarding ? null : nearestFood();
    let maxSpeed = 0.5 * MOTION, resp = 3.0;
    let chase = 0;                       // 0..1 urgency as she closes on a morsel
    if (st.intro) { maxSpeed = 0.9; if (st.pos.x > -bounds.x) st.intro = false; }
    if (food) {
      st.probe = 0;
      const fx = food.mesh.position.x - st.pos.x, fz = food.mesh.position.z - st.pos.z;
      const df = Math.hypot(fx, fz);
      st.target.set(food.mesh.position.x, 0, food.mesh.position.z);
      chase = smoothstep(3.2, 0.7, df);
      maxSpeed = lerp(1.05, 2.1, chase) * MOTION;
      resp = lerp(5.5, 9, chase);
      // little excited claw-snaps on the way in
      if (chase > 0.45 && st.snap <= 0 && rand() < 2.4 * dt) st.snap = 0.35;
      // jaws part as she gets within reach
      if (mouthW.distanceTo(food.mesh.position) < 0.85) st.gape = Math.max(st.gape, 0.75);
    } else if (st.probe > 0) {
      st.probe -= dt;
      maxSpeed = 0; resp = 6;
    } else if (guarding) {
      maxSpeed = 0; resp = 6;
    } else {
      st.wanderT -= dt;
      const dx = st.target.x - st.pos.x, dz = st.target.z - st.pos.z;
      if (!st.intro && (st.wanderT <= 0 || Math.hypot(dx, dz) < 0.22)) {
        pickWander();
        if (rand() < 0.45) st.probe = rr(0.9, 2.0);   // stop and feel around
      }
    }

    tA.set(st.target.x - st.pos.x, 0, st.target.z - st.pos.z);
    const dist = tA.length();
    tA.multiplyScalar(dist > 1e-4 ? Math.min(maxSpeed, dist * 1.6) / dist : 0);
    st.vel.x = damp(st.vel.x, tA.x, resp, dt);
    st.vel.z = damp(st.vel.z, tA.z, resp, dt);
    st.pos.x = clamp(st.pos.x + st.vel.x * dt, -Math.max(bounds.x, 0), Math.max(bounds.x, 0));
    st.pos.z = clamp(st.pos.z + st.vel.z * dt, bounds.zMin, bounds.zMax);

    const speed = Math.hypot(st.vel.x, st.vel.z);
    const gy = sandAt(st.pos.x, st.pos.z);
    st.gaitPh += dt * (2.4 + speed * 9 + reactK * 3 + chase * 6);
    const stepBob = Math.abs(Math.sin(st.gaitPh)) * 0.02 * (1 - P01);
    st.pos.y = damp(st.pos.y, gy + 0.46 + stepBob + 0.10 * P01, 10, dt);

    // ── heading & terrain tilt
    const prevYaw = st.yaw;
    if (food) {
      const fx = food.mesh.position.x - st.pos.x, fz = food.mesh.position.z - st.pos.z;
      if (Math.hypot(fx, fz) > 0.05) st.yaw = dampAngle(st.yaw, Math.atan2(fx, fz), 7 + chase * 7, dt);
    } else if (speed > 0.03) {
      st.yaw = dampAngle(st.yaw, Math.atan2(st.vel.x, st.vel.z), 3.2, dt);
    }
    const yawRate = wrapAngle(st.yaw - prevYaw) / Math.max(dt, 1e-3);

    const ax = Math.sin(st.yaw), az = Math.cos(st.yaw);
    const aheadY = sandAt(st.pos.x + ax * 0.5, st.pos.z + az * 0.5);
    const behindY = sandAt(st.pos.x - ax * 0.5, st.pos.z - az * 0.5);
    const slopePitch = -Math.atan2(aheadY - behindY, 1.0) * 0.55;
    st.pitch = damp(st.pitch, slopePitch, 4, dt);
    st.roll = damp(st.roll, clamp(-yawRate * 0.12, -0.2, 0.2) + Math.sin(st.gaitPh) * 0.025 * (1 - P01), 5, dt);
    lob.position.copy(st.pos);
    lob.rotation.set(st.pitch, st.yaw, st.roll);

    // ── body pose
    core.rotation.x = -0.30 * P01 - 0.10 * reactK * (1 - P01) + 0.06 * chase + Math.sin(t * 1.1) * 0.012;
    core.rotation.z = Math.sin(st.gaitPh) * 0.028 * (1 - P01);
    core.position.y = 0.06 * P01 + 0.03 * reactK * Math.sin(t * 22) * (1 - P01);
    core.scale.setScalar(0.78 * (1 + 0.04 * P01 + 0.02 * reactK));

    // ── claws: reach forward when hunting, raised when guarding
    st.snap = Math.max(0, st.snap - dt * 2.2);
    const snapWave = st.snap > 0 ? (0.5 + 0.5 * Math.sin(st.snap * 26)) * st.snap : 0;
    const reach = chase * (1 - P01);
    for (const c of claws) {
      const restX = lerp(0.32, -0.36, P01);
      c.root.rotation.x = restX - 0.26 * reach + Math.sin(t * 2 + c.ph) * 0.03 +
        Math.sin(st.gaitPh + c.ph) * 0.05 * (1 - P01) + happyK * Math.sin(t * 16) * 0.14;
      c.root.rotation.y = c.base.y + c.side * 0.24 * P01 + Math.sin(t * 1.3 + c.ph) * 0.03 +
        c.side * 0.10 * reach;
      c.root.rotation.z = c.base.z + c.side * 0.16 * P01;
      const open = clamp(P01 * 0.55 + snapWave * 0.85 + reach * 0.45 + reactK * 0.2, 0, 1);
      c.dactyl.rotation.x = -open * 0.75;
    }

    // ── walking legs (alternating tetrapod gait)
    for (const L of legs) {
      const phase = ((L.i + (L.side > 0 ? 1 : 0)) % 2) * Math.PI;
      const ph = st.gaitPh + phase;
      const swing = Math.cos(ph);
      const lift = Math.max(0, Math.sin(ph));
      L.hip.rotation.x = L.baseX + swing * (0.07 + Math.min(speed, 1.4) * 0.12);
      L.up.rotation.z = L.upZ + L.side * lift * 0.22;
      L.low.rotation.z = L.lowZ + L.side * lift * 0.10;
    }

    // ── tail fan & abdomen
    st.tailPh += dt * (2.5 + speed * 6 + P01 * 8);
    tail.rotation.x = 0.22 * P01 + Math.sin(st.tailPh) * (0.05 + speed * 0.06);
    for (let i = 0; i < abdomen.length; i++) {
      abdomen[i].rotation.x = Math.sin(st.tailPh - i * 0.5) * 0.035;
    }

    bob.position.y = stepBob * 0.6 + happyK * Math.sin(t * 18) * 0.03;
    bob.rotation.x = Math.sin(t * 1.3 + 1) * 0.02;
    bob.rotation.z = Math.sin(st.gaitPh) * 0.03;

    lob.updateMatrixWorld(true);
    mouth.getWorldPosition(mouthW);
    fwd.set(0, 0, 1).applyQuaternion(lob.quaternion);

    updateAntennae(t, P01, food ? Math.max(reactK, 0.55) : 0);

    // ── eyes lock onto the morsel
    if (food) {
      tC.copy(food.mesh.position);
      core.worldToLocal(tC);
      for (const e of eyeStalks) {
        const dx = tC.x - e.g.position.x;
        const dy = tC.y - e.g.position.y;
        const dz = tC.z - e.g.position.z;
        const yaw = clamp(Math.atan2(dx, dz), -0.55, 0.55);
        const pitch = clamp(Math.atan2(dy, Math.max(0.001, Math.hypot(dx, dz))), -0.4, 0.4);
        e.g.rotation.y = damp(e.g.rotation.y, e.baseY + yaw * 0.75, 10, dt);
        e.g.rotation.x = damp(e.g.rotation.x, e.baseX - pitch * 0.75, 10, dt);
      }
    } else {
      for (const e of eyeStalks) {
        e.g.rotation.y = damp(e.g.rotation.y, e.baseY, 3, dt);
        e.g.rotation.x = damp(e.g.rotation.x, e.baseX, 3, dt);
      }
    }

    // ── mandibles
    st.chomp = Math.max(0, st.chomp - dt * 3.5);
    st.gape = Math.max(0, st.gape - dt * 4.5);
    const gp = Math.sin(st.gape * Math.PI);
    const ch = Math.sin(st.chomp * Math.PI);
    for (const j of jaws) {
      j.m.position.x = j.side * (0.045 + gp * 0.055 + ch * 0.02);
      j.m.rotation.z = j.side * (gp * 0.5 + ch * 0.3);
      j.m.scale.y = 0.085 * (1 + ch * 0.2);
    }
    st.happy = Math.max(0, st.happy - dt);

    // ── bubbles from the mouth
    st.bubbleIn -= dt;
    if (st.bubbleIn <= 0 && !guarding) {
      st.bubbleIn = rr(2.5, 6.5);
      const n = 1 + Math.floor(rand() * 3);
      for (let i = 0; i < n; i++) {
        tA.copy(mouthW).addScaledVector(fwd, 0.05 + i * 0.05).add(tC.set(rr(-0.03, 0.03), i * 0.09, rr(-0.03, 0.03)));
        spawnBubble(tA, rr(0.04, 0.085), fwd.x * 0.3, 0.15, fwd.z * 0.3);
      }
    }
    if (st.deflate > 0) {
      st.deflate -= dt;
      if (rand() < 36 * smoothstep(0, 0.4, st.deflate) * dt) {
        tA.copy(mouthW).add(tC.set(rr(-0.04, 0.04), rr(-0.04, 0.04), rr(-0.04, 0.04)));
        spawnBubble(tA, rr(0.035, 0.1), fwd.x * 0.9, 0.2, fwd.z * 0.9);
      }
    }

    // ── food: sink, settle, fade, or get eaten
    for (let i = foods.length - 1; i >= 0; i--) {
      const f = foods[i], m = f.mesh;
      f.t += dt;
      let fade = 1;
      if (!f.landed) {
        m.position.y -= 0.24 * dt;
        m.position.x += Math.sin(f.t * 2.2 + f.ph) * 0.14 * dt;
        m.rotation.x += f.spin * dt;
        m.rotation.z += f.spin * 0.6 * dt;
        const fy = sandAt(m.position.x, m.position.z) + 0.06;
        if (m.position.y <= fy) { m.position.y = fy; f.landed = true; f.landT = f.t; }
      } else {
        fade = 1 - smoothstep(10, 13, f.t - f.landT);
        if (fade <= 0) { scene.remove(m); foods.splice(i, 1); continue; }
      }
      m.scale.setScalar(Math.max(0.001, smoothstep(0, 0.25, f.t) * fade));
      if (!guarding && mouthW.distanceTo(m.position) < 0.45) {
        scene.remove(m);
        foods.splice(i, 1);
        st.chomp = 1; st.gape = 1; st.happy = 1.1;
        st.snap = Math.max(st.snap, 0.7);
        st.foodReact = Math.max(st.foodReact, 1.0);
        for (let k = 0; k < 4; k++) {
          tA.copy(mouthW).add(tC.set(rr(-0.08, 0.08), rr(0, 0.1), rr(-0.05, 0.05)));
          spawnBubble(tA, rr(0.03, 0.06), rr(-0.1, 0.1), 0.25, rr(-0.1, 0.1));
        }
      }
    }

    // ── soft shadow on the sand
    sandMat.uniforms.uShadow.value.set(st.pos.x, st.pos.z, 0.5, 1.25);
    sandMat.uniforms.uTime.value = t * MOTION;
    snMat.uniforms.uTime.value = t;

    updateWhips(t);
    updateFans(t);
    updateAnemones(t);
    updateSnow(dt, t);
    updateVents(dt);
    updateBubbles(dt);
    updateSchool(t);
  }

  readTheme();
  applyTheme(0);
  const clock = new THREE.Clock();
  renderer.setAnimationLoop(() => {
    update(Math.min(clock.getDelta(), 1 / 20));
    renderer.render(scene, camera);
  });
})();
</script>
</body>
</html>
MikeHiggins.me.uk LinkedIn GitHub Bluesky Contra Upwork
© 2026 Mike Higgins. All rights reserved.