Skip to content
VibeCodeBench
Back to the app

The code

Swim the Kelp Garden by Claude Sonnet 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.)31.0 KB · 257 lines · loads cdnjs.cloudflare.com/ajax/libs/three.js/r128/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,viewport-fit=cover">
<title>Kelp Garden Swim</title>
<style>
html,body{margin:0;height:100%;overflow:hidden;background:#0b4260;font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;color:#fff2cf;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent;touch-action:none}
canvas{position:fixed;left:0;top:0;width:100%;height:100%;display:block;touch-action:none}
#ui{position:fixed;left:0;right:0;bottom:0;display:flex;gap:12px;justify-content:center;padding:14px 16px calc(14px + env(safe-area-inset-bottom));pointer-events:none}
button{pointer-events:auto;min-width:120px;min-height:58px;padding:0 22px;border-radius:30px;border:2px solid rgba(255,214,130,.75);background:rgba(8,52,72,.62);color:#ffe9b0;font:600 18px system-ui,sans-serif;-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);touch-action:manipulation;cursor:pointer}
button.on{background:rgba(245,160,60,.9);color:#2a1604;border-color:#ffd77a}
#hint{position:fixed;left:0;right:0;top:calc(18px + env(safe-area-inset-top));text-align:center;font-size:17px;line-height:1.45;text-shadow:0 1px 8px #04202f,0 0 2px #04202f;pointer-events:none;transition:opacity 1.6s;padding:0 18px;box-sizing:border-box}
#hint b{display:block;font-size:24px;letter-spacing:.1em;margin-bottom:4px;color:#ffd77a}
#hint small{opacity:.8;font-size:14px}
#fade{position:fixed;left:0;top:0;right:0;bottom:0;background:#06283b;opacity:0;pointer-events:none}
</style></head><body>
<canvas id="c"></canvas>
<div id="hint"></div>
<div id="fade"></div>
<div id="ui"><button id="bTour">Auto tour</button><button id="bSnd">Sound: off</button></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
(function(){
'use strict';
const $=id=>document.getElementById(id);
const hint=$('hint'),fadeEl=$('fade'),cv=$('c'),bTour=$('bTour'),bSnd=$('bSnd');
if(!window.THREE){hint.textContent='three.js could not be loaded.';return;}
let renderer;
try{renderer=new THREE.WebGLRenderer({canvas:cv,antialias:true});}catch(e){hint.textContent='WebGL is not available in this browser.';return;}
const PI=Math.PI,clamp=(v,a,b)=>Math.max(a,Math.min(b,v)),C=h=>new THREE.Color(h);
let sd=20261122;const rnd=()=>{sd=(Math.imul(sd,1664525)+1013904223)>>>0;return sd/4294967296;};
const R=(a,b)=>a+(b-a)*rnd();
const _o=new THREE.Vector3(),_up=new THREE.Vector3(0,1,0),_z=new THREE.Vector3(0,0,1),_a=new THREE.Vector3(),_b=new THREE.Vector3(),_s=new THREE.Vector3(),_m=new THREE.Matrix4(),_q=new THREE.Quaternion(),_qr=new THREE.Quaternion();
let tw=0;
const SY=36,scene=new THREE.Scene(),U={uTime:{value:0}};
const cDeep=C(0x072c4a),cShal=C(0x1a8a98);
scene.fog=new THREE.FogExp2(0x0b4260,.017);scene.background=new THREE.Color(0x0b4260);
const cam=new THREE.PerspectiveCamera(68,1,.1,500);cam.rotation.order='YXZ';
scene.add(new THREE.HemisphereLight(0x7fe0d6,0xc98a40,.95));
const sun=new THREE.DirectionalLight(0xffe0a0,1.15);sun.position.set(.4,1,.3);scene.add(sun);

/* ---------- shared shader bits ---------- */
const CAUS='float caustic(vec2 p,float t){vec2 i=p;float c=1.;for(int n=0;n<4;n++){float tt=t*(1.-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./length(vec2(p.x*.005/sin(i.x+tt),p.y*.005/cos(i.y+tt)));}c/=4.;c=1.17-pow(c,1.4);return pow(abs(c),8.);}';
function caust(m){m.onBeforeCompile=s=>{s.uniforms.uTime=U.uTime;
 s.vertexShader=s.vertexShader.replace('#include <common>','#include <common>\nvarying vec3 vCW;varying vec3 vWN;').replace('#include <project_vertex>','#include <project_vertex>\nvCW=(modelMatrix*vec4(transformed,1.)).xyz;vWN=normalize(mat3(modelMatrix)*normal);');
 s.fragmentShader=s.fragmentShader.replace('#include <common>','#include <common>\nvarying vec3 vCW;varying vec3 vWN;uniform float uTime;\n'+CAUS).replace('#include <fog_fragment>','float cs=caustic(mod(vCW.xz*.3,6.28318)-250.,uTime*.5+23.);gl_FragColor.rgb+=vec3(1.,.82,.5)*cs*.7*clamp(abs(vWN.y)*.8+.2,0.,1.);\n#include <fog_fragment>');};return m;}
function merge(parts){const P=[],N=[],Cl=[];for(const [g0,m,c] of parts){const g=g0.index?g0.toNonIndexed():g0;g.applyMatrix4(m);const p=g.attributes.position.array,n=g.attributes.normal.array;for(let i=0;i<p.length;i++){P.push(p[i]);N.push(n[i]);}for(let i=0;i<p.length/3;i++)Cl.push(c.r,c.g,c.b);}
 const r=new THREE.BufferGeometry();r.setAttribute('position',new THREE.Float32BufferAttribute(P,3));r.setAttribute('normal',new THREE.Float32BufferAttribute(N,3));r.setAttribute('color',new THREE.Float32BufferAttribute(Cl,3));return r;}

/* ---------- seabed ---------- */
const gY=(x,z)=>2.4*Math.sin(x*.045+1.3)*Math.cos(z*.04)+1.2*Math.sin(x*.11+z*.09)+.5*Math.sin(x*.27-z*.21);
{const tg=new THREE.PlaneGeometry(380,380,170,170);tg.rotateX(-PI/2);
const tp=tg.attributes.position,tcol=new Float32Array(tp.count*3),sa=C(0xd8a950),sb=C(0xe59a4a),sc=C(0x4a9a8a),c=new THREE.Color();
for(let i=0;i<tp.count;i++){const x=tp.getX(i),z=tp.getZ(i),h=gY(x,z);tp.setY(i,h);const n=.5+.5*Math.sin(x*.7)*Math.sin(z*.63+x*.1);c.copy(sc).lerp(sa,.35+.65*clamp((h+4)/8,0,1)).lerp(sb,n*.3);tcol[i*3]=c.r;tcol[i*3+1]=c.g;tcol[i*3+2]=c.b;}
tg.setAttribute('color',new THREE.BufferAttribute(tcol,3));tg.computeVertexNormals();
scene.add(new THREE.Mesh(tg,caust(new THREE.MeshLambertMaterial({vertexColors:true}))));}

/* ---------- rocks, arches, ship (with colliders) ---------- */
const COL=[],solid=caust(new THREE.MeshLambertMaterial({vertexColors:true,side:THREE.DoubleSide}));
const rockPal=[0x1f6a73,0x1a4d78,0x2b7f86,0x2d5d86];
function mkRock(r,s){const g=new THREE.IcosahedronGeometry(r,2),p=g.attributes.position,n=p.count,col=new Float32Array(n*3);
 const A=C(rockPal[s%4]),B=C(0xb8662c),G=C(0xd9a03a),c=new THREE.Color();
 for(let i=0;i<n;i++){const x=p.getX(i)/r,y=p.getY(i)/r,z=p.getZ(i)/r;
  const q=Math.sin(x*3.1+s)*Math.sin(y*2.7+s*1.7)*Math.sin(z*3.3+s*.7)+.35*Math.sin(x*7+z*5+s),f=1+.17*q;
  p.setXYZ(i,x*r*f,y*r*f*.92,z*r*f);
  c.copy(A);if(y>.3+.3*q)c.lerp(B,.55);else if(q>.5)c.lerp(G,.5);
  c.multiplyScalar(.65+.35*clamp((y+1)/2,0,1));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 new THREE.Mesh(g,solid);}
function blob(g,x,y,z,r,s){const m=mkRock(r,s);m.position.set(x,y,z);m.userData.r=r;g.add(m);return m;}
function reg(g){g.updateMatrixWorld(true);const v=new THREE.Vector3();g.traverse(o=>{if(o.userData.r){v.setFromMatrixPosition(o.matrixWorld);COL.push([v.x,v.y,v.z,o.userData.r*(o.isMesh?.9:1)]);}});}
function arch(x,z,yaw,Rr){const g=new THREE.Group();let k=0;
 for(let i=0;i<=11;i++){const a=PI*i/11;blob(g,Math.cos(a)*Rr,Math.sin(a)*Rr,R(-.7,.7),Rr*R(.33,.4),k++);if(i%2)blob(g,Math.cos(a)*Rr*1.1,Math.sin(a)*Rr*1.1,R(-2.4,2.4),Rr*.26,k++);}
 for(const sg of[-1,1]){blob(g,sg*Rr,-1.2,0,Rr*.5,k++);blob(g,sg*Rr*1.12,.6,R(-1,1),Rr*.34,k++);}
 g.position.set(x,gY(x,z)-.6,z);g.rotation.y=yaw;scene.add(g);reg(g);return g;}
arch(-14,-36,0,9);arch(48,24,1,7.5);arch(-52,34,-.6,10);
const wmc={},wm=h=>wmc[h]||(wmc[h]=new THREE.MeshLambertMaterial({color:h,side:THREE.DoubleSide}));
function box(p,w,h,d,x,y,z,col,rx,ry,rz){const m=new THREE.Mesh(new THREE.BoxGeometry(w,h,d),wm(col));m.position.set(x,y,z);m.rotation.set(rx||0,ry||0,rz||0);p.add(m);return m;}
function cyl(p,r0,r1,h,x,y,z,col,rx,ry,rz){const m=new THREE.Mesh(new THREE.CylinderGeometry(r0,r1,h,7),wm(col));m.position.set(x,y,z);m.rotation.set(rx||0,ry||0,rz||0);p.add(m);return m;}
function mkShip(){const g=new THREE.Group(),P=[],Cc=[],L=28,N=20,M=14;
 const W=u=>u<.5?3.3+Math.sin(u/.5*PI/2):4.3*(1-Math.pow((u-.5)/.5,2.2))+.2,D=u=>4.6*(1-.5*u*u*u),T=u=>.9*Math.pow(2*u-1,2);
 const S=(u,th)=>[W(u)*Math.cos(th),T(u)-D(u)*Math.sin(th),-L/2+u*L];
 const pw=[C(0x8a4c23),C(0xa96a30)],gr=C(0x3f7a45),dk=[C(0xb9803d),C(0x9c6a30)];
 const tri=(a,b,c,col)=>{for(const p of[a,b,c]){P.push(p[0],p[1],p[2]);Cc.push(col.r,col.g,col.b);}},quad=(a,b,c,d,col)=>{tri(a,b,c,col);tri(a,c,d,col);};
 for(let k=0;k<N;k++)for(let j=0;j<M;j++){const u0=k/N,u1=(k+1)/N,t0=PI*j/M,t1=PI*(j+1)/M;
  const col=pw[j%2].clone().lerp(gr,Math.pow(Math.sin((t0+t1)/2),3)*.45).multiplyScalar(.88+.2*rnd());quad(S(u0,t0),S(u0,t1),S(u1,t1),S(u1,t0),col);}
 const E=(u,f)=>{const a=S(u,0),b=S(u,PI);return[b[0]+(a[0]-b[0])*f,a[1],a[2]];};
 for(let k=0;k<N;k++)for(let s=0;s<6;s++)quad(E(k/N,s/6),E(k/N,(s+1)/6),E((k+1)/N,(s+1)/6),E((k+1)/N,s/6),dk[(s+k)%2].clone().multiplyScalar(.9+.15*rnd()));
 for(const u of[0,1]){const c=[0,T(u)-.2,-L/2+u*L];for(let j=0;j<M;j++)tri(c,S(u,PI*j/M),S(u,PI*(j+1)/M),pw[0]);}
 const hg=new THREE.BufferGeometry();hg.setAttribute('position',new THREE.Float32BufferAttribute(P,3));hg.setAttribute('color',new THREE.Float32BufferAttribute(Cc,3));hg.computeVertexNormals();g.add(new THREE.Mesh(hg,solid));
 box(g,6.2,3.2,6.4,0,T(.1)+1.6,-L/2+4,0x8a4c23);box(g,6.9,.3,7.1,0,T(.1)+3.35,-L/2+4,0xa96a30);box(g,1,1.3,.1,2,T(.1)+1.7,-L/2+.75,0x2a1608);box(g,1,1.3,.1,-2,T(.1)+1.7,-L/2+.75,0x2a1608);
 cyl(g,.3,.45,12,0,6.1,3,0x6b3b1b,0,0,.06);cyl(g,.17,.17,8,0,9.2,3.2,0x6b3b1b,0,0,PI/2+.05);cyl(g,.3,.42,7,.1,3.8,-4,0x6b3b1b,.05,0,-.12);
 cyl(g,.18,.3,7,0,T(1)+1.1,L/2+2,0x6b3b1b,PI/2-.25,0,0);box(g,.35,3.8,1.6,0,-2.4,-L/2-.4,0x5a3216);box(g,2.2,.35,2.2,0,.2,-1,0x4a2a12);box(g,1.8,.35,1.8,0,.2,8,0x4a2a12);
 for(let k=1;k<N-2;k++){if(rnd()<.2)continue;const u=k/N;for(const sg of[-1,1])box(g,.16,1.1,.16,sg*(W(u)-.18),T(u)+.55,-L/2+u*L,0x6b3b1b);}
 const sg=new THREE.PlaneGeometry(7.4,5,10,6),sail=new THREE.Mesh(sg,new THREE.MeshLambertMaterial({color:0xe6bf7c,transparent:true,opacity:.82,side:THREE.DoubleSide}));sail.position.set(0,6.4,3.5);g.add(sail);
 g.userData.sail=[sg,sg.attributes.position.array.slice()];
 const mk=(x,y,z,r)=>{const o=new THREE.Object3D();o.position.set(x,y,z);o.userData.r=r;g.add(o);};
 for(let z=-L/2+1.5;z<=L/2-1.2;z+=3){const u=(z+L/2)/L;mk(0,T(u)-2.3,z,Math.max(1.5,W(u)*1.05));}
 mk(0,3,-L/2+4,3.7);for(let y=2;y<=11;y+=1.8)mk(0,y,3,.8);mk(0,3,-4,.9);mk(0,5.5,-4,.8);
 g.position.set(24,gY(24,-34)+3.2,-34);g.rotation.order='YXZ';g.rotation.set(.07,.5,.28);scene.add(g);reg(g);return g;}
const ship=mkShip();
const LM=[[-14,-36,14],[48,24,12],[-52,34,14],[24,-34,20]],near=(x,z)=>LM.some(l=>Math.hypot(x-l[0],z-l[1])<l[2]);
{const rg=new THREE.Group();scene.add(rg);let rk=100;
 for(let i=0;i<30;i++){let x,z,t=0;do{x=R(-100,100);z=R(-100,100);t++;}while((Math.hypot(x,z)<16||near(x,z))&&t<40);const r=R(1.6,5);blob(rg,x,gY(x,z)+r*.35,z,r,rk++);}
 for(let i=0;i<7;i++){const x=R(-95,95),z=R(-95,95);if(Math.hypot(x,z)<22||near(x,z))continue;let y=gY(x,z),r=R(3,4.4);for(let j=0;j<4;j++){blob(rg,x+R(-.6,.6),y+r*.4,z+R(-.6,.6),r,rk++);y+=r*1.05;r*=.78;}}
 reg(rg);}
const blocked=(x,y,z,m)=>COL.some(c=>Math.hypot(x-c[0],y-c[1],z-c[2])<c[3]+m);

/* ---------- kelp ---------- */
function kelpGeo(){const P=[],Cl=[],I=[],c0=C(0xa3c79a),c1=C(0xfff08c);
 function strip(n,pt,wd,sd,tint){const b=P.length/3;for(let i=0;i<=n;i++){const t=i/n,p=pt(t),w=wd(t),c=c0.clone().lerp(c1,tint(t));P.push(p[0]-sd[0]*w,p[1]-sd[1]*w,p[2]-sd[2]*w,p[0]+sd[0]*w,p[1]+sd[1]*w,p[2]+sd[2]*w);Cl.push(c.r,c.g,c.b,c.r,c.g,c.b);if(i<n){const a=b+i*2;I.push(a,a+1,a+2,a+1,a+3,a+2);}}}
 const stem=t=>[Math.sin(t*5)*.012,t,Math.cos(t*4)*.01],sw=t=>.007*(1-.6*t)+.002;
 strip(16,stem,sw,[1,0,0],t=>t*t);strip(16,stem,sw,[0,0,1],t=>t*t);
 for(let b=0;b<9;b++){const t0=.1+.85*b/9,a=b*2.4,ca=Math.cos(a),sa=Math.sin(a),s0=stem(t0);
  strip(7,t=>[s0[0]+ca*t*.17,s0[1]+Math.sin(t*2.4)*.05+t*.06,s0[2]+sa*t*.17],t=>.008+.022*Math.sin(Math.min(t*1.15,1)*PI*.85),[-sa*.6,.8,ca*.6],t=>t*.6+.2);}
 const g=new THREE.BufferGeometry();g.setIndex(I);g.setAttribute('position',new THREE.Float32BufferAttribute(P,3));g.setAttribute('color',new THREE.Float32BufferAttribute(Cl,3));g.computeVertexNormals();return g;}
{const kmat=new THREE.MeshLambertMaterial({vertexColors:true,side:THREE.DoubleSide});
 kmat.onBeforeCompile=s=>{s.uniforms.uTime=U.uTime;s.vertexShader=s.vertexShader.replace('#include <common>','#include <common>\nuniform float uTime;').replace('#include <begin_vertex>','#include <begin_vertex>\nvec3 ip=instanceMatrix[3].xyz;float h=position.y,w=h*h,ph=ip.x*.21+ip.z*.17;transformed.x+=(sin(uTime*.9+ph+h*2.2)+.5*sin(uTime*1.7+ph*1.7+h*3.1))*.05*w;transformed.z+=cos(uTime*.8+ph*1.3+h*1.9)*.04*w;');};
 const cl=[[-8,-4],[12,-12],[4,18],[-20,10],[18,12],[-30,-18],[30,0]];for(let i=0;i<10;i++)cl.push([R(-95,95),R(-95,95)]);
 const KP=[];for(const [cx,cz] of cl)for(let i=0,n=Math.floor(R(26,42));i<n;i++){const a=R(0,6.283),d=Math.sqrt(rnd())*14,x=cx+Math.cos(a)*d,z=cz+Math.sin(a)*d;if(Math.hypot(x,z)>104||blocked(x,gY(x,z),z,1.6))continue;KP.push([x,z,rnd()<.2?R(3,7):R(8,22)]);}
 const km=new THREE.InstancedMesh(kelpGeo(),kmat,KP.length),kc=[0x4aa845,0x2f9a62,0x6fb043,0x3a9a8a].map(C);km.frustumCulled=false;
 KP.forEach((k,i)=>{_s.setScalar(k[2]);_q.setFromAxisAngle(_up,R(0,6.28));_a.set(k[0],gY(k[0],k[1])-.3,k[1]);_m.compose(_a,_q,_s);km.setMatrixAt(i,_m);km.setColorAt(i,kc[i%4].clone().multiplyScalar(R(.8,1.2)));});
 scene.add(km);}

/* ---------- coral (teal, gold, orange only) ---------- */
function branchGeo(){const parts=[];(function br(pos,dir,len,rad,dep){const q=new THREE.Quaternion().setFromUnitVectors(_up,dir),m=new THREE.Matrix4().compose(pos,q,new THREE.Vector3(1,1,1)),cg=new THREE.CylinderGeometry(rad*.65,rad,len,5,1);cg.translate(0,len/2,0);parts.push([cg,m,C(0xffffff).multiplyScalar(.7+.1*dep)]);
 const tip=pos.clone().addScaledVector(dir,len);if(dep>=3){parts.push([new THREE.IcosahedronGeometry(rad*1.6,0),new THREE.Matrix4().makeTranslation(tip.x,tip.y,tip.z),C(0xffffff)]);return;}
 const n=2+(rnd()<.5?1:0);for(let i=0;i<n;i++)br(tip,dir.clone().add(new THREE.Vector3(R(-.9,.9),R(.1,.7),R(-.9,.9))).normalize(),len*.72,rad*.7,dep+1);})(new THREE.Vector3(0,0,0),new THREE.Vector3(0,1,0),.35,.07,0);return merge(parts);}
function domeGeo(){const parts=[],I=new THREE.Quaternion();for(let i=0;i<6;i++){const a=i*1.05,d=i?.32:0,r=i?R(.18,.26):.34;parts.push([new THREE.IcosahedronGeometry(r,1),new THREE.Matrix4().compose(new THREE.Vector3(Math.cos(a)*d,r*.5,Math.sin(a)*d),I,new THREE.Vector3(1,.8,1)),C(0xffffff).multiplyScalar(.75+.25*rnd())]);}
 for(let i=0;i<3;i++){const h=R(.4,.7),cg=new THREE.CylinderGeometry(.06,.09,h,6);cg.translate(Math.cos(i*2.1)*.45,h/2,Math.sin(i*2.1)*.45);parts.push([cg,new THREE.Matrix4(),C(0xffffff).multiplyScalar(.85)]);}return merge(parts);}
{const cm=new THREE.MeshLambertMaterial({vertexColors:true}),cc=[0xff8a3d,0xf2b632,0x2fc4b2,0xe8662a,0xffb04a].map(C);
 const cpos=()=>{for(let t=0;t<30;t++){let x,z;if(rnd()<.6){const c=COL[(rnd()*COL.length)|0],a=R(0,6.28),d=c[3]+R(1.5,7);x=c[0]+Math.cos(a)*d;z=c[2]+Math.sin(a)*d;}else{x=R(-100,100);z=R(-100,100);}if(Math.hypot(x,z)<104&&!blocked(x,gY(x,z)+.3,z,1))return[x,z];}return null;};
 [[branchGeo(),140,.9,2.6],[domeGeo(),110,.8,2.4]].forEach(([g,n,s0,s1])=>{const im=new THREE.InstancedMesh(g,cm,n);im.frustumCulled=false;
  for(let i=0;i<n;i++){const p=cpos()||[500,500];_s.setScalar(R(s0,s1));_q.setFromEuler(new THREE.Euler(R(-.15,.15),R(0,6.28),R(-.15,.15)));_a.set(p[0],gY(p[0],p[1])-.05,p[1]);_m.compose(_a,_q,_s);im.setMatrixAt(i,_m);im.setColorAt(i,cc[(rnd()*5)|0].clone().multiplyScalar(R(.85,1.15)));}scene.add(im);});}

/* ---------- sunbeams ---------- */
{const bc=document.createElement('canvas');bc.width=64;bc.height=256;const bx=bc.getContext('2d');
 let gr=bx.createLinearGradient(0,0,64,0);gr.addColorStop(0,'rgba(255,225,150,0)');gr.addColorStop(.5,'rgba(255,225,150,1)');gr.addColorStop(1,'rgba(255,225,150,0)');bx.fillStyle=gr;bx.fillRect(0,0,64,256);
 gr=bx.createLinearGradient(0,0,0,256);gr.addColorStop(0,'rgba(0,0,0,1)');gr.addColorStop(.55,'rgba(0,0,0,.5)');gr.addColorStop(1,'rgba(0,0,0,0)');bx.globalCompositeOperation='destination-in';bx.fillStyle=gr;bx.fillRect(0,0,64,256);
 const bm=new THREE.ShaderMaterial({uniforms:{uTime:U.uTime,uMap:{value:new THREE.CanvasTexture(bc)},uFogD:{value:.017}},transparent:true,depthWrite:false,blending:THREE.AdditiveBlending,side:THREE.DoubleSide,
 vertexShader:'varying vec2 vUv;varying float vD,vP;void main(){vUv=uv;vP=modelMatrix[3].x*.37+modelMatrix[3].z*.51;vec4 mv=modelViewMatrix*vec4(position,1.);vD=length(mv.xyz);gl_Position=projectionMatrix*mv;}',
 fragmentShader:'uniform sampler2D uMap;uniform float uTime,uFogD;varying vec2 vUv;varying float vD,vP;void main(){float a=texture2D(uMap,vUv).a;a*=.55+.45*sin(uTime*.6+vP);a*=exp(-pow(vD*uFogD*1.15,2.))*smoothstep(1.,7.,vD);gl_FragColor=vec4(1.,.82,.45,a*.5);}'});
 for(let i=0;i<18;i++){const grp=new THREE.Group(),h=SY+6,pg=new THREE.PlaneGeometry(R(7,15),h);pg.translate(0,-h/2,0);const m=new THREE.Mesh(pg,bm),m2=new THREE.Mesh(pg,bm);m2.rotation.y=PI/2;m.rotation.y=R(0,PI);m.add(m2);grp.add(m);
  const sp=i<8?45:100;grp.position.set(R(-sp,sp),SY+.5,R(-sp,sp));grp.rotation.z=.3;scene.add(grp);}}

/* ---------- rippling surface ---------- */
const surfMat=new THREE.ShaderMaterial({uniforms:{uTime:U.uTime,uFogC:{value:scene.fog.color},uFogD:{value:.017}},side:THREE.DoubleSide,
 vertexShader:'varying vec3 vW;void main(){vec4 w=modelMatrix*vec4(position,1.);vW=w.xyz;gl_Position=projectionMatrix*viewMatrix*w;}',
 fragmentShader:'uniform float uTime,uFogD;uniform vec3 uFogC;varying vec3 vW;'+CAUS+'void main(){vec2 p=vW.xz*.05;float t=uTime*.5;float r=sin(p.x*5.+t*2.)+sin(p.y*4.3-t*1.7)+sin((p.x+p.y)*7.+t*2.6)*.6+sin((p.x-p.y)*11.-t*3.1)*.4;float c=caustic(mod(vW.xz*.18,6.28318)-250.,uTime*.4+23.);vec3 col=mix(vec3(.05,.42,.5),vec3(.35,.78,.74),.5+.2*r);col+=vec3(1.,.8,.45)*(c*.8+pow(max(r*.25+.5,0.),4.)*.45);float d=length(vW-cameraPosition);float f=1.-exp(-pow(uFogD*d,2.));gl_FragColor=vec4(mix(col,uFogC,f),1.);}'});
const surf=new THREE.Mesh(new THREE.PlaneGeometry(900,900).rotateX(PI/2),surfMat);surf.position.y=SY;surf.frustumCulled=false;scene.add(surf);

/* ---------- fish schools ---------- */
const fishGeo=(()=>{const tg=new THREE.ConeGeometry(.3,.45,4);tg.rotateX(-PI/2);return merge([[new THREE.SphereGeometry(.5,8,6),new THREE.Matrix4().makeScale(.3,.4,1),C(0xffffff)],[tg,new THREE.Matrix4().compose(new THREE.Vector3(0,0,.72),new THREE.Quaternion(),new THREE.Vector3(.25,1.2,1)),C(0xffd9a0)]]);})();
const fishMat=new THREE.MeshLambertMaterial({vertexColors:true});
fishMat.onBeforeCompile=s=>{s.uniforms.uTime=U.uTime;s.vertexShader=s.vertexShader.replace('#include <common>','#include <common>\nuniform float uTime;').replace('#include <begin_vertex>','#include <begin_vertex>\nfloat wg=smoothstep(.15,.95,position.z);transformed.x+=sin(uTime*9.+instanceMatrix[3].x*2.7+instanceMatrix[3].z*1.9)*.2*wg;');};
const schoolPos=(S,t,o)=>o.set(S.cx+S.ax*Math.sin(S.w*t+S.ph),S.cy+S.ay*Math.sin(S.w*t*1.3+S.ph*2),S.cz+S.az*Math.cos(S.w*t*.83+S.ph));
const SCH=[],fcol=[0xf2b632,0xff8a3d,0x2fc4b2,0x3b8fd8,0xffc15a,0x35b7a0,0xff9f4a];
for(let s=0;s<7;s++){const n=s<2?34:24,m=new THREE.InstancedMesh(fishGeo,fishMat,n);m.frustumCulled=false;
 const S={m,n,cx:s?R(-70,70):2,cy:s?R(7,17):11,cz:s?R(-70,70):-8,ax:s?R(15,35):20,ay:R(2,4),az:s?R(15,35):16,w:s?R(.12,.2):.22,ph:R(0,6.3),f:[]},bc=C(fcol[s]),sz=R(.8,1.4);
 for(let i=0;i<n;i++){const p=new THREE.Vector3();schoolPos(S,0,p);p.add(new THREE.Vector3(R(-3,3),R(-1.5,1.5),R(-3,3)));S.f.push({p,v:new THREE.Vector3(R(-1,1),0,R(-1,1)).setLength(3),s:sz*R(.85,1.15)});m.setColorAt(i,bc.clone().multiplyScalar(R(.85,1.15)));}
 scene.add(m);SCH.push(S);}
function updFish(dt,t){for(const S of SCH){schoolPos(S,t+1,_a);const F=S.f,n=S.n;let cx=0,cy=0,cz=0,vx=0,vy=0,vz=0;
 for(const f of F){cx+=f.p.x;cy+=f.p.y;cz+=f.p.z;vx+=f.v.x;vy+=f.v.y;vz+=f.v.z;}cx/=n;cy/=n;cz/=n;vx/=n;vy/=n;vz/=n;
 for(let i=0;i<n;i++){const f=F[i],p=f.p,v=f.v;
  let ax=(_a.x-p.x)*.12+(cx-p.x)*.07+(vx-v.x)*.9,ay=(_a.y-p.y)*.12+(cy-p.y)*.07+(vy-v.y)*.9,az=(_a.z-p.z)*.12+(cz-p.z)*.07+(vz-v.z)*.9;
  for(let j=0;j<n;j++){if(j===i)continue;const q=F[j].p,dx=p.x-q.x,dy=p.y-q.y,dz=p.z-q.z,d2=dx*dx+dy*dy+dz*dz;if(d2<1.6&&d2>1e-4){const k=.8/d2;ax+=dx*k;ay+=dy*k;az+=dz*k;}}
  for(const c of COL){const dx=p.x-c[0],dy=p.y-c[1],dz=p.z-c[2],r=c[3]+4,d2=dx*dx+dy*dy+dz*dz;if(d2<r*r){const d=Math.sqrt(d2)+.01,k=(1-d/r)*30/d;ax+=dx*k;ay+=dy*k;az+=dz*k;}}
  const g=gY(p.x,p.z)+1.5;if(p.y<g)ay+=(g-p.y)*8;if(p.y>SY-6)ay-=(p.y-SY+6)*8;
  const rr=Math.hypot(p.x,p.z);if(rr>100){ax-=p.x/rr*(rr-100)*.5;az-=p.z/rr*(rr-100)*.5;}
  v.x+=ax*dt;v.y+=ay*dt;v.z+=az*dt;v.y=clamp(v.y*.99,-2.2,2.2);
  const sp=v.length();if(sp>5.8)v.multiplyScalar(5.8/sp);else if(sp<2.6)v.multiplyScalar(2.6/(sp+1e-4));
  p.addScaledVector(v,dt);_m.lookAt(_o,v,_up);_q.setFromRotationMatrix(_m);_s.setScalar(f.s);_m.compose(p,_q,_s);S.m.setMatrixAt(i,_m);}
 S.m.instanceMatrix.needsUpdate=true;}}

/* ---------- manta rays ---------- */
function mantaGeo(){const nu=14,nv=6,P=[],Cl=[],I=[],xs=[],by=[],tc=C(0x1f8c96),dc=C(0x0f2f5c),gc=C(0xf0c277),oc=C(0xff8f3f);
 for(let s=0;s<2;s++)for(let i=0;i<=nu;i++)for(let j=0;j<=nv;j++){const u=-1+2*i/nu,v=j/nv,a=Math.abs(u),lead=-3.3*Math.pow(1-a,.8),trail=2.2*(1-Math.pow(a,1.6))+.3*a,th=Math.pow(1-a,1.2)*Math.sin(PI*v);
  const x=u*4.4,y=s?-.16*th:.42*th,z=lead+(trail-lead)*v,c=s?gc.clone().lerp(oc,a*a):dc.clone().lerp(tc,Math.pow(a,1.2));
  P.push(x,y,z);Cl.push(c.r,c.g,c.b);xs.push(Math.abs(x));by.push(y);}
 for(let s=0;s<2;s++)for(let i=0;i<nu;i++)for(let j=0;j<nv;j++){const b=s*(nu+1)*(nv+1),a=b+i*(nv+1)+j,c=a+nv+1;I.push(a,a+1,c,a+1,c+1,c);}
 const g=new THREE.BufferGeometry();g.setIndex(I);g.setAttribute('position',new THREE.Float32BufferAttribute(P,3));g.setAttribute('color',new THREE.Float32BufferAttribute(Cl,3));return{g,xs,by};}
const mantaMat=new THREE.MeshLambertMaterial({vertexColors:true,side:THREE.DoubleSide}),tailG=new THREE.ConeGeometry(.14,5,5).rotateX(PI/2).translate(0,0,4.4),tailMat=new THREE.MeshLambertMaterial({color:0x15406a});
const mantaPos=(M,t,o)=>o.set(M.cx+M.Ax*Math.cos(M.w*t+M.ph),M.cy+M.Ay*Math.sin(M.w*t*1.3+M.ph*2),M.cz+M.Az*Math.sin(M.w*t+M.ph));
const MT=[];[[6,17,-16,26,5,18,2*PI/40,0,1.1],[-30,20,10,40,5,28,.05,2,1],[38,15,22,30,4,26,.06,4,1.25],[-10,22,-60,40,4,20,.045,1,.9]].forEach(a=>{const mg=mantaGeo(),grp=new THREE.Group();grp.add(new THREE.Mesh(mg.g,mantaMat),new THREE.Mesh(tailG,tailMat));grp.children.forEach(c=>c.frustumCulled=false);scene.add(grp);MT.push({grp,g:mg.g,xs:mg.xs,by:mg.by,cx:a[0],cy:a[1],cz:a[2],Ax:a[3],Ay:a[4],Az:a[5],w:a[6],ph:a[7],s:a[8]});});
function updManta(t){for(const M of MT){mantaPos(M,t,_a);mantaPos(M,t+.3,_b);_b.sub(_a);_m.lookAt(_o,_b,_up);_q.setFromRotationMatrix(_m);_q.multiply(_qr.setFromAxisAngle(_z,-.28));
 M.grp.position.copy(_a);M.grp.quaternion.copy(_q);M.grp.scale.setScalar(M.s);
 const pa=M.g.attributes.position,ar=pa.array;for(let k=0;k<M.xs.length;k++)ar[k*3+1]=M.by[k]+Math.sin(t*1.5-M.xs[k]*.5+M.ph)*M.xs[k]*.2;pa.needsUpdate=true;M.g.computeVertexNormals();}}

/* ---------- bubbles and drifting motes ---------- */
const bubMat=new THREE.ShaderMaterial({uniforms:{uTime:U.uTime,uCam:{value:cam.position},uScale:{value:600}},transparent:true,depthWrite:false,
 vertexShader:'attribute vec4 aData;uniform float uTime,uScale;uniform vec3 uCam;varying float vA;void main(){float sz=aData.x,sp=aData.y,ph=aData.z;vec3 p=position;vA=1.;if(aData.w<.5){vec3 bx=vec3(60.,40.,60.);p.y+=uTime*sp;p=mod(p-uCam+bx*.5,bx)-bx*.5+uCam;p.x+=sin(uTime*.7+ph*20.+p.y*.4)*.25;p.z+=cos(uTime*.6+ph*17.+p.y*.3)*.25;}else{float h=mod(uTime*sp+ph*40.,36.);p.y+=h;p.xz+=vec2(sin(h*.9+ph*30.),cos(h*.7+ph*20.))*(.15+h*.03);sz*=1.+h*.05;vA=1.-smoothstep(28.,36.,h);}vec4 mv=viewMatrix*vec4(p,1.);gl_Position=projectionMatrix*mv;gl_PointSize=clamp(sz*uScale/-mv.z,1.6,70.);vA*=exp(-pow(length(mv.xyz)*.017,2.));}',
 fragmentShader:'varying float vA;void main(){vec2 c=gl_PointCoord-.5;float d=length(c)*2.;if(d>1.)discard;float ring=smoothstep(.55,.95,d)*(1.-smoothstep(.97,1.,d));float hl=smoothstep(.34,0.,length(c-vec2(-.17,-.17)));gl_FragColor=vec4(vec3(.82,1.,.95)*(.3+ring*.9+hl),(.1+ring*.7+hl*.6)*vA);}'});
{const vents=[[30,-28],[-14,-30],[10,2],[-30,0],[44,20]],NB=1400,bp=new Float32Array(NB*3),bd=new Float32Array(NB*4);
 for(let i=0;i<NB;i++){let x,y,z,d;if(i<600){x=R(-30,30);y=R(0,40);z=R(-30,30);d=[R(.1,.22),R(.5,1.4),rnd(),0];}else if(i<1000){x=R(-30,30);y=R(0,40);z=R(-30,30);d=[R(.02,.045),R(.03,.15),rnd(),0];}else{const v=vents[i%5];x=v[0]+R(-.6,.6);z=v[1]+R(-.6,.6);y=gY(v[0],v[1])+.2;d=[R(.12,.3),R(1.2,2),rnd(),1];}
  bp.set([x,y,z],i*3);bd.set(d,i*4);}
 const g=new THREE.BufferGeometry();g.setAttribute('position',new THREE.BufferAttribute(bp,3));g.setAttribute('aData',new THREE.BufferAttribute(bd,4));const pts=new THREE.Points(g,bubMat);pts.frustumCulled=false;scene.add(pts);}

/* ---------- swimming controls ---------- */
const PR=.9,P={x:0,y:7,z:6,yaw:0,pitch:0,v:{x:0,y:0,z:0}};
let held=false,pid=null,lx=0,ly=0;
function showHint(h,ms){hint.innerHTML=h;hint.style.opacity=1;clearTimeout(showHint.t);if(ms)showHint.t=setTimeout(()=>{hint.style.opacity=0;},ms);}
const HELP='<b>KELP GARDEN</b>Press and hold to glide ahead, drag to turn.<br><small>Mouse: hold the button and move the pointer.</small>';
cv.addEventListener('pointerdown',e=>{if(held)return;held=true;pid=e.pointerId;lx=e.clientX;ly=e.clientY;try{cv.setPointerCapture(e.pointerId);}catch(x){}hint.style.opacity=0;e.preventDefault();});
cv.addEventListener('pointermove',e=>{if(!held||e.pointerId!==pid)return;P.yaw-=(e.clientX-lx)*.0052;P.pitch=clamp(P.pitch-(e.clientY-ly)*.0042,-1.25,1.25);lx=e.clientX;ly=e.clientY;e.preventDefault();});
['pointerup','pointercancel','lostpointercapture'].forEach(n=>cv.addEventListener(n,e=>{if(e.pointerId===pid){held=false;pid=null;}}));
cv.addEventListener('contextmenu',e=>e.preventDefault());
function resolve(o,v){for(let it=0;it<2;it++)for(const c of COL){const dx=o.x-c[0],dy=o.y-c[1],dz=o.z-c[2],rr=c[3]+PR,d2=dx*dx+dy*dy+dz*dz;
  if(d2<rr*rr){const d=Math.sqrt(d2)||.001,nx=dx/d,ny=dy/d,nz=dz/d;o.x=c[0]+nx*rr;o.y=c[1]+ny*rr;o.z=c[2]+nz*rr;if(v){const vn=v.x*nx+v.y*ny+v.z*nz;if(vn<0){v.x-=vn*nx;v.y-=vn*ny;v.z-=vn*nz;}}}}
 const g=gY(o.x,o.z)+1.2;if(o.y<g){o.y=g;if(v&&v.y<0)v.y=0;}if(o.y>SY-3)o.y=SY-3;const r=Math.hypot(o.x,o.z);if(r>110){o.x*=110/r;o.z*=110/r;}}
function move(dt){const cp=Math.cos(P.pitch),fx=-Math.sin(P.yaw)*cp,fy=Math.sin(P.pitch),fz=-Math.cos(P.yaw)*cp,sp=held?7.5:0,k=1-Math.exp(-dt*(held?1.5:.8)),V=P.v;
 V.x+=(fx*sp-V.x)*k;V.y+=(fy*sp-V.y)*k;V.z+=(fz*sp-V.z)*k;P.x+=V.x*dt;P.y+=V.y*dt;P.z+=V.z*dt;resolve(P,V);}

/* ---------- hands-free demo (#demo) ---------- */
let demo=false,d0=0,dLoop=-1,kf=[],curve=null,first=true;const dp={x:0,y:0,z:0},lookS=new THREE.Vector3(),tgt=new THREE.Vector3();
function tourUI(){bTour.textContent=demo?'Stop tour':'Auto tour';bTour.classList.toggle('on',demo);}
function startDemo(){demo=true;d0=tw;dLoop=-1;tourUI();showHint('<b>KELP GARDEN</b>Hands-free tour. Touch anywhere to swim yourself.',5000);}
function endDemo(){if(!demo)return;demo=false;cam.getWorldDirection(_a);P.x=cam.position.x;P.y=cam.position.y;P.z=cam.position.z;P.yaw=Math.atan2(-_a.x,-_a.z);P.pitch=Math.asin(clamp(_a.y,-1,1));P.v.x=P.v.y=P.v.z=0;fadeEl.style.opacity=0;tourUI();showHint(HELP,7000);}
function runDemo(dt){const e=tw-d0,L=Math.floor(e/20),t=e-L*20,B=d0+L*20;
 if(L!==dLoop){dLoop=L;const sp=new THREE.Vector3(),m1=new THREE.Vector3(),m2=new THREE.Vector3();schoolPos(SCH[0],B+7.5,sp);mantaPos(MT[0],B+17.5,m1);mantaPos(MT[0],B+20,m2);
  kf=[[0,[3,5.5,12]],[4,[-3,8,0]],[7.5,[sp.x-10,sp.y+1,sp.z+8]],[10.5,[-14,4,-16]],[12.8,[-14,3.6,-48]],[15.5,[8,11,-27]],[17.5,[m1.x+7,m1.y-9,m1.z+7]],[20,[m2.x+7,m2.y-9,m2.z+7]]];
  curve=new THREE.CatmullRomCurve3(kf.map(k=>new THREE.Vector3(k[1][0],k[1][1],k[1][2])),false,'catmullrom',.5);first=true;}
 let i=0;while(i<kf.length-2&&t>=kf[i+1][0])i++;
 curve.getPoint(Math.min(1,(i+clamp((t-kf[i][0])/(kf[i+1][0]-kf[i][0]),0,1))/(kf.length-1)),_a);dp.x=_a.x;dp.y=_a.y;dp.z=_a.z;resolve(dp,null);
 if(t<5)tgt.set(-2,17,-14);else if(t<9.5)schoolPos(SCH[0],tw,tgt);else if(t<12.2)tgt.set(-14,5,-90);else if(t<16.2)tgt.copy(ship.position);else mantaPos(MT[0],tw,tgt);
 if(first){lookS.copy(tgt);first=false;}else lookS.lerp(tgt,1-Math.exp(-dt*2.2));
 cam.position.set(dp.x,dp.y,dp.z);cam.lookAt(lookS);
 fadeEl.style.opacity=Math.max(clamp((t-19.2)/.8,0,1),clamp(1-t/.8,0,1)).toFixed(3);}
const trusted=e=>{if(demo&&e.isTrusted&&e.target!==bTour)endDemo();};
window.addEventListener('pointerdown',trusted,true);window.addEventListener('touchstart',trusted,{capture:true,passive:true});
bTour.addEventListener('click',()=>{demo?endDemo():startDemo();});
window.addEventListener('hashchange',()=>{if(location.hash.toLowerCase()==='#demo'&&!demo)startDemo();});

/* ---------- synthesized sound ---------- */
let AC=null,mg=null,sndOn=false;
function snd(on){sndOn=on;bSnd.textContent=on?'Sound: on':'Sound: off';bSnd.classList.toggle('on',on);
 try{if(on&&!AC){const A=window.AudioContext||window.webkitAudioContext;AC=new A();mg=AC.createGain();mg.gain.value=0;mg.connect(AC.destination);
  const n=AC.sampleRate*4,b=AC.createBuffer(1,n,AC.sampleRate),d=b.getChannelData(0);let l=0;for(let i=0;i<n;i++){l=(l+.02*(Math.random()*2-1))/1.02;d[i]=l*3.2;}
  const s=AC.createBufferSource();s.buffer=b;s.loop=true;const f=AC.createBiquadFilter();f.type='lowpass';f.frequency.value=380;const lf=AC.createOscillator(),lg=AC.createGain();lf.frequency.value=.09;lg.gain.value=160;lf.connect(lg);lg.connect(f.frequency);lf.start();s.connect(f);f.connect(mg);s.start();
  [110,164.8,220.5].forEach((fr,i)=>{const o=AC.createOscillator(),g=AC.createGain();o.type='sine';o.frequency.value=fr;g.gain.value=.012;o.connect(g);g.connect(mg);o.start();const l2=AC.createOscillator(),g2=AC.createGain();l2.frequency.value=.05+i*.03;g2.gain.value=.01;l2.connect(g2);g2.connect(g.gain);l2.start();});}
  if(AC){AC.resume();mg.gain.setTargetAtTime(on?.55:0,AC.currentTime,.3);}}catch(e){}}
bSnd.addEventListener('click',()=>snd(!sndOn));
setInterval(()=>{if(!sndOn||!AC)return;try{const o=AC.createOscillator(),g=AC.createGain(),t=AC.currentTime,f=500+Math.random()*400;o.frequency.setValueAtTime(f,t);o.frequency.exponentialRampToValueAtTime(f*1.8,t+.12);g.gain.setValueAtTime(0,t);g.gain.linearRampToValueAtTime(.05,t+.02);g.gain.exponentialRampToValueAtTime(.001,t+.2);o.connect(g);g.connect(mg);o.start(t);o.stop(t+.25);}catch(e){}},1400);

/* ---------- main loop ---------- */
function resize(){const w=innerWidth,h=innerHeight;renderer.setPixelRatio(Math.min(devicePixelRatio||1,1.75));renderer.setSize(w,h,false);cam.aspect=w/h;cam.fov=w/h<1?82:66;cam.updateProjectionMatrix();bubMat.uniforms.uScale.value=renderer.domElement.height/(2*Math.tan(cam.fov*PI/360));}
window.addEventListener('resize',resize);resize();
let last=performance.now();
function frame(now){requestAnimationFrame(frame);const dt=Math.min(.05,(now-last)/1000);last=now;tw+=dt;U.uTime.value=tw;
 if(demo)runDemo(dt);else{move(dt);cam.position.set(P.x,P.y+Math.sin(tw*.7)*.08,P.z);cam.rotation.set(P.pitch,P.yaw,Math.sin(tw*.45)*.02);}
 scene.fog.color.lerpColors(cDeep,cShal,Math.pow(clamp(cam.position.y/SY,0,1),.8));scene.background.copy(scene.fog.color);
 surf.position.x=cam.position.x;surf.position.z=cam.position.z;
 updFish(dt,tw);updManta(tw);
 const sl=ship.userData.sail,sp=sl[0].attributes.position.array,sb=sl[1];for(let i=0;i<sp.length;i+=3){const x=sb[i],y=sb[i+1];sp[i+2]=Math.sin(tw*1.1+x*.8+y*.7)*.35*(.3+.7*(2.5-y)/5);}sl[0].attributes.position.needsUpdate=true;
 renderer.render(scene,cam);}
if(location.hash.toLowerCase()==='#demo'){startDemo();}else{showHint(HELP,9000);}
tourUI();requestAnimationFrame(frame);
})();
</script>
</body></html>