Skip to content
VibeCodeBench
Back to the app

The code

Lantern Cats 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.)69.9 KB · 1,003 lines · no libraries
Download
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<meta name="theme-color" content="#101922">
<title>Lantern Cats · Paper Theatre</title>
<style>
:root{color-scheme:dark;--ink:#101923;--paper:#f1eadb;--dim:#a7b2bb;--apricot:#f5ac7a;--edge:rgba(205,218,223,.16);--gutter:clamp(18px,3.65vw,76px);--serif:Baskervville,"Palatino Linotype","Book Antiqua",Georgia,serif;--sans:"DM Sans","Segoe UI",system-ui,sans-serif}
*{box-sizing:border-box}
html,body{margin:0;width:100%;height:100%;overflow:hidden;background:var(--ink);color:var(--paper);font-family:var(--sans)}
body{height:100svh;height:100dvh;display:grid;grid-template-rows:auto minmax(0,1fr) auto}
button{font:inherit;color:inherit;cursor:pointer;-webkit-tap-highlight-color:transparent;touch-action:manipulation}
button:focus-visible{outline:2px solid #ffc595;outline-offset:3px}
svg{display:block;overflow:visible}
.mast,.controls{display:flex;align-items:center;justify-content:space-between;padding-inline:var(--gutter);position:relative;z-index:2;background:#111b25}
.mast{min-height:66px;padding-top:env(safe-area-inset-top);border-bottom:1px solid var(--edge)}
.brand{display:flex;align-items:center;gap:12px;white-space:nowrap;font:500 25px/1 var(--serif);letter-spacing:-1.05px}
.brand svg{width:29px;height:36px;color:var(--apricot)}
.tools{display:flex;align-items:center;gap:12px}
.sound,.expand,.leave{display:inline-flex;justify-content:center;align-items:center;min-height:44px;border:1px solid var(--edge);background:rgba(255,255,255,.022)}
.sound{gap:9px;min-width:113px;border-radius:24px;padding:0 17px;font-size:12px;letter-spacing:.025em}
.eq{display:flex;align-items:center;justify-content:center;gap:2px;width:18px;height:17px}
.eq b{width:2px;background:#e7b186;border-radius:2px;height:4px}
.eq b:nth-child(2){height:10px}.eq b:nth-child(3){height:14px}.eq b:nth-child(4){height:7px}
.sound[aria-pressed="true"] .eq b{animation:music 1.2s ease-in-out infinite alternate}
.sound[aria-pressed="true"] .eq b:nth-child(2){animation-delay:-.7s}.sound[aria-pressed="true"] .eq b:nth-child(3){animation-delay:-.35s}.sound[aria-pressed="true"] .eq b:nth-child(4){animation-delay:-.9s}
@keyframes music{from{transform:scaleY(.4)}to{transform:scaleY(1.16)}}
.expand,.leave{width:44px;border-radius:50%}.expand svg,.leave svg{width:17px;height:17px}
.stage{position:relative;min-height:0;isolation:isolate;overflow:hidden;background:linear-gradient(#142336,#536873)}
#world{user-select:none;-webkit-touch-callout:none;position:absolute;inset:0;display:block;width:100%;height:100%;touch-action:none;cursor:grab}
#world.held{cursor:grabbing}
.caption{position:absolute;z-index:1;top:clamp(20px,3.8vh,58px);left:var(--gutter);pointer-events:none;user-select:none}
.overline{display:flex;align-items:center;gap:11px;font-size:clamp(9px,.69vw,12px);letter-spacing:.225em;font-weight:600;color:#e9caaa;text-shadow:0 1px 8px #142231}
.overline .rule{width:29px;height:1px;background:#d2a17f}.jp{font:500 13px/1 "Yu Mincho","MS Mincho",serif;letter-spacing:.14em}
.overline .dot{width:3px;height:3px;border-radius:50%;background:#c79170}
h1{margin:9px 0 0 -3px;font:400 clamp(49px,5.5vw,100px)/1.05 var(--serif);letter-spacing:-.061em;color:#f2eadd;text-shadow:0 2px 20px rgba(10,23,36,.16)}
h1 em{font-family:Baskervville,Georgia,serif;color:#f1bc92;font-weight:400;letter-spacing:-.07em}
.seal{position:absolute;right:var(--gutter);bottom:21px;pointer-events:none;user-select:none;border:1px solid rgba(238,159,116,.65);box-shadow:inset 0 0 0 2px rgba(91,46,43,.36);border-radius:3px 2px 4px 1px;background:rgba(127,59,49,.35);color:#f0aa82;font:15px/.98 "Yu Mincho","Songti SC","MS Mincho",serif;text-align:center;padding:4px 2px 3px;transform:rotate(-3deg)}
.controls{min-height:79px;gap:16px;border-top:1px solid var(--edge);padding-block:9px max(9px,env(safe-area-inset-bottom))}
.guide{display:flex;align-items:center;gap:13px;min-width:0}
.gesture{display:grid;place-items:center;width:40px;height:40px;flex:none;border:1px solid rgba(224,178,137,.25);border-radius:50%;background:#212a31;color:#e9bc95}
.gesture svg{width:24px;height:24px}
.guide strong{display:block;font-weight:520;font-size:14px;letter-spacing:.015em;line-height:1.35}
.guide small{display:block;margin-top:3px;color:var(--dim);font-size:12px;line-height:1.4}
.camera{display:flex;align-items:center;gap:15px}
.camera-label{font-weight:600;color:#aab6bd;font-size:9px;letter-spacing:.19em}
.modes{display:flex;padding:3px;border:1px solid var(--edge);border-radius:9px;background:#0e1620}
.modes button{display:flex;align-items:center;justify-content:center;gap:7px;min-height:44px;padding:0 15px;border:1px solid transparent;border-radius:6px;color:#b4bec5;background:transparent;font-size:12px;line-height:1;transition:background .2s,color .2s}
.modes button[aria-pressed="true"]{color:#f6eddf;background:#293842;border-color:#45535b;box-shadow:0 1px 4px #09111a55}
.modes svg{width:18px;height:18px}.ember{color:#f3a26c}.pearl{color:#c4d3d4}
.leave{display:none;position:fixed;z-index:5;top:max(14px,env(safe-area-inset-top));right:16px;background:#14212bdf}
body.cinema{grid-template-rows:minmax(0,1fr)}.cinema .mast,.cinema .controls,.cinema .caption,.cinema .seal{display:none}.cinema .leave{display:inline-flex}
@media (hover:hover){.sound:hover,.expand:hover,.leave:hover,.modes button:hover{background:#2a3841;color:#fff3e4}}
@media (max-width:670px){.mast{min-height:57px}.brand{gap:8px;font-size:22px}.brand svg{width:25px;height:30px}.tools{gap:6px}.sound{min-width:96px;padding-inline:12px}.expand{border-color:transparent;width:44px}.caption{top:23px}.controls{flex-wrap:wrap;justify-content:center;gap:7px;padding-block:9px max(9px,env(safe-area-inset-bottom))}.guide{justify-content:center;gap:8px;width:100%}.gesture{width:24px;height:24px;background:none;border:0}.gesture svg{width:21px;height:21px}.guide strong{display:inline;font-size:12px}.guide small{display:inline;font-size:11px;margin-left:5px}.camera{gap:10px}.modes{padding:2px}.modes button{min-height:44px;padding-inline:14px}.seal{bottom:13px;font-size:13px}}
@media (max-width:420px){.guide small{font-size:10.5px}.camera-label{font-size:8px}.caption h1{font-size:48px}.overline .rule{width:22px}}
@media (max-height:520px) and (min-aspect-ratio:3/2){.mast{min-height:46px}.brand{font-size:20px}.brand svg{height:26px}.sound,.expand{min-height:44px}.controls{min-height:48px;flex-wrap:nowrap;padding-block:2px}.guide{width:auto}.guide small{display:none}.caption{top:12px}.caption h1{font-size:35px;margin-top:4px}.modes button{min-height:40px}.modes{padding:1px}.seal{bottom:8px}}
@media (prefers-reduced-motion:reduce){*,*::before,*::after{animation-duration:.001ms!important;transition-duration:.001ms!important}}
</style>
</head>
<body>
<header class="mast">
  <div class="brand">
    <svg viewBox="0 0 32 38" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linejoin="round">
      <path d="M16 1v4m-6 1h12M9 8h14c6 4.7 7.2 16.4.3 21H8.7C2.5 24.4 2.4 13 9 8Z" fill="#d88c5d" fill-opacity=".12"/>
      <path d="M12 8C8 14 8 23 12 29m8-21c4 6 4 15 0 21M16 8v21M7.2 11.8q9 2.1 17.6 0M6.4 24.7q9.4 2.1 19.2 0M10 31h12m-6 1v4m-2.2.5 2.2-2.2 2.2 2.2"/>
    </svg>
    <span>Paper Theatre</span>
  </div>
  <div class="tools">
    <button class="sound" id="sound" type="button" aria-pressed="false" aria-label="Play the festival melody"><span class="eq" aria-hidden="true"><b></b><b></b><b></b><b></b></span><span id="soundText">Sound off</span></button>
    <button class="expand" id="expand" type="button" aria-label="Enter immersive view" title="Immersive view"><svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.4"><path d="M2 7V2h5m6 0h5v5M2 13v5h5m6 0h5v-5"/></svg></button>
  </div>
</header>
<main class="stage" id="stage" aria-label="Moonlit lantern festival">
  <canvas id="world" aria-label="An orange and a silver paper-lantern cat fly over a moonlit riverside town. Touch or drag the sky to guide the nearest cat."></canvas>
  <div class="caption"><div class="overline"><span class="rule"></span><span>NIGHT FESTIVAL</span><span class="dot"></span><span class="jp" lang="ja">夜祭</span></div><h1>Lantern <em>Cats</em></h1></div>
  <span class="seal" aria-hidden="true" lang="ja">月<br>夜</span>
</main>
<footer class="controls">
  <div class="guide"><span class="gesture" aria-hidden="true"><svg viewBox="0 0 28 28" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.3"><path d="M9 13.4V7.7c0-2 2.8-2.1 3-.1l.8 5.4.4-1.6c.5-1.4 2.3-1.1 2.6.3l.3.9c1-1.9 2.7-1 2.9.5 1.3-1 2.8 0 2.7 1.4l-.5 5.7c-.2 2-1.6 3.8-3.5 4.1l-3.3.3c-1.7.1-3-.6-4.2-2.1l-4.5-5.9c-1-1.5.8-3.1 2.1-1.9l2.4 2.2Z"/><path d="M4.5 10.2a6.3 6.3 0 0 1 8.8-7M18.5 3.4h5m-1.8-1.7 1.8 1.7-1.8 1.7"/></svg></span><div><strong id="guideTitle">Drag the sky</strong><small id="guideText">The nearest cat will follow your touch.</small></div></div>
  <div class="camera" role="group" aria-label="Camera view"><span class="camera-label">CAMERA</span>
    <div class="modes">
      <button type="button" data-view="wide" aria-pressed="true"><svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="1.8" y="3.8" width="16.4" height="12.4" rx="2"/><path d="m3.5 13 4-4.3 3.2 2.9 2.4-2.4 3.6 4.1"/><circle cx="13.4" cy="7.3" r=".9" fill="currentColor" stroke="none"/></svg>Wide</button>
      <button type="button" data-view="ember" aria-pressed="false"><svg viewBox="0 0 20 20" class="ember" aria-hidden="true"><path d="m3.2 8-.5-5.2 4.9 2.8a9.2 9.2 0 0 1 4.8 0l4.9-2.8-.5 5.2c2.6 6.4-1.7 9-6.8 9s-9.4-2.6-6.8-9Z" fill="currentColor"/><path d="m6 10 .9.5m6.2-.5-.9.5m-2.7 2h1" fill="none" stroke="#603a34" stroke-width="1.3" stroke-linecap="round"/></svg>Ember</button>
      <button type="button" data-view="pearl" aria-pressed="false"><svg viewBox="0 0 20 20" class="pearl" aria-hidden="true"><path d="m3.2 8-.5-5.2 4.9 2.8a9.2 9.2 0 0 1 4.8 0l4.9-2.8-.5 5.2c2.6 6.4-1.7 9-6.8 9s-9.4-2.6-6.8-9Z" fill="currentColor"/><path d="m6 10 .9.5m6.2-.5-.9.5m-2.7 2h1" fill="none" stroke="#344550" stroke-width="1.3" stroke-linecap="round"/></svg>Pearl</button>
    </div>
  </div>
</footer>
<button type="button" class="leave" id="leave" aria-label="Leave immersive view" title="Leave immersive view"><svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.4"><path d="M2 7h5V2m6 0v5h5M2 13h5v5m6 0v-5h5"/></svg></button>
<script>
(() => {
'use strict';
const canvas=document.getElementById('world'), ctx=canvas.getContext('2d',{alpha:false}), stage=document.getElementById('stage');
const TAU=Math.PI*2, sin=Math.sin, cos=Math.cos, clamp=(v,a,b)=>Math.max(a,Math.min(b,v)), mix=(a,b,k)=>a+(b-a)*k, wrap=(v,m)=>(v%m+m)%m;
const still=window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const viewBtns=[...document.querySelectorAll('[data-view]')], guideTitle=document.getElementById('guideTitle'), guideText=document.getElementById('guideText');
let W=0,H=0,unit=1,pixel=1,pad=100,bank=0,cacheScale=1,elapsed=0,demo=location.hash==='#demo',demoClock=0;
let ground,city,overwires,farwires,grain,reflection,refCtx,ambientGlows,lanternSprites,roof,route=[],routeLen=0,startDist=0,cats=[],wisps=[],flecks=[],ripples=[],waterLights=[];
let cam={x:0,y:0,z:1},view='wide',guide=null,touchId=null,lastTime=0,resizePending=true;
function rng(seed){return function(){seed=(Math.imul(1664525,seed)+1013904223)>>>0;return seed/4294967296}}
function hash(n){const a=sin(n*127.1+17.31)*43758.5453;return a-Math.floor(a)}
function noise(x,k){const i=Math.floor(x),f=x-i;return mix(hash(i+k),hash(i+1+k),f*f*(3-2*f))-.5}
function linear(g,x,y,X,Y,stops){const a=g.createLinearGradient(x,y,X,Y);for(let i=0;i<stops.length;i+=2)a.addColorStop(stops[i],stops[i+1]);return a}
function radial(g,x,y,r,stops){const a=g.createRadialGradient(x,y,0,x,y,r);for(let i=0;i<stops.length;i+=2)a.addColorStop(stops[i],stops[i+1]);return a}
function ellipse(g,x,y,a,b,color,angle=0){if(a<=0||b<=0)return;g.beginPath();g.ellipse(x,y,a,b,angle,0,TAU);g.fillStyle=color;g.fill()}
function poly(g,pts,color,stroke,width=1){g.beginPath();g.moveTo(pts[0],pts[1]);for(let i=2;i<pts.length;i+=2)g.lineTo(pts[i],pts[i+1]);g.closePath();g.fillStyle=color;g.fill();if(stroke){g.lineWidth=width;g.strokeStyle=stroke;g.stroke()}}
function line(g,pts,color,width=1){g.beginPath();g.moveTo(pts[0],pts[1]);for(let i=2;i<pts.length;i+=2)g.lineTo(pts[i],pts[i+1]);g.lineWidth=width;g.strokeStyle=color;g.stroke()}
function curve(g,pts,color,width=1){g.beginPath();g.moveTo(pts[0],pts[1]);for(let i=2;i+5<pts.length;i+=6)g.bezierCurveTo(...pts.slice(i,i+6));g.strokeStyle=color;g.lineWidth=width;g.stroke()}
function surface(w,h){const c=document.createElement('canvas');c.width=Math.max(1,Math.ceil(w));c.height=Math.max(1,Math.ceil(h));return c}
function sheet(fn){const c=surface((W+pad*2)*cacheScale,(H+pad*2)*cacheScale),g=c.getContext('2d');g.setTransform(cacheScale,0,0,cacheScale,pad*cacheScale,pad*cacheScale);g.lineCap='round';g.lineJoin='round';fn(g);return c}
function blit(g,c){g.drawImage(c,-pad,-pad,c.width/cacheScale,c.height/cacheScale)}
function worldView(g,depth=1){g.translate(W/2,H/2);g.scale(cam.z,cam.z);g.translate(-W/2-cam.x*depth,-H/2-cam.y*depth)}
function glowSprite(rgb){const c=surface(128,128),g=c.getContext('2d');g.fillStyle=radial(g,64,64,64,[0,'rgba('+rgb+',.8)',.19,'rgba('+rgb+',.49)',.49,'rgba('+rgb+',.16)',1,'rgba('+rgb+',0)']);g.fillRect(0,0,128,128);return c}
function glow(g,kind,x,y,rx,ry,alpha){g.save();g.globalAlpha*=clamp(alpha,0,1);g.drawImage(ambientGlows[kind],x-rx,y-ry,rx*2,ry*2);g.restore()}
function roofMark(x1,x2,top){const a=clamp(Math.floor(x1/4),0,roof.length-1),b=clamp(Math.ceil(x2/4),0,roof.length-1);for(let i=a;i<=b;i++)roof[i]=Math.min(roof[i],top)}
function clearRoof(x,r){const a=clamp(Math.floor((x-r)/4),0,roof.length-1),b=clamp(Math.ceil((x+r)/4),0,roof.length-1);let h=bank;for(let i=a;i<=b;i++)h=Math.min(h,roof[i]);return h}
function altitude(x,r){return clearRoof(x,r)-r-7}


function ridgeHeight(x,points,seed,rough){
  const q=x/W;let i=0;while(i<points.length-2&&points[i+1][0]<q)i++;
  const a=points[i],b=points[i+1],f=clamp((q-a[0])/(b[0]-a[0]),0,1);
  return H*mix(a[1],b[1],f)+rough*(noise(q*44,seed)*15+noise(q*147,seed+7)*8+noise(q*511,seed+3)*3);
}
function mountains(g,pts,seed,top,bottom,detail){
  const rr=rng(seed),yy=x=>ridgeHeight(x,pts,seed,detail),floor=bank+80;
  const path=new Path2D();path.moveTo(-pad,floor);
  for(let x=-pad;x<W+pad+4;x+=3.7)path.lineTo(x,yy(x));
  path.lineTo(W+pad,floor);path.closePath();g.fillStyle=linear(g,0,H*.32,0,bank,[0,top,1,bottom]);g.fill(path);
  g.save();g.clip(path);
  for(let j=1;j<pts.length-1;j++){
    if(pts[j][1]>pts[j-1][1]||pts[j][1]>pts[j+1][1])continue;
    const x=pts[j][0]*W,y=yy(x),len=H*(.063+rr()*.11),reach=W*(.03+rr()*.06);
    g.beginPath();g.moveTo(x,y-1);g.lineTo(x+reach*.19,y+len*.33);g.lineTo(x+reach*.11,y+len*.37);g.lineTo(x+reach*.67,y+len*.72);g.lineTo(x+reach,y+len);g.lineTo(x+reach*2.3,y+len*1.35);g.lineTo(x+reach*.91,y+len*.14);g.closePath();
    g.fillStyle='rgba(171,184,184,.065)';g.fill();
    for(let k=0;k<19;k++){const u=rr(),sx=x+u*reach*.75,sy=y+u*len*.64+rr()*10;curve(g,[sx,sy,sx+4,sy+8,sx+12,sy+9,sx+rr()*26,sy+13+rr()*12],'rgba(187,193,184,.09)',.65)}
  }
  for(let j=0;j<Math.ceil(W*.40);j++){const x=rr()*(W+2*pad)-pad,y=yy(x)+rr()*75;line(g,[x,y,x+rr()*8+1,y+rr()*5+1],'rgba(219,221,201,.062)',.7)}
  g.restore();
}
function windCloud(g,x,y,w,h,opacity){
  g.save();g.translate(x,y);g.scale(w/210,h/29);g.globalAlpha=opacity;
  const p=new Path2D('M-110 7 Q-85 5 -66 4 Q-72 1 -53 -1 Q-44 -9 -20 -5 Q-6 -15 17 -9 Q28 -6 32 -2 Q62 -4 67 2 Q97 1 112 5 Q88 5 76 7 Q45 6 26 9 Q-19 8 -43 10 Q-85 11 -110 7Z');
  g.fillStyle='#a4b3bc';g.fill(p);
  curve(g,[-88,12,-56,13,-38,10,-21,12,6,14,20,11,44,12],'#c9c6b9',.85);
  curve(g,[-20,-6,-7,-13,1,-10,9,-11,26,-11,27,-3,36,-4],'#ded0b6',.8);
  g.restore();
}
function distantTower(g,x,y,k){
  g.save();g.translate(x,y);g.scale(k,k);
  g.fillStyle='#3a505a';g.fillRect(-9,-31,18,32);
  for(let i=0;i<3;i++){const yy=-i*12-3,w=20-i*4;poly(g,[-w,yy,-w*.55,yy-3,-4,yy-9,4,yy-9,w*.55,yy-3,w,yy,w*.8,yy+3,-w*.8,yy+3],'#354a56');g.fillRect(-4,yy-13,8,6)}
  line(g,[0,-35,0,-45],'#364d58',1.2);g.restore();
}
function paintLand(g){
  const r=rng(39566);g.fillStyle=linear(g,0,-pad,0,bank+30,[0,'#0d192a',.19,'#172a42',.48,'#344860',.72,'#5f6d7b',.88,'#8d8584',1,'#ab9486']);g.fillRect(-pad,-pad,W+2*pad,H+2*pad);
  const mx=W*.782,my=H*.196,mr=clamp(W*.043,44,75);
  glow(g,'moon',mx,my,mr*3.65,mr*3.65,.53);
  for(let i=0;i<Math.round(W*.30);i++){
    const x=-pad+r()*(W+2*pad),y=-pad+r()*(H*.63+pad),sz=r();
    if(Math.hypot(x-mx,y-my)<mr*1.04)continue;
    const op=(.22+r()*.64)*clamp(1-(y/H-.2)*1.25,.25,1);
    ellipse(g,x,y,.36+sz*sz*1.02,.36+sz*sz*1.02,'rgba(239,224,201,'+op+')');
    if(sz>.977){glow(g,'moon',x,y,7.7,7.7,.26);line(g,[x-2.6,y,x+2.6,y],'#d9d0bb83',.65);line(g,[x,y-3.3,x,y+3.3],'#e9d9bb95',.65)}
  }
  g.beginPath();g.arc(mx,my,mr*1.28,-2.65,2.1);g.strokeStyle='rgba(236,215,170,.23)';g.lineWidth=.7;g.stroke();
  g.beginPath();g.arc(mx,my,mr*1.39,-1.48,.78);g.strokeStyle='rgba(224,209,174,.12)';g.stroke();
  g.save();g.beginPath();g.arc(mx,my,mr,0,TAU);g.clip();
  g.fillStyle=linear(g,mx-mr,my-mr,mx+mr,my+mr,[0,'#fff0c6',.43,'#f0d9ae',1,'#d8ba99']);g.fillRect(mx-mr-1,my-mr-1,2*mr+2,2*mr+2);
  for(let i=0;i<60;i++){
    const x=mx+(r()-.5)*mr*2,y=my+(r()-.5)*mr*2,rad=mr*(.02+r()*.16);
    ellipse(g,x,y,rad,rad*(.46+r()*.55),'rgba(164,147,137,'+(.025+r()*.06)+')',r()*2);
  }
  for(let i=0;i<1800;i++){g.fillStyle=r()>.55?'rgba(255,247,215,.22)':'rgba(129,108,97,.12)';g.fillRect(mx+(r()-.5)*mr*2,my+(r()-.5)*mr*2,.42+r()*1.1,.36+r()*.7)}
  g.restore();
  windCloud(g,W*.16,H*.262,W*.18,15,.085);windCloud(g,W*.46,H*.18,W*.16,12,.09);
  windCloud(g,mx+mr*.95,my+mr*.38,mr*3.35,14,.34);windCloud(g,mx-mr*1.03,my+mr*.82,mr*2.35,9,.16);
  windCloud(g,W*.992,H*.105,W*.16,10,.10);windCloud(g,W*.33,H*.46,W*.30,17,.095);
  const a=[[-.22,.54],[-.05,.447],[.006,.47],[.09,.393],[.15,.446],[.208,.41],[.294,.503],[.366,.463],[.424,.485],[.51,.395],[.535,.406],[.606,.349],[.65,.405],[.685,.397],[.754,.477],[.837,.395],[.864,.418],[.935,.34],[1.16,.462]];
  const b=[[-.22,.51],[-.04,.469],[.044,.458],[.119,.528],[.190,.473],[.22,.489],[.259,.477],[.325,.545],[.436,.487],[.483,.508],[.58,.453],[.662,.506],[.726,.486],[.803,.535],[.90,.472],[.949,.491],[1.04,.448],[1.20,.502]];
  const c=[[-.2,.53],[-.025,.50],[.067,.546],[.143,.538],[.202,.576],[.294,.555],[.384,.608],[.47,.581],[.57,.606],[.637,.556],[.69,.567],[.744,.528],[.82,.551],[.912,.50],[1.1,.527],[1.25,.55]];
  mountains(g,a,42,'#63778b','#7e8289',1);mountains(g,b,237,'#485e72','#68747d',.92);mountains(g,c,511,'#374e5b','#4d6067',.82);
  for(let x=-pad;x<W+pad;x+=2.6+r()*3.2){
    const y=ridgeHeight(x,c,511,.82),h=2+r()*7.5;poly(g,[x-1.7,y+1,x-.5,y-h*.55,x,y-h,x+1.8,y-.3,x+2.4,y+2],'#3d5360');
  }
  distantTower(g,W*.325,H*.602,.73);distantTower(g,W*.955,H*.52,.58);
  for(let i=0;i<W*.16;i++){
    const x=r()*(W+2*pad)-pad,y=H*(.597+r()*.076),w=6+r()*19,h=4+r()*13;
    g.fillStyle='#465764';g.fillRect(x,y-h,w,h);poly(g,[x-2,y-h+1,x+w*.24,y-h-3,x+w*.74,y-h-3,x+w+2,y-h+1],'#394b59');
    if(r()>.35){g.fillStyle=r()>.35?'#cba27b':'#b3afa0';g.fillRect(x+2+r()*(w-4),y-h*.57,1.2+r()*1.8,1.7)}
  }
  const mist=linear(g,0,H*.52,0,H*.72,[0,'rgba(202,170,140,0)',.7,'rgba(215,178,140,.085)',1,'rgba(200,166,141,0)']);
  g.fillStyle=mist;g.fillRect(-pad,H*.52,W+pad*2,H*.2);
}
function paperLamp(g,x,y,s,tone,lit=true){
  g.save();g.translate(x,y);g.scale(s,s);
  const warm=tone===1,light=tone===2;
  if(lit)glow(g,warm?'gold':'ember',0,1,29,29,light ? .21:.38);
  line(g,[0,-11,0,-7],'#67544b',.8);
  const p=new Path2D('M-4.1-7 Q-8-5-7.8 1 Q-7.6 7-4.2 8 L4.3 8 Q7.8 6.6 7.8.7 Q7.9-4.7 4-7 Z');
  g.fillStyle=linear(g,-8,0,8,1,[0,warm?'#a24f2f':'#893b38',.25,warm?'#edaa58':'#db6241',.53,light?'#ffeac1':warm?'#ffe19a':'#ffab67',.8,warm?'#f4b768':'#ef8453',1,warm?'#aa633e':'#a14438']);g.fill(p);
  g.save();g.clip(p);
  for(let i=-4;i<=5;i+=3.2)curve(g,[-8,i,-4,i+1.8,4,i+1.8,8,i],'#6e454453',.6);
  curve(g,[-2,-7,-4,-1,-3,4,-2,8],'#ffdf9d75',.6);g.restore();
  g.fillStyle='#574044';g.fillRect(-4.3,-7.4,8.6,1.5);g.fillRect(-4.4,7.3,8.8,1.7);
  line(g,[0,9,0,12.5],'#dd975d',.8);line(g,[-1,13,0,11,1.2,13.2],'#b26349',1);g.restore();
}
function paintWires(g,front){
  const rr=rng(front?990:778),sp=Math.min(1.1,W/1370+.1);
  const strand=(x1,y1,x2,y2,sag,large,far)=>{
    x1*=W;x2*=W;y1*=H;y2*=H;sag*=H;
    const cy=(y1+y2)/2+2*sag;
    g.beginPath();g.moveTo(x1,y1);g.quadraticCurveTo((x1+x2)/2,cy,x2,y2);g.strokeStyle=far?'#343e48':'#242c37';g.lineWidth=far?1.25:1.8;g.stroke();
    const n=Math.max(3,Math.floor(Math.hypot(x2-x1,y2-y1)/((large?42:27)*sp)));
    for(let i=1;i<n;i++){const f=i/n,x=mix(x1,x2,f),y=mix(y1,y2,f)+4*sag*f*(1-f),drop=(large?7:3)+rr()*4;line(g,[x,y,x,y+drop],far?'#534f50':'#484047',.8);
      if((i%3!==0&&large)||(!large&&i%3===1)){const size=(large ? .73:.46)*sp*(.75+rr()*.35);paperLamp(g,x,y+drop+7*size,size,i%4===0?0:i%4===2?2:1)}
      else {const size=(large?2.4:1.9)*sp;glow(g,'gold',x,y+drop,size*5.7,size*5.7,.46);ellipse(g,x,y+drop,size*.85,size*1.25,i%2?'#f3b875':'#f8d69c')}
    }
  };
  if(front){
    strand(-.076,.365,.166,.613,.054,true,false);
    strand(.859,.533,1.07,.32,.057,true,false);
  }else{
    strand(-.055,.264,.246,.598,.069,true,true);strand(.246,.598,.491,.625,.043,false,true);
    strand(.491,.625,.728,.582,.042,false,true);strand(.728,.582,1.055,.281,.067,true,true);
    for(const v of [[.246,.598],[.491,.625],[.728,.582]]){line(g,[v[0]*W,H*.738,v[0]*W-1,v[1]*H-5],'#3e4247',2.1);ellipse(g,v[0]*W-1,v[1]*H-6,2,2.3,'#ab947a')}
  }
}


const walls=['#795b50','#71605b','#8b6853','#827064','#5a6062','#65504d','#716559'];
const roofColors=[['#263846','#42505b'],['#27343e','#48505b'],['#2c3a43','#4c595d'],['#333b46','#515765']];
function tiledRoof(g,x,y,w,h,pal,rr,tier=false){
  const l=x-w/2,r=x+w/2,ridge=w*(tier ? .16:.44),left=x-ridge*.63,right=x+ridge*.45;
  const p=new Path2D();p.moveTo(l,y-h*.18);p.bezierCurveTo(l+w*.10,y+h*.01,left-w*.12,y-h*.58,left,y-h);p.lineTo(right,y-h);
  p.bezierCurveTo(right+w*.11,y-h*.58,r-w*.13,y+h*.015,r,y-h*.21);
  p.quadraticCurveTo(r-w*.03,y+h*.02,r-w*.07,y+h*.04);p.quadraticCurveTo(x,y+h*.23,l+w*.055,y+h*.045);p.quadraticCurveTo(l+w*.013,y+h*.01,l,y-h*.18);p.closePath();
  g.fillStyle=linear(g,0,y-h,0,y+h*.1,[0,pal[1],.48,pal[0],1,'#1f2e38']);g.fill(p);
  g.save();g.clip(p);
  const cols=Math.max(6,Math.floor(w/6.5));
  for(let i=0;i<=cols;i++){const f=i/cols,sx=mix(left,right,f),ex=mix(l+1,r-1,f);
    curve(g,[sx,y-h,sx+(ex-sx)*.36,y-h*.53,ex-(ex-sx)*.19,y-h*.095,ex,y+h*.093],'rgba(162,171,174,.35)',.82);
    curve(g,[sx+1.6,y-h,sx+(ex-sx)*.36+1.6,y-h*.53,ex-(ex-sx)*.19+1.3,y-h*.095,ex+1.4,y+h*.093],'rgba(16,29,37,.33)',.8);
  }
  for(let i=1;i<5;i++){const f=i/5,yc=y-h*(1-f);curve(g,[l,yc-h*.21,l+w*.24,yc+h*.12,r-w*.22,yc+h*.12,r,yc-h*.23],'#9aaba61f',.72)}
  g.restore();
  line(g,[left-1,y-h-1,right+1,y-h-1],'#8a9090',1.65);
  curve(g,[l,y-h*.17,l+w*.13,y+h*.16,r-w*.15,y+h*.16,r,y-h*.20],'#82908d',1.3);
  curve(g,[l+2,y-h*.12,l+w*.13,y+h*.24,r-w*.13,y+h*.24,r-1,y-h*.14],'#1b2934',2);
  if(w>65){
    for(let i=2;i<cols;i++){const f=i/cols,yy=y+h*(.105-.90*(f-.5)*(f-.5));ellipse(g,l+w*f,yy,1.4,1,'#707d7d')}
    if(rr()>.38||tier){curve(g,[l+3,y-h*.10,l-1,y-h*.22,l-1,y-h*.34,l+.6,y-h*.34],'#899593',1.15);curve(g,[r-3,y-h*.12,r+2,y-h*.25,r+1,y-h*.38,r,y-h*.36],'#8a9793',1.15)}
  }
}
function windowPanel(g,x,y,w,h,rr,lit,far){
  g.fillStyle=far?'#37434a':'#372f32';g.fillRect(x-1,y-1,w+2,h+2);
  if(lit){
    const bright=rr();
    g.fillStyle=linear(g,x,y,x+w*.7,y+h,[0,bright>.48?'#e9aa71':'#ce9463',.56,bright>.52?'#ffdc96':'#edbc80',1,bright>.45?'#e7ad74':'#cc8c61']);g.fillRect(x,y,w,h);
    g.fillStyle='rgba(255,204,133,.10)';g.fillRect(x-2,y-2,w+4,h+4);
  }else{g.fillStyle=rr()>.4?'#485760':'#384952';g.fillRect(x,y,w,h)}
  const timber=far?'#544b45':'#674d42';g.fillStyle=timber;const n=Math.max(1,Math.round(w/6));
  for(let i=1;i<n;i++)g.fillRect(x+w*i/n-.43,y,.86,h);
  g.fillRect(x,y+h*.47,w,.85);
  if(h>13&&!far)g.fillRect(x,y+h*.23,w,.65);
  g.fillStyle=lit?'#bf926c':'#686b65';g.fillRect(x-1,y+h,w+2,1);
}
function house(g,x,y,w,floors,rr,far=false){
  const fh=w*(.20+rr()*.075),h=fh*floors,side=w*.144,top=y-h,rh=w*(.145+rr()*.082),wall=walls[Math.floor(rr()*walls.length)],rp=roofColors[Math.floor(rr()*roofColors.length)];
  const l=x-w*.48,r=x+w*.34,back=top-w*.051;
  roofMark(l-4,x+w*.51,top-rh-3);
  g.fillStyle=wall;g.fillRect(l,top,r-l,h+1);
  poly(g,[r,top,r+side,back,r+side,y-w*.051,r,y],'#4a4648');
  g.fillStyle=linear(g,0,top,0,y,[0,'rgba(8,22,31,.35)',.34,'rgba(35,31,35,.025)',1,'rgba(23,29,33,.20)']);g.fillRect(l,top,r-l,h+1);
  for(let i=0;i<floors;i++){
    const yy=top+i*fh,gap=w*.045,ww=(r-l-gap*3)/2,wh=fh*.49;
    for(let j=0;j<2;j++)windowPanel(g,l+gap+(ww+gap)*j,yy+fh*.24,ww,wh,rr,rr()>(far ? .39:.22),far);
    poly(g,[r+side*.19,yy+fh*.24,r+side*.77,yy+fh*.24-w*.027,r+side*.77,yy+fh*.68-w*.027,r+side*.19,yy+fh*.68],rr()>.45?'#b18460':'#3d4a4d');
    line(g,[r+side*.45,yy+fh*.25-w*.012,r+side*.45,yy+fh*.68-w*.012],'#55463f',.9);
    g.fillStyle=far?'#454346':'#493c37';g.fillRect(l,yy+fh*.83,r-l,1.7);g.fillRect(l+gap*.35,yy,1.6,fh);g.fillRect(r-2,yy,2,fh);
    if(i>0&&w>55)tiledRoof(g,x-.03*w,yy+1,w*1.02,fh*.20,rp,rr);
  }
  if(!far&&w>58){
    if(rr()>.37){
      const yy=y-fh*.79,num=4+Math.floor(rr()*3),aw=w*.38;
      line(g,[l+w*.035,yy-1,l+w*.035+aw,yy-1],'#312e31',1.65);
      const cloth=rr()>.52?'#99584c':'#425f68';
      for(let j=0;j<num;j++){const sx=l+w*.035+aw*j/num;poly(g,[sx,yy,sx+aw/num-.5,yy,sx+aw/num-1.2,yy+fh*.26,sx,yy+fh*.23],cloth);line(g,[sx+1,yy+fh*.17,sx+aw/num-1,yy+fh*.18],'#d9b38888',.6)}
    }
    if(rr()>.48){
      const sx=r-w*.045,sy=top+fh*.2;g.fillStyle='#442f32';g.fillRect(sx-1,sy-1,w*.09+2,fh*.86+2);g.fillStyle=rr()>.45?'#a85643':'#c89d70';g.fillRect(sx,sy,w*.09,fh*.86);
      for(let i=0;i<3;i++){const yy=sy+3+i*fh*.24;line(g,[sx+1.7,yy,sx+w*.067,yy-.4,sx+w*.048,yy+2.5,sx+w*.03,yy+2.9],'#f4c696',.65)}
    }
    if(rr()>.27)paperLamp(g,l+3,y-fh*.63,w*.0067,rr()>.58?1:0);
  }
  tiledRoof(g,x,top-1,w*1.12,rh,rp,rr);
  if(far){g.fillStyle='rgba(92,105,115,.20)';g.fillRect(l,top+2,r-l,h-2)}
}
function pine(g,x,y,h,seed,back=false){
  const rr=rng(seed),dir=rr()>.48?1:-1,ink=back?'#354950':'#253b40',leaf=back?'#3c5054':'#324a4a';
  g.save();g.translate(x,y);g.scale(dir*h/100,h/100);
  curve(g,[0,1,-3,-23,13,-41,8,-55,7,-66,13,-80,16,-91],ink,4.4);
  for(let j=0;j<6;j++){
    const t=j/6,yy=-22-65*t,side=j%2?-1:1,xx=8+t*8,reach=(33-19*t)*side;
    curve(g,[xx,yy,xx+reach*.38,yy-1,xx+reach*.63,yy-14,xx+reach,yy-11],ink,2.6-t);
    const cx=xx+reach,cy=yy-12;
    for(let k=0;k<14;k++){const px=cx+(rr()-.5)*(37-15*t),py=cy+(rr()-.5)*6+.008*(px-cx)*(px-cx);ellipse(g,px,py,4.5+rr()*7.5,2.7+rr()*3.2,k%4?ink:leaf,-.16*side)}
    for(let k=0;k<12;k++){const px=cx+(rr()-.5)*(39-15*t),py=cy-2+rr()*4;line(g,[px-2,py+1.5,px,py-2.8,px+2,py],'#66746a55',.65)}
  }
  for(let k=0;k<12;k++)ellipse(g,15+(rr()-.5)*15,-90+(rr()-.5)*4,3+rr()*5,3,ink);
  g.restore();
}
function pagoda(g,x,y,s,rr){
  g.save();g.translate(x,y);g.scale(s,s);
  const palettes=[['#293741','#56616a'],['#283641','#505e68'],['#2d3943','#59636a']];
  poly(g,[-47,0,-47,-6,-39,-13,40,-13,47,-5,47,0],'#655e58');
  for(let j=0;j<3;j++){
    const yy=-12-j*34,ww=79-j*17,hh=24-j*1.8;
    g.fillStyle=j%2?'#92715e':'#90604e';g.fillRect(-ww/2,yy-hh,ww,hh);
    for(let k=0;k<5;k++){const wx=-ww*.43+k*ww*.173;windowPanel(g,wx,yy-hh+2.8,ww*.125,hh*.61,rr,k!==1||j===1,false)}
    for(let k=0;k<=6;k++){const xx=-ww/2+ww*k/6;g.fillStyle='#624338';g.fillRect(xx-1.35,yy-hh,2.7,hh)}
    g.fillStyle='#b3744e';g.fillRect(-ww*.56,yy-2.5,ww*1.12,2.7);
    for(let k=0;k<10;k++){const xx=-ww*.52+k*ww*.116;line(g,[xx,yy-1,xx,yy-6.8],'#986847',1.4)}
    line(g,[-ww*.58,yy-7.5,ww*.58,yy-7.5],'#c38c5f',1.6);
    const rw=ww*1.46,ry=yy-hh-1,rh=j===2?22:18;
    tiledRoof(g,-1,ry,rw,rh,palettes[j],rr,true);
    for(const sign of [-1,1]){const tx=-1+sign*rw*.485;line(g,[tx,ry-1.5,tx,ry+3.5],'#b59770',.7);ellipse(g,tx,ry+5,1.7,2.1,'#d6b27b')}
    roofMark(x-rw*s*.5,x+rw*s*.5,y+(ry-rh)*s-2);
  }
  const apex=-122;line(g,[0,apex+3,0,apex-23],'#3e4148',2.4);
  for(let j=0;j<5;j++)ellipse(g,0,apex-2-j*3,4.8-j*.68,1.45,'#555557');
  ellipse(g,0,apex-19,1.9,3,'#ba9a76');line(g,[0,apex-21,0,apex-25],'#756c64',1.2);
  roofMark(x-3*s,x+3*s,y+(apex-25)*s);
  g.restore();
}
function bridge(g,x,y,w){
  const h=w*.135,rr=rng(730);
  const p=new Path2D();p.moveTo(x-w/2,y);p.quadraticCurveTo(x,y-h*2.04,x+w/2,y);p.lineTo(x+w/2,y+h*.21);p.quadraticCurveTo(x,y-h*1.56,x-w/2,y+h*.21);p.closePath();
  g.fillStyle='#5b5253';g.fill(p);
  g.beginPath();g.moveTo(x-w/2,y-1);g.quadraticCurveTo(x,y-h*2.04-2,x+w/2,y-1);g.strokeStyle='#cf9d76';g.lineWidth=2.3;g.stroke();
  const posts=15,pnts=[],pnts2=[];
  for(let i=0;i<=posts;i++){
    const f=i/posts,xx=x-w/2+f*w,yy=y-4*h*1.02*f*(1-f),top=yy-h*.35;
    line(g,[xx,yy,xx,top],'#6c4541',2.45);ellipse(g,xx,top-.4,1.7,1.55,'#cf9c70');pnts.push(xx,top+1);pnts2.push(xx,top+h*.14);
    if(i===1||i===posts-1){line(g,[xx,top,xx,top-h*.55],'#574646',1.7);paperLamp(g,xx,top-h*.63,.58,i===1?1:0)}
    if(i>1&&i<posts-1&&rr()>.55){const sy=yy-4;ellipse(g,xx+3,sy-5.2,1.65,2.1,'#2b3540');poly(g,[xx+1,sy-3.8,xx+4,sy-3.8,xx+5.5,sy+3,xx-.4,sy+3],rr()>.48?'#754d45':'#34424c')}
  }
  line(g,pnts,'#a66c55',1.8);line(g,pnts2,'#815548',1.2);
  roofMark(x-w/2,x+w/2,y-h*1.42);
}
function paintTown(g){
  const r=rng(7783),S=clamp(W/1420,.73,1.22),cen=W*.524,gap=clamp(W*.164,105,272);
  for(let i=0;i<Math.ceil(W/46)+6;i++){
    const x=-pad+(W+2*pad)*i/(Math.ceil(W/46)+5),base=H*(.689+.027*r());
    if(r()>.30)pine(g,x,base,25+r()*34,Math.floor(r()*9999),true);
  }
  let x=-pad-45;
  while(x<W+pad+60){
    const w=(37+r()*40)*S,base=H*(.685+.034*r());house(g,x+w/2,base,w,1+(r()>.40?1:0),r,true);x+=w*(.73+r()*.18);
  }
  g.fillStyle=linear(g,0,H*.69,0,bank,[0,'#435152',.62,'#505251',1,'#4e4945']);g.fillRect(-pad,H*.707,W+pad*2,bank-H*.707+1);
  for(let i=0;i<22;i++){const tx=(i/21*(W+pad*2)-pad)+r()*24;if(tx>W*.74&&tx<W*.93)continue;pine(g,tx,H*(.718+.012*r()),(30+r()*46)*S,Math.floor(r()*8000),true)}
  for(const v of [.084,.332,.69,.85])glow(g,'gold',v*W,H*.69,W*.065,H*.046,.12);
  pagoda(g,W*.847,H*.722,Math.min(H*.00162,W*.00098)*.98,r);
  x=-pad-45;
  while(x<W+pad){
    const w=(59+r()*57)*S,c=x+w*.5,base=bank-(8+r()*13)*S;
    if(Math.abs(c-cen)>gap*.59+w*.16 && Math.abs(c-W*.847)>w*.46){
      house(g,c,base,w,1+(r()>.34?1:0),r);
      if(r()>.68)pine(g,c+w*.52,base+1,(32+r()*31)*S,Math.floor(r()*9999));
    }
    x+=w*(.87+r()*.15);
  }
  const wallY=bank-9*S;
  for(const ab of [[-pad,cen-gap*.47],[cen+gap*.47,W+pad]]){
    const a=ab[0],b=ab[1];g.fillStyle='#3a4245';g.fillRect(a,wallY,b-a,bank-wallY+1);line(g,[a,wallY-1,b,wallY-1],'#887b68',1.9);
    for(let row=0;row<2;row++){
      let xx=a-row*7;
      while(xx<b){const ww=(9+r()*14)*S,yy=wallY+row*4.3*S;const left=Math.max(a,xx),right=Math.min(b,xx+ww);
        if(right>left)poly(g,[left,yy+1,right-.8,yy+.6,right-1,yy+3.7*S,left+.4,yy+4*S],r()>.5?'#5c5b57':'#4d5252');xx+=ww}
    }
  }
  const rear=H*.706,channel=linear(g,0,rear,0,bank,[0,'#6b7473',.45,'#52666d',1,'#41575f']);
  poly(g,[cen-gap*.10,rear,cen+gap*.11,rear,cen+gap*.49,bank+1,cen-gap*.49,bank+1],channel);
  for(let j=0;j<43;j++){
    const d=r(),xx=cen+(r()-.5)*gap*(.19+d*.72),yy=mix(rear,bank,d),ww=1+d*r()*8;
    line(g,[xx-ww,yy,xx+ww,yy],j%3?'#96a29c70':'#c4a78b88',.65);
  }
  line(g,[cen-gap*.10,rear,cen-gap*.49,bank],'#8e8372',1.6);
  line(g,[cen+gap*.11,rear,cen+gap*.49,bank],'#79776c',1.4);
  bridge(g,cen,bank-1,gap*1.14);
  for(const v of [[.166,.613],[.859,.533]]){
    const xx=v[0]*W,yy=v[1]*H;
    line(g,[xx+3,bank-8,xx,yy-6],'#373c3e',2.25);line(g,[xx-2.4,yy-3,xx+2.8,yy-3],'#9b8872',1.4);
  }
  const dockY=bank-3*S;
  for(const v of [.12,.35,.716,.944]){
    const xx=v*W,len=(38+r()*31)*S;
    g.fillStyle='#493f3b';g.fillRect(xx-len/2,dockY,len,3*S);
    for(let i=0;i<5;i++){const sx=xx-len*.43+len*.21*i;line(g,[sx,dockY+1,sx,dockY+7*S],'#3b3939',2.8*S)}
    line(g,[xx-len/2,dockY,xx+len/2,dockY],'#aa8a69',1.2);
    paperLamp(g,xx-len/2+4,dockY-9*S,.47*S,1);
  }
  pine(g,-.002*W,bank+4,clamp(H*.19,108,173),1151);pine(g,1.015*W,bank+6,clamp(H*.158,87,145),3434);
}


const paints=[
  {name:'Ember',id:'ember',ink:'#714638',deep:'#985034',edge:'#b65b37',back:'#ce6c38',mid:'#f99548',lit:'#ffd087',milk:'#ffe0a6',chest:'#ffdc98',stripe:'#b65b39',line:'#8d5136',rose:'#dd8a70',nose:'#a9534c',eye:'#343c3d',iris:'#d7ac63',cord:'#985342',flash:'#ffe6ac',aura:'ember',binding:'#795145'},
  {name:'Pearl',id:'pearl',ink:'#495662',deep:'#60717c',edge:'#778892',back:'#93a2aa',mid:'#c4cdca',lit:'#e2e2cd',milk:'#f2e7cc',chest:'#ece6ce',stripe:'#798997',line:'#697983',rose:'#c59892',nose:'#a87370',eye:'#303d49',iris:'#a4c4c5',cord:'#92716a',flash:'#f9edcf',aura:'pearl',binding:'#596573'}
];
function shape(g,d,fill,stroke,width=.024){const p=typeof d==='string'?new Path2D(d):d;if(fill){g.fillStyle=fill;g.fill(p)}if(stroke){g.strokeStyle=stroke;g.lineWidth=width;g.stroke(p)}}
function sprite(box,res,paint){
  const c=surface((box[2]-box[0])*res,(box[3]-box[1])*res),g=c.getContext('2d');g.setTransform(res,0,0,res,-box[0]*res,-box[1]*res);g.lineCap='round';g.lineJoin='round';paint(g);
  return {c,box};
}
function inkPrint(g,s){const b=s.box;g.drawImage(s.c,b[0],b[1],b[2]-b[0],b[3]-b[1])}
function makeCell(p,index){
  return sprite([-1.11,-1.13,1.11,1.13],94,g=>{
    const shell=new Path2D('M-.99-.47 C-.88-.83-.50-1.02-.06-1 C.43-1.03.84-.85.99-.48 Q1.071 0 .985 .50 C.82 .87 .38 1.015 -.05 1 C-.51 1.02-.87.81-.99.50 Q-1.065 0-.99-.47Z');
    shape(g,shell,linear(g,0,-1,0,1,[0,p.back,.16,p.mid,.46,p.lit,.65,p.lit,.86,p.mid,1,p.deep]),p.ink,.055);
    g.save();g.clip(shell);
    g.fillStyle=radial(g,-.08,.20,1.38,[0,p.milk+'99',.52,p.lit+'15',1,p.deep+'72']);g.fillRect(-1.1,-1.1,2.2,2.2);
    const rr=rng(832+index*29);
    for(let i=0;i<125;i++){const x=rr()*2-1,y=rr()*2-1;line(g,[x,y,x+.014+rr()*.036,y+(rr()-.35)*.044],i%3?'#fff0c330':'#64483e29',.006+rr()*.007)}
    for(const x of [-.44,-.05,.37]){
      const bend=x*.27-.085;
      curve(g,[x,-1.03,x+bend,-.60,x+bend,.60,x,1.03],p.line+'8a',.023);
      curve(g,[x+.025,-.99,x+bend+.025,-.52,x+bend+.024,.55,x+.025,1.02],p.flash+'98',.014);
    }
    shape(g,'M-.47-1 Q-.29-.81-.18-.39 Q-.12-.63-.18-.93 L-.10-1.08Z',p.stripe+'c7');
    shape(g,'M.11-1.04 Q.34-.83.45-.59 Q.47-.82.38-1.01Z',p.stripe+'a9');
    curve(g,[-.64,.64,-.27,.81,.17,.83,.58,.62],p.flash+'9e',.027);
    for(let j=0;j<3;j++){const x=-.26+.22*j,y=.50+.06*cos(j-1);curve(g,[x-.10,y,x-.045,y-.12,x+.045,y-.12,x+.10,y],p.line+'75',.018);curve(g,[x-.059,y,x-.03,y-.065,x+.03,y-.065,x+.062,y],p.flash+'c4',.013)}
    if(index===1){shape(g,'M-.045.06 0-.06 .047.06 0 .16Z',p.flash+'c0')}
    for(const sign of [-1,1]){
      const x=sign*.82;
      curve(g,[x*.91,-.87,x+sign*.15,-.49,x+sign*.15,.50,x*.91,.87],p.binding,.061);
      curve(g,[x*.91-sign*.046,-.86,x+sign*.10,-.49,x+sign*.10,.50,x*.91-sign*.046,.86],p.flash,.024);
    }
    g.restore();
    curve(g,[-.62,-.83,-.25,-1.038,.32,-1.0,.61,-.83],p.flash+'dd',.034);
  });
}
function catEye(g,x,y,k,p){
  g.save();g.translate(x,y);g.scale(k,k);
  shape(g,'M-.232.012 Q-.07-.189.146-.121 Q.2-.087.22-.029 Q.127.14-.066.129 Q-.158.127-.232.012Z',p.eye,p.ink,.024);
  ellipse(g,.008,.005,.112,.119,p.iris,-.14);ellipse(g,.025,-.004,.057,.111,p.eye);
  ellipse(g,-.04,-.051,.045,.037,'#fff3d4');ellipse(g,.082,.069,.018,.014,'#f7dbab');
  curve(g,[-.232,.012,-.106,-.187,.091,-.166,.206,-.081],p.eye,.04);
  curve(g,[-.166,.14,-.104,.177,.043,.172,.121,.143],p.flash,.024);
  g.restore();
}
function makeFace(p){
  return sprite([-1.23,-1.09,1.24,1.02],114,g=>{
    const base=new Path2D('M-1.00-.23 C-1.02-.59-.70-.89-.29-.92 C.15-1.02.72-.89.91-.59 Q1.04-.39 1.00-.14 L1.105.005 1.018.01 1.135.167 1.026.16 Q1.034.444.785.60 Q.48.915.045.91 Q-.49.95-.816.58 L-.986.61-.928.465-1.15.404-1.02.30-1.167.18-1.014.157 Q-1.092-.021-1.00-.23Z');
    shape(g,base,linear(g,-.3,-1,.4,.95,[0,p.back,.24,p.mid,.53,p.lit,.80,p.chest,1,p.edge]),p.ink,.045);
    g.save();g.clip(base);
    g.fillStyle=radial(g,.13,.04,1.05,[0,p.milk+'79',.68,p.lit+'08',1,p.deep+'60']);g.fillRect(-1.2,-1,2.4,2.1);
    for(const v of [-.65,-.26,.19,.62])curve(g,[v,-1,v-.12,-.46,v-.12,.5,v+.12,.94],p.line+'47',.018);
    for(const v of [-.52,.39])curve(g,[-1.12,v,-.3,v+.21,.54,v+.14,1.15,v-.05],p.flash+'5e',.013);
    shape(g,'M-.56-.94 Q-.37-.66-.28-.49 Q-.17-.62-.22-.89 L-.36-.99Z',p.stripe);
    shape(g,'M-.12-1.03 Q.06-.75.13-.50 Q.26-.66.22-.98Z',p.stripe);
    shape(g,'M.36-.99 Q.52-.79.54-.62 Q.63-.71.64-.90Z',p.stripe);
    shape(g,'M-1.12-.18 Q-.75-.13-.58.04 Q-.76.008-1.05.031Z',p.stripe);
    shape(g,'M-1.04.08 Q-.71.15-.64.30 Q-.87.22-1.02.28Z',p.stripe);
    shape(g,'M1.10-.19 Q.90-.15.796-.034 Q.96-.087 1.10-.022Z',p.stripe);
    shape(g,'M1.13.07 Q.96.067.88.177 Q1.01.145 1.1.20Z',p.stripe);
    shape(g,'M-1.04.46 Q-.79.41-.68.39 Q-.53.53-.35.56 Q.03.68.31.42 Q.62.55.93.35 Q.77.87.17.94 Q-.59 1.09-1.04.46Z',p.chest);
    const rr=rng(49);for(let i=0;i<225;i++){const x=rr()*2.2-1.1,y=rr()*2-1;line(g,[x,y,x+.008+rr()*.024,y+rr()*.019],'#fff5db48',.007)}
    g.restore();
    curve(g,[-.51,-.27,-.41,-.37,-.27,-.40,-.14,-.32],p.line,.048);
    curve(g,[.55,-.36,.65,-.43,.75,-.40,.80,-.35],p.line,.041);
    catEye(g,-.267,-.116,1.06,p);catEye(g,.655,-.183,.77,p);
    ellipse(g,-.52,.21,.19,.085,p.rose+'72',.12);ellipse(g,.895,.135,.097,.057,p.rose+'76',-.19);
    ellipse(g,.055,.291,.292,.19,p.milk,-.12);ellipse(g,.449,.25,.226,.167,p.milk,-.11);
    shape(g,'M.143.152 Q.248.097.377.134 Q.41.16.363.223 L.286.286 Q.255.311.215.268L.135.199 Q.113.165.143.152Z',p.nose,p.ink,.022);
    line(g,[.182,.158,.252,.147],p.flash,.029);
    curve(g,[.279,.274,.30,.357,.258,.420,.18,.424,.087,.430,.052,.382,.022,.372],p.ink,.031);
    curve(g,[.275,.322,.347,.412,.435,.401,.488,.331],p.ink,.027);
    for(const a of [[-.11,.242],[-.18,.285],[-.078,.319],[.535,.237],[.588,.255]])ellipse(g,a[0],a[1],.017,.013,p.line);
    shape(g,'M.125-.454 .16-.523 .196-.458 .16-.395Z',p.flash);
  });
}
function ear(g,x,y,angle,k,p){
  g.save();g.translate(x,y);g.rotate(angle);g.scale(k,k);
  shape(g,'M-.37.20 Q-.43-.23-.46-.824 Q-.472-.98-.36-.90 Q.01-.69.39-.09 L.42.13Z',linear(g,-.45,-.83,.37,.16,[0,p.flash,.23,p.mid,.78,p.back,1,p.deep]),p.ink,.047);
  shape(g,'M-.296-.674 Q-.113-.547.19-.128 Q-.03-.173-.25-.056 Q-.283-.364-.296-.674Z',linear(g,0,-.7,0,0,[0,p.rose,1,p.chest]),p.line+'a0',.017);
  curve(g,[-.398,-.824,-.385,-.48,-.378,-.24,-.341,-.03],p.flash,.034);
  for(let i=0;i<3;i++)line(g,[-.21+i*.07,-.09,-.19+i*.049,-.23-i*.06],p.flash+'c7',.023);g.restore();
}
function forePaw(g,x,y,size,flip,tilt,p,near){
  g.save();g.translate(x,y);g.scale(flip*size,size);g.rotate(tilt);
  shape(g,'M-.33-.12 Q-.018-.22.23-.08 Q.22.17.09.43 Q.24.48.268.62 Q.301.806.04.864 Q-.174.93-.34.779 Q-.438.67-.36.51 L-.24.19Z',linear(g,0,-.14,0,.88,[0,near?p.mid:p.back,.55,near?p.lit:p.mid,.8,p.chest,1,p.lit]),p.ink,.043);
  curve(g,[-.325,.45,-.21,.51,-.073,.53,.078,.46],p.stripe,.056);
  for(let i=0;i<2;i++)curve(g,[-.182+i*.15,.83,-.15+i*.14,.78,-.13+i*.13,.73,-.135+i*.13,.698],p.line,.026);
  g.restore();
}
function drawHead(g,cat,t){
  const n=cat.nodes[0],s=cat.headSize,p=cat.pal,dir=cat.facing;
  const tilt=clamp(Math.atan2(n.ty,Math.max(.36,Math.abs(n.tx)))*.48,-.53,.51);
  const a=sin(t*1.65+cat.id*3),flick=Math.pow(.5+.5*sin(t*1.37+cat.id),13)*sin(t*10.5+cat.id);
  g.save();g.translate(n.x,n.y);g.scale(dir*s,s);g.rotate(tilt);
  ear(g,.64,-.60,.48+.048*a+flick*.072,.88,p);ear(g,-.57,-.58,-.08-.042*a+flick*.105,1,p);
  inkPrint(g,cat.art.face);
  for(let i=0;i<3;i++){
    const y=.18+i*.087,ext=1.79-.09*i,bend=(i-1)*.23;
    curve(g,[-.48,y,-.91,y-.10,-1.31,y+bend-.20+a*.034,-ext,y+bend-.073+sin(t*2.6+i*.5)*.075],p.ink+'a8',.034);
    curve(g,[-.48,y-.012,-.91,y-.12,-1.31,y+bend-.214+a*.034,-ext,y+bend-.086+sin(t*2.6+i*.5)*.075],p.flash,.021);
    curve(g,[.68,y-.09,.99,y-.18,1.23,y+bend-.19,1.62-.09*i,y+bend-.17+sin(t*2.4+i*.57)*.067],p.flash,.022);
  }
  g.restore();
}
function drawCat(g,cat,t){
  const ns=cat.nodes,p=cat.pal,N=cat.count,st=cat.step,tip=ns.length-1;
  g.save();g.lineJoin='round';g.lineCap='round';
  for(let i=0;i<=N;i+=2){const n=ns[i];glow(g,p.aura,n.x,n.y,st*2.15,st*1.67,i===0 ? .35:.21)}
  for(let i=tip;i>N;i--){
    const a=ns[i-1],b=ns[i],z=(i-N)/(tip-N),w=st*(.47-.36*z);
    line(g,[a.x,a.y,b.x,b.y],p.ink,w+1.7);
    line(g,[a.x,a.y,b.x,b.y],i%3===0?p.back:p.mid,w);
    line(g,[a.x,a.y-w*.20,b.x,b.y-w*.20],p.lit,w*.23);
  }
  const end=ns[tip];
  g.save();g.translate(end.x,end.y);g.rotate(Math.atan2(end.ty,end.tx));g.scale(st,st);
  shape(g,'M.17-.068 Q-.042-.14-.167-.07 L-.34.048 Q-.16.0004-.10.09 Q.006.15.19.07Z',p.chest,p.ink,.022);g.restore();
  for(let i=N;i>0;i--){const n=ns[i],a=ns[i-1];line(g,[n.x,n.y,a.x,a.y],p.binding,st*(.43+.13*sin(Math.PI*i/(N+1))));line(g,[n.x,n.y,a.x,a.y],p.lit,st*.26)}
  for(const i of [N-2,2]){
    const n=ns[i],legScale=st*(i===2 ? .85:.65);
    forePaw(g,n.x+cat.facing*st*.16,n.y+cat.radii[i]*.64,legScale,cat.facing,.47+.085*sin(t*1.8+i),p,false);
  }
  for(let i=N;i>=1;i--){
    const n=ns[i],r=cat.radii[i],phi=Math.atan2(n.ty,n.tx),dir=n.tx>=0?1:-1;
    g.save();g.translate(n.x,n.y);g.rotate(dir===1?phi:Math.atan2(-n.ty,-n.tx));g.scale(dir*st*(i===N ? .545:.595),r);
    inkPrint(g,cat.art.cells[i%2]);g.restore();
  }
  for(const i of [N-1,1]){
    const n=ns[i];forePaw(g,n.x-cat.facing*st*.16,n.y+cat.radii[i]*.69,st*(i===1 ? .83:.62),cat.facing,-.33+.09*sin(t*1.82+i),p,true);
  }
  const h=ns[0],neck=ns[1],bx=mix(h.x,neck.x,.60),by=mix(h.y,neck.y,.60)+st*.38;
  curve(g,[bx-st*.14,by-st*.3,bx-st*.06,by-st*.01,bx+st*.10,by+st*.09,bx+st*.08,by+st*.21],p.cord,st*.07);
  const bellX=bx+st*(.08+.042*sin(t*2.6)),bellY=by+st*.30;
  line(g,[bx+st*.08,by+st*.16,bellX,bellY],p.cord,1.3);
  ellipse(g,bellX,bellY,st*.102,st*.113,'#c99860');ellipse(g,bellX-st*.022,bellY-st*.022,st*.052,st*.063,'#ffdf93');
  curve(g,[bellX-st*.075,bellY+st*.032,bellX-st*.03,bellY+st*.057,bellX+st*.045,bellY+st*.057,bellX+st*.08,bellY+st*.021],'#856648',1.15);
  drawHead(g,cat,t);g.restore();
}


const knots=[[.044,.417],[.072,.355],[.126,.308],[.194,.312],[.262,.353],[.321,.366],[.375,.343],[.443,.287],[.512,.266],[.575,.281],[.646,.318],[.716,.312],[.788,.265],[.861,.250],[.922,.279],[.955,.343],[.947,.402],[.903,.442],[.845,.459],[.778,.447],[.710,.462],[.638,.505],[.562,.548],[.490,.555],[.423,.526],[.357,.510],[.29,.525],[.219,.554],[.149,.545],[.086,.501]];
const catSize=()=>Math.min(W*(W<940 ? .034:.0295),H*.059,49);
function catmull(a,b,c,d,t){return .5*((2*b)+(-a+c)*t+(2*a-5*b+4*c-d)*t*t+(-a+3*b-3*c+d)*t*t*t)}
function makeRoute(){
  route=[];routeLen=0;const n=knots.length,r=catSize()*1.66;
  for(let i=0;i<n;i++){
    const a=knots[wrap(i-1,n)],b=knots[i],c=knots[(i+1)%n],d=knots[(i+2)%n];
    for(let j=0;j<30;j++){const u=j/30,x=clamp(W*catmull(a[0],b[0],c[0],d[0],u),r*.94,W-r*.94),y=Math.min(H*catmull(a[1],b[1],c[1],d[1],u),altitude(x,r));
      if(route.length){const last=route[route.length-1];routeLen+=Math.hypot(x-last.x,y-last.y)}route.push({x,y,d:routeLen})}
  }
  const first=route[0],last=route[route.length-1];routeLen+=Math.hypot(first.x-last.x,first.y-last.y);route.push({x:first.x,y:first.y,d:routeLen});
}
function along(d){
  d=wrap(d,routeLen);let lo=0,hi=route.length-1;
  while(hi-lo>1){const m=(lo+hi)>>1;if(route[m].d<=d)lo=m;else hi=m}
  const a=route[lo],b=route[hi],f=(d-a.d)/Math.max(.0001,b.d-a.d);return {x:mix(a.x,b.x,f),y:mix(a.y,b.y,f)};
}
function nearRoute(x,y,tx=0,ty=0){
  let best=Infinity,d=0;
  for(let i=0;i<route.length-1;i+=2){const a=route[i],b=route[i+1],delta=Math.hypot(b.x-a.x,b.y-a.y)||1,skew=1-((b.x-a.x)*tx+(b.y-a.y)*ty)/delta;
    const score=(a.x-x)**2+(a.y-y)**2+skew*skew*catSize()**2*2.4;if(score<best){best=score;d=a.d}}
  return d;
}
function bodyFromHistory(cat,head,t){
  const trail=cat.trail,ns=[{x:head.x,y:head.y}],N=cat.count;let j=trail.length-1;
  for(let i=1;i<cat.offsets.length;i++){
    const s=head.s-cat.offsets[i];while(j>0&&trail[j].s>s)j--;
    const a=trail[j],b=j+1<trail.length?trail[j+1]:head,f=clamp((s-a.s)/Math.max(.001,b.s-a.s),0,1);
    let x=mix(a.x,b.x,f),y=mix(a.y,b.y,f);
    if(i>N){const u=(i-N)/(cat.offsets.length-1-N);y+=u*cat.step*(-.33+(.10+.78*u)*sin(t*2.14+cat.id*2.8-u*4.05));x+=u*u*cat.step*.19*sin(t*1.86-u*3)}
    y=Math.min(y,altitude(x,cat.hit[i]));ns.push({x,y});
  }
  for(let i=0;i<ns.length;i++){
    const a=ns[Math.max(0,i-1)],b=ns[Math.min(ns.length-1,i+1)],dx=a.x-b.x,dy=a.y-b.y,len=Math.hypot(dx,dy)||1;
    ns[i].tx=dx/len;ns[i].ty=dy/len;
  }
  return ns;
}
function newCat(id,progress){
  const p=paints[id],step=catSize()*(id ? .908:1),N=W<910?10:11,headSize=step*.88;
  const cat={id,pal:p,art:p.art,count:N,step,headSize,progress,trail:[],offsets:[0],radii:[headSize],hit:[headSize*1.89],facing:id?-1:1};
  for(let i=1;i<=N;i++){
    cat.offsets.push(step*(i-.10));const r=step*(.485+.157*sin((i+.12)/(N+1)*Math.PI)+.070*(1-i/N)-(i===N ? .045:0));cat.radii.push(r);
    cat.hit.push(i<=2?step*1.25:i===N-1||i===N-2?step*1.01:Math.max(r,step*.62)+1);
  }
  for(let i=1;i<=7;i++){cat.offsets.push(cat.offsets[cat.offsets.length-1]+step*(.445-.012*i));cat.hit.push(step*(.29-.019*i)+2);cat.radii.push(step*.18)}
  cat.length=cat.offsets[cat.offsets.length-1];
  for(let s=-Math.ceil((cat.length+step*2)/3)*3;s<=0;s+=3){const v=along(progress+s);cat.trail.push({x:v.x,y:v.y,s})}
  cat.head=cat.trail[cat.trail.length-1];cat.nodes=bodyFromHistory(cat,cat.head,elapsed);cat.heading=Math.atan2(cat.nodes[0].ty,cat.nodes[0].tx);return cat;
}
function pointSegment(x,y,a,b){const vx=b.x-a.x,vy=b.y-a.y,k=clamp(((x-a.x)*vx+(y-a.y)*vy)/(vx*vx+vy*vy||1),0,1);return (x-a.x-vx*k)**2+(y-a.y-vy*k)**2}
function cross(ax,ay,bx,by){return ax*by-ay*bx}
function separated(ns,cat,other){
  const os=other.nodes;
  for(let i=1;i<ns.length;i++){
    const a=ns[i-1],b=ns[i],ra=Math.max(cat.hit[i-1],cat.hit[i]),lx=Math.min(a.x,b.x),rx=Math.max(a.x,b.x),uy=Math.min(a.y,b.y),dy=Math.max(a.y,b.y);
    for(let j=1;j<os.length;j++){
      const c=os[j-1],d=os[j],r=ra+Math.max(other.hit[j-1],other.hit[j])+2;
      if(lx>Math.max(c.x,d.x)+r||rx<Math.min(c.x,d.x)-r||uy>Math.max(c.y,d.y)+r||dy<Math.min(c.y,d.y)-r)continue;
      const ax=b.x-a.x,ay=b.y-a.y,bx=d.x-c.x,by=d.y-c.y,ox=c.x-a.x,oy=c.y-a.y,k=cross(ax,ay,bx,by);
      if(Math.abs(k)>.00001){const u=cross(ox,oy,bx,by)/k,v=cross(ox,oy,ax,ay)/k;if(u>=0&&u<=1&&v>=0&&v<=1)return false}
      if(Math.min(pointSegment(a.x,a.y,c,d),pointSegment(b.x,b.y,c,d),pointSegment(c.x,c.y,a,b),pointSegment(d.x,d.y,a,b))<r*r)return false;
    }
  }
  return true;
}
function demoGuide(cat){
  if(!demo)return null;
  const start=cat.id?11.2:2.1,dur=5.95,f=(demoClock-start)/dur;if(f<0||f>1)return null;
  const u=sin(Math.PI*f)**2,base=along(cat.progress+cat.step*(1.0+.58*u)),x=base.x+cat.step*.64*sin(f*TAU)*u;
  return {x,y:Math.min(base.y-H*.073*u,altitude(x,cat.hit[0])),alpha:Math.min(1,u*2.7),cat:cat.id};
}
function steerCat(cat,other,dt,t){
  const normalSpeed=routeLen/(demo?20:still?105:70);
  const hand=guide&&guide.cat===cat.id?guide:null;
  if(!hand)cat.progress=wrap(cat.progress+normalSpeed*dt,routeLen);
  const auto=demoGuide(cat),dest=hand||auto||along(cat.progress),h=cat.head,margin=cat.hit[0],
        dx=clamp(dest.x,margin,Math.max(margin,W-margin))-h.x;
  const goalY=clamp(dest.y,margin+5,altitude(h.x+dx,margin));
  const dy=goalY-h.y,dist=Math.hypot(dx,dy);
  let speed=hand?Math.min(W*.265+40,dist*2.7):Math.min(normalSpeed*1.48+(auto?35:24)+Math.min(80,dist*.74),dist/Math.max(.001,dt));
  if(!hand&&!auto&&dist>cat.step*3.4)speed=Math.min(W*.24+38,Math.max(speed,dist*1.65));
  const travel=Math.min(speed*dt,dist);
  if(travel<.018){
    const ns=bodyFromHistory(cat,h,t);if(separated(ns,cat,other))cat.nodes=ns;return;
  }
  let vx=dx/Math.max(.001,dist),vy=dy/Math.max(.001,dist);
  const px=h.x+vx*margin*.81,py=h.y+vy*margin*.81;
  let best=Infinity,barrier=null;
  for(let j=0;j<other.nodes.length;j++){
    const n=other.nodes[j],xx=px-n.x,yy=py-n.y,len=Math.hypot(xx,yy),edge=len-margin-other.hit[j];
    if(edge<best){best=edge;barrier={xx,yy,len}}
  }
  if(barrier&&best<margin*.48){const w=clamp(1-best/(margin*.48),0,2.8);vx+=barrier.xx/(barrier.len||1)*w*1.28;vy+=barrier.yy/(barrier.len||1)*w*1.28}
  const aim=Math.atan2(vy,vx),turn=wrap(aim-cat.heading+Math.PI,TAU)-Math.PI,heading=cat.heading+clamp(turn,-dt*(hand?3.65:5.2),dt*(hand?3.65:5.2));
  const choices=[0,.36,-.36,.78,-.78,1.18,-1.18,1.62,-1.62,2.14,-2.14],sign=cat.id?-1:1;
  for(const extra of choices){
    const ang=heading+extra*sign,x=clamp(h.x+cos(ang)*travel,margin,W-margin),y=clamp(h.y+sin(ang)*travel,margin+4,altitude(x,margin)),ds=Math.hypot(x-h.x,y-h.y);
    if(ds<.01)continue;
    const head={x,y,s:h.s+ds},nodes=bodyFromHistory(cat,head,t);
    if(!separated(nodes,cat,other))continue;
    cat.head=head;cat.nodes=nodes;cat.heading=Math.atan2(y-h.y,x-h.x);
    if(Math.abs(nodes[0].tx)>.13)cat.facing=nodes[0].tx>=0?1:-1;
    if(head.s-cat.trail[cat.trail.length-1].s>=2.15)cat.trail.push(head);
    while(cat.trail.length>3&&cat.trail[1].s<head.s-cat.length-cat.step)cat.trail.shift();
    return;
  }
}
function releaseCat(){
  if(!guide)return;
  const c=cats[guide.cat],n=c.nodes[0];c.progress=nearRoute(n.x,n.y,n.tx,n.ty);guide=null;updateGuide();
}
function updateGuide(){
  if(guide){guideTitle.textContent='Guiding '+cats[guide.cat].pal.name;guideText.textContent=touchId===null?'The cat will rejoin the parade shortly.':'Move your touch to lead the way.'}
  else if(demo){guideTitle.textContent='Festival preview';guideText.textContent='Touch the sky to take the lead.'}
  else{guideTitle.textContent='Drag the sky';guideText.textContent='The nearest cat will follow your touch.'}
}


function skyLampArt(kind){
  return sprite([-29,-34,29,32],2.4,g=>{
    const colors=kind?['#cc6544','#ed9261','#ffd49b','#a64b42']:['#b8623b','#f4ac63','#ffe4a2','#ab623d'];
    glow(g,kind?'ember':'gold',0,0,28,30,.55);
    shape(g,'M-7-10 Q-.4-13 6.5-10 L8.7-6.9 5.4 8.1 Q.7 10.3-4.6 8.5L-9-6.2Z',linear(g,0,-13,0,10,[0,colors[0],.55,colors[1],1,colors[2]]),'#86523f',.65);
    poly(g,[-9,-6.2,-5.7,-6.0,-2.8,8.9,-4.6,8.5],colors[3]+'a8');
    poly(g,[-5.7,-6,3.5,-6.4,2.45,8.6,-2.8,8.9],colors[2]+'48');
    poly(g,[-7,-10,6.5,-10,8.7,-6.9,3.5,-6.4,-5.7,-6,-9,-6.2],colors[0]+'9e');
    curve(g,[-5.7,-6,-3.1,-5.1,1.5,-5.7,3.5,-6.4],'#ffe0a78c',.55);
    line(g,[3.5,-6.4,2.45,8.6],colors[3]+'a6',.5);line(g,[-5.5,-6,-2.8,8.4],'#ffd893ca',.5);
    ellipse(g,.3,8.5,4.8,1.35,'#945a41');ellipse(g,.2,8.0,3.5,.8,'#ffde93');ellipse(g,.0,6.8,1.1,2.2,'#fff0b1');
  });
}
function makeFestival(){
  const rr=rng(150123);wisps=[];flecks=[];ripples=[];waterLights=[];
  const total=Math.max(17,Math.round(W/51));
  for(let i=0;i<total;i++){
    const z=rr(),x=rr(),y=rr();wisps.push({x,y,z,scale:.25+.77*z*z,speed:.010+.013*z,phase:rr()*TAU,kind:i%3===0?1:0});
  }
  for(let i=0;i<Math.min(125,Math.max(48,W*.062));i++)flecks.push({x:rr(),y:rr(),a:rr(),b:rr()*TAU,c:rr()});
  for(let i=0;i<Math.max(320,W*.48);i++)ripples.push({x:rr(),d:rr(),s:rr(),p:rr()*TAU,v:.27+rr()*.42});
  for(let i=0;i<32;i++){const x=rr();if(Math.abs(x-.525)>.058)waterLights.push({x,reach:.09+rr()*.48,s:rr(),p:rr()*TAU})}
  lanternSprites=[skyLampArt(0),skyLampArt(1)];
  const tile=surface(158,158),g=tile.getContext('2d'),im=g.createImageData(158,158);
  for(let i=0;i<im.data.length;i+=4){const v=rr()>.48?244:10;im.data[i]=v;im.data[i+1]=v;im.data[i+2]=v;im.data[i+3]=Math.floor(3+rr()*15)}
  g.putImageData(im,0,0);grain=ctx.createPattern(tile,'repeat');
}
function risingLanterns(g,t,near){
  for(const a of wisps){
    if((a.z>.86)!==near)continue;
    const f=wrap(a.y+t*a.speed*.31,1),x=wrap(a.x+.011*sin(t*.17+a.phase)+.038*f,1.12)*W-.033*W,
      y=H*(.69-.80*f),op=clamp(f*14,0,1)*clamp((1-f)*13,0,1);
    g.save();g.globalAlpha*=op*(.48+.50*a.z);g.translate(x,y);g.rotate(.14*sin(t*.48+a.phase)-.055);g.scale(a.scale,a.scale);inkPrint(g,lanternSprites[a.kind]);g.restore();
  }
}
function sparks(g,t){
  for(const a of flecks){
    const f=wrap(a.y+t*(.0055+.006*a.a),1),y=H*(.737-.68*f),x=wrap(a.x+.032*f+.007*sin(t*.31+a.b+f*6),1.05)*W-.02*W;
    const pulse=.4+.6*(.5+.5*sin(t*(.8+a.c)+a.b))**2,op=(.26+a.a*.61)*pulse*clamp(f*17,0,1)*clamp((1-f)*13,0,1);
    g.globalAlpha=op;
    if(a.c>.79)line(g,[x-1.15,y+2.6,x,y],'#e8ac78',.83);
    ellipse(g,x,y,.51+a.a*.88,.55+a.a*1.05,a.c>.17?'#ffd493':'#dbe0ca',-.31);
    if(a.a>.77)glow(g,'gold',x,y,5.4,5.4,.33);
  }
  g.globalAlpha=1;
}
function silkTrail(g,c,t){
  const tail=c.nodes[c.nodes.length-1],p=c.pal,st=c.step;
  const dx=-tail.tx,dy=-tail.ty,sideX=-dy,sideY=dx,len=st*1.92;
  g.save();
  for(let k=0;k<2;k++){
    const wing=k?1:-1,px=tail.x+sideX*4*wing,py=tail.y+sideY*4*wing;
    const ex=px+dx*len+sideX*st*.29*sin(t*1.2+k),ey=py+dy*len+sideY*st*.29*sin(t*1.2+k);
    curve(g,[px+dx*5,py+dy*5,px+dx*st*.5+sideX*wing*6,py+dy*st*.5+sideY*wing*6,ex-dx*st*.65-sideX*wing*9,ey-dy*st*.65-sideY*wing*9,ex,ey],p.flash+'49',.8);
  }
  for(let i=0;i<9;i++){
    const f=wrap(i/9+t*.17,1),w=sin(f*9+i*1.2)*st*(.09+.24*f),x=tail.x+dx*f*len*1.3+sideX*w,y=tail.y+dy*f*len*1.3+sideY*w;
    g.globalAlpha=.57*sin(f*Math.PI);ellipse(g,x,y,.85+sin(i)*.23,.9,p.flash);
  }
  g.restore();
}
function boatShape(g,small){
  const hull=small?'#323d41':'#26343b';
  line(g,[-37,-8,-37,-28,-24,-30],'#3d4140',1.8);line(g,[-38,-25,-28,-29],'#927b5d',.8);
  paperLamp(g,-25,-24,.55,small?0:1);
  shape(g,'M-14-6 Q-14-25-3-26 Q10-28 16-8 L16-5Z','#92745a','#534d46',1.1);
  shape(g,'M-6-25 Q3-28 8-23 Q13-18 16-8 L11-7 Q8-24-1-24Z','#b39169');
  for(let i=0;i<6;i++)curve(g,[-12+i*3.3,-9,-12+i*3.25,-16,-10+i*2.84,-21,-6+i*2.67,-24],'#665945',.82);
  g.fillStyle='#43413b';g.fillRect(-14,-7,30,2.5);
  ellipse(g,25,-18,2.7,3.4,'#343b3e');poly(g,[20,-19,25,-23.3,30,-20.3,30.4,-19.3],'#827b68');
  shape(g,'M23-15 Q26-17 28-14L30-8 26-6 20-8Z','#435354','#303d40',.7);
  line(g,[26,-14,31,-11.4,36,-16.5],'#6e6c5c',1.35);line(g,[39,-23,22,3,13,13],'#797662',1.35);
  shape(g,'M-55-12 Q-43-4-17-5 Q24-3 50-11 Q42-.5 31 1 Q-4 6-40 0 Q-50-4-55-12Z',hull,'#233239',1.3);
  curve(g,[-54,-11,-33,-2,20,-1,49,-10],'#a7916c',1.5);curve(g,[-42,-2,-22,2,13,3,32,-.7],'#65706b',.85);
}
function boats(g,t,by){
  const h=H-by;
  for(let i=0;i<2;i++){
    const x=W*(i ? .77:.186)+W*.007*sin(t*.12+i*3)-cam.x*.46,y=by+h*(i ? .223:.55)+sin(t*.73+i)*.73,k=clamp(W/1510,.57,1.17)*(i ? .57:1.03)*cam.z;
    for(let j=0;j<4;j++){
      const w=k*(20+9*j);curve(g,[x-w,y+2+j*2.6*k,x-w*.44,y+4.6+j*2.6*k,x+w*.35,y+3.2+j*2.6*k,x+w,y+1.8+j*2.6*k],j%2?'#8a9c994e':'#b5ad8b64',.78);
    }
    g.save();g.translate(x,y+2*k);g.scale(k,-k*.48);g.globalAlpha=.26;boatShape(g,i);g.restore();
    g.save();g.translate(x,y);g.rotate(sin(t*.64+i)*.012);g.scale(k,k);boatShape(g,i);g.restore();
  }
}
function water(g,t,by){
  const depth=H-by;if(depth<2)return;
  const rw=reflection.width,rh=reflection.height;
  refCtx.setTransform(1,0,0,-1,0,rh);refCtx.drawImage(canvas,0,0,canvas.width,clamp(Math.round(by*pixel),1,canvas.height),0,0,rw,rh);
  g.fillStyle=linear(g,0,by,0,H,[0,'#47585c',.28,'#354a55',.74,'#263c48',1,'#1b303e']);g.fillRect(0,by,W,depth+1);
  g.save();g.beginPath();g.rect(0,by,W,depth+1);g.clip();
  const band=Math.max(1.35,1.38/pixel);
  for(let y=0;y<depth;y+=band){
    const v=y/depth,endy=Math.min(y+band,depth),s1=rh*Math.pow(v,1.16),s2=rh*Math.pow(endy/depth,1.16),amp=.64+v*5.9;
    const dx=(sin(y*.70+t*1.36)+.73*sin(y*.207-t*.91)+.49*sin(y*1.73+t*.64))*amp;
    g.globalAlpha=.72-.23*v+.045*sin(y*1.7+t);
    g.drawImage(reflection,0,Math.min(rh-.12,s1),rw,Math.max(.12,Math.min(rh-s1,s2-s1)),dx-13,by+y,W+26,endy-y+.48);
  }
  g.globalAlpha=1;
  g.fillStyle=linear(g,0,by,0,H,[0,'rgba(27,43,52,.11)',.45,'rgba(31,56,67,.08)',1,'rgba(15,36,49,.16)']);g.fillRect(0,by,W,depth+1);
  for(const a of ripples){
    const v=a.d,xx=a.x*(W+60)-30+3.8*sin(t*a.v+a.p)+cam.x*(-.18-.2*v),yy=by+v*depth+sin(t*.4+a.p)*.6*v,ww=(2.2+a.s*16)*(v+.35);
    const alpha=(.17+.26*a.s)*(.48+.52*(.5+.5*sin(t*a.v+a.p)));
    g.globalAlpha=alpha;line(g,[xx-ww*.52,yy+.32,xx,yy,xx+ww*.48,yy+.18],a.s>.52?'#b4c0b4':'#152e40',a.s>.79?1.06:.79);
  }
  g.globalAlpha=1;
  for(const a of waterLights){
    const xx=(a.x*W-W/2-cam.x)*cam.z+W/2;
    for(let j=0;j<11;j++){
      const q=(j+.3)/11,yy=by+q*a.reach*depth,phase=a.p+j*2.58,ww=(3+a.s*8+q*4)*(.54+.56*(.5+.5*sin(t*1.3+phase))),dx=sin(phase+t*.82)*q*9;
      g.globalAlpha=(1-q)*(.2+.28*a.s)*(.60+.40*sin(t+phase)**2);
      line(g,[xx+dx-ww,yy,xx+dx,yy-.12,xx+dx+ww*.75,yy+.18],j%3===0?'#ffd48c':'#d6a773',.73+.30*a.s);
    }
  }
  const mx=(W*.782-W/2-cam.x*.53)*cam.z+W/2;
  for(let j=0;j<49;j++){
    const f=j/49,phase=j*7.38,xx=mx+sin(phase+.3*sin(t*.51))*(4+f*W*.034),yy=by+depth*(.12+f*.88),ww=(1.5+f*8)*(1+.4*sin(t+phase));
    g.globalAlpha=(.08+.19*f)*(.64+.36*sin(t+phase));line(g,[xx-ww,yy,xx+ww,yy],'#f3d8a5',.85);
  }
  g.globalAlpha=1;boats(g,t,by);g.restore();
}
function reeds(g,t){
  g.save();
  const s=clamp(W/1550,.57,1.12);
  for(let side=0;side<2;side++){
    g.save();g.translate(side?W:0,H+1);g.scale(side?-s:s,s);const base=side?51:78;
    shape(g,'M-10 3 -10-13 Q9-22 22-16 Q39-18 49-10 Q68-11 86-2 L95 3Z',side?'#172c37':'#192e36');
    for(let i=0;i<(side?11:17);i++){
      const a=hash(i+side*321),b=hash(i+77),px=a*base-7,lean=(b-.4)*29+2.4*sin(t*.51+i),h=10+hash(i+97)*36;
      g.beginPath();g.moveTo(px,1);g.quadraticCurveTo(px+lean*.15,-h*.48,px+lean,-h);g.quadraticCurveTo(px+lean*.28,-h*.43,px+2.5,1);g.closePath();g.fillStyle=i%3?'#1d333b':'#32474a';g.fill();
    }g.restore();
  }
  g.restore();
}
function targetRing(g,a,t,alpha){
  if(!a||alpha<.01)return;
  const c=cats[a.cat],p=c.pal,col=c.id?'#e6e4d1':'#ffd099',x=a.x,y=a.y,rad=c.step*.40+5,head=c.nodes[0];
  g.save();g.globalAlpha=alpha;g.lineCap='round';
  const dx=x-head.x,dy=y-head.y,len=Math.hypot(dx,dy);
  if(len>rad*2.9){
    g.save();g.setLineDash([1.3,6]);const f=.32;
    curve(g,[head.x+dx*.16,head.y+dy*.16,head.x+dx*f,head.y+dy*.22-14,x-dx*.24,y-dy*.32-10,x-dx*rad/len,y-dy*rad/len],col+'88',1);g.restore();
  }
  for(let i=0;i<4;i++){const start=i*Math.PI*.5+.19;g.beginPath();g.arc(x,y,rad,start,start+.93);g.strokeStyle=col;g.lineWidth=1.15;g.stroke()}
  const b=wrap(t*.65,1);g.beginPath();g.arc(x,y,rad*(.73+b*.81),0,TAU);g.lineWidth=.9;g.strokeStyle=col;g.globalAlpha=alpha*(1-b)*.6;g.stroke();
  g.globalAlpha=alpha;poly(g,[x,y-3.3,x+2.5,y,x,y+3.3,x-2.5,y],p.flash);g.restore();
}


const soundButton=document.getElementById('sound'),soundText=document.getElementById('soundText');
let audio=null,master=null,voiceBus=null,timbre=null,wanted=true,manuallyQuiet=false,tickTimer=0,noteTime=0,beat=0;
const melody=[
  69,0,0,71,74,0,71,0, 66,0,0,64,62,0,0,0,
  66,69,0,71,0,69,66,0, 64,0,62,0,59,0,0,0,
  69,0,74,0,76,0,74,71, 69,0,66,0,64,0,0,0,
  66,0,69,71,0,66,64,0, 62,0,0,0,0,0,0,0
];
function reflectSound(){
  const playing=!!(audio&&audio.state==='running'&&wanted&&!document.hidden);
  soundButton.setAttribute('aria-pressed',String(playing));soundButton.setAttribute('aria-label',playing?'Mute the festival melody':'Play the festival melody');soundText.textContent=playing?'Sound on':'Sound off';
}
function makeAudio(){
  if(audio)return true;
  const A=window.AudioContext||window.webkitAudioContext;if(!A)return false;
  try{
    audio=new A();master=audio.createGain();master.gain.value=0;master.connect(audio.destination);
    voiceBus=audio.createBiquadFilter();voiceBus.type='lowpass';voiceBus.frequency.value=3150;voiceBus.Q.value=.35;voiceBus.connect(master);
    const room=audio.createConvolver(),wet=audio.createGain(),rate=audio.sampleRate,size=Math.floor(rate*1.65),impulse=audio.createBuffer(2,size,rate),rr=rng(94271);
    for(let ch=0;ch<2;ch++){const data=impulse.getChannelData(ch);for(let i=0;i<size;i++)data[i]=(rr()*2-1)*Math.pow(1-i/size,3.2)*(.28+.72*Math.min(1,i/(rate*.018)))}
    room.buffer=impulse;wet.gain.value=.24;voiceBus.connect(room);room.connect(wet);wet.connect(master);
    timbre=audio.createPeriodicWave(new Float32Array(8),new Float32Array([0,1,.33,.145,.066,.046,.021,.010]));
    audio.addEventListener('statechange',()=>{if(audio.state==='running'&&wanted&&!document.hidden)runScore();else reflectSound()});
    return true;
  }catch(e){if(audio){try{audio.close().catch(()=>{})}catch(ignored){}}audio=null;return false}
}
function playNote(midi,when,dur,loud,pan,bass=false){
  if(!audio||!midi)return;
  const osc=audio.createOscillator(),env=audio.createGain(),spatial=audio.createStereoPanner?audio.createStereoPanner():audio.createGain(),freq=440*2**((midi-69)/12);
  if(spatial.pan)spatial.pan.value=pan;if(bass)osc.type='sine';else osc.setPeriodicWave(timbre);
  osc.frequency.setValueAtTime(freq*(bass?1:1.0022),when);osc.frequency.exponentialRampToValueAtTime(freq,when+.09);
  const attack=bass ? .30:.013;env.gain.setValueAtTime(.0001,when);env.gain.exponentialRampToValueAtTime(loud,when+attack);
  env.gain.exponentialRampToValueAtTime(loud*(bass ? .72:.38),when+attack+(bass ? .40:.21));
  env.gain.exponentialRampToValueAtTime(.00012,when+dur);
  osc.connect(env);env.connect(spatial);spatial.connect(voiceBus);
  osc.onended=()=>{osc.disconnect();env.disconnect();spatial.disconnect()};osc.start(when);osc.stop(when+dur+.035);
}
function scheduleScore(){
  if(!audio||audio.state!=='running'||!wanted||document.hidden)return;
  const now=audio.currentTime;if(noteTime<now-.2)noteTime=now+.055;
  while(noteTime<now+.29){
    const idx=beat%melody.length,m=melody[idx];
    if(m){playNote(m,noteTime,1.82+(idx%4)*.19,.25+.043*(idx%5===0),sin(beat*.72)*.33);
      if(idx===4||idx===34||idx===56)playNote(m+12,noteTime+.027,2.3,.054,-.37)}
    if(beat%8===0)playNote([50,47,43,45,50,47,45,50][Math.floor(beat/8)%8],noteTime+.022,3.55,.12,-.18,true);
    if(beat%8===5)playNote([57,54,55,57][Math.floor(beat/8)%4],noteTime+.058,2.23,.075,.29);
    beat++;noteTime+=.438;
  }
}
function runScore(){
  if(!audio||!master||!wanted||document.hidden||audio.state!=='running'){reflectSound();return}
  master.gain.cancelScheduledValues(audio.currentTime);master.gain.setTargetAtTime(.219,audio.currentTime,.24);
  if(!tickTimer){noteTime=audio.currentTime+.07;scheduleScore();tickTimer=window.setInterval(scheduleScore,105)}
  reflectSound();
}
function wakeMusic(){
  if(manuallyQuiet||!wanted||document.hidden)return;
  if(!makeAudio()){reflectSound();return}
  if(audio.state==='running')runScore();else audio.resume().then(runScore).catch(reflectSound);
}
function quietMusic(){
  if(tickTimer){clearInterval(tickTimer);tickTimer=0}
  if(audio&&master){
    master.gain.cancelScheduledValues(audio.currentTime);master.gain.setTargetAtTime(.00001,audio.currentTime,.068);
    setTimeout(()=>{if(audio&&(!wanted||document.hidden)&&audio.state==='running')audio.suspend().catch(()=>{})},330);
  }
  reflectSound();
}
soundButton.addEventListener('click',()=>{
  if(audio&&audio.state==='running'&&wanted){wanted=false;manuallyQuiet=true;quietMusic()}
  else{wanted=true;manuallyQuiet=false;wakeMusic()}
});


function sizeScene(){
  const rect=stage.getBoundingClientRect(),width=rect.width,height=rect.height;
  if(width<1||height<1)return false;
  if(W&&Math.abs(width-W*unit)<.05&&Math.abs(height-H*unit)<.05&&canvas.width===Math.round(width*Math.min(window.devicePixelRatio||1,1.85,Math.sqrt(4600000/(width*height))))){resizePending=false;return true}
  const oldW=W,oldH=H,oldLength=routeLen,oldPhases=cats.map(c=>c.progress/Math.max(1,oldLength));
  unit=Math.min(height/750,width/750);W=width/unit;H=height/unit;bank=H*.766;pad=Math.max(92,W*.105);
  const dpr=Math.min(window.devicePixelRatio||1,1.85,Math.sqrt(4600000/(width*height)));canvas.width=Math.max(1,Math.round(width*dpr));pixel=canvas.width/W;canvas.height=Math.max(1,Math.round(H*pixel));
  cacheScale=Math.max(.32,Math.min(pixel,1.58,Math.sqrt(3450000/((W+2*pad)*(H+2*pad)))));
  roof=new Float32Array(Math.ceil(W/4)+2).fill(bank);
  ground=sheet(paintLand);farwires=sheet(g=>paintWires(g,false));city=sheet(paintTown);overwires=sheet(g=>paintWires(g,true));
  for(let i=1;i<roof.length;i++)roof[i]=Math.min(roof[i],roof[i-1]+2.42);
  for(let i=roof.length-2;i>=0;i--)roof[i]=Math.min(roof[i],roof[i+1]+2.42);
  makeRoute();
  startDist=nearRoute(W*.505,H*.268,1,0);
  const lower=nearRoute(W*.612,H*.518,-1,.32);
  cats=[newCat(0,oldPhases.length?oldPhases[0]*routeLen:startDist),newCat(1,oldPhases.length?oldPhases[1]*routeLen:lower)];
  if(!separated(cats[0].nodes,cats[0],cats[1]))cats[1]=newCat(1,cats[0].progress+routeLen*.5);
  if(oldW&&oldH){cam.x*=W/oldW;cam.y*=H/oldH;if(guide){guide.x=guide.x/oldW*W;guide.y=guide.y/oldH*H}}
  reflection=surface(Math.min(1190,canvas.width),Math.min(420,Math.max(130,(H-bank)*pixel*1.25)));
  refCtx=reflection.getContext('2d',{alpha:false});makeFestival();resizePending=false;return true;
}
function moveCamera(dt){
  const t=demo?demoClock:elapsed,slow=still ? .36:1,phase=demo?t*TAU/20:t*.087*slow;
  let x=W*.0105*sin(phase),y=H*(.0048*sin(phase*2-.29)+.0025*cos(phase)),z=1.012+.006*(.5+.5*sin(phase-.6));
  if(view!=='wide'){
    const c=cats[view==='ember'?0:1];z=1.235;
    x+=clamp((c.head.x-W/2)*.44,-W*.151,W*.151);
    y+=(c.head.y-H*.495)*.235;
  }
  const k=1-Math.exp(-dt*1.50);cam.x=mix(cam.x,x,k);cam.y=mix(cam.y,y,k);cam.z=mix(cam.z,z,k);
}
function drawScene(){
  const g=ctx,t=elapsed;g.setTransform(pixel,0,0,pixel,0,0);g.globalAlpha=1;g.lineCap='round';g.lineJoin='round';g.imageSmoothingEnabled=true;
  g.save();worldView(g,.53);blit(g,ground);g.restore();
  g.save();worldView(g,.78);risingLanterns(g,t,false);g.restore();
  g.save();worldView(g);blit(g,farwires);blit(g,city);
  silkTrail(g,cats[1],t);silkTrail(g,cats[0],t);
  drawCat(g,cats[1],t);drawCat(g,cats[0],t);blit(g,overwires);g.restore();
  g.save();worldView(g,1.04);risingLanterns(g,t,true);sparks(g,t);g.restore();
  const by=(bank-H/2-cam.y)*cam.z+H/2;water(g,t,by);reeds(g,t);
  g.save();g.translate(W*.5,H*.48);g.scale(W*.72,H*.81);g.fillStyle=radial(g,0,0,1,[0,'rgba(11,19,30,0)',.51,'rgba(11,19,30,0)',1,'rgba(10,20,31,.27)']);g.fillRect(-1.3,-1.3,2.6,2.6);g.restore();
  g.save();g.setTransform(1,0,0,1,0,0);g.fillStyle=grain;g.fillRect(0,0,canvas.width,canvas.height);g.restore();
  if(guide||demo){
    g.save();worldView(g);
    if(guide)targetRing(g,guide,t,touchId!==null ? .96:clamp((guide.until-t)*.72,0,.79));
    else for(const c of cats){const a=demoGuide(c);if(a)targetRing(g,a,t,a.alpha*.86)}
    g.restore();
  }
}
function advance(stamp){
  let dt=lastTime?clamp((stamp-lastTime)/1000,0,.075):0;lastTime=stamp;
  if(resizePending){if(!sizeScene()){requestAnimationFrame(advance);return}dt=0}
  if(!document.hidden){
    const steps=dt>.025?Math.ceil(dt/.021):1,delta=dt/steps;
    for(let i=0;i<steps;i++){
      elapsed+=delta;if(demo)demoClock=wrap(demoClock+delta,20);
      if(guide&&touchId===null&&elapsed>=guide.until)releaseCat();
      if(delta>0){steerCat(cats[0],cats[1],delta,elapsed);steerCat(cats[1],cats[0],delta,elapsed)}
      moveCamera(delta);
    }
    drawScene();
  }
  requestAnimationFrame(advance);
}
function stopDemo(){if(demo){demo=false;updateGuide()}}
document.addEventListener('pointerdown',e=>{if(e.isTrusted)stopDemo()},{capture:true,passive:true});
window.addEventListener('hashchange',()=>{demo=location.hash==='#demo';demoClock=0;updateGuide()});
function touchWorld(e){const rect=canvas.getBoundingClientRect();return {x:((e.clientX-rect.left)/unit-W/2)/cam.z+W/2+cam.x,y:((e.clientY-rect.top)/unit-H/2)/cam.z+H/2+cam.y}}
function steerToPointer(e){const v=touchWorld(e),r=cats[guide.cat].hit[0];guide.x=clamp(v.x,r,W-r);guide.y=clamp(v.y,r+5,altitude(guide.x,r))}
canvas.addEventListener('pointerdown',e=>{
  if(touchId!==null||!cats.length||(e.pointerType==='mouse'&&e.button!==0))return;
  e.preventDefault();stopDemo();wakeMusic();const v=touchWorld(e);let nearest=0,best=Infinity;
  for(const c of cats){for(let i=1;i<c.nodes.length;i++){const d=Math.sqrt(pointSegment(v.x,v.y,c.nodes[i-1],c.nodes[i]))-c.radii[i];if(d<best){best=d;nearest=c.id}}}
  if(guide&&guide.cat!==nearest)releaseCat();
  touchId=e.pointerId;guide={cat:nearest,x:v.x,y:v.y,until:Infinity};steerToPointer(e);canvas.classList.add('held');
  try{canvas.setPointerCapture(e.pointerId)}catch(ignored){}updateGuide();
});
canvas.addEventListener('pointermove',e=>{if(e.pointerId!==touchId||!guide)return;e.preventDefault();steerToPointer(e)});
function finishTouch(e){
  if(e.pointerId!==touchId)return;
  touchId=null;if(guide)guide.until=elapsed+3.3;canvas.classList.remove('held');
  if(canvas.hasPointerCapture(e.pointerId)){try{canvas.releasePointerCapture(e.pointerId)}catch(ignored){}}updateGuide();
}
canvas.addEventListener('pointerup',finishTouch);canvas.addEventListener('pointercancel',finishTouch);canvas.addEventListener('lostpointercapture',finishTouch);
for(const button of viewBtns)button.addEventListener('click',()=>{
  stopDemo();view=button.dataset.view;for(const b of viewBtns)b.setAttribute('aria-pressed',String(b===button));wakeMusic();
});
const expand=document.getElementById('expand'),leave=document.getElementById('leave');let nativeCinema=false;
function setCinema(flag){document.body.classList.toggle('cinema',flag);resizePending=true;(flag?leave:expand).focus({preventScroll:true})}
expand.addEventListener('click',()=>{
  stopDemo();setCinema(true);wakeMusic();
  if(document.fullscreenEnabled&&document.documentElement.requestFullscreen){try{document.documentElement.requestFullscreen().then(()=>{nativeCinema=true}).catch(()=>{})}catch(ignored){}}
});
leave.addEventListener('click',()=>{setCinema(false);if(document.fullscreenElement&&document.exitFullscreen)document.exitFullscreen().catch(()=>{})});
document.addEventListener('fullscreenchange',()=>{if(document.fullscreenElement)nativeCinema=true;else if(nativeCinema){nativeCinema=false;if(document.body.classList.contains('cinema'))setCinema(false)}});
document.addEventListener('keydown',e=>{if(e.key==='Escape'&&document.body.classList.contains('cinema'))leave.click()});
window.addEventListener('resize',()=>{resizePending=true},{passive:true});
if(window.ResizeObserver)new ResizeObserver(()=>{resizePending=true}).observe(stage);
document.addEventListener('visibilitychange',()=>{
  lastTime=0;if(document.hidden){if(guide&&touchId!==null){touchId=null;guide.until=elapsed+1.2;canvas.classList.remove('held');updateGuide()}quietMusic()}
  else if(audio&&!manuallyQuiet&&wanted)wakeMusic();
});
ambientGlows={moon:glowSprite('244,217,171'),gold:glowSprite('255,187,94'),ember:glowSprite('255,143,65'),pearl:glowSprite('212,221,211')};
for(const p of paints)p.art={cells:[makeCell(p,0),makeCell(p,1)],face:makeFace(p)};
updateGuide();requestAnimationFrame(advance);
if(makeAudio()&&audio.state==='running')runScore();
})();
</script>
</body>
</html>