Skip to content
VibeCodeBench
Back to the app

The code

Swim the Kelp Garden by Claude Opus 5.5

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

index.html

works · auto-checked (Checked by an automated pass. Not hand-played yet.)39.9 KB · 773 lines · loads cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.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>
  html,body{margin:0;height:100%;overflow:hidden;background:#08304f;touch-action:none;-webkit-user-select:none;user-select:none;font-family:system-ui,-apple-system,Segoe UI,sans-serif}
  canvas{display:block;touch-action:none;outline:none}
  #hud{position:fixed;left:0;right:0;top:0;padding:14px 16px;color:#f3e2b4;pointer-events:none;text-shadow:0 1px 5px #000a}
  #title{font-size:20px;font-weight:600;letter-spacing:.05em}
  #hint{margin-top:6px;font-size:15px;opacity:.92;transition:opacity 1.4s;max-width:560px;line-height:1.4}
  #btns{position:fixed;right:16px;bottom:26px;display:flex;flex-direction:column;gap:14px}
  .b{width:74px;height:74px;border-radius:50%;border:2px solid rgba(232,196,106,.6);background:rgba(11,42,74,.55);color:#f3d48a;font-size:15px;font-weight:600;display:flex;flex-direction:column;align-items:center;justify-content:center;touch-action:none;-webkit-tap-highlight-color:transparent;cursor:pointer;backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px)}
  .b span{font-size:24px;line-height:1}
  .b.on{background:rgba(232,116,44,.75);color:#fff}
  #demo{position:fixed;left:50%;bottom:30px;transform:translateX(-50%);padding:10px 18px;border-radius:24px;background:rgba(11,42,74,.8);color:#f3d48a;font-size:15px;display:none;pointer-events:none;white-space:nowrap}
</style>
</head>
<body>
<div id="hud"><div id="title">Kelp Garden</div><div id="hint">Press and hold to glide ahead, drag to turn.<br>Use Rise and Sink to change depth.</div></div>
<div id="btns">
  <div class="b" id="up" role="button" aria-label="Rise"><span>&#9650;</span>Rise</div>
  <div class="b" id="dn" role="button" aria-label="Sink"><span>&#9660;</span>Sink</div>
</div>
<div id="demo">Demo &middot; touch anywhere to swim</div>

<script type="importmap">
{"imports":{"three":"https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js"}}
</script>
<script type="module">
import * as THREE from 'three';
const V3 = THREE.Vector3;
const UP = new V3(0,1,0);

// ---------- seeded random ----------
let seed = 98765;
function rand(){ seed |= 0; seed = seed + 0x6D2B79F5 | 0; let t = Math.imul(seed ^ seed >>> 15, 1 | seed); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; }
const rr = (a,b) => a + (b-a)*rand();
const clamp = (v,a,b) => v<a?a:(v>b?b:v);
function angDiff(a,b){ let d=a-b; while(d>Math.PI) d-=Math.PI*2; while(d<-Math.PI) d+=Math.PI*2; return d; }

const SURF = 30;
const PAL = {
  teal: new THREE.Color('#1fa3a0'), tealL: new THREE.Color('#5fd0c4'),
  deep: new THREE.Color('#0b2a4a'), deep2: new THREE.Color('#1a4677'),
  kelp: new THREE.Color('#3f7d2a'), kelpL: new THREE.Color('#6c9c34'), kelpD: new THREE.Color('#2c5e22'),
  gold: new THREE.Color('#e0b040'), goldL: new THREE.Color('#f2cf6a'),
  orange: new THREE.Color('#e8742c'), orangeD: new THREE.Color('#b8521f'), orangeL: new THREE.Color('#f39a4a')
};

// ---------- terrain ----------
function gh(x,z){
  let h = Math.sin(x*0.045)*1.6 + Math.cos(z*0.05+1.3)*1.4 + Math.sin((x-z)*0.09)*0.7 + Math.cos(x*0.13+z*0.07)*0.4;
  h += Math.sin(x*0.8 + z*0.3)*0.07 + Math.sin(z*0.9 - x*0.2)*0.05;
  const d = Math.hypot(x,z); if(d>75) h += (d-75)*(d-75)*0.012;
  return h;
}

// ---------- renderer / scene ----------
const renderer = new THREE.WebGLRenderer({antialias:true, powerPreference:'high-performance'});
renderer.setPixelRatio(Math.min(window.devicePixelRatio||1, 1.75));
renderer.setSize(innerWidth, innerHeight);
document.body.prepend(renderer.domElement);
const canvas = renderer.domElement;
const scene = new THREE.Scene();
const FOG_DEEP = new THREE.Color('#073057'), FOG_SHAL = new THREE.Color('#17718c');
scene.fog = new THREE.FogExp2(FOG_DEEP.clone(), 0.024);
scene.background = scene.fog.color;
const camera = new THREE.PerspectiveCamera(65, innerWidth/innerHeight, 0.1, 400);
camera.rotation.order = 'YXZ';

scene.add(new THREE.HemisphereLight(0x8fe0d8, 0x0b2a4a, 1.5));
const L = new V3(0.35,-1,0.2).normalize();
const sun = new THREE.DirectionalLight(0xffe0a8, 2.1);
sun.position.copy(L).multiplyScalar(-60); scene.add(sun);

// ---------- shader patching: caustics, sway, fish tails, manta wings ----------
const U = { uTime:{value:0} };
const CAUS = `
float causF(vec2 uv){
  vec2 p = mod(uv*6.28318, 6.28318) - 250.0;
  vec2 i = p; float c = 1.0; float inten = 0.005; float t = uTime*0.45 + 23.0;
  for(int n=0;n<4;n++){
    float tt = t*(1.0-(3.5/float(n+1)));
    i = p + vec2(cos(tt-i.x)+sin(tt+i.y), sin(tt-i.y)+cos(tt+i.x));
    c += 1.0/length(vec2(p.x/(sin(i.x+tt)/inten), p.y/(cos(i.y+tt)/inten)));
  }
  c /= 4.0; c = 1.17 - pow(c, 1.4);
  return clamp(pow(abs(c), 8.0), 0.0, 1.5);
}`;
const WP = `
vec4 cwp = vec4(transformed,1.0);
#ifdef USE_INSTANCING
cwp = instanceMatrix*cwp;
#endif
cwp = modelMatrix*cwp; vCW = cwp.xyz;
vec3 cnn = objectNormal;
#ifdef USE_INSTANCING
cnn = mat3(instanceMatrix)*cnn;
#endif
vCNy = normalize(mat3(modelMatrix)*cnn).y;`;
const DEF = {
  none: '',
  kelp: `
float kph = float(gl_InstanceID)*1.37;
float hh = max(position.y, 0.0);
float bend = hh*hh;
transformed.x += (sin(uTime*0.7 + kph + hh*2.2)*0.10 + 0.05) * bend;
transformed.z += (cos(uTime*0.55 + kph*1.3 + hh*1.7)*0.07) * bend;`,
  fish: `
float fph = float(gl_InstanceID)*2.17;
float tw = 1.0 - smoothstep(-0.6, 0.15, position.z);
transformed.x += sin(uTime*9.0 + fph + position.z*5.0)*0.13*tw + sin(uTime*9.0+fph)*0.015;`,
  manta: `
float ax = abs(position.x);
transformed.y += sin(uTime*1.6 + uPhase - ax*0.8)*pow(ax/2.9, 1.4)*1.1;
transformed.y += sin(uTime*1.6 + uPhase + position.z*1.5)*0.04;`
};
function patch(mat, kind, k){
  mat.customProgramCacheKey = () => kind + '_' + k;
  mat.onBeforeCompile = (sh) => {
    sh.uniforms.uTime = U.uTime;
    sh.uniforms.uPhase = { value: mat.userData.phase || 0 };
    sh.vertexShader = 'uniform float uTime;\nuniform float uPhase;\nvarying vec3 vCW;\nvarying float vCNy;\n' +
      sh.vertexShader
        .replace('#include <begin_vertex>', '#include <begin_vertex>\n' + DEF[kind])
        .replace('#include <project_vertex>', '#include <project_vertex>\n' + WP);
    sh.fragmentShader = 'uniform float uTime;\nvarying vec3 vCW;\nvarying float vCNy;\n' + CAUS + '\n' +
      sh.fragmentShader.replace('#include <fog_fragment>', `
      {
        float cz = causF(vCW.xz/15.0);
        float upf = clamp(vCNy*0.6+0.4, 0.0, 1.0); upf *= upf;
        float dk = clamp(1.0 - (30.0 - vCW.y)/60.0, 0.45, 1.0);
        gl_FragColor.rgb += vec3(1.0,0.85,0.55)*cz*${k.toFixed(3)}*upf*dk;
      }
      #include <fog_fragment>`);
  };
}

// ---------- sand floor ----------
{
  const g = new THREE.PlaneGeometry(300,300,220,220); g.rotateX(-Math.PI/2);
  const p = g.attributes.position; const col = new Float32Array(p.count*3);
  const sA = new THREE.Color('#d9b468'), sB = new THREE.Color('#a8864a'), sT = new THREE.Color('#2f8f88'), c = new THREE.Color();
  for(let i=0;i<p.count;i++){
    const x=p.getX(i), z=p.getZ(i), y=gh(x,z); p.setY(i,y);
    const n = 0.5+0.5*Math.sin(x*0.21+Math.cos(z*0.17)*2.0)*Math.cos(z*0.23+x*0.05);
    c.copy(sB).lerp(sA, 0.35+0.65*n);
    c.lerp(sT, clamp(-(y+1.2)*0.25, 0, 0.35));
    col[i*3]=c.r; col[i*3+1]=c.g; col[i*3+2]=c.b;
  }
  g.setAttribute('color', new THREE.BufferAttribute(col,3));
  g.computeVertexNormals();
  const m = new THREE.MeshStandardMaterial({vertexColors:true, roughness:1});
  patch(m,'none',0.95);
  scene.add(new THREE.Mesh(g,m));
}

// ---------- water surface overhead ----------
const surfMat = new THREE.ShaderMaterial({
  uniforms: THREE.UniformsUtils.merge([THREE.UniformsLib.fog, { uSunDir:{value:L.clone().negate()} }]),
  vertexShader: `
    varying vec3 vW;
    #include <fog_pars_vertex>
    void main(){ vec4 wp = modelMatrix*vec4(position,1.0); vW = wp.xyz; vec4 mvPosition = viewMatrix*wp; gl_Position = projectionMatrix*mvPosition;
    #include <fog_vertex>
    }`,
  fragmentShader: `
    uniform float uTime; uniform vec3 uSunDir; varying vec3 vW;
    #include <fog_pars_fragment>
    ${CAUS}
    void main(){
      vec3 vd = normalize(vW - cameraPosition);
      float c = causF(vW.xz/22.0 + vec2(uTime*0.01, 0.0));
      float c2 = causF(vW.xz/9.0 - vec2(0.0, uTime*0.015));
      vec3 col = vec3(0.10,0.46,0.54) + vec3(0.45,0.70,0.62)*c*0.55 + vec3(0.9,0.8,0.5)*c2*0.28;
      float s = max(dot(vd, uSunDir), 0.0);
      col += vec3(1.0,0.86,0.52)*(pow(s,40.0)*1.8 + pow(s,6.0)*0.25);
      gl_FragColor = vec4(col,1.0);
      #include <fog_fragment>
    }`,
  side: THREE.DoubleSide, fog: true
});
surfMat.uniforms.uTime = U.uTime;
const surface = new THREE.Mesh(new THREE.PlaneGeometry(700,700,1,1).rotateX(Math.PI/2), surfMat);
surface.position.y = SURF; scene.add(surface);

// ---------- layout data ----------
const ARCH = [
  {x:18, z:-8, rot:0.4, span:7, h:8},
  {x:-10, z:30, rot:1.6, span:6, h:7.5}
];
const SX=-38, SZ=-34;
function nearShip(x,z,pad){ return Math.hypot(x-SX,z-SZ) < 14+pad; }
function blocked(x,z,pad){
  if(nearShip(x,z,pad)) return true;
  for(const a of ARCH) if(Math.hypot(x-a.x,z-a.z) < a.span+3+pad) return true;
  return false;
}

// demo path (also used to keep boulders off the tour route)
const DP = [[15,15,5],[22.67,3.05,4],[18,-8,3.4],[13.33,-19.05,4],[-8,-34,7],[-24,-42,8],[-38,-52,9],[-54,-38,8],[-50,-16,7],[-36,10,5],[-24,30,3.6],[-10,30,3.1],[4,31,4],[13,27,5]];
const demoCurve = new THREE.CatmullRomCurve3(DP.map(([x,z,h]) => new V3(x, gh(x,z)+h, z)), true, 'centripetal');
const pathPts = demoCurve.getSpacedPoints(300);
function nearPath(x,z,r){ for(const p of pathPts){ if(Math.hypot(p.x-x,p.z-z) < r) return true; } return false; }

// ---------- colliders ----------
const colS = []; // spheres
const colB = []; // oriented boxes
const pendingBoxes = [];
function boxLater(mesh,hx,hy,hz){ pendingBoxes.push([mesh,hx,hy,hz]); }
function finalizeBoxes(){
  scene.updateMatrixWorld(true);
  for(const [m,hx,hy,hz] of pendingBoxes){
    const M = m.matrixWorld.clone();
    const c = new V3().setFromMatrixPosition(M);
    colB.push({m:M, inv:M.clone().invert(), h:new V3(hx,hy,hz), c, br:Math.hypot(hx,hy,hz)});
  }
  pendingBoxes.length = 0;
}

// ---------- rocks & arches ----------
const rockMat = new THREE.MeshStandardMaterial({vertexColors:true, flatShading:true, roughness:0.95});
patch(rockMat,'none',0.55);
const rockGeos = [];
for(let v=0; v<6; v++){
  const g = new THREE.IcosahedronGeometry(1, 2);
  const p = g.attributes.position; const col = new Float32Array(p.count*3);
  const a1=rr(1.5,3.5), a2=rr(1.5,3.5), a3=rr(2,4), o1=rr(0,6), o2=rr(0,6), o3=rr(0,6);
  const v3 = new V3(), c = new THREE.Color();
  for(let i=0;i<p.count;i++){
    v3.fromBufferAttribute(p,i).normalize();
    const n = Math.sin(v3.x*a1+o1)*Math.cos(v3.y*a2+o2) + 0.6*Math.sin(v3.z*a3+v3.x*3.0+o3);
    let f = 0.86 + 0.09*n + 0.03*Math.sin(v3.y*9+v3.z*7);
    f = clamp(f, 0.74, 1.0);
    v3.multiplyScalar(f); p.setXYZ(i, v3.x, v3.y, v3.z);
    c.copy(PAL.deep2).lerp(PAL.teal, 0.2 + 0.35*(v3.y*0.5+0.5) + 0.1*n);
    if(v3.y > 0.5 && n > 0.1) c.lerp(PAL.gold, 0.45);
    else if(v3.y > 0.35 && n < -0.4) c.lerp(PAL.kelp, 0.5);
    col[i*3]=c.r; col[i*3+1]=c.g; col[i*3+2]=c.b;
  }
  g.setAttribute('color', new THREE.BufferAttribute(col,3));
  g.computeVertexNormals();
  rockGeos.push(g);
}
let rockIdx = 0;
function addRock(x,y,z,s){
  const m = new THREE.Mesh(rockGeos[rockIdx++ % rockGeos.length], rockMat);
  m.position.set(x,y,z); m.rotation.set(rand()*6.28, rand()*6.28, rand()*6.28); m.scale.setScalar(s);
  scene.add(m); colS.push({c:new V3(x,y,z), r:s*0.9});
}
for(const A of ARCH){
  const ca=Math.cos(A.rot), sa=Math.sin(A.rot), base=gh(A.x,A.z);
  const N=14;
  for(let k=0;k<=N;k++){
    const a = Math.PI*k/N;
    const lx = Math.cos(a)*A.span, ly = Math.sin(a)*A.h;
    const wx = A.x + lx*ca, wz = A.z - lx*sa;
    addRock(wx, base + ly + 0.3, wz, 2.5 - 0.6*Math.sin(a) + rr(-0.15,0.15));
  }
  for(const s of [-1,1]) for(let j=0;j<3;j++){
    const lx = s*(A.span + rr(-0.3,1.6)), lz = rr(-2.2,2.2);
    const wx = A.x + lx*ca + lz*sa, wz = A.z - lx*sa + lz*ca;
    addRock(wx, gh(wx,wz)+0.1, wz, rr(2.0,2.9));
  }
}
// scattered boulders
{
  let made=0, tries=0;
  while(made<34 && tries<900){
    tries++;
    const x=rr(-88,88), z=rr(-88,88); const s=rr(1.2,3.2);
    if(Math.hypot(x,z)>92 || blocked(x,z,2) || nearPath(x,z,s+3.5) || Math.hypot(x,z-48)<8) continue;
    addRock(x, gh(x,z)-s*0.3, z, s); made++;
    if(rand()<0.4){ const x2=x+rr(-2.5,2.5)*s*0.6, z2=z+rr(-2.5,2.5)*s*0.6, s2=s*rr(0.4,0.7); if(!nearPath(x2,z2,s2+3)) addRock(x2, gh(x2,z2)-s2*0.2, z2, s2); }
  }
}

// ---------- sunken ship ----------
function woodTex(){
  const c=document.createElement('canvas'); c.width=c.height=256; const x=c.getContext('2d');
  x.fillStyle='#8f4e24'; x.fillRect(0,0,256,256);
  for(let i=0;i<16;i++){
    const y=i*16;
    x.fillStyle=`hsl(${18+rand()*10},${48+rand()*15}%,${25+rand()*10}%)`; x.fillRect(0,y,256,15);
    x.fillStyle='#3a1a0a'; x.fillRect(0,y+14.5,256,1.5);
    for(let j=0;j<2;j++) x.fillRect(rand()*256, y, 1.5, 15);
  }
  x.strokeStyle='rgba(55,22,8,0.28)'; x.lineWidth=1;
  for(let i=0;i<300;i++){ const y=rand()*256, x0=rand()*256; x.beginPath(); x.moveTo(x0,y); x.lineTo(x0+10+rand()*40, y+rand()*1.5-0.75); x.stroke(); }
  for(let i=0;i<45;i++){ x.fillStyle=`rgba(31,163,160,${0.08+rand()*0.25})`; x.beginPath(); x.arc(rand()*256, rand()*256, 4+rand()*18, 0, 6.283); x.fill(); }
  for(let i=0;i<20;i++){ x.fillStyle=`rgba(224,176,64,${0.08+rand()*0.18})`; x.beginPath(); x.arc(rand()*256, rand()*256, 2+rand()*7, 0, 6.283); x.fill(); }
  const t=new THREE.CanvasTexture(c); t.wrapS=t.wrapT=THREE.RepeatWrapping; t.colorSpace=THREE.SRGBColorSpace; t.repeat.set(3,1); t.anisotropy=4; return t;
}
const wood = woodTex();
const hullMat = new THREE.MeshStandardMaterial({map:wood, roughness:0.9}); patch(hullMat,'none',0.35);
const darkWood = new THREE.MeshStandardMaterial({map:wood, color:0xb5785a, roughness:0.9}); patch(darkWood,'none',0.3);
const goldMat = new THREE.MeshStandardMaterial({color:PAL.gold, metalness:0.7, roughness:0.35}); patch(goldMat,'none',0.3);
const sailMat = new THREE.MeshStandardMaterial({color:new THREE.Color('#d9b058'), side:THREE.DoubleSide, roughness:1, transparent:true, opacity:0.85}); patch(sailMat,'none',0.3);
const glowMat = new THREE.MeshBasicMaterial({color:new THREE.Color('#ffb24a')});

const ship = new THREE.Group();
ship.position.set(SX, gh(SX,SZ)-1.3, SZ); ship.rotation.set(0.04, 0.7, 0.2); scene.add(ship);
function part(geo, mat, x,y,z, parent, hx,hy,hz, rx=0,ry=0,rz=0){
  const m=new THREE.Mesh(geo,mat); m.position.set(x,y,z); m.rotation.set(rx,ry,rz); parent.add(m);
  if(hx!==undefined && hx!==null) boxLater(m,hx,hy,hz); return m;
}
{
  const hg = new THREE.BoxGeometry(6,3.6,18,6,4,18); const hp = hg.attributes.position;
  for(let i=0;i<hp.count;i++){
    let x=hp.getX(i), y=hp.getY(i), z=hp.getZ(i);
    const t=(y+1.8)/3.6; let sx = 0.5 + 0.5*Math.pow(t,0.7);
    if(z>3){ const k=(z-3)/6; sx *= 1 - 0.88*Math.pow(k,1.6); y += (1-t)*k*1.4; }
    if(z<-7){ sx *= 1 - (-7-z)*0.06; }
    hp.setXYZ(i, x*sx, y, z);
  }
  hg.computeVertexNormals();
  part(hg, hullMat, 0,1.8,0, ship, 3,1.8,9);
  part(new THREE.BoxGeometry(4.6,2.4,4.4), darkWood, 0,4.8,-6, ship, 2.3,1.2,2.2);
  part(new THREE.BoxGeometry(4.8,0.15,4.6), goldMat, 0,6.05,-6, ship);
  for(const wx of [-1.3,0,1.3]) part(new THREE.BoxGeometry(0.55,0.5,0.06), glowMat, wx,4.9,-8.23, ship);
  const mast = part(new THREE.CylinderGeometry(0.3,0.38,13,8), darkWood, 0,3.6+6.5,1.5, ship, 0.4,6.5,0.4, 0,0,0.1);
  const yard = part(new THREE.BoxGeometry(8,0.3,0.3), darkWood, 0,3.5,0, mast, 4,0.2,0.2, 0,0.35,0);
  const sg = new THREE.PlaneGeometry(7,4.2,12,7); const sp = sg.attributes.position;
  for(let i=0;i<sp.count;i++){
    const x=sp.getX(i); let y=sp.getY(i);
    let z = Math.sin((x/7+0.5)*Math.PI)*0.35*(0.5-y/8.4) + (rand()-0.5)*0.08;
    if(y < -1.0) y += rand()*rand()*1.6;
    sp.setXYZ(i, x, y, z);
  }
  sg.computeVertexNormals();
  part(sg, sailMat, 0,-2.2,0.12, yard, 3.5,2.1,0.3);
  part(new THREE.CylinderGeometry(0.9,0.7,0.6,10), darkWood, 0,5.6,0, mast, 0.9,0.3,0.9);
  part(new THREE.CylinderGeometry(0.28,0.34,3.2,8), darkWood, 0,3.6+1.6,5.5, ship, 0.35,1.6,0.35, 0.1,0,-0.15);
  for(const s of [-1,1]) part(new THREE.BoxGeometry(0.18,0.7,12), darkWood, s*2.85,3.95,-2, ship, 0.12,0.35,6);
  part(new THREE.CylinderGeometry(0.18,0.26,6,6), darkWood, 0,3.4,10.5, ship, 0.3,3,0.3, Math.PI/2-0.3,0,0);
  part(new THREE.SphereGeometry(0.45,10,8), goldMat, 0,3.0,9.0, ship);
  // broken mast on the sand
  const bx=-48, bz=-28;
  const bm = new THREE.Mesh(new THREE.CylinderGeometry(0.3,0.36,10,8), darkWood);
  bm.position.set(bx, gh(bx,bz)+0.15, bz); bm.rotation.set(0, 0.3, Math.PI/2); scene.add(bm); boxLater(bm,0.4,5,0.4);
  // barrels
  for(const [x,z] of [[-29,-44],[-27.5,-45.5],[-46,-44]]){
    const b=new THREE.Mesh(new THREE.CylinderGeometry(0.48,0.48,1.1,10), darkWood);
    const y=gh(x,z)+0.45; b.position.set(x,y,z); b.rotation.set(rand()*0.5, rand()*3, rand()<0.5?Math.PI/2:0.1); scene.add(b);
    colS.push({c:new V3(x,y,z), r:0.65});
  }
}
// treasure chest
const CHX=-31, CHZ=-37;
{
  const ch = new THREE.Group(); ch.position.set(CHX, gh(CHX,CHZ)-0.1, CHZ); ch.rotation.y=0.9; scene.add(ch);
  part(new THREE.BoxGeometry(1.4,0.8,0.9), darkWood, 0,0.4,0, ch, 0.7,0.45,0.45);
  part(new THREE.BoxGeometry(1.45,0.12,0.95), goldMat, 0,0.82,0, ch);
  for(const x of [-0.5,0.5]) part(new THREE.BoxGeometry(0.1,0.82,0.94), goldMat, x,0.41,0, ch);
  const lid = part(new THREE.BoxGeometry(1.45,0.3,0.95), darkWood, 0,1.15,-0.62, ch, null,0,0, -1.1,0,0);
  for(let i=0;i<9;i++) part(new THREE.CylinderGeometry(0.12,0.12,0.03,10), goldMat, rr(-0.5,0.5),0.85+rand()*0.05,rr(-0.3,0.3), ch, null,0,0, rr(-0.4,0.4),0,rr(-0.4,0.4));
  for(let i=0;i<7;i++){ const a=rand()*6.28, r=rr(0.9,1.8); part(new THREE.CylinderGeometry(0.12,0.12,0.03,10), goldMat, Math.cos(a)*r,0.12,Math.sin(a)*r, ch, null,0,0, rr(-0.3,0.3),0,rr(-0.3,0.3)); }
  const pl = new THREE.PointLight(0xffb040, 18, 12, 2); pl.position.set(CHX, gh(CHX,CHZ)+1.6, CHZ); scene.add(pl);
}
finalizeBoxes();

// ---------- kelp forest ----------
function kelpGeo(){
  const segs=34, pos=[], idx=[];
  for(let r=0;r<2;r++){
    const base=pos.length/3, rot=r*Math.PI/2;
    for(let i=0;i<=segs;i++){
      const y=i/segs;
      const w = 0.022*(0.5+0.5*Math.abs(Math.sin(y*26+r)))*(1-0.45*y) + 0.003;
      const a = y*5.0 + rot;
      const cx = Math.sin(y*9+r)*0.012;
      const dx=Math.cos(a)*w, dz=Math.sin(a)*w;
      pos.push(cx-dx, y, -dz, cx+dx, y, dz);
    }
    for(let i=0;i<segs;i++){ const a=base+2*i, b=a+1, c=a+2, d=a+3; idx.push(a,b,c, b,d,c); }
  }
  const g=new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(pos,3)); g.setIndex(idx); g.computeVertexNormals(); return g;
}
{
  const KP=[[12,15],[-22,8],[38,22],[-48,8],[8,-40],[42,-28],[-8,-62],[-62,-60],[25,50],[-38,50],[58,2],[0,-14],[-16,-14],[30,-55],[-60,-15],[60,40],[-25,-70],[70,-10]];
  const kel=[];
  for(const [px,pz] of KP){
    const n=40+Math.floor(rand()*30);
    for(let k=0;k<n;k++){
      const r=Math.sqrt(rand())*9, a=rand()*6.283;
      const x=px+Math.cos(a)*r, z=pz+Math.sin(a)*r;
      if(blocked(x,z,1) || Math.hypot(x,z)>96) continue;
      kel.push([x,z,rr(9,21)*(1-r/22)]);
    }
  }
  for(let k=0;k<160;k++){ const x=rr(-90,90), z=rr(-90,90); if(blocked(x,z,1)||Math.hypot(x,z)>95) continue; kel.push([x,z,rr(5,15)]); }
  const mat=new THREE.MeshStandardMaterial({side:THREE.DoubleSide, roughness:0.75}); patch(mat,'kelp',0.25);
  const im=new THREE.InstancedMesh(kelpGeo(), mat, kel.length);
  const dm=new THREE.Object3D(), c=new THREE.Color();
  kel.forEach(([x,z,h],i)=>{
    dm.position.set(x, gh(x,z)-0.3, z); dm.rotation.set(0, rand()*6.283, 0); dm.scale.setScalar(h); dm.updateMatrix();
    im.setMatrixAt(i, dm.matrix);
    c.copy(PAL.kelpD).lerp(PAL.kelpL, rand()); if(rand()<0.25) c.lerp(PAL.gold, 0.25);
    im.setColorAt(i, c);
  });
  im.frustumCulled=false; scene.add(im);
}

// ---------- coral (teal / gold / orange only) ----------
{
  const MAXC=5000, MAXS=2500;
  const coralMat=new THREE.MeshStandardMaterial({roughness:0.8}); patch(coralMat,'none',0.35);
  const cylIM=new THREE.InstancedMesh(new THREE.CylinderGeometry(0.75,1,1,6), coralMat, MAXC);
  const sphIM=new THREE.InstancedMesh(new THREE.IcosahedronGeometry(1,1), coralMat, MAXS);
  const dm=new THREE.Object3D(); let nc=0, ns=0;
  const cols=[PAL.orange, PAL.gold, PAL.teal, PAL.tealL, PAL.orangeL, PAL.orangeD, PAL.goldL];
  const pick=()=>cols[Math.floor(rand()*cols.length)].clone().offsetHSL(rr(-0.015,0.015),0,rr(-0.05,0.05));
  function addCyl(a,b,r,col){
    if(nc>=MAXC) return; const d=new V3().subVectors(b,a); const len=d.length();
    dm.position.copy(a).addScaledVector(d,0.5); dm.quaternion.setFromUnitVectors(UP, d.multiplyScalar(1/len)); dm.scale.set(r,len,r); dm.updateMatrix();
    cylIM.setMatrixAt(nc,dm.matrix); cylIM.setColorAt(nc,col); nc++;
  }
  function addSph(p,sx,sy,sz,ry,col){
    if(ns>=MAXS) return; dm.position.copy(p); dm.quaternion.setFromEuler(new THREE.Euler(0,ry,0)); dm.scale.set(sx,sy,sz); dm.updateMatrix();
    sphIM.setMatrixAt(ns,dm.matrix); sphIM.setColorAt(ns,col); ns++;
  }
  function branch(p,dir,len,r,depth,col){
    const e=p.clone().addScaledVector(dir,len); addCyl(p,e,r,col);
    if(depth===0){ addSph(e,r*1.5,r*1.5,r*1.5,0,col); return; }
    const n=2+(rand()<0.4?1:0);
    for(let k=0;k<n;k++){
      const nd=dir.clone().add(new V3(rand()-0.5, rand()*0.3, rand()-0.5).multiplyScalar(1.2)).addScaledVector(UP,0.35).normalize();
      branch(e,nd,len*0.78,r*0.72,depth-1,col);
    }
  }
  function cluster(cx,cz){
    const nb=1+Math.floor(rand()*3);
    for(let b=0;b<nb;b++){ const x=cx+rr(-2,2), z=cz+rr(-2,2); branch(new V3(x,gh(x,z)-0.1,z), new V3(rr(-0.2,0.2),1,rr(-0.2,0.2)).normalize(), rr(0.5,0.9), rr(0.09,0.14), 3, pick()); }
    if(rand()<0.7){ const x=cx+rr(-2,2), z=cz+rr(-2,2), s=rr(0.5,1.0); addSph(new V3(x,gh(x,z)+0.05,z), s, s*0.6, s, rand()*6, pick()); }
    if(rand()<0.6){ const x=cx+rr(-2,2), z=cz+rr(-2,2), s=rr(0.8,1.3); const c=rand()<0.5?PAL.orange.clone():PAL.gold.clone(); addSph(new V3(x,gh(x,z)+s*0.95,z), s, s*1.15, 0.06, rand()*6, c); addCyl(new V3(x,gh(x,z)-0.1,z), new V3(x,gh(x,z)+0.3,z), 0.08, c); }
    if(rand()<0.5){ const c=pick(); const n=3+Math.floor(rand()*3); for(let k=0;k<n;k++){ const x=cx+rr(-1,1), z=cz+rr(-1,1), y=gh(x,z)-0.1, h=rr(0.5,1.3); addCyl(new V3(x,y,z), new V3(x+rr(-0.1,0.1),y+h,z+rr(-0.1,0.1)), 0.13, c); } }
  }
  for(const A of ARCH) for(let k=0;k<7;k++){ const a=rand()*6.283, r=rr(A.span-1, A.span+6); cluster(A.x+Math.cos(a)*r, A.z+Math.sin(a)*r); }
  for(let k=0;k<6;k++){ const a=rand()*6.283, r=rr(12,17); cluster(SX+Math.cos(a)*r, SZ+Math.sin(a)*r); }
  for(let k=0;k<55;k++){ const x=rr(-85,85), z=rr(-85,85); if(nearShip(x,z,1)||Math.hypot(x,z)>90) continue; cluster(x,z); }
  cylIM.count=nc; sphIM.count=ns; scene.add(cylIM); scene.add(sphIM);
}

// ---------- fish schools ----------
function fishGeo(){
  const N=[0,0,0.55], T=[0,0.2,0.05], B=[0,-0.16,0.05], Lf=[-0.09,0.01,0.1], R=[0.09,0.01,0.1], K=[0,0.02,-0.32], TT=[0,0.22,-0.62], TB=[0,-0.18,-0.6], D=[0,0.31,-0.12];
  const tris=[N,T,Lf, N,Lf,B, N,B,R, N,R,T, K,Lf,T, K,B,Lf, K,R,B, K,T,R, K,TT,TB, T,D,K];
  const g=new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(tris.flat(),3)); g.computeVertexNormals(); return g;
}
const schools=[], fish=[];
{
  const defs=[[45,'orange',0.8],[35,'gold',0.9],[50,'teal',0.6],[30,'orange',1.2],[40,'gold',0.7],[30,'teal',1.0],[25,'mix',1.1]];
  for(const [n,kind,sc] of defs){
    let x,z,t=0; do{ x=rr(-60,60); z=rr(-60,60); t++; } while((blocked(x,z,4)) && t<50);
    const yaw=rand()*6.283;
    const s={c:new V3(x,gh(x,z)+rr(4,10),z), yaw, ty:rr(3,12), target:yaw, speed:rr(2.2,3.4), size:2+n*0.05, next:rr(3,8)};
    schools.push(s);
    for(let k=0;k<n;k++){
      let ox,oy,oz; do{ ox=rand()*2-1; oy=rand()*2-1; oz=rand()*2-1; } while(ox*ox+oy*oy+oz*oz>1);
      let col;
      if(kind==='orange') col=PAL.orange.clone().lerp(PAL.orangeL,rand()*0.6);
      else if(kind==='gold') col=PAL.gold.clone().lerp(PAL.goldL,rand()*0.6);
      else if(kind==='teal') col=PAL.teal.clone().lerp(PAL.tealL,rand()*0.7);
      else col=(rand()<0.5?PAL.orange:PAL.gold).clone();
      fish.push({s, o:new V3(ox*s.size, oy*s.size*0.5, oz*s.size*1.3), rate:rr(1.5,3.5), ph:rand()*6.28,
        p:s.c.clone(), d:new V3(Math.sin(yaw),0,Math.cos(yaw)), sc:sc*rr(0.85,1.15), col});
    }
  }
}
const fishMat=new THREE.MeshStandardMaterial({side:THREE.DoubleSide, roughness:0.45, metalness:0.25, flatShading:true}); patch(fishMat,'fish',0.3);
const fishIM=new THREE.InstancedMesh(fishGeo(), fishMat, fish.length);
fish.forEach((f,i)=>fishIM.setColorAt(i,f.col));
fishIM.frustumCulled=false; scene.add(fishIM);

// ---------- manta rays ----------
function mantaGeo(){
  const s=new THREE.Shape();
  s.moveTo(0,1.3); s.quadraticCurveTo(1.0,1.0,2.9,-0.3); s.quadraticCurveTo(1.6,-0.5,0.6,-1.1);
  s.lineTo(0,-0.9); s.lineTo(-0.6,-1.1); s.quadraticCurveTo(-1.6,-0.5,-2.9,-0.3); s.quadraticCurveTo(-1.0,1.0,0,1.3);
  const g=new THREE.ShapeGeometry(s,12); g.rotateX(Math.PI/2);
  const p=g.attributes.position, col=new Float32Array(p.count*3), c=new THREE.Color();
  for(let i=0;i<p.count;i++){ const ax=Math.abs(p.getX(i))/2.9; c.copy(PAL.deep).lerp(PAL.deep2,0.5).lerp(PAL.teal, Math.pow(ax,1.6)*0.6); col[i*3]=c.r; col[i*3+1]=c.g; col[i*3+2]=c.b; }
  g.setAttribute('color', new THREE.BufferAttribute(col,3)); g.computeVertexNormals(); return g;
}
const mantas=[];
{
  const mg=mantaGeo();
  const defs=[{cx:0,cz:0,R:24,h:14,w:0.11,ph:0},{cx:5,cz:-5,R:34,h:18,w:-0.08,ph:2.1},{cx:20,cz:30,R:22,h:12,w:0.13,ph:4.2}];
  for(const d of defs){
    const mat=new THREE.MeshStandardMaterial({vertexColors:true, side:THREE.DoubleSide, roughness:0.7}); mat.userData.phase=d.ph; patch(mat,'manta',0.3);
    const m=new THREE.Mesh(mg,mat); m.scale.setScalar(rr(1.6,2.1));
    const body=new THREE.Mesh(new THREE.SphereGeometry(1,12,8), mat); body.scale.set(0.5,0.2,1.0); body.position.z=0.1; m.add(body);
    const tail=new THREE.Mesh(new THREE.ConeGeometry(0.05,2.4,4).rotateX(-Math.PI/2), mat); tail.position.z=-2.0; m.add(tail);
    for(const s of [-1,1]){ const h=new THREE.Mesh(new THREE.BoxGeometry(0.12,0.05,0.5), mat); h.position.set(s*0.35,0,1.35); h.rotation.y=-s*0.3; m.add(h); }
    m.frustumCulled=false; scene.add(m); mantas.push({m,d});
  }
}

// ---------- sunbeams ----------
const beams=[]; const G=80;
const BLEN=(SURF+4)/(-L.y);
const BUP=L.clone().negate();
{
  const geo=new THREE.PlaneGeometry(1,1).translate(0,-0.5,0);
  for(let i=0;i<16;i++){
    const mat=new THREE.ShaderMaterial({
      uniforms:{uTime:U.uTime, uSeed:{value:rand()}, uOp:{value:0}},
      vertexShader:`varying vec2 vUv; varying float vD; void main(){ vUv=uv; vec4 wp=modelMatrix*vec4(position,1.0); vD=distance(wp.xyz,cameraPosition); gl_Position=projectionMatrix*viewMatrix*wp; }`,
      fragmentShader:`uniform float uTime; uniform float uSeed; uniform float uOp; varying vec2 vUv; varying float vD;
        void main(){ float e=sin(vUv.x*3.14159); e*=e; float l=smoothstep(0.0,0.75,vUv.y);
          float fl=0.55+0.45*sin(uTime*0.5+uSeed*6.0)*sin(uTime*0.27+uSeed*3.1);
          float f=exp(-vD*0.028)*smoothstep(2.0,9.0,vD);
          gl_FragColor=vec4(vec3(0.95,0.86,0.58), e*l*fl*f*uOp); }`,
      transparent:true, depthWrite:false, blending:THREE.AdditiveBlending, side:THREE.DoubleSide
    });
    const m=new THREE.Mesh(geo,mat); m.matrixAutoUpdate=false; m.frustumCulled=false; scene.add(m);
    beams.push({m, mat, bx:rand()*G, bz:rand()*G, w:rr(2,6), op:rr(0.25,0.5)});
  }
}

// ---------- particles: bubbles & marine snow ----------
const PU={uScale:{value:500}};
const ptV=`attribute float aSize; uniform float uScale; uniform float uDens; varying float vFog;
  void main(){ vec4 mv=modelViewMatrix*vec4(position,1.0); float d=max(-mv.z,0.1); gl_PointSize=min(aSize*uScale/d, 80.0); gl_Position=projectionMatrix*mv; vFog=1.0-exp(-uDens*uDens*d*d); }`;
const ptF=`uniform vec3 uFogC; uniform vec3 uCol; uniform float uKind; varying float vFog;
  void main(){ vec2 q=gl_PointCoord-0.5; float d=length(q); if(d>0.5) discard; float a;
    if(uKind<0.5){ float rim=smoothstep(0.30,0.46,d)*(1.0-smoothstep(0.46,0.5,d)); float hl=1.0-smoothstep(0.0,0.12,length(q-vec2(-0.14,-0.14))); a=0.15*(1.0-smoothstep(0.45,0.5,d))+0.8*rim+0.9*hl; }
    else { a=(1.0-smoothstep(0.0,0.5,d))*0.75; }
    vec3 c=linearToOutputTexel(vec4(uCol,1.0)).rgb; c=mix(c,uFogC,vFog);
    gl_FragColor=vec4(c, clamp(a,0.0,1.0)*(1.0-vFog*0.9)); }`;
function pointsMat(kind,col){
  return new THREE.ShaderMaterial({uniforms:{uScale:PU.uScale, uDens:{value:scene.fog.density}, uFogC:{value:scene.fog.color}, uCol:{value:new THREE.Color(col)}, uKind:{value:kind}},
    vertexShader:ptV, fragmentShader:ptF, transparent:true, depthWrite:false});
}
// bubble sources
const bsrc=[];
{
  const v=new V3();
  for(const p of [[0,3.7,3],[1,3.7,-2],[-0.5,6.1,-6],[0,1.5,8]]){ v.set(...p); ship.localToWorld(v); bsrc.push({x:v.x,y:v.y,z:v.z,sp:0.25}); }
  bsrc.push({x:CHX,y:gh(CHX,CHZ)+0.8,z:CHZ,sp:0.2});
  for(const A of ARCH){ const ca=Math.cos(A.rot), sa=Math.sin(A.rot); for(const s of [-1,1]){ const wx=A.x+s*(A.span-1)*ca, wz=A.z-s*(A.span-1)*sa; bsrc.push({x:wx,y:gh(wx,wz)+0.2,z:wz,sp:0.4}); } }
  let k=0; while(k<7){ const x=rr(-70,70), z=rr(-70,70); if(blocked(x,z,1)) continue; bsrc.push({x,y:gh(x,z),z,sp:0.3}); k++; }
}
const NB=480;
const bubbles=[]; const bPos=new Float32Array(NB*3), bSize=new Float32Array(NB);
for(let i=0;i<NB;i++){ const s=bsrc[i%bsrc.length]; const b={s, x:s.x, y:s.y+rand()*(SURF-s.y), z:s.z, v:rr(1.2,2.4), ph:rand()*6.28, sp:rr(0.2,0.6)}; bubbles.push(b); bSize[i]=rr(0.12,0.42); }
const bGeo=new THREE.BufferGeometry(); bGeo.setAttribute('position', new THREE.BufferAttribute(bPos,3)); bGeo.setAttribute('aSize', new THREE.BufferAttribute(bSize,1));
const bPts=new THREE.Points(bGeo, pointsMat(0,'#d6f5ef')); bPts.frustumCulled=false; scene.add(bPts);

const NS=1200, SB=50;
const sBase=new Float32Array(NS*3), sPos=new Float32Array(NS*3), sSize=new Float32Array(NS);
for(let i=0;i<NS;i++){ sBase[i*3]=rand()*SB; sBase[i*3+1]=rand()*SB; sBase[i*3+2]=rand()*SB; sSize[i]=rr(0.05,0.13); }
const sGeo=new THREE.BufferGeometry(); sGeo.setAttribute('position', new THREE.BufferAttribute(sPos,3)); sGeo.setAttribute('aSize', new THREE.BufferAttribute(sSize,1));
const sPts=new THREE.Points(sGeo, pointsMat(1,'#f2e3b8')); sPts.frustumCulled=false; scene.add(sPts);

// ---------- player & controls ----------
const player={p:new V3(0, gh(0,48)+5, 48), v:new V3(), yaw:0, pitch:-0.05, roll:0, prevYaw:0};
let ptr=null, holding=false, rise=0;
let demo = location.hash === '#demo';
const demoEl=document.getElementById('demo'), hintEl=document.getElementById('hint');
let hintHidden=false;
function interacted(){ if(!hintHidden){ hintHidden=true; setTimeout(()=>{ hintEl.style.opacity='0'; }, 3500); } }

canvas.addEventListener('pointerdown', e=>{
  if(ptr) return;
  ptr={id:e.pointerId, x:e.clientX, y:e.clientY}; holding=true;
  try{ canvas.setPointerCapture(e.pointerId); }catch(_){}
  interacted(); e.preventDefault();
});
canvas.addEventListener('pointermove', e=>{
  if(!ptr || e.pointerId!==ptr.id) return;
  const dx=e.clientX-ptr.x, dy=e.clientY-ptr.y; ptr.x=e.clientX; ptr.y=e.clientY;
  if(demo) return;
  player.yaw -= dx*0.0055;
  player.pitch = clamp(player.pitch - dy*0.0045, -1.2, 1.2);
});
function endPtr(e){ if(ptr && e.pointerId===ptr.id){ ptr=null; holding=false; } }
canvas.addEventListener('pointerup', endPtr);
canvas.addEventListener('pointercancel', endPtr);
canvas.addEventListener('lostpointercapture', endPtr);
canvas.addEventListener('contextmenu', e=>e.preventDefault());

function setupBtn(el, dir){
  const off=()=>{ if(rise===dir) rise=0; el.classList.remove('on'); };
  el.addEventListener('pointerdown', e=>{ e.stopPropagation(); e.preventDefault(); rise=dir; el.classList.add('on'); try{ el.setPointerCapture(e.pointerId); }catch(_){} interacted(); });
  el.addEventListener('pointerup', off); el.addEventListener('pointercancel', off); el.addEventListener('lostpointercapture', off);
  el.addEventListener('contextmenu', e=>e.preventDefault());
}
setupBtn(document.getElementById('up'), 1);
setupBtn(document.getElementById('dn'), -1);

const tmpM=new THREE.Matrix4(), tq=new THREE.Quaternion();
function endDemo(){
  if(!demo) return; demo=false; demoEl.style.display='none';
  const dir=new V3(0,0,-1).applyQuaternion(camera.quaternion);
  player.yaw=Math.atan2(-dir.x,-dir.z); player.prevYaw=player.yaw; player.pitch=clamp(Math.asin(clamp(dir.y,-1,1)),-1.2,1.2); player.roll=0;
  player.p.copy(camera.position); player.v.set(0,0,0);
  collide(player.p, player.v, 0.8); collide(player.p, player.v, 0.8);
}
window.addEventListener('pointerdown', e=>{ if(e.isTrusted && demo) endDemo(); }, true);
window.addEventListener('touchstart', e=>{ if(e.isTrusted && demo) endDemo(); }, {capture:true, passive:true});
window.addEventListener('hashchange', ()=>{ if(location.hash==='#demo' && !demo){ demo=true; demoT=0; demoEl.style.display='block'; } });
if(demo) demoEl.style.display='block';

// ---------- collision ----------
const lp=new V3(), pb=new V3(), nrm=new V3();
function collide(p,v,r){
  for(const s of colS){
    const dx=p.x-s.c.x, dy=p.y-s.c.y, dz=p.z-s.c.z, R=s.r+r, d2=dx*dx+dy*dy+dz*dz;
    if(d2<R*R){
      const d=Math.sqrt(d2)||1e-4; nrm.set(dx/d,dy/d,dz/d);
      p.set(s.c.x+nrm.x*R, s.c.y+nrm.y*R, s.c.z+nrm.z*R);
      const vn=v.dot(nrm); if(vn<0) v.addScaledVector(nrm,-vn);
    }
  }
  for(const b of colB){
    if(p.distanceTo(b.c) > b.br + r) continue;
    lp.copy(p).applyMatrix4(b.inv); const h=b.h;
    const cx=clamp(lp.x,-h.x,h.x), cy=clamp(lp.y,-h.y,h.y), cz=clamp(lp.z,-h.z,h.z);
    const dx=lp.x-cx, dy=lp.y-cy, dz=lp.z-cz, d2=dx*dx+dy*dy+dz*dz;
    if(d2>=r*r) continue;
    if(d2>1e-8){ const d=Math.sqrt(d2); lp.set(cx+dx/d*r, cy+dy/d*r, cz+dz/d*r); }
    else {
      const px=h.x-Math.abs(lp.x), py=h.y-Math.abs(lp.y), pz=h.z-Math.abs(lp.z);
      if(px<=py && px<=pz) lp.x=Math.sign(lp.x||1)*(h.x+r);
      else if(py<=pz) lp.y=Math.sign(lp.y||1)*(h.y+r);
      else lp.z=Math.sign(lp.z||1)*(h.z+r);
    }
    pb.copy(p); lp.applyMatrix4(b.m); p.copy(lp);
    nrm.subVectors(p,pb); const nl=nrm.length();
    if(nl>1e-6){ nrm.multiplyScalar(1/nl); const vn=v.dot(nrm); if(vn<0) v.addScaledVector(nrm,-vn); }
  }
}

// ---------- updates ----------
const F=new V3();
let T=0, demoT=0; const DUR=22;
function updatePlayer(dt){
  const P=player, cp=Math.cos(P.pitch);
  F.set(-Math.sin(P.yaw)*cp, Math.sin(P.pitch), -Math.cos(P.yaw)*cp);
  if(holding) P.v.addScaledVector(F, 10*dt);
  if(rise) P.v.y += rise*8*dt;
  P.v.multiplyScalar(Math.exp(-1.7*dt));
  const sp=P.v.length(); if(sp>7) P.v.multiplyScalar(7/sp);
  P.p.addScaledVector(P.v, dt);
  collide(P.p,P.v,0.8); collide(P.p,P.v,0.8);
  const d=Math.hypot(P.p.x,P.p.z); if(d>100){ P.p.x*=100/d; P.p.z*=100/d; }
  const g=gh(P.p.x,P.p.z)+1.3; if(P.p.y<g){ P.p.y=g; if(P.v.y<0) P.v.y=0; }
  if(P.p.y>SURF-1.8){ P.p.y=SURF-1.8; if(P.v.y>0) P.v.y=0; }
  const yv=(P.yaw-P.prevYaw)/Math.max(dt,1e-3); P.prevYaw=P.yaw;
  P.roll += (clamp(yv*0.05,-0.16,0.16)-P.roll)*Math.min(1,dt*3);
  camera.position.copy(P.p); camera.position.y += Math.sin(T*1.1)*0.06;
  camera.rotation.set(P.pitch, P.yaw, P.roll, 'YXZ');
}
function updateDemo(dt){
  demoT+=dt; const u=(demoT%DUR)/DUR;
  const p=demoCurve.getPointAt(u), a=demoCurve.getPointAt((u+0.018)%1);
  p.y=Math.max(p.y, gh(p.x,p.z)+1.5);
  camera.position.copy(p);
  tmpM.lookAt(p,a,UP); tq.setFromRotationMatrix(tmpM);
  if(demoT<0.05) camera.quaternion.copy(tq); else camera.quaternion.slerp(tq, 1-Math.exp(-dt*2.5));
}
function updateFog(){
  const k=clamp(camera.position.y/SURF,0,1);
  scene.fog.color.copy(FOG_DEEP).lerp(FOG_SHAL, k*0.8);
}
const dmF=new THREE.Object3D(), tv=new V3();
function updateFish(dt){
  const cam=camera.position;
  for(const s of schools){
    s.next-=dt;
    if(s.next<=0){ s.target=s.yaw+(rand()<0.5?-1:1)*rr(0.8,2.3); s.next=rr(4,9); s.ty=rr(3,13); }
    const dx0=Math.sin(s.yaw), dz0=Math.cos(s.yaw);
    let ax=0, az=0;
    const look=s.c.x+dx0*4, lookz=s.c.z+dz0*4;
    for(const c of colS){
      const dx=look-c.c.x, dz=lookz-c.c.z, d=Math.hypot(dx,dz)+1e-3, lim=c.r+3+s.size*0.6;
      if(d<lim && Math.abs(s.c.y-c.c.y)<c.r+4){ ax+=dx/d*(lim-d); az+=dz/d*(lim-d); }
    }
    { const dx=look-SX, dz=lookz-SZ, d=Math.hypot(dx,dz)+1e-3, lim=15; if(d<lim){ ax+=dx/d*(lim-d)*1.5; az+=dz/d*(lim-d)*1.5; } }
    { const dx=s.c.x-cam.x, dz=s.c.z-cam.z, d=Math.hypot(dx,dz)+1e-3; if(d<9 && Math.abs(s.c.y-cam.y)<6){ ax+=dx/d*(9-d)*2; az+=dz/d*(9-d)*2; } }
    const d0=Math.hypot(s.c.x,s.c.z); if(d0>65){ ax-=s.c.x/d0*(d0-65)*0.6; az-=s.c.z/d0*(d0-65)*0.6; }
    if(ax||az){ const ay=Math.atan2(dx0+ax*0.5, dz0+az*0.5); s.target = s.yaw + angDiff(ay, s.yaw); }
    const diff=angDiff(s.target,s.yaw), step=1.1*dt;
    s.yaw += clamp(diff,-step,step);
    s.c.x += Math.sin(s.yaw)*s.speed*dt; s.c.z += Math.cos(s.yaw)*s.speed*dt;
    const tyw=Math.min(gh(s.c.x,s.c.z)+s.ty, SURF-5);
    s.c.y += (tyw-s.c.y)*Math.min(1,dt*0.4);
  }
  for(let i=0;i<fish.length;i++){
    const f=fish[i], s=f.s, cy=Math.cos(s.yaw), sy=Math.sin(s.yaw);
    const wx=f.o.x*cy + f.o.z*sy, wz=-f.o.x*sy + f.o.z*cy;
    tv.set(s.c.x+wx+Math.sin(T*0.7+f.ph)*0.25, s.c.y+f.o.y+Math.sin(T*0.9+f.ph*1.3)*0.2, s.c.z+wz+Math.cos(T*0.6+f.ph)*0.25);
    pb.copy(f.p);
    f.p.lerp(tv, 1-Math.exp(-f.rate*dt));
    const gy=gh(f.p.x,f.p.z)+0.6; if(f.p.y<gy) f.p.y=gy;
    nrm.subVectors(f.p,pb);
    if(nrm.lengthSq()>1e-8){ nrm.normalize(); f.d.lerp(nrm, 1-Math.exp(-6*dt)).normalize(); }
    dmF.position.copy(f.p); tv.copy(f.p).add(f.d); dmF.lookAt(tv); dmF.scale.setScalar(f.sc); dmF.updateMatrix();
    fishIM.setMatrixAt(i, dmF.matrix);
  }
  fishIM.instanceMatrix.needsUpdate=true;
}
function updateMantas(){
  for(const {m,d} of mantas){
    const th=d.ph+d.w*T, th2=th+d.w*0.3;
    m.position.set(d.cx+d.R*Math.cos(th), d.h+Math.sin(th*3)*1.2, d.cz+d.R*Math.sin(th));
    tv.set(d.cx+d.R*Math.cos(th2), d.h+Math.sin(th2*3)*1.2, d.cz+d.R*Math.sin(th2));
    m.lookAt(tv); m.rotateZ(Math.sign(d.w)*0.22);
  }
}
const bTop=new V3(), bMid=new V3(), bTc=new V3(), bX=new V3(), bS=new V3();
function updateBeams(){
  const cam=camera.position;
  for(const b of beams){
    const ox=((b.bx-cam.x)%G + G*1.5)%G - G/2, oz=((b.bz-cam.z)%G + G*1.5)%G - G/2;
    bTop.set(cam.x+ox, SURF, cam.z+oz);
    bMid.copy(bTop).addScaledVector(L, BLEN*0.5);
    bTc.subVectors(cam,bMid); bTc.addScaledVector(BUP, -bTc.dot(BUP));
    if(bTc.lengthSq()<1e-6) bTc.set(1,0,0); bTc.normalize();
    bX.crossVectors(BUP,bTc);
    b.m.matrix.makeBasis(bX,BUP,bTc); b.m.matrix.scale(bS.set(b.w,BLEN,1)); b.m.matrix.setPosition(bTop);
    b.m.matrixWorldNeedsUpdate=true;
    const e=clamp((G/2-Math.max(Math.abs(ox),Math.abs(oz)))/12,0,1);
    b.mat.uniforms.uOp.value=b.op*e;
  }
}
function updateBubbles(dt){
  for(let i=0;i<NB;i++){
    const b=bubbles[i];
    b.v=Math.min(b.v+dt*0.15, 3.0);
    b.y+=b.v*dt;
    b.x+=Math.sin(T*2.1+b.ph)*0.35*dt; b.z+=Math.cos(T*1.7+b.ph)*0.35*dt;
    if(b.y>SURF-0.3){ const s=b.s; b.x=s.x+rr(-s.sp,s.sp); b.z=s.z+rr(-s.sp,s.sp); b.y=s.y-rand()*5; b.v=rr(1.2,2.2); }
    bPos[i*3]=b.x; bPos[i*3+1]=b.y; bPos[i*3+2]=b.z;
  }
  bGeo.attributes.position.needsUpdate=true;
}
function updateSnow(){
  const c=camera.position, h=SB/2;
  for(let i=0;i<NS;i++){
    const bx=sBase[i*3]+T*0.15, by=sBase[i*3+1]-T*0.12, bz=sBase[i*3+2]+Math.sin(T*0.2+i)*0.5;
    sPos[i*3]  =c.x+(((bx-c.x)%SB+SB*1.5)%SB)-h;
    sPos[i*3+1]=c.y+(((by-c.y)%SB+SB*1.5)%SB)-h;
    sPos[i*3+2]=c.z+(((bz-c.z)%SB+SB*1.5)%SB)-h;
  }
  sGeo.attributes.position.needsUpdate=true;
}

// ---------- resize ----------
const dbs=new THREE.Vector2();
function onResize(){
  renderer.setSize(innerWidth, innerHeight);
  camera.aspect=innerWidth/innerHeight; camera.updateProjectionMatrix();
  renderer.getDrawingBufferSize(dbs);
  PU.uScale.value = dbs.y/(2*Math.tan(THREE.MathUtils.degToRad(camera.fov)/2));
}
window.addEventListener('resize', onResize); onResize();

// ---------- loop ----------
const clock=new THREE.Clock();
renderer.setAnimationLoop(()=>{
  const dt=Math.min(clock.getDelta(),0.05); T+=dt; U.uTime.value=T;
  if(demo) updateDemo(dt); else updatePlayer(dt);
  updateFog(); updateFish(dt); updateMantas(); updateBeams(); updateBubbles(dt); updateSnow();
  surface.position.x=camera.position.x; surface.position.z=camera.position.z;
  renderer.render(scene,camera);
});
</script>
</body>
</html>