Back to the app
The code
Swim the Kelp Garden by GPT-6.2 Astra
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.)<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#0a363e">
<meta name="color-scheme" content="dark">
<title>Drift Atlas · Kelp Garden</title>
<style>
:root{color-scheme:dark;--paper:#f4f0d9;--muted:#c1d5ce;--gold:#e1bb79;--edge:clamp(20px,3.4vw,64px);--hair:rgba(219,234,218,.22);--sans:"Segoe UI",Arial,sans-serif;--serif:"Palatino Linotype","Book Antiqua",Palatino,Georgia,serif}
*{box-sizing:border-box}html,body{margin:0;width:100%;height:100%;overflow:hidden;background:#124954;color:var(--paper);font-family:var(--sans);-webkit-tap-highlight-color:transparent}body{overscroll-behavior:none;user-select:none;-webkit-user-select:none}
#sea{position:fixed;inset:0;width:100%;height:100%;display:block;touch-action:none;outline:0;cursor:grab;background:radial-gradient(ellipse at 61% 0%,#7ab9aa,#206476 48%,#0a343c 94%)}#sea:active{cursor:grabbing}
.shade,.wash{position:fixed;inset:0;pointer-events:none}.shade{background:linear-gradient(to bottom,rgba(4,27,33,.36),transparent 17%,transparent 66%,rgba(2,23,26,.16) 77%,rgba(2,18,23,.63)),radial-gradient(ellipse at 51% 45%,transparent 50%,rgba(0,25,31,.19) 100%)}.wash{background:#092f37;opacity:0;transition:opacity .23s;z-index:2}.wash.on{opacity:.96}
button{font:inherit;color:inherit;cursor:pointer;touch-action:manipulation}button:focus-visible,a:focus-visible{outline:2px solid #f3ce85;outline-offset:4px}button svg,.gesture svg{width:19px;height:19px;fill:none;stroke:currentColor;stroke-width:1.55;stroke-linecap:round;stroke-linejoin:round;flex-shrink:0}
header{position:fixed;z-index:4;left:var(--edge);right:var(--edge);top:max(24px,env(safe-area-inset-top));display:flex;align-items:center;justify-content:space-between;pointer-events:none}
.identity{display:flex;align-items:center;gap:12px;text-shadow:0 2px 14px #0d37386b}.seal{width:38px;height:43px;color:var(--gold)}.wordmark{font-family:var(--serif);font-size:clamp(21px,1.85vw,29px);letter-spacing:-1.25px;line-height:1.2}
.tools{display:flex;align-items:center;gap:9px;pointer-events:auto}.glass{display:inline-flex;align-items:center;justify-content:center;gap:9px;border-radius:30px;background:rgba(6,40,45,.43);border:1px solid rgba(217,239,220,.32);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);height:44px;transition:background .18s,border-color .18s}.glass:hover,.glass[aria-expanded="true"]{background:rgba(9,51,55,.82);border-color:rgba(224,240,214,.68)}.round{width:44px;padding:0}.sites{padding:0 16px;font-size:13px;font-weight:550}.sites .chev{width:12px;height:12px;margin-left:2px;transition:transform .2s}.sites[aria-expanded=true] .chev{transform:rotate(180deg)}
.heading-tape{position:fixed;top:max(27px,env(safe-area-inset-top));left:50%;transform:translateX(-50%);width:226px;height:44px;pointer-events:none;z-index:2;opacity:.93;mask-image:linear-gradient(90deg,transparent,#000 16%,#000 84%,transparent)}#compass{display:block;width:100%;height:100%}
.depth{position:fixed;z-index:2;right:var(--edge);top:46%;transform:translateY(-50%);display:flex;align-items:center;gap:10px;pointer-events:none;color:#e4eddf;text-shadow:0 1px 7px #0c4851}.depth-values{text-align:right}.depth-name{font-size:9px;letter-spacing:2.1px;display:block;margin:0 0 3px}.depth-num{font-family:ui-monospace,Consolas,monospace;font-size:15px;letter-spacing:-.6px}.depth-num small{font-size:11px}.ruler{width:17px;height:99px;position:relative;opacity:.86;border-right:1px solid rgba(213,232,221,.36);background:repeating-linear-gradient(to bottom,rgba(227,238,221,.67) 0 1px,transparent 1px 9.8px) right/6px 100% no-repeat;mask-image:linear-gradient(transparent,#000 20%,#000 80%,transparent)}.ruler:after{content:"";position:absolute;background:var(--gold);height:2px;width:17px;top:49px;right:0}
footer{position:fixed;z-index:3;left:var(--edge);right:var(--edge);bottom:max(22px,env(safe-area-inset-bottom));pointer-events:none}.site-name{display:table;text-shadow:0 2px 24px rgba(0,27,28,.32);transition:opacity .22s,transform .22s}.site-name.changing{opacity:0;transform:translateY(4px)}.eyebrow{display:flex;align-items:center;gap:11px;color:#f0cb8c;font-size:10px;font-weight:650;letter-spacing:2.55px;text-transform:uppercase}.eyebrow:before{content:"";width:29px;height:1px;background:currentColor}.site-count{font:10px/1.2 ui-monospace,Consolas,monospace;letter-spacing:1.3px;color:#d3dfcd;padding-left:2px}
h1{margin:7px 0 19px;font-family:var(--serif);font-weight:400;font-size:clamp(52px,5.6vw,98px);letter-spacing:-.063em;line-height:1.12}h1 em{font-family:Georgia,"Times New Roman",serif;font-weight:400;letter-spacing:-.068em;margin-left:.022em}
.bottom-row{display:flex;justify-content:space-between;align-items:center;gap:12px;position:relative;padding-top:13px;border-top:1px solid var(--hair)}.gesture{display:flex;gap:11px;align-items:center;color:#e6ecde;font-size:12px;letter-spacing:.15px}.gesture .dot{width:3px;height:3px;border-radius:100%;background:#d3b67c}.gesture svg{color:#e9ca91;width:18px;height:21px}.touch-icon{display:none}.drift{pointer-events:auto;display:flex;gap:9px;align-items:center;border:0;background:transparent;font-size:12px;letter-spacing:.25px;padding:0 0 0 10px;min-height:44px}.play-icon{width:29px;height:29px;border-radius:50%;border:1px solid #d6e6d477;display:grid;place-items:center;background:#07313940}.play-icon svg{width:13px;height:13px;color:var(--gold)}.drift:hover .play-icon,.drift[aria-pressed=true] .play-icon{background:#c6ac7133;border-color:var(--gold)}
.panel{position:fixed;z-index:5;right:var(--edge);top:max(80px,calc(env(safe-area-inset-top) + 57px));width:min(314px,calc(100vw - 40px));border:1px solid #c7ddc147;border-radius:16px;background:linear-gradient(145deg,rgba(14,57,61,.97),rgba(6,35,43,.98));box-shadow:0 18px 64px #001a244d;padding:17px;backdrop-filter:blur(16px);-webkit-backdrop-filter:blur(16px)}.panel[hidden]{display:none}.panel-head{display:flex;align-items:center;justify-content:space-between;margin:0 0 9px 3px;font-family:var(--serif);font-size:23px;letter-spacing:-1px}.close{border:0;background:transparent;width:44px;height:44px;margin:-8px -7px -8px 0;display:grid;place-items:center}.close svg{width:16px;height:16px}.chart{display:block;width:100%;height:108px;border:1px solid #acd3b82b;border-radius:8px;margin:0 0 10px;background:#123f47}.place{width:100%;padding:12px 5px;display:flex;align-items:center;gap:12px;text-align:left;border:0;border-top:1px solid #bdd4bf28;background:transparent;font-size:14px;min-height:47px}.place:hover{color:#f0cc92}.place .no{font-family:ui-monospace,Consolas,monospace;font-size:11px;color:var(--gold)}.place .here{margin-left:auto;width:6px;height:6px;border-radius:50%;background:transparent}.place[aria-current=true] .here{background:#e8c285;box-shadow:0 0 0 4px #d6b57519}
@media(pointer:coarse){.gesture .touch-icon{display:block}.gesture .mouse-icon{display:none}}
@media(max-width:680px){header{top:max(17px,env(safe-area-inset-top))}.identity{gap:8px}.seal{width:30px;height:36px}.wordmark{font-size:23px}.heading-tape{top:78px;width:158px;height:36px}.tools{gap:6px}.sites{padding:0 13px}.depth{right:16px;gap:7px;top:45%}.depth-num{font-size:13px}.depth-name{font-size:8px}.ruler{height:78px}.ruler:after{top:39px}.site-count{font-size:9px}footer{bottom:max(13px,env(safe-area-inset-bottom))}h1{margin-bottom:15px;font-size:clamp(47px,12.5vw,71px)}.eyebrow{font-size:9px;gap:9px}.bottom-row{padding-top:6px}.gesture,.drift{font-size:11px}.gesture{gap:7px}.drift{gap:6px}.panel{top:71px}.play-icon{width:26px;height:26px}}
@media(max-width:365px){.drift .tour-label{max-width:42px;text-align:left;line-height:1.15}.sites .chev{display:none}.depth{right:11px}}
@media(max-height:480px) and (min-width:540px){header{top:12px}.heading-tape{top:13px}.depth{top:47%}footer{bottom:8px}h1{font-size:44px;margin:4px 0 7px}.bottom-row{padding-top:2px}.panel{top:60px}.chart{height:65px}.place{padding:7px 5px;min-height:40px}}
@media(prefers-reduced-motion:reduce){*,*:before,*:after{transition-duration:.01ms!important}}
</style>
</head>
<body>
<svg width="0" height="0" aria-hidden="true" style="position:absolute;overflow:hidden"><defs>
<symbol id="i-map" viewBox="0 0 24 24"><path d="m3 5 6-2 6 3 6-2v15l-6 2-6-3-6 2zM9 3v15m6-12v15"/></symbol>
<symbol id="i-down" viewBox="0 0 16 16"><path d="m3.5 6 4.5 4.5L12.5 6"/></symbol>
<symbol id="i-quiet" viewBox="0 0 24 24"><path d="M4 9h4l5-4v14l-5-4H4zM17.5 9.5l4 5m0-5-4 5"/></symbol>
<symbol id="i-sound" viewBox="0 0 24 24"><path d="M3 9h4l5-4v14l-5-4H3zM16 8a6 6 0 0 1 0 8m3-11a10 10 0 0 1 0 14"/></symbol>
<symbol id="i-mouse" viewBox="0 0 24 26"><rect x="5.5" y="2" width="13" height="21" rx="6.5"/><path d="M12 3v7m-6.3.4h12.6"/><path d="M7.5 8.5c0-2.1 1.1-3.8 3-4.4v4.4z" fill="currentColor" stroke="none"/></symbol>
<symbol id="i-hand" viewBox="0 0 24 24"><path d="M7.5 13.8V6.4a1.6 1.6 0 0 1 3.2 0v5.3-7.2a1.5 1.5 0 0 1 3 0v7-5a1.5 1.5 0 0 1 3 0v5.7-2.9a1.5 1.5 0 0 1 3 0V16c0 4.2-2.2 6.1-5.9 6.1h-1.5c-2.1 0-3.9-1.2-5.3-3.1l-3.4-5a1.7 1.7 0 0 1 2.5-2.1z"/></symbol>
<symbol id="i-play" viewBox="0 0 20 20"><path d="m6.7 4.2 9 5.8-9 5.8z" fill="currentColor" stroke="none"/></symbol>
<symbol id="i-stop" viewBox="0 0 20 20"><rect x="5" y="5" width="10" height="10" rx="1.4" fill="currentColor" stroke="none"/></symbol>
<symbol id="i-close" viewBox="0 0 24 24"><path d="m6 6 12 12m0-12L6 18"/></symbol>
</defs></svg>
<canvas id="sea" tabindex="0" aria-label="Underwater garden. Hold to swim. Drag to turn. Arrow keys turn and W swims forward."></canvas>
<div class="shade"></div><div class="wash" id="wash"></div>
<header>
<div class="identity">
<svg class="seal" viewBox="0 0 44 48" fill="none" aria-hidden="true"><path d="M21.7 2.5C11 2.5 4 10.5 4 22.8c0 10 6.3 18.2 17.7 22.1C33.2 41 40 32.8 40 22.8c0-12.3-7.4-20.3-18.3-20.3Z" stroke="currentColor" stroke-width="1.05"/><g fill="currentColor"><path d="M21.8 39c-1.7-7.5.9-11.9 1.2-16.3.5-6.1-4.1-8.5-.1-16-8 6.7-4.4 12.1-3.3 16.4 1.2 4.6-1 10.1 2.2 15.9Z"/><path d="M20.2 37.2c-2.8-5.3-6.7-6.2-7.7-10.9-.7-3.5 1.3-5.8-2.5-9.8 6.3 2.7 5.1 5.5 5.9 9.5.7 3.7 3.9 5.8 4.3 11.2Zm3.2 1.3c-.1-4.8 1.3-8.7 4.5-12.7 2.8-3.3 3.5-6.8 2-10.6 5.7 5.3 2.3 10.3-.9 14-2.5 2.6-4.4 6.2-5.6 9.3Z"/></g></svg>
<span class="wordmark">Drift Atlas</span></div>
<div class="tools"><button class="glass round" id="sound" aria-label="Turn on underwater sound" aria-pressed="false" title="Underwater sound"><svg><use id="sound-icon" href="#i-quiet"/></svg></button><button class="glass sites" id="sites" aria-controls="panel" aria-expanded="false"><svg><use href="#i-map"/></svg>Dive sites<svg class="chev"><use href="#i-down"/></svg></button></div>
</header>
<div class="heading-tape"><canvas id="compass" aria-label="Compass heading"></canvas></div>
<aside class="depth" aria-label="Depth below the surface"><div class="depth-values"><span class="depth-name">DEPTH</span><span class="depth-num"><span id="depth-value">10.2</span> <small>m</small></span></div><div class="ruler"></div></aside>
<section class="panel" id="panel" aria-label="Dive sites" hidden><div class="panel-head">Dive sites<button class="close" id="close" aria-label="Close dive sites"><svg><use href="#i-close"/></svg></button></div><canvas class="chart" id="chart" aria-label="Map of the three dive sites"></canvas>
<button class="place" data-site="0" aria-current="true"><span class="no">01</span>Kelp Garden<span class="here"></span></button>
<button class="place" data-site="1"><span class="no">02</span>Stone Arch<span class="here"></span></button>
<button class="place" data-site="2"><span class="no">03</span>Sunken Ship<span class="here"></span></button></section>
<footer><div class="site-name" id="site-name"><div class="eyebrow">Dive site <span class="site-count" id="site-count">01 / 03</span></div><h1 id="site-title">Kelp <em>Garden</em></h1></div>
<div class="bottom-row"><div class="gesture"><svg class="mouse-icon"><use href="#i-mouse"/></svg><svg class="touch-icon"><use href="#i-hand"/></svg><span>Hold to swim</span><span class="dot"></span><span>Drag to turn</span></div><button class="drift" id="drift" aria-pressed="false"><span class="play-icon"><svg><use id="drift-icon" href="#i-play"/></svg></span><span class="tour-label" id="drift-label">Guided drift</span></button></div></footer>
<script id="ocean-glsl" type="x-shader/x-part">
precision highp float;
uniform float uTime,uAspect,uFocal;
uniform vec3 uEye,uRight,uUp,uForward;
uniform sampler2D uWater;
const float surfaceY=14.6;
const vec3 sun=vec3(.4624,.8410,-.2803);
vec4 cameraClip(vec3 p){
vec3 d=p-uEye;float z=dot(d,uForward);
return vec4(dot(d,uRight)*uFocal/uAspect,dot(d,uUp)*uFocal,z*1.00090-.12005,z);
}
vec3 waterColor(vec3 ray){
float upper=smoothstep(-.45,.9,ray.y);
float east=.5+.5*dot(ray,normalize(vec3(.35,.38,-.90)));
return mix(vec3(.029,.162,.227),vec3(.099,.385,.455),upper*.63+east*.32)+vec3(.008,.018,.028)*east;
}
float shaft(vec2 q,vec2 v,vec2 source,float w,float endT){
vec2 a=(q-source)*vec2(1.,.65),b=v*vec2(1.,.65);
float b2=max(dot(b,b),.0008);float s=-dot(a,b)/b2;
vec2 nearV=a+s*b;float k=sqrt(b2)/w;
float layer=smoothstep(-1.35,1.35,(endT-s)*k)-smoothstep(-1.35,1.35,-s*k);
return layer*exp(-dot(nearV,nearV)/(w*w))*exp(-max(s,0.)*.022);
}
vec3 scatter(vec3 ray,float endT){
vec2 slope=vec2(.55,-.3333);
vec2 q=uEye.xz+slope*(surfaceY-uEye.y);
vec2 v=ray.xz-slope*ray.y;
q.x+=.10*sin(uTime*.15+q.y*.13);
float l=shaft(q,v,vec2(5.6,-8.),1.65,endT)*.78
+shaft(q,v,vec2(8.25,-8.8),.42,endT)*.75
+shaft(q,v,vec2(3.1,-9.7),.36,endT)*.74
+shaft(q,v,vec2(-3.5,-18.),1.1,endT)*.82
+shaft(q,v,vec2(-5.5,-17.8),.42,endT)*.64
+shaft(q,v,vec2(14.2,-20.),1.85,endT)*.73
+shaft(q,v,vec2(-10.,2.),.8,endT)*.45;
return vec3(.152,.204,.145)*l*(.75+.32*max(ray.y,0.));
}
</script>
<script id="sky-vs" type="x-shader/x-vertex">
attribute vec2 aPosition;varying vec2 screen;
void main(){screen=aPosition;gl_Position=vec4(aPosition,1.,1.);}
</script>
<script id="sky-fs" type="x-shader/x-fragment">
#include_ocean
varying vec2 screen;
void main(){
vec3 rd=normalize(uForward+uRight*screen.x*uAspect/uFocal+uUp*screen.y/uFocal);
vec3 c=waterColor(rd);float endT=115.;
if(rd.y>.003){
float d=(surfaceY-uEye.y)/rd.y;endT=min(d,115.);
vec2 p=uEye.xz+rd.xz*d;
vec2 uv=p*vec2(.052,.082);float t=uTime*.035;
float slow=texture2D(uWater,uv*.43+vec2(t*.11,0.)).g;
vec4 a=texture2D(uWater,uv+vec2(.035*sin(p.y*.38+t),t*.23));
vec4 b=texture2D(uWater,p*vec2(.06,.163)+vec2(t*.19,.07*a.g));
float wave=.5+.5*sin(p.y*3.25+p.x*.56+3.7*a.g+2.0*sin(p.x*.64+t)-t*2.);
float glow=exp(-dot((p-vec2(4.,-9.))*vec2(.065,.051),(p-vec2(4.,-9.))*vec2(.065,.051)));
vec3 surface=mix(vec3(.065,.395,.449),vec3(.36,.70,.66),slow*.55+glow*.42);
surface+=vec3(.135,.175,.14)*(a.r*.78+b.r*.28+pow(wave,8.)*.24);
surface+=vec3(.23,.23,.155)*glow*(.36+.64*pow(max(a.r,b.r*.76),1.7));
float vis=exp(-d*.016)*smoothstep(.02,.19,rd.y);
c=mix(c,surface,vis);
}
c+=scatter(rd,endT);
gl_FragColor=vec4(c,1.);
}
</script>
<script id="light-glsl" type="x-shader/x-part">
vec3 lightSpace(vec3 p){
vec3 l=normalize(vec3(.55,1.,-.3333));
vec3 h=normalize(cross(vec3(0.,1.,0.),l));vec3 v=cross(l,h);
vec3 d=p-vec3(0.,3.,-10.);
return vec3(dot(d,h)/43.,dot(d,v)/43.,-dot(d,l)/57.);
}
</script>
<script id="mesh-vs" type="x-shader/x-vertex">
#include_ocean
#include_light
attribute vec3 aPosition,aNormal,aColor,aDetail;
uniform int uKind;uniform mat4 uModel;uniform float uPhase;
varying vec3 pos,norm,col,detail,shadowCoord;
void main(){
vec3 p=aPosition,n=aNormal;
if(uKind==3){
float h=aDetail.x,phase=aDetail.y;
p.x+=h*(.50*sin(uTime*.48+phase+h*4.6)+.32*sin(uTime*.27+phase*.8+h*2.1));
p.z+=h*.31*cos(uTime*.39+phase+h*3.4);
p.y+=sin(p.x*2.1+p.z*.6+uTime*.68+phase)*.057*abs(aDetail.z)*h;
n.x+=.10*h*cos(uTime*.48+phase+h*4.6);
}else if(uKind==5){
float tail=clamp((.25-p.z)*1.10,0.,1.);float bend=sin(uTime*4.2+uPhase+p.z*4.2);
p.x+=tail*tail*bend*.21;n.z+=tail*bend*.12;
}else if(uKind==6){
float wing=abs(p.x);float wave=sin(uTime*1.06+uPhase-wing*.83);
p.y+=wing*wing*.146*wave;n.x-=sign(p.x)*wing*wave*.22;
p.x+=sin(uTime*1.06+uPhase+p.z*.9)*max(0.,-p.z-.8)*.095;
}
pos=(uModel*vec4(p,1.)).xyz;norm=mat3(uModel)*n;col=aColor;detail=aDetail;
shadowCoord=lightSpace(pos)*.5+.5;gl_Position=cameraClip(pos);
}
</script>
<script id="mesh-fs" type="x-shader/x-fragment">
#include_ocean
uniform int uKind;uniform sampler2D uShadow,uAO;uniform float uShadowStep;
varying vec3 pos,norm,col,detail,shadowCoord;
float visibleAt(vec2 off,float d){vec2 rg=texture2D(uShadow,shadowCoord.xy+off*uShadowStep).rg;return step(d,rg.x+rg.y/255.);}
float sunlit(float nl){
if(uShadowStep<.00001 || max(abs(shadowCoord.x-.5),abs(shadowCoord.y-.5))>.498)return 1.;
float d=shadowCoord.z-(.00052+.00084*(1.-nl));
return .25*(visibleAt(vec2(-.7,-.4),d)+visibleAt(vec2(.4,-.7),d)+visibleAt(vec2(.7,.4),d)+visibleAt(vec2(-.4,.7),d));
}
void main(){
vec3 delta=pos-uEye;float dist=length(delta);vec3 ray=delta/max(.001,dist);
vec3 n=normalize(norm);if(dot(n,-ray)<0.)n=-n;
float nl=max(dot(n,sun),0.);vec3 base=col;
vec2 litUV=(pos.xz+(surfaceY-pos.y)*vec2(.55,-.3333))*.082;
litUV+=vec2(.028*sin(pos.z*.53+uTime*.31),.020*cos(pos.x*.52-uTime*.24));
vec4 water=texture2D(uWater,litUV+vec2(uTime*.0035,-uTime*.002));
float light=water.r;
float vis=sunlit(nl);float contact=1.;float shine=.03;
if(uKind==0){
vec4 sand=texture2D(uWater,pos.xz*.135);
float ripple=.5+.5*sin(pos.z*12.4+pos.x*1.75+1.9*sin(pos.x*.92+pos.z*.25)+2.6*sin(pos.x*.28-pos.z*.31)+sand.g*3.9);
float ridge=pow(ripple,2.6);float nearDetail=1.-smoothstep(16.,55.,dist);
base*=.90+(.16*ridge-.048)*nearDetail+.18*(sand.g-.42);
base+=vec3(.035,.032,.018)*(texture2D(uWater,pos.xz*2.2).b-.5)*nearDetail;
contact=texture2D(uAO,(pos.xz+vec2(64.,80.))/128.).r;
vec3 sandN=normalize(n+vec3(.045,0.,.145)*sin(pos.z*12.4+pos.x*1.75+1.9*sin(pos.x*.92+pos.z*.25)+sand.g*3.9)*nearDetail);
nl=max(dot(sandN,sun),0.);
light=max(light,.30*texture2D(uWater,litUV*1.71+vec2(-uTime*.004,.12)).r);
}else if(uKind==1){
vec2 uv=vec2(pos.x*.39+pos.z*.26,pos.y*.70+pos.z*.05);
vec4 stone=texture2D(uWater,uv*.50);
float band=sin(pos.y*13.7+2.2*stone.g+pos.x*.67+pos.z*.51);
base*=.89+.17*stone.g+.05*band+.08*(texture2D(uWater,uv*2.2).b-.5);
float growth=smoothstep(.52,.79,stone.g)*smoothstep(.13,.93,n.y);
base=mix(base,vec3(.385,.442,.253),growth*.42);
}else if(uKind==2){
float grain=sin(pos.y*86.+2.5*sin(pos.x*3.+pos.z)+water.g*5.);
base*=.90+.13*water.g+.055*grain*(1.-smoothstep(12.,38.,dist));
}else if(uKind==3){
nl=.27+.73*abs(dot(n,sun));
float mid=exp(-abs(detail.z)*28.);float rib=pow(.5+.5*sin(pos.y*22.+abs(detail.z)*7.+pos.x*3.),8.);
base*=.92+.12*water.g+.065*rib;
base+=vec3(.115,.119,.041)*mid*step(.015,abs(detail.z)+.014);
shine=.085;
}else if(uKind==5){shine=.40;}else if(uKind==6){shine=.115;}
vec3 ambient=vec3(.39,.535,.555)+max(n.y,0.)*vec3(.065,.079,.064);
vec3 c=base*(ambient+vec3(.74,.635,.395)*(.12+.88*nl)*(.16+.84*vis));
c*=mix(vec3(.48,.61,.62),vec3(1.),contact);
float focusing=light*(.22+.78*nl)*(.13+.87*vis);
c+=focusing*(base*vec3(.39,.38,.22)+vec3(.067,.087,.051));
float glint=pow(max(dot(n,normalize(sun-ray)),0.),uKind==5?32.:22.);
c+=vec3(.83,.93,.72)*shine*glint*(.35+.65*vis);
float mist=1.-exp(-dist*(.0223+.0041*(1.-smoothstep(0.,13.,pos.y))));
c=mix(c,waterColor(ray),mist);c+=scatter(ray,dist);
gl_FragColor=vec4(c,1.);
}
</script>
<script id="shadow-vs" type="x-shader/x-vertex">
precision highp float;
#include_light
attribute vec3 aPosition;void main(){gl_Position=vec4(lightSpace(aPosition),1.);}
</script>
<script id="shadow-fs" type="x-shader/x-fragment">
precision highp float;
void main(){float d=gl_FragCoord.z;gl_FragColor=vec4(floor(d*255.)/255.,fract(d*255.),0.,1.);}
</script>
<script id="motes-vs" type="x-shader/x-vertex">
#include_ocean
attribute vec3 aPosition,aDetail;uniform float uPixels;
varying float bubble,alpha,seed;
void main(){
vec3 p=aPosition;seed=aDetail.z;bubble=step(.10,aDetail.x);float age;
if(bubble>.5){
age=fract(aDetail.y+uTime*(.019+.011*fract(seed*3.13)));
p.y=mix(p.y,surfaceY-.12,age);
p.x+=(.13+.33*age)*sin(seed+age*10.)+.74*age;
p.z+=.19*sin(seed*1.8+age*9.0);
}else{
age=fract(seed*.08+uTime*.009);
p.x+=sin(uTime*.14+seed)*.46;p.z+=cos(uTime*.17+seed)*.37;
p.y+=sin(uTime*.20+seed)*.32;
}
gl_Position=cameraClip(p);float z=max(.25,gl_Position.w);
float diam=aDetail.x*(bubble>.5?(.63+.64*age):1.);
gl_PointSize=clamp(diam*uPixels*uFocal/(2.*z),1.35,84.);
alpha=exp(-length(p-uEye)*.030)*smoothstep(.35,1.5,z);
if(bubble>.5)alpha*=smoothstep(0.,.06,age)*(1.-smoothstep(.91,1.,age));
}
</script>
<script id="motes-fs" type="x-shader/x-fragment">
precision highp float;varying float bubble,alpha,seed;
void main(){vec2 d=gl_PointCoord*2.-1.;float r=length(d);if(r>=1.)discard;
if(bubble>.5){
float rim=smoothstep(.70,.90,r)*(1.-smoothstep(.92,1.,r));
float gleam=exp(-dot(d-vec2(-.38,-.49),d-vec2(-.38,-.49))*29.);
float lower=exp(-dot(d-vec2(.31,.63),d-vec2(.31,.63))*35.);
vec3 c=mix(vec3(.22,.58,.64),vec3(.89,.96,.83),clamp(rim*.56+gleam+lower*.6,0.,1.));
gl_FragColor=vec4(c,alpha*(.048+.48*rim+.92*gleam+.38*lower));
}else{gl_FragColor=vec4(mix(vec3(.59,.85,.78),vec3(.93,.83,.54),fract(seed*.7)),(1.-r*r)*alpha*.42);}
}
</script>
<script>
'use strict';
(()=>{
const $=id=>document.getElementById(id), TAU=Math.PI*2, PI=Math.PI, S=14.6;
const clamp=(x,a,b)=>Math.max(a,Math.min(b,x)), mix=(a,b,t)=>a+(b-a)*t;
const V=(x,y,z)=>[x,y,z], zero=[0,0,0], up=[0,1,0];
const add=(a,b)=>[a[0]+b[0],a[1]+b[1],a[2]+b[2]], sub=(a,b)=>[a[0]-b[0],a[1]-b[1],a[2]-b[2]];
const mul=(a,s)=>[a[0]*s,a[1]*s,a[2]*s], mad=(a,b,s)=>[a[0]+b[0]*s,a[1]+b[1]*s,a[2]+b[2]*s];
const dot=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2], cross=(a,b)=>[a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]];
const unit=a=>mul(a,1/(Math.hypot(a[0],a[1],a[2])||1)), blend=(a,b,t)=>[mix(a[0],b[0],t),mix(a[1],b[1],t),mix(a[2],b[2],t)];
const rgb=s=>[parseInt(s.slice(0,2),16)/255,parseInt(s.slice(2,4),16)/255,parseInt(s.slice(4,6),16)/255];
let seed=19620417;
function random(){seed=(Math.imul(seed,1664525)+1013904223)>>>0;return seed/4294967296;}
const between=(a,b)=>mix(a,b,random()), pick=a=>a[Math.min(a.length-1,Math.floor(random()*a.length))];
const terrain=(x,z)=>-.21+.39*Math.sin(.195*x+.50*Math.sin(z*.245))+.29*Math.cos(.225*z+x*.092)+.35*Math.cos(.108*x-.076*z)+.13*Math.sin(.45*x+.18*z)+.31*Math.sin(.12*z-.15*x)*Math.cos(.083*x);
const groundNormal=(x,z)=>unit([terrain(x-.08,z)-terrain(x+.08,z),.16,terrain(x,z-.08)-terrain(x,z+.08)]);
const reduced=matchMedia('(prefers-reduced-motion: reduce)').matches;
let sea=$('sea'),gl=null,ctx=null,progs={},screenBuffer,waterTex,aoTex,shadowTex,shadowStep=0;
const identity=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);
const attributes=['aPosition','aNormal','aColor','aDetail'];
function source(id){return $(id).textContent.replace('#include_ocean',$('ocean-glsl').textContent).replace('#include_light',$('light-glsl').textContent);}
function program(vs,fs){
function stage(type,id){const sh=gl.createShader(type);gl.shaderSource(sh,source(id));gl.compileShader(sh);if(!gl.getShaderParameter(sh,gl.COMPILE_STATUS))throw Error(gl.getShaderInfoLog(sh));return sh;}
const vm=stage(gl.VERTEX_SHADER,vs),fm=stage(gl.FRAGMENT_SHADER,fs),p=gl.createProgram();gl.attachShader(p,vm);gl.attachShader(p,fm);
attributes.forEach((name,i)=>gl.bindAttribLocation(p,i,name));gl.linkProgram(p);
if(!gl.getProgramParameter(p,gl.LINK_STATUS))throw Error(gl.getProgramInfoLog(p));
gl.deleteShader(vm);gl.deleteShader(fm);const u={};
const num=gl.getProgramParameter(p,gl.ACTIVE_UNIFORMS);for(let i=0;i<num;i++){const name=gl.getActiveUniform(p,i).name;u[name]=gl.getUniformLocation(p,name);}return {p,u};
}
try{
gl=sea.getContext('webgl',{alpha:false,antialias:true,depth:true,stencil:false,powerPreference:'high-performance'});
if(gl){
progs.sky=program('sky-vs','sky-fs');progs.mesh=program('mesh-vs','mesh-fs');progs.shadow=program('shadow-vs','shadow-fs');progs.motes=program('motes-vs','motes-fs');
screenBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,screenBuffer);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),gl.STATIC_DRAW);
}
}catch(error){console.info('Using the canvas renderer.',error.message);const alternate=sea.cloneNode(false);sea.replaceWith(alternate);sea=alternate;gl=null;}
if(!gl)ctx=sea.getContext('2d',{alpha:false});
const compact=Math.min(innerWidth,innerHeight)<590, simple=!gl;
const camera={p:[0,4.4,12.2],yaw:-.012,pitch:-.043,tyaw:-.012,tpitch:-.043};
let eye=camera.p.slice(),forward=[0,0,-1],right=[1,0,0],upper=[0,1,0],focal=1.72,aspect=1,w=1,h=1,clock=0;
const collisionGrid=new Map(),cellSize=3.5,bodyRadius=.34,rr=bodyRadius*bodyRadius;
const cellKey=(x,z)=>(x+256)*1024+z+256;
function solidFace(a,b,c,n){
let loX=Math.min(a[0],b[0],c[0])-bodyRadius,hiX=Math.max(a[0],b[0],c[0])+bodyRadius;
let loZ=Math.min(a[2],b[2],c[2])-bodyRadius,hiZ=Math.max(a[2],b[2],c[2])+bodyRadius;
if(loX>39||hiX< -39||loZ>25||hiZ< -55)return;
const e=sub(b,a),f=sub(c,a),ee=dot(e,e),ff=dot(f,f),ef=dot(e,f),det=ee*ff-ef*ef;
if(det<1e-12)return;
const t={a,b,c,n,e,f,ee,ff,ef,inv:1/det,loY:Math.min(a[1],b[1],c[1])-bodyRadius,hiY:Math.max(a[1],b[1],c[1])+bodyRadius,loX,hiX,loZ,hiZ};
for(let i=Math.floor(loX/cellSize);i<=Math.floor(hiX/cellSize);i++)for(let j=Math.floor(loZ/cellSize);j<=Math.floor(hiZ/cellSize);j++){const key=cellKey(i,j);let list=collisionGrid.get(key);if(!list){list=[];collisionGrid.set(key,list);}list.push(t);}
}
function edgeDistance(p,a,b){
const x=b[0]-a[0],y=b[1]-a[1],z=b[2]-a[2],ox=p[0]-a[0],oy=p[1]-a[1],oz=p[2]-a[2];
const t=clamp((ox*x+oy*y+oz*z)/(x*x+y*y+z*z||1),0,1);return (ox-x*t)**2+(oy-y*t)**2+(oz-z*t)**2;
}
function blocked(p){
const list=collisionGrid.get(cellKey(Math.floor(p[0]/cellSize),Math.floor(p[2]/cellSize)));if(!list)return false;
for(const t of list){
if(p[1]<t.loY||p[1]>t.hiY||p[0]<t.loX||p[0]>t.hiX||p[2]<t.loZ||p[2]>t.hiZ)continue;
const d=sub(p,t.a);if(Math.abs(dot(d,t.n))>bodyRadius)continue;
const de=dot(d,t.e),df=dot(d,t.f),u=(de*t.ff-df*t.ef)*t.inv,v=(df*t.ee-de*t.ef)*t.inv;
if((u>=0&&v>=0&&u+v<=1)||edgeDistance(p,t.a,t.b)<rr||edgeDistance(p,t.b,t.c)<rr||edgeDistance(p,t.c,t.a)<rr)return true;
}return false;
}
function move(delta){
const len=Math.hypot(...delta);if(len<.00001)return;
const steps=Math.ceil(len/.15),step=mul(delta,1/steps);
function tryStep(d){const a=camera.p,b=add(a,d);b[0]=clamp(b[0],-37.4,37.4);b[2]=clamp(b[2],-53,23.5);b[1]=clamp(b[1],terrain(b[0],b[2])+.65,S-.63);if(blocked(b))return false;camera.p=b;return true;}
for(let i=0;i<steps;i++)if(!tryStep(step)){tryStep([step[0],0,0]);tryStep([0,step[1],0]);tryStep([0,0,step[2]]);}
}
const aoSize=256,aoData=new Uint8Array(aoSize*aoSize).fill(255);
function contact(x,z,rx,rz,strength){
const sx=(x+64)*2,sz=(z+80)*2,wx=rx*2,wz=rz*2;
for(let j=Math.max(0,Math.floor(sz-wz*1.55));j<Math.min(256,Math.ceil(sz+wz*1.55));j++)for(let i=Math.max(0,Math.floor(sx-wx*1.55));i<Math.min(256,Math.ceil(sx+wx*1.55));i++){
const ds=((i+.5-sx)/wx)**2+((j+.5-sz)/wz)**2,k=j*256+i;
aoData[k]=Math.min(aoData[k],255*(1-strength*Math.exp(-ds*1.55)));
}
}
const vertex=(p,c,n=null,d=zero)=>({p,c,n,d});
class Mesh{
constructor(kind,solid=false){this.kind=kind;this.solid=solid;this.count=0;this.parts=[];this.part=null;this.offset=0;this.faces=[];this.buf=null;}
put(v,n){
if(!this.part||this.offset>=this.part.length){this.part=new Float32Array(12288*12);this.parts.push(this.part);this.offset=0;}
const a=this.part;let k=this.offset;const normal=v.n||n;
a[k++]=v.p[0];a[k++]=v.p[1];a[k++]=v.p[2];a[k++]=normal[0];a[k++]=normal[1];a[k++]=normal[2];
a[k++]=v.c[0];a[k++]=v.c[1];a[k++]=v.c[2];a[k++]=v.d[0];a[k++]=v.d[1];a[k++]=v.d[2];this.offset=k;
}
tri(a,b,c){
const norm=cross(sub(b.p,a.p),sub(c.p,a.p));const len=Math.hypot(...norm);if(len<1e-8)return;const n=mul(norm,1/len);
if(this.solid)solidFace(a.p,b.p,c.p,n);
if(gl){this.put(a,n);this.put(b,n);this.put(c,n);}
else this.faces.push([a,b,c,n]);this.count+=3;
}
quad(a,b,c,d){this.tri(a,b,c);this.tri(a,c,d);}
flat(a,b,c,color){this.tri(vertex(a,color),vertex(b,color),vertex(c,color));}
panel(a,b,c,d,color){this.quad(vertex(a,color),vertex(b,color),vertex(c,color),vertex(d,color));}
upload(){if(!gl||!this.count)return;this.buf=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this.buf);gl.bufferData(gl.ARRAY_BUFFER,this.count*48,gl.STATIC_DRAW);let n=0;for(const chunk of this.parts){const part=chunk.subarray(0,Math.min(chunk.length,this.count*12-n));gl.bufferSubData(gl.ARRAY_BUFFER,n*4,part);n+=part.length;}this.parts.length=0;this.part=null;}
bind(shadow=false){gl.bindBuffer(gl.ARRAY_BUFFER,this.buf);for(let i=0;i<(shadow?1:4);i++){gl.enableVertexAttribArray(i);gl.vertexAttribPointer(i,3,gl.FLOAT,false,48,i*12);}}
}
const seabed=new Mesh(0),stones=new Mesh(1,true),timber=new Mesh(2,true),kelp=new Mesh(3),reefs=new Mesh(4),cloth=new Mesh(8,true);
const world=[seabed,stones,timber,kelp,reefs,cloth];
function tube(mesh,a,b,r1,r2,c1,c2=c1,sides=7,d1=zero,d2=d1,caps=false){
const axis=sub(b,a),len=Math.hypot(...axis);if(len<.00001)return;const dir=mul(axis,1/len);
const e=unit(cross(dir,Math.abs(dir[2])>.88?up:[0,0,1])),f=cross(dir,e),lo=[],hi=[];
for(let i=0;i<sides;i++){const ang=i*TAU/sides,n=add(mul(e,Math.cos(ang)),mul(f,Math.sin(ang))),sn=unit(mad(n,dir,(r1-r2)/len));lo.push(vertex(mad(a,n,r1),c1,sn,d1));hi.push(vertex(mad(b,n,r2),c2,sn,d2));}
for(let i=0;i<sides;i++){const j=(i+1)%sides;mesh.quad(lo[i],lo[j],hi[j],hi[i]);if(caps){mesh.tri(vertex(a,c1,mul(dir,-1),d1),lo[j],lo[i]);mesh.tri(vertex(b,c2,dir,d2),hi[i],hi[j]);}}
}
function ellipsoid(mesh,center,scale,color,lons=10,lats=6){
const rings=[];
for(let j=0;j<=lats;j++){const p=-PI/2+PI*j/lats,yy=Math.sin(p),r=Math.cos(p),ring=[];
for(let i=0;i<lons;i++){const a=i*TAU/lons,x=r*Math.cos(a),z=r*Math.sin(a);
ring.push(vertex([center[0]+scale[0]*x,center[1]+scale[1]*yy,center[2]+scale[2]*z],color,unit([x/scale[0],yy/scale[1],z/scale[2]])));}
rings.push(ring);
}
for(let j=0;j<lats;j++)for(let i=0;i<lons;i++){const k=(i+1)%lons;mesh.quad(rings[j][i],rings[j+1][i],rings[j+1][k],rings[j][k]);}
}
function waterTexture(){
const N=256,G=6,grid=[];for(let i=0;i<G*G;i++)grid.push([between(.12,.88),between(.12,.88)]);
const data=new Uint8Array(N*N*4);
for(let y=0;y<N;y++)for(let x=0;x<N;x++){
const u=x/N*TAU,v=y/N*TAU;
const px=x/N*G+.32*Math.sin(v*2+.7*Math.cos(u+v))+.17*Math.sin(3*u+v);
const py=y/N*G+.34*Math.sin(u*2-.7*Math.cos(v-u))+.15*Math.sin(u-3*v);
const bx=Math.floor(px),by=Math.floor(py);let f1=99,f2=99;
for(let j=-1;j<=1;j++)for(let i=-1;i<=1;i++){let ix=bx+i,iy=by+j;const g=grid[((iy%G+G)%G)*G+(ix%G+G)%G];const ds=(ix+g[0]-px)**2+(iy+g[1]-py)**2;if(ds<f1){f2=f1;f1=ds;}else if(ds<f2)f2=ds;}
const edge=Math.sqrt(f2)-Math.sqrt(f1),sq=edge*edge,off=(y*N+x)*4;
const noise=.5+.18*Math.sin(u+2*v+.9*Math.cos(v))+.13*Math.sin(3*u-v)+.09*Math.cos(4*v+2*u)+.06*Math.sin(7*u+4*v)+.03*Math.cos(11*u-9*v);
data[off]=clamp(255*(.74*Math.exp(-sq/.0039)+.26*Math.exp(-sq/.023))*(.71+.40*noise),0,255);
data[off+1]=clamp(noise*255,0,255);data[off+2]=random()*255;data[off+3]=255;
}
const t=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,t);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,N,N,0,gl.RGBA,gl.UNSIGNED_BYTE,data);
gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR_MIPMAP_LINEAR);gl.generateMipmap(gl.TEXTURE_2D);return t;
}
const stoneColors=['536761','667466','586961','657572','475f60','788174','64756a'].map(rgb);
function boulder(x,z,rx,ry,rz,cy=terrain(x,z)+ry*.17,base=pick(stoneColors),quality=1){
const rings=[],a0=between(0,TAU),lean=between(-.21,.21),slant=between(-.1,.1),n=simple?7:quality>1?15:quality===0?8:11,m=simple?4:quality>1?8:quality===0?4:6;
const phase=between(0,TAU);
for(let j=0;j<=m;j++){
const lat=-PI*.5+PI*j/m,sy=Math.sin(lat),width=Math.pow(Math.max(0,Math.cos(lat)),.78),ring=[];
for(let i=0;i<n;i++){
const a=a0+TAU*i/n+.072*Math.sin(j*2.2+phase),bump=1+.085*Math.sin(a*3+phase+sy*1.7)+.055*Math.cos(a*5+sy*3)+between(-.055,.055);
const dx=Math.cos(a)*width*bump,dz=Math.sin(a)*width*bump;
const yy=sy+(j>0&&j<m?between(-.085,.085)*width:0)+slant*dx;
const p=[x+rx*(dx+lean*sy),cy+ry*yy,z+rz*dz];
const col=mul(base,.76+.17*(sy+1)+between(-.045,.048));ring.push(vertex(p,col));
}rings.push(ring);
}
for(let j=0;j<m;j++)for(let i=0;i<n;i++){const k=(i+1)%n;stones.quad(rings[j][i],rings[j+1][i],rings[j+1][k],rings[j][k]);}
if(rx>.23)contact(x,z,rx*1.27,rz*1.27,.64);
}
function arch(cx,cz,scale){
const count=simple?20:34,sides=simple?9:15,rows=[];
for(let i=0;i<=count;i++){
const a=PI*i/count,s=Math.sin(a),c=Math.cos(a);
const center=[cx+scale*(4.07*c+.36*Math.sin(2*a)+.28*s),terrain(cx,cz)-.87+scale*(6.72*Math.pow(Math.max(s,0),.91)+.39*Math.sin(2*a)),cz+scale*(.93*c+.34*Math.sin(2.3*a))];
const row=[];
for(let j=0;j<sides;j++){
const t=TAU*j/sides+.043*Math.sin(4*a),rt=Math.cos(t),dz=Math.sin(t);
const erosion=1+.093*Math.sin(8*a+3*t)+.057*Math.cos(14*a-2*t)+.048*Math.sin(5*t-3*a);
const r=scale*(1.07+.54*c*c+.21*Math.sin(2*a+.4)**2+.10*Math.cos(5*a))*erosion;
const p=[center[0]+c*rt*r,center[1]+s*rt*r,center[2]+dz*r*1.47];
const tint=.5+.28*Math.sin(3*a+t)+.14*Math.cos(9*a-2*t);
let color=blend(rgb('4b6564'),rgb('809080'),clamp(tint,0,1));color=mul(color,(.90+.12*rt)*between(.96,1.04));
row.push(vertex(p,color));
}rows.push(row);
}
for(let i=0;i<count;i++)for(let j=0;j<sides;j++){const k=(j+1)%sides;stones.quad(rows[i][j],rows[i+1][j],rows[i+1][k],rows[i][k]);}
for(const sign of [-1,1]){
contact(cx+sign*4.2*scale,cz+sign*.9*scale,2.55*scale,2.65*scale,.85);
for(let i=0;i<5;i++){const x=cx+sign*(4.2+between(-.55,1.5))*scale,z=cz+(between(-1.8,1.35)+sign*.62)*scale,r=between(.62,1.63)*scale;boulder(x,z,r,between(.75,1.52)*r,r*between(.78,1.36));}
}
}
function makeGround(){
function grid(){const a=[];let x=-144;while(x<144){a.push(x);x+=Math.abs(x)>78?9:Math.abs(x)>45?3.4:(simple?2.85:1.32);}a.push(144);return a;}
const coords=grid(),rows=[],cool=rgb('90a894'),warm=rgb('d8c89b');
for(const z of coords){const row=[];for(const x of coords){
const v=.54+.21*Math.sin(.24*x+.11*z)+.14*Math.cos(.15*z-.12*x)+.08*Math.sin(.61*x-.27*z);
const c=blend(cool,warm,clamp(v,0,1));row.push(vertex([x,terrain(x,z),z],c,groundNormal(x,z)));
}rows.push(row);}
for(let j=0;j<coords.length-1;j++)for(let i=0;i<coords.length-1;i++)seabed.quad(rows[j][i],rows[j+1][i],rows[j+1][i+1],rows[j][i+1]);
}
makeGround();arch(-4.75,-10.85,1);arch(19.2,-39.1,.83);
const outcrops=[
[-7.05,3.75,2.25,1.5,1.92],[-5.28,4.60,1.46,.95,1.32],[-6.05,5.4,1.0,.59,1.13],[-8.65,2.1,2.7,1.65,2.2],
[6.6,4.22,2.10,1.46,1.76],[4.95,3.45,1.52,.92,1.35],[8.23,1.62,2.22,1.78,2.25],[5.44,5.2,.82,.54,.71],
[-9.92,-4.46,2.48,1.85,2.4],[-1.2,-14.32,1.34,.92,1.23],[-1.70,-7.64,.76,.5,.84],[-10,-16.6,2.3,1.37,2.25],
[12.95,-5.85,2.1,1.82,1.87],[13.15,-17,2.14,1.29,1.78],[3,-17.6,1.22,.87,1.32],[-14,10,3.2,2.74,2.75],
[14,12.65,3.4,2.6,3.05],[-4,20.9,2.2,1.55,1.95],[5.6,19.5,2.8,2.35,1.96]
];
for(const q of outcrops)boulder(...q);
for(let i=0;i<(simple?46:83);i++){
const x=between(-44,44),z=between(-56,24);if((Math.abs(x)<11&&z> -18&&z<14)||(x>1&&x<14&&z> -22&&z< -11))continue;
const r=between(.62,2.65);boulder(x,z,r,r*between(.44,1.05),r*between(.72,1.45));
}
for(let i=0;i<(simple?26:48);i++){
const angle=TAU*i/(simple?26:48),dist=between(49,69),x=Math.cos(angle)*dist,z=-13+Math.sin(angle)*dist;
const rad=between(3.1,7.1);boulder(x,z,rad,between(2.8,8.2),rad*between(.74,1.5),terrain(x,z)-.52,pick(stoneColors));
}
for(let i=0;i<(simple?80:300);i++){
const x=between(-19,21),z=between(-27,17),r=Math.pow(random(),2)*.47+.052;
boulder(x,z,r,between(.45,.85)*r,between(.65,1.45)*r,terrain(x,z)+r*.07,pick(stoneColors),0);
}
const shipX=7.75,shipZ=-16.7,shipY=terrain(shipX,shipZ)-.11,shipAng=-2.78;
function shipP(x,y,z){
const roll=.157,yy=Math.cos(roll)*y-Math.sin(roll)*z+.026*x,zz=Math.sin(roll)*y+Math.cos(roll)*z;
return [shipX+x*Math.cos(shipAng)+zz*Math.sin(shipAng),shipY+yy,shipZ-x*Math.sin(shipAng)+zz*Math.cos(shipAng)];
}
const darkWood=rgb('443e2c'),railWood=rgb('99815a'),oldWood=rgb('796444'),ropeColor=rgb('554f34'),patina=rgb('6c7251');
function spar(a,b,r1,r2,c,cap=true){tube(timber,shipP(...a),shipP(...b),r1,r2,c,mul(c,1.06),simple?6:10,zero,zero,cap);}
function line(a,b,sag,r=.024,color=ropeColor){
let prev=a;const steps=simple?4:8;
for(let i=1;i<=steps;i++){const t=i/steps,q=blend(a,b,t);q[1]-=Math.sin(PI*t)*sag;tube(timber,shipP(...prev),shipP(...q),r,r,color,color,5);prev=q;}
}
function box(a,b,color){
const p=[];for(let i=0;i<8;i++)p.push(shipP(i&1?b[0]:a[0],i&2?b[1]:a[1],i&4?b[2]:a[2]));
for(const q of [[0,2,3,1],[4,5,7,6],[0,4,6,2],[1,3,7,5],[2,6,7,3],[0,1,5,4]])timber.panel(p[q[0]],p[q[1]],p[q[2]],p[q[3]],color);
}
function makeShip(){
const stations=[[-5.65,1.35,3.34,.89],[-5.03,1.82,3.26,.49],[-3.82,2.03,2.91,.02],[-2.0,2.12,2.67,-.20],[.03,2.07,2.57,-.26],[2.02,1.86,2.61,-.10],[3.64,1.45,2.84,.13],[4.91,.80,3.20,.49],[5.70,.055,3.54,1.27]];
function at(st,t,side,e=0){return shipP(st[0],mix(st[3],st[2],t),side*(st[1]*Math.pow(Math.sin(t*1.53),.72)+e));}
const boards=['826443','94734b','977b54','6e5b3f','837050','9b8056','74644a'].map(rgb);
for(let i=0;i<stations.length-1;i++){
const a=stations[i],b=stations[i+1];
for(const sign of [-1,1]){
for(let j=0;j<9;j++){
const hole=sign<0&&((i===2&&j>5)||(i===3&&j===8));
if(hole)continue;
const lo=j/9,hi=(j+1)/9;
timber.panel(at(a,lo,sign),at(b,lo,sign),at(b,hi,sign),at(a,hi,sign),darkWood);
const c=mul(pick(boards),.78+.23*hi);
timber.panel(at(a,lo+.006,sign,.014),at(b,lo+.006,sign,.014),at(b,hi-.007,sign,.014),at(a,hi-.007,sign,.014),c);
}
if(!(sign<0&&(i===2||i===3)))tube(timber,at(a,.985,sign,.02),at(b,.985,sign,.02),.093,.092,railWood,railWood,7);
tube(timber,at(a,.65,sign,.015),at(b,.65,sign,.015),.064,.064,darkWood,darkWood,6);
if(i===2||i===3||i===0){
for(let k=0;k<5;k++)tube(timber,at(a,k/5,sign,-.011),at(a,(k+1)/5,sign,-.011),.094,.088,oldWood,patina,6);
}
}
for(let j=0;j<12;j++){
if((i===2||i===3)&&j>=3&&j<=7)continue;
const z0=-1+j/6+.006,z1=-1+(j+1)/6-.006;
timber.panel(shipP(a[0],a[2]-.09,z0*a[1]),shipP(b[0],b[2]-.09,z0*b[1]),shipP(b[0],b[2]-.09,z1*b[1]),shipP(a[0],a[2]-.09,z1*a[1]),pick(boards));
}
}
for(const st of [stations[0],stations[stations.length-1]])for(let j=0;j<9;j++){const u=j/9,v=(j+1)/9;timber.panel(at(st,u,-1),at(st,u,1),at(st,v,1),at(st,v,-1),pick(boards));}
const back=-5.45;box([back,3.2,-1.43],[-3.82,3.90,1.43],oldWood);
for(const sign of [-1,1]){
for(let i=0;i<3;i++){const x=-5.19+i*.44;box([x,3.38,1.44*sign],[x+.27,3.71,1.455*sign],rgb('243c37'));}
spar([back,4.,1.48*sign],[-3.60,3.96,1.48*sign],.067,.061,railWood);
for(let k=0;k<4;k++)spar([-5.38+k*.56,3.97,1.43*sign],[-5.38+k*.56,4.32,1.43*sign],.045,.038,oldWood);
spar([-5.38,4.32,1.43*sign],[-3.7,4.32,1.43*sign],.056,.048,railWood);
}
box([-5.67,3.89,-1.56],[-3.61,4.02,1.56],railWood);
for(let i=0;i<5;i++)box([-3.59+i*.13,3.65-i*.22,-.52],[-3.32+i*.13,3.77-i*.22,.53],pick(boards));
box([.75,2.6,-.68],[2.35,2.74,.68],darkWood);
for(let i=0;i<9;i++)box([.8+i*.174,2.74,-.60],[.86+i*.174,2.79,.60],oldWood);
for(let i=0;i<5;i++)box([.8,2.79,-.59+i*.29],[2.29,2.82,-.55+i*.29],oldWood);
const mastA=[-.58,2.36,.05],mastB=[.06,8.67,.37];
spar(mastA,mastB,.225,.133,oldWood);
for(let i=0;i<5;i++)spar([.055+between(-.09,.1),8.55,.36+between(-.06,.08)],[.09+between(-.14,.11),8.74+between(.02,.28),.36+between(-.12,.12)],.036,.009,railWood);
const yard=[-.02,7.59,.30],along=[.852,-.039,.522];
const a=mad(yard,along,-2.87),b=mad(yard,along,2.87);
spar(a,b,.093,.082,oldWood);
spar([2.75,2.49,-.05],[3.15,4.77,-.45],.166,.094,darkWood);
spar([4.27,2.55,0],[7.04,4.54,.2],.16,.072,oldWood);
line(mastB,[6.86,4.47,.20],.28,.029);line(mastB,[-5.23,4.10,.9],.33,.028);
line(a,[4.48,3.05,-.86],.54,.022);line(b,[-4.0,4.03,1.54],.42,.023);
for(const sign of [-1,1]){
const peak=[-.02,7.91,.29],feet=[];
for(let i=0;i<4;i++){const foot=[-2.21+i*.57,2.65,sign*1.91];feet.push(foot);line(peak,foot,.067,.019);}
for(let i=1;i<11;i++){const t=i/13;line(blend(feet[0],peak,t),blend(feet[3],peak,t),.032,.012);}
}
const nc=22,nr=6,clothRows=[];
const linen=rgb('b2a77c'),aged=rgb('7f8665');
for(let j=0;j<=nr;j++){
const t=j/nr,row=[];for(let i=0;i<=nc;i++){
const u=i/nc,v=2*u-1;
const tear=.23*Math.sin(i*1.7)+.17*Math.sin(i*3.66)+((i===4||i===15||i===19)?.47:0);
const drop=2.05+.51*Math.cos(v*2.4)-tear;
const p=mad(yard,along,v*2.62*(1.-.12*t));p[1]-=.08+t*drop;
p[2]+=t*.15+.47*Math.sin(PI*t)*(.49+.51*(1-v*v))+.18*Math.sin(5.8*v+3.9*t)*t;
p[0]+=.28*t*t+.072*Math.sin(6*u+2*t);
row.push(vertex(shipP(...p),blend(linen,aged,.12+.18*t+.18*(.5+.5*Math.sin(i*1.7)))));
}clothRows.push(row);
}
for(let j=0;j<nr;j++)for(let i=0;i<nc;i++){
if((j>2&&(i===4||i===18))||(j>3&&i>=12&&i<=14)||(j===2&&(i===6||i===7))||(j===5&&i<2))continue;
cloth.quad(clothRows[j][i],clothRows[j][i+1],clothRows[j+1][i+1],clothRows[j+1][i]);
}
for(let i=0;i<8;i++)contact(shipX-4.7+i*1.27,shipZ+(i-3)*-.34,2.05,2.61,.84);
}
makeShip();
const leafPalette=['678d46','8f9e43','557b3c','a1a348','738e3a','9c9f4a','467746','6b9049','879d4d'].map(rgb);
const stipePalette=['757c37','86883c','6c7936','8a8b44'].map(rgb);
function stipe(x,z,y,H,phase,far){
const lean=between(-.59,.93),leanZ=between(-.58,.70),bend=between(.44,1.05),stalk=pick(stipePalette),base=pick(leafPalette);
function point(t){return [x+lean*t*t+bend*t*Math.sin(phase+t*4.8),y+H*t,z+leanZ*t+bend*.53*t*Math.cos(phase+t*4.1)];}
const sections=far?7:13;
for(let j=0;j<sections;j++){const u=j/sections,v=(j+1)/sections;tube(kelp,point(u),point(v),mix(.084,.022,u),mix(.084,.022,v),stalk,stalk,far?4:6,[u,phase,0],[v,phase,0]);}
const ns=Math.max(6,Math.round(H*(far?.80:1.50))),seg=far?5:9;
let angle=phase;
for(let i=0;i<ns;i++){
const t=.065+.91*(i+between(.08,.65))/ns,p=point(t);angle+=2.38+between(-.38,.38);
const dx=Math.cos(angle),dz=Math.sin(angle),len=between(1.01,2.15)*(.62+.46*Math.sin(t*2.9))*(.80+H*.021);
const width=between(.16,.342)*(.86+.2*Math.sin(t*PI)),rise=between(-.16,.83),curl=between(-.5,.5);
const fold=between(.35,1.22),flute=between(0,TAU),sag=between(.13,.36),end=between(-.15,.15);
const c=mul(blend(base,pick(leafPalette),.29),between(.86,1.13)*(.90+.13*t));
let prev;
for(let j=0;j<=seg;j++){
const u=j/seg,sp=Math.sin(PI*u),reach=len*(.92*u+.105*sp),sw=curl*Math.sin(1.67*PI*u)*u+end*u;
const center=[p[0]+dx*reach-dz*sw,p[1]+len*(rise*u+sag*sp+.145*u*Math.sin(6.7*u+flute)),p[2]+dz*reach+dx*sw];
const wide=width*(.017+.983*Math.pow(Math.max(sp,0),.66))*(.90+.13*Math.sin(16.6*u+flute));
const turn=fold+.65*Math.sin(4.5*u+flute),side=[-dz*Math.cos(turn),Math.sin(turn),dx*Math.cos(turn)];
const h=clamp((center[1]-y)/H,0,1.1),row=[];
for(const s of [-1,0,1]){
const pos=mad(center,side,s*wide);pos[1]+=(s===0?.062*sp:.03*sp*Math.sin(18*u+flute+s));
row.push(vertex(pos,mul(c,(s===0?1.09:s<0?.88:1.01)*(.87+.18*u)),null,[h,phase,s]));
}
if(prev){kelp.quad(prev[0],row[0],row[1],prev[1]);kelp.quad(prev[1],row[1],row[2],prev[2]);}prev=row;
}
if(!far&&!simple&&i%4===1){
const q=mad(p,[dx,.33,dz],.15);
tube(kelp,p,q,.041,.069,mul(base,.86),rgb('a2a34b'),5,[t,phase,0],[t,phase,0]);
tube(kelp,q,mad(q,[dx,.36,dz],.105),.069,.022,rgb('a2a34b'),base,5,[t,phase,0],[t,phase,0]);
}
}
}
function ribbon(x,z,y,H,width,phase,angle,col){
const count=simple?8:17,dx=Math.cos(angle),dz=Math.sin(angle),spread=between(.32,1.36),curl=between(.35,.76);let prev;
for(let j=0;j<=count;j++){
const t=j/count,sp=Math.max(0,Math.sin(PI*t)),sweep=spread*t+curl*t*Math.sin(6.75*t+phase),twist=angle+.86*Math.sin(5.1*t+phase);
const cx=x+dx*sweep+.48*t*t,cz=z+dz*sweep;
const wide=width*(.024+.98*Math.pow(sp,.62))*(.86+.15*Math.sin(26*t+phase));
const row=[];for(const e of [-1,0,1]){
row.push(vertex([cx+Math.cos(twist)*wide*e,y+H*t+.063*e*Math.sin(22*t+phase),cz+Math.sin(twist)*wide*e+(e===0?.13*sp:0)],mul(col,(e===0?1.09:e===1?.92:1)*(.74+.35*t)),null,[t*.91,phase,e]));
}
if(prev){kelp.quad(prev[0],row[0],row[1],prev[1]);kelp.quad(prev[1],row[1],row[2],prev[2]);}prev=row;
}
}
const beds=[
[-6.87,4.13,4,12.3],[6.89,4.4,4,12.9],[-8.46,.50,3,13.2],[9.3,.8,3,11.6],[-9.8,-5.6,3,13.8],[-12.9,-9.5,4,13.7],
[-11.53,-15.8,4,12.5],[-7.47,-20.7,2,11.2],[-4.7,-23.8,2,10.8],[-1.74,-29,3,12.8],
[2.44,-25.5,2,10.8],[7.61,-29,4,12.3],[13.99,-21.82,3,13.7],[15.35,-12.95,4,12.8],[12.14,-5.6,3,12.6],
[-1.37,-12.44,1,3.3],[-10.51,12.3,4,12.9],[11.5,11,4,12.4],[-7.7,20.3,3,12.7],[6.7,20.7,3,12.2]
];
for(const [x,z,num,height] of beds){
for(let i=0;i<(simple?Math.ceil(num*.52):num);i++){const xx=x+between(-1.23,1.23),zz=z+between(-1.15,1.15),yy=terrain(xx,zz)+.04,H=Math.min(S-yy-.76,height*between(.62,1.09));stipe(xx,zz,yy,H,between(0,TAU),simple||z< -22);}
contact(x,z,1.1,1.3,.37);
const n=simple?2:5;for(let i=0;i<n;i++){const xx=x+between(-.92,.92),zz=z+between(-.9,.9);ribbon(xx,zz,terrain(xx,zz),between(1.5,4.3),between(.18,.38),between(0,TAU),between(0,TAU),pick(leafPalette));}
}
for(let i=0;i<(simple?18:68);i++){
const a=between(0,TAU),dist=between(25,53),x=Math.cos(a)*dist,z=Math.sin(a)*dist-10;
if(Math.abs(x)<13&&z> -25&&z<18)continue;
const yy=terrain(x,z);
stipe(x,z,yy,Math.min(S-yy-.6,between(6.3,14.)),between(0,TAU),true);
}
function meadow(x,z,rad,count){
for(let i=0;i<count;i++){
const ang=between(0,TAU),r=rad*Math.sqrt(random()),xx=x+r*Math.cos(ang),zz=z+r*.73*Math.sin(ang),yy=terrain(xx,zz),len=between(.20,.99);
const phase=between(0,TAU),col=mul(pick(leafPalette),between(.65,.98));
for(let j=0;j<(simple?4:9);j++){
const a=between(0,TAU),dx=Math.cos(a),dz=Math.sin(a),sz=len*between(.50,1.22),wid=between(.026,.074);
const root=[xx+between(-.13,.13),yy-.02,zz+between(-.13,.13)],end=mad(root,[dx*.53,between(.70,1.1),dz*.53],sz);
const m=blend(root,end,.52);m[1]+=.12*sz;const n=[-dz,0,dx],tip=vertex(end,mul(col,1.16),null,[.18,phase,1]);
const b0=vertex(mad(root,n,-wid*.4),mul(col,.64),null,[0,phase,-1]),b1=vertex(mad(root,n,wid*.4),mul(col,.64),null,[0,phase,1]);
const m0=vertex(mad(m,n,-wid),col,null,[.08,phase,-1]),m1=vertex(mad(m,n,wid),col,null,[.08,phase,1]);kelp.quad(b0,m0,m1,b1);kelp.tri(m0,tip,m1);
}
}
}
for(const [x,z,rad,n] of [[-6.9,4.4,3.6,38],[6.2,3.1,3.52,40],[-7.85,-9.1,3.6,33],[.35,-10.5,2.0,16],[8.2,-15.2,5.4,28],[-12.3,-1.9,4.2,24],[12.6,-5.3,4.4,28],[3.5,15.8,3.1,17],[-6,16.1,3.0,13]])meadow(x,z,rad,simple?Math.ceil(n*.3):n);
const coralOrange=rgb('d77e42'),coralTip=rgb('efa367'),coralRed=rgb('ad552e');
function fan(x,z,y,size,angle,seedOffset=0){
const u=[Math.cos(angle),0,Math.sin(angle)],w=[-Math.sin(angle),0,Math.cos(angle)],start=[x,y,z],base=blend(coralRed,coralOrange,between(.03,.55));
function twig(p,theta,len,r,level,side){
const next=mad(mad(mad(p,u,Math.sin(theta)*len),up,Math.cos(theta)*len),w,between(-.14,.14)*len);
const mid=blend(p,next,.52);mid[0]+=.04*size*Math.sin(theta+level+seedOffset);
const col=blend(base,coralTip,level*.13),endCol=blend(base,coralTip,level*.16+.05);
tube(reefs,p,mid,r,r*.89,col,col,5);tube(reefs,mid,next,r*.89,r*.72,col,endCol,5);
if(level>=(simple?3:compact?4:5)||len<.06)return;
const turn=side*between(.26,.60);
twig(next,clamp(theta+between(-.20,.17)-theta*.06,-1.27,1.27),len*between(.68,.84),r*.74,level+1,-side);
twig(level%2?mid:next,clamp(theta+turn,-1.34,1.34),len*between(.62,.79),r*.60,level+1,side);
}
const root=mad(start,up,size*.15);tube(reefs,start,root,.112*size,.094*size,coralRed,base,7);
for(let i=-2;i<=2;i++)twig(root,i*.42+between(-.09,.09),size*between(.43,.61),size*(.048+.012*(2-Math.abs(i))),0,i>0?1:-1);
}
fan(4.67,4.29,terrain(4.67,4.29)+.62,1.50,-.28);
fan(5.70,3.41,terrain(5.70,3.41)+1.01,1.12,.36,2);
fan(-5.17,4.96,terrain(-5.17,4.96)+.71,1.25,.22,3);
fan(-6.18,4.52,terrain(-6.18,4.52)+1.1,.98,-.35);
fan(-8.75,-8.99,terrain(-8.75,-8.99)+.68,1.44,.08);
fan(-.72,-10.21,terrain(-.72,-10.21)+.28,.94,-.63);
fan(3.20,-16.9,terrain(3.20,-16.9)+.40,1.06,.52);
fan(12.48,-6.91,terrain(12.48,-6.91)+.75,1.29,.91);
fan(-9.6,12,terrain(-9.6,12),1.40,.95);
function sponges(x,z,y,scale,count){
const colors=['b47835','c0873c','c89649','ac743b'].map(rgb);
for(let i=0;i<count;i++){
const a=i*2.399+between(-.4,.4),r=scale*.72*Math.sqrt(i/count),cx=x+r*Math.cos(a),cz=z+r*Math.sin(a),ht=scale*between(.33,.95),radius=ht*between(.16,.27),n=9,col=pick(colors);
const tilt=[Math.cos(a)*ht*.22,0,Math.sin(a)*ht*.22];const rings=[];
for(const [t,k] of [[0,.50],[.25,.65],[.72,.94],[.91,1.13],[1.,1.23],[.988,.89],[.75,.67]]){
const row=[];for(let j=0;j<n;j++){const angle=j*TAU/n,rr=radius*k*(1+.06*Math.sin(angle*3+i));
row.push(vertex([cx+tilt[0]*t+rr*Math.cos(angle),y+ht*t+.027*ht*Math.sin(3*angle+i)*t,cz+tilt[2]*t+rr*Math.sin(angle)],mul(col,k<.85&&t>.5?.35:.72+.35*t)));
}rings.push(row);
}
for(let j=0;j<rings.length-1;j++)for(let k=0;k<n;k++){const kk=(k+1)%n;reefs.quad(rings[j][k],rings[j+1][k],rings[j+1][kk],rings[j][kk]);}
const last=rings[rings.length-1];for(let k=1;k<n-1;k++)reefs.flat(last[0].p,last[k].p,last[k+1].p,mul(col,.25));
}
}
for(const [x,z,s,n,oy] of [[3.95,4.05,.84,9,.08],[-4.12,3.12,.75,7,0],[-.05,-9.95,.91,9,.1],[-7.4,-7.9,.83,6,.3],[3.44,-14.1,.65,10,0],[7.62,5.36,.86,7,.38],[-8.5,14,1.14,9,0]])sponges(x,z,terrain(x,z)+oy,s,n);
function starfish(x,z,r,a){
const center=[x,terrain(x,z)+.071*r+.026,z],c=pick([rgb('d39049'),rgb('b87535'),rgb('db9d55')]);
const outer=[];for(let i=0;i<10;i++){const b=a+i*TAU/10,rr=r*(i%2?.30:between(.79,1.06)),xx=x+Math.cos(b)*rr,zz=z+Math.sin(b)*rr;outer.push([xx,terrain(xx,zz)+.018,zz]);}
for(let i=0;i<10;i++)reefs.flat(center,outer[i],outer[(i+1)%10],mul(c,i%2?.9:1.06));
}
for(let i=0;i<20;i++)starfish(between(-7,8),between(-8,6.7),between(.13,.34),between(0,TAU));
function makeFish(type){
const mesh=new Mesh(5),deep=rgb(type===0?'477c7c':type===1?'346370':'a26732'),belly=rgb(type===0?'ced3b6':type===1?'a8c7bf':'e6bc77');
const flank=rgb(type===0?'a5bca3':type===1?'83a899':'e4a450'),gold=rgb(type===2?'d28136':'d4af56'),fin=rgb(type===1?'82a490':'ab9e66');
const shape=[[-.54,.035,.045],[-.39,.053,.076],[-.20,.121,.157],[.02,.148,.207],[.21,.131,.180],[.36,.098,.125],[.452,.053,.071],[.49,.009,.018]];
const rings=[],sides=simple?8:12;
for(let j=0;j<shape.length;j++){
const [z,w,h]=shape[j],row=[];
for(let i=0;i<sides;i++){const a=i*TAU/sides,sy=Math.sin(a),sx=Math.cos(a),p=[sx*w,sy*h*(type===2?1.28:1),z];
let c=sy>.18?blend(flank,deep,clamp((sy-.18)*1.25,0,1)):blend(flank,belly,clamp(-sy*1.2+.12,0,1));if(type===2&&(j===2||j===4)&&sy>0)c=mul(c,.76);
row.push(vertex(p,c,unit([sx*1.23,sy,.65*(z+.07)])));
}rings.push(row);
}
for(let j=0;j<rings.length-1;j++)for(let i=0;i<sides;i++){const k=(i+1)%sides;mesh.quad(rings[j][i],rings[j][k],rings[j+1][k],rings[j+1][i]);}
for(const sign of [-1,1]){
for(let j=1;j<shape.length-2;j++){
function stripe(k,y){const [z,w,h]=shape[k];return [sign*(w*Math.sqrt(Math.max(.02,1-(y/h)**2))+.002),y,z];}
mesh.panel(stripe(j,.012),stripe(j,.041),stripe(j+1,.041),stripe(j+1,.012),type===1?rgb('aebba4'):gold);
}
ellipsoid(mesh,[sign*.112,.048,.297],[.020,.032,.033],rgb('dac68a'),7,4);
ellipsoid(mesh,[sign*.128,.049,.30],[.009,.020,.020],rgb('1d3536'),7,4);
mesh.flat([sign*.123,.013,.16],[sign*.142,-.082,.10],[sign*.260,-.135,-.130],fin);
}
const root=[0,0,-.49],notch=[0,0,-.625];
for(const side of [-1,1]){const shoulder=[0,side*.079,-.57],tip=[0,side*.236,-.811];
mesh.flat(root,shoulder,tip,gold);mesh.flat(root,tip,notch,mul(gold,.92));mesh.flat([0,.018*side,-.56],[0,.034*side,-.58],tip,mul(gold,1.16));
}
mesh.flat([0,.153,-.19],[.008,.310,-.219],[0,.19,.135],fin);
mesh.flat([0,-.135,-.19],[0,-.240,-.22],[0,-.183,.048],mul(fin,.9));
return mesh;
}
function makeManta(){
const m=new Mesh(6),samples=[[0,1.15,-1.46],[.1,1.14,-1.29],[.21,.99,-.97],[.39,.79,-.76],[.60,.50,-.67],[.80,.08,-.71],[1,-.70,-.72]];
function shape(u,k){for(let j=1;j<samples.length;j++)if(u<=samples[j][0])return mix(samples[j-1][k],samples[j][k],(u-samples[j-1][0])/(samples[j][0]-samples[j-1][0]));return samples[samples.length-1][k];}
const top=rgb('31595f'),tip=rgb('233f4b'),belly=rgb('91aba3'),shoulder=rgb('779492'),rows=simple?16:32,steps=8;
for(const side of [1,-1]){
const grid=[];
for(let i=0;i<=rows;i++){const x=i/rows*2-1,u=Math.abs(x),front=shape(u,1),back=shape(u,2),row=[];
for(let j=0;j<=steps;j++){
const v=j/steps,z=mix(back,front,v),thick=(.034+.215*Math.exp(-u*u*8))*Math.pow(Math.max(0,Math.sin(PI*v)),.73)*(1-u*.94);
const y=.09*u+.13*u**2+.085*Math.sin(PI*v)*(1-u)+thick*side;
const flash=Math.exp(-(((u-.28)/.18)**2+((v-.78)/.17)**2));
let c=side>0?blend(blend(top,tip,u*.72),shoulder,flash*.69):blend(belly,tip,clamp(.14+.55*u**1.6+.21*(1-Math.sin(PI*v)),0,1));
row.push(vertex([x*2.87,y,z],c));
}grid.push(row);
}
for(let i=0;i<rows;i++)for(let j=0;j<steps;j++)m.quad(grid[i][j],grid[i+1][j],grid[i+1][j+1],grid[i][j+1]);
}
let tail=[0,-.010,-1.23];for(let i=1;i<=9;i++){const t=i/9,next=[.12*Math.sin(t*3.5)*t,.032+.14*t,-1.23-2.45*t];tube(m,tail,next,mix(.092,.010,(i-1)/9),mix(.092,.010,t),tip,tip,7);tail=next;}
m.flat([0,.07,-1.12],[0,.37,-1.43],[0,.04,-1.63],top);
for(const sign of [-1,1]){
const p=[sign*.40,.012,.98],q=[sign*.44,.035,1.31],end=[sign*.385,.122,1.58];
tube(m,p,q,.127,.096,top,blend(top,belly,.3),8);tube(m,q,end,.096,.032,blend(top,belly,.3),belly,8);
ellipsoid(m,[sign*.49,.072,.92],[.119,.104,.174],top,9,5);
ellipsoid(m,[sign*.556,.125,.975],[.060,.047,.072],rgb('203a40'),8,4);
for(let j=0;j<5;j++){
const z=.61-j*.17;
const p=[sign*.30,-.154,z],q=[sign*.66,-.089,z-.095];
tube(m,p,q,.022,.011,rgb('4d706e'),rgb('648580'),4);
}
}
return m;
}
const fishMeshes=[makeFish(0),makeFish(1),makeFish(2)],rayMesh=makeManta();
const schools=[];
function school(center,rx,rz,speed,phase,count,type,length,spread,size){
const group={center,rx,rz,speed,phase,type,members:[]};
for(let i=0;i<(simple?Math.ceil(count*.59):count);i++){
const a=between(0,TAU),s=between(-1,1),r=Math.sqrt(1-s*s)*Math.pow(random(),.32);
group.members.push({long:s*length,side:Math.cos(a)*r*spread,y:Math.sin(a)*r*spread*.60,size:size*between(.70,1.26),phase:between(0,TAU)});
}schools.push(group);
}
school([-.66,5.54,-6.12],3.53,2.37,.145,.12,31,0,3.78,1.18,.87);
school([-7.5,7.54,-19.0],4.55,3.0,.12,1.88,32,1,4.8,1.53,.81);
school([3.23,2.68,-2.9],2.63,2.22,.152,2.57,10,2,1.96,1.38,.91);
school([11.8,5.78,-25.7],4.1,2.8,.13,3.04,17,0,3.10,1.13,.77);
school([-7.6,3.05,12.6],3.2,1.8,.16,.64,13,1,2.54,1.13,.72);
const animals=[];
function pose(mesh,x,y,z,heading,pitch,bank,size,phase){
const sh=Math.sin(heading),ch=Math.cos(heading),sp=Math.sin(pitch),cp=Math.cos(pitch),cb=Math.cos(bank),sb=Math.sin(bank);
const rx=ch*cb-sh*sp*sb,ry=cp*sb,rz=-sh*cb-ch*sp*sb;
const ux=-ch*sb-sh*sp*cb,uy=cp*cb,uz=sh*sb-ch*sp*cb;
animals.push({mesh,p:[x,y,z],phase,m:new Float32Array([rx*size,ry*size,rz*size,0,ux*size,uy*size,uz*size,0,sh*cp*size,sp*size,ch*cp*size,0,x,y,z,1])});
}
function wildlife(time){
animals.length=0;
for(const g of schools){const t=time*g.speed+g.phase,s=Math.sin(t),c=Math.cos(t);
const heading=Math.atan2(g.rx*c,-g.rz*s),sh=Math.sin(heading),ch=Math.cos(heading);
const xx=g.center[0]+g.rx*s,zz=g.center[2]+g.rz*c,yy=g.center[1]+.32*Math.sin(t*1.85);
for(const f of g.members){
const side=f.side+.25*Math.sin(time*.64+f.phase),long=f.long+.33*Math.sin(time*.43+f.phase),by=f.y+.105*Math.sin(time*.88+f.phase);
pose(fishMeshes[g.type],xx+ch*side+sh*long,yy+by,zz-sh*side+ch*long,heading+.12*Math.sin(t*2.+f.phase)+.029*long,.045*Math.cos(time*.71+f.phase),.06*Math.sin(time*.65+f.phase),f.size,f.phase);
}
}
const rays=[[-1.1,9.04,-8.4,7.3,5.65,.69,.074,1.22],[-7.3,9.17,-19.5,5.1,4.4,2.14,.091,.91],[10.2,10.85,-36,6.9,5.3,1.47,.08,1.02]];
for(let i=0;i<rays.length;i++){const [x,y,z,rx,rz,init,speed,size]=rays[i],t=init+time*speed;
pose(rayMesh,x+rx*Math.cos(t),y+.33*Math.sin(t*2.3),z+rz*Math.sin(t),Math.atan2(-rx*Math.sin(t),rz*Math.cos(t)),.075*Math.cos(t*2.3),-.14+.18*Math.sin(t*1.51),size,1.4+i*2.07);
}
}
const motes=[],vents=[[-4.35,1.2,2.1],[4.32,.35,.68],[-1.18,.72,-11.0],[7.41,2.9,-15.42],[-9.4,1.0,-7.8],[9.2,1.3,9.2],[-7.2,.5,17.1]];
for(const vent of vents){
const base=terrain(vent[0],vent[2])+vent[1];for(let j=0;j<(simple?9:19);j++){
const r=between(.11,.264);motes.push([vent[0]+between(-.37,.38),base,vent[2]+between(-.32,.32),r,random(),between(0,70)]);
}
}
for(let i=0;i<(simple?95:525);i++)motes.push([between(-26,26),between(.25,14.5),between(-41,23),between(.015,.064),random(),between(0,79)]);
let motesBuffer;
function setupGraphics(){
for(const mesh of [...world,...fishMeshes,rayMesh])mesh.upload();
waterTex=waterTexture();aoTex=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,aoTex);
gl.texImage2D(gl.TEXTURE_2D,0,gl.LUMINANCE,aoSize,aoSize,0,gl.LUMINANCE,gl.UNSIGNED_BYTE,aoData);
gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);
const size=Math.min(gl.getParameter(gl.MAX_TEXTURE_SIZE),gl.getParameter(gl.MAX_RENDERBUFFER_SIZE),compact?1024:2048);
shadowTex=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,shadowTex);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,size,size,0,gl.RGBA,gl.UNSIGNED_BYTE,null);
gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);
const target=gl.createFramebuffer(),depth=gl.createRenderbuffer();gl.bindFramebuffer(gl.FRAMEBUFFER,target);gl.bindRenderbuffer(gl.RENDERBUFFER,depth);
gl.renderbufferStorage(gl.RENDERBUFFER,gl.DEPTH_COMPONENT16,size,size);gl.framebufferRenderbuffer(gl.FRAMEBUFFER,gl.DEPTH_ATTACHMENT,gl.RENDERBUFFER,depth);gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,shadowTex,0);
if(gl.checkFramebufferStatus(gl.FRAMEBUFFER)===gl.FRAMEBUFFER_COMPLETE){
gl.viewport(0,0,size,size);gl.clearColor(1,1,1,1);gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);gl.enable(gl.DEPTH_TEST);gl.disable(gl.BLEND);gl.disable(gl.DITHER);
gl.useProgram(progs.shadow.p);
for(const mesh of [stones,timber,kelp,reefs,cloth]){mesh.bind(true);gl.drawArrays(gl.TRIANGLES,0,mesh.count);}
shadowStep=1/size;
}
gl.bindFramebuffer(gl.FRAMEBUFFER,null);gl.bindRenderbuffer(gl.RENDERBUFFER,null);gl.deleteFramebuffer(target);gl.deleteRenderbuffer(depth);gl.enable(gl.DITHER);gl.clearColor(.06,.27,.32,1);
gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,waterTex);gl.activeTexture(gl.TEXTURE1);gl.bindTexture(gl.TEXTURE_2D,shadowTex);gl.activeTexture(gl.TEXTURE2);gl.bindTexture(gl.TEXTURE_2D,aoTex);gl.activeTexture(gl.TEXTURE0);
motesBuffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,motesBuffer);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(motes.flat()),gl.STATIC_DRAW);
gl.useProgram(progs.mesh.p);const u=progs.mesh.u;gl.uniform1i(u.uWater,0);gl.uniform1i(u.uShadow,1);gl.uniform1i(u.uAO,2);gl.uniform1f(u.uShadowStep,shadowStep);
gl.useProgram(progs.sky.p);gl.uniform1i(progs.sky.u.uWater,0);
}
if(gl)setupGraphics();
let resolutionScale=1;
function resize(){
const cssW=Math.max(1,sea.clientWidth),cssH=Math.max(1,sea.clientHeight);
const maxPixels=gl?(compact?1090000:1980000):600000;
const ratio=Math.min(devicePixelRatio||1,gl?1.65:1,Math.sqrt(maxPixels/(cssW*cssH)))*resolutionScale;
w=Math.max(1,Math.round(cssW*ratio));h=Math.max(1,Math.round(cssH*ratio));sea.width=w;sea.height=h;
aspect=w/h;focal=1/Math.tan((aspect<1?74:aspect>2.3?57:60.5)*PI/360);if(gl)gl.viewport(0,0,w,h);
}
resize();window.addEventListener('resize',resize);
function basis(){
const yaw=camera.yaw,pitch=camera.pitch,sy=Math.sin(yaw),cy=Math.cos(yaw),sp=Math.sin(pitch),cp=Math.cos(pitch);
forward=[sy*cp,sp,-cy*cp];right=[cy,0,sy];upper=cross(right,forward);
eye=camera.p.slice();eye[1]+=(reduced?.004:.026)*Math.sin(clock*.64);
}
function globals(pg){
gl.useProgram(pg.p);const u=pg.u;
gl.uniform1f(u.uTime,clock);gl.uniform1f(u.uAspect,aspect);gl.uniform1f(u.uFocal,focal);
gl.uniform3fv(u.uEye,eye);gl.uniform3fv(u.uRight,right);gl.uniform3fv(u.uUp,upper);gl.uniform3fv(u.uForward,forward);
}
function glFrame(){
gl.depthMask(true);gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);gl.disable(gl.BLEND);gl.disable(gl.DEPTH_TEST);
globals(progs.sky);gl.bindBuffer(gl.ARRAY_BUFFER,screenBuffer);
gl.enableVertexAttribArray(0);for(let i=1;i<4;i++)gl.disableVertexAttribArray(i);gl.vertexAttribPointer(0,2,gl.FLOAT,false,8,0);gl.drawArrays(gl.TRIANGLES,0,3);
gl.enable(gl.DEPTH_TEST);gl.depthFunc(gl.LEQUAL);globals(progs.mesh);const u=progs.mesh.u;gl.uniformMatrix4fv(u.uModel,false,identity);gl.uniform1f(u.uPhase,0);
for(const mesh of world){gl.uniform1i(u.uKind,mesh.kind);mesh.bind();gl.drawArrays(gl.TRIANGLES,0,mesh.count);}
let old=null;
for(const a of animals){
const rel=sub(a.p,eye),z=dot(rel,forward),r=a.mesh.kind===6?6:1.6;
if(z< -r||Math.abs(dot(rel,right))>Math.max(0,z)*aspect/focal+r||Math.abs(dot(rel,upper))>Math.max(0,z)/focal+r)continue;
if(a.mesh!==old){old=a.mesh;gl.uniform1i(u.uKind,old.kind);old.bind();}
gl.uniform1f(u.uPhase,a.phase);gl.uniformMatrix4fv(u.uModel,false,a.m);gl.drawArrays(gl.TRIANGLES,0,old.count);
}
globals(progs.motes);gl.uniform1f(progs.motes.u.uPixels,h);
gl.bindBuffer(gl.ARRAY_BUFFER,motesBuffer);gl.disableVertexAttribArray(1);gl.disableVertexAttribArray(2);gl.enableVertexAttribArray(0);gl.enableVertexAttribArray(3);
gl.vertexAttribPointer(0,3,gl.FLOAT,false,24,0);gl.vertexAttribPointer(3,3,gl.FLOAT,false,24,12);
gl.enable(gl.BLEND);gl.blendFunc(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA);gl.depthMask(false);gl.drawArrays(gl.POINTS,0,motes.length);
gl.depthMask(true);gl.disable(gl.BLEND);
}
function project(p){const d=sub(p,eye),z=dot(d,forward),k=h*focal/(2*Math.max(.06,z));return [w*.5+dot(d,right)*k,h*.5-dot(d,upper)*k,z];}
function modelPoint(p,m){return [m[0]*p[0]+m[4]*p[1]+m[8]*p[2]+m[12],m[1]*p[0]+m[5]*p[1]+m[9]*p[2]+m[13],m[2]*p[0]+m[6]*p[1]+m[10]*p[2]+m[14]];}
let stamp=0;
function canvasFrame(){
const sky=ctx.createLinearGradient(0,0,0,h);sky.addColorStop(0,'#78b8ae');sky.addColorStop(.41,'#337e86');sky.addColorStop(.72,'#1e586c');sky.addColorStop(1,'#174951');ctx.fillStyle=sky;ctx.fillRect(0,0,w,h);
ctx.lineWidth=Math.max(1,h*.0013);for(let i=0;i<38;i++){const y=h*.23*(i/38)**2;ctx.strokeStyle='rgba(203,229,202,'+(.105*(1-i/38))+')';ctx.beginPath();for(let j=0;j<=45;j++){const x=j*w/45,yy=y+(2+2*i/38)*Math.sin(x*.032+i*.74+clock*.29)+1.3*Math.sin(x*.067+i*2);if(j===0)ctx.moveTo(x,yy);else ctx.lineTo(x,yy);}ctx.stroke();}
const draw=[],kLight=[.46,.84,-.28];
function faces(mesh,m,phase){
const key=++stamp;
function point(v){if(v.key===key)return v.screen;let p=v.p;
if(mesh.kind===3){const t=v.d[0],ph=v.d[1];p=[p[0]+t*(.49*Math.sin(clock*.48+ph+t*4.6)+.30*Math.sin(clock*.27+ph*.8+t*2.1)),p[1],p[2]+t*.31*Math.cos(clock*.39+ph+t*3.4)];}
if(mesh.kind===6)p=[p[0],p[1]+p[0]*p[0]*.146*Math.sin(clock*1.06+phase-Math.abs(p[0])*.83),p[2]];
if(mesh.kind===5)p=[p[0]+clamp(.25-p[2],0,1)**2*.21*Math.sin(clock*4.2+phase+p[2]*4.2),p[1],p[2]];
if(m)p=modelPoint(p,m);v.key=key;v.world=p;v.screen=project(p);return v.screen;
}
for(const f of mesh.faces){
const a=point(f[0]),b=point(f[1]),c=point(f[2]);if(Math.min(a[2],b[2],c[2])<.10||Math.min(a[0],b[0],c[0])>w||Math.max(a[0],b[0],c[0])<0||Math.min(a[1],b[1],c[1])>h||Math.max(a[1],b[1],c[1])<0)continue;
const z=(a[2]+b[2]+c[2])/3;if(z>93)continue;
const p=f[0].world,n=f[0].n||f[3],L=m?Math.abs(n[1]*.76+n[0]*.25):Math.abs(dot(n,kLight));
const col=f[0].c,ambient=.64+.41*L,fog=1-Math.exp(-z*.028);
let extra=.015;
if(mesh.kind===0){const s=Math.sin(.82*p[0]+Math.sin(p[2]*1.1+clock*.26))+Math.sin(.94*p[2]+.87*Math.cos(p[0]*.82-clock*.22));extra=.11*Math.exp(-s*s*17);}
const cr=clamp(mix(col[0]*ambient+extra,.095,fog),0,1),cg=clamp(mix(col[1]*(ambient+.05)+extra,.337,fog),0,1),cb=clamp(mix(col[2]*(ambient+.04)+extra*.58,.401,fog),0,1);
draw.push([z,a,b,c,'rgb('+Math.round(cr*255)+','+Math.round(cg*255)+','+Math.round(cb*255)+')']);
}
}
for(const mesh of world)faces(mesh,null,0);
for(const a of animals){const p=project(a.p);if(p[2]<-.6||p[0]<-w*.3||p[0]>w*1.3||p[1]< -h*.3||p[1]>h*1.3)continue;faces(a.mesh,a.m,a.phase);}
draw.sort((a,b)=>b[0]-a[0]);
for(const q of draw){ctx.fillStyle=q[4];ctx.beginPath();ctx.moveTo(q[1][0],q[1][1]);ctx.lineTo(q[2][0],q[2][1]);ctx.lineTo(q[3][0],q[3][1]);ctx.closePath();ctx.fill();}
ctx.save();ctx.globalCompositeOperation='screen';
for(const [x,z,sz] of [[3.1,-9.7,.56],[5.6,-8,2.1],[8.25,-8.8,.6],[-3.5,-18,1.5],[-5.5,-17.8,.6]]){
const top=project([x,S,z]),foot=project([x-S*.55,0,z+S*.333]);if(top[2]<.1||foot[2]<.1)continue;
const width=sz*h*focal/(top[2]*2),g=ctx.createLinearGradient(top[0],top[1],foot[0],foot[1]);g.addColorStop(0,'rgba(210,230,175,.15)');g.addColorStop(1,'rgba(187,210,151,.015)');
ctx.fillStyle=g;ctx.beginPath();ctx.moveTo(top[0]-width*.5,top[1]);ctx.lineTo(top[0]+width*.5,top[1]);ctx.lineTo(foot[0]+width*1.14,foot[1]);ctx.lineTo(foot[0]-width*1.14,foot[1]);ctx.closePath();ctx.fill();
}ctx.restore();
for(const o of motes){const age=(o[4]+clock*(.019+.011*((o[5]*3.13)%1)))%1,b=o[3]>.10;
const p=project([o[0]+(b?.45*Math.sin(o[5]+age*10):.28*Math.sin(clock*.22+o[5])),b?mix(o[1],S-.12,age):o[1],o[2]]);
if(p[2]<.3||p[0]<0||p[0]>w||p[1]<0||p[1]>h)continue;
const r=clamp(o[3]*h*focal/(4*p[2]),.55,35);
ctx.beginPath();ctx.arc(p[0],p[1],r,0,TAU);
if(b){ctx.strokeStyle='rgba(192,228,216,.42)';ctx.lineWidth=Math.max(.7,r*.11);ctx.stroke();ctx.fillStyle='rgba(227,238,210,.77)';ctx.beginPath();ctx.arc(p[0]-.36*r,p[1]-.48*r,Math.max(.45,r*.17),0,TAU);ctx.fill();}
else{ctx.fillStyle='rgba(200,224,195,.32)';ctx.fill();}
}
}
const places=[
{words:['Kelp','Garden'],p:[0,4.4,12.2],aim:[-.25,3.51,-8.5],mark:[0,8.8]},
{words:['Stone','Arch'],p:[-4.35,3.64,-1.92],aim:[-4.62,3.15,-11.1],mark:[-4.75,-10.85]},
{words:['Sunken','Ship'],p:[5.54,4.12,-4.51],aim:[7.63,4.02,-16.64],mark:[7.75,-16.7]}
];
let currentSite=0,siteTimer=0,transitionTimer=0,transitioning=false,touring=false,tourTime=0;
let held=false,activePointer=null,pointerX=0,pointerY=0,speed=0,skipTourClick=false;
const keys=new Set(),panel=$('panel'),buttons=Array.from(document.querySelectorAll('button[data-site]'));
function showSite(index){
if(currentSite===index)return;currentSite=index;clearTimeout(siteTimer);
$('site-name').classList.add('changing');buttons.forEach((b,i)=>b.setAttribute('aria-current',String(i===index)));
siteTimer=setTimeout(()=>{const words=places[index].words;$('site-title').innerHTML=words[0]+' <em>'+words[1]+'</em>';$('site-count').textContent='0'+(index+1)+' / 03';$('site-name').classList.remove('changing');},155);
}
function region(){const [x,,z]=camera.p;
if(Math.hypot((x-7.75)*.92,z+16.7)<13.65&&x>1.08)return 2;
if(Math.hypot(x+4.75,(z+10.85)*.96)<10.15&&x<1.55)return 1;
return 0;
}
function lookAt(target){const d=sub(target,camera.p);camera.yaw=camera.tyaw=Math.atan2(d[0],-d[2]);camera.pitch=camera.tpitch=Math.atan2(d[1],Math.hypot(d[0],d[2]));}
function arrive(site){const s=places[site];camera.p=s.p.slice();lookAt(s.aim);speed=0;showSite(site);}
function fadeTo(action){
clearTimeout(transitionTimer);transitioning=true;$('wash').classList.add('on');held=false;speed=0;
transitionTimer=setTimeout(()=>{action();transitioning=false;$('wash').classList.remove('on');},230);
}
function setTour(on){
touring=on;held=false;speed=0;keys.clear();$('drift').setAttribute('aria-pressed',String(on));$('drift-icon').setAttribute('href',on?'#i-stop':'#i-play');$('drift-label').textContent=on?'End drift':'Guided drift';
if(on)tourTime=0;
}
const route=[
[[0,4.4,12.2],[-.25,3.51,-8.5]],
[[-.51,4.55,9.10],[1.48,6.15,-6.20]],
[[-2.67,4.12,4.11],[-3.85,3.97,-10.73]],
[[-4.05,3.47,-.85],[-4.88,3.14,-11.47]],
[[-3.33,3.65,-3.6],[-1.38,3.92,-12.86]],
[[.51,4.12,-4.0],[7.25,4.24,-16.55]],
[[2.67,4.53,-.20],[7.51,4.32,-15.91]],
[[2.11,4.28,6.46],[2.52,4.03,-9.86]]
];
function curve(a,b,c,d,t){const t2=t*t,t3=t2*t;return .5*((2*b)+(-a+c)*t+(2*a-5*b+4*c-d)*t2+(-a+3*b-3*c+d)*t3);}
function tourStep(dt){
tourTime=(tourTime+dt)%20;const u=tourTime/20*route.length,j=Math.floor(u),t=u-j,n=route.length;
function sample(k){return [0,1,2].map(i=>curve(route[(j-1+n)%n][k][i],route[j][k][i],route[(j+1)%n][k][i],route[(j+2)%n][k][i],t));}
const pos=sample(0);move(sub(pos,camera.p));lookAt(sample(1));showSite(u>=2.12&&u<4.43?1:u>=4.43&&u<6.98?2:0);
}
function showPanel(open){panel.hidden=!open;$('sites').setAttribute('aria-expanded',String(open));if(open){drawChart();buttons[currentSite].focus({preventScroll:true});}}
$('sites').addEventListener('click',()=>showPanel(panel.hidden));$('close').addEventListener('click',()=>{showPanel(false);$('sites').focus({preventScroll:true});});
buttons.forEach((button,i)=>button.addEventListener('click',()=>{setTour(false);showPanel(false);fadeTo(()=>arrive(i));$('sites').focus({preventScroll:true});}));
$('drift').addEventListener('click',()=>{
if(skipTourClick){skipTourClick=false;return;}
if(touring){setTour(false);return;}showPanel(false);
if(Math.hypot(...sub(camera.p,places[0].p))<.35){arrive(0);setTour(true);}
else fadeTo(()=>{arrive(0);setTour(true);});
});
document.addEventListener('pointerdown',event=>{
if(transitioning){clearTimeout(transitionTimer);transitioning=false;$('wash').classList.remove('on');}
skipTourClick=touring&&$('drift').contains(event.target);if(touring)setTour(false);
if(!panel.hidden&&!panel.contains(event.target)&&!$('sites').contains(event.target))showPanel(false);
},{capture:true,passive:true});
function release(id){if(id!=null&&id!==activePointer)return;held=false;activePointer=null;}
sea.addEventListener('pointerdown',event=>{
if((event.pointerType==='mouse'&&event.button!==0)||activePointer!==null)return;
event.preventDefault();sea.focus({preventScroll:true});activePointer=event.pointerId;held=true;pointerX=event.clientX;pointerY=event.clientY;
try{sea.setPointerCapture(activePointer);}catch(_){}
});
window.addEventListener('pointermove',event=>{
if(event.pointerId!==activePointer||!held)return;
const dx=event.clientX-pointerX,dy=event.clientY-pointerY;pointerX=event.clientX;pointerY=event.clientY;
const sensitivity=event.pointerType==='mouse'?.0041:.0051;
camera.tyaw+=dx*sensitivity;camera.tpitch=clamp(camera.tpitch-dy*sensitivity,-1.25,1.25);
},{passive:true});
window.addEventListener('pointerup',e=>release(e.pointerId));window.addEventListener('pointercancel',e=>release(e.pointerId));sea.addEventListener('lostpointercapture',e=>release(e.pointerId));
sea.addEventListener('contextmenu',e=>e.preventDefault());
document.addEventListener('keydown',event=>{
if(event.key==='Escape'&&!panel.hidden){showPanel(false);$('sites').focus({preventScroll:true});return;}
if(event.key==='Escape'&&touring){setTour(false);return;}
if(!panel.hidden||event.target.closest('button'))return;
const key=event.key.toLowerCase();if(['arrowleft','arrowright','arrowup','arrowdown','w','a','s','d'].includes(key)){event.preventDefault();if(touring)setTour(false);keys.add(key);}
});
window.addEventListener('keyup',event=>keys.delete(event.key.toLowerCase()));
function rest(){release();keys.clear();speed=0;}
window.addEventListener('blur',rest);document.addEventListener('visibilitychange',()=>{if(document.hidden)rest();});
function swim(dt){
camera.tyaw+=((keys.has('arrowright')?1:0)-(keys.has('arrowleft')?1:0))*dt*1.13;
camera.tpitch=clamp(camera.tpitch+((keys.has('arrowup')?1:0)-(keys.has('arrowdown')?1:0))*dt*.91,-1.25,1.25);
const smooth=1-Math.exp(-dt*15);camera.yaw=mix(camera.yaw,camera.tyaw,smooth);camera.pitch=mix(camera.pitch,camera.tpitch,smooth);
const desire=((held||keys.has('w')?1:0)-(keys.has('s')?1:0))*2.72;
speed=mix(speed,desire,1-Math.exp(-dt*(desire===0?6.:2.05)));if(Math.abs(speed)<.005)speed=0;
const strafe=((keys.has('d')?1:0)-(keys.has('a')?1:0))*1.70,cp=Math.cos(camera.pitch),sy=Math.sin(camera.yaw),cy=Math.cos(camera.yaw);
if(speed||strafe)move([dt*(sy*cp*speed+cy*strafe),dt*Math.sin(camera.pitch)*speed,dt*(-cy*cp*speed+sy*strafe)]);
}
function fitCanvas(c){
const width=c.clientWidth||226,height=c.clientHeight||44,dpr=Math.min(devicePixelRatio||1,2);
if(c.width!==Math.round(width*dpr)||c.height!==Math.round(height*dpr)){c.width=Math.round(width*dpr);c.height=Math.round(height*dpr);}
const g=c.getContext('2d');g.setTransform(dpr,0,0,dpr,0,0);g.clearRect(0,0,width,height);return {g,width,height,dpr};
}
function drawCompass(){
const {g,width,height}=fitCanvas($('compass')),deg=camera.yaw*180/PI,factor=width/112,center=width/2;
g.textAlign='center';g.textBaseline='top';g.font='10px "Segoe UI", Arial, sans-serif';g.lineWidth=1;
const names=['N','NE','E','SE','S','SW','W','NW'];
for(let k=Math.floor((deg-58)/5)*5;k<=deg+58;k+=5){const x=center+(k-deg)*factor,major=k%45===0,middle=k%15===0;
g.strokeStyle=major?'rgba(242,239,214,.95)':'rgba(219,236,216,.66)';g.beginPath();g.moveTo(Math.round(x)+.5,major?11:middle?14:17);g.lineTo(Math.round(x)+.5,21);g.stroke();
if(major){g.fillStyle=k%360===0?'#f1d398':'#e0e7d7';g.fillText(names[((k/45)%8+8)%8],x,25);}
}
g.fillStyle='#e5c080';g.beginPath();g.moveTo(center-3,3);g.lineTo(center+3,3);g.lineTo(center,8);g.closePath();g.fill();
}
let chartPaper=null,chartDims='';
function drawChart(){
if(panel.hidden)return;
const {g,width,height,dpr}=fitCanvas($('chart')),W=width,H=height;
const bounds=[-26,26,-25,18],mx=x=>(x-bounds[0])/(bounds[1]-bounds[0])*W,mz=z=>(z-bounds[2])/(bounds[3]-bounds[2])*H;
const tag=W+','+H+','+dpr;
if(!chartPaper||chartDims!==tag){
chartDims=tag;chartPaper=document.createElement('canvas');chartPaper.width=Math.round(W*dpr);chartPaper.height=Math.round(H*dpr);
const p=chartPaper.getContext('2d');p.scale(dpr,dpr);p.fillStyle='#123f46';p.fillRect(0,0,W,H);
const nx=36,nz=21,grid=[];
function elevation(x,z){return terrain(x,z)+2.05*Math.exp(-(((x+8)/4)**2+((z+11)/5)**2))+1.40*Math.exp(-(((x-10)/7)**2+((z+14)/4)**2));}
for(let j=0;j<=nz;j++){const row=[];for(let i=0;i<=nx;i++){const x=mix(bounds[0],bounds[1],i/nx),z=mix(bounds[2],bounds[3],j/nz);row.push([i*W/nx,j*H/nz,elevation(x,z)]);}grid.push(row);}
for(let level=-1;level<=2.5;level+=.21){p.strokeStyle='rgba(154,197,171,.27)';p.lineWidth=.68;p.beginPath();
for(let j=0;j<nz;j++)for(let i=0;i<nx;i++){
const q=[grid[j][i],grid[j][i+1],grid[j+1][i+1],grid[j+1][i]],hits=[];
for(let e=0;e<4;e++){const a=q[e],b=q[(e+1)%4];if((a[2]>level)!==(b[2]>level)){const t=(level-a[2])/(b[2]-a[2]);hits.push([mix(a[0],b[0],t),mix(a[1],b[1],t)]);}}
for(let k=1;k<hits.length;k+=2){p.moveTo(hits[k-1][0],hits[k-1][1]);p.lineTo(hits[k][0],hits[k][1]);}
}p.stroke();
}
p.fillStyle='#b6cfc080';p.font='8px Consolas, monospace';p.fillText('N',W-16,13);p.strokeStyle='#b6cfc077';p.beginPath();p.moveTo(W-14,17);p.lineTo(W-14,25);p.stroke();
}
g.drawImage(chartPaper,0,0,W,H);
places.forEach((p,i)=>{const x=mx(p.mark[0]),z=mz(p.mark[1]);g.fillStyle=i===currentSite?'#e2bd7c':'#abcabe';g.beginPath();g.arc(x,z,2.7,0,TAU);g.fill();g.font='9px Consolas, monospace';g.fillText('0'+(i+1),x+6,z-3);});
g.save();g.translate(clamp(mx(eye[0]),4,W-4),clamp(mz(eye[2]),4,H-4));g.rotate(camera.yaw);
g.fillStyle='#efd49b';g.beginPath();g.moveTo(0,-5.8);g.lineTo(3.9,4);g.lineTo(0,2.4);g.lineTo(-3.9,4);g.closePath();g.fill();g.restore();
}
let soundCtx,volume,soundOn=false,soundVersion=0,nextBubble=0;
function buildAudio(){
const AC=window.AudioContext||window.webkitAudioContext;if(!AC)return false;
soundCtx=new AC();volume=soundCtx.createGain();volume.gain.value=0;volume.connect(soundCtx.destination);
const count=Math.floor(soundCtx.sampleRate*5.1),noise=soundCtx.createBuffer(1,count,soundCtx.sampleRate),arr=noise.getChannelData(0);let sample=0;
for(let i=0;i<count;i++){sample=(sample+.052*(Math.random()*2-1))/1.036;arr[i]=sample*2.5;}
for(let i=0;i<384;i++)arr[count-384+i]=mix(arr[count-384+i],arr[i],i/384);
const source=soundCtx.createBufferSource();source.buffer=noise;source.loop=true;
const filter=soundCtx.createBiquadFilter();filter.type='lowpass';filter.frequency.value=480;filter.Q.value=.47;
const drift=soundCtx.createOscillator(),sweep=soundCtx.createGain();drift.frequency.value=.069;sweep.gain.value=112;drift.connect(sweep);sweep.connect(filter.frequency);
source.connect(filter);filter.connect(volume);source.start();drift.start();
for(const [freq,gain] of [[51,.012],[79.4,.006]]){const tone=soundCtx.createOscillator(),g=soundCtx.createGain();tone.frequency.value=freq;g.gain.value=gain;tone.connect(g);g.connect(volume);tone.start();}
return true;
}
function soundUI(){const el=$('sound');el.setAttribute('aria-pressed',String(soundOn));el.setAttribute('aria-label',soundOn?'Mute underwater sound':'Turn on underwater sound');$('sound-icon').setAttribute('href',soundOn?'#i-sound':'#i-quiet');}
$('sound').addEventListener('click',async()=>{
const version=++soundVersion;
try{
if(!soundCtx&&!buildAudio())return;soundOn=!soundOn;soundUI();
if(soundOn){await soundCtx.resume();if(version!==soundVersion)return;volume.gain.cancelScheduledValues(soundCtx.currentTime);volume.gain.setTargetAtTime(.41,soundCtx.currentTime,.19);nextBubble=clock+1.6;}
else{volume.gain.cancelScheduledValues(soundCtx.currentTime);volume.gain.setTargetAtTime(0,soundCtx.currentTime,.06);setTimeout(()=>{if(!soundOn&&version===soundVersion)soundCtx.suspend().catch(()=>{});},290);}
}catch(_){if(version===soundVersion){soundOn=false;soundUI();}}
});
function soundTick(){
if(!soundOn||!soundCtx||soundCtx.state!=='running'||clock<nextBubble)return;
nextBubble=clock+2.1+Math.random()*3.5;const now=soundCtx.currentTime;
for(let i=0;i<2;i++){const o=soundCtx.createOscillator(),g=soundCtx.createGain(),t=now+i*.14,f=between(320,490);o.frequency.setValueAtTime(f,t);o.frequency.exponentialRampToValueAtTime(f*1.48,t+.096);g.gain.setValueAtTime(.0001,t);g.gain.exponentialRampToValueAtTime(.012,t+.016);g.gain.exponentialRampToValueAtTime(.0001,t+.15);o.connect(g);g.connect(volume);o.start(t);o.stop(t+.16);o.onended=()=>{o.disconnect();g.disconnect();};}
}
if(location.href.endsWith('#demo'))setTour(true);
window.addEventListener('hashchange',()=>{if(location.href.endsWith('#demo')){arrive(0);setTour(true);}else if(touring)setTour(false);});
let previous=0,lastFrame=0,lastHud=-1,lastAdjust=0,frameSum=0,samples=0;
function frame(now){
requestAnimationFrame(frame);if(document.hidden){previous=0;return;}
if(!gl&&lastFrame&&now-lastFrame<55)return;lastFrame=now;
const elapsed=previous?Math.max(.001,(now-previous)/1000):1/60;previous=now;
const dt=Math.min(elapsed,.12);clock+=Math.min(elapsed,.25)*(reduced?.72:1);
if(!transitioning){if(touring)tourStep(Math.min(elapsed,.5));else swim(dt);}
basis();wildlife(clock);
if(gl)glFrame();else canvasFrame();
if(now-lastHud>99||lastHud<0){lastHud=now;$('depth-value').textContent=(S-camera.p[1]).toFixed(1);drawCompass();if(!panel.hidden)drawChart();if(!touring&&!transitioning)showSite(region());soundTick();}
if(gl&&elapsed<.18){samples++;frameSum+=elapsed;}
if(gl&&now-lastAdjust>4700){if(samples>20&&frameSum/samples>.039&&resolutionScale>.71){resolutionScale*=.87;resize();}lastAdjust=now;samples=0;frameSum=0;}
}
requestAnimationFrame(frame);
})();
</script>
</body>
</html>
