• 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

LOCUST SOURCE CODE

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Locust</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% 50%, #120a1d 0%, #07040c 60%, #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;
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 = 9001;
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 FOG = 0x09050f;
const scene = new T.Scene();
scene.fog = new T.FogExp2(FOG, 0.045);
const camera = new T.PerspectiveCamera(42, innerWidth/innerHeight, 0.05, 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).
   Patterned parts read a data texture:
   R = brightness, G = hue offset, B = structural-colour 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??.3, metalness:o.metal??.5,
    side:o.side??T.FrontSide, envMapIntensity:o.env??1.25, transparent:!!o.transparent, depthWrite:o.depthWrite??true });
  m.defines = {};
  if (o.pat){ m.map = o.pat; m.defines.USE_PAT = ''; if (o.cut) m.alphaTest = .5; }
  if (o.bump){ m.bumpMap = o.bump; m.bumpScale = o.bumpScale ?? .003; }
  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} };
  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;\n' + HSL_GLSL +
      sh.fragmentShader.replace('#include <map_fragment>', `
#ifdef USE_PAT
  vec4 patS = texture2D(map, vUv); diffuseColor.a *= patS.a;
#else
  vec4 patS = vec4(0.5263, 0.0, 1.0, 1.0);
#endif`).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)*0.45*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.16, iriS*0.45);
    totalEmissiveRadiance += c * 0.12 * iriS * pow(1.0-ndv, 1.5);
  }`);
  };
  m.customProgramCacheKey = () => 'iri' + (o.pat?'p':'') + (o.bump?'b':'') + (o.cut?'c':'');
  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,wrap){ const t=new T.CanvasTexture(c); t.anisotropy=ANISO; if(wrap){ t.wrapS=t.wrapT=T.RepeatWrapping; } 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 rNoise(g,W,H,n,lo=185){ g.globalCompositeOperation='multiply'; for(let i=0;i<n;i++){ const v=Math.round(rr(lo,255)); g.fillStyle=`rgb(${v},255,255)`; g.fillRect(rnd()*W,rnd()*H,rr(1.5,3.5),rr(1.5,3.5)); } g.globalCompositeOperation='source-over'; }

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),.0006), 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, 28, 20), 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);
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 spikes(parent,list,mat){ const im=new T.InstancedMesh(CONE,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; }
function hairs(parent,n,sampler,mat,l0,l1,rad){ const im=new T.InstancedMesh(HAIR,mat,n), m4=new T.Matrix4();
  for(let i=0;i<n;i++){ const [p,d]=sampler(i); d.normalize(); const len=rr(l0,l1); _q.setFromUnitVectors(UP,d); m4.compose(p.clone().addScaledVector(d,len*.5),_q,V3(rad,len,rad)); im.setMatrixAt(i,m4); }
  im.instanceMatrix.needsUpdate=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
   ===================================================================== */
// pronotum saddle: median carina, three sulci, punctures, darker posterior rim
const pronC = makeCanvas(512,512,(g,W,H)=>{
  g.fillStyle=D(.5,.1,1); g.fillRect(0,0,W,H);
  let gr=g.createLinearGradient(0,0,0,H); gr.addColorStop(0,D(.35,.06,.7)); gr.addColorStop(.2,D(.5,.1,1,0)); gr.addColorStop(.8,D(.5,.1,1,0)); gr.addColorStop(1,D(.35,.06,.7)); g.fillStyle=gr; g.fillRect(0,0,W,H);
  [.32,.5,.68].forEach((s,i)=>{ g.strokeStyle=D(.12,.05,.4); g.lineWidth=i===1?9:6; g.beginPath(); for(let k=0;k<=40;k++){ const v=k/40, x=(s+.03*Math.sin(v*Math.PI))*W; k?g.lineTo(x,v*H):g.moveTo(x,v*H);} g.stroke(); });
  g.fillStyle=D(.88,.18,1); g.fillRect(0,H*.485,W,H*.03);                     // median carina
  [.38,.62].forEach(v=>{ g.fillStyle=D(.7,.14,.9); g.fillRect(W*.05,H*v,W*.6,H*.012); });
  for(let i=0;i<2600;i++){ g.fillStyle=D(rr(.15,.3),.08,.6); g.beginPath(); g.arc(rnd()*W,rnd()*H,rr(1,2.4),0,7); g.fill(); }
  g.fillStyle=D(.18,.04,.5); g.fillRect(W*.965,0,W*.035,H);                    // posterior rim
  rNoise(g,W,H,9000);
});
const pronT=dataTex(pronC), pronB=bumpOf(pronC);

// tegmen: reticulate venation, dark spots in the distal half
const tegC = makeCanvas(1024,256,(g,W,H)=>{
  g.fillStyle=D(.52,.1,.9); g.fillRect(0,0,W,H);
  let gr=g.createLinearGradient(0,0,W,0); gr.addColorStop(0,D(.32,.04,.6)); gr.addColorStop(.25,D(.5,.1,.9,0)); g.fillStyle=gr; g.fillRect(0,0,W,H);
  for(let i=0;i<55;i++){ const x=rr(.3,.97)*W, y=rr(.1,.9)*H, r=rr(6,20); g.fillStyle=D(.13,.02,.35,rr(.6,.95)); g.beginPath(); g.ellipse(x,y,r*1.4,r,rr(0,3),0,7); g.fill(); }
  const X=u=>u*W, Y=v=>(1-v)*H; g.lineCap='round';
  for(let i=0;i<4200;i++){ const x=rnd()*W,y=rnd()*H,l=rr(4,11),a=Math.PI/2+rr(-.6,.6); g.strokeStyle=D(.72,.14,.75,rr(.35,.7)); g.lineWidth=rr(.7,1.3); g.beginPath(); g.moveTo(x,y); g.lineTo(x+Math.cos(a)*l,y+Math.sin(a)*l); g.stroke(); }
  const N=10; for(let k=0;k<N;k++){ const q=k/(N-1), v0=.45, v1=lerp(.08,.95,q), u1=q>.85?lerp(.6,.95,(q-.85)/.15):.99;
    for(const [c,w] of [[D(.15,.04,.4),4],[D(.85,.16,.85),2.2]]){ g.strokeStyle=c; g.lineWidth=w; g.beginPath(); g.moveTo(X(0),Y(v0)); g.bezierCurveTo(X(.2),Y(lerp(v0,v1,.7)),X(.6),Y(v1),X(u1),Y(v1*.9+.05)); g.stroke(); } }
  g.fillStyle=D(.85,.2,.7); for(let i=0;i<500;i++){ g.fillRect(rnd()*W*.7,H*rr(.0,.12),2,2); }    // dense costal field
  g.fillStyle=D(.12,.04,.35); g.fillRect(0,0,W,4); g.fillRect(0,H-4,W,4);
  rNoise(g,W,H,12000,200);
});
const tegT=dataTex(tegC), tegB=bumpOf(tegC);

// hindwing fan membrane: translucent, radial veins, smoky border (alpha < 1)
const hindC = makeCanvas(512,512,(g,W,H)=>{
  g.clearRect(0,0,W,H); let gr=g.createLinearGradient(0,H,0,0); gr.addColorStop(0,D(.62,.55,1,.5)); gr.addColorStop(.75,D(.66,.6,1,.38)); gr.addColorStop(1,D(.3,.6,.6,.7)); g.fillStyle=gr; g.fillRect(0,0,W,H);
  const n=24; for(let k=0;k<=n;k++){ const x=k/n*W; g.fillStyle=D(.85,.5,.9,.95); g.fillRect(x-2,0,4,H); }
  for(let i=0;i<1800;i++){ const x=rnd()*W, y=rnd()*H; g.fillStyle=D(.8,.5,.9,.8); g.fillRect(x,y,W/24*.9,1.5); }
  g.fillStyle=D(.2,.5,.5,.85); g.fillRect(0,0,W,10);
});
const hindT=dataTex(hindC);

// hind femur: herringbone (chevron) muscle pattern, carinae, dark knee with pale lunule
const femC = makeCanvas(512,512,(g,W,H)=>{
  g.fillStyle=D(.5,.62,1); g.fillRect(0,0,W,H);
  for(let k=0;k<16;k++){ const y=H*(1-lerp(.08,.86,k/15));
    [.25,.75].forEach(c=>{ for(const [col,w,off] of [[D(.18,.58,.5),6,4],[D(.85,.66,1),3,0]]){ g.strokeStyle=col; g.lineWidth=w; g.beginPath(); g.moveTo((c-.22)*W,y-24+off); g.lineTo(c*W,y+off); g.lineTo((c+.22)*W,y-24+off); g.stroke(); } }); }
  [0,.25,.5,.75,1].forEach(u=>{ g.fillStyle=D(.15,.55,.6); g.fillRect(u*W-4,0,8,H); });
  for(let k=0;k<3;k++){ g.fillStyle=D(.2,.55,.6,.5); g.fillRect(0,H*(.25+k*.18),W,10); }   // faint transverse bands
  g.fillStyle=D(.1,.5,.4); g.fillRect(0,0,W,H*.08);                                         // dark knee
  [.25,.75].forEach(c=>{ g.fillStyle=D(.92,.85,1); g.beginPath(); g.ellipse(c*W,H*.045,W*.08,H*.025,0,0,7); g.fill(); });
  rNoise(g,W,H,9000);
});
const femT=dataTex(femC), femB=bumpOf(femC);

// abdominal tergites/sternites: posterior dark band, pale lateral spot
function plateC(bright,hue){ return makeCanvas(256,128,(g,W,H)=>{
  g.fillStyle=D(bright,hue,1); g.fillRect(0,0,W,H);
  let gr=g.createLinearGradient(0,0,0,H); gr.addColorStop(0,D(bright,hue,1,0)); gr.addColorStop(.7,D(bright,hue,1,0)); gr.addColorStop(.88,D(.16,hue,.5)); gr.addColorStop(1,D(.75,hue+.05,.8)); g.fillStyle=gr; g.fillRect(0,0,W,H);
  [.12,.88].forEach(u=>{ g.fillStyle=D(.85,hue+.08,.7,.8); g.beginPath(); g.ellipse(u*W,H*.4,W*.05,H*.18,0,0,7); g.fill(); });
  g.fillStyle=D(.75,hue,1); g.fillRect(W*.495,0,W*.01,H);
  rNoise(g,W,H,2500); }); }
const tergC=plateC(.5,.3), sternC=plateC(.62,.38);
const tergT=dataTex(tergC), sternT=dataTex(sternC), tergB=bumpOf(tergC);

// striped compound eye
const eyeC = makeCanvas(256,256,(g,W,H)=>{ g.fillStyle=D(.16,.6,1); g.fillRect(0,0,W,H);
  for(let i=0;i<9;i++){ g.fillStyle=D(.42,.65,1); g.fillRect(0,H*(i/9),W,H/18); }
  const r=3.2; 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='rgba(255,255,255,.18)'; g.beginPath(); g.arc(x,y,r*.6,0,7); g.fill(); } });
const eyeT=dataTex(eyeC), eyeB=bumpOf(eyeC);

/* =====================================================================
   THE LOCUST
   ===================================================================== */
const root = new T.Group(); scene.add(root);     // ground frame (stays at origin)
const body = new T.Group(); root.add(body);      // body pose
const BODY_Y = .78;
body.position.y = BODY_Y;

const M = {
  thor: iriMat({hue:.22,light:.46,iri:.9,rough:.3,metal:.55}),
  thorD: iriMat({hue:.18,light:.26,iri:.6,rough:.45}),
  pron: iriMat({pat:pronT,bump:pronB,bumpScale:.005,hue:.08,light:.52,rough:.24,metal:.6,side:DS}),
  head: iriMat({hue:.0,light:.48,iri:.9,rough:.26,metal:.55}),
  face: iriMat({hue:.92,light:.52,iri:.8,rough:.3}),
  eye:  iriMat({pat:eyeT,bump:eyeB,bumpScale:.002,hue:.0,light:.32,rough:.08,metal:.7,env:1.8}),
  mand: iriMat({hue:.8,light:.2,iri:.5,rough:.25,metal:.7}),
  palp: iriMat({hue:.9,light:.5,iri:.8,rough:.35}),
  terg: iriMat({pat:tergT,bump:tergB,hue:0,light:.52,rough:.28,metal:.6,side:DS}),
  stern:iriMat({pat:sternT,hue:0,light:.55,rough:.34,side:DS}),
  memb: iriMat({hue:.2,light:.16,iri:.4,rough:.6,metal:.2}),
  tymp: iriMat({hue:.55,light:.62,iri:1,rough:.08,metal:.8,env:2}),
  teg:  iriMat({pat:tegT,bump:tegB,bumpScale:.003,hue:.14,light:.52,rough:.24,metal:.55,side:DS}),
  hind: iriMat({pat:hindT,hue:.86,light:.6,rough:.12,metal:.5,side:DS,transparent:true,depthWrite:false,env:1.6}),
  fem:  iriMat({pat:femT,bump:femB,bumpScale:.006,hue:0,light:.5,rough:.24,metal:.62}),
  tib:  iriMat({hue:.7,light:.5,iri:.9,rough:.26,metal:.6}),
  legD: iriMat({hue:.64,light:.3,iri:.6,rough:.42}),
  spine: new T.MeshStandardMaterial({color:lin(0x1a0f0c),roughness:.5,metalness:.2}),
  claw:  new T.MeshStandardMaterial({color:lin(0x0e0805),roughness:.35,metalness:.4}),
  pad:  iriMat({hue:.95,light:.7,iri:.6,rough:.35}),
  fuzz: iriMat({hue:.3,light:.55,sat:.5,iri:.4,rough:.7,metal:.05}),
};

/* ---- thorax & pronotum saddle ---- */
mesh(SPH, M.thor, body, V3(0,.02,.62), V3(.38,.38,.6));
mesh(SPH, M.thorD, body, V3(0,.06,.98), V3(.31,.31,.46));   // prothorax inside the saddle
mesh(SPH, M.thorD, body, V3(0,-.2,.6), V3(.34,.16,.5));                       // sternum
[-1,1].forEach(s=>{ mesh(SPH_LO, M.thorD, body, V3(s*.1,-.33,.78), V3(.07,.04,.1)); mesh(SPH_LO, M.thorD, body, V3(s*.12,-.33,.42), V3(.08,.04,.11)); });   // sternal lobes
hairs(body, 300, ()=>{ const d=randDir(); d.y=-Math.abs(d.y); return [V3(d.x*.34,-.2+d.y*.16,.6+d.z*.5), V3(d.x,-1,d.z*.3)]; }, M.fuzz, .03,.07,.005);
const pronotum = (()=>{
  const A=1.85;
  const g = gridGeo(40,48,(s,v)=>{
    const a=lerp(-A,A,v), ca=Math.cos(a), sa=Math.sin(a);
    const zf=.4-.06*Math.max(0,ca), zb=-.52-.2*Math.max(0,ca)**3, z=lerp(zf,zb,s);
    const rx=.35+.03*Math.sin(s*Math.PI)+.04*s, ry=.39;
    const x=rx*Math.sign(sa)*Math.abs(sa)**.72, y=ry*Math.sign(ca)*Math.abs(ca)**.45 + .03*Math.exp(-(a*a)/.01);
    return [x, y-.1*(1-Math.abs(ca)), z];
  });
  const m = mesh(g, M.pron, body, V3(0,.12,.92)); m.rotation.x=-.04; return m;
})();
[-1,1].forEach(s=>mesh(SPH_LO, M.thorD, body, V3(s*.43,-.12,.62), V3(.025,.018,.04)));   // thoracic spiracles

/* ---- abdomen ---- */
const abdomen = new T.Group(); abdomen.position.set(0,.0,.24); body.add(abdomen);
const segs=[];
function shellGeo(rx0,ry0,rx1,ry1,len,a0,a1){ return gridGeo(6,26,(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 N=10, step=.205;
  for(let i=0;i<N;i++){
    const t=i/(N-1), w=.36*(1-t*.5), hT=.3*(1-t*.42), hB=.26*(1-t*.4), y=-.02-t*.06;
    const g=new T.Group(); g.position.set(0,y,-i*step); abdomen.add(g); segs.push(g);
    mesh(shellGeo(w,hT,w*1.03,hT*1.02,.26,-1.75,1.75), M.terg, g);
    mesh(shellGeo(w*.97,hB,w*1.0,hB*1.02,.25,Math.PI-1.5,Math.PI+1.5), M.stern, g);
    mesh(SPH_LO, M.memb, g, V3(0,-.01,-.14), V3(w*.97,Math.min(hT,hB)*.95,.15));
    if(i>0&&i<8) [-1,1].forEach(s=>mesh(SPH_LO, M.spine, g, V3(s*w*.99,-.06,-.12), V3(.014,.018,.03)));
    if(i===0) [-1,1].forEach(s=>{ const ty=mesh(SPH, M.tymp, g, V3(s*w*.93,.02,-.13), V3(.03,.09,.1)); });   // tympanal organ
  }
  const end=new T.Group(); end.position.set(0,-.1,-N*step+.02); abdomen.add(end);
  // ovipositor valves (dorsal pair curve up, ventral pair curve down)
  [[1,.06],[-1,-.04]].forEach(([dir,y])=>[-1,1].forEach(s=>{
    const c=new T.CatmullRomCurve3([V3(s*.04,y,0),V3(s*.05,y+dir*.01,-.12),V3(s*.04,y+dir*.06,-.22)]);
    mesh(new T.TubeGeometry(c,10,.022,6,false), M.legD, end);
    mesh(CONE, M.claw, end, c.getPoint(1), V3(.018,.05,.018)).quaternion.setFromUnitVectors(UP, c.getTangent(1));
  }));
  [-1,1].forEach(s=>mesh(alongZ(.12,u=>.025*(1-u)+.003,8,4), M.tib, end, V3(s*.09,.1,.02)).rotation.set(-.4,s*.5+Math.PI,0));   // cerci
  mesh(SPH, M.terg, end, V3(0,.11,.02), V3(.11,.05,.12));                                        // supra-anal plate
}

/* ---- head ---- */
const head = new T.Group(); head.position.set(0,.14,1.4); head.rotation.x=.12; body.add(head);
mesh(SPH, M.head, head, null, V3(.28,.38,.27));
mesh(SPH, M.face, head, V3(0,-.03,.17), V3(.2,.3,.12));                     // frons
mesh(new T.CylinderGeometry(.012,.012,.36,6), M.head, head, V3(0,-.03,.27)).rotation.x=.1;   // frontal costa
mesh(SPH, M.face, head, V3(0,-.26,.2), V3(.14,.08,.08));                    // clypeus
const labrum = mesh(SPH, M.palp, head, V3(0,-.34,.21), V3(.11,.07,.06));
mesh(new T.ConeGeometry(.1,.2,4), M.head, head, V3(0,.34,.15)).rotation.x=1.3;   // fastigium
[-1,1].forEach(s=>{
  const eg=SPH.clone(); const e=mesh(eg, M.eye, head, V3(s*.22,.13,.04), V3(.09,.19,.13)); e.rotation.z=-s*.12;
  mesh(SPH_LO, new T.MeshStandardMaterial({color:0xffffff,roughness:.05,metalness:.2,envMapIntensity:2}), head, V3(s*.29,.22,.1), .02);
  mesh(new T.TorusGeometry(.045,.014,6,14), M.head, head, V3(s*.1,.18,.22)).rotation.y=s*.25;
});
[[0,.08,.29],[-.08,.24,.2],[.08,.24,.2]].forEach(p=>mesh(SPH_LO, new T.MeshStandardMaterial({color:lin(0xffe0a0),emissive:lin(0x553311),roughness:.15,metalness:.3}), head, V3(...p), V3(.022,.022,.012)));
hairs(head, 120, ()=>{ const d=randDir(); d.z=Math.abs(d.z); return [V3(d.x*.18,-.15+d.y*.15,.2+d.z*.05), V3(d.x,-.4,1)]; }, M.fuzz, .02,.05,.004);
const mandibles=[], palps=[];
[-1,1].forEach(s=>{
  const mg=new T.Group(); mg.position.set(s*.1,-.33,.14); head.add(mg);
  const mm=mesh(SPH, M.mand, mg, V3(-s*.02,-.03,0), V3(.08,.09,.06));
  spikes(mg,[0,1,2].map(k=>[V3(-s*(.06+k*.012),-.06-k*.01,.02),V3(-s,-.4,.3),.04,.012]),M.claw);
  mandibles.push({mg,s});
  [[V3(s*.15,-.3,.15),[.08,.075,.07,.06,.055],.026,V3(s*.35,-1,.55)],[V3(s*.06,-.4,.12),[.06,.055,.05],.02,V3(s*.2,-1,.4)]].forEach(([base,lens,r0,dir],pi)=>{
    const rootP=new T.Group(); rootP.position.copy(base); rootP.quaternion.setFromUnitVectors(V3(0,0,1),dir.normalize()); head.add(rootP);
    let parent=rootP; const joints=[];
    lens.forEach((L,k)=>{ const j=new T.Group(); j.userData.b=[0,.4,-.45,.3,.2][k]; j.rotation.x=j.userData.b; parent.add(j);
      mesh(alongZ(L,u=>r0*(1-k*.1)*(.82+.18*Math.sin(u*Math.PI)),8,5), M.palp, j);
      const nx=new T.Group(); nx.position.z=L; j.add(nx); parent=nx; joints.push(j); });
    mesh(SPH_LO, M.pad, parent, null, r0*.7);
    palps.push({joints,s,pi});
  });
});
// antennae: filiform, ~26 beaded flagellomeres
const antennae=[];
const mAnt=[0,1,2,3,4].map(k=>iriMat({hue:.04+k*.11,light:k%2?.56:.44,iri:.8,rough:.4}));
[-1,1].forEach(s=>{
  const r=new T.Group(); r.position.set(s*.1,.18,.24); head.add(r);
  r.quaternion.setFromUnitVectors(V3(0,0,1), V3(s*.35,.5,1).normalize());
  const joints=[]; let parent=r; const N=28;
  for(let i=0;i<N;i++){ const t=i/(N-1); const L=i===0?.09:i===1?.06:lerp(.07,.045,t), R=i===0?.045:i===1?.036:lerp(.03,.009,t);
    const j=new T.Group(); j.userData.bx=i<2?-.05:-.035; j.userData.by=s*.012; j.rotation.set(j.userData.bx,j.userData.by,0); parent.add(j);
    mesh(alongZ(L,u=>R*(.86+.14*Math.sin(u*Math.PI)),8,3), mAnt[Math.min(4,(t*5)|0)], j);
    const nx=new T.Group(); nx.position.z=L; j.add(nx); parent=nx; joints.push(j); }
  antennae.push({joints,s});
});

/* ---- wings ---- */
const TEG={L:3.2,W:.64};
const tegGeo = gridGeo(48,10,(u,v)=>{ const env=u<.12?Math.sin(u/.12*Math.PI/2)**.8:1, tip=u>.84?Math.sqrt(Math.max(0,1-((u-.84)/.16)**2)):1;
  const hw=.5*TEG.W*Math.max(.04,env*tip), cen=.5*TEG.W; const x=cen-hw+2*hw*v; return [x, .015*Math.sin(Math.PI*v)-.04*u*u, -u*TEG.L]; });
const tegs=[], hinds=[];
// hindwing fan: rebuilt each frame from its fold state
const HW={N:24,R:8,len:2.7};
function makeFan(){ const g=gridGeo(HW.N,HW.R,()=>[0,0,0]); g.attributes.position.setUsage(T.DynamicDrawUsage); return g; }
function updateFan(g,open,side){
  const p=g.attributes.position; let idx=0;
  for(let i=0;i<=HW.N;i++){ const k=i/HW.N, phi=(.05+1.55*k)*open+.02*k, R=HW.len*(.78+.22*Math.sin(Math.PI*(.25+.75*k)))*(k>.92?1-(k-.92)*2:1);
    for(let j=0;j<=HW.R;j++){ const r=j/HW.R*R; const pleat=(i%2?1:-1)*.05*(1-open*.85)*(j/HW.R);
      p.setXYZ(idx++, side*Math.sin(phi)*r, pleat, -Math.cos(phi)*r); } }
  p.needsUpdate=true; g.computeVertexNormals();
}
[-1,1].forEach(s=>{
  // tegmen: flap (body-axis beat) > yaw (spread) > roll (roof at rest)
  const flap=new T.Group(); flap.position.set(s*.06,.5,.72); body.add(flap);
  const yaw=new T.Group(); flap.add(yaw); const roll=new T.Group(); yaw.add(roll);
  const tm=mesh(tegGeo, M.teg, roll); tm.scale.x=s;
  tegs.push({flap,yaw,roll,s});
  const hf=new T.Group(); hf.position.set(s*.08,.46,.5); body.add(hf);
  const hr=new T.Group(); hf.add(hr); const fg=makeFan(); const fm=mesh(fg, M.hind, hr); fm.castShadow=false; fm.renderOrder=2;
  hinds.push({flap:hf,roll:hr,geo:fg,s,mesh:fm});
});

/* ---- legs (two-bone IK) ---- */
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)+.04,t=>D.cr*(1-.35*t)+.02,10,6), M.legD, cg).scale.y=.75;
  mesh(SPH_LO, M.tib, body, tro, D.cr*.75);
  const fem=new T.Group(), tib=new T.Group(), tar=new T.Group(); body.add(fem,tib,tar);
  if(D.hind){
    mesh(alongX(D.a,t=>.26*Math.pow(Math.sin(Math.PI*(.04+.9*t)),.6)*(1-.62*t)+.07,20,22), M.fem, fem).scale.z=.55;
    mesh(SPH, M.legD, fem, V3(D.a,0,0), V3(.11,.1,.08));
    [-1,1].forEach(cs=>mesh(SPH_LO, M.fem, fem, V3(D.a-.03,-.01,cs*.06), V3(.07,.06,.035)));      // genicular lobes
    hairs(fem,60,()=>{ const x=rnd()*D.a*.9; return [V3(x,.2*(1-x/D.a)+.05,rr(-.05,.05)), V3(.6,1,rr(-.3,.3))]; }, M.fuzz,.03,.06,.004);
    mesh(alongX(D.b,t=>.065*(1-.4*t)+.01,10,12), M.tib, tib);
    const sp=[]; for(let k=0;k<11;k++){ const x=D.b*(.15+.075*k); [-1,1].forEach(cs=>sp.push([V3(x,-.05,cs*.025),V3(.5,-1,cs*.35),.085,.012])); }
    [-1,1].forEach(cs=>sp.push([V3(D.b*.97,-.02,cs*.03),V3(1,-.3,cs*.5),.13,.016]));
    spikes(tib,sp,M.spine);
    let x=0; [.42,.22,.36].forEach((f,k)=>{ const L=D.tl*f; mesh(alongX(L,u=>.035*(1-k*.12)*(.8+.2*u),8,4), k===1?M.legD:M.tib, tar, V3(x,0,0)); mesh(SPH_LO,M.pad,tar,V3(x+L*.5,-.03,0),V3(L*.45,.018,.03)); x+=L; });
    [-1,1].forEach(cs=>{ const c=mesh(alongX(.07,u=>.012*(1-u)+.001,6,3),M.claw,tar,V3(x,0,cs*.012)); c.rotation.set(0,cs*.35,-.9); });
    mesh(SPH_LO, M.pad, tar, V3(x+.02,-.015,0), V3(.025,.015,.022));
  } else {
    mesh(alongX(D.a,t=>.06*Math.pow(Math.sin(Math.PI*(.06+.9*t)),.5)*(1-.3*t)+.016,12,12), M.tib, fem).scale.z=.8;
    [.35,.62,.86].forEach(t=>mesh(alongX(D.a*.035,()=>.063*(1-.3*t)+.017,12,1), M.legD, fem, V3(D.a*t,0,0)));
    mesh(SPH_LO, M.legD, fem, V3(D.a,0,0), .05);
    mesh(alongX(D.b,t=>.035*(1-.35*t)+.006,10,10), M.thor, tib);
    const sp=[]; for(let k=0;k<7;k++) [-1,1].forEach(cs=>sp.push([V3(D.b*(.18+.11*k),-.03,cs*.015),V3(.6,-1,cs*.3),.055,.009]));
    [-1,1].forEach(cs=>sp.push([V3(D.b*.97,-.01,cs*.02),V3(1,-.4,cs*.5),.07,.01])); spikes(tib,sp,M.spine);
    let x=0; [.4,.22,.38].forEach((f,k)=>{ const L=D.tl*f; mesh(alongX(L,u=>.026*(1-k*.12)*(.8+.2*u),8,4), k===1?M.legD:M.thor, tar, V3(x,0,0)); mesh(SPH_LO,M.pad,tar,V3(x+L*.5,-.022,0),V3(L*.45,.014,.022)); x+=L; });
    [-1,1].forEach(cs=>{ const c=mesh(alongX(.05,u=>.009*(1-u)+.001,6,3),M.claw,tar,V3(x,0,cs*.01)); c.rotation.set(0,cs*.35,-.9); });
    mesh(SPH_LO, M.pad, tar, V3(x+.015,-.012,0), V3(.02,.012,.018));
  }
  const L={D,s,tro,fem,tib,tar,home:V3(s*D.home[0],0,D.home[1]),toe:V3(s*D.home[0],0,D.home[1]),lift:V3(),target:V3(),swinging:false,air:0,step:0,stepping:false};
  L.toe.copy(L.home); legs.push(L); return L;
}
const LEGDEF=[
  {hip:[.18,-.24,1.02],tro:[.3,-.34,1.12],a:.56,b:.62,tl:.3,cr:.07,home:[.95,1.9],phase:0,bend:[.4,1,0],airT:[.28,-.2,.32]},
  {hip:[.24,-.26,.58],tro:[.4,-.36,.52],a:.62,b:.72,tl:.34,cr:.08,home:[1.25,.62],phase:.5,bend:[.4,1,0],airT:[.36,-.24,-.1]},
  {hip:[.26,-.12,.16],tro:[.4,-.16,.1],a:1.34,b:1.4,tl:.46,cr:.11,home:[.74,-.5],hind:true,bend:[.2,.16,-1],airT:[.3,-.38,-2.45]},
];
LEGDEF.forEach((D,i)=>[-1,1].forEach(s=>{ const L=buildLeg(D,s); L.phase=i<2?((s<0)===(i===0)?0:.5):0; }));

/* =====================================================================
   GROUND: sandy soil with pebbles and dry grass (scrolls under the insect)
   ===================================================================== */
const TILE=8, REP=9;
const groundC = makeCanvas(1024,1024,(g,W,H)=>{
  g.fillStyle='#2b241d'; g.fillRect(0,0,W,H);
  for(let i=0;i<70;i++){ const x=rnd()*W,y=rnd()*H,r=rr(40,200),gr=g.createRadialGradient(x,y,0,x,y,r); gr.addColorStop(0,`rgba(${rnd()<.5?'12,9,6':'70,58,44'},${rr(.15,.3)})`); gr.addColorStop(1,'rgba(0,0,0,0)'); g.fillStyle=gr; g.fillRect(0,0,W,H); }
  const cols=['#4a3d2e','#1a1510','#5e4f3c','#382e23','#6b5a44','#241d16'];
  for(let i=0;i<60000;i++){ g.fillStyle=cols[(rnd()*cols.length)|0]; g.fillRect(rnd()*W,rnd()*H,rr(.8,2.2),rr(.8,2.2)); }
  for(let i=0;i<30;i++){ g.strokeStyle='rgba(10,7,5,.5)'; g.lineWidth=rr(1,2.5); let x=rnd()*W,y=rnd()*H; g.beginPath(); g.moveTo(x,y); for(let k=0;k<8;k++){ x+=rr(-30,30); y+=rr(-30,30); g.lineTo(x,y);} g.stroke(); }
});
const gT=new T.CanvasTexture(groundC); gT.encoding=T.sRGBEncoding; gT.wrapS=gT.wrapT=T.RepeatWrapping; gT.repeat.set(REP,REP); gT.anisotropy=ANISO;
const gB=new T.CanvasTexture(groundC); gB.wrapS=gB.wrapT=T.RepeatWrapping; gB.repeat.set(REP,REP);
const groundPivot=new T.Group(); scene.add(groundPivot);
const ground=new T.Mesh(new T.PlaneGeometry(TILE*REP,TILE*REP), new T.MeshStandardMaterial({map:gT,bumpMap:gB,bumpScale:.03,roughness:.95,metalness:0,color:0xb0a090}));
ground.rotation.x=-Math.PI/2; ground.receiveShadow=true; groundPivot.add(ground);
(function(){ // per-tile props, repeated on a grid so wrapping is seamless
  const pebbles=[], blades=[];
  for(let i=0;i<34;i++) pebbles.push([rr(0,TILE),rr(0,TILE),rr(.03,.14),rr(0,6.3)]);
  for(let i=0;i<5;i++){ const cx=rr(0,TILE), cz=rr(0,TILE); if(Math.hypot(cx-TILE/2,cz-TILE/2)<0) continue; for(let k=0;k<14;k++) blades.push([cx+rr(-.15,.15),cz+rr(-.15,.15),rr(.3,.85),randDir(),rnd()]); }
  const half=Math.floor(7/2), m4=new T.Matrix4(), col=new T.Color();
  const pm=new T.InstancedMesh(new T.IcosahedronGeometry(1,1), new T.MeshStandardMaterial({color:0xffffff,roughness:.85}), pebbles.length*49);
  const bm=new T.InstancedMesh(new T.ConeGeometry(.018,1,4).translate(0,.5,0), new T.MeshStandardMaterial({color:0xffffff,roughness:.8,side:DS}), blades.length*49);
  let pi=0, bi=0;
  for(let tx=-half;tx<=half;tx++) for(let tz=-half;tz<=half;tz++){
    pebbles.forEach(([x,z,r,a])=>{ _q.setFromAxisAngle(randDir(),a); m4.compose(V3(tx*TILE+x-TILE/2,r*.35,tz*TILE+z-TILE/2),_q,V3(r*rr(.9,1.4),r*.6,r)); pm.setMatrixAt(pi,m4); col.set(rnd()<.5?0x3d3429:0x5a4c3c).convertSRGBToLinear(); pm.setColorAt(pi++,col); });
    blades.forEach(([x,z,h,d,c])=>{ const dir=V3(d.x*.35,1,d.z*.35).normalize(); _q.setFromUnitVectors(UP,dir); m4.compose(V3(tx*TILE+x-TILE/2,0,tz*TILE+z-TILE/2),_q,V3(1,h,1)); bm.setMatrixAt(bi,m4); col.set(0x3f3520).lerp(new T.Color(0x6a5a36),c).convertSRGBToLinear(); bm.setColorAt(bi++,col); });
  }
  pm.castShadow=pm.receiveShadow=bm.castShadow=true; groundPivot.add(pm,bm);
})();

/* lights */
scene.add(new T.HemisphereLight(0xbfd8ff,0x1a1030,.5));
const key=new T.DirectionalLight(0xffffff,1.25); 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=4;
scene.add(key);
const rim=new T.PointLight(0x33ccff,2.2,70); rim.position.set(-6,3,-4); scene.add(rim);
const rim2=new T.PointLight(0xff33aa,1.8,70); rim2.position.set(6,1,-3); scene.add(rim2);
const glint=new T.PointLight(0xffffff,1.0,45); glint.position.set(2,4,8); scene.add(glint);

/* =====================================================================
   BEHAVIOUR: walk / pause / crouch → kick → glide-flight → land
   ===================================================================== */
let mode='walk', modeT=3, speed=0, tSpeed=.6, curv=0, tCurv=0, heading=0, gphase=0;
const wpos={x:0,z:0};
let bodyY=BODY_Y, vy=0, airborne=false, jumpT=0, wingOpen=0, crouch=0, landDip=0, pitch=0, nextJump=rr(6,9);
const DUTY=.65;
function pick(){
  const r=rnd();
  if(r<.5){ mode='walk'; tSpeed=rr(.45,.9); modeT=rr(2.5,5); }
  else { mode='pause'; tSpeed=0; modeT=rr(1.5,3.5); }
  tCurv=rr(-.3,.3);
}
function startJump(){ mode='crouch'; jumpT=0; tSpeed=0; }

const _t=V3(), _hd=V3(), _ank=V3(), _d=V3(), _w=V3(), _kn=V3(), _a2=V3(), _toe=V3(), _air=V3();
function solveLegs(){
  body.updateMatrixWorld(true);
  for(const L of legs){
    const {a,b,tl}=L.D;
    _toe.copy(L.toe); root.localToWorld(_toe); body.worldToLocal(_toe);
    if(L.air>0){ _air.set(L.s*L.D.airT[0],L.D.airT[1],L.D.airT[2]).add(L.tro); _toe.lerp(_air,smooth(L.air)); }
    _hd.set(_toe.x-L.tro.x,0,_toe.z-L.tro.z).normalize();
    const inc=.4+(L.swinging?.3:0);
    _ank.copy(_toe).addScaledVector(_hd,-tl*Math.cos(inc)); _ank.y+=tl*Math.sin(inc)*(1-L.air*.8);
    _d.subVectors(_ank,L.tro); const raw=_d.length(); _d.divideScalar(raw); const c=clamp(raw,Math.abs(a-b)+.03,(a+b)*.995);
    L.reach=raw/(a+b);
    const B=L.D.bend; _w.set(_hd.x*B[0]*Math.sign(L.s*_hd.x||1)*0+L.s*B[0]*Math.abs(_hd.x),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); if(_t.distanceToSquared(_a2)<1e-6) _t.add(V3(0,-.1,0)); orient(L.tar,_a2,_t,UP);
  }
}

function stanceMove(L,v,w,dt){ const ca=Math.cos(-w*dt), sa=Math.sin(-w*dt), x=L.toe.x, z=L.toe.z; L.toe.x=x*ca+z*sa; L.toe.z=-x*sa+z*ca-v*dt; }

function update(dt,t){
  // --- behaviour
  modeT-=dt; nextJump-=dt;
  if(mode==='walk'||mode==='pause'){ if(nextJump<=0 && !reduceMotion) startJump(); else if(modeT<=0) pick(); }
  if(mode==='crouch'){ jumpT+=dt; crouch=smooth(jumpT/.55); if(jumpT>.6){ mode='launch'; jumpT=0; } }
  else if(mode==='launch'){ jumpT+=dt; crouch=1-smooth(jumpT/.12); speed=lerp(speed,5.5,1-Math.exp(-dt*30)); vy=lerp(vy,4.6,1-Math.exp(-dt*30)); }
  if(mode==='launch' && jumpT>.12){ mode='air'; airborne=true; }
  if(airborne){
    const g=wingOpen>.5?4.2:12; vy-=g*dt; bodyY+=vy*dt; speed=lerp(speed,4,1-Math.exp(-dt*.6));
    if(bodyY<=BODY_Y && vy<0){ bodyY=BODY_Y; airborne=false; mode='land'; jumpT=0; landDip=1; vy=0; nextJump=rr(7,12);
      legs.forEach(L=>{ L.toe.copy(L.home); L.toe.z+=rr(-.1,.1); L.swinging=false; }); }
  } else if(mode==='launch'){ bodyY+=vy*dt; }
  if(mode==='land'){ jumpT+=dt; speed=lerp(speed,0,1-Math.exp(-dt*7)); if(jumpT>.9){ mode='pause'; modeT=rr(1,2.5); } }
  if(mode==='walk'||mode==='pause') speed+=(tSpeed-speed)*(1-Math.exp(-dt*3));
  curv+=(tCurv-curv)*(1-Math.exp(-dt*1.2));
  landDip*=Math.exp(-dt*5);

  const v=speed, w=(airborne||mode==='launch')?0:v*curv;

  // --- legs
  const kick = mode==='launch'||airborne;
  legs.forEach(L=>{
    const wantAir = airborne ? (L.D.hind ? 1 : (bodyY-BODY_Y>.35||vy>0?1:0)) : (mode==='launch'&&!L.D.hind?1:0);
    L.air+=(wantAir-L.air)*(1-Math.exp(-dt*(wantAir?10:7)));
    if(airborne && L.air>.5){ L.toe.copy(L.home); }
  });
  // walking legs: diagonal-pair gait
  const stride=clamp(.35+.15*v,.35,.6); let rate=(mode==='walk'||mode==='pause')?v*DUTY/stride:0;
  const walkLegs=legs.filter(L=>!L.D.hind);
  if(v<.06 && walkLegs.some(L=>L.swinging)) rate=Math.max(rate,1.6);
  gphase=(gphase+rate*dt)%1; const Tst=DUTY/Math.max(rate,.001);
  for(const L of walkLegs){
    if(L.air>.5) continue;
    const p=(gphase+L.phase)%1, sw=p>=DUTY && rate>0 && !kick;
    if(!sw){ if(L.swinging){ L.swinging=false; L.toe.copy(L.target); L.toe.y=0; } stanceMove(L,v,w,dt); }
    else { if(!L.swinging){ L.swinging=true; L.lift.copy(L.toe); } const s=(p-DUTY)/(1-DUTY), half=Math.min(.3,v*Tst*.5);
      L.target.set(L.home.x,0,L.home.z+half); L.toe.lerpVectors(L.lift,L.target,smooth(s)); L.toe.y=Math.sin(Math.PI*s)*.12; }
  }
  // hind legs: step only when they drift too far (and planted during the kick)
  for(const L of legs.filter(L=>L.D.hind)){
    if(L.air>.5) continue;
    if(L.stepping){ L.step+=dt/.35; const s=smooth(L.step); L.target.set(L.home.x,0,L.home.z+Math.min(.25,v*.3)); L.toe.lerpVectors(L.lift,L.target,s); L.toe.y=Math.sin(Math.PI*L.step)*.18; if(L.step>=1){ L.stepping=false; L.toe.y=0; } }
    else { stanceMove(L,v,w,dt); const other=legs.find(o=>o.D.hind&&o!==L);
      if(!kick && mode!=='crouch' && L.toe.distanceTo(L.home)>.38 && !other.stepping){ L.stepping=true; L.step=0; L.lift.copy(L.toe); } }
  }

  // --- wings
  const wantOpen = airborne && bodyY>BODY_Y+.15 ? 1 : 0;
  wingOpen+=(wantOpen-wingOpen)*(1-Math.exp(-dt*(wantOpen?9:3.5)));
  const beat=Math.sin(t*2*Math.PI*11)*smooth(wingOpen);
  tegs.forEach(W=>{ const o=smooth(wingOpen), s=W.s; W.roll.rotation.z=lerp(-s*.78,-s*.08,o); W.yaw.rotation.y=-s*1.32*o; W.flap.rotation.z=s*(o*.12+beat*.32)+s*.008*Math.sin(t*1.3); W.flap.rotation.x=-.04*o; });
  hinds.forEach(Hn=>{ const o=smooth(wingOpen), s=Hn.s; Hn.mesh.visible=o>.02; if(Hn.mesh.visible){ updateFan(Hn.geo,o,s); }
    Hn.roll.rotation.z=lerp(-s*.78,-s*.04,o); Hn.flap.rotation.z=s*(o*.08+Math.sin(t*2*Math.PI*11-.9)*.42*o); });

  // --- ground treadmill
  heading+=w*dt; wpos.x+=Math.sin(heading)*v*dt; wpos.z+=Math.cos(heading)*v*dt;
  const px=((wpos.x%TILE)+TILE)%TILE, pz=((wpos.z%TILE)+TILE)%TILE, ch=Math.cos(-heading), sh=Math.sin(-heading);
  groundPivot.rotation.y=-heading; groundPivot.position.set(-(px*ch+pz*sh),0,-(-px*sh+pz*ch));

  // --- body pose
  const busy=Math.min(1,v)*(airborne?0:1);
  const tp = airborne ? clamp(-vy*.07,-.35,.3) - .08*wingOpen : (mode==='crouch'? -.14*crouch : 0);
  pitch+=(tp-pitch)*(1-Math.exp(-dt*6));
  body.position.y=bodyY - .2*crouch - .1*landDip + .015*Math.cos(gphase*Math.PI*4)*busy;
  body.rotation.x=pitch + .012*Math.sin(t*.9)*(1-busy);
  body.rotation.z=.015*Math.sin(gphase*Math.PI*2)*busy + beat*.02 + curv*v*.03;
  body.rotation.y=.02*Math.sin(gphase*Math.PI*2)*busy;
  const br=Math.sin(t*1.9);
  segs.forEach((g,i)=>{ g.scale.y=1+.04*br*(i/9); g.scale.x=1+.015*br; g.position.z=-i*.205*(1+.02*br); });
  abdomen.rotation.x=-.02*br*(1-busy) + .06*wingOpen;

  // --- head, antennae, mouthparts
  head.rotation.x=.12+.02*Math.sin(t*1.35)-pitch*.3; head.rotation.y=.04*Math.sin(t*.68); head.rotation.z=.02*Math.sin(t*.9);
  antennae.forEach(({joints,s})=>joints.forEach((j,i)=>{ const u=i/joints.length, damp=1-.7*wingOpen;
    j.rotation.x=j.userData.bx+Math.sin(t*2.4-i*.4)*.035*u*damp+wingOpen*.03*(i<3?1:0);
    j.rotation.y=j.userData.by+Math.sin(t*1.9-i*.45+s*1.3)*.05*u*damp-curv*v*.01*u; }));
  palps.forEach(({joints,s,pi})=>joints.forEach((j,k)=>{ j.rotation.x=j.userData.b+Math.sin(t*(pi?7:5.5)+s+k*.7)*(.14+.04*k)*(1-wingOpen); }));
  mandibles.forEach(({mg,s})=>{ mg.rotation.y=s*.18*Math.max(0,Math.sin(t*5))*(1-busy)*(1-wingOpen); });
  labrum.rotation.x=.1*Math.max(0,Math.sin(t*5));

  solveLegs();
}

/* =====================================================================
   CAMERA / INPUT
   ===================================================================== */
const cam={dist:9,yaw:.7,pitch:.3,tYaw:.7,tPitch:.3,tDist:9,auto:0}; let tgtY=.6, dragging=false;
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,11); }
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,4,18); pinch=d; return; }
  cam.tYaw-=(e.clientX-lx)*.006; cam.tPitch=clamp(cam.tPitch+(e.clientY-ly)*.005,.04,1.35); lx=e.clientX; ly=e.clientY; });
const up=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,up));
canvas.addEventListener('wheel',e=>{ e.preventDefault(); cam.tDist=clamp(cam.tDist+e.deltaY*.008,4,18); },{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);
  tgtY+=(lerp(.55,body.position.y-.1,.7)-tgtY)*(1-Math.exp(-dt*3));
  if(!dragging&&!reduceMotion) cam.auto+=dt*.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(Math.sin(y)*Math.cos(p)*cam.dist, tgtY+Math.sin(p)*cam.dist, Math.cos(y)*Math.cos(p)*cam.dist-.3);
  camera.lookAt(0,tgtY,-.3);
  renderer.render(scene,camera);
}
frame();
}
</script>
</body>
</html>
MikeHiggins.me.uk LinkedIn GitHub Bluesky Contra Upwork
© 2026 Mike Higgins. All rights reserved.