Skip to content
VibeCodeBench
Back to the app

The code

Swim the Kelp Garden by Claude Haiku 5.5

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.)24.2 KB · 600 lines · loads cdnjs.cloudflare.com/ajax/libs/three.js/r160/three.min.js
Download
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>Kelp Garden</title>
<style>
  :root { --teal:#1f8a86; --deep:#0a2a4a; --kelp:#2f6b3a; --gold:#e8b44a; --orange:#ff8a4c; --coral:#ff7a6b; }
  html, body { margin:0; height:100%; overflow:hidden; background:#06213a; font-family: system-ui, -apple-system, sans-serif; touch-action:none; user-select:none; -webkit-user-select:none; }
  canvas { display:block; width:100vw; height:100vh; }
  #hud { position:fixed; left:0; right:0; top:0; display:flex; justify-content:space-between; align-items:center; padding:12px 16px; color:#e9f7f5; font-size:15px; pointer-events:none; text-shadow:0 1px 4px rgba(0,0,0,.4); }
  #hud button { pointer-events:auto; min-width:56px; min-height:48px; padding:0 16px; font-size:16px; border:0; border-radius:14px; background:rgba(232,180,74,.92); color:#0a2a4a; font-weight:700; }
  #hint { position:fixed; left:50%; bottom:22px; transform:translateX(-50%); color:#f4fbfa; background:rgba(10,42,74,.55); padding:10px 16px; border-radius:14px; font-size:15px; text-align:center; pointer-events:none; max-width:90vw; transition:opacity .8s; }
  #hint.off { opacity:0; }
</style>
</head>
<body>
<canvas id="c"></canvas>
<div id="hud">
  <span id="count">Fish: 0</span>
  <button id="sound" type="button">Calm</button>
</div>
<div id="hint">Press and hold to glide ahead. Drag to turn. Mouse: hold the button and move.</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r160/three.min.js"></script>
<script>
(function () {
  "use strict";

  var canvas = document.getElementById("c");
  var hint = document.getElementById("hint");
  var countEl = document.getElementById("count");

  // Storage wrapped in try/catch (sandbox may block it)
  function safeGet(k) { try { return window.localStorage.getItem(k); } catch (e) { return null; } }
  function safeSet(k, v) { try { window.localStorage.setItem(k, v); } catch (e) {} }

  var DEMO = (location.hash === "#demo");

  // ---------- Renderer / scene ----------
  var renderer;
  try {
    renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true });
  } catch (e) {
    countEl.textContent = "WebGL not available";
    return;
  }
  renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
  renderer.setSize(window.innerWidth, window.innerHeight, false);

  var scene = new THREE.Scene();
  var WATER_NEAR = new THREE.Color(0x2fb3b0);  // teal close
  var WATER_FAR  = new THREE.Color(0x06244a);  // deep blue far
  scene.background = WATER_FAR.clone();
  scene.fog = new THREE.Fog(WATER_FAR.clone(), 40, 240);

  var camera = new THREE.PerspectiveCamera(65, window.innerWidth / window.innerHeight, 0.1, 400);

  // ---------- Lights (stylized, warm sun shafts) ----------
  scene.add(new THREE.HemisphereLight(0x9fe8e0, 0x0a2a4a, 0.9));
  var sun = new THREE.DirectionalLight(0xffd98a, 0.85);
  sun.position.set(20, 60, 10);
  scene.add(sun);

  // ---------- Seeded random for stable layout ----------
  var seed = 1337;
  function rnd() { seed = (seed * 16807) % 2147483647; return (seed - 1) / 2147483646; }
  function rr(a, b) { return a + (b - a) * rnd(); }

  // ---------- Sand floor with ripple shading ----------
  var floorGeo = new THREE.PlaneGeometry(600, 600, 120, 120);
  floorGeo.rotateX(-Math.PI / 2);
  var fp = floorGeo.attributes.position;
  for (var i = 0; i < fp.count; i++) {
    var x = fp.getX(i), z = fp.getZ(i);
    fp.setY(i, Math.sin(x * 0.11) * 0.6 + Math.cos(z * 0.09) * 0.5 + Math.sin((x + z) * 0.21) * 0.25);
  }
  floorGeo.computeVertexNormals();
  var sandMat = new THREE.MeshStandardMaterial({ color: 0xd9b77a, roughness: 1, metalness: 0 });
  var floor = new THREE.Mesh(floorGeo, sandMat);
  floor.position.y = -18;
  scene.add(floor);

  // ---------- Animated light ripples on the sand (moving caustic-like stripes) ----------
  var causticCanvas = document.createElement("canvas");
  causticCanvas.width = causticCanvas.height = 256;
  var cctx = causticCanvas.getContext("2d");
  var causticTex = new THREE.CanvasTexture(causticCanvas);
  causticTex.wrapS = causticTex.wrapT = THREE.RepeatWrapping;
  causticTex.repeat.set(6, 6);
  var causticPlane = new THREE.Mesh(
    new THREE.PlaneGeometry(600, 600),
    new THREE.MeshBasicMaterial({ map: causticTex, transparent: true, opacity: 0.35, depthWrite: false, blending: THREE.AdditiveBlending })
  );
  causticPlane.rotation.x = -Math.PI / 2;
  causticPlane.position.y = -17.5;
  scene.add(causticPlane);

  function drawCaustics(t) {
    cctx.fillStyle = "#000";
    cctx.fillRect(0, 0, 256, 256);
    cctx.strokeStyle = "#ffe6a0";
    cctx.lineWidth = 3;
    for (var k = 0; k < 7; k++) {
      cctx.beginPath();
      for (var x = 0; x <= 256; x += 8) {
        var y = 128 + Math.sin(x * 0.05 + t * 1.3 + k) * 22 + Math.sin(x * 0.11 - t * 0.9 + k * 1.7) * 10 + k * 18 - 54;
        if (x === 0) cctx.moveTo(x, y); else cctx.lineTo(x, y);
      }
      cctx.stroke();
    }
    causticTex.needsUpdate = true;
  }

  // ---------- Sunbeams from the surface ----------
  var beams = [];
  var beamGeo = new THREE.CylinderGeometry(1.2, 9, 120, 8, 1, true);
  for (var b = 0; b < 9; b++) {
    var beamMat = new THREE.MeshBasicMaterial({ color: 0xfff1b8, transparent: true, opacity: 0.09, depthWrite: false, side: THREE.DoubleSide, blending: THREE.AdditiveBlending });
    var beam = new THREE.Mesh(beamGeo, beamMat);
    beam.position.set(rr(-70, 70), 40, rr(-70, 70));
    beam.rotation.z = rr(-0.25, 0.25);
    beam.rotation.x = rr(-0.1, 0.1);
    beam.userData.phase = rnd() * 6.28;
    scene.add(beam);
    beams.push(beam);
  }

  // ---------- Rippling surface ----------
  var surfGeo = new THREE.PlaneGeometry(700, 700, 60, 60);
  surfGeo.rotateX(Math.PI / 2);
  var surfMat = new THREE.MeshBasicMaterial({ color: 0x9ff3e6, transparent: true, opacity: 0.22, side: THREE.DoubleSide, depthWrite: false });
  var surface = new THREE.Mesh(surfGeo, surfMat);
  surface.position.y = 60;
  scene.add(surface);

  // ---------- Kelp: tall swaying stalks with leaves ----------
  var kelpGroup = new THREE.Group();
  scene.add(kelpGroup);
  var kelpMat = new THREE.MeshStandardMaterial({ color: 0x2f6b3a, roughness: 0.6, flatShading: true });
  var kelpLeafMat = new THREE.MeshStandardMaterial({ color: 0x3d8a45, roughness: 0.5, side: THREE.DoubleSide, flatShading: true });
  var kelps = [];
  var kelpCount = 64;
  for (var kk = 0; kk < kelpCount; kk++) {
    var kx = rr(-120, 120), kz = rr(-120, 120);
    if (Math.hypot(kx, kz) < 10) { kk--; continue; }
    var height = rr(40, 62);
    var stalk = new THREE.Group();
    stalk.position.set(kx, -18, kz);
    var segs = 8;
    var segArr = [];
    for (var s = 0; s < segs; s++) {
      var seg = new THREE.Mesh(new THREE.CylinderGeometry(0.35 - s * 0.02, 0.45 - s * 0.02, height / segs, 5), kelpMat);
      seg.position.y = (s + 0.5) * (height / segs);
      stalk.add(seg);
      segArr.push(seg);
      if (s % 2 === 1) {
        var leaf = new THREE.Mesh(new THREE.PlaneGeometry(2.4, 0.9), kelpLeafMat);
        leaf.position.set(0.6, seg.position.y, 0);
        leaf.rotation.y = rr(-0.8, 0.8);
        stalk.add(leaf);
      }
    }
    scene.add(stalk);
    kelps.push({ group: stalk, segs: segArr, phase: rnd() * 6.28, height: height, x: kx, z: kz });
  }

  // ---------- Rocky arches (solid, collidable) ----------
  var colliders = [];   // {x, z, r} circles on the floor plane
  var rockMat = new THREE.MeshStandardMaterial({ color: 0x4f5d6b, roughness: 0.95, flatShading: true });
  var rockMat2 = new THREE.MeshStandardMaterial({ color: 0x6a5c52, roughness: 0.95, flatShading: true });

  function addArch(ax, az, rot, scale) {
    var arch = new THREE.Group();
    arch.position.set(ax, -18, az);
    arch.rotation.y = rot;
    var pillarGeo = new THREE.BoxGeometry(4 * scale, 22 * scale, 5 * scale);
    var left = new THREE.Mesh(pillarGeo, rockMat);
    left.position.set(-7 * scale, 11 * scale, 0);
    var right = new THREE.Mesh(pillarGeo, rockMat2);
    right.position.set(7 * scale, 11 * scale, 0);
    var top = new THREE.Mesh(new THREE.BoxGeometry(18 * scale, 5 * scale, 6 * scale), rockMat);
    top.position.set(0, 23 * scale, 0);
    arch.add(left, right, top);
    scene.add(arch);
    // Collider: two pillars, approximated as circles on the floor.
    colliders.push({ x: ax + Math.cos(rot) * (-7 * scale) , z: az - Math.sin(rot) * (-7 * scale), r: 3.2 * scale });
    colliders.push({ x: ax + Math.cos(rot) * (7 * scale) , z: az - Math.sin(rot) * (7 * scale), r: 3.2 * scale });
  }
  addArch(-38, -30, 0.4, 1.3);
  addArch(40, 18, -0.6, 1.1);
  addArch(-10, 46, 1.1, 1.0);

  // ---------- Scattered rocks ----------
  for (var rk = 0; rk < 22; rk++) {
    var rx = rr(-130, 130), rz = rr(-130, 130);
    if (Math.hypot(rx, rz) < 14) continue;
    var rs = rr(1.5, 4.5);
    var rock = new THREE.Mesh(new THREE.DodecahedronGeometry(rs, 0), rnd() > 0.5 ? rockMat : rockMat2);
    rock.position.set(rx, -18 + rs * 0.3, rz);
    rock.rotation.set(rnd() * 3, rnd() * 3, rnd() * 3);
    scene.add(rock);
    colliders.push({ x: rx, z: rz, r: rs * 0.95 });
  }

  // ---------- Sunken wooden ship (solid) ----------
  var ship = new THREE.Group();
  var woodMat = new THREE.MeshStandardMaterial({ color: 0x8a5a2b, roughness: 0.9, flatShading: true });
  var woodDark = new THREE.MeshStandardMaterial({ color: 0x5a3a1c, roughness: 0.9, flatShading: true });
  var hull = new THREE.Mesh(new THREE.BoxGeometry(16, 4, 6), woodMat);
  hull.position.y = 2;
  var bow = new THREE.Mesh(new THREE.ConeGeometry(3, 5, 4), woodMat);
  bow.rotation.z = -Math.PI / 2;
  bow.position.set(10, 2.5, 0);
  var mast = new THREE.Mesh(new THREE.CylinderGeometry(0.25, 0.3, 14, 6), woodDark);
  mast.position.set(-1, 9, 0);
  var sail = new THREE.Mesh(new THREE.PlaneGeometry(7, 7), new THREE.MeshStandardMaterial({ color: 0xe8c890, side: THREE.DoubleSide, roughness: 1 }));
  sail.position.set(-1, 8, 0.1);
  sail.rotation.x = 0.2;
  ship.add(hull, bow, mast, sail);
  ship.position.set(70, -18 + 1.2, -55);
  ship.rotation.y = 0.5;
  ship.rotation.z = 0.12;
  scene.add(ship);
  colliders.push({ x: 70, z: -55, r: 7.5 });

  // ---------- Coral (warm orange, coral) ----------
  var coralMat1 = new THREE.MeshStandardMaterial({ color: 0xff8a4c, roughness: 0.8, flatShading: true });
  var coralMat2 = new THREE.MeshStandardMaterial({ color: 0xff7a6b, roughness: 0.8, flatShading: true });
  for (var c = 0; c < 26; c++) {
    var cx = rr(-120, 120), cz = rr(-120, 120);
    if (Math.hypot(cx, cz) < 12) continue;
    var cs = rr(1.2, 2.6);
    var coral = new THREE.Mesh(new THREE.IcosahedronGeometry(cs, 0), rnd() > 0.5 ? coralMat1 : coralMat2);
    coral.position.set(cx, -18 + cs * 0.5, cz);
    scene.add(coral);
    colliders.push({ x: cx, z: cz, r: cs * 0.9 });
  }

  // ---------- Fish schools (instanced, flocking) ----------
  var FISH = 90;
  var fishGeo = new THREE.ConeGeometry(0.45, 1.8, 5);
  fishGeo.rotateX(Math.PI / 2);   // point along +Z
  var fishMat = new THREE.MeshStandardMaterial({ color: 0xe8b44a, roughness: 0.5, flatShading: true });
  var fishMesh = new THREE.InstancedMesh(fishGeo, fishMat, FISH);
  fishMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
  scene.add(fishMesh);
  var fishes = [];
  var schoolCenters = [
    { x: -20, y: 6, z: -20, hue: 0xe8b44a },
    { x: 30, y: 12, z: 30, hue: 0xff8a4c },
    { x: -55, y: 2, z: 40, hue: 0x6fd6c8 }
  ];
  for (var f = 0; f < FISH; f++) {
    var sc = schoolCenters[f % schoolCenters.length];
    fishes.push({
      p: new THREE.Vector3(sc.x + rr(-6, 6), sc.y + rr(-3, 3), sc.z + rr(-6, 6)),
      v: new THREE.Vector3(rr(-1, 1), rr(-0.2, 0.2), rr(-1, 1)).normalize().multiplyScalar(4),
      school: f % schoolCenters.length
    });
  }
  var tmpColor = new THREE.Color();
  var fishColors = [0xe8b44a, 0xff8a4c, 0x6fd6c8];
  for (var fc = 0; fc < FISH; fc++) {
    tmpColor.setHex(fishColors[fc % fishColors.length]);
    fishMesh.setColorAt(fc, tmpColor);
  }
  if (fishMesh.instanceColor) fishMesh.instanceColor.needsUpdate = true;

  // ---------- Manta rays (slow gliding) ----------
  var mantas = [];
  var mantaMat = new THREE.MeshStandardMaterial({ color: 0x1f4f78, roughness: 0.6, side: THREE.DoubleSide, flatShading: true });
  var mantaBelly = new THREE.MeshStandardMaterial({ color: 0xc9ecef, roughness: 0.6, side: THREE.DoubleSide, flatShading: true });
  for (var m = 0; m < 4; m++) {
    var manta = new THREE.Group();
    var wingShape = new THREE.Shape();
    wingShape.moveTo(0, 0);
    wingShape.quadraticCurveTo(4, 2.5, 8, 0.4);
    wingShape.lineTo(0, -0.6);
    wingShape.lineTo(-8, 0.4);
    wingShape.quadraticCurveTo(-4, 2.5, 0, 0);
    var wingGeo = new THREE.ShapeGeometry(wingShape);
    var wingL = new THREE.Mesh(wingGeo, mantaMat);
    var wingR = new THREE.Mesh(wingGeo, mantaBelly);
    wingL.rotation.x = Math.PI / 2;
    wingR.rotation.x = Math.PI / 2;
    wingR.scale.set(0.9, 1, 1);
    manta.add(wingL, wingR);
    manta.scale.set(1.3, 1.3, 1.3);
    manta.userData = { t: rnd() * 10, r: rr(30, 70), cx: rr(-60, 60), cz: rr(-60, 60), y: rr(4, 14), speed: rr(0.08, 0.14) };
    scene.add(manta);
    mantas.push(manta);
  }

  // ---------- Bubbles ----------
  var BUBBLES = 120;
  var bubbleGeo = new THREE.SphereGeometry(0.3, 8, 6);
  var bubbleMat = new THREE.MeshBasicMaterial({ color: 0xbff7f0, transparent: true, opacity: 0.55, depthWrite: false });
  var bubbleMesh = new THREE.InstancedMesh(bubbleGeo, bubbleMat, BUBBLES);
  bubbleMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
  scene.add(bubbleMesh);
  var bubbles = [];
  for (var bb = 0; bb < BUBBLES; bb++) {
    bubbles.push({ x: rr(-30, 30), y: rr(-18, 60), z: rr(-30, 30), s: rr(0.4, 1.2), sp: rr(1.5, 3.5), wob: rnd() * 6.28 });
  }

  // ---------- Player (diver) ----------
  var player = { pos: new THREE.Vector3(0, 0, 40), yaw: Math.PI, pitch: 0, speed: 0 };
  var PLAYER_R = 1.6;
  var tmp = new THREE.Vector3();

  // Input: press and hold to glide forward; drag to steer
  var pointer = { down: false, x: 0, y: 0, lastX: 0, lastY: 0, id: -1, moved: false };
  var demoMode = DEMO;
  var demoStart = performance.now();
  var interacted = false;

  function endDemo() {
    if (demoMode) {
      demoMode = false;
      hint.classList.add("off");
    }
  }

  canvas.addEventListener("pointerdown", function (e) {
    interacted = true;
    endDemo();
    pointer.down = true;
    pointer.id = e.pointerId;
    pointer.x = pointer.lastX = e.clientX;
    pointer.y = pointer.lastY = e.clientY;
    pointer.moved = false;
    try { canvas.setPointerCapture(e.pointerId); } catch (err) {}
    hint.classList.add("off");
    e.preventDefault();
  });
  canvas.addEventListener("pointermove", function (e) {
    if (!pointer.down || e.pointerId !== pointer.id) return;
    var dx = e.clientX - pointer.lastX;
    var dy = e.clientY - pointer.lastY;
    pointer.lastX = e.clientX;
    pointer.lastY = e.clientY;
    player.yaw -= dx * 0.006;
    player.pitch = Math.max(-0.9, Math.min(0.9, player.pitch - dy * 0.004));
    pointer.moved = true;
    e.preventDefault();
  });
  function release(e) {
    if (e && e.pointerId !== pointer.id) return;
    pointer.down = false;
    pointer.id = -1;
  }
  canvas.addEventListener("pointerup", release);
  canvas.addEventListener("pointercancel", release);
  canvas.addEventListener("pointerleave", release);
  // Prevent the sandboxed page from scrolling or zooming on touch
  document.addEventListener("touchmove", function (e) { e.preventDefault(); }, { passive: false });
  document.addEventListener("contextmenu", function (e) { e.preventDefault(); });

  // Demo: hands-free loop (about 20 s) that shows swimming, turning, fish and rays
  function demoDrive(t) {
    var cyc = (t % 20) / 20;
    // steer gently in a figure-eight through the garden, with a small up/down bob
    player.yaw = Math.PI + Math.sin(cyc * Math.PI * 2) * 1.1;
    player.pitch = Math.sin(cyc * Math.PI * 4) * 0.25;
    return true;
  }

  // ---------- Movement and collisions ----------
  var GLIDE_SPEED = 13;
  var BOUND = 150;

  function resolveCollisions(p) {
    for (var i = 0; i < colliders.length; i++) {
      var c = colliders[i];
      var dx = p.x - c.x, dz = p.z - c.z;
      var d = Math.sqrt(dx * dx + dz * dz);
      var minD = c.r + PLAYER_R;
      if (d < minD) {
        if (d < 1e-4) { dx = 1; dz = 0; d = 1; }
        var push = minD - d;
        p.x += (dx / d) * push;
        p.z += (dz / d) * push;
      }
    }
    // Keep the diver above the sand and below the surface
    if (p.y < -16) p.y = -16;
    if (p.y > 52) p.y = 52;
    // Keep inside the garden
    if (p.x > BOUND) p.x = BOUND; if (p.x < -BOUND) p.x = -BOUND;
    if (p.z > BOUND) p.z = BOUND; if (p.z < -BOUND) p.z = -BOUND;
  }

  // Keep a short look-ahead check to stop the diver before solid things
  function blockedAt(x, z) {
    for (var i = 0; i < colliders.length; i++) {
      var c = colliders[i];
      var dx = x - c.x, dz = z - c.z;
      if (dx * dx + dz * dz < Math.pow(c.r + PLAYER_R * 0.5, 2)) return true;
    }
    return false;
  }

  // ---------- Fish flocking update ----------
  function updateFish(dt, t) {
    var sep = 5.5, ali = 1.0, coh = 0.6, wander = 0.4;
    var sumByS = [];
    for (var s = 0; s < schoolCenters.length; s++) sumByS.push({ p: new THREE.Vector3(), v: new THREE.Vector3(), n: 0 });
    for (var i = 0; i < fishes.length; i++) {
      var f = fishes[i];
      sumByS[f.school].p.add(f.p);
      sumByS[f.school].v.add(f.v);
      sumByS[f.school].n++;
    }
    for (var j = 0; j < fishes.length; j++) {
      var a = fishes[j];
      var g = sumByS[a.school];
      var inv = 1 / Math.max(1, g.n);
      var center = tmp.copy(g.p).multiplyScalar(inv);
      var acc = new THREE.Vector3();
      acc.add(center.sub(a.p).multiplyScalar(coh * 0.2));
      acc.add(g.v.clone().multiplyScalar(inv).sub(a.v).multiplyScalar(ali * 0.2));
      // Wander so schools roam the garden
      acc.x += Math.sin(t * 0.3 + j) * wander;
      acc.z += Math.cos(t * 0.27 + j * 0.7) * wander;
      // Separation from neighbours (sample a few)
      for (var k = 0; k < 4; k++) {
        var o = fishes[(j * 7 + k * 13 + 3) % fishes.length];
        if (o === a) continue;
        var dd = a.p.distanceTo(o.p);
        if (dd < 2.2 && dd > 1e-3) acc.add(a.p.clone().sub(o.p).multiplyScalar(sep / dd * 0.02));
      }
      // Stay away from solid objects
      if (blockedAt(a.p.x, a.p.z)) acc.add(new THREE.Vector3(-a.p.x, 0, -a.p.z).normalize().multiplyScalar(4));
      a.v.add(acc.multiplyScalar(dt * 5));
      var sp = a.v.length();
      if (sp > 6) a.v.multiplyScalar(6 / sp);
      if (sp < 2.5) a.v.multiplyScalar(2.5 / Math.max(sp, 1e-3));
      a.p.addScaledVector(a.v, dt);
      // Keep schools inside the garden volume
      if (a.p.y < -14) a.p.y = -14;
      if (a.p.y > 46) a.p.y = 46;
      if (Math.abs(a.p.x) > BOUND) a.v.x *= -1;
      if (Math.abs(a.p.z) > BOUND) a.v.z *= -1;
    }
  }

  // ---------- Resize ----------
  function onResize() {
    var w = window.innerWidth, h = window.innerHeight;
    renderer.setSize(w, h, false);
    camera.aspect = w / h;
    camera.updateProjectionMatrix();
  }
  window.addEventListener("resize", onResize);

  // ---------- Main loop ----------
  var clock = performance.now();
  var last = clock;
  var sndOn = false;
  var sndBtn = document.getElementById("sound");
  sndBtn.addEventListener("click", function () { sndOn = !sndOn; sndBtn.textContent = sndOn ? "Calm on" : "Calm"; endDemo(); });
  countEl.textContent = "Fish: " + FISH;

  // Hint fades after a while if not interacting
  setTimeout(function () { if (!interacted && !demoMode) hint.classList.add("off"); }, 9000);

  var bgNear = new THREE.Color();
  var bgTmp = new THREE.Color();
  var fishMatrix = new THREE.Matrix4();
  var bubMatrix = new THREE.Matrix4();
  var quat = new THREE.Quaternion();
  var scl = new THREE.Vector3(1, 1, 1);

  function frame(now) {
    var dt = Math.min(0.05, (now - last) / 1000);
    last = now;
    var t = (now - clock) / 1000;

    if (demoMode) {
      // Auto-drive the diver for the demo; real touch ends the demo (handled in pointerdown)
      demoDrive(now / 1000 - demoStart / 1000);
      if (now - demoStart > 20000) {
        demoMode = false;
        hint.classList.add("off");
      }
    }

    // Swim: glide forward while held (or always, during the demo)
    var gliding = pointer.down || demoMode;
    var target = gliding ? GLIDE_SPEED : 0;
    player.speed += (target - player.speed) * Math.min(1, dt * 2.2);

    var fx = -Math.sin(player.yaw) * Math.cos(player.pitch);
    var fy = Math.sin(player.pitch);
    var fz = -Math.cos(player.yaw) * Math.cos(player.pitch);
    var nx = player.pos.x + fx * player.speed * dt;
    var ny = player.pos.y + fy * player.speed * dt;
    var nz = player.pos.z + fz * player.speed * dt;

    // Simple solid check: slide along the obstacle instead of entering it
    if (blockedAt(nx, nz)) {
      player.speed *= 0.4;
    } else {
      player.pos.x = nx; player.pos.y = ny; player.pos.z = nz;
    }
    resolveCollisions(player.pos);

    // Camera follows behind and above the diver
    var camDist = 7, camHeight = 2.6;
    var cx = player.pos.x - fx * camDist;
    var cy = player.pos.y - fy * camDist + camHeight;
    var cz = player.pos.z - fz * camDist;
    camera.position.set(cx, cy, cz);
    camera.lookAt(player.pos.x + fx * 4, player.pos.y + fy * 4, player.pos.z + fz * 4);

    // Water color: teal near, deeper blue far, hazier with distance
    fishMatrix.identity();
    updateFish(dt, t);
    for (var fi = 0; fi < fishes.length; fi++) {
      var fsh = fishes[fi];
      var dir = fsh.v.clone();
      if (dir.lengthSq() < 1e-6) dir.set(0, 0, 1);
      dir.normalize();
      quat.setFromUnitVectors(new THREE.Vector3(0, 0, 1), dir);
      fishMatrix.compose(fsh.p, quat, scl);
      fishMesh.setMatrixAt(fi, fishMatrix);
    }
    fishMesh.instanceMatrix.needsUpdate = true;

    // Manta rays glide in wide loops
    for (var mi = 0; mi < mantas.length; mi++) {
      var mn = mantas[mi];
      var u = mn.userData;
      u.t += dt * u.speed;
      mn.position.set(u.cx + Math.cos(u.t) * u.r, u.y + Math.sin(u.t * 0.7) * 1.5, u.cz + Math.sin(u.t) * u.r);
      mn.rotation.set(0.15 * Math.sin(u.t * 0.7), -u.t + Math.PI / 2, 0.25 * Math.sin(t * 1.4 + mi));
    }

    // Bubbles drift upward and wobble
    for (var bi = 0; bi < bubbles.length; bi++) {
      var bu = bubbles[bi];
      bu.y += bu.sp * dt;
      bu.x += Math.sin(t * 1.3 + bu.wob) * 0.4 * dt;
      if (bu.y > 60) { bu.y = -18; bu.x = rr(-30, 30); bu.z = rr(-30, 30); }
      bubMatrix.makeTranslation(bu.x, bu.y, bu.z);
      bubMatrix.scale(new THREE.Vector3(bu.s, bu.s, bu.s));
      bubbleMesh.setMatrixAt(bi, bubMatrix);
    }
    bubbleMesh.instanceMatrix.needsUpdate = true;

    // Kelp sway: each stalk bends like it is held by a current
    for (var ki = 0; ki < kelps.length; ki++) {
      var kp = kelps[ki];
      for (var si = 0; si < kp.segs.length; si++) {
        var seg = kp.segs[si];
        var bend = Math.sin(t * 0.9 + kp.phase + si * 0.35) * 0.09 * (si + 1) * 0.5;
        seg.rotation.z = bend;
        seg.rotation.x = Math.cos(t * 0.7 + kp.phase + si * 0.3) * 0.06 * (si + 1) * 0.5;
      }
    }

    // Sunbeams and surface ripples
    for (var bmi = 0; bmi < beams.length; bmi++) {
      var bm = beams[bmi];
      bm.material.opacity = 0.05 + 0.05 * Math.sin(t * 0.6 + bm.userData.phase);
      bm.rotation.z += Math.sin(t * 0.2 + bmi) * 0.0004;
    }
    var sp2 = surface.geometry.attributes.position;
    for (var si2 = 0; si2 < sp2.count; si2++) {
      var sx = sp2.getX(si2), sz = sp2.getZ(si2);
      sp2.setY(si2, Math.sin(sx * 0.06 + t * 1.1) * 0.9 + Math.cos(sz * 0.07 + t * 0.9) * 0.7);
    }
    sp2.needsUpdate = true;

    // Caustics on the sand
    if ((Math.floor(t * 12) % 2) === 0) drawCaustics(t);
    causticTex.offset.x = (t * 0.02) % 1;
    causticTex.offset.y = (t * 0.015) % 1;

    // Fog colour follows depth: bluer and hazier farther away, teal near the surface
    var depth = Math.max(0, Math.min(1, (player.pos.y + 18) / 70));
    bgNear.copy(WATER_NEAR).lerp(WATER_FAR, 0.55);
    bgTmp.copy(WATER_FAR).lerp(bgNear, depth * 0.6);
    scene.background.copy(bgTmp);
    scene.fog.color.copy(bgTmp);

    renderer.render(scene, camera);
    requestAnimationFrame(frame);
  }

  // Start
  if (DEMO) {
    hint.textContent = "Demo: touch the screen to take control.";
  }
  requestAnimationFrame(function (now) { last = now; demoStart = now; requestAnimationFrame(frame); });
})();
</script>
</body>
</html>