Skip to content
VibeCodeBench
Back to the app

The code

Swim the Kelp Garden by GPT-6.2 Sol

Exactly as the AI wrote it. Shown as text, so nothing runs on this page.

index.html

broken · auto-checked (Checked by an automated pass. Not hand-played yet.)77.5 KB · 1,600 lines · loads cdn.jsdelivr.net/npm/[email protected]/build/three.min.js
Download
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#092b35">
<title>Kelp Garden · Underwater Explorer</title>
<style>
  :root {
    color-scheme: dark;
    --ink: #f2f3e4;
    --mist: #b8d3cb;
    --gold: #edc283;
    --line: rgba(185, 220, 207, .26);
    --glass: rgba(5, 29, 36, .76);
    --edge: clamp(20px, 3.45vw, 60px);
    --top: max(24px, env(safe-area-inset-top));
    --bottom: max(27px, env(safe-area-inset-bottom));
  }
  * { box-sizing: border-box; }
  html, body { width: 100%; height: 100%; margin: 0; overflow: hidden; overscroll-behavior: none; }
  body {
    color: var(--ink);
    background: #092b35;
    font: 14px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif;
    touch-action: none;
    -webkit-tap-highlight-color: transparent;
    user-select: none;
  }
  button { font: inherit; color: inherit; }
  #garden { position: fixed; inset: 0; isolation: isolate; overflow: hidden; }
  #view, #view canvas, .shade { position: absolute; inset: 0; width: 100%; height: 100%; }
  #view { background: radial-gradient(ellipse at 60% 0%, #28767c, #103e51 55%, #082732); touch-action: none; }
  #view canvas { display: block; outline: none; }
  .shade {
    pointer-events: none;
    background:
      linear-gradient(90deg, rgba(3, 24, 29, .61), rgba(3, 27, 32, .14) 34%, transparent 57%),
      linear-gradient(0deg, rgba(3, 24, 32, .83), transparent 25%),
      linear-gradient(180deg, rgba(4, 29, 37, .49), transparent 19%),
      radial-gradient(ellipse at 53% 42%, transparent 52%, rgba(5, 26, 34, .35) 100%);
  }
  .topbar {
    position: absolute; top: var(--top); left: var(--edge); right: var(--edge);
    display: flex; align-items: center; justify-content: space-between; gap: 14px;
    padding-bottom: 14px; border-bottom: 1px solid var(--line);
  }
  .brand { display: flex; align-items: center; gap: 11px; }
  .brand-mark {
    display: grid; place-items: center; width: 41px; height: 41px; flex: none;
    border: 1px solid rgba(206, 235, 220, .51); border-radius: 50%; background: rgba(7, 43, 48, .42);
  }
  .brand-mark canvas { width: 29px; height: 29px; }
  .micro {
    font-size: 10px; font-weight: 650; letter-spacing: .19em; text-transform: uppercase;
  }
  .brand .micro { font-size: 11px; white-space: nowrap; }
  .actions { display: flex; align-items: center; gap: 8px; }
  .control {
    height: 45px; display: inline-flex; align-items: center; justify-content: center; gap: 8px;
    padding: 0 14px; border-radius: 24px; border: 1px solid var(--line);
    background: var(--glass); cursor: pointer; touch-action: manipulation;
    box-shadow: 0 2px 10px rgba(3, 21, 27, .13); transition: background .18s, border-color .18s;
  }
  .control:focus-visible { outline: 2px solid var(--gold); outline-offset: 3px; }
  .control:active, .control[aria-pressed="true"] { background: #194d50; border-color: #94b9a4; }
  .control span { white-space: nowrap; font-size: 12px; font-weight: 600; }
  .control canvas { width: 19px; height: 19px; }
  .control.icon-only { width: 45px; padding: 0; }
  .compass {
    overflow: hidden; position: absolute; left: 50%; top: 4px; transform: translateX(-50%);
    width: 182px; height: 36px; pointer-events: none;
    mask-image: linear-gradient(90deg, transparent, #000 18%, #000 82%, transparent);
  }
  .compass i {
    position: absolute; top: 24px; width: 1px; height: 4px; background: rgba(197, 224, 215, .55);
  }
  .compass i.cardinal { height: 7px; }
  .compass i span {
    position: absolute; bottom: 13px; left: 0; transform: translateX(-50%);
    font: 600 9px/1 system-ui, sans-serif; font-style: normal; color: #dcf0e7;
  }
  .compass::after {
    content: ""; position: absolute; top: 29px; left: 50%; margin-left: -3px; width: 0; height: 0;
    border-left: 3px solid transparent; border-right: 3px solid transparent; border-bottom: 5px solid var(--gold);
  }
  .intro {
    position: absolute; top: clamp(106px, 16.4vh, 175px); left: var(--edge); pointer-events: none;
    transition: transform .8s ease, opacity .8s ease;
  }
  .exploring .intro { opacity: 0; transform: translateY(-9px); }
  .eyebrow { display: flex; align-items: center; gap: 10px; color: var(--gold); }
  .eyebrow::before { content: ""; width: 24px; height: 1px; background: currentColor; }
  h1 {
    margin: 15px 0 20px; font: 400 clamp(68px, 7.5vw, 122px)/.84 Georgia, "Times New Roman", serif;
    letter-spacing: -.075em; text-shadow: 0 5px 36px rgba(4, 26, 32, .27);
  }
  h1 em { font-weight: 400; color: #d0e5ce; }
  .intro p { margin: 0; max-width: 235px; color: #d0e2db; line-height: 1.6; }
  .depth {
    position: absolute; left: var(--edge); bottom: var(--bottom); display: flex; align-items: center;
    gap: 11px; pointer-events: none; text-shadow: 0 2px 10px #071e27;
  }
  .depth .micro { display: block; color: var(--mist); margin-bottom: 2px; }
  .depth canvas { width: 14px; height: 39px; }
  .depth strong {
    display: inline-block; font-size: 28px; line-height: 1; letter-spacing: -.045em;
    font-weight: 450; font-variant-numeric: tabular-nums;
  }
  .depth small { color: var(--gold); font-size: 13px; margin-left: 4px; }
  .dock {
    position: absolute; bottom: var(--bottom); left: 50%; transform: translateX(-50%);
    pointer-events: none; overflow: hidden; white-space: nowrap;
    border: 1px solid var(--line); border-radius: 28px; background: var(--glass);
    box-shadow: 0 6px 28px rgba(2, 20, 28, .17); transition: border-color .25s, background .25s;
  }
  .gesture, .tour-readout { height: 50px; display: flex; align-items: center; justify-content: center; gap: 10px; padding: 0 17px; }
  .gesture canvas { width: 22px; height: 22px; }
  .gesture strong { font-weight: 600; }
  .gesture span { color: var(--mist); font-size: 13px; }
  .gesture b { display: block; width: 3px; height: 3px; background: var(--gold); border-radius: 100%; }
  .swimming .dock { background: rgba(12, 57, 59, .84); border-color: rgba(186, 230, 198, .6); }
  .tour-readout { display: none; min-width: 244px; gap: 9px; }
  .tour-readout .micro { color: var(--gold); font-size: 9px; }
  .tour-readout strong { font-size: 13px; font-weight: 600; }
  .tour-readout .progress { position: absolute; bottom: 0; left: 0; width: 100%; height: 2px; background: var(--gold); transform: scaleX(0); transform-origin: left; }
  .touring .tour-readout { display: flex; }
  .touring .gesture { display: none; }
  .map-card {
    position: absolute; right: var(--edge); bottom: var(--bottom); width: 181px; padding: 11px 12px 10px;
    border: 1px solid var(--line); border-radius: 13px; background: var(--glass);
    pointer-events: none; box-shadow: 0 6px 28px rgba(2, 20, 28, .17);
  }
  .map-top { display: flex; align-items: center; justify-content: space-between; color: var(--mist); }
  .map-top span:last-child { color: var(--gold); font-size: 10px; }
  #map { display: block; width: 100%; height: 101px; }
  .map-key { display: flex; justify-content: space-between; gap: 6px; font-size: 10px; color: #d0e2db; }
  .map-key span { display: flex; align-items: center; gap: 5px; white-space: nowrap; }
  .map-key i { display: inline-block; width: 6px; height: 6px; border: 1px solid #a5d5be; border-radius: 50%; }
  .map-key i.wreck { border-color: var(--gold); border-radius: 0; transform: rotate(45deg); }
  .site-label {
    position: absolute; pointer-events: none; transform: translate(-50%, -100%);
    color: #e1efe1; text-align: center; white-space: nowrap; text-shadow: 0 1px 6px #06353c, 0 1px 12px #06353c;
  }
  .site-label .micro { font-size: 9px; letter-spacing: .16em; }
  .site-label .range { margin-left: 5px; color: var(--gold); font-size: 10px; font-variant-numeric: tabular-nums; }
  .site-label::after {
    display: block; margin: 4px auto 0; content: ""; height: 14px; width: 1px;
    background: linear-gradient(#def1df, transparent);
  }
  .message {
    position: absolute; top: 56%; left: 50%; transform: translate(-50%, -50%); width: min(330px, 90%);
    padding: 18px 22px; border: 1px solid var(--line); border-radius: 12px; background: #0b333e;
  }
  [hidden] { display: none !important; }
  @media (max-width: 720px) {
    :root { --edge: max(17px, env(safe-area-inset-left)); --top: max(14px, env(safe-area-inset-top)); --bottom: max(15px, env(safe-area-inset-bottom)); }
    .compass, .site-label { display: none; }
    .brand { gap: 7px; }
    .brand .micro { font-size: 9px; letter-spacing: .13em; }
    .brand-mark { width: 35px; height: 35px; }
    .topbar { padding-bottom: 9px; }
    .actions { gap: 5px; }
    .control { padding: 0 11px; }
    .control span { font-size: 11px; }
    .intro { top: clamp(90px, 13vh, 136px); }
    h1 { font-size: clamp(57px, 12.4vw, 90px); margin: 13px 0 15px; }
    .intro p { font-size: 12px; max-width: 178px; }
    .shade {
      background:
        linear-gradient(135deg, #041d27a6, transparent 51%),
        linear-gradient(0deg, #041d27d6, transparent 31%),
        radial-gradient(ellipse at 51% 39%, transparent 47%, #05242c58);
    }
    .map-card { bottom: calc(var(--bottom) + 63px); width: 128px; padding: 7px 8px; border-radius: 10px; }
    #map { height: 72px; }
    .map-key { display: none; }
    .map-top .micro { font-size: 9px; }
    .depth { bottom: calc(var(--bottom) + 65px); }
    .depth strong { font-size: 25px; }
    .gesture, .tour-readout { height: 46px; }
  }
  @media (max-width: 355px) { .brand .micro { display: none; } }
  @media (max-height: 490px) and (orientation: landscape) {
    :root { --top: 9px; --bottom: 9px; }
    .topbar { padding-bottom: 5px; }
    .intro { top: 74px; }
    h1 { font-size: 57px; margin: 9px 0 12px; }
    .intro p { font-size: 11px; }
    .map-card, .depth { bottom: var(--bottom); }
    #map { height: 62px; }
  }
  @media (prefers-reduced-motion: reduce) {
    .intro, .dock, .control { transition: none; }
  }
</style>
</head>
<body>
<main id="garden" aria-label="Kelp Garden underwater explorer">
  <div id="view"></div>
  <div class="shade" aria-hidden="true"></div>
  <div id="arch-label" class="site-label" aria-hidden="true"><span class="micro">Rock arch</span><span class="range"></span></div>
  <div id="wreck-label" class="site-label" aria-hidden="true"><span class="micro">Shipwreck</span><span class="range"></span></div>
  <header class="topbar">
    <div class="brand"><div class="brand-mark"><canvas data-icon="garden" aria-hidden="true"></canvas></div><span class="micro">Underwater Explorer</span></div>
    <div class="compass" id="compass" aria-hidden="true"></div>
    <div class="actions">
      <button class="control" id="tour" type="button" aria-pressed="false"><canvas id="tour-icon" data-icon="play" aria-hidden="true"></canvas><span id="tour-text">Guided tour</span></button>
      <button class="control icon-only" id="reset" type="button" aria-label="Reset view" title="Reset view"><canvas data-icon="reset" aria-hidden="true"></canvas></button>
    </div>
  </header>
  <section class="intro" id="intro">
    <div class="eyebrow micro">Coastal habitat</div>
    <h1>Kelp<br><em>Garden</em></h1>
    <p>Swim through sunlit kelp, past a rocky arch and a ship resting on the seafloor.</p>
  </section>
  <div class="depth" aria-label="Depth below the surface">
    <canvas data-icon="depth" aria-hidden="true"></canvas>
    <div><span class="micro">Depth</span><strong id="depth">10.6</strong><small>m</small></div>
  </div>
  <div class="dock">
    <div class="gesture" id="instructions"><canvas id="gesture-icon" data-icon="mouse" aria-hidden="true"></canvas><strong>Hold to swim</strong><b></b><span>Drag to turn</span></div>
    <div class="tour-readout"><span class="micro">Guided tour</span><strong id="chapter" role="status">Kelp forest</strong><span class="progress" id="progress"></span></div>
  </div>
  <aside class="map-card" aria-label="Dive map. Rock arch and shipwreck are north of the starting position.">
    <div class="map-top"><span class="micro">Dive map</span><span>↑ N</span></div>
    <canvas id="map" aria-hidden="true"></canvas>
    <div class="map-key"><span><i></i>Rock arch</span><span><i class="wreck"></i>Shipwreck</span></div>
  </aside>
  <div class="message" id="message" role="status" hidden></div>
</main>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>
<script>
(() => {
  "use strict";
  const byId = id => document.getElementById(id);
  const stage = byId("garden");
  const view = byId("view");
  const tourButton = byId("tour");
  const resetButton = byId("reset");

  function paintIcon(canvas, kind) {
    const depth = kind === "depth";
    const w = depth ? 14 : 24;
    const h = depth ? 39 : 24;
    canvas.width = w * 3;
    canvas.height = h * 3;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;
    ctx.scale(3, 3);
    ctx.strokeStyle = depth ? "#9fbdb1" : "#dcebe0";
    ctx.fillStyle = "#edc283";
    ctx.lineWidth = 1.35;
    ctx.lineCap = "round";
    ctx.lineJoin = "round";
    const draw = path => { ctx.beginPath(); path(); ctx.stroke(); };
    if (kind === "garden") {
      draw(() => {
        ctx.moveTo(4, 17.8); ctx.bezierCurveTo(8.6, 14.8, 13, 20.2, 20, 16.8);
        ctx.moveTo(6.3, 20); ctx.bezierCurveTo(10.5, 18.8, 14.2, 21.8, 18.3, 19.5);
        ctx.moveTo(11.8, 16); ctx.bezierCurveTo(9.9, 11.7, 13.1, 9.2, 11.7, 4.2);
        ctx.moveTo(11.4, 12.2); ctx.bezierCurveTo(8.4, 12.2, 6.7, 9.3, 7.6, 7);
        ctx.moveTo(12, 10.1); ctx.bezierCurveTo(14.5, 9.7, 16.4, 7.2, 16.4, 5.1);
      });
      ctx.beginPath(); ctx.arc(19.1, 10.3, 1.05, 0, Math.PI * 2); ctx.fill();
    } else if (kind === "play") {
      ctx.beginPath(); ctx.moveTo(8.5, 5.2); ctx.lineTo(18.9, 12); ctx.lineTo(8.5, 18.8); ctx.closePath(); ctx.fill();
    } else if (kind === "pause") {
      ctx.fillRect(8, 5.3, 2.7, 13.4); ctx.fillRect(13.8, 5.3, 2.7, 13.4);
    } else if (kind === "reset") {
      draw(() => {
        ctx.arc(12, 12, 6.8, -2.48, 2.7);
        ctx.moveTo(5.6, 4.9); ctx.lineTo(5.3, 9.8); ctx.lineTo(10.3, 9.1);
      });
    } else if (kind === "depth") {
      draw(() => {
        ctx.moveTo(3, 3); ctx.lineTo(3, 35);
        for (let i = 0; i < 5; i++) { ctx.moveTo(3, 3 + 8 * i); ctx.lineTo(i % 2 ? 6.5 : 9, 3 + 8 * i); }
      });
      ctx.beginPath(); ctx.moveTo(5, 19); ctx.lineTo(11.5, 16.4); ctx.lineTo(11.5, 21.6); ctx.closePath(); ctx.fill();
    } else if (kind === "touch") {
      draw(() => {
        ctx.moveTo(9.1, 20.4); ctx.lineTo(5, 14.7); ctx.quadraticCurveTo(4.4, 13.3, 5.4, 12.7);
        ctx.quadraticCurveTo(6.2, 12.2, 8.8, 14.8); ctx.lineTo(8.8, 6.1);
        ctx.quadraticCurveTo(8.8, 3.2, 10.6, 3.2); ctx.quadraticCurveTo(12.1, 3.2, 12.1, 6.1);
        ctx.lineTo(12.1, 11.1); ctx.lineTo(16.9, 11.7); ctx.quadraticCurveTo(19.5, 12, 19, 15.3);
        ctx.lineTo(17.9, 20.4); ctx.closePath();
      });
    } else {
      draw(() => {
        ctx.moveTo(12, 21); ctx.bezierCurveTo(7.5, 21, 5.5, 18.7, 5.5, 14);
        ctx.lineTo(5.5, 9.7); ctx.bezierCurveTo(5.5, .9, 18.5, .9, 18.5, 9.7);
        ctx.lineTo(18.5, 14); ctx.bezierCurveTo(18.5, 18.7, 16.5, 21, 12, 21);
        ctx.moveTo(12, 6.1); ctx.lineTo(12, 10);
      });
    }
  }
  document.querySelectorAll("[data-icon]").forEach(canvas => paintIcon(canvas, canvas.dataset.icon));
  if (matchMedia("(pointer: coarse)").matches) paintIcon(byId("gesture-icon"), "touch");

  function fail() {
    const message = byId("message");
    message.textContent = "The garden needs WebGL and access to the three.js library on jsDelivr.";
    message.hidden = false;
    tourButton.disabled = resetButton.disabled = true;
    document.querySelectorAll(".site-label, .map-card, .dock, .depth").forEach(element => { element.hidden = true; });
  }

  if (!window.THREE) { fail(); return; }
  try {
    createGarden(window.THREE);
  } catch (error) {
    console.error(error);
    fail();
  }

  function createGarden(T) {
    const scene = new T.Scene();
    const camera = new T.PerspectiveCamera(54, 1, .08, 190);
    const renderer = new T.WebGLRenderer({ antialias: true, alpha: false });
    renderer.outputColorSpace = T.SRGBColorSpace;
    renderer.toneMapping = T.ACESFilmicToneMapping;
    renderer.toneMappingExposure = 1.05;
    renderer.domElement.setAttribute("aria-label", "Underwater garden. Hold to swim and drag to turn.");
    view.appendChild(renderer.domElement);

    const WATER = 17.2;
    const TAU = Math.PI * 2;
    const UP = new T.Vector3(0, 1, 0);
    const Z = new T.Vector3(0, 0, 1);
    const ORIGIN = new T.Vector3();
    const time = { value: 0 };
    const pointRatio = { value: 1 };
    const V = (x, y, z) => new T.Vector3(x, y, z);
    const color = value => new T.Color(value);
    const clamp = (x, a, b) => Math.max(a, Math.min(b, x));
    const mix = (a, b, f) => a + (b - a) * f;
    let seed = 473191;
    function random() {
      seed ^= seed << 13;
      seed ^= seed >>> 17;
      seed ^= seed << 5;
      return (seed >>> 0) / 4294967296;
    }
    const range = (a, b) => mix(a, b, random());
    const pick = list => list[Math.floor(random() * list.length)];
    const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;

    const waterColor = `
      vec3 gardenWater(vec3 ray) {
        float up = smoothstep(-.11, .65, ray.y);
        float down = smoothstep(.05, .87, -ray.y);
        float sun = pow(max(dot(ray, normalize(vec3(.23, .42, -.88))), 0.0), 8.0);
        vec3 water = mix(vec3(.016, .100, .148), vec3(.009, .045, .077), down);
        water = mix(water, vec3(.030, .178, .218), up);
        return water + sun * (.34 + .66 * up) * vec3(.052, .222, .196);
      }
      float gardenHaze(float distanceToEye) {
        return 1.0 - exp(-pow(distanceToEye * .024, 1.51));
      }
    `;
    const glintPattern = `
      float gardenGlints(vec2 p, float t) {
        p += vec2(.62 * sin(p.y * 1.08 + .28 * t), .57 * sin(p.x * .94 - .25 * t));
        float m = sin(p.x * 1.63 + p.y * .84 + t * .32)
                + sin(p.y * 1.87 - p.x * .43 - t * .38) * .94
                + sin(p.x * 1.22 - p.y * 1.53 + t * .24) * .48;
        return .78 * (1.0 - smoothstep(.026, .25, abs(m)))
             + .22 * (1.0 - smoothstep(.10, .78, abs(m)));
      }
    `;
    const materialDetails = {
      sand: `
        vec2 p = vGardenWorld.xz;
        float ridge = .5 + .5 * sin(p.y * 5.1 + p.x * 1.26 + 1.8 * sin(p.x * .52 + p.y * .15));
        float grain = fract(sin(dot(floor(p * 51.0), vec2(12.9898, 78.233))) * 43758.5453);
        float closeSand = 1.0 - smoothstep(9.0, 32.0, length(vGardenWorld - cameraPosition));
        diffuseColor.rgb *= .91 + closeSand * (.18 * ridge + .11 * (grain - .5));
      `,
      rock: `
        vec3 p = vGardenWorld;
        float layers = sin(p.y * 6.7 + p.x * .8 + 1.6 * sin(p.z * 1.9));
        float flecks = sin(p.x * 12.0 + p.y * 15.1) * sin(p.z * 10.7 - p.y * 17.5);
        diffuseColor.rgb *= .88 + .11 * layers + .11 * flecks;
        diffuseColor.rgb *= mix(vec3(.91, .97, 1.02), vec3(1.12, 1.06, .85), smoothstep(.2, .9, layers));
      `,
      wood: `
        vec2 p = vGardenUv;
        float fibers = sin(p.y * 114.0 + 1.4 * sin(p.x * 12.0 + p.y * 3.0)) * .11;
        float crack = smoothstep(.90, .99, sin(p.y * 66.0 + sin(p.x * 4.0)));
        float rim = smoothstep(.82, 1.0, p.y);
        diffuseColor.rgb *= .94 + fibers - crack * .16 + rim * .24;
      `,
      kelp: `
        float vein = pow(max(0.0, 1.0 - abs(vGardenUv.y * 2.0 - 1.0)), 15.0);
        float folds = .5 + .5 * sin(vGardenUv.x * 41.0 - vGardenUv.y * 2.8);
        diffuseColor.rgb *= .89 + vein * .32 + folds * .16;
      `
    };

    function gardenMaterial(kind, options = {}, phase = 0) {
      const mat = new T.MeshStandardMaterial({ roughness: .87, ...options });
      mat.customProgramCacheKey = () => "garden-" + kind;
      mat.onBeforeCompile = shader => {
        shader.uniforms.uGardenTime = time;
        shader.uniforms.uRayPhase = { value: phase };
        let animation = "";
        let attributes = "";
        if (kind === "kelp") {
          attributes = "attribute vec3 aSway;";
          animation = `
            float along = aSway.y;
            float sway = pow(max(along, 0.0), 1.35);
            transformed.x += sway * (.67 * sin(uGardenTime * .76 + aSway.x + along * 2.6)
                          + .28 * cos(uGardenTime * .38 + along * 4.0));
            transformed.z += sway * (.49 * cos(uGardenTime * .57 + aSway.x + along * 2.0));
            transformed.y += aSway.z * .14 * sin(uGardenTime * 1.46 + aSway.x + position.x * .9);
          `;
        } else if (kind === "fish") {
          attributes = "attribute float aSchoolPhase;";
          animation = `
            transformed.x += pow(clamp(.20 - position.z, 0.0, 1.0), 1.5)
                           * .23 * sin(uGardenTime * 12.5 + aSchoolPhase + position.z * 8.0);
          `;
        } else if (kind === "ray") {
          attributes = "uniform float uRayPhase;";
          animation = `
            float wing = clamp(abs(position.x) / 3.3, 0.0, 1.0);
            transformed.y += .93 * pow(wing, 1.65) * sin(uGardenTime * 1.83 + uRayPhase - wing * 1.45);
            transformed.z += .17 * pow(wing, 1.8) * cos(uGardenTime * 1.83 + uRayPhase - wing);
            transformed.x += .16 * max(0.0, -position.z - 1.2) * sin(uGardenTime * 1.5 + position.z);
          `;
        }
        const varyings = "uniform float uGardenTime; varying vec3 vGardenWorld; varying vec2 vGardenUv;\n";
        shader.vertexShader = varyings + attributes + "\n" + shader.vertexShader
          .replace("#include <begin_vertex>", "#include <begin_vertex>\n" + animation)
          .replace("#include <worldpos_vertex>", `
            #include <worldpos_vertex>
            vec4 gardenPosition = vec4(transformed, 1.0);
            #ifdef USE_INSTANCING
              gardenPosition = instanceMatrix * gardenPosition;
            #endif
            vGardenWorld = (modelMatrix * gardenPosition).xyz;
            vGardenUv = uv;
          `);
        const strength = kind === "sand" ? ".96" : kind === "rock" ? ".70" : kind === "wood" ? ".62" : ".38";
        shader.fragmentShader = varyings + waterColor + glintPattern + shader.fragmentShader
          .replace("#include <color_fragment>", "#include <color_fragment>\n" + (materialDetails[kind] || ""))
          .replace("#include <opaque_fragment>", `
            vec2 projectedLight = vGardenWorld.xz + vec2(.48, -.37) * vGardenWorld.y;
            vec2 sunPatch = (projectedLight - vec2(4.0, -12.0)) * vec2(.049, .038);
            float pool = .36 + .64 * exp(-dot(sunPatch, sunPatch));
            float glints = gardenGlints(projectedLight * 1.05, uGardenTime) * pool * ` + strength + `;
            outgoingLight = outgoingLight * (.97 + glints * .57)
              + (diffuseColor.rgb * .26 + vec3(.14, .30, .21)) * glints * .42;
            #include <opaque_fragment>
          `)
          .replace("#include <colorspace_fragment>", `
            vec3 waterRay = vGardenWorld - cameraPosition;
            gl_FragColor.rgb = mix(gl_FragColor.rgb, gardenWater(normalize(waterRay)), gardenHaze(length(waterRay)));
            #include <colorspace_fragment>
          `);
      };
      return mat;
    }
    function colored(kind, options) {
      return gardenMaterial(kind, { vertexColors: true, side: T.DoubleSide, ...options });
    }
    function addMesh(geometry, material, parent = scene) {
      const mesh = new T.Mesh(geometry, material);
      parent.add(mesh);
      return mesh;
    }

    class MeshDraft {
      constructor(sway = false) {
        this.positions = [];
        this.colors = [];
        this.uvs = [];
        this.indices = [];
        this.sway = sway ? [] : null;
      }
      vertex(p, tint, u = 0, v = 0, bend = [0, 0, 0]) {
        const index = this.positions.length / 3;
        this.positions.push(p.x, p.y, p.z);
        this.colors.push(tint.r, tint.g, tint.b);
        this.uvs.push(u, v);
        if (this.sway) this.sway.push(bend[0], bend[1], bend[2]);
        return index;
      }
      triangle(a, b, c) { this.indices.push(a, b, c); }
      quad(a, b, c, d) { this.indices.push(a, b, d, b, c, d); }
      geometry() {
        const g = new T.BufferGeometry();
        g.setAttribute("position", new T.Float32BufferAttribute(this.positions, 3));
        g.setAttribute("color", new T.Float32BufferAttribute(this.colors, 3));
        g.setAttribute("uv", new T.Float32BufferAttribute(this.uvs, 2));
        if (this.sway) g.setAttribute("aSway", new T.Float32BufferAttribute(this.sway, 3));
        g.setIndex(this.indices);
        g.computeVertexNormals();
        g.computeBoundingSphere();
        return g;
      }
    }
    function plate(draft, points, tints) {
      const indices = points.map((p, i) => draft.vertex(p, Array.isArray(tints) ? tints[i] : tints, i % 2, i < 2 ? 0 : 1));
      for (let i = 1; i < indices.length - 1; i++) draft.triangle(indices[0], indices[i], indices[i + 1]);
    }
    function tube(draft, points, radius, tint, sides = 7, swayAt, shape) {
      const rings = [];
      const end = points.length - 1;
      const axis = points[end].clone().sub(points[0]).normalize();
      const reference = Math.abs(axis.dot(Z)) > .91 ? UP : Z;
      for (let i = 0; i <= end; i++) {
        const u = i / end;
        const tangent = points[Math.min(i + 1, end)].clone().sub(points[Math.max(i - 1, 0)]).normalize();
        const side = tangent.clone().cross(reference);
        if (side.lengthSq() < .0001) side.crossVectors(tangent, V(1, 0, 0));
        side.normalize();
        const across = tangent.clone().cross(side);
        const r = typeof radius === "function" ? radius(u) : radius;
        const ring = [];
        for (let j = 0; j < sides; j++) {
          const a = j / sides * TAU;
          const radiusScale = shape ? shape(u, a) : 1;
          const p = points[i].clone().addScaledVector(side, r * radiusScale * Math.cos(a))
            .addScaledVector(across, r * radiusScale * Math.sin(a) * (shape ? .82 : 1));
          ring.push(draft.vertex(p, typeof tint === "function" ? tint(u, a) : tint, u, j / sides, swayAt && swayAt(u)));
        }
        rings.push(ring);
        if (i === 0) continue;
        for (let j = 0; j < sides; j++) {
          const next = (j + 1) % sides;
          draft.quad(rings[i - 1][j], rings[i - 1][next], ring[next], ring[j]);
        }
      }
      for (let i = 1; i < sides - 1; i++) {
        draft.triangle(rings[0][0], rings[0][i + 1], rings[0][i]);
        draft.triangle(rings[end][0], rings[end][i], rings[end][i + 1]);
      }
    }
    function curve(points, steps) { return new T.CatmullRomCurve3(points).getPoints(steps); }
    function box(draft, x0, x1, y0, y1, z0, z1, tint) {
      const p = [
        V(x0, y0, z0), V(x1, y0, z0), V(x1, y1, z0), V(x0, y1, z0),
        V(x0, y0, z1), V(x1, y0, z1), V(x1, y1, z1), V(x0, y1, z1)
      ];
      [[0, 3, 2, 1], [4, 5, 6, 7], [0, 4, 7, 3], [1, 2, 6, 5], [0, 1, 5, 4], [3, 7, 6, 2]]
        .forEach(face => plate(draft, face.map(i => p[i]), tint));
    }

    scene.add(new T.HemisphereLight(0xb8f2e7, 0x36545e, 1.78));
    const sunlight = new T.DirectionalLight(0xffebba, 2.15);
    sunlight.position.set(11, 26, -13);
    scene.add(sunlight);
    const fill = new T.DirectionalLight(0x91d9ca, .88);
    fill.position.set(-12, 8, 15);
    scene.add(fill);

    const sky = addMesh(new T.SphereGeometry(140, 28, 14), new T.ShaderMaterial({
      side: T.BackSide, depthWrite: false, toneMapped: false,
      vertexShader: `
        varying vec3 vWorld;
        void main() {
          vWorld = (modelMatrix * vec4(position, 1.0)).xyz;
          gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
        }
      `,
      fragmentShader: waterColor + `
        varying vec3 vWorld;
        void main() {
          gl_FragColor = vec4(gardenWater(normalize(vWorld - cameraPosition)), 1.0);
          #include <colorspace_fragment>
        }
      `
    }));
    sky.renderOrder = -100;

    const ocean = new T.PlaneGeometry(206, 206, 85, 85);
    ocean.rotateX(-Math.PI / 2);
    const surface = addMesh(ocean, new T.ShaderMaterial({
      side: T.DoubleSide, toneMapped: false, uniforms: { uTime: time },
      vertexShader: `
        uniform float uTime;
        varying vec3 vWorld;
        void main() {
          vec3 p = position;
          p.y += .29 * sin(p.x * .45 + p.z * .31 + uTime * .79)
               + .15 * sin(-p.x * .73 + p.z * .48 - uTime * .74)
               + .075 * sin(p.x * 1.22 + p.z * .92 + uTime * 1.4);
          vWorld = (modelMatrix * vec4(p, 1.0)).xyz;
          gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0);
        }
      `,
      fragmentShader: waterColor + glintPattern + `
        uniform float uTime;
        varying vec3 vWorld;
        void main() {
          vec2 p = vWorld.xz;
          vec3 delta = vWorld - cameraPosition;
          vec3 ray = normalize(delta);
          float w1 = cos(p.x * .45 + p.y * .31 + uTime * .79);
          float w2 = cos(-p.x * .73 + p.y * .48 - uTime * .74);
          float w3 = cos(p.x * 1.58 + p.y * 1.07 + uTime * 1.3);
          vec3 n = normalize(vec3(-.17 * w1 + .14 * w2 - .12 * w3, 1.0, -.13 * w1 - .09 * w2 - .12 * w3));
          float angle = max(0.0, dot(n, ray));
          vec2 opening = (p - vec2(8.0, -21.0)) * vec2(.065, .045);
          float sun = exp(-dot(opening, opening));
          float foam = gardenGlints(p * 1.26, uTime * 1.2);
          float crossing = gardenGlints(p.yx * .67 + vec2(5.0, -11.0), uTime * .78);
          float spark = pow(max(0.0, dot(reflect(ray, n), normalize(vec3(.25, -.74, -.62)))), 12.0);
          vec3 skin = mix(vec3(.015, .108, .162), vec3(.095, .421, .380), sun * .78 + .18 * angle);
          skin += foam * (.12 + sun * .52) * vec3(.28, .76, .69);
          skin += crossing * (.04 + .10 * sun) * vec3(.42, .72, .58);
          skin += spark * sun * vec3(.39, .54, .33);
          float clarity = (1.0 - smoothstep(18.0, 100.0, length(delta))) * (.55 + .45 * angle);
          gl_FragColor = vec4(mix(gardenWater(ray), skin, clarity), 1.0);
          #include <colorspace_fragment>
        }
      `
    }));
    surface.position.set(0, WATER, -14);

    const beamGeometry = new T.PlaneGeometry(2, 1);
    const sunShafts = [
      [-15,-14, .36, 1.1, .11], [-10,-20, .64, 2.1, .125], [-6,-24, .36, 1.25, .19],
      [-2,-27, .55, 2.5, .115], [1,-22, .38, 1.26, .19], [3,-17, .33, 1.4, .22],
      [5,-26, .60, 2.6, .13], [7,-20, .30, 1.05, .22], [8,-29, .88, 2.9, .14],
      [11,-23, .52, 1.8, .16], [13,-17, .25, .98, .145], [16,-28, .38, 1.6, .11],
      [19,-35, 1.04, 3.2, .12], [-19,-35, .91, 2.9, .09]
    ];
    sunShafts.forEach(([x, z, w0, w1, strength], index) => {
      const beam = addMesh(beamGeometry, new T.ShaderMaterial({
        side: T.DoubleSide, transparent: true, depthWrite: false, blending: T.AdditiveBlending, toneMapped: false,
        uniforms: {
          uTime: time, uTop: { value: V(x, WATER - .13, z) }, uBase: { value: V(x - 8.5, -.2, z + 6.0) },
          uWidths: { value: new T.Vector2(w0, w1) }, uPower: { value: strength }, uPhase: { value: index * 1.83 }
        },
        vertexShader: `
          uniform vec3 uTop, uBase;
          uniform vec2 uWidths;
          uniform float uTime, uPhase;
          varying vec2 vUV;
          varying float vRange;
          void main() {
            vUV = uv;
            vec3 center = mix(uTop, uBase, uv.y);
            vec3 facing = normalize(cross(uBase - uTop, cameraPosition - center) + vec3(.0001));
            center += facing * (position.x * mix(uWidths.x, uWidths.y, uv.y)
                   + sin(uTime * .43 + uPhase + uv.y) * .26);
            vRange = distance(cameraPosition, center);
            gl_Position = projectionMatrix * viewMatrix * vec4(center, 1.0);
          }
        `,
        fragmentShader: `
          uniform float uTime, uPower, uPhase;
          varying vec2 vUV;
          varying float vRange;
          void main() {
            float x = (vUV.x - .5) * 2.0;
            float soft = exp(-x * x * 4.8) * (1.0 - smoothstep(.70, 1.0, abs(x)));
            float lengthFade = smoothstep(0.0, .09, vUV.y) * (1.0 - smoothstep(.22, 1.0, vUV.y));
            float flicker = .83 + .17 * sin(uTime * .77 + uPhase + x * 3.0 + vUV.y * 5.0);
            float distanceFade = 1.0 - smoothstep(29.0, 74.0, vRange);
            gl_FragColor = vec4(.32, .67, .53, soft * lengthFade * flicker * uPower * distanceFade);
            #include <colorspace_fragment>
          }
        `
      }));
      beam.frustumCulled = false;
      beam.renderOrder = 2;
    });

    function ground(x, z) {
      const left = ((x + 16) / 8.7) ** 2 + ((z + 3) / 14) ** 2;
      const right = ((x - 17) / 10) ** 2 + ((z + 9) / 15) ** 2;
      return -.38 + .48 * Math.sin(x * .16 + z * .108)
        + .34 * Math.cos(z * .253 - x * .105) + .17 * Math.sin(x * .47 + z * .335)
        + .105 * Math.cos(x * .73 - z * .695) + 1.23 * Math.exp(-left) + .98 * Math.exp(-right);
    }
    const sand = new T.PlaneGeometry(174, 162, 152, 144);
    sand.rotateX(-Math.PI / 2);
    sand.translate(0, 0, -15);
    const sandPoints = sand.getAttribute("position");
    const sandTint = new Float32Array(sandPoints.count * 3);
    const goldSand = color("#b59b66");
    const shadowSand = color("#63654d");
    const sandColor = new T.Color();
    for (let i = 0; i < sandPoints.count; i++) {
      const x = sandPoints.getX(i);
      const z = sandPoints.getZ(i);
      sandPoints.setY(i, ground(x, z));
      const bands = .59 + .17 * Math.sin(x * .34 + z * .16) + .13 * Math.cos(z * .47 - x * .51);
      const wreckShadow = .44 * Math.exp(-((x - 9.7) / 4.9) ** 2 - ((z + 13.2) / 5.0) ** 2);
      const forestShadow = .19 * Math.exp(-((x + 13) / 8.5) ** 2 - ((z + 9.0) / 11.0) ** 2);
      sandColor.copy(shadowSand).lerp(goldSand, clamp(bands - wreckShadow - forestShadow, .06, 1));
      sandColor.toArray(sandTint, 3 * i);
    }
    sand.setAttribute("color", new T.BufferAttribute(sandTint, 3));
    sand.computeVertexNormals();
    addMesh(sand, gardenMaterial("sand", { vertexColors: true }));

    const PLAYER = .46;
    const rockBodies = [];
    const rockRecords = [[], [], []];
    const rockTints = ["#334e48", "#4e655b", "#65715a", "#344d50", "#54685d", "#626c58", "#3b5555"];
    function rock(x, z, w, h, d, y = ground(x, z) + h * .27) {
      const rot = range(0, TAU);
      const index = Math.floor(range(0, rockRecords.length));
      rockRecords[index].push({ x, y, z, w, h, d, rot, tint: color(pick(rockTints)) });
      const padding = 1.17 + PLAYER / Math.min(w, h, d);
      rockBodies.push({
        x, y, z, c: Math.cos(rot), s: Math.sin(rot),
        rx: w * padding, ry: h * padding, rz: d * padding, reach: Math.max(w, d) * padding
      });
    }
    function buildRocks() {
      const rockMat = gardenMaterial("rock");
      rockRecords.forEach((records, index) => {
        const g = new T.IcosahedronGeometry(1, 2);
        const position = g.getAttribute("position");
        for (let i = 0; i < position.count; i++) {
          const x = position.getX(i), y = position.getY(i), z = position.getZ(i);
          const wave = 1 + .102 * Math.sin(x * 7.3 + y * 4.8 - z * 3.1 + index * 1.88)
                         + .061 * Math.sin(z * 7.1 + x * 2.1 + index);
          position.setXYZ(i, x * wave, y * wave, z * wave);
        }
        g.computeVertexNormals();
        const mesh = new T.InstancedMesh(g, rockMat, records.length);
        const pose = new T.Object3D();
        records.forEach((record, i) => {
          pose.position.set(record.x, record.y, record.z);
          pose.rotation.y = record.rot;
          pose.scale.set(record.w, record.h, record.d);
          pose.updateMatrix();
          mesh.setMatrixAt(i, pose.matrix);
          mesh.setColorAt(i, record.tint);
        });
        mesh.instanceMatrix.needsUpdate = true;
        if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
        scene.add(mesh);
      });
    }

    const capsules = [];
    function capsule(list, a, b, r) {
      const delta = b.clone().sub(a);
      list.push({ a: a.clone(), delta, inverseLength: 1 / Math.max(delta.lengthSq(), .0001), radius: (r + PLAYER) ** 2 });
    }
    function touchesCapsules(list, p) {
      for (const body of list) {
        const x = p.x - body.a.x, y = p.y - body.a.y, z = p.z - body.a.z;
        const along = clamp((x * body.delta.x + y * body.delta.y + z * body.delta.z) * body.inverseLength, 0, 1);
        if ((x - body.delta.x * along) ** 2 + (y - body.delta.y * along) ** 2 + (z - body.delta.z * along) ** 2 < body.radius) return true;
      }
      return false;
    }
    const stone = new MeshDraft();
    function rockArch(x, z, scale, angle) {
      const bottom = ground(x, z);
      const c = Math.cos(angle), s = Math.sin(angle);
      const at = (px, py, pz) => V(x + (px * c + pz * s) * scale, bottom + py * scale, z + (pz * c - px * s) * scale);
      const centerline = [
        [-5.7,-.52,.5], [-5.5,1.5,.35], [-5.02,3.7,.16], [-3.96,5.93,-.16],
        [-2.34,7.65,-.55], [-.45,8.31,-.58], [1.19,7.99,-.43], [2.91,6.81,-.15],
        [4.08,5.09,.16], [4.79,2.73,.43], [4.98,-.4,.70]
      ].map(p => at(...p));
      const path = curve(centerline, 34);
      const radius = u => scale * (1.05 + .69 * Math.pow(Math.abs(u - .5) * 2, 3) + .16 * Math.sin(u * 17 + .4));
      const dark = color("#465d54"), light = color("#7a8260");
      tube(stone, path, radius, (u, a) => dark.clone().lerp(light, .43 + .21 * Math.sin(u * 18 + a) + .14 * Math.cos(a * 3.0)), 17, null,
        (u, a) => 1 + .105 * Math.sin(u * 38 + a * 3) + .095 * Math.cos(a * 5 - u * 21));
      for (let i = 1; i < path.length; i++) {
        capsule(capsules, path[i - 1], path[i], Math.max(radius((i - 1) / 34), radius(i / 34)) * 1.21 + .07);
      }
      for (const [px, py, pz, w, h, d] of [
        [-6.25, .55, 1.01, 2.12,1.58,1.85], [5.8,.5,.13,2,1.6,1.7], [-5.9,2.65,-.33,1.22,1.79,1.3],
        [5.35,2.25,.52,1.33,1.89,1.53], [-2.59,7.66,-.33,1.22,.92,1.07], [1.1,8.06,-.43,1.28,.79,1.08],
        [-4.55,.3,2.45,1.48,.8,1.18], [5.18,.4,2.75,1.65,.76,1.15]
      ]) {
        const p = at(px, py, pz);
        rock(p.x, p.z, w * scale, h * scale, d * scale, p.y);
      }
    }
    rockArch(-8.8, -13.2, 1.02, .15);
    rockArch(20, -36.5, .78, -.75);
    rockArch(-21, -42, .68, .63);
    addMesh(stone.geometry(), colored("rock"));
    [
      [-11,3,3.8,2.8,3.7], [-8.1,4.9,2.6,1.45,2.1], [-6.6,3.5,1.85,1.05,1.31],
      [9.0,3.0,2.83,1.85,2.41], [11.6,1.4,3.1,2.8,3.1], [7.35,3.55,1.3,.64,1.09],
      [-13.8,-6,3.15,2.63,2.86], [15.9,-8.1,3.85,2.25,2.85], [15.4,-22.9,2.13,1.46,2.75],
      [-5.3,-19.2,1.26,.71,1.25], [-15.2,-27.3,3.6,2.5,3.4], [2.1,-32.8,2.9,1.75,3.1],
      [10.9,-37,3.9,3.1,3.1], [-2.8,-40,2.6,1.4,2.3], [26,-21,6,3.8,5.1], [-25,-14,4.7,4.2,4.9]
    ].forEach(args => rock(...args));
    for (let i = 0; i < 153; i++) {
      const x = range(-36, 36), z = range(-59, 24);
      const w = random() < .15 ? range(.43, 1.13) : range(.12, .51);
      rock(x, z, w, w * range(.37, .83), w * range(.63, 1.35));
    }
    buildRocks();

    const wreck = new T.Group();
    wreck.position.set(9.6, ground(9.6, -13.2) + .12, -13.2);
    wreck.rotation.set(.045, -.91, -.11, "YXZ");
    scene.add(wreck);
    const wood = new MeshDraft();
    const cloth = new MeshDraft();
    const timbers = ["#8f603e", "#a16c47", "#7b4f35", "#a77850", "#6e492f", "#985d3e", "#896044"].map(color);
    const rail = color("#a98155"), frame = color("#775138"), rope = color("#776246");
    const wreckSolids = [];
    const hull = [
      [-6.9,.51,3.73,.73], [-6.3,1.89,4.07,.50], [-5.2,2.62,4.14,.31], [-3.5,2.95,3.95,.24],
      [-1.4,3.13,3.77,.20], [.8,3.10,3.65,.20], [2.85,2.87,3.75,.29], [4.6,2.34,3.99,.44],
      [5.85,1.54,4.34,.80], [6.78,.66,4.84,1.26], [7.3,.07,5.28,1.97]
    ];
    function section(z) {
      const value = clamp(z, hull[0][0], hull[hull.length - 1][0]);
      for (let i = 1; i < hull.length; i++) {
        const a = hull[i - 1], b = hull[i];
        if (value <= b[0]) {
          const f = (value - a[0]) / (b[0] - a[0]);
          return [mix(a[1], b[1], f), mix(a[2], b[2], f), mix(a[3], b[3], f)];
        }
      }
      return hull[hull.length - 1].slice(1);
    }
    function hullPoint(z, height, side) {
      const [width, edge, keel] = section(z);
      const taper = Math.pow(Math.sin(height * Math.PI * .5), .79);
      return V(side * (width * (.04 + .96 * taper)), mix(keel, edge, height), z);
    }
    for (const side of [-1, 1]) {
      for (let row = 0; row < 11; row++) {
        for (let span = 0; span < hull.length - 1; span++) {
          const starboardGap = side === 1 && ((span === 4 && row >= 7) || (span === 3 && row === 9) || (span === 5 && row === 8) || (span === 1 && row === 10));
          const portGap = side === -1 && ((span === 2 && row >= 8) || (span === 5 && row > 8));
          if (starboardGap || portGap) continue;
          const z0 = hull[span][0] + .02, z1 = hull[span + 1][0] - .02;
          const t0 = row / 11 + .004, t1 = (row + 1) / 11 - .004;
          const tint = pick(timbers);
          for (let part = 0; part < 3; part++) {
            const a = mix(z0, z1, part / 3), b = mix(z0, z1, (part + 1) / 3);
            wood.quad(wood.vertex(hullPoint(a,t0,side), tint, part/3, 0),
              wood.vertex(hullPoint(b,t0,side), tint, (part+1)/3, 0),
              wood.vertex(hullPoint(b,t1,side), tint, (part+1)/3, 1),
              wood.vertex(hullPoint(a,t1,side), tint, part/3, 1));
          }
        }
      }
      for (const part of [[-6.75, -1.56], [.88, 7.29]]) {
        const points = Array.from({length: 17}, (_, i) => hullPoint(mix(part[0], part[1], i / 16), .992, side));
        tube(wood, points, .144, rail, 6);
        for (let i = 1; i < points.length; i++) capsule(wreckSolids, points[i-1], points[i], .16);
      }
      for (let index = 1; index < hull.length - 1; index++) {
        const z = hull[index][0];
        const points = Array.from({length: 8}, (_, i) => {
          const p = hullPoint(z, .17 + i * .83 / 7, side);
          p.x -= side * .112;
          return p;
        });
        if (index === 4 || index === 5) points.push(points[7].clone().add(V(-side * .1, .28, .06)));
        tube(wood, points, .121, frame, 6);
      }
    }
    for (let lane = -6; lane <= 6; lane++) {
      const x0 = lane * .42 - .20, x1 = x0 + .39;
      for (let i = 0; i < 8; i++) {
        const z0 = -6.55 + i * 1.65, z1 = z0 + 1.61;
        if ((i === 3 && lane >= -2) || (i === 4 && lane >= 0) || (i === 2 && lane === 2)) continue;
        if (Math.max(Math.abs(x0), Math.abs(x1)) > Math.min(section(z0)[0], section(z1)[0]) - .21) continue;
        const lo = section(z0)[1] - .31, hi = section(z1)[1] - .31;
        plate(wood, [V(x0,lo,z0), V(x0,hi,z1), V(x1,hi,z1), V(x1,lo,z0)], pick(timbers));
      }
    }
    const prow = curve([V(0,1.11,6.36), V(0,2.32,7.01), V(0,4.02,7.27), V(0,5.32,7.30)], 11);
    tube(wood, prow, .18, rail, 8);
    for (let i = 1; i < prow.length; i++) capsule(wreckSolids, prow[i-1], prow[i], .19);
    for (let i = 0; i < 9; i++) {
      const y = 1.02 + .335 * i;
      const w = .77 + i * .112;
      box(wood, -w, w, y, y + .305, -6.70, -6.47, pick(timbers));
    }
    for (const side of [-1, 1]) {
      for (const z of [-6, -5.15, -4.31]) {
        const base = hullPoint(z, .963, side);
        const top = base.clone().add(V(-side*.10, .75, -.07));
        tube(wood, [base, top], .085, frame, 6);
        capsule(wreckSolids, base, top, .10);
      }
      const a = hullPoint(-6.04,.968,side).add(V(-side*.10,.72,-.06));
      const b = hullPoint(-4.29,.968,side).add(V(-side*.10,.79,-.06));
      tube(wood, [a,b], .087, rail, 6);
      capsule(wreckSolids, a, b, .10);
    }
    for (const x of [-1.43, 1.43]) {
      for (const z of [-5.73, -3.57]) box(wood, x-.12, x+.12, 3.68, 5.37, z-.12, z+.12, frame);
      for (let i = 0; i < 5; i++) {
        const y = 3.78 + i * .26;
        if (i < 2 || i === 4) box(wood, x-.045, x+.045, y, y+.23, -5.68, -3.55, pick(timbers));
        else {
          box(wood, x-.045, x+.045, y, y+.235, -5.68, -5.21, pick(timbers));
          box(wood, x-.045, x+.045, y, y+.235, -4.47, -3.55, pick(timbers));
        }
      }
    }
    for (let i = 0; i < 8; i++) {
      if (i === 3 || i === 4) continue;
      const x = -1.57 + i * .39;
      box(wood, x, x+.363, 5.24, 5.36, -5.91, -3.42 + (i % 3) * .11, pick(timbers));
    }
    const mastFoot = V(.12, 3.04, .65), mastHead = V(-.83, 10.44, -.64);
    tube(wood, [mastFoot, mastHead], u => mix(.235, .114, u), rail, 9);
    capsule(wreckSolids, mastFoot, mastHead, .26);
    const yardA = V(-3.42, 8.79, -.31), yardB = V(1.94, 8.11, -.96);
    tube(wood, [yardA, yardB], u => .09 + .055 * Math.sin(u * Math.PI), frame, 7);
    capsule(wreckSolids, yardA, yardB, .15);
    const foreStub = [V(.34,3.46,4.56), V(.78,6.26,4.96), V(.69,6.53,5.04)];
    tube(wood, foreStub, u => mix(.16, .077, u), frame, 8);
    capsule(wreckSolids, foreStub[0], foreStub[2], .20);
    function rig(a, b, sag) {
      const mid = a.clone().lerp(b, .52).add(V(.06, -sag, .09));
      const points = curve([a, mid, b], 10);
      tube(wood, points, .03, rope, 5);
      for (let i = 1; i < points.length; i++) capsule(wreckSolids, points[i - 1], points[i], .045);
    }
    rig(mastHead, V(0,5.23,7.25), .65);
    rig(mastHead, V(1.55,4.6,-5.58), .73);
    rig(mastHead, V(-1.55,4.6,-5.58), .76);
    rig(yardB, V(2.46,3.79,1.91), .50);
    rig(yardA, V(-2.28,3.87,2.59), .60);
    const sail = color("#aa8457"), hem = color("#73573b");
    plate(cloth, [V(-2.91,8.68,-.34), V(-2.07,8.57,-.46), V(-1.20,8.50,-.54),
      V(-1.39,7.65,-.38), V(-1.82,7.49,-.27), V(-1.88,6.88,-.10), V(-2.28,7.12,-.18),
      V(-2.42,7.64,-.24), V(-2.83,7.35,-.13)], [sail, sail, sail, hem, sail, hem, hem, sail, hem]);
    plate(cloth, [V(.27,8.32,-.72), V(1.56,8.14,-.88), V(1.16,7.62,-.64),
      V(.91,7.89,-.66), V(.63,7.16,-.45), V(.41,7.63,-.59)], [sail,sail,hem,sail,hem,hem]);
    addMesh(wood.geometry(), colored("wood"), wreck);
    addMesh(cloth.geometry(), colored("plain"), wreck);
    wreck.updateMatrixWorld(true);
    const wreckInverse = wreck.matrixWorld.clone().invert();

    const kelp = new MeshDraft(true);
    const stemGreen = color("#476744");
    const leafColors = [
      ["#284d32", "#7a953d"], ["#306140", "#81a54b"], ["#465e32", "#a3a246"],
      ["#215542", "#759852"], ["#405b31", "#a49740"], ["#265b45", "#5a8b52"]
    ].map(pair => pair.map(color));
    function blade(root, azimuth, length, width, lift, phase, low, high, bend, grass = false) {
      const dx = Math.cos(azimuth), dz = Math.sin(azimuth);
      const steps = grass ? 7 : 11;
      let previous;
      for (let i = 0; i <= steps; i++) {
        const u = i / steps;
        const curl = length * (.18 * Math.sin(Math.PI * u) + .12 * u * u) * Math.sin(phase);
        const cx = root.x + dx * length * u - dz * curl;
        const cz = root.z + dz * length * u + dx * curl;
        const cy = root.y + length * (lift * u + .26 * Math.sin(Math.PI * u) - (grass ? 0 : .21) * u * u);
        const twist = .46 * Math.sin(phase) + .63 * Math.sin(u * 4.6 + phase * .61);
        const profile = Math.max(.023, Math.pow(Math.sin(Math.PI * u), grass ? .8 : .72));
        const fringe = 1 + .15 * Math.sin(u * 36 + phase) + .07 * Math.cos(71 * u + phase);
        const tint = low.clone().lerp(high, .17 + .67 * u + .12 * Math.sin(u * 3.6 + phase));
        const next = [];
        for (let s = -1; s <= 1; s++) {
          const offset = width * profile * fringe * s;
          const p = V(cx - dz * offset * Math.cos(twist), cy + offset * Math.sin(twist) + (1 - Math.abs(s)) * width * .22 * profile,
            cz + dx * offset * Math.cos(twist));
          const edge = tint.clone().multiplyScalar(s === 0 ? 1.11 : .88 + .08 * s);
          next.push(kelp.vertex(p, edge, u, (s + 1) * .5, [bend[0], bend[1], u * bend[2]]));
        }
        if (previous) {
          kelp.quad(previous[0], previous[1], next[1], next[0]);
          kelp.quad(previous[1], previous[2], next[2], next[1]);
        }
        previous = next;
      }
    }
    function kelpPlant(x, z, height) {
      const base = ground(x, z) - .07;
      height = Math.min(height, WATER - base - .55);
      const phase = range(0, TAU), lean = range(.32, 1.52);
      const [low, high] = pick(leafColors);
      const stem = f => V(x + (Math.sin(f * 4 + phase) - Math.sin(phase)) * f * lean + .55 * f,
        base + height * f, z + Math.cos(f * 4.6 + phase) * f * lean);
      const nodes = Array.from({length: 16}, (_, i) => stem(i / 15));
      tube(kelp, nodes, u => mix(.084, .019, u) * clamp(height / 11, .63, 1.2),
        u => stemGreen.clone().lerp(high, u * .52), 6, u => [phase, u, 0]);
      const leafCount = Math.round(range(12, 17) * clamp(height / 12, .66, 1.2));
      for (let i = 0; i < leafCount; i++) {
        const f = .16 + .79 * (i + range(-.23, .23)) / (leafCount - 1);
        const a = phase + i * 2.34 + range(-.46,.46);
        const length = range(1.38, 3.41) * (1.16 - f * .42) * clamp(height / 11.5, .64, 1.21);
        blade(stem(f), a, length, range(.17, .46) * (.94 + .12*f), range(.11, .69),
          phase + i * .61, low, high, [phase, f, 1]);
      }
      blade(stem(.91), phase + .6, range(.68, 1.24), .19, .85, phase, low, high, [phase,.98,.74]);
    }
    [
      [-6.45,5.9,13.7], [-7.54,3.65,15.5], [-9.62,4.35,15.2], [-11.3,2.6,11.1], [-7.18,1.1,12.1],
      [-9.1,-.55,15.8], [-6.4,-2.4,13.3], [-11.7,-2.8,14.5], [-14.3,-1.3,15.8], [-11.8,-7.9,14.4],
      [-13.9,-12,15.7], [-16.7,-15,13.3], [-3.9,-11.2,10.4], [-15.3,-15.5,13.6],
      [7.75,5.9,13.6], [8.8,3.1,16.3], [10.2,3.9,13.8], [12.2,1.8,14.9], [7.45,-.47,11.9],
      [9,-1.7,15.3], [12.8,-3.5,16], [15.4,-8,14.5], [17.3,-12.1,13.1], [10.9,-22.9,14.2],
      [13.1,-23.7,13.5], [6.4,-22.4,11.3], [-6.2,-23.7,10.8], [-9.5,-26.1,13.9]
    ].forEach(args => kelpPlant(...args));
    for (let i = 0; i < 75; i++) {
      const sign = i % 2 ? -1 : 1;
      const x = sign * range(9.4, 39);
      const z = range(-62, -4);
      if (sign > 0 && x < 15.8 && z > -19 && z < -8) continue;
      kelpPlant(x, z, range(6.9, 15.6));
    }
    const grassPatches = [[-5.65,3.5], [6.3,3.25], [-6.7,-1], [7,-4.4], [-13.6,-13], [-4.1,-14], [13.5,-14.1], [-4.6,-22.2], [3.1,-29]];
    for (const [px, pz] of grassPatches) {
      for (let i = 0; i < 7; i++) {
        const x = px + range(-1.2, 1.2), z = pz + range(-1.3,1.3);
        const p = V(x, ground(x,z), z);
        const [lo, hi] = pick(leafColors);
        for (let j = 0; j < 6; j++) {
          blade(p, range(0,TAU), range(.25,.89), range(.025,.075), range(.77,1.64), range(0,TAU), lo, hi, [1,.26,.57], true);
        }
      }
    }
    const kelpMesh = addMesh(kelp.geometry(), colored("kelp"));
    kelpMesh.frustumCulled = false;

    const coral = new MeshDraft();
    const coralPalettes = [
      ["#863e2a", "#d27943", "#f0ba70"], ["#8f592c", "#cb9748", "#f2ce82"],
      ["#994630", "#db8051", "#f4bb80"], ["#614d32", "#9b914b", "#d5be72"]
    ].map(palette => palette.map(color));
    function branchCoral(x, z, scale, paletteIndex, raised) {
      const [low, middle, tip] = coralPalettes[paletteIndex];
      const root = V(x, raised === undefined ? ground(x,z)-.04 : raised, z);
      const count = Math.round(range(6,10));
      const phase = range(0,TAU);
      for (let i = 0; i < count; i++) {
        const a = phase + i * 2.39;
        const h = range(.63,1.48) * scale;
        const spread = range(.25,.79) * scale;
        const lean = V(Math.cos(a)*spread,0,Math.sin(a)*spread);
        const points = curve([root.clone().addScaledVector(lean,.12),
          root.clone().addScaledVector(lean,.53).add(V(0,h*.38,0)),
          root.clone().addScaledVector(lean,.92).add(V(0,h*.71,0)),
          root.clone().add(lean).add(V(0,h,0))], 7);
        const blend = u => u < .78 ? low.clone().lerp(middle, u / .78) : middle.clone().lerp(tip, (u-.78)/.22);
        tube(coral, points, u => scale * mix(.114,.028,u), blend, 7);
        for (let j = 0; j < 3; j++) {
          const base = points[3 + j];
          const b = a + (j % 2 ? -1 : 1) * range(.55,1.22);
          const l = scale * range(.24,.49);
          const end = base.clone().add(V(Math.cos(b)*l, l*range(.63,1.26), Math.sin(b)*l));
          const elbow = base.clone().lerp(end,.57).add(V(Math.cos(b)*l*.17,-.026,Math.sin(b)*l*.17));
          tube(coral, [base, elbow, end], u => scale * mix(.057,.016,u), u => middle.clone().lerp(tip,u*.89), 6);
        }
      }
    }
    function seaFan(x, z, scale, angle) {
      const baseY = ground(x,z) - .03;
      const at = (a, r) => {
        const f = Math.sin(a) * r * scale;
        return V(x + f * Math.cos(angle), baseY + Math.cos(a) * r * scale * 1.25,
          z + f * Math.sin(angle) + .18 * r * r * scale);
      };
      const first = color("#a45a32"), last = color("#dba95f");
      const ribs = [];
      for (let i = 0; i < 11; i++) {
        const a = mix(-1.17,1.17,i/10);
        const end = range(.82,1.12);
        const rib = Array.from({length: 9}, (_, j) => at(a + .11 * Math.sin(j*.38+i), end * j / 8));
        ribs.push(rib);
        tube(coral, rib, u => scale * mix(.046,.010,u), u => first.clone().lerp(last,u), 5);
        if (i < 1) continue;
        for (let k = 3; k <= 7; k++) {
          const p = rib[k], q = ribs[i-1][k + (k % 2)];
          const mid = p.clone().lerp(q,.49).add(V(0,-scale*.053,scale*.016));
          tube(coral, [p,mid,q], scale*.010, first.clone().lerp(last,k/8), 4);
        }
      }
    }
    function tubeSponges(x, z, size) {
      const low = color("#834c27"), bright = color("#cc913e"), inner = color("#63412b");
      for (let i = 0; i < 7; i++) {
        const px = x + range(-.49,.49)*size, pz = z + range(-.46,.46)*size;
        const y = ground(px,pz) - .06;
        const h = range(.38,1.14)*size, r = range(.10,.22)*size;
        const dx = range(-.24,.24)*size, dz = range(-.22,.22)*size;
        const ringSpecs = [[0,.85,low],[.43,.83,low],[.82,1.13,bright],[1,1.15,bright],[1,.70,bright],[.64,.66,inner],[.61,.035,inner]];
        let old;
        ringSpecs.forEach(([f,width,tint]) => {
          const next = [];
          for (let k = 0; k < 12; k++) {
            const a = k / 12 * TAU;
            const w = r * width * (1 + .075 * Math.sin(a*5+i));
            next.push(coral.vertex(V(px+f*dx+Math.cos(a)*w, y+f*h+.035*size*Math.sin(a+i)*f, pz+f*dz+Math.sin(a)*w), tint, f, k/12));
          }
          if (old) for (let k = 0; k < 12; k++) coral.quad(old[k], old[(k+1)%12], next[(k+1)%12], next[k]);
          old = next;
        });
      }
    }
    [
      [-5.67,4.0,1.14,0], [-7.05,4.7,1.13,1], [-5.56,1.67,.90,2], [-8.91,2.6,1.05,3], [-4.13,-.25,.65,1],
      [7.18,4.33,1.48,2], [6.5,3.66,.91,0], [7.48,1.19,1.06,1], [8.91,-.65,1.26,0], [5.84,-4.03,.73,1],
      [-4.33,-11.91,1.16,1], [-12.9,-10.75,1.22,0], [-14.43,-13.92,1.06,2], [12.3,-9.8,1.03,3],
      [15.7,-18.2,1.39,0], [-6.4,-21.3,1.04,1], [3.5,-20.4,.92,2], [5.58,-26.6,1.02,0],
      [-19.8,-31,1.38,1], [-3.41,-33.9,1.18,3], [15,-32.7,1.18,0]
    ].forEach(args => branchCoral(...args));
    branchCoral(-6.25,-12.05,.64,1,ground(-8.8,-13.2)+3.7);
    branchCoral(-11.3,-12.85,.59,2,ground(-8.8,-13.2)+7.95);
    for (const args of [[-7.03,5.04,1.5,-.25], [7.25,3.25,1.5,.23], [5.8,2.12,1.03,-.36], [-5.32,-2.64,.94,.23],
      [-12.68,-11.7,1.02,-.35], [-3.82,-12.8,.96,.16], [12.35,-9.97,1.16,.65], [18.03,-23,1.2,-.23]]) seaFan(...args);
    for (const args of [[-5.77,3.94,1.16], [-6.56,1.83,.83], [6.76,3.47,1.23], [8.6,1.35,1.1], [5.19,-5.02,.66],
      [-4.7,-10.62,1.04], [-13.7,-11.53,1.15], [12.5,-8.9,.92], [16.5,-17.5,1.04], [-6.31,-20.3,.86]]) tubeSponges(...args);
    addMesh(coral.geometry(), colored("plain"));

    function fishShape() {
      const body = new MeshDraft();
      const gold = color("#c7a358"), back = color("#53785f"), belly = color("#dcc890");
      const fin = color("#ac884a"), ink = color("#153f49");
      const crossSections = [[-.47,.017,.036],[-.30,.058,.088],[-.11,.113,.171],[.09,.133,.165],[.24,.109,.113],[.37,.051,.065],[.43,.013,.025]];
      let previous;
      for (const [z,w,h] of crossSections) {
        const next = [];
        for (let i = 0; i < 12; i++) {
          const a = i / 12 * TAU, y = Math.sin(a);
          const tint = gold.clone().lerp(y > 0 ? back : belly, Math.abs(y)*.86);
          const band = .89 + .11 * Math.cos(21*z + y*.5);
          next.push(body.vertex(V(w*Math.cos(a), h*y, z), tint.multiplyScalar(band), z+.5, i/12));
        }
        if (previous) for (let i = 0; i < 12; i++) body.quad(previous[i],previous[(i+1)%12],next[(i+1)%12],next[i]);
        previous = next;
      }
      plate(body, [V(0,0,-.44), V(0,.189,-.76), V(0,.035,-.65), V(0,-.168,-.76)], [gold,fin,gold,fin]);
      plate(body, [V(0,.11,-.28), V(0,.246,-.17), V(0,.145,.12)], [fin,gold,back]);
      for (const side of [-1,1]) {
        plate(body, [V(side*.092,-.02,.134), V(side*.182,-.089,-.12), V(side*.119,-.075,-.087)], [gold,fin,fin]);
        const ring = Array.from({length: 9}, (_, i) => V(side*.109, .046 + Math.cos(i/9*TAU)*.023, .258 + Math.sin(i/9*TAU)*.023));
        plate(body, ring, ink);
        plate(body, [V(side*.110,.057,.259),V(side*.110,.047,.272),V(side*.110,.063,.274)], belly);
      }
      return body.geometry();
    }
    const fishGeometry = fishShape();
    const tailPhases = Float32Array.from({length: 47}, () => range(0,TAU));
    fishGeometry.setAttribute("aSchoolPhase", new T.InstancedBufferAttribute(tailPhases, 1));
    const fishMat = colored("fish", { roughness: .55, emissive: 0x8a7c4f, emissiveIntensity: .12 });
    const fishPacks = [
      {count:39, x:-4.7,y:5.4,z:-10.1, ax:5.7,ay:.68,az:5.08, phase:.31, rate:.217, width:3.7,size:.78,tint:"#fde1a1"},
      {count:33, x:10.9,y:7.38,z:-20.4, ax:7.7,ay:1.0,az:5.62, phase:-.49, rate:-.204, width:4.2,size:.76,tint:"#c0d5ad"},
      {count:46, x:-13.1,y:5.6,z:-29, ax:7.1,ay:1.63,az:6.0, phase:1.84, rate:.17, width:4.5,size:.81,tint:"#c5d9ab"},
      {count:24, x:2.4,y:3.4,z:-4.8, ax:5.1,ay:.65,az:4.5, phase:2.74, rate:.246, width:2.7,size:.56,tint:"#a0c9ad"}
    ].map(pack => {
      const mesh = new T.InstancedMesh(fishGeometry, fishMat, pack.count);
      mesh.instanceMatrix.setUsage(T.DynamicDrawUsage);
      mesh.frustumCulled = false;
      scene.add(mesh);
      const slots = [];
      for (let i = 0; i < pack.count; i++) {
        const a = range(0,TAU), r = Math.sqrt(random());
        slots.push({ x:r*pack.width*Math.cos(a), y:r*1.24*Math.sin(a), z:range(-3.3,3.3),
          phase:range(0,TAU), scale:pack.size*range(.70,1.27) });
        mesh.setColorAt(i, color(pack.tint).multiplyScalar(range(.75,1.13)));
      }
      return { ...pack, mesh, slots };
    });
    const fishPose = new T.Object3D();
    const fishBasis = new T.Matrix4();
    const heading = V(0,0,-1), sideHeading = V(1,0,0), schoolCenter = V(0,0,0), direction = V(0,0,0);
    function updateFish(t) {
      for (const pack of fishPacks) {
        const a = pack.phase + t * pack.rate;
        schoolCenter.set(pack.x + pack.ax*Math.sin(a), pack.y + pack.ay*Math.sin(a*2.1), pack.z + pack.az*Math.cos(a));
        heading.set(pack.ax*Math.cos(a)*pack.rate, pack.ay*2.1*Math.cos(a*2.1)*pack.rate, -pack.az*Math.sin(a)*pack.rate).normalize();
        sideHeading.crossVectors(UP, heading).normalize();
        pack.slots.forEach((slot, i) => {
          const sway = t * 1.28 + slot.phase;
          fishPose.position.copy(schoolCenter).addScaledVector(sideHeading, slot.x + .22*Math.sin(sway))
            .addScaledVector(heading, slot.z + .28*Math.cos(sway));
          fishPose.position.y += slot.y + .14 * Math.sin(sway*1.43);
          direction.copy(heading).addScaledVector(sideHeading, .118*Math.cos(sway));
          direction.y += .065 * Math.cos(sway * 1.36);
          fishBasis.lookAt(direction, ORIGIN, UP);
          fishPose.quaternion.setFromRotationMatrix(fishBasis);
          fishPose.scale.setScalar(slot.scale);
          fishPose.updateMatrix();
          pack.mesh.setMatrixAt(i, fishPose.matrix);
        });
        pack.mesh.instanceMatrix.needsUpdate = true;
      }
    }

    function mantaShape() {
      const draft = new MeshDraft();
      const dark = color("#275858"), bright = color("#4c8880"), underside = color("#87b5a1"), rim = color("#a39763");
      for (const side of [1,-1]) {
        let old;
        for (let i = 0; i <= 36; i++) {
          const x = (i/18 - 1) * 3.3;
          const w = Math.abs(x)/3.3;
          const front = 1.19 - .54*w - 1.39*w**2.73;
          const backEdge = -1.38 + .99*Math.sin(w*1.5) - .39*w;
          const next = [];
          for (let j = 0; j <= 12; j++) {
            const f = j/12;
            const body = Math.sin(Math.PI*f) ** .79 * (1 - w)**1.53;
            const y = .13 * w*w + body * (side === 1 ? .33 : -.21);
            const tint = side === 1 ? dark.clone().lerp(bright, .17+.62*w) : underside.clone().lerp(bright, .04+.56*w);
            tint.lerp(rim, (j <= 1 || j === 12) ? (.16 + .42*w) : 0);
            next.push(draft.vertex(V(x,y,mix(front,backEdge,f)), tint, w, f));
          }
          if (old) for (let j = 0; j < 12; j++) {
            if (side > 0) draft.quad(old[j],next[j],next[j+1],old[j+1]);
            else draft.quad(old[j],old[j+1],next[j+1],next[j]);
          }
          old = next;
        }
      }
      const tail = curve([V(0,.008,-.93),V(0,.03,-1.65),V(.06,-.058,-2.38),V(-.10,-.11,-3.55)], 12);
      tube(draft, tail, u => mix(.089,.009,u), dark, 7);
      for (const side of [-1,1]) {
        const lobe = curve([V(side*.30,.015,.98), V(side*.41,-.025,1.24), V(side*.37,-.12,1.58), V(side*.25,-.15,1.62)], 7);
        tube(draft, lobe, u => mix(.105,.051,u), u => dark.clone().lerp(rim,u*.32), 7);
      }
      return draft.geometry();
    }
    const mantaGeometry = mantaShape();
    const rays = [
      {x:3, y:10.8, z:-20, ax:6, az:8, rate:.185, offset:.36, phase:.62, size:1.02},
      {x:-13, y:11.55, z:-32, ax:9, az:8, rate:-.128, offset:1.17, phase:2.19, size:.87},
      {x:15, y:8.85, z:-31, ax:7.2, az:6.3, rate:.119, offset:2.92, phase:3.85, size:.70}
    ].map((data, i) => ({ ...data, mesh: addMesh(mantaGeometry, gardenMaterial("ray", {
      vertexColors: true, side: T.DoubleSide, roughness: .66, emissive: 0x377973, emissiveIntensity: .11
    }, i*1.83)) }));
    function updateRays(t) {
      for (const ray of rays) {
        const a = ray.offset + t * ray.rate;
        const b = ray.phase + a * 1.14;
        ray.mesh.position.set(ray.x + ray.ax*Math.sin(a), ray.y + .63*Math.sin(ray.phase+t*.31), ray.z + ray.az*Math.sin(b));
        direction.set(ray.ax*Math.cos(a)*ray.rate, .10*Math.cos(ray.phase+t*.31), ray.az*Math.cos(b)*ray.rate*1.14);
        fishBasis.lookAt(direction, ORIGIN, UP);
        ray.mesh.quaternion.setFromRotationMatrix(fishBasis);
        ray.mesh.rotateZ(.11*Math.sin(a+.58));
        ray.mesh.scale.setScalar(ray.size);
      }
    }

    function suspended(bubbles) {
      const g = new T.BufferGeometry();
      const positions = [], particles = [];
      const vents = [[-5.85,4.6],[5.81,2.7],[-7.91,-11.5],[8.75,-12.0],[13,-17.3],[-4.1,-24.9],[3.9,-34.2]];
      const count = bubbles ? 149 : 1220;
      for (let i = 0; i < count; i++) {
        if (bubbles) {
          const [px,pz] = vents[i % vents.length];
          const x = px + range(-.77,.77), z = pz + range(-.80,.80);
          positions.push(x, ground(x,z)+.37, z);
          particles.push(range(.12,.31),random(),range(.52,1.29));
        } else {
          positions.push(range(-48,48),range(.7,16.8),range(-75,29));
          particles.push(range(.036,.106),random(),range(.66,1.25));
        }
      }
      g.setAttribute("position", new T.Float32BufferAttribute(positions,3));
      g.setAttribute("aParticle", new T.Float32BufferAttribute(particles,3));
      const points = new T.Points(g, new T.ShaderMaterial({
        transparent: true, depthWrite: false, toneMapped: false, uniforms: { uTime: time, uRatio: pointRatio },
        defines: bubbles ? { GARDEN_BUBBLES: 1 } : {},
        vertexShader: `
          uniform float uTime, uRatio;
          attribute vec3 aParticle;
          varying float vFade, vSeed;
          void main() {
            vec3 p = position;
            float phase = aParticle.y * 6.283185;
            float alive = 1.0;
            #ifdef GARDEN_BUBBLES
              float rise = fract(aParticle.y + uTime * .064 * aParticle.z);
              p.y = mix(p.y, 16.88, rise);
              p.x += .30 * sin(uTime * .85 + phase + rise * 4.6);
              p.z += .19 * cos(uTime * 1.02 + phase + rise * 6.4);
              alive = smoothstep(0.0,.06,rise) * (1.0 - smoothstep(.88,1.0,rise));
            #else
              p.x += sin(phase + uTime*.33 + p.y*.21) * .63;
              p.z += cos(phase + uTime*.27) * .51;
              p.y += sin(phase + uTime*.47) * .28;
            #endif
            vec4 eye = viewMatrix * vec4(p,1.0);
            float distanceToEye = length(eye.xyz);
            vFade = alive * smoothstep(.40,1.45,distanceToEye) * (1.0 - smoothstep(22.0,65.0,distanceToEye));
            vSeed = aParticle.y;
            gl_PointSize = clamp(aParticle.x * 540.0 * uRatio / max(1.0,-eye.z), 1.0, 31.0 * uRatio);
            gl_Position = projectionMatrix * eye;
          }
        `,
        fragmentShader: `
          varying float vFade, vSeed;
          void main() {
            vec2 p = gl_PointCoord - .5;
            float rho = length(p);
            if (rho > .49) discard;
            #ifdef GARDEN_BUBBLES
              float ring = smoothstep(.27,.42,rho) * (1.0 - smoothstep(.43,.49,rho));
              float glint = 1.0 - smoothstep(.048,.145,length(p-vec2(-.18,-.21)));
              float rimLight = .35 + .38 * clamp(.8 - p.x - p.y,0.0,1.0);
              gl_FragColor = vec4(mix(vec3(.30,.70,.65),vec3(.69,.90,.78),glint), vFade * (ring*rimLight + glint*.77 + .032));
            #else
              float speck = 1.0 - smoothstep(.08,.49,rho);
              gl_FragColor = vec4(mix(vec3(.27,.59,.53),vec3(.63,.67,.39),vSeed), speck * vFade * (.18+.43*vSeed));
            #endif
            #include <colorspace_fragment>
          }
        `
      }));
      points.frustumCulled = false;
      points.renderOrder = bubbles ? 4 : 3;
      scene.add(points);
    }
    suspended(false);
    suspended(true);

    const swimmer = V(.8, 6.65, 14.5);
    const trial = V(0,0,0), local = V(0,0,0), movement = V(0,0,0);
    function clear(p) {
      if (p.y < ground(p.x,p.z) + .73 || p.y > WATER - .86 || p.x < -45 || p.x > 45 || p.z < -65 || p.z > 33) return false;
      for (const rock of rockBodies) {
        const x = p.x - rock.x, y = p.y - rock.y, z = p.z - rock.z;
        if (Math.abs(x) > rock.reach || Math.abs(z) > rock.reach || Math.abs(y) > rock.ry) continue;
        const u = (x * rock.c - z * rock.s) / rock.rx;
        const v = (x * rock.s + z * rock.c) / rock.rz;
        if (u*u + (y/rock.ry)**2 + v*v < 1) return false;
      }
      if (touchesCapsules(capsules, p)) return false;
      local.copy(p).applyMatrix4(wreckInverse);
      if (local.z > -7.47 && local.z < 7.89 && Math.abs(local.x) < 3.87 && local.y < 6) {
        const a = section(local.z);
        const b = section(local.z-.49);
        const c = section(local.z+.49);
        const halfWidth = Math.max(a[0],b[0],c[0]) + .53;
        if (Math.abs(local.x) < halfWidth && local.y > -.76 && local.y < Math.max(a[1],b[1],c[1]) + .55) return false;
      }
      if (Math.abs(local.x) < 2.07 && local.y > 3.23 && local.y < 5.86 && local.z > -6.39 && local.z < -2.98) return false;
      if (local.x > -3.4 && local.x < 2.05 && local.y > 6.38 && local.y < 9.19 && local.z > -1.45 && local.z < .37) return false;
      return !touchesCapsules(wreckSolids, local);
    }
    function swim(dx, dy, dz) {
      const steps = Math.max(1, Math.ceil(Math.hypot(dx,dy,dz)/.15));
      const x = dx/steps, y = dy/steps, z = dz/steps;
      for (let i = 0; i < steps; i++) {
        trial.set(swimmer.x+x, swimmer.y+y, swimmer.z+z);
        if (clear(trial)) { swimmer.copy(trial); continue; }
        trial.copy(swimmer); trial.y += y;
        if (clear(trial)) swimmer.y = trial.y;
        trial.copy(swimmer); trial.x += x;
        if (clear(trial)) swimmer.x = trial.x;
        trial.copy(swimmer); trial.z += z;
        if (clear(trial)) swimmer.z = trial.z;
      }
    }

    const route = new T.CatmullRomCurve3([
      [.8,6.65,14.5], [.2,6.1,7.7], [-1.95,4.7,.2], [-5.9,4.3,-8.7], [-8.1,4.55,-13.7],
      [-6.7,5.4,-19.3], [-.6,6.1,-19.4], [3.9,7.55,-14.4], [4.3,7.9,-8.1], [5.1,9,.9], [3.4,7.8,9.4]
    ].map(p => V(...p)), true, "centripetal");
    route.arcLengthDivisions = 460;
    const sights = [
      [0,2.1,3.9,-24], [.12,-7.9,6.3,-13.9], [.24,-8.55,5.8,-15.2], [.32,-8.33,4.96,-18.9],
      [.40,-6.0,7,-29.1], [.53,9.2,4.6,-13.9], [.65,10.8,4.35,-11.9], [.74,8,6.1,-14.3],
      [.85,.9,12.8,-24.6], [.93,-2.1,9.4,-23.5], [1,2.1,3.9,-24]
    ];
    const routePoint = V(0,0,0), sight = V(0,0,0);
    const clock = { t: 0, previous: performance.now() };
    const aim = V(0,0,-1);
    let yaw = .034, pitch = -.071, desiredYaw = yaw, desiredPitch = pitch;
    let touring = false, tourTime = 0, pointer = null, pointerX = 0, pointerY = 0, speed = 0, buttonCanceledTour = false;
    let width = 1, height = 1, lastHud = -1;

    const compass = byId("compass");
    const compassTicks = Array.from({length: 24}, (_, i) => {
      const tick = document.createElement("i");
      if (i % 3 === 0) {
        tick.className = "cardinal";
        const caption = document.createElement("span");
        caption.textContent = ["N","NE","E","SE","S","SW","W","NW"][i/3];
        tick.appendChild(caption);
      }
      compass.appendChild(tick);
      return tick;
    });
    const mapCanvas = byId("map");
    const mapContext = mapCanvas.getContext("2d");
    const landmarks = [
      { label: byId("arch-label"), point: V(-8.65,9.78,-13.3) },
      { label: byId("wreck-label"), point: V(12.15,5.35,-14.1) }
    ];
    const projected = V(0,0,0);

    function resize() {
      width = Math.max(1, view.clientWidth);
      height = Math.max(1, view.clientHeight);
      camera.aspect = width / height;
      camera.fov = Math.max(54, Math.min(86, 2 * Math.atan(Math.tan(.393)/camera.aspect) * 180 / Math.PI));
      camera.updateProjectionMatrix();
      pointRatio.value = Math.min(window.devicePixelRatio || 1, width < 740 ? 1.35 : 1.6);
      renderer.setPixelRatio(pointRatio.value);
      renderer.setSize(width,height,false);
    }
    window.addEventListener("resize", resize);
    resize();

    function drawMap() {
      if (!mapContext) return;
      const w = mapCanvas.clientWidth, h = mapCanvas.clientHeight;
      if (w < 2 || h < 2) return;
      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      if (mapCanvas.width !== Math.floor(w*dpr) || mapCanvas.height !== Math.floor(h*dpr)) {
        mapCanvas.width = Math.floor(w*dpr);
        mapCanvas.height = Math.floor(h*dpr);
      }
      const ctx = mapContext;
      ctx.setTransform(dpr,0,0,dpr,0,0);
      ctx.clearRect(0,0,w,h);
      const sx = (w - 12) / 92;
      const sy = (h - 8) / 92;
      const mx = x => w*.5 + x*sx;
      const my = z => h*.5 + (z+14)*sy;
      ctx.lineWidth = 1;
      ctx.strokeStyle = "rgba(166,210,196,.15)";
      ctx.setLineDash([2,4]);
      for (let i = -36; i <= 37; i += 12) {
        ctx.beginPath(); ctx.moveTo(mx(i),3); ctx.lineTo(mx(i),h-3); ctx.stroke();
        ctx.beginPath(); ctx.moveTo(4,my(i-14)); ctx.lineTo(w-4,my(i-14)); ctx.stroke();
      }
      ctx.setLineDash([]);
      for (const [x,z,r] of [[-21,-12,12],[21,-22,13],[-19,-42,10],[16,-45,11],[-11,9,7],[13,5,6]]) {
        ctx.strokeStyle = "rgba(139,189,163,.24)";
        for (let layer = 0; layer < 2; layer++) {
          ctx.beginPath();
          for (let i = 0; i <= 28; i++) {
            const a = i/28*TAU;
            const edge = r*(.65+layer*.24+.13*Math.sin(a*3+x)+.09*Math.cos(a*5+z));
            const px = mx(x+Math.cos(a)*edge), py = my(z+Math.sin(a)*edge);
            if (i) ctx.lineTo(px,py); else ctx.moveTo(px,py);
          }
          ctx.closePath(); ctx.stroke();
        }
      }
      ctx.fillStyle = "#0b343d"; ctx.strokeStyle = "#a5d5be";
      ctx.beginPath(); ctx.arc(mx(-8.8),my(-13.2),3.4,0,TAU); ctx.fill(); ctx.stroke();
      const wx=mx(9.6), wy=my(-13.2);
      ctx.strokeStyle = "#edc283";
      ctx.beginPath(); ctx.moveTo(wx,wy-4.3); ctx.lineTo(wx+4.3,wy); ctx.lineTo(wx,wy+4.3); ctx.lineTo(wx-4.3,wy);
      ctx.closePath(); ctx.fill(); ctx.stroke();
      const px = clamp(mx(swimmer.x),4,w-4), py = clamp(my(swimmer.z),5,h-5);
      ctx.save();
      ctx.translate(px,py);
      ctx.rotate(yaw);
      ctx.fillStyle = "rgba(186,232,216,.20)";
      ctx.beginPath(); ctx.moveTo(0,1); ctx.lineTo(-9,-15); ctx.lineTo(9,-15); ctx.closePath(); ctx.fill();
      ctx.fillStyle = "#effbe8";
      ctx.beginPath(); ctx.moveTo(0,-5.4); ctx.lineTo(3.35,3.1); ctx.lineTo(0,1.9); ctx.lineTo(-3.35,3.1); ctx.closePath(); ctx.fill();
      ctx.restore();
    }
    function updateHud() {
      byId("depth").textContent = (WATER-swimmer.y).toFixed(1);
      const degrees = (yaw * 180 / Math.PI % 360 + 360) % 360;
      compassTicks.forEach((tick, i) => {
        const diff = (i * 15 - degrees + 540) % 360 - 180;
        tick.style.left = (91 + diff * 2.08) + "px";
      });
      drawMap();
      if (width <= 720) return;
      camera.updateMatrixWorld();
      landmarks.forEach(({label,point}) => {
        projected.copy(point).project(camera);
        const x = (projected.x + 1) * .5 * width, y = (1 - projected.y) * .5 * height;
        const titleArea = !stage.classList.contains("exploring") && x < Math.min(330, width*.31) && y < height*.65;
        label.hidden = projected.z < -1 || projected.z > 1 || x < 60 || x > width-60 || y < 127 || y > height-110 || titleArea;
        if (!label.hidden) {
          label.style.left = x + "px";
          label.style.top = y + "px";
          label.querySelector(".range").textContent = Math.round(swimmer.distanceTo(point)) + " m";
        }
      });
    }
    function resetPose() {
      swimmer.set(.8,6.65,14.5);
      yaw = desiredYaw = .034;
      pitch = desiredPitch = -.071;
      speed = 0;
      pointer = null;
      stage.classList.remove("exploring", "swimming");
      lastHud = -1;
    }
    function setTour(active) {
      if (active) { resetPose(); tourTime = 0; }
      else { desiredYaw = yaw; desiredPitch = pitch; }
      touring = active;
      tourButton.setAttribute("aria-pressed", String(active));
      byId("tour-text").textContent = active ? "End tour" : "Guided tour";
      paintIcon(byId("tour-icon"), active ? "pause" : "play");
      stage.classList.toggle("touring", active);
    }
    document.addEventListener("pointerdown", event => {
      buttonCanceledTour = touring && tourButton.contains(event.target);
      if (touring) setTour(false);
    }, true);
    tourButton.addEventListener("click", event => {
      if (buttonCanceledTour && event.detail > 0) { buttonCanceledTour = false; return; }
      buttonCanceledTour = false;
      setTour(!touring);
    });
    resetButton.addEventListener("click", () => {
      setTour(false);
      resetPose();
    });
    view.addEventListener("pointerdown", event => {
      if (pointer !== null || (event.pointerType === "mouse" && event.button !== 0)) return;
      event.preventDefault();
      pointer = event.pointerId;
      pointerX = event.clientX;
      pointerY = event.clientY;
      if (event.pointerType === "touch") paintIcon(byId("gesture-icon"), "touch");
      if (view.setPointerCapture) view.setPointerCapture(pointer);
      stage.classList.add("exploring", "swimming");
    });
    window.addEventListener("pointermove", event => {
      if (event.pointerId !== pointer) return;
      const sensitivity = event.pointerType === "touch" ? .0056 : .0044;
      desiredYaw += (event.clientX - pointerX) * sensitivity;
      desiredPitch = clamp(desiredPitch - (event.clientY - pointerY) * sensitivity, -1.31, 1.31);
      pointerX = event.clientX;
      pointerY = event.clientY;
    });
    function release(event) {
      if (event && pointer !== event.pointerId) return;
      pointer = null;
      stage.classList.remove("swimming");
    }
    window.addEventListener("pointerup", release);
    window.addEventListener("pointercancel", release);
    view.addEventListener("lostpointercapture", release);
    window.addEventListener("blur", () => release());
    view.addEventListener("contextmenu", event => event.preventDefault());

    function guide(u) {
      route.getPointAt(u, routePoint);
      movement.copy(routePoint).sub(swimmer);
      if (movement.lengthSq() > .36) movement.setLength(.6);
      swim(movement.x, movement.y, movement.z);
      let i = 1;
      while (i < sights.length - 1 && u > sights[i][0]) i++;
      const a = sights[i-1], b = sights[i];
      const f = (u-a[0])/(b[0]-a[0]);
      const eased = f*f*(3-2*f);
      sight.set(mix(a[1],b[1],eased),mix(a[2],b[2],eased),mix(a[3],b[3],eased)).sub(swimmer);
      yaw = Math.atan2(sight.x,-sight.z);
      pitch = Math.atan2(sight.y,Math.hypot(sight.x,sight.z));
      const chapter = u < .23 ? "Kelp forest" : u < .44 ? "Rock arch" : u < .76 ? "Shipwreck" : "Manta rays";
      if (byId("chapter").textContent !== chapter) byId("chapter").textContent = chapter;
      byId("progress").style.transform = "scaleX(" + u + ")";
    }
    if (location.hash === "#demo") setTour(true);
    window.addEventListener("hashchange", () => { if (location.hash === "#demo") setTour(true); });

    function frame(now) {
      const dt = Math.min(.045, Math.max(0,(now-clock.previous)/1000));
      clock.previous = now;
      clock.t += dt;
      time.value = clock.t;
      if (touring) {
        tourTime += dt;
        if (tourTime > 2.6) stage.classList.add("exploring");
        guide((tourTime % 20) / 20);
      } else {
        const smoothing = 1 - Math.exp(-dt * 15);
        yaw = mix(yaw,desiredYaw,smoothing);
        pitch = mix(pitch,desiredPitch,smoothing);
        speed = mix(speed,pointer === null ? 0 : 4.7,1 - Math.exp(-dt * (pointer === null ? 6.4 : 4.3)));
        const flat = Math.cos(pitch);
        aim.set(Math.sin(yaw)*flat, Math.sin(pitch), -Math.cos(yaw)*flat);
        if (speed > .009) swim(aim.x*speed*dt,aim.y*speed*dt,aim.z*speed*dt);
      }
      camera.position.copy(swimmer);
      if (!reducedMotion) camera.position.y += Math.sin(clock.t*1.54)*.035;
      camera.rotation.set(pitch,-yaw,0,"YXZ");
      sky.position.copy(camera.position);
      updateFish(clock.t);
      updateRays(clock.t);
      if (clock.t-lastHud > .079) { updateHud(); lastHud = clock.t; }
      renderer.render(scene,camera);
      requestAnimationFrame(frame);
    }
    requestAnimationFrame(frame);
  }
})();
</script>
</body>
</html>