• 01 - Games
  • 02 - Creative Instruments & Explorers
  • 03 - Language, Signals & Text
  • 04 - Developer & Web Utilities
  • 05 - Generators & Data
  • 06 - Colour Theory
  • 07 - Music 26
  • 08 - 3D, Shaders & Visuals
ARCHIVE
  • Locust
  • Butterfly
  • Cockroach
  • Spider
  • Scorpion
  • Dragon
  • Brazilian Treehopper
  • Tardigrade
  • Diatoms
  • Bumblebee
  • Wasp
  • Hammerhead Worm
  • Giraffe Weevil
  • Trilobite Beetle

WASP SOURCE CODE

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ThreeJS: Wasp</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<style>
  * { margin: 0; padding: 0; box-sizing: border-box; }
  html, body { height: 100%; overflow: hidden; background: radial-gradient(ellipse at 50% 38%, #16233c 0%, #0e1626 55%, #05070d 100%); }
  #c { position: fixed; inset: 0; width: 100%; height: 100%; display: block; cursor: grab; touch-action: none; }
  #c:active { cursor: grabbing; }
</style>
</head>
<body>
<canvas id="c"></canvas>
<script>
{
"use strict";
if (typeof THREE === 'undefined') throw new Error('three missing');
const T = THREE, TAU = Math.PI*2;
const V3 = (x=0,y=0,z=0) => new T.Vector3(x,y,z);
const clamp = (x,a,b) => Math.max(a, Math.min(b, x));
const lerp = (a,b,t) => a + (b-a)*t;
const smooth = t => { t = clamp(t,0,1); return t*t*(3-2*t); };
let seed = 31337;
const rnd = () => (seed = (seed*16807) % 2147483647, (seed-1)/2147483646);
const rr = (a,b) => a + (b-a)*rnd();
const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
const UP = V3(0,1,0), DS = T.DoubleSide;
const lin = h => new T.Color(h).convertSRGBToLinear();

/* =====================================================================
   RENDERER / SCENE / ENVIRONMENT
   ===================================================================== */
const canvas = document.getElementById('c');
const renderer = new T.WebGLRenderer({ canvas, antialias:true, alpha:true, powerPreference:'high-performance' });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.outputEncoding = T.sRGBEncoding;
renderer.toneMapping = T.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = T.PCFSoftShadowMap;
const ANISO = renderer.capabilities.getMaxAnisotropy();

const scene = new T.Scene();
scene.fog = new T.FogExp2(0x0b1220, 0.045);
const camera = new T.PerspectiveCamera(42, innerWidth/innerHeight, 0.03, 200);
(function(){
  const c=document.createElement('canvas'); c.width=1024; c.height=512; const x=c.getContext('2d');
  const g=x.createLinearGradient(0,0,0,512); g.addColorStop(0,'#3a2a63'); g.addColorStop(.3,'#1a1030'); g.addColorStop(.5,'#0a0612'); g.addColorStop(.62,'#1c1024'); g.addColorStop(1,'#040208');
  x.fillStyle=g; x.fillRect(0,0,1024,512);
  [[190,110,210,'#7a55ff',.6],[800,80,230,'#22d3ff',.5],[560,300,280,'#ff3fa4',.34],[960,250,200,'#ffd36e',.3],[80,340,240,'#2affc2',.2],[400,400,300,'#5522ff',.22]].forEach(b=>{
    const rg=x.createRadialGradient(b[0],b[1],0,b[0],b[1],b[2]); rg.addColorStop(0,b[3]); rg.addColorStop(1,'rgba(0,0,0,0)'); x.globalAlpha=b[4]; x.fillStyle=rg; x.beginPath(); x.arc(b[0],b[1],b[2],0,7); x.fill(); });
  const tex=new T.CanvasTexture(c); tex.mapping=T.EquirectangularReflectionMapping; tex.encoding=T.sRGBEncoding;
  const pm=new T.PMREMGenerator(renderer); pm.compileEquirectangularShader(); scene.environment=pm.fromEquirectangular(tex).texture; pm.dispose(); tex.dispose();
})();

/* =====================================================================
   IRIDESCENT MATERIAL
   Hue cycles with time and shifts with viewing angle (thin-film look).
   Data textures: R = brightness, G = hue offset, B = film strength, A = alpha.
   ===================================================================== */
const U_TIME = { value: 0 };
const HSL_GLSL = `
vec3 hsl2rgb(vec3 c){ vec3 rgb = clamp(abs(mod(c.x*6.0+vec3(0.,4.,2.),6.)-3.)-1.,0.,1.);
  return c.z + c.y*(rgb-0.5)*(1.0-abs(2.0*c.z-1.0)); }
`;
function iriMat(o={}){
  const m = new T.MeshStandardMaterial({ color:0xffffff, roughness:o.rough??.28, metalness:o.metal??.55,
    side:o.side??T.FrontSide, envMapIntensity:o.env??1.3, transparent:!!o.transparent, depthWrite:o.depthWrite??true });
  m.defines = {};
  if (o.pat){ m.map = o.pat; m.defines.USE_PAT = ''; }
  if (o.bump){ m.bumpMap = o.bump; m.bumpScale = o.bumpScale ?? .002; }
  const u = { uTime:U_TIME, uHue:{value:o.hue??0}, uSat:{value:o.sat??.85}, uLight:{value:o.light??.5}, uIri:{value:o.iri??1}, uAlpha:{value:o.alpha??1}, uFilm:{value:o.film??.45} };
  m.userData.u = u;
  m.onBeforeCompile = sh => {
    Object.assign(sh.uniforms, u);
    sh.fragmentShader = 'uniform float uTime; uniform float uHue; uniform float uSat; uniform float uLight; uniform float uIri; uniform float uAlpha; uniform float uFilm;\n' + HSL_GLSL +
      sh.fragmentShader.replace('#include <map_fragment>', `
#ifdef USE_PAT
  vec4 patS = texture2D(map, vUv);
#else
  vec4 patS = vec4(0.5263, 0.0, 1.0, 1.0);
#endif
  diffuseColor.a *= patS.a * uAlpha;`).replace('#include <normal_fragment_maps>', `#include <normal_fragment_maps>
  {
    float ndv = clamp(abs(dot(normal, normalize(vViewPosition))), 0.0, 1.0);
    float iriS = patS.b * uIri;
    float h = fract(uTime*0.05 + uHue + patS.g + (1.0-ndv)*uFilm*iriS);
    float L = clamp(uLight * patS.r * 1.9, 0.0, 0.82);
    vec3 c = pow(hsl2rgb(vec3(h, uSat*(0.3+0.7*patS.b), L)), vec3(2.2));
    diffuseColor.rgb = c;
    metalnessFactor = mix(metalnessFactor, 0.9, iriS*0.5);
    roughnessFactor = mix(roughnessFactor, 0.14, iriS*0.45);
    totalEmissiveRadiance += c * 0.14 * iriS * pow(1.0-ndv, 1.5) * uAlpha;
  }`);
  };
  m.customProgramCacheKey = () => 'iri' + (o.pat?'p':'') + (o.bump?'b':'');
  return m;
}

/* =====================================================================
   HELPERS
   ===================================================================== */
function makeCanvas(w,h,draw){ const c=document.createElement('canvas'); c.width=w; c.height=h; draw(c.getContext('2d'),w,h); return c; }
function dataTex(c){ const t=new T.CanvasTexture(c); t.anisotropy=ANISO; return t; }
const D = (r,g,b,a=1) => `rgba(${Math.round(clamp(r,0,1)*255)},${Math.round(clamp(g,0,1)*255)},${Math.round(clamp(b,0,1)*255)},${a})`;
function lathe(len,rf,n=12,rs=12){ const p=[]; for(let i=0;i<=rs;i++){ const s=i/rs; p.push(new T.Vector2(Math.max(rf(s),.0005), s*len)); } return new T.LatheGeometry(p,n); }
const alongX = (len,rf,n,rs) => lathe(len,rf,n,rs).rotateZ(-Math.PI/2);
const alongZ = (len,rf,n,rs) => lathe(len,rf,n,rs).rotateX(Math.PI/2);
const SPH = new T.SphereGeometry(1, 30, 22), SPH_LO = new T.SphereGeometry(1, 10, 8);
const CONE = new T.ConeGeometry(1,1,5).translate(0,.5,0);
const HAIR = new T.CylinderGeometry(0, 1, 1, 3, 1).translate(0,.5,0);
const _q = new T.Quaternion(), _m = new T.Matrix4(), _x=V3(), _y=V3(), _z=V3();
function mesh(geo,mat,parent,pos,scl){ const m=new T.Mesh(geo,mat); if(pos) m.position.copy(pos); if(scl!==undefined) (typeof scl==='number'?m.scale.setScalar(scl):m.scale.copy(scl)); m.castShadow=true; m.receiveShadow=true; parent&&parent.add(m); return m; }
function orient(o,from,to,up){ _x.subVectors(to,from).normalize(); _z.crossVectors(_x,up).normalize(); _y.crossVectors(_z,_x); _m.makeBasis(_x,_y,_z); o.quaternion.setFromRotationMatrix(_m); o.position.copy(from); }
function instanced(parent,geo,mat,list){ const im=new T.InstancedMesh(geo,mat,list.length), m4=new T.Matrix4();
  list.forEach(([p,d,len,rad],i)=>{ _q.setFromUnitVectors(UP,d.clone().normalize()); m4.compose(p,_q,V3(rad,len,rad)); im.setMatrixAt(i,m4); });
  im.instanceMatrix.needsUpdate=true; im.castShadow=true; parent.add(im); return im; }
const randDir = () => V3(rr(-1,1),rr(-1,1),rr(-1,1)).normalize();
function gridGeo(NU,NV,fn){ const pos=[],uv=[],idx=[];
  for(let i=0;i<=NU;i++) for(let j=0;j<=NV;j++){ const u=i/NU, v=j/NV, p=fn(u,v); pos.push(p[0],p[1],p[2]); uv.push(u,v); }
  for(let i=0;i<NU;i++) for(let j=0;j<NV;j++){ const a=i*(NV+1)+j,b=a+NV+1; idx.push(a,b,a+1,b,b+1,a+1); }
  const g=new T.BufferGeometry(); g.setAttribute('position',new T.Float32BufferAttribute(pos,3)); g.setAttribute('uv',new T.Float32BufferAttribute(uv,2)); g.setIndex(idx); g.computeVertexNormals(); return g; }

/* =====================================================================
   PATTERN TEXTURES  (dark bands vs bright bands = two contrasting film hues)
   ===================================================================== */
// gaster tergite: dark front, bright rear band, dark median notch and paired dots
const tergC = makeCanvas(256,128,(g,W,H)=>{ g.fillStyle=D(.2,.0,1); g.fillRect(0,0,W,H);
  g.fillStyle=D(.88,.42,1); g.fillRect(0,H*.42,W,H*.58);
  g.fillStyle=D(.2,.0,1); g.beginPath(); g.moveTo(W*.43,H*.42); g.lineTo(W*.57,H*.42); g.lineTo(W*.5,H*.8); g.closePath(); g.fill();
  [.33,.67].forEach(u=>{ g.beginPath(); g.ellipse(u*W,H*.66,W*.035,H*.1,0,0,7); g.fill(); });
  g.fillStyle=D(.6,.42,1); g.fillRect(0,H*.96,W,H*.04);
  g.globalCompositeOperation='multiply'; for(let i=0;i<2500;i++){ const v=Math.round(rr(195,255)); g.fillStyle=`rgb(${v},255,255)`; g.fillRect(rnd()*W,rnd()*H,2,2); } });
const tergT=dataTex(tergC);
const sternC = makeCanvas(128,64,(g,W,H)=>{ g.fillStyle=D(.3,.0,1); g.fillRect(0,0,W,H); g.fillStyle=D(.8,.42,1); g.fillRect(0,H*.55,W,H*.45); });
const sternT=dataTex(sternC);
// face: bright clypeus with a dark anchor mark
const faceC = makeCanvas(256,256,(g,W,H)=>{ g.fillStyle=D(.9,.42,1); g.fillRect(0,0,W,H);
  g.fillStyle=D(.2,.0,1); g.fillRect(W*.47,H*.15,W*.06,H*.5); g.beginPath(); g.ellipse(W*.5,H*.42,W*.07,H*.06,0,0,7); g.fill(); });
const faceT=dataTex(faceC);
const eyeC = makeCanvas(256,256,(g,W,H)=>{ g.fillStyle=D(.18,.62,1); g.fillRect(0,0,W,H); const r=3;
  for(let row=0;row*r*1.5<H+r;row++) for(let col=0;col*r*1.75<W+r;col++){ const x=col*r*1.75+(row%2)*r*.87, y=row*r*1.5; g.fillStyle=D(.42,.66,1); g.beginPath(); g.arc(x,y,r*.6,0,7); g.fill(); } });
const eyeT=dataTex(eyeC), eyeB=new T.CanvasTexture(eyeC);
// wings: smoky amber membrane, dark veins, thin-film sheen
const foreC = makeCanvas(512,160,(g,W,H)=>{ g.clearRect(0,0,W,H);
  let gr=g.createLinearGradient(0,0,0,H); gr.addColorStop(0,D(.6,.08,1,.55)); gr.addColorStop(.35,D(.7,.12,1,.3)); gr.addColorStop(1,D(.75,.2,1,.22)); g.fillStyle=gr; g.fillRect(0,0,W,H);
  for(let i=0;i<4000;i++){ g.fillStyle=D(.8,rr(.05,.25),1,.2); g.fillRect(rnd()*W,rnd()*H,1.2,1.2); }
  const X=u=>u*W, Y=v=>(1-v)*H, vein=(pts,w)=>{ g.strokeStyle=D(.12,.05,.4,1); g.lineWidth=w; g.lineJoin=g.lineCap='round'; g.beginPath(); pts.forEach(([u,v],i)=>i?g.lineTo(X(u),Y(v)):g.moveTo(X(u),Y(v))); g.stroke(); };
  vein([[0,.66],[.3,.92],[.6,.95]],7); g.fillStyle=D(.12,.05,.4,1); g.beginPath(); g.ellipse(X(.6),Y(.92),20,7,-.05,0,7); g.fill();
  vein([[0,.58],[.35,.8],[.6,.86],[.88,.78]],3.5); vein([[.6,.86],[.88,.78],[.75,.7],[.6,.74]],3);
  vein([[.42,.74],[.6,.74]],3); [[.42,.74,.42,.52],[.52,.74,.5,.52],[.6,.74,.6,.5],[.7,.72,.7,.48]].forEach(([a,b,c,d])=>vein([[a,b],[c,d]],3));
  vein([[0,.5],[.22,.54],[.42,.52],[.7,.48]],3.5); vein([[0,.4],[.3,.3],[.5,.28],[.62,.22]],3.5); vein([[.3,.3],[.42,.52]],3); vein([[0,.26],[.4,.08]],3); });
const hindC = makeCanvas(256,96,(g,W,H)=>{ g.clearRect(0,0,W,H); g.fillStyle=D(.72,.15,1,.22); g.fillRect(0,0,W,H);
  const vein=(pts,w)=>{ g.strokeStyle=D(.12,.05,.4,1); g.lineWidth=w; g.lineCap='round'; g.beginPath(); pts.forEach(([u,v],i)=>i?g.lineTo(u*W,(1-v)*H):g.moveTo(u*W,(1-v)*H)); g.stroke(); };
  vein([[0,.62],[.6,.92]],4); vein([[0,.45],[.35,.5],[.6,.42]],2.5); vein([[0,.3],[.42,.2]],2.5); vein([[.35,.5],[.42,.2]],2); });
const foreT=dataTex(foreC), hindT=dataTex(hindC);

/* =====================================================================
   THE WASP
   ===================================================================== */
const wasp=new T.Group(); scene.add(wasp);
const body=new T.Group(); wasp.add(body);
wasp.scale.setScalar(.5);
const leftSide=new T.Group(); leftSide.scale.x=-1; body.add(leftSide); const sides=[body,leftSide];

const M = {
  dark:  iriMat({hue:.62,light:.22,iri:1,rough:.2,metal:.65}),
  bright:iriMat({hue:.04,light:.55,iri:1,rough:.24,metal:.55}),
  terg:  iriMat({pat:tergT,hue:.62,light:.5,rough:.2,metal:.6,side:DS}),
  stern: iriMat({pat:sternT,hue:.62,light:.5,rough:.3,side:DS}),
  face:  iriMat({pat:faceT,hue:.62,light:.55,rough:.26}),
  eye:   iriMat({pat:eyeT,bump:eyeB,bumpScale:.0015,hue:.5,light:.35,rough:.08,metal:.7,env:1.8,film:.7}),
  leg:   iriMat({hue:.06,light:.5,iri:.9,rough:.3,metal:.5}),
  legD:  iriMat({hue:.66,light:.24,iri:.8,rough:.3}),
  ant:   iriMat({hue:.66,light:.24,iri:.8,rough:.3}),
  antB:  iriMat({hue:.1,light:.5,iri:.8,rough:.3}),
  seta:  iriMat({hue:.1,light:.6,sat:.5,iri:.5,rough:.5}),
  claw:  new T.MeshStandardMaterial({color:lin(0x140c08),roughness:.3,metalness:.4}),
  ocel:  new T.MeshStandardMaterial({color:lin(0xffe0a0),emissive:lin(0x553311),roughness:.15,metalness:.3}),
  pulp:  new T.MeshStandardMaterial({color:lin(0xb8ab98),roughness:.95}),
};

// mesosoma: pronotal collar, mesoscutum, scutellum, metanotum, propodeum
const thor=new T.Group(); body.add(thor);
mesh(SPH, M.dark, thor, V3(0,.04,.86), V3(.24,.22,.32));
{ const col=mesh(new T.TorusGeometry(.175,.026,10,28,Math.PI*1.2), M.bright, thor, V3(0,.04,1.07)); col.rotation.set(0,0,-Math.PI*.1); col.scale.z=.7; }   // pronotal collar
mesh(SPH, M.dark, thor, V3(0,.02,1.08), V3(.17,.16,.08));
mesh(SPH, M.dark, thor, V3(0,.16,.58), V3(.13,.07,.09));                     // scutellum
[-1,1].forEach(s=>mesh(SPH_LO, M.bright, thor, V3(s*.06,.215,.6), V3(.04,.012,.035)));   // scutellar spots
mesh(SPH, M.bright, thor, V3(0,.12,.49), V3(.1,.04,.04));                    // metanotal band
mesh(SPH, M.dark, thor, V3(0,.0,.42), V3(.19,.17,.13));                      // propodeum
[-1,1].forEach(s=>{ mesh(SPH_LO, M.bright, thor, V3(s*.12,.02,.4), V3(.04,.07,.04)); mesh(SPH_LO, M.bright, thor, V3(s*.21,-.02,.82), V3(.03,.06,.09)); });
instanced(thor, HAIR, M.seta, Array.from({length:260},()=>{ const d=randDir(); return [V3(d.x*.24,.04+d.y*.22,.86+d.z*.32), d.clone().add(V3(0,.3,0)), rr(.02,.05), .003]; }));
// petiole & gaster
mesh(alongZ(.14,u=>.055+.02*Math.sin(Math.PI*u),10,6), M.dark, body, V3(0,-.01,.24));
const gaster=new T.Group(); gaster.position.set(0,-.02,.26); body.add(gaster);
const gSegs=[];
function shellGeo(rx0,ry0,rx1,ry1,len,a0,a1){ return gridGeo(6,28,(s,q)=>{ const a=lerp(a0,a1,q), rx=lerp(rx0,rx1,s), ry=lerp(ry0,ry1,s); return [rx*Math.sin(a), ry*Math.cos(a), -s*len]; }); }
const GB=[.07,.25,.32,.335,.3,.23,.13];
[[.0,.3],[-.28,.32],[-.58,.33],[-.88,.3],[-1.16,.27],[-1.42,.22]].forEach(([z,len],i)=>{
  const w0=GB[i]*(i?.94:1), w1=GB[i+1]*1.02;
  const g=new T.Group(); g.position.set(0,-.02-i*.018,z); gaster.add(g); gSegs.push(g);
  mesh(shellGeo(w0,w0*.92,w1,w1*.92,len+.03,-1.8,1.8), M.terg, g);
  mesh(shellGeo(w0*.96,w0*.82,w1*.97,w1*.84,len+.02,Math.PI-1.4,Math.PI+1.4), M.stern, g);
  mesh(SPH_LO, M.legD, g, V3(0,0,-len*.5), V3(Math.min(w0,w1)*.92,Math.min(w0,w1)*.82,len*.52));
});
const sting=mesh(alongZ(.18,u=>.022*(1-u)+.001,6,4), M.claw, gaster, V3(0,-.1,-1.62)); sting.rotation.x=Math.PI;

// head: emarginate (kidney) eyes wrapping the antennal sockets, ocelli, patterned face, toothed mandibles
const head=new T.Group(); head.position.set(0,.02,1.26); head.rotation.x=.5; body.add(head);
mesh(SPH, M.dark, head, null, V3(.19,.17,.12));
mesh(SPH, M.face, head, V3(0,-.06,.07), V3(.12,.12,.07));
[-1,1].forEach(s=>{ const eg=SPH.clone(), pa=eg.attributes.position;
  for(let i=0;i<pa.count;i++){ const y=pa.getY(i), z=pa.getZ(i); pa.setX(i, pa.getX(i) - s*.55*Math.exp(-((y-.25)**2)/.08)*Math.max(0,z)); }
  eg.computeVertexNormals();
  const e=mesh(eg, M.eye, head, V3(s*.14,.0,.02), V3(.07,.15,.1)); e.rotation.y=s*.3;
  mesh(SPH_LO, new T.MeshStandardMaterial({color:0xffffff,roughness:.05,envMapIntensity:2}), head, V3(s*.17,.06,.08), .012);
  mesh(SPH_LO, M.bright, head, V3(s*.1,.07,.1), V3(.025,.035,.02));            // yellow eye notch fill
});
[[-0.035,.13,.06],[.035,.13,.06],[0,.15,.09]].forEach(p=>mesh(SPH_LO, M.ocel, head, V3(...p), .014));
const mandibles=[];
[-1,1].forEach(s=>{ const mg=new T.Group(); mg.position.set(s*.06,-.15,.08); head.add(mg);
  const mm=mesh(SPH, M.bright, mg, V3(-s*.025,-.02,.01), V3(.045,.03,.035)); mm.rotation.z=s*.4;
  instanced(mg, CONE, M.claw, [0,1,2,3].map(k=>[V3(-s*(.03+k*.014),-.035-k*.004,.015),V3(-s*.3,-1,.2),.02,.007]));
  mandibles.push({mg,s}); });
const pulp=mesh(new T.IcosahedronGeometry(1,2), M.pulp, head, V3(0,-.21,.1), 0.001);
// antennae: scape, pedicel, 11 flagellomeres with a curled tip
const antennae=[];
[-1,1].forEach(s=>{ const r=new T.Group(); r.position.set(s*.045,.05,.1); head.add(r); r.rotation.set(-1.0,s*.3,0);
  mesh(alongZ(.15,u=>.017*(1-.2*u),8,4), M.antB, r);
  const fl=new T.Group(); fl.position.z=.15; r.add(fl); fl.rotation.set(1.1,s*.3,0);
  let p=fl; const J=[]; for(let k=0;k<12;k++){ const j=new T.Group(); j.userData.b=k>8?.18:.03; j.rotation.x=j.userData.b; p.add(j);
    mesh(alongZ(.045,u=>.014*(k>3&&k<10?1.1:.9)*(.85+.15*Math.sin(u*Math.PI)),6,3), M.ant, j); const n=new T.Group(); n.position.z=.045; j.add(n); p=n; J.push(j); }
  antennae.push({r,fl,J,s}); });

// wings: folded lengthwise at rest (as vespids do), ghost copies blur the beat in flight
function wingGeo(L,W){ return gridGeo(30,10,(u,v)=>{ const env=Math.pow(Math.sin(Math.PI*clamp(u*1.04+.05,0,1)),.55)*(1-.2*u)*(u<.08?u/.08*.7+.3:1); const hw=.5*W*env; return [u*L,0,.04*u-hw+2*hw*v]; }); }
const FW=wingGeo(1.65,.5), HWg=wingGeo(1.25,.36);
const wingSets=[]; const GHOSTS=[-.85,-.35,.2,.7];
sides.forEach(p=>{ [null,...GHOSTS].forEach(gp=>{
  const a=gp===null?1:.3;
  const fp=new T.Group(); fp.position.set(.14,.22,.86); p.add(fp);
  const fm=new T.Mesh(FW, iriMat({pat:foreT,hue:.08,light:.6,rough:.12,metal:.35,side:DS,transparent:true,depthWrite:false,alpha:a,film:.8,env:1.8})); fm.renderOrder=3; fp.add(fm);
  const hp=new T.Group(); hp.position.set(.15,.18,.68); p.add(hp);
  const hm=new T.Mesh(HWg, iriMat({pat:hindT,hue:.1,light:.6,rough:.12,metal:.35,side:DS,transparent:true,depthWrite:false,alpha:a,film:.8})); hm.renderOrder=2; hp.add(hm);
  wingSets.push({fp,hp,fm,hm,gp,a}); });
  mesh(SPH, M.bright, p, V3(.16,.2,.9), V3(.045,.03,.07));                    // tegula
});

// legs (two-bone IK; feet placed in world space on the rail)
const legs=[];
function buildLeg(D,s){
  const hip=V3(s*D.hip[0],D.hip[1],D.hip[2]), tro=V3(s*D.tro[0],D.tro[1],D.tro[2]);
  const cg=new T.Group(); body.add(cg); orient(cg,hip,tro,UP); mesh(alongX(hip.distanceTo(tro)+.02,t=>.04*(1-.3*t)+.01,8,5), M.legD, cg);
  const fem=new T.Group(), tib=new T.Group(), tar=new T.Group(); body.add(fem,tib,tar);
  mesh(alongX(D.a,t=>.028*Math.sin(Math.PI*(.08+.86*t))**.4*(1-.2*t)+.008,10,8), M.legD, fem);
  mesh(alongX(D.b,t=>.018*(1-.2*t)+.006,8,8), M.leg, tib);
  instanced(tib, CONE, M.claw, [[V3(D.b*.97,-.01,.008),V3(1,-.4,.3),.06,.006],[V3(D.b*.97,-.01,-.008),V3(1,-.4,-.3),.05,.005]]);
  instanced(tib, HAIR, M.seta, Array.from({length:16},()=>{ const x=rnd()*D.b, a=rnd()*TAU; return [V3(x,Math.cos(a)*.018,Math.sin(a)*.018),V3(.8,Math.cos(a),Math.sin(a)),rr(.015,.03),.002]; }));
  let x=0; [.38,.18,.14,.12,.18].forEach((f,k)=>{ const L=D.tl*f; mesh(alongX(L,u=>.012*(1-k*.07)*(.8+.2*u),6,3), M.leg, tar, V3(x,0,0)); x+=L; });
  [-1,1].forEach(cs=>{ const c=mesh(alongX(.035,u=>.006*(1-u)+.0008,5,3), M.claw, tar, V3(x,0,cs*.006)); c.rotation.set(0,cs*.4,-1.0); });
  const L={D,s,tro,fem,tib,tar,home:V3(s*D.home[0],D.home[1],D.home[2]),air:V3(s*D.airT[0],D.airT[1],D.airT[2]),toeW:V3(),lift:V3(),target:V3(),step:-1,group:0};
  legs.push(L); return L;
}
const LEGDEF=[
  {hip:[.08,-.16,1.0],tro:[.13,-.2,1.04],a:.36,b:.36,tl:.24,home:[.42,-.62,1.5],airT:[.18,-.5,1.25],bend:[.5,1,.3]},
  {hip:[.12,-.18,.78],tro:[.18,-.22,.76],a:.4,b:.4,tl:.27,home:[.62,-.62,.75],airT:[.24,-.6,.55],bend:[.5,1,0]},
  {hip:[.12,-.16,.56],tro:[.18,-.2,.5],a:.46,b:.52,tl:.3,home:[.52,-.62,-.05],airT:[.2,-.85,-.2],bend:[.4,1,-.4]},
];
LEGDEF.forEach((D,i)=>[-1,1].forEach(s=>{ const L=buildLeg(D,s); L.group=((i%2===0)===(s<0))?0:1; }));

/* =====================================================================
   THE FENCE: weathered rail between two posts; scrape marks paint into the rail
   ===================================================================== */
const RAIL={W:1.7,H:.55,L:9};
function woodCanvas(w,h,vertical){ return makeCanvas(w,h,(g,W,H)=>{
  g.fillStyle='#4a453e'; g.fillRect(0,0,W,H);
  for(let i=0;i<220;i++){ const c=rnd(); g.strokeStyle=c<.6?`rgba(28,24,20,${rr(.15,.4)})`:`rgba(130,122,110,${rr(.08,.2)})`; g.lineWidth=rr(.6,2.5);
    const x=rnd()*W; g.beginPath(); g.moveTo(x,0); for(let y=0;y<=H;y+=H/24) g.lineTo(x+Math.sin(y*.004+i)*14+Math.sin(y*.02+i*3)*3,y); g.stroke(); }
  for(let i=0;i<14;i++){ g.strokeStyle='rgba(20,18,16,.8)'; g.lineWidth=rr(1.5,4); const x=rnd()*W, y=rnd()*H, l=rr(H*.05,H*.3); g.beginPath(); g.moveTo(x,y); g.lineTo(x+rr(-6,6),y+l); g.stroke(); }
  for(let i=0;i<4;i++){ const x=rnd()*W, y=rnd()*H, r=rr(8,20); const gr=g.createRadialGradient(x,y,0,x,y,r*2.5); gr.addColorStop(0,'rgba(30,22,16,.9)'); gr.addColorStop(.4,'rgba(60,50,40,.5)'); gr.addColorStop(1,'rgba(0,0,0,0)'); g.fillStyle=gr; g.beginPath(); g.ellipse(x,y,r,r*2.5,0,0,7); g.fill(); }
  for(let i=0;i<34;i++){ const x=rnd()*W, y=rnd()*H, r=rr(5,18), col=rnd()<.6?'150,168,105':'200,175,80';
    for(let k=0;k<14;k++){ const a=rnd()*TAU, d=rnd()*r; g.fillStyle=`rgba(${col},${rr(.2,.45)})`; g.beginPath(); g.arc(x+Math.cos(a)*d,y+Math.sin(a)*d,rr(1.5,r*.45),0,7); g.fill(); } }
}); }
// the top of the rail is a live canvas: x across, y along the length
const topC = woodCanvas(512,2048);
(function(){ const g=topC.getContext('2d'); for(let i=0;i<9;i++){ const x=rr(.25,.75)*512, y=rr(.1,.9)*2048, l=rr(60,260); g.strokeStyle='rgba(190,175,145,.5)'; g.lineWidth=rr(5,8); g.lineCap='round'; g.beginPath(); g.moveTo(x,y); g.lineTo(x+rr(-12,12),y+l); g.stroke(); } })();
const topT=new T.CanvasTexture(topC); topT.encoding=T.sRGBEncoding; topT.anisotropy=ANISO;
const sideT=new T.CanvasTexture(woodCanvas(256,1024)); sideT.encoding=T.sRGBEncoding; sideT.wrapS=sideT.wrapT=T.RepeatWrapping; sideT.anisotropy=ANISO;
const sideMat=new T.MeshStandardMaterial({map:sideT,bumpMap:sideT,bumpScale:.02,roughness:.92,envMapIntensity:.4});
const topMat=new T.MeshStandardMaterial({map:topT,bumpMap:topT,bumpScale:.015,roughness:.9,envMapIntensity:.4});
const fence=new T.Group(); scene.add(fence);
const rail=new T.Mesh(new T.BoxGeometry(RAIL.W,RAIL.H,RAIL.L),[sideMat,sideMat,topMat,sideMat,sideMat,sideMat]);
rail.position.y=-RAIL.H/2; rail.castShadow=rail.receiveShadow=true; fence.add(rail);
[-1,1].forEach(s=>{ const post=new T.Mesh(new T.BoxGeometry(1.4,14,1.4),sideMat); post.position.set(0,-6.4,s*(RAIL.L/2+.5)); post.castShadow=post.receiveShadow=true; fence.add(post);
  const cap=new T.Mesh(new T.ConeGeometry(1.0,.5,4),sideMat); cap.position.set(0,.85,s*(RAIL.L/2+.5)); cap.rotation.y=Math.PI/4; fence.add(cap);
  const nail=mesh(new T.CylinderGeometry(.07,.07,.04,12),new T.MeshStandardMaterial({color:lin(0x6a3a1c),roughness:.7,metalness:.6}),fence,V3(.71,-.25,s*(RAIL.L/2+.5))); nail.rotation.z=Math.PI/2;
  const streak=mesh(new T.PlaneGeometry(.12,1.2),new T.MeshStandardMaterial({color:lin(0x5a2a10),roughness:.9,transparent:true,opacity:.5}),fence,V3(.705,-.9,s*(RAIL.L/2+.5))); streak.rotation.y=Math.PI/2; });
// tall grass silhouettes beyond the fence
(function(){ const N=600, im=new T.InstancedMesh(new T.ConeGeometry(.03,1,4).translate(0,.5,0),new T.MeshStandardMaterial({color:0xffffff,roughness:.8}),N), m4=new T.Matrix4(), c=new T.Color();
  for(let i=0;i<N;i++){ const x=rr(-9,9), z=rr(-12,12); if(Math.abs(x)<1.6) continue; _q.setFromUnitVectors(UP,V3(rr(-.25,.25),1,rr(-.25,.25)).normalize()); m4.compose(V3(x,-4.5,z),_q,V3(1,rr(2.5,5.5),1)); im.setMatrixAt(i,m4); c.set(rnd()<.5?0x2a3a1e:0x3a4a28).convertSRGBToLinear(); im.setColorAt(i,c); }
  scene.add(im); })();
// rail-space painting helpers
function paintScrape(worldPt, prevPt){
  const l=rail.worldToLocal(worldPt.clone()), p=rail.worldToLocal(prevPt.clone());
  if(Math.abs(l.x)>RAIL.W/2-.05||Math.abs(l.z)>RAIL.L/2) return;
  const X=v=>(v.x+RAIL.W/2)/RAIL.W*512, Y=v=>(v.z+RAIL.L/2)/RAIL.L*2048;
  const g=topC.getContext('2d'); g.lineCap='round';
  g.strokeStyle='rgba(200,184,150,.6)'; g.lineWidth=7; g.beginPath(); g.moveTo(X(p),Y(p)); g.lineTo(X(l),Y(l)); g.stroke();
  g.strokeStyle='rgba(235,224,200,.35)'; g.lineWidth=3; g.beginPath(); g.moveTo(X(p)+1.5,Y(p)); g.lineTo(X(l)+1.5,Y(l)); g.stroke();
  topDirty=true;
}
let topDirty=false, topTimer=0;
const motes=(()=>{ const N=200,pos=new Float32Array(N*3); for(let i=0;i<N;i++){ pos[i*3]=rr(-8,8); pos[i*3+1]=rr(-3,6); pos[i*3+2]=rr(-8,8); }
  const g=new T.BufferGeometry(); g.setAttribute('position',new T.BufferAttribute(pos,3));
  const sp=new T.CanvasTexture(makeCanvas(32,32,x=>{ const gr=x.createRadialGradient(16,16,0,16,16,16); gr.addColorStop(0,'rgba(255,240,220,1)'); gr.addColorStop(1,'rgba(0,0,0,0)'); x.fillStyle=gr; x.fillRect(0,0,32,32); }));
  const p=new T.Points(g,new T.PointsMaterial({size:.05,map:sp,transparent:true,depthWrite:false,blending:T.AdditiveBlending,opacity:.5})); scene.add(p); return p; })();

/* lights */
scene.add(new T.HemisphereLight(0xbfd8ff,0x1a1030,.55));
const key=new T.DirectionalLight(0xfff0dc,1.6); key.position.set(4,8,5); key.castShadow=true; key.shadow.mapSize.set(2048,2048);
Object.assign(key.shadow.camera,{left:-5,right:5,top:5,bottom:-5,near:1,far:25}); key.shadow.bias=-.0004; key.shadow.normalBias=.02; key.shadow.radius=3; scene.add(key);
const rim=new T.PointLight(0x33ccff,2.0,70); rim.position.set(-6,3,-4); scene.add(rim);
const rim2=new T.PointLight(0xff33aa,1.1,70); rim2.position.set(6,0,-3); scene.add(rim2);
const glint=new T.PointLight(0xffffff,1.0,45); glint.position.set(2,4,8); scene.add(glint);

/* =====================================================================
   BEHAVIOUR: patrol the fence → land on the rail → walk backwards scraping
              wood fibre into a pulp ball → fly off with it → return
   ===================================================================== */
let tau=0;
function wander(t){ const a=t*.5+.5*Math.sin(t*.37), R=3.2+.9*Math.sin(t*.43);
  return V3(Math.cos(a)*R+.3*Math.sin(t*2.9), 1.8+.7*Math.sin(t*.8)+.2*Math.sin(t*2.5), Math.sin(a)*R*1.15+.3*Math.cos(t*2.2)); }
const st={mode:'fly',t:0,dur:rr(5,7),p0:V3(),p1:V3(),c0:V3(),c1:V3(),spot:V3(),yaw:0};
const bez=(a,b,c,d,s)=>{ const u=1-s; return a.clone().multiplyScalar(u*u*u).addScaledVector(b,3*u*u*s).addScaledVector(c,3*u*s*s).addScaledVector(d,s*s*s); };
const eul=new T.Euler(0,0,0,'YXZ');
const PERCH_H=.33;
let prev=wander(0), vel=V3(), roll=0, fold=0, ground=0, pulpAmt=0, prevTip=V3(), headDown=0;
wasp.position.copy(prev);

const _t=V3(),_hd=V3(),_ank=V3(),_d=V3(),_w=V3(),_kn=V3(),_a2=V3(),_toe=V3(),_air=V3(),_hw=V3();
function homeWorld(L,out){ out.copy(L.home); body.localToWorld(out); out.y=0; return out; }
function solveLegs(){
  body.updateMatrixWorld(true);
  for(const L of legs){
    const {a,b,tl}=L.D;
    _toe.copy(L.toeW); body.worldToLocal(_toe);
    _air.copy(L.air); _toe.lerp(_air,1-ground);
    _hd.set(_toe.x-L.tro.x,0,_toe.z-L.tro.z).normalize();
    _ank.copy(_toe).addScaledVector(_hd,-tl*.85); _ank.y+=tl*.45*ground;
    _d.subVectors(_ank,L.tro); const c=clamp(_d.length(),Math.abs(a-b)+.02,(a+b)*.995); _d.normalize();
    const B=L.D.bend; _w.set(L.s*B[0],B[1],B[2]); _w.addScaledVector(_d,-_w.dot(_d)).normalize();
    const al=Math.acos(clamp((a*a+c*c-b*b)/(2*a*c),-1,1));
    _kn.copy(L.tro).addScaledVector(_d,a*Math.cos(al)).addScaledVector(_w,a*Math.sin(al));
    _a2.copy(L.tro).addScaledVector(_d,c);
    orient(L.fem,L.tro,_kn,_w); orient(L.tib,_kn,_a2,_w);
    _t.copy(_toe).sub(_ank).add(_a2); orient(L.tar,_a2,_t,UP);
  }
}

function update(dt,t){
  st.t+=dt;
  const go=(m,d)=>{ st.mode=m; st.t=0; st.dur=d; };
  if(st.mode==='fly'){ tau+=dt; wasp.position.copy(wander(tau));
    if(st.t>st.dur && !reduceMotion){ go('approach',2.4); st.p0.copy(wasp.position); st.c0.copy(wasp.position).addScaledVector(vel,.8);
      st.spot.set(rr(-.25,.25),PERCH_H,rr(-2.6,2.6)); st.yaw=(rnd()<.5?0:Math.PI)+rr(-.35,.35); pulpAmt=0; } }
  else if(st.mode==='approach'){ st.p1.copy(st.spot); st.c1.copy(st.spot).add(V3(0,1.3,0)); wasp.position.copy(bez(st.p0,st.c0,st.c1,st.p1,smooth(st.t/st.dur)));
    if(st.t>=st.dur){ go('scrape',rr(7,9)); legs.forEach(L=>{ homeWorld(L,L.toeW); L.step=-1; }); } }
  else if(st.mode==='scrape'){
    const backDir=V3(-Math.sin(st.yaw),0,-Math.cos(st.yaw)), working=st.t>.8&&st.t<st.dur-.8;
    if(working){ st.spot.addScaledVector(backDir,dt*.1); st.yaw+=Math.sin(t*1.3)*dt*.12; pulpAmt=Math.min(1,pulpAmt+dt*.14); }
    st.spot.x=clamp(st.spot.x,-.55,.55); st.spot.z=clamp(st.spot.z,-3.6,3.6);
    wasp.position.copy(st.spot);
    if(st.t>=st.dur){ go('takeoff',1.5); tau+=1.8; st.p0.copy(wasp.position); st.c0.copy(wasp.position).add(V3(0,1.4,0)); } }
  else if(st.mode==='takeoff'){ const w=wander(tau); st.p1.copy(w); st.c1.copy(w).sub(wander(tau+.1)).multiplyScalar(8).add(w); wasp.position.copy(bez(st.p0,st.c0,st.c1,st.p1,smooth(st.t/st.dur))); if(st.t>=st.dur) go('fly',rr(5,8)); }

  const v=wasp.position.clone().sub(prev).divideScalar(Math.max(dt,1e-4)); prev.copy(wasp.position); vel.lerp(v,1-Math.exp(-dt*5));
  const perched=st.mode==='scrape';
  if(!perched){ const hs=Math.hypot(vel.x,vel.z), cur=new T.Euler().setFromQuaternion(wasp.quaternion,'YXZ'), yaw=hs>.05?Math.atan2(vel.x,vel.z):cur.y;
    let dy=Math.atan2(Math.sin(yaw-cur.y),Math.cos(yaw-cur.y)); roll+=(clamp(-dy*1.2,-.5,.5)-roll)*(1-Math.exp(-dt*3));
    let q=new T.Quaternion().setFromEuler(eul.set(-.18-clamp(vel.y*.08,-.3,.3)+clamp(hs*.04,0,.2),yaw,roll));
    if(st.mode==='approach'){ q.slerp(new T.Quaternion().setFromEuler(eul.set(.05,st.yaw,0)),smooth((st.t/st.dur-.5)/.5)); }
    wasp.quaternion.slerp(q,1-Math.exp(-dt*4)); }
  else wasp.quaternion.slerp(new T.Quaternion().setFromEuler(eul.set(.1+.06*headDown,st.yaw,0)),1-Math.exp(-dt*3));

  const landed=perched||(st.mode==='approach'&&st.t/st.dur>.88);
  fold+=((perched?1:0)-fold)*(1-Math.exp(-dt*(perched?3:12)));
  ground+=((landed?1:0)-ground)*(1-Math.exp(-dt*7));
  headDown+=((perched&&st.t>.6&&st.t<st.dur-.6?1:0)-headDown)*(1-Math.exp(-dt*4));

  // legs: stance feet stay put on the rail; a foot steps when it drifts from its home (alternating tripods)
  if(ground>.5){
    for(const L of legs){
      if(L.step>=0){ L.step+=dt/.22; const s=smooth(L.step); L.toeW.lerpVectors(L.lift,L.target,s); L.toeW.y=Math.sin(Math.PI*Math.min(1,L.step))*.08; if(L.step>=1){ L.step=-1; L.toeW.y=0; } }
      else { homeWorld(L,_hw); const busy=legs.some(o=>o.step>=0&&o.group!==L.group);
        if(!busy && L.toeW.distanceTo(_hw)>.11){ L.step=0; L.lift.copy(L.toeW); L.target.copy(_hw).add(V3(-Math.sin(st.yaw)*.05,0,-Math.cos(st.yaw)*.05)); } }
    }
  } else legs.forEach(L=>{ homeWorld(L,L.toeW); L.step=-1; });

  // wings: folded along the gaster at rest; ghosts sample the stroke in flight
  const flying=1-fold, beat=t*TAU*22;
  wingSets.forEach(W=>{ const ph=W.gp===null?Math.sin(beat):W.gp;
    const sweep=lerp(1.42,ph*.85,flying), elev=lerp(.08,.16+.2*ph,flying), pitch=lerp(.05,W.gp===null?-.5*Math.cos(beat):W.gp*.25,flying);
    W.fp.rotation.set(pitch,sweep,elev); W.hp.rotation.set(pitch*.8,sweep*.97,elev*.9-(1-flying)*.03);
    const narrow=lerp(.42,1,flying); W.fm.scale.z=narrow; W.hm.scale.z=narrow;   // longitudinal fold
    if(W.gp!==null){ const a=.3*flying*flying; W.fm.material.userData.u.uAlpha.value=a; W.hm.material.userData.u.uAlpha.value=a; W.fp.visible=W.hp.visible=a>.01; } });

  // body: hover bob, gaster pumping & curl, head tilt
  body.position.y=(1-ground)*(.04*Math.sin(t*TAU*1.4)+.012*Math.sin(beat*.5));
  body.rotation.z=(1-ground)*.04*Math.sin(t*2.1);
  const pump=Math.sin(t*(perched?3:4.2));
  gSegs.forEach((g,i)=>{ g.scale.y=1+.035*pump*(i/5); g.position.z=[.0,-.28,-.58,-.88,-1.16,-1.42][i]*(1+.015*pump); });
  gaster.rotation.x=.22*(1-ground)+.04*pump;
  sting.position.z=-1.62-.04*Math.max(0,Math.sin(t*.7))*(1-ground);
  head.rotation.x=.5+.45*headDown+.05*Math.sin(t*1.3);
  head.rotation.y=.08*Math.sin(t*.9)*(1-headDown)+.05*Math.sin(t*3)*headDown;

  // mandibles scrape; paint the trail where the jaws meet the wood
  const chew=headDown>.5?Math.max(0,Math.sin(t*11)):0;
  mandibles.forEach(({mg,s})=>{ mg.rotation.y=s*(.08+.28*chew); });
  pulp.scale.setScalar(.001+.055*pulpAmt); pulp.position.set(0,-.2-.02*pulpAmt,.1);
  head.updateMatrixWorld(true); const tip=head.localToWorld(V3(0,-.2,.12));
  if(headDown>.8 && perched) paintScrape(tip, prevTip.lengthSq()?prevTip:tip);
  prevTip.copy(tip);
  topTimer-=dt; if(topDirty&&topTimer<=0){ topT.needsUpdate=true; topDirty=false; topTimer=.15; }

  // antennae
  antennae.forEach(({r,fl,J,s},i)=>{ r.rotation.x=-1.0+.12*Math.sin(t*2.3+i)+.25*headDown-(1-ground)*.15; r.rotation.y=s*(.3+.12*Math.sin(t*1.8+i*2));
    fl.rotation.x=1.1+.15*Math.sin(t*2.7+i*1.4)+.3*headDown; J.forEach((j,k)=>j.rotation.x=j.userData.b+.03*Math.sin(t*3+k*.5+i)); });

  // motes drift
  const mp=motes.geometry.attributes.position; for(let i=0;i<mp.count;i++){ let y=mp.getY(i)+dt*.05; if(y>6) y=-3; mp.setY(i,y); } mp.needsUpdate=true;
  solveLegs();
}

/* =====================================================================
   CAMERA / INPUT
   ===================================================================== */
const cam={dist:6.2,yaw:.9,pitch:.32,tYaw:.9,tPitch:.32,tDist:6.2,auto:0}; let dragging=false;
const camTarget=V3(0,.6,0);
function fitCam(){ const w=innerWidth; camera.fov=w<480?58:w<768?50:42; camera.aspect=innerWidth/innerHeight; camera.updateProjectionMatrix(); if(w<480) cam.tDist=Math.max(cam.tDist,8.5); }
fitCam();
const pts=new Map(); let pinch=0,lx=0,ly=0;
canvas.addEventListener('pointerdown',e=>{ pts.set(e.pointerId,[e.clientX,e.clientY]); canvas.setPointerCapture(e.pointerId); dragging=true; lx=e.clientX; ly=e.clientY; pinch=0; });
canvas.addEventListener('pointermove',e=>{ if(!pts.has(e.pointerId)) return; pts.set(e.pointerId,[e.clientX,e.clientY]);
  if(pts.size===2){ const [a,b]=[...pts.values()], d=Math.hypot(a[0]-b[0],a[1]-b[1]); if(pinch) cam.tDist=clamp(cam.tDist+(pinch-d)*.015,1.8,15); pinch=d; return; }
  cam.tYaw-=(e.clientX-lx)*.006; cam.tPitch=clamp(cam.tPitch+(e.clientY-ly)*.005,.05,1.35); lx=e.clientX; ly=e.clientY; });
const upH=e=>{ pts.delete(e.pointerId); pinch=0; if(!pts.size) dragging=false; else { const [p]=[...pts.values()]; lx=p[0]; ly=p[1]; } };
['pointerup','pointercancel'].forEach(n=>canvas.addEventListener(n,upH));
canvas.addEventListener('wheel',e=>{ e.preventDefault(); cam.tDist=clamp(cam.tDist+e.deltaY*.006,1.8,15); },{passive:false});
addEventListener('resize',()=>{ renderer.setSize(innerWidth,innerHeight); fitCam(); });

const clock=new T.Clock(); let time=0;
function frame(){
  requestAnimationFrame(frame);
  const dt=Math.min(clock.getDelta(),1/30); time+=dt; U_TIME.value=time;
  update(dt,time);
  camTarget.lerp(V3(0,.3,0).lerp(wasp.position,.6),1-Math.exp(-dt*1.6));
  if(!dragging&&!reduceMotion) cam.auto+=dt*.08;
  cam.yaw+=(cam.tYaw-cam.yaw)*.08; cam.pitch+=(cam.tPitch-cam.pitch)*.08; cam.dist+=(cam.tDist-cam.dist)*.08;
  const y=cam.yaw+cam.auto, p=cam.pitch;
  camera.position.set(camTarget.x+Math.sin(y)*Math.cos(p)*cam.dist, camTarget.y+Math.sin(p)*cam.dist, camTarget.z+Math.cos(y)*Math.cos(p)*cam.dist);
  camera.lookAt(camTarget);
  renderer.render(scene,camera);
}
frame();
}
</script>
</body>
</html>
MikeHiggins.me.uk LinkedIn GitHub Bluesky Contra Upwork
© 2026 Mike Higgins. All rights reserved.