• 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

SPIDER 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: Orb-Weaver Spider</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% 45%, #0e1020 0%, #06060d 55%, #000 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); };
const angWrap = a => Math.atan2(Math.sin(a), Math.cos(a));
let seed = 424242;
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(0x05050b, 0.035);
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],[620,60,90,'#ffffff',.5]].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();
})();

/* =====================================================================
   WEB DYNAMICS (shared by the GPU and by JS so the spider and prey ride the same surface)
   z-displacement of the web plane: a breeze sway plus travelling ripples from impacts and plucks
   ===================================================================== */
const U_TIME = { value: 0 };
const RIP = [0,1,2,3].map(()=>new T.Vector4(0,0,-99,0));
const U_RIP = { value: RIP };
let ripIdx=0;
function ripple(x,y,amp){ RIP[ripIdx].set(x,y,U_TIME.value,amp); ripIdx=(ripIdx+1)%4; }
const WEB_R=3.7;
function webDisp(x,y){ const t=U_TIME.value, r=Math.hypot(x,y), env=clamp(1-r/WEB_R,0,1);
  let d=.06*Math.sin(t*.6+x*.35)*Math.sin(t*.45+y*.3)*env*2;
  for(const R of RIP){ const age=t-R.z; if(age<0||age>4) continue; const dist=Math.hypot(x-R.x,y-R.y); if(dist>age*3) continue;
    d+=R.w*Math.sin(dist*7-age*16)*Math.exp(-age*1.6)*Math.exp(-dist*.7)*env; }
  return d; }
const DISP_GLSL = `
uniform float uTime; uniform vec4 uRip[4];
float webDisp(vec2 p){ float r=length(p); float env=clamp(1.0-r/${WEB_R.toFixed(2)},0.0,1.0);
  float d=0.06*sin(uTime*0.6+p.x*0.35)*sin(uTime*0.45+p.y*0.3)*env*2.0;
  for(int i=0;i<4;i++){ vec4 R=uRip[i]; float age=uTime-R.z; if(age<0.0||age>4.0) continue; float dist=length(p-R.xy); if(dist>age*3.0) continue;
    d+=R.w*sin(dist*7.0-age*16.0)*exp(-age*1.6)*exp(-dist*0.7)*env; }
  return d; }
`;
function withWebDisp(m){
  const prev=m.onBeforeCompile;
  m.onBeforeCompile=sh=>{ if(prev) prev(sh); sh.uniforms.uTime=U_TIME; sh.uniforms.uRip=U_RIP;
    sh.vertexShader=DISP_GLSL+sh.vertexShader.replace('#include <project_vertex>',`
      vec4 mvPosition = vec4( transformed, 1.0 );
      #ifdef USE_INSTANCING
        mvPosition = instanceMatrix * mvPosition;
      #endif
      mvPosition.z += webDisp(mvPosition.xy);
      mvPosition = modelViewMatrix * mvPosition;
      gl_Position = projectionMatrix * mvPosition;`); };
  const key=m.customProgramCacheKey?m.customProgramCacheKey():''; m.customProgramCacheKey=()=>key+'web'; return m;
}

/* =====================================================================
   IRIDESCENT MATERIAL (hue drifts with time and viewing angle)
   Data textures: R = brightness, G = hue offset, B = film strength, A = alpha.
   ===================================================================== */
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.35, 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}, uFilm:{value:o.film??.45}, uAlpha:{value:o.alpha??1} };
  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 uFilm; uniform float uAlpha;\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.85);
    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);
  }`);
  };
  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; }
function bumpOf(c){ const o=makeCanvas(c.width,c.height,g=>g.drawImage(c,0,0)); const g=o.getContext('2d'), d=g.getImageData(0,0,o.width,o.height), p=d.data;
  for(let i=0;i<p.length;i+=4){ p[i]=p[i+1]=p[i+2]=p[i]; p[i+3]=255; } g.putImageData(d,0,0); const t=new T.CanvasTexture(o); 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, 32, 24), 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; }
function 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); }

/* =====================================================================
   THE ORB WEB (vertical plane z = 0, hub at the origin)
   ===================================================================== */
const FRAME=[[-3.0,2.8],[.3,3.25],[3.1,2.55],[3.55,-1.0],[1.7,-3.75],[-1.9,-3.65],[-3.6,-.5]];
function frameDist(th){ const dx=Math.cos(th), dy=Math.sin(th); let best=9;
  for(let i=0;i<FRAME.length;i++){ const [ax,ay]=FRAME[i], [bx,by]=FRAME[(i+1)%FRAME.length], ex=bx-ax, ey=by-ay, den=dx*ey-dy*ex; if(Math.abs(den)<1e-6) continue;
    const t=(ax*ey-ay*ex)/den, s=(ax*dy-ay*dx)/den; if(t>0&&s>=0&&s<=1) best=Math.min(best,t); } return best; }
const NR=36, RADII=[]; for(let i=0;i<NR;i++){ const th=i/NR*TAU+rr(-.04,.04); RADII.push({th,len:frameDist(th)}); }
RADII.sort((a,b)=>a.th-b.th);
const HUB_R=.36, FREE_R=.78, TURNS=31;
const segs={radius:[],spiral:[],hub:[],frame:[],anchor:[],stab:[]}, drops=[];
const P2=(r,th)=>V3(Math.cos(th)*r,Math.sin(th)*r,0);
RADII.forEach(R=>segs.radius.push([V3(),P2(R.len,R.th),.0065]));
// sticky capture spiral: follows the frame shape, broken where the spiral would cross the free zone
for(let k=0;k<TURNS;k++) for(let i=0;i<NR;i++){
  const a=RADII[i], b=RADII[(i+1)%NR], s0=(k+i/NR)/TURNS, s1=(k+(i+1)/NR)/TURNS;
  if(s1>1) continue;
  const p=P2(lerp(FREE_R,a.len*.93,s0),a.th), q=P2(lerp(FREE_R,b.len*.93,s1),b.th);
  segs.spiral.push([p,q,.0035]);
  const L=p.distanceTo(q), n=Math.max(1,Math.round(L/.06));
  for(let j=0;j<n;j++){ if(rnd()<.35) continue; const t=(j+rr(.2,.8))/n; drops.push([p.clone().lerp(q,t),rr(.004,.009)]); }
}
// hub: tight, thicker meshwork
for(let k=0;k<7;k++) for(let i=0;i<NR;i++){ const a=RADII[i], b=RADII[(i+1)%NR];
  segs.hub.push([P2(.05+(k+i/NR)*.045,a.th),P2(.05+(k+(i+1)/NR)*.045,b.th),.006]); }
FRAME.forEach((p,i)=>{ const q=FRAME[(i+1)%FRAME.length]; segs.frame.push([V3(p[0],p[1],0),V3(q[0],q[1],0),.011]); });
// stabilimentum: four zigzag bands of bright silk (an X through the hub)
[Math.PI*.25,Math.PI*.75,Math.PI*1.25,Math.PI*1.75].forEach(base=>{ let prev=null;
  const len=rr(1.05,1.5); let side=1; for(let r=.42;r<len;r+=rr(.035,.06)){ side=-side; const th=base+side*rr(.035,.085)*(1-.25*(r-.4))+rr(-.01,.01), p=P2(r,th); if(prev) segs.stab.push([prev,p,rr(.006,.01)]); prev=p; } });
// bigger dew drops scattered on radii
RADII.forEach(R=>{ if(rnd()<.5) drops.push([P2(rr(.9,R.len*.9),R.th),rr(.016,.03)]); });

const CYL=new T.CylinderGeometry(1,1,1,5,1,true).translate(0,.5,0);
function threadMesh(list,mat){ const im=new T.InstancedMesh(CYL,mat,list.length), m4=new T.Matrix4(), d=V3();
  list.forEach(([a,b,r],i)=>{ d.subVectors(b,a); const L=d.length(); _q.setFromUnitVectors(UP,d.normalize()); m4.compose(a,_q,V3(r,L,r)); im.setMatrixAt(i,m4); });
  im.instanceMatrix.needsUpdate=true; im.frustumCulled=false; scene.add(im); return im; }
const silk=withWebDisp(iriMat({hue:.55,light:.42,sat:.6,film:1.2,rough:.25,metal:.45,env:1.4}));
const silkBright=withWebDisp(iriMat({hue:.1,light:.58,sat:.35,film:1,rough:.35,metal:.2}));
threadMesh(segs.radius,silk); threadMesh(segs.spiral,silk); threadMesh(segs.hub,silk); threadMesh(segs.frame,silk); threadMesh(segs.stab,silkBright);
const dropMat=withWebDisp(new T.MeshStandardMaterial({color:0xbfd0e0,roughness:.02,metalness:.2,envMapIntensity:2.6,transparent:true,opacity:.8}));
(function(){ const geo=new T.IcosahedronGeometry(1,1), im=new T.InstancedMesh(geo,dropMat,drops.length), m4=new T.Matrix4();
  drops.forEach(([p,r],i)=>{ m4.compose(p,_q.identity(),V3(r,r,r*.9)); im.setMatrixAt(i,m4); }); im.instanceMatrix.needsUpdate=true; im.frustumCulled=false; scene.add(im); })();

// twigs, grass and anchor lines holding the frame
const bark=(()=>{ const c=makeCanvas(128,512,(g,W,H)=>{ g.fillStyle='#2e2016'; g.fillRect(0,0,W,H); for(let i=0;i<140;i++){ g.strokeStyle=`rgba(${rnd()<.5?'14,8,4':'80,62,44'},.55)`; g.lineWidth=rr(1,3); const x=rnd()*W; g.beginPath(); g.moveTo(x,0); g.lineTo(x+rr(-5,5),H); g.stroke(); }
  for(let i=0;i<50;i++){ g.fillStyle='rgba(150,160,110,.4)'; g.beginPath(); g.arc(rnd()*W,rnd()*H,rr(2,6),0,7); g.fill(); } });
  const t=new T.CanvasTexture(c); t.encoding=T.sRGBEncoding; t.wrapS=t.wrapT=T.RepeatWrapping; t.repeat.set(1,4); return new T.MeshStandardMaterial({map:t,bumpMap:t,bumpScale:.02,roughness:.85}); })();
const twigs=[
  [V3(-9,4.6,-1.2),V3(-5.5,3.8,-.4),V3(-3.4,3.5,.1),V3(-.5,4.3,.2),V3(2.5,4.4,-.2),V3(6,5.2,-1)],
  [V3(8,-6,-.8),V3(5.8,-2.5,-.3),V3(4.4,-.6,.1),V3(4.6,2.5,.1),V3(5,6,-.5)],
  [V3(-8,-7,-1),V3(-5.2,-4.2,-.2),V3(-4.6,-1.2,.05),V3(-5.5,1.5,-.4)],
];
twigs.forEach((pts,i)=>{ const c=new T.CatmullRomCurve3(pts); mesh(new T.TubeGeometry(c,80,.11-i*.015,10,false),bark,scene); });
const leafMat=new T.MeshStandardMaterial({color:lin(0x2e5a24),roughness:.55,side:DS});
[[-2.2,3.65,.1,.4],[1.2,4.4,.1,2.6],[4.5,1.2,.1,-1.2],[-4.8,-2.2,0,2]].forEach(([x,y,z,a])=>{ const g=new T.Group(); g.position.set(x,y,z); g.rotation.set(rr(-.5,.5),a,rr(-.6,.6)); scene.add(g);
  mesh(gridGeo(16,6,(u,v)=>{ const w=.45*Math.sin(Math.PI*u)**.7; return [u*1.4,.08*((v-.5)*2)**2-.15*u*u,(v-.5)*2*w]; }),leafMat,g); });
const ANCH=[[-3.0,2.8,-3.3,3.55],[.3,3.25,.2,4.35],[3.1,2.55,4.45,2.2],[3.55,-1.0,4.42,-.8],[1.7,-3.75,4.8,-3.6],[-1.9,-3.65,-5.0,-3.7],[-3.6,-.5,-4.62,-.9]];
ANCH.forEach(([x0,y0,x1,y1])=>segs.anchor.push([V3(x0,y0,0),V3(x1,y1,0),.011]));
threadMesh(segs.anchor,silk);
(function(){ const N=260, im=new T.InstancedMesh(new T.ConeGeometry(.03,1,4).translate(0,.5,0),new T.MeshStandardMaterial({color:0xffffff,roughness:.7}),N), m4=new T.Matrix4(), c=new T.Color();
  for(let i=0;i<N;i++){ const x=rr(-9,9), z=rr(-5,3); _q.setFromUnitVectors(UP,V3(rr(-.3,.3),1,rr(-.3,.3)).normalize()); m4.compose(V3(x,-7.5,z),_q,V3(1,rr(2.5,5.5),1)); im.setMatrixAt(i,m4); c.set(rnd()<.5?0x1e3a1a:0x2c4a22).convertSRGBToLinear(); im.setColorAt(i,c); }
  scene.add(im); })();
// soft bokeh far behind
(function(){ const N=60,pos=new Float32Array(N*3),col=new Float32Array(N*3); const cs=[[.5,.4,1],[.2,.9,1],[1,.4,.8],[1,.85,.5]];
  for(let i=0;i<N;i++){ pos[i*3]=rr(-30,30); pos[i*3+1]=rr(-14,16); pos[i*3+2]=rr(-40,-18); const c=cs[(rnd()*4)|0]; col.set(c,i*3); }
  const g=new T.BufferGeometry(); g.setAttribute('position',new T.BufferAttribute(pos,3)); g.setAttribute('color',new T.BufferAttribute(col,3));
  const sp=new T.CanvasTexture(makeCanvas(64,64,x=>{ const gr=x.createRadialGradient(32,32,0,32,32,32); gr.addColorStop(0,'rgba(255,255,255,.9)'); gr.addColorStop(.6,'rgba(255,255,255,.25)'); gr.addColorStop(1,'rgba(255,255,255,0)'); x.fillStyle=gr; x.fillRect(0,0,64,64); }));
  scene.add(new T.Points(g,new T.PointsMaterial({size:2.6,map:sp,vertexColors:true,transparent:true,depthWrite:false,blending:T.AdditiveBlending,opacity:.35,fog:false}))); })();

// snap a point in the web plane onto the nearest radial thread
function snapToThread(x,y,out){ const th=Math.atan2(y,x); let best=RADII[0], bd=9; for(const R of RADII){ const d=Math.abs(angWrap(R.th-th)); if(d<bd){ bd=d; best=R; } }
  const r=clamp(Math.hypot(x,y),.08,best.len*.97); out.set(Math.cos(best.th)*r,Math.sin(best.th)*r,0); out.z=webDisp(out.x,out.y); return out; }

/* =====================================================================
   SPIDER PATTERNS
   ===================================================================== */
// abdomen (sphere with poles along the body): dorsal folium + transverse bands, pale ventral marks
const abdC = makeCanvas(512,512,(g,W,H)=>{
  g.fillStyle=D(.45,.0,1); g.fillRect(0,0,W,H);
  // wavy transverse bands wrapping the dorsal half (u≈.75 is the dorsal midline)
  const bands=[[.86,.42],[.14,.0],[.6,.12],[.14,.0],[.86,.42],[.14,.0],[.6,.12],[.14,.0],[.86,.42],[.14,.0],[.6,.12]];
  bands.forEach(([r,gg],k)=>{ const y0=H*(.06+k*.082), th=H*(r<.2?.018:.05);
    g.fillStyle=D(r,gg,1); g.beginPath();
    for(let i=0;i<=64;i++){ const u=i/64, x=u*W, w=Math.sin((u*2+k*.3)*Math.PI*4)*H*.012+Math.cos((u-.75)*Math.PI*2)*H*.02; i?g.lineTo(x,y0+w):g.moveTo(x,y0+w); }
    for(let i=64;i>=0;i--){ const u=i/64, x=u*W, w=Math.sin((u*2+k*.3)*Math.PI*4)*H*.012+Math.cos((u-.75)*Math.PI*2)*H*.02; g.lineTo(x,y0+w+th); }
    g.fill(); });
  // paired dorsal spots and a thin median line
  for(let k=0;k<6;k++){ [-1,1].forEach(s=>{ g.fillStyle=D(.95,.2,.9); g.beginPath(); g.arc(W*(.75+s*(.05-k*.004)),H*(.16+k*.13),6,0,7); g.fill(); }); }
  g.fillStyle=D(.2,.0,.8); g.fillRect(W*.748,H*.05,3,H*.85);
  // dark venter with two pale stripes
  g.fillStyle=D(.12,.0,.6); g.fillRect(W*.12,0,W*.26,H);
  [.2,.3].forEach(u=>{ g.fillStyle=D(.8,.42,.8); g.fillRect(u*W-4,H*.2,8,H*.6); });
  g.globalCompositeOperation='multiply'; for(let i=0;i<5000;i++){ const v=Math.round(rr(190,255)); g.fillStyle=`rgb(${v},255,255)`; g.fillRect(rnd()*W,rnd()*H,2,2); } g.globalCompositeOperation='source-over'; });
const abdT=dataTex(abdC), abdB=bumpOf(abdC);
// legs: annulated bands (bright/dark)
const legC = makeCanvas(64,256,(g,W,H)=>{ g.fillStyle=D(.58,.4,1); g.fillRect(0,0,W,H);
  [[.0,.16],[.4,.56],[.84,1]].forEach(([a,b])=>{ g.fillStyle=D(.14,.0,.8); g.fillRect(0,H*(1-b),W,H*(b-a)); });
  for(let i=0;i<500;i++){ g.fillStyle=D(.3,.0,.8,.4); g.fillRect(rnd()*W,rnd()*H,1.5,1.5); } });
const legT=dataTex(legC);
// carapace: radiating striae from the fovea, pale margin
const carC = makeCanvas(256,256,(g,W,H)=>{ g.fillStyle=D(.3,.1,1); g.fillRect(0,0,W,H);
  for(let k=0;k<16;k++){ const x=(k+.5)/16*W; g.fillStyle=D(.18,.08,.9); g.fillRect(x-2,0,4,H*.6); }
  let gr=g.createLinearGradient(0,H,0,0); gr.addColorStop(0,D(.85,.5,1)); gr.addColorStop(.25,D(.3,.1,1,0)); g.fillStyle=gr; g.fillRect(0,0,W,H); });
const carT=dataTex(carC);

/* =====================================================================
   THE SPIDER (local: +z = head, +y = dorsal, origin at the cephalothorax)
   ===================================================================== */
const spider=new T.Group(); scene.add(spider);
const body=new T.Group(); spider.add(body);
const BODY_H=.32;
const M={
  car:  iriMat({pat:carT,hue:.1,light:.5,rough:.22,metal:.62}),
  abd:  iriMat({pat:abdT,bump:abdB,bumpScale:.003,hue:.55,light:.52,rough:.2,metal:.6}),
  dark: iriMat({hue:.62,light:.2,iri:.8,rough:.3,metal:.55}),
  leg:  iriMat({pat:legT,hue:.0,light:.46,rough:.26,metal:.6}),
  fang: iriMat({hue:.02,light:.25,iri:.8,rough:.15,metal:.7}),
  eye:  new T.MeshPhysicalMaterial({color:lin(0x07050a),roughness:.05,metalness:.3,clearcoat:1,clearcoatRoughness:.02,envMapIntensity:2}),
  gloss:new T.MeshStandardMaterial({color:0xffffff,roughness:.05,envMapIntensity:2}),
  seta: iriMat({hue:.1,light:.3,sat:.4,iri:.5,rough:.5}),
  spine:new T.MeshStandardMaterial({color:lin(0x0e0806),roughness:.4,metalness:.3}),
};
// cephalothorax: carapace with raised head region and fovea, sternum, labium, endites
mesh(SPH, M.car, body, V3(0,.0,0), V3(.36,.19,.44));
mesh(SPH, M.car, body, V3(0,.09,.2), V3(.24,.14,.24));
mesh(SPH_LO, M.dark, body, V3(0,.19,-.06), V3(.03,.01,.06));                     // fovea
mesh(SPH, M.dark, body, V3(0,-.13,-.02), V3(.27,.07,.32));                         // sternum
mesh(SPH, M.dark, body, V3(0,-.11,.32), V3(.08,.05,.06));                          // labium
[-1,1].forEach(s=>mesh(SPH, M.car, body, V3(s*.08,-.1,.36), V3(.06,.05,.07)));    // endites
instanced(body, HAIR, M.seta, Array.from({length:180},()=>{ const d=randDir(); d.y=Math.abs(d.y); return [V3(d.x*.35,d.y*.2,d.z*.42), d.clone().add(V3(0,.4,-.5)), rr(.02,.05), .004]; }));
// eight eyes
[[.075,.22,.43,.05],[-.075,.22,.43,.05],[.17,.18,.38,.032],[-.17,.18,.38,.032],[.06,.26,.36,.035],[-.06,.26,.36,.035],[.19,.21,.3,.03],[-.19,.21,.3,.03]].forEach(([x,y,z,r])=>{
  mesh(SPH, M.eye, body, V3(x,y,z), r); mesh(SPH_LO, M.gloss, body, V3(x*1.05,y+r*.45,z+r*.5), r*.28); });
// chelicerae with fangs
const chel=[];
[-1,1].forEach(s=>{ const g=new T.Group(); g.position.set(s*.075,.02,.44); body.add(g);
  mesh(alongZ(.18,u=>.065*(1-.3*u),12,6), M.car, g).rotation.x=.9;
  const fg=new T.Group(); fg.position.set(0,-.13,.1); g.add(fg);
  const c=new T.QuadraticBezierCurve3(V3(),V3(-s*.03,-.04,.04),V3(-s*.07,-.02,-.02)); mesh(new T.TubeGeometry(c,8,.014,6,false), M.fang, fg);
  instanced(g, HAIR, M.seta, Array.from({length:14},()=>[V3(rr(-.04,.04),rr(-.05,.05),rr(0,.14)),V3(rr(-.3,.3),.2,1),rr(.02,.04),.003]));
  chel.push({g,fg,s}); });
// pedipalps
const palps=[];
[-1,1].forEach(s=>{ const r=new T.Group(); r.position.set(s*.14,-.05,.4); body.add(r); r.rotation.set(.2,s*.5,0);
  let p=r; const J=[]; [.12,.1,.12,.14].forEach((L,k)=>{ const j=new T.Group(); j.rotation.x=[.4,-.5,.3,.2][k]; p.add(j); mesh(alongZ(L,u=>.035*(1-k*.12)*(.85+.15*Math.sin(u*Math.PI)),8,4), k%2?M.leg:M.dark, j); const n=new T.Group(); n.position.z=L; j.add(n); p=n; J.push(j); });
  palps.push({J,s}); });
// pedicel & abdomen with spinnerets
mesh(alongZ(.16,u=>.07,10,3), M.dark, body, V3(0,.04,-.5));
const abdomen=new T.Group(); abdomen.position.set(0,.1,-.52); abdomen.rotation.x=-.25; body.add(abdomen);
const abdGeo=SPH.clone().rotateX(Math.PI/2);
const abdMesh=mesh(abdGeo, M.abd, abdomen, V3(0,.14,-.72), V3(.58,.5,.78));
instanced(abdomen, HAIR, M.seta, Array.from({length:500},()=>{ const d=randDir(); return [V3(d.x*.58,.14+d.y*.5,-.72+d.z*.78), d.clone().add(V3(0,0,-.6)), rr(.02,.045), .0035]; }));
[[0,.0],[-.04,.02],[.04,.02],[-.07,.05],[.07,.05],[0,.06]].forEach(([x,y],i)=>{ const c=mesh(CONE, M.dark, abdomen, V3(x,.0+y,-1.44), V3(.025,.09,.025)); c.rotation.x=-Math.PI/2-.3; });
const SPIN_LOCAL=V3(0,.02,-1.55);

// legs: coxa, trochanter, femur, patella, tibia, metatarsus, tarsus + claws (three-bone IK)
const legs=[];
const LEGDEF=[
  {z:.28, a:.88,b:.98,c:1.02, home:[.95,1.8]},
  {z:.12, a:.8,b:.88,c:.9,   home:[1.5,.7]},
  {z:-.06,a:.5,b:.52,c:.52,  home:[1.05,-.4]},
  {z:-.22,a:.72,b:.78,c:.82, home:[.78,-1.45]},
];
function buildLeg(D,s,li){
  const hip=V3(s*.24,-.02,D.z), tro=V3(s*.36,-.02,D.z*1.05);
  const cg=new T.Group(); body.add(cg); orient(cg,hip,tro,UP); mesh(alongX(hip.distanceTo(tro)+.02,t=>.045*(1-.2*t)+.008,10,4), M.dark, cg);
  const fem=new T.Group(), tib=new T.Group(), met=new T.Group(); body.add(fem,tib,met);
  mesh(alongX(D.a,t=>.036*(1-.25*t)+.006+.006*Math.sin(Math.PI*t),12,8), M.leg, fem);
  mesh(SPH, M.dark, fem, V3(D.a,0,0), V3(.032,.03,.028));                          // patella
  mesh(alongX(D.b,t=>.028*(1-.25*t)+.005,10,8), M.leg, tib);
  mesh(alongX(D.c*.72,t=>.019*(1-.3*t)+.004,8,6), M.leg, met);
  mesh(alongX(D.c*.28,t=>.018*(1-.4*t)+.003,8,4), M.dark, met, V3(D.c*.72,0,0));  // tarsus
  [-1,1,0].forEach(cs=>{ const cl=mesh(alongX(.035,u=>.006*(1-u)+.0008,5,3), M.spine, met, V3(D.c,0,cs*.006)); cl.rotation.set(0,cs*.35,-1.1+(cs===0?.3:0)); });
  // macrosetae (spines) and fine hairs
  const sp=[], hr=[];
  [[fem,D.a,.036],[tib,D.b,.028],[met,D.c*.72,.019]].forEach(([g,L,r],gi)=>{ for(let k=0;k<(gi===2?4:6);k++){ const x=L*(.15+k*.14), a=[.5,1.6,-1.6,2.6][k%4];
    sp.push([g,V3(x,Math.cos(a)*r,Math.sin(a)*r),V3(.9,Math.cos(a),Math.sin(a)),.09,.007]); }
    for(let k=0;k<40;k++){ const x=rnd()*L, a=rnd()*TAU; hr.push([g,V3(x,Math.cos(a)*r,Math.sin(a)*r),V3(.6,Math.cos(a),Math.sin(a)),rr(.025,.05),.0025]); } });
  [fem,tib,met].forEach(g=>{ instanced(g,CONE,M.spine,sp.filter(x=>x[0]===g).map(x=>x.slice(1))); instanced(g,HAIR,M.seta,hr.filter(x=>x[0]===g).map(x=>x.slice(1))); });
  const L={D,s,li,tro,fem,tib,met,home:V3(s*D.home[0],-BODY_H,D.home[1]),toe:V3(),lift:V3(),target:V3(),step:-1,group:((li%2===0)===(s>0))?0:1,override:null};
  legs.push(L); return L;
}
LEGDEF.forEach((D,i)=>[-1,1].forEach(s=>buildLeg(D,s,i)));

/* =====================================================================
   PREY: a moth that blunders into the web, then a silk mummy
   ===================================================================== */
const mothC=makeCanvas(256,128,(g,W,H)=>{ let gr=g.createLinearGradient(0,0,W,0); gr.addColorStop(0,'#5a4a3a'); gr.addColorStop(1,'#8a765a'); g.fillStyle=gr; g.fillRect(0,0,W,H);
  for(let k=0;k<3;k++){ g.strokeStyle='rgba(40,28,18,.8)'; g.lineWidth=3; g.beginPath(); g.moveTo(W*(.3+k*.2),0); g.quadraticCurveTo(W*(.25+k*.2),H*.5,W*(.32+k*.2),H); g.stroke(); }
  g.fillStyle='rgba(30,20,12,.9)'; g.beginPath(); g.arc(W*.62,H*.45,10,0,7); g.fill(); for(let i=0;i<1500;i++){ g.fillStyle=`rgba(${rnd()<.5?'30,22,14':'170,150,120'},.15)`; g.fillRect(rnd()*W,rnd()*H,2,2); } });
const mothT=new T.CanvasTexture(mothC); mothT.encoding=T.sRGBEncoding;
const moth=new T.Group(); scene.add(moth); moth.visible=false;
const mothBody=new T.Group(); moth.add(mothBody);
const fur=new T.MeshStandardMaterial({color:lin(0x7a6650),roughness:.95});
mesh(SPH, fur, mothBody, V3(0,0,.12), V3(.12,.11,.16)); mesh(SPH, fur, mothBody, V3(0,-.01,-.2), V3(.1,.09,.26)); mesh(SPH, fur, mothBody, V3(0,0,.32), V3(.08,.08,.07));
instanced(mothBody, HAIR, new T.MeshStandardMaterial({color:lin(0x9a8466),roughness:1}), Array.from({length:260},()=>{ const d=randDir(); return [V3(d.x*.11,d.y*.1,.05+d.z*.3),d,rr(.03,.06),.006]; }));
[-1,1].forEach(s=>{ const a=new T.Group(); a.position.set(s*.04,.05,.36); a.rotation.set(-.5,s*.5,0); mothBody.add(a); mesh(alongZ(.3,u=>.008*(1-u)+.002,5,3),fur,a);
  instanced(a, HAIR, fur, Array.from({length:24},(v,k)=>[V3(0,0,k/24*.28),V3(s,.3,.4),.04*(1-k/30),.003])); });
const mothWings=[];
[-1,1].forEach(s=>{ [[.6,.42,.05,0],[.45,.3,-.12,1]].forEach(([L,Wd,z,hind])=>{ const p=new T.Group(); p.position.set(s*.08,.05,z); mothBody.add(p);
  const g=gridGeo(10,6,(u,v)=>{ const hw=Wd*Math.sin(Math.PI*Math.min(1,u*1.05+.05))**.5; return [s*u*L, 0, (v-.5)*hw*2-u*(hind?.12:.05)]; });
  const m=mesh(g,new T.MeshStandardMaterial({map:mothT,roughness:.9,side:DS}),p); mothWings.push({p,s,hind}); }); });
const mummyC=makeCanvas(128,256,(g,W,H)=>{ g.fillStyle='#e8e4dc'; g.fillRect(0,0,W,H); for(let i=0;i<90;i++){ g.strokeStyle=`rgba(255,255,255,${rr(.3,.8)})`; g.lineWidth=rr(1,3); const y=rnd()*H; g.beginPath(); g.moveTo(0,y); g.lineTo(W,y+rr(-40,40)); g.stroke(); g.strokeStyle='rgba(150,140,130,.3)'; g.beginPath(); g.moveTo(0,y+3); g.lineTo(W,y+rr(-40,40)); g.stroke(); } });
const mummyT=new T.CanvasTexture(mummyC); mummyT.encoding=T.sRGBEncoding;
const mummyMat=new T.MeshPhysicalMaterial({map:mummyT,roughness:.5,sheen:new T.Color(0xffffff),clearcoat:.3,transparent:true,opacity:1});
const mummy=mesh(SPH.clone().rotateX(Math.PI/2), mummyMat, moth, null, 0.001);
const oldMummy=mesh(SPH.clone().rotateX(Math.PI/2), mummyMat.clone(), scene, null, 0.001); oldMummy.visible=false;
// silk lines drawn while wrapping
const wrapLines=(()=>{ const N=40, g=new T.BufferGeometry(); g.setAttribute('position',new T.BufferAttribute(new Float32Array(N*6),3));
  const l=new T.LineSegments(g,new T.LineBasicMaterial({color:0xeef4ff,transparent:true,opacity:.7})); l.frustumCulled=false; scene.add(l); return {l,g,N}; })();

/* lights */
scene.add(new T.HemisphereLight(0xffffff,0x141020,.5));
const key=new T.DirectionalLight(0xf2f0ff,1.5); key.position.set(-3,7,6); 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; scene.add(key);
const rim=new T.PointLight(0x33ccff,1.8,60); rim.position.set(-6,3,-4); scene.add(rim);
const rim2=new T.PointLight(0xff33aa,1.5,60); rim2.position.set(6,-2,-3); scene.add(rim2);
const glint=new T.PointLight(0xffffff,1.3,40); glint.position.set(2,3,7); scene.add(glint);

/* =====================================================================
   BEHAVIOUR
   hub (head down, plucking) → moth strikes → alert (turn toward the vibration) →
   run along the threads → turn and wrap with hind legs, silk from spinnerets →
   bite → return to the hub → wait for the next moth
   ===================================================================== */
const st={mode:'hub',t:0,dur:rr(3,5)}; const prey={mode:'none',t:0,hit:V3(),p0:V3(),c0:V3(),c1:V3(),wrap:0,spin:0};
const sp={pos:V3(0,-.15,0), head:-Math.PI/2, target:V3(), vel:0};
const _f=V3(),_r=V3(),_n=V3(0,0,1),_t=V3(),_ank=V3(),_d=V3(),_w=V3(),_kn=V3(),_a2=V3(),_toe=V3(),_hw=V3(),_tmp=V3();
function placeSpider(){
  const dz=webDisp(sp.pos.x,sp.pos.y), dx=(webDisp(sp.pos.x+.05,sp.pos.y)-webDisp(sp.pos.x-.05,sp.pos.y))/.1, dy=(webDisp(sp.pos.x,sp.pos.y+.05)-webDisp(sp.pos.x,sp.pos.y-.05))/.1;
  _n.set(-dx,-dy,1).normalize(); _f.set(Math.cos(sp.head),Math.sin(sp.head),0); _f.addScaledVector(_n,-_f.dot(_n)).normalize(); _r.crossVectors(_n,_f);
  _m.makeBasis(_r,_n,_f); spider.quaternion.setFromRotationMatrix(_m); spider.position.set(sp.pos.x,sp.pos.y,dz).addScaledVector(_n,BODY_H);
}
function homeWorld(L,out){ out.copy(L.home); spider.localToWorld(out); return snapToThread(out.x,out.y,out); }
placeSpider(); spider.updateMatrixWorld(true); legs.forEach(L=>homeWorld(L,L.toe));
function solve2(root,target,l1,l2,bend,outKnee,outEnd){
  _d.subVectors(target,root); const c=clamp(_d.length(),Math.abs(l1-l2)+.01,(l1+l2)*.995); _d.normalize();
  _w.copy(bend).addScaledVector(_d,-bend.dot(_d)).normalize();
  const al=Math.acos(clamp((l1*l1+c*c-l2*l2)/(2*l1*c),-1,1));
  outKnee.copy(root).addScaledVector(_d,l1*Math.cos(al)).addScaledVector(_w,l1*Math.sin(al)); outEnd.copy(root).addScaledVector(_d,c); return _w;
}
function turnToward(ang,dt,rate){ const d=angWrap(ang-sp.head); sp.head+=clamp(d,-rate*dt,rate*dt); return Math.abs(d); }
function moveToward(p,dt,speed){ _tmp.subVectors(p,sp.pos); _tmp.z=0; const d=_tmp.length(); if(d>1e-4) sp.pos.addScaledVector(_tmp,Math.min(1,speed*dt/d)); return d; }
let nextMoth=3, pluckT=0, flutter=0, biting=0;

function spawnMoth(){
  const a=rr(0,TAU), r=rr(1.3,2.4); prey.hit.set(Math.cos(a)*r,Math.sin(a)*r*.95-.2,0); snapToThread(prey.hit.x,prey.hit.y,prey.hit); prey.hit.z=0;
  prey.p0.set(prey.hit.x+rr(-4,4),prey.hit.y+rr(1,3),rr(4,6)); prey.c0.copy(prey.p0).add(V3(rr(-2,2),rr(-1,1),-1.5)); prey.c1.copy(prey.hit).add(V3(rr(-1,1),rr(-.5,.8),1.5));
  prey.mode='fly'; prey.t=0; prey.wrap=0; prey.spin=0; moth.visible=true; mummy.scale.setScalar(.001); moth.rotation.set(0,0,0);
}

function update(dt,t){
  st.t+=dt; prey.t+=dt; const go=(m,d)=>{ st.mode=m; st.t=0; st.dur=d; };
  // --- prey
  if(prey.mode==='none'){ nextMoth-=dt; if(nextMoth<=0&&st.mode==='hub'&&!reduceMotion) spawnMoth(); }
  else if(prey.mode==='fly'){ const s=Math.min(1,prey.t/2.2), p=bez(prey.p0,prey.c0,prey.c1,prey.hit,smooth(s)), q=bez(prey.p0,prey.c0,prey.c1,prey.hit,smooth(Math.min(1,s+.02)));
    moth.position.copy(p); if(q.distanceToSquared(p)>1e-8) moth.lookAt(q); flutter=1;
    if(s>=1){ prey.mode='stuck'; prey.t=0; ripple(prey.hit.x,prey.hit.y,.35); if(oldMummy.visible) oldMummy.userData.fade=1; go('alert',.9); } }
  else if(prey.mode==='stuck'||prey.mode==='wrap'||prey.mode==='done'){
    const struggling=prey.mode==='stuck'&&Math.sin(t*1.7)>.2, wz=webDisp(prey.hit.x,prey.hit.y);
    moth.position.set(prey.hit.x,prey.hit.y,wz+.08); moth.quaternion.setFromEuler(new T.Euler(-.2,Math.PI,prey.spin));
    flutter=struggling?1:(prey.mode==='stuck'?.15:0);
    if(struggling&&rnd()<dt*3) ripple(prey.hit.x,prey.hit.y,.06);
    mummy.scale.set(.2*prey.wrap+.001,.18*prey.wrap+.001,.48*prey.wrap+.001); mothBody.scale.setScalar(1-.35*prey.wrap);
  }
  mothWings.forEach(W=>{ const amp=flutter*.9, base=prey.mode==='fly'?.2:(prey.mode==='none'?0:-.15*(1-prey.wrap)-.4*prey.wrap); W.p.rotation.z=W.s*(base+amp*Math.sin(t*(prey.mode==='fly'?40:26)+(W.hind?.5:0))); });
  if(oldMummy.userData.fade){ oldMummy.userData.fade-=dt*.5; oldMummy.material.opacity=Math.max(0,oldMummy.userData.fade); if(oldMummy.userData.fade<=0){ oldMummy.visible=false; oldMummy.userData.fade=0; } }
  if(oldMummy.visible){ const o=oldMummy.userData.at; oldMummy.position.set(o.x,o.y,webDisp(o.x,o.y)+.08); }

  // --- spider
  let speed=0;
  if(st.mode==='hub'){ turnToward(-Math.PI/2,dt,2.5); moveToward(V3(0,-.15,0),dt,.8);
    pluckT-=dt; if(pluckT<=0){ pluckT=rr(2.5,5); legs.find(L=>L.li===0&&L.s===(rnd()<.5?1:-1)).pluck=1; ripple(sp.pos.x,sp.pos.y+.6,.03); } }
  else if(st.mode==='alert'){ const a=Math.atan2(prey.hit.y-sp.pos.y,prey.hit.x-sp.pos.x); turnToward(a,dt,4); if(st.t>=st.dur) go('run',99); }
  else if(st.mode==='run'){ const a=Math.atan2(prey.hit.y-sp.pos.y,prey.hit.x-sp.pos.x); turnToward(a,dt,6);
    _tmp.set(prey.hit.x-Math.cos(a)*.95,prey.hit.y-Math.sin(a)*.95,0); const d=moveToward(_tmp,dt,1.6); speed=1.6;
    if(d<.03){ go('turn',99); prey.mode='wrap'; } }
  else if(st.mode==='turn'){ const a=Math.atan2(sp.pos.y-prey.hit.y,sp.pos.x-prey.hit.x); const left=turnToward(a,dt,3.2);
    _tmp.set(prey.hit.x+Math.cos(a)*1.55,prey.hit.y+Math.sin(a)*1.55,0); moveToward(_tmp,dt,1.2); if(left<.05&&st.t>.4) go('wrap',4.5); }
  else if(st.mode==='wrap'){ prey.wrap=Math.min(1,prey.wrap+dt/4); prey.spin+=dt*3.2; if(rnd()<dt*4) ripple(prey.hit.x,prey.hit.y,.025); if(st.t>=st.dur) go('face',99); }
  else if(st.mode==='face'){ const a=Math.atan2(prey.hit.y-sp.pos.y,prey.hit.x-sp.pos.x); const left=turnToward(a,dt,3.2);
    _tmp.set(prey.hit.x-Math.cos(a)*.95,prey.hit.y-Math.sin(a)*.95,0); moveToward(_tmp,dt,1.2); if(left<.05&&st.t>.4){ go('bite',1.4); prey.mode='done'; } }
  else if(st.mode==='bite'){ biting=1; if(st.t>=st.dur){ biting=0; go('return',99); } }
  else if(st.mode==='return'){ const a=Math.atan2(-.15-sp.pos.y,-sp.pos.x); turnToward(a,dt,5); const d=moveToward(V3(0,-.15,0),dt,1.3); speed=1.3;
    if(d<.03){ go('hub',99); oldMummy.userData.at=prey.hit.clone(); oldMummy.scale.copy(mummy.scale); oldMummy.quaternion.copy(moth.quaternion); oldMummy.visible=true; oldMummy.material.opacity=1; oldMummy.userData.fade=0;
      moth.visible=false; prey.mode='none'; nextMoth=rr(5,8); } }
  placeSpider(); spider.updateMatrixWorld(true);

  // --- legs: feet hold radial threads and step (alternating tetrapods); during the wrap hind legs comb silk onto the prey
  const wrapping=st.mode==='wrap';
  for(const L of legs){
    L.override=null;
    if(wrapping&&L.li===3){ const ph=t*7+(L.s>0?0:Math.PI); const pr=_tmp.set(prey.hit.x,prey.hit.y,webDisp(prey.hit.x,prey.hit.y)+.1);
      L.override=V3(pr.x+Math.cos(ph)*.16*L.s,pr.y+Math.sin(ph)*.16,pr.z+.12+.08*Math.sin(ph*2)); continue; }
    if(L.step>=0){ L.step+=dt/(speed>0?.13:.2); const s=smooth(L.step); L.toe.lerpVectors(L.lift,L.target,s); L.toe.z=webDisp(L.toe.x,L.toe.y)+Math.sin(Math.PI*Math.min(1,L.step))*.25; if(L.step>=1){ L.step=-1; snapToThread(L.toe.x,L.toe.y,L.toe); } }
    else { L.toe.z=webDisp(L.toe.x,L.toe.y); homeWorld(L,_hw); const busy=legs.some(o=>o.step>=0&&o.group!==L.group); const thr=L.li===2?.22:.32;
      if(!busy&&L.toe.distanceTo(_hw)>thr){ L.step=0; L.lift.copy(L.toe); L.target.copy(_hw); } }
  }
  for(const L of legs){ const {a,b,c}=L.D;
    _toe.copy(L.override||L.toe);
    if(L.pluck){ L.pluck=Math.max(0,L.pluck-dt*2); }
    body.worldToLocal(_toe);
    if(L.pluck) _toe.y+=Math.sin(Math.PI*L.pluck)*.12;
    // ankle sits up and back from the foot so the metatarsus comes down onto the thread
    _tmp.set(L.tro.x-_toe.x,0,L.tro.z-_toe.z).normalize().multiplyScalar(.72).add(V3(0,.7,0)).normalize();
    _ank.copy(_toe).addScaledVector(_tmp,c);
    const w=solve2(L.tro,_ank,a,b,V3(L.s*.55,1,0),_kn,_a2);
    orient(L.fem,L.tro,_kn,w); orient(L.tib,_kn,_a2,w); orient(L.met,_a2,_toe,w);
  }

  // --- silk drawn from the spinnerets during the wrap
  const pos=wrapLines.g.attributes.position; const spin=abdomen.localToWorld(SPIN_LOCAL.clone());
  for(let i=0;i<wrapLines.N;i++){ if(wrapping){ const a=t*5+i*.7, pr=moth.position; pos.setXYZ(i*2,spin.x,spin.y,spin.z); pos.setXYZ(i*2+1,pr.x+Math.cos(a)*.18,pr.y+Math.sin(a)*.18*.6,pr.z+Math.sin(a*1.3)*.15); }
    else { pos.setXYZ(i*2,0,0,-99); pos.setXYZ(i*2+1,0,0,-99); } }
  pos.needsUpdate=true; wrapLines.l.material.opacity=wrapping?.55+.2*Math.sin(t*10):0;

  // --- body details
  const breath=1+.02*Math.sin(t*2.1);
  abdMesh.scale.set(.58*breath,.5*breath,.78);
  abdomen.rotation.x=-.25+.03*Math.sin(t*1.3)+(wrapping?.25+.08*Math.sin(t*7):0);
  abdomen.rotation.y=wrapping?.15*Math.sin(t*3.5):0;
  body.position.y=speed?.015*Math.sin(t*22):.005*Math.sin(t*1.2);
  palps.forEach(({J,s})=>J.forEach((j,k)=>{ j.rotation.x=[.4,-.5,.3,.2][k]+Math.sin(t*5.5+s+k)*.15*(st.mode==='alert'?2:1); }));
  chel.forEach(({g,fg,s})=>{ g.rotation.x=.04*Math.sin(t*4+s)+(biting?.25:0); fg.rotation.y=s*(biting?.6*Math.max(0,Math.sin(t*9)):.05); });
}

/* =====================================================================
   CAMERA / INPUT
   ===================================================================== */
const cam={dist:10,yaw:.32,pitch:.1,tYaw:.32,tPitch:.1,tDist:10,auto:0}; let dragging=false;
const camTarget=V3(0,-.2,0);
function fitCam(){ const w=innerWidth; camera.fov=w<480?60:w<768?50:42; camera.aspect=innerWidth/innerHeight; camera.updateProjectionMatrix(); if(w<480) cam.tDist=Math.max(cam.tDist,14); }
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)*.02,2,22); pinch=d; return; }
  cam.tYaw-=(e.clientX-lx)*.006; cam.tPitch=clamp(cam.tPitch+(e.clientY-ly)*.005,-1.2,1.3); 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*.008,2,22); },{passive:false});
addEventListener('resize',()=>{ renderer.setSize(innerWidth,innerHeight); fitCam(); });

const clock=new T.Clock(); let time=0, TS=1;
function frame(){
  requestAnimationFrame(frame);
  const dt=Math.min(clock.getDelta(),1/30)*TS; time+=dt; U_TIME.value=time;
  update(dt,time);
  // drift between the whole web and the spider, swinging gently around the front of the web
  camTarget.lerp(V3(sp.pos.x*.45,sp.pos.y*.45-.2,0),1-Math.exp(-dt*1.2));
  if(!dragging&&!reduceMotion) cam.auto=.55*Math.sin(time*.07);
  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.