COCKROACH SOURCE CODE
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cockroach — Three.js study</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<style>
:root{color-scheme:dark}
*{box-sizing:border-box;margin:0;padding:0;min-width:0}
html,body{height:100%;background:#0d0a08;overflow:hidden;}
#c{position:fixed;inset:0;width:100%;height:100%;display:block;cursor:grab;touch-action:none}
#c:active{cursor:grabbing}
.vig{position:fixed;inset:0;pointer-events:none;background:radial-gradient(ellipse at 50% 45%,transparent 45%,rgba(5,3,2,.75) 100%)}
</style>
</head>
<body>
<canvas id="c"></canvas>
<div class="vig"></div>
<script>
{
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*t*(3-2*t);
let seed = 1337;
const rnd = () => (seed = (seed*16807) % 2147483647, (seed-1)/2147483646);
const rr = (a,b) => a + (b-a)*rnd();
/* ---------------- renderer / scene ---------------- */
const canvas = document.getElementById('c');
const renderer = new T.WebGLRenderer({ canvas, antialias:true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.outputEncoding = T.sRGBEncoding;
renderer.toneMapping = T.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = T.PCFSoftShadowMap;
const ANISO = renderer.capabilities.getMaxAnisotropy();
const BG = 0x0d0a08;
const scene = new T.Scene();
scene.background = new T.Color(BG);
scene.fog = new T.FogExp2(BG, 0.05);
const camera = new T.PerspectiveCamera(40, innerWidth/innerHeight, 0.05, 200);
/* ---------------- procedural textures ---------------- */
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 tex(c,{srgb=true,repeat=0}={}){
const t=new T.CanvasTexture(c); if(srgb) t.encoding=T.sRGBEncoding; t.anisotropy=ANISO;
if(repeat){ t.wrapS=t.wrapT=T.RepeatWrapping; t.repeat.set(repeat,repeat); }
return t;
}
function greyOf(c,lo=0.5){
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;
let mx=1; for(let i=0;i<p.length;i+=4){ const l=0.3*p[i]+0.59*p[i+1]+0.11*p[i+2]; p[i]=l; if(l>mx) mx=l; }
for(let i=0;i<p.length;i+=4){ const v=255*(lo+(1-lo)*p[i]/mx); p[i]=p[i+1]=p[i+2]=v; }
g.putImageData(d,0,0); return o;
}
function dots(g,w,h,n,col,r0,r1){ for(let i=0;i<n;i++){ g.fillStyle=typeof col==='function'?col():col; g.beginPath(); g.arc(rnd()*w,rnd()*h,rr(r0,r1),0,6.3); g.fill(); } }
// generic micro-pitting for chitin
const pitsC = makeCanvas(256,256,(g,w,h)=>{ g.fillStyle='#808080'; g.fillRect(0,0,w,h);
dots(g,w,h,1600,()=>`rgba(0,0,0,${rr(.12,.35)})`,.5,1.5); dots(g,w,h,600,()=>`rgba(255,255,255,${rr(.08,.2)})`,.4,1.1); });
const pitsT = tex(pitsC,{srgb:false,repeat:4});
// pronotum: pale amber shield with the dark two-lobed central blotch
const PW=1.36, PD=1.1;
function seBound(th){ const c=Math.cos(th), s=Math.sin(th), n=s<0?2.9:2.15;
return [PW/2*Math.sign(c)*Math.abs(c)**(2/n), PD/2*Math.sign(s)*Math.abs(s)**(2/n)]; }
const pronC = makeCanvas(512,512,(g,w,h)=>{
const P=(x,z)=>[(x/PW+.5)*w,(.5-z/PD)*h];
let gr=g.createRadialGradient(w/2,h*.55,20,w/2,h/2,w*.62); gr.addColorStop(0,'#9a5a26'); gr.addColorStop(.5,'#b98039'); gr.addColorStop(1,'#c99a52');
g.fillStyle=gr; g.fillRect(0,0,w,h);
dots(g,w,h,1400,()=>`rgba(110,50,16,${rr(.05,.16)})`,1,7);
// blotch
g.save(); g.shadowColor='rgba(50,20,6,.95)'; g.shadowBlur=40;
gr=g.createRadialGradient(w/2,h*.56,10,w/2,h*.5,w*.32); gr.addColorStop(0,'#7a3614'); gr.addColorStop(.6,'#4c200c'); gr.addColorStop(1,'#2e1207');
g.fillStyle=gr; g.beginPath();
for(let i=0;i<=120;i++){ const th=i/120*Math.PI*2;
let rx=.33, rz=.43; let r=1+.08*Math.cos(2*th)+.05*Math.sin(5*th+.6)*Math.cos(th);
const notchF=Math.exp(-((th-Math.PI/2)**2)/.04), notchB=Math.exp(-((th-1.5*Math.PI)**2)/.03);
r*=1-.22*notchF-.1*notchB;
const z0=-.04; const [px,py]=P(Math.cos(th)*rx*r, z0+Math.sin(th)*rz*r); i?g.lineTo(px,py):g.moveTo(px,py); }
g.closePath(); g.fill(); g.restore();
// paler inner lobes and median line
[[-1],[1]].forEach(([s])=>{ const [x,y]=P(s*.1,.02); const r=g.createRadialGradient(x,y,2,x,y,46); r.addColorStop(0,'rgba(160,80,30,.55)'); r.addColorStop(1,'rgba(160,80,30,0)'); g.fillStyle=r; g.fillRect(0,0,w,h); });
g.strokeStyle='rgba(30,10,4,.6)'; g.lineWidth=3; g.beginPath(); g.moveTo(...P(0,.3)); g.lineTo(...P(0,-.4)); g.stroke();
dots(g,w,h,2200,()=>`rgba(20,8,2,${rr(.05,.18)})`,.5,1.6);
// darker margin following the outline
g.strokeStyle='rgba(90,40,14,.85)'; g.lineWidth=7; g.shadowColor='rgba(60,25,8,.8)'; g.shadowBlur=8; g.beginPath();
for(let i=0;i<=160;i++){ const [bx,bz]=seBound(i/160*Math.PI*2); const [px,py]=P(bx*.985,bz*.985); i?g.lineTo(px,py):g.moveTo(px,py); }
g.stroke();
});
const pronT=tex(pronC), pronG=greyOf(pronC), pronTI=tex(pronG), pronBump=tex(greyOf(pronC,0),{srgb:false});
// tegmen (leathery forewing): venation fanning from the hinge
function tegmenCanvas(){ return makeCanvas(1024,256,(g,w,h)=>{
let gr=g.createLinearGradient(0,0,w,0); gr.addColorStop(0,'#4a200d'); gr.addColorStop(.18,'#73351a'); gr.addColorStop(.7,'#8b4520'); gr.addColorStop(1,'#7a3a1a');
g.fillStyle=gr; g.fillRect(0,0,w,h);
gr=g.createLinearGradient(0,0,0,h); gr.addColorStop(0,'rgba(196,122,58,.45)'); gr.addColorStop(.28,'rgba(196,122,58,0)'); gr.addColorStop(.85,'rgba(30,10,4,0)'); gr.addColorStop(1,'rgba(30,10,4,.35)');
g.fillStyle=gr; g.fillRect(0,0,w,h);
dots(g,w,h,2600,()=>`rgba(35,12,4,${rr(.04,.12)})`,2,9);
dots(g,w,h,900,()=>`rgba(190,110,50,${rr(.04,.1)})`,2,6);
const X=u=>u*w, Y=v=>(1-v)*h;
// cross-veins (reticulation)
g.lineCap='round';
for(let i=0;i<3200;i++){ const x=rnd()*w,y=rnd()*h,l=rr(4,12),a=rr(-.5,.5)+Math.PI/2;
g.strokeStyle=`rgba(175,98,45,${rr(.15,.35)})`; g.lineWidth=rr(.7,1.4); g.beginPath(); g.moveTo(x,y); g.lineTo(x+Math.cos(a)*l,y+Math.sin(a)*l); g.stroke(); }
// main longitudinal veins
const N=17;
for(let k=0;k<N;k++){ const q=k/(N-1); let ut,vt;
if(q<.45){ ut=.12+q/.45*.84; vt=.93; } else if(q<.62){ ut=.985; vt=lerp(.88,.14,(q-.45)/.17); } else { ut=lerp(.9,.16,(q-.62)/.38); vt=.07; }
const cu=ut*.45, cv=lerp(.52,vt,.35);
for(const [col,lw,off] of [['rgba(30,10,4,.55)',4,1.5],['rgba(196,112,52,.9)',2.2,0]]){
g.strokeStyle=col; g.lineWidth=lw*(1-q*.25); g.beginPath(); g.moveTo(X(0),Y(.52)+off); g.quadraticCurveTo(X(cu),Y(cv)+off,X(ut),Y(vt)+off); g.stroke(); }
if(k%3===1){ const bu=lerp(ut,cu,.45), bv=lerp(vt,cv,.45); g.strokeStyle='rgba(185,104,48,.7)'; g.lineWidth=1.4;
g.beginPath(); g.moveTo(X(bu),Y(bv)); g.quadraticCurveTo(X(lerp(bu,ut,.5)),Y(lerp(bv,vt,.3)+.05),X(Math.min(.98,ut+.08)),Y(vt+(vt>.5?-.05:.04))); g.stroke(); } }
// claval furrow + anal veins
g.strokeStyle='rgba(25,8,3,.8)'; g.lineWidth=4; g.beginPath(); g.moveTo(X(.01),Y(.44)); g.quadraticCurveTo(X(.12),Y(.3),X(.32),Y(.06)); g.stroke();
for(let k=0;k<5;k++){ g.strokeStyle='rgba(180,100,46,.7)'; g.lineWidth=1.6; g.beginPath(); g.moveTo(X(.01),Y(.4-k*.05)); g.quadraticCurveTo(X(.06+k*.02),Y(.25-k*.03),X(.1+k*.045),Y(.06)); g.stroke(); }
// margins
g.fillStyle='rgba(30,10,4,.55)'; g.fillRect(0,0,w,5); g.fillRect(0,h-6,w,6);
}); }
const tegC=tegmenCanvas(), tegT=tex(tegC), tegTI=tex(greyOf(tegC,.45)), tegBump=tex(greyOf(tegC,0),{srgb:false});
// hindwing: smoky membrane with radial fan veins
const hindC = makeCanvas(512,256,(g,w,h)=>{
g.clearRect(0,0,w,h); let gr=g.createLinearGradient(0,0,w,0); gr.addColorStop(0,'rgba(120,64,28,.75)'); gr.addColorStop(1,'rgba(170,110,60,.38)');
g.fillStyle=gr; g.fillRect(0,0,w,h);
for(let k=0;k<22;k++){ const q=k/21; g.strokeStyle=`rgba(55,24,8,${.75-q*.3})`; g.lineWidth=2.2-q;
g.beginPath(); g.moveTo(0,h*.5); g.quadraticCurveTo(w*.35,h*(.5+(q-.5)*.4),w,h*(1-q)); g.stroke(); }
for(let i=0;i<1400;i++){ const x=rnd()*w,y=rnd()*h; g.strokeStyle=`rgba(60,28,10,${rr(.12,.3)})`; g.lineWidth=.8; g.beginPath(); g.moveTo(x,y); g.lineTo(x+rr(-2,2),y+rr(5,10)); g.stroke(); }
});
const hindT=tex(hindC), hindTI=tex(hindC);
// compound eye: hexagonal ommatidia
const eyeC = makeCanvas(512,256,(g,w,h)=>{ g.fillStyle='#0c0604'; g.fillRect(0,0,w,h); const r=4.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; const gr=g.createRadialGradient(x-1,y-1,0,x,y,r);
gr.addColorStop(0,'#3a2112'); gr.addColorStop(.7,'#160b06'); gr.addColorStop(1,'#050201'); g.fillStyle=gr; g.beginPath(); g.arc(x,y,r*.92,0,6.3); g.fill(); } });
const eyeT=tex(eyeC), eyeBump=tex(greyOf(eyeC,0),{srgb:false});
// abdominal plates
function plateCanvas(base,dark,edge){ return makeCanvas(256,128,(g,w,h)=>{
let gr=g.createLinearGradient(0,0,0,h); gr.addColorStop(0,base); gr.addColorStop(.72,base); gr.addColorStop(.86,dark); gr.addColorStop(.96,dark); gr.addColorStop(1,edge);
g.fillStyle=gr; g.fillRect(0,0,w,h);
gr=g.createLinearGradient(0,0,w,0); gr.addColorStop(0,'rgba(200,140,80,.35)'); gr.addColorStop(.18,'rgba(200,140,80,0)'); gr.addColorStop(.82,'rgba(200,140,80,0)'); gr.addColorStop(1,'rgba(200,140,80,.35)');
g.fillStyle=gr; g.fillRect(0,0,w,h);
dots(g,w,h,700,()=>`rgba(20,8,2,${rr(.1,.3)})`,.5,1.3); }); }
const tergC=plateCanvas('#6a3317','#3b1a0b','#b87a44'), sternC=plateCanvas('#93592e','#6d3d1d','#d0a066');
const tergT=tex(tergC), tergTI=tex(greyOf(tergC)), sternT=tex(sternC), sternTI=tex(greyOf(sternC));
// floor: worn speckled ceramic tile
const TILE=5;
const floorC = makeCanvas(1024,1024,(g,w,h)=>{
g.fillStyle='#3b342d'; g.fillRect(0,0,w,h);
for(let i=0;i<60;i++){ const x=rnd()*w,y=rnd()*h,r=rr(40,180),gr=g.createRadialGradient(x,y,0,x,y,r);
gr.addColorStop(0,`rgba(${rnd()<.5?'20,15,10':'90,80,68'},${rr(.08,.2)})`); gr.addColorStop(1,'rgba(0,0,0,0)'); g.fillStyle=gr; g.fillRect(0,0,w,h); }
const cols=['#5c5247','#241e19','#7b6f61','#1a1512','#4a4038','#8d806f'];
dots(g,w,h,14000,()=>cols[(rnd()*cols.length)|0],.6,2.6);
dots(g,w,h,900,()=>cols[(rnd()*cols.length)|0],2.5,6);
for(let i=0;i<40;i++){ g.strokeStyle=`rgba(200,190,170,${rr(.03,.07)})`; g.lineWidth=rr(1,3); const x=rnd()*w,y=rnd()*h; g.beginPath(); g.moveTo(x,y); g.lineTo(x+rr(-120,120),y+rr(-30,30)); g.stroke(); }
g.fillStyle='#16110d'; g.fillRect(0,0,w,14); g.fillRect(0,0,14,h);
g.fillStyle='rgba(22,17,13,.5)'; g.fillRect(0,14,w,6); g.fillRect(14,0,6,h);
});
const floorT=tex(floorC,{repeat:160/TILE}), floorB=tex(greyOf(floorC,0),{srgb:false,repeat:160/TILE});
/* ---------------- materials (natural + iridescent) ---------------- */
const mats=[];
function M(hex,hue,o={}){
const m=new T.MeshPhysicalMaterial({ color:0xffffff, roughness:o.rough??.4, metalness:o.metal??.04, clearcoat:o.coat??.75, clearcoatRoughness:o.coatRough??.2,
side:o.side??T.FrontSide, transparent:!!o.transparent, depthWrite:o.depthWrite??true });
const nat=new T.Color(hex).convertSRGBToLinear(); m.color.copy(nat);
if(o.map) m.map=o.map;
if(o.bump!==null){ m.bumpMap=o.bump||pitsT; m.bumpScale=o.bumpScale??.0035; }
m.userData={ nat, hue, mapN:o.map||null, mapI:o.mapI||o.map||null, rough:m.roughness, metal:m.metalness, light:o.light??.52 };
mats.push(m); return m;
}
const DS=T.DoubleSide;
const mt={
pron: M('#ffffff',.08,{map:pronT,mapI:pronTI,bump:pronBump,bumpScale:.004,coat:.65,coatRough:.22,rough:.42,side:DS}),
teg: M('#ffffff',.52,{map:tegT,mapI:tegTI,bump:tegBump,bumpScale:.004,coat:.6,coatRough:.26,rough:.48,side:DS}),
hind: M('#ffffff',.62,{map:hindT,mapI:hindTI,transparent:true,depthWrite:false,side:DS,coat:.4,rough:.3,bump:null,light:.6}),
terg: M('#ffffff',.82,{map:tergT,mapI:tergTI,side:DS,coat:.9}),
stern: M('#ffffff',.9,{map:sternT,mapI:sternTI,side:DS}),
memb: M('#b07d4c',.72,{rough:.7,coat:.1,light:.6}),
thor: M('#5a2811',.3,{}),
head: M('#683217',.0,{coat:.9,coatRough:.14}),
face: M('#8f4c22',.95,{}),
lab: M('#a8622e',.92,{light:.6}),
eye: M('#ffffff',null,{map:eyeT,bump:eyeBump,bumpScale:.003,coat:1,coatRough:.03,rough:.22}),
fen: M('#b9925c',null,{rough:.5,coat:.3}),
mand: M('#2a1107',null,{coat:1,rough:.3}),
spine: M('#22100a',null,{rough:.35,coat:.6,bump:null}),
claw: M('#1a0c06',null,{rough:.3,coat:.8,bump:null}),
pad: M('#d3ab72',null,{rough:.55,coat:.3,bump:null}),
cerc: M('#7c4322',.98,{}),
palp: M('#94552a',.9,{light:.58}),
};
const antMats=[...Array(8)].map((_,k)=>{ const c=new T.Color('#46200e').lerp(new T.Color('#86471f'),k/7); return M('#'+c.getHexString(),k/8*.9,{rough:.45,coat:.6}); });
function legMats(hue){ return { coxa:M('#8f4d25',hue-.04,{}), fem:M('#7d3e1d',hue,{coat:.85}), tib:M('#713518',hue+.05,{coat:.85}), tar:M('#83451f',hue+.08,{}) }; }
const hairMat=new T.LineBasicMaterial({color:0x2c170b,transparent:true,opacity:.75});
/* ---------------- geometry helpers ---------------- */
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,24,16), SPH_LO=new T.SphereGeometry(1,10,8);
const CONE=new T.ConeGeometry(1,1,6).translate(0,.5,0);
const UP=V3(0,1,0), _m=new T.Matrix4(), _x=V3(), _y=V3(), _z=V3();
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 mesh(geo,mat,parent,pos,scl){ const m=new T.Mesh(geo,mat); if(pos) m.position.copy(pos); if(scl) (typeof scl==='number'?m.scale.setScalar(scl):m.scale.copy(scl)); m.castShadow=true; m.receiveShadow=true; parent&&parent.add(m); return m; }
function spike(parent,pos,dir,len,rad,mat){ const m=mesh(CONE,mat,parent,pos,V3(rad,len,rad)); m.quaternion.setFromUnitVectors(UP,dir.clone().normalize()); m.receiveShadow=false; return m; }
function hairs(parent,list){ const a=[]; for(const [p,d,l] of list) a.push(p.x,p.y,p.z,p.x+d.x*l,p.y+d.y*l,p.z+d.z*l);
const g=new T.BufferGeometry(); g.setAttribute('position',new T.Float32BufferAttribute(a,3)); const ls=new T.LineSegments(g,hairMat); parent.add(ls); return ls; }
const randDir=()=>V3(rr(-1,1),rr(-1,1),rr(-1,1)).normalize();
function shell(rx0,ry0,rx1,ry1,len,a0,a1,na=28,nl=6){
const pos=[],uv=[],idx=[];
for(let i=0;i<=nl;i++){ const s=i/nl, rx=lerp(rx0,rx1,s), ry=lerp(ry0,ry1,s);
for(let j=0;j<=na;j++){ const q=j/na, a=lerp(a0,a1,q); pos.push(rx*Math.sin(a),ry*Math.cos(a),-s*len); uv.push(q,1-s); } }
for(let i=0;i<nl;i++) for(let j=0;j<na;j++){ const a=i*(na+1)+j,b=a+na+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;
}
/* ---------------- the animal ---------------- */
const roach=new T.Group(); scene.add(roach);
const body=new T.Group(); roach.add(body);
const BODY_Y=.44;
body.position.y=BODY_Y;
// pronotum: custom dome with a curled rim
(function(){
const NR=26, NT=96, pos=[], uv=[], idx=[], H=.135;
for(let i=0;i<=NR;i++){ const r=i/NR;
for(let j=0;j<=NT;j++){ const [bx,bz]=seBound(j/NT*Math.PI*2); const x=bx*r, z=bz*r;
const y=H*Math.pow(Math.max(0,1-r*r),.62) - .055*smooth(clamp((r-.84)/.16,0,1)) + .025*Math.exp(-((x)**2)/.02)*(1-r);
pos.push(x,y,z); uv.push(x/PW+.5, z/PD+.5); } }
for(let i=0;i<NR;i++) for(let j=0;j<NT;j++){ const a=i*(NT+1)+j,b=a+NT+1; idx.push(a,a+1,b,b,a+1,b+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();
const p=mesh(g,mt.pron,body,V3(0,.17,.9)); p.rotation.x=-.07;
})();
// thorax underside, neck
mesh(SPH,mt.thor,body,V3(0,-.03,.42),V3(.44,.17,.66));
mesh(SPH,mt.thor,body,V3(0,.06,.62),V3(.5,.14,.42));
[-1,1].forEach(s=>{ for(let k=0;k<3;k++) mesh(SPH_LO,mt.thor,body,V3(s*.2,-.15,.78-k*.42),V3(.12,.05,.16)); });
mesh(alongZ(.26,t=>.13+.02*Math.sin(t*Math.PI),14,6),mt.memb,body,V3(0,.0,1.0));
// abdomen: imbricate tergites over sternites, pleural membrane, spiracles
const abdomen=new T.Group(); body.add(abdomen);
const AW=[.5,.55,.57,.56,.53,.48,.41,.33,.24], ATY=[.16,.17,.17,.165,.155,.14,.12,.1,.08], ABY=[.14,.16,.17,.17,.16,.145,.125,.1,.075];
const A_STEP=.235, A_Z0=.08;
const tergites=[];
AW.forEach((w,i)=>{
const z=A_Z0-i*A_STEP, yc=-.03-i*.014;
const seg=new T.Group(); seg.position.set(0,yc,z); abdomen.add(seg);
mesh(shell(w,ATY[i],w*1.03,ATY[i]*1.02,.31,-1.72,1.72),mt.terg,seg);
mesh(shell(w*.98,ABY[i],w*1.01,ABY[i]*1.03,.3,Math.PI-1.56,Math.PI+1.56),mt.stern,seg);
mesh(SPH,mt.memb,seg,V3(0,-.01,-.16),V3(w*.97,Math.min(ATY[i],ABY[i])*.92,.2));
[-1,1].forEach(s=>mesh(SPH_LO,mt.spine,seg,V3(s*w*.985,-.035,-.1),V3(.012,.02,.03)));
tergites.push(seg);
});
const zTip=A_Z0-(AW.length-1)*A_STEP-.3;
mesh(SPH,mt.terg,abdomen,V3(0,-.07,zTip+.02),V3(.16,.05,.12));
mesh(SPH,mt.stern,abdomen,V3(0,-.13,zTip+.06),V3(.18,.05,.14));
// cerci
const cerci=[];
[-1,1].forEach(s=>{
const g=new T.Group(); g.position.set(s*.09,-.07,zTip+.02); abdomen.add(g);
const dir=V3(s*.42,.22,-1).normalize(); let p=V3(); const hl=[];
for(let k=0;k<14;k++){ const len=.05-k*.0012, r=.032*(1-k/15)+.006, q=p.clone().addScaledVector(dir,len);
dir.y-=.012; dir.normalize();
const holder=new T.Group(); orient(holder,p,q,UP); g.add(holder);
mesh(alongX(len,t=>r*(.82+.18*t),8,4),mt.cerc,holder);
for(let h=0;h<3;h++){ const d=randDir(); d.addScaledVector(dir,-.3); hl.push([q.clone(),d.normalize(),rr(.03,.06)]); }
p=q; }
hairs(g,hl); cerci.push({g,s});
spike(abdomen,V3(s*.05,-.14,zTip+.05),V3(s*.2,-.1,-1),.09,.008,mt.cerc); // styli
});
// head
const head=new T.Group(); head.position.set(0,.0,1.3); head.rotation.x=.5; body.add(head);
mesh(SPH,mt.head,head,null,V3(.27,.31,.2));
mesh(SPH,mt.face,head,V3(0,-.13,.14),V3(.17,.1,.07));
mesh(SPH,mt.lab,head,V3(0,-.24,.13),V3(.1,.06,.04));
const mandibles=[], palps=[];
[-1,1].forEach(s=>{
// kidney-shaped compound eye
const eg=SPH.clone(); const pa=eg.attributes.position;
for(let i=0;i<pa.count;i++){ const y=pa.getY(i); pa.setX(i,pa.getX(i)-s*.55*y*y); }
eg.computeVertexNormals();
const e=mesh(eg,mt.eye,head,V3(s*.205,.06,.07),V3(.075,.17,.1)); e.rotation.y=s*.55; e.rotation.z=-s*.12;
mesh(new T.TorusGeometry(.04,.012,8,16),mt.head,head,V3(s*.12,.09,.17)).rotation.y=s*.3;
mesh(SPH_LO,mt.fen,head,V3(s*.08,.2,.13),V3(.022,.015,.008));
// mandible
const mg=new T.Group(); mg.position.set(s*.065,-.27,.06); head.add(mg);
const mh=new T.Group(); orient(mh,V3(),V3(-s*.55,-1,.25),V3(0,0,1)); mg.add(mh);
mesh(alongX(.13,t=>.042*Math.pow(1-t,.7)+.003,8,6),mt.mand,mh);
for(let k=0;k<3;k++) spike(mh,V3(.05+k*.025,0,-.02*s),V3(.3,0,-s),.025,.008,mt.mand);
mandibles.push({mg,s});
// maxillary palp (5 segments) + labial palp (3)
[[V3(s*.12,-.25,.05),[.07,.06,.1,.11,.12],.022,V3(s*.35,-1,.5)],[V3(s*.04,-.3,.02),[.05,.05,.07],.014,V3(s*.2,-1,.2)]].forEach(([base,lens,r0,dir],pi)=>{
const root=new T.Group(); root.position.copy(base); root.quaternion.setFromUnitVectors(V3(0,0,1),dir.normalize()); head.add(root);
let parent=root; const joints=[];
lens.forEach((L,k)=>{ const j=new T.Group(); j.userData.b=[0,.35,-.5,.3,.25][k]; j.rotation.x=j.userData.b; parent.add(j);
const r=r0*(1-k*.12); mesh(alongZ(L,t=>r*(.8+.2*Math.sin(t*Math.PI))+(k===lens.length-1?.006*t:0),8,6),mt.palp,j);
const nx=new T.Group(); nx.position.z=L; j.add(nx); parent=nx; joints.push(j); });
palps.push({joints,s,pi});
});
});
// antennae: scape, pedicel and ~46 bead-like flagellomeres
const antennae=[];
[-1,1].forEach(s=>{
const root=new T.Group(); root.position.set(s*.12,.09,.18); head.add(root);
const dirBody=V3(s*.42,.32,1).normalize(); const inv=head.quaternion.clone().invert();
root.quaternion.setFromUnitVectors(V3(0,0,1),dirBody.applyQuaternion(inv));
const joints=[]; let parent=root; const N=48;
for(let i=0;i<N;i++){
const t=i/(N-1); const j=new T.Group();
j.userData.bx= i<2?0:.022+.012*t; j.userData.by= i<2?0:s*.012;
j.rotation.set(j.userData.bx,j.userData.by,0); parent.add(j);
let L,r0,r1;
if(i===0){ L=.13; r0=.042; r1=.034; } else if(i===1){ L=.06; r0=.03; r1=.028; }
else { L=lerp(.085,.05,t); r0=lerp(.02,.005,t); r1=r0*1.18; }
mesh(alongZ(L,u=>lerp(r0,r1,u)*(i>1?(.9+.1*Math.sin(u*Math.PI)):1),i<6?10:6,i<2?6:3),antMats[Math.min(7,(t*8)|0)],j);
if(i>1 && i%2===0){ const hl=[]; for(let h=0;h<5;h++){ const a=rnd()*6.3; hl.push([V3(Math.cos(a)*r1,Math.sin(a)*r1,L*rr(.3,.95)),V3(Math.cos(a),Math.sin(a),1.4).normalize(),rr(.02,.035)]); } hairs(j,hl); }
const nx=new T.Group(); nx.position.z=L; j.add(nx); parent=nx; joints.push(j);
}
antennae.push({joints,s,yaw:0,pitch:0,ty:0,tp:0,next:0});
});
// wings
const WING={L:2.78,W:.9,arc:.95,z:.42,y:.29};
function tegmenGeo(side){
const NU=44,NV=14,pos=[],uv=[],idx=[], {L,W,arc}=WING, R=W/arc;
for(let i=0;i<=NU;i++){ const t=i/NU;
const env=t<.16?Math.pow(Math.sin(t/.16*Math.PI/2),.75):1, tip=t>.74?Math.sqrt(Math.max(0,1-((t-.74)/.26)**2)):1;
const hw=.5*W*Math.max(.03,env*tip), cen=.5*W+.03*W*t;
for(let j=0;j<=NV;j++){ const v=cen-hw+2*hw*(j/NV), a=(v/W)*arc;
const lat=R*Math.sin(a), dy=-R*(1-Math.cos(a));
const x=side>0?lat:-(lat-.1), y=dy-.15*t*t+(side<0?.024:0)+.012*Math.sin(t*Math.PI);
pos.push(x,y,-t*L); uv.push(t,v/W); } }
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 hindGeo(side){
const NU=36,NV=24,pos=[],uv=[],idx=[],L=2.35,W=1.45;
for(let i=0;i<=NU;i++){ const t=i/NU, hw=W*Math.pow(Math.sin(Math.PI*Math.min(1,t*1.05)),.55)*(1-.35*t)+.01;
for(let j=0;j<=NV;j++){ const q=j/NV, v=hw*q; pos.push(side*v,.035*Math.sin(q*Math.PI*11)*q,-t*L); uv.push(t,q); } }
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;
}
const wings=[];
[1,-1].forEach(s=>{
const hp=new T.Group(); hp.position.set(s*.03,WING.y-.04,WING.z); body.add(hp);
const hm=mesh(hindGeo(s),mt.hind,hp); hm.castShadow=false; hp.visible=false;
const tp=new T.Group(); tp.position.set(s*.02,WING.y,WING.z); body.add(tp);
mesh(tegmenGeo(s),mt.teg,tp);
wings.push({tp,hp,s});
});
// legs: coxa, trochanter, spined femur & tibia, 5-segment tarsus with pads and claws, solved by 2-bone IK
const legs=[];
const LEGDEF=[
{hip:[.12,-.15,.72],tro:[.3,-.26,.98],a:.6,b:.66,tl:.42,foot:[1.28,2.05],sp:10,ss:.8,hue:.02},
{hip:[.2,-.16,.3],tro:[.44,-.25,.2],a:.74,b:.84,tl:.5,foot:[2.12,.35],sp:16,ss:1,hue:.4},
{hip:[.2,-.15,-.1],tro:[.47,-.22,-.44],a:.92,b:1.12,tl:.6,foot:[1.88,-2.2],sp:22,ss:1.25,hue:.74},
];
function buildLeg(D,s,phase){
const m=legMats(D.hue), 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=>.1*Math.pow(Math.sin(Math.PI*(.12+.88*t)),.55)*(1-.4*t)+.02,12,10),m.coxa,cg).scale.set(1,.6,1);
mesh(SPH_LO,m.coxa,body,tro,.06);
// femur
const fem=new T.Group(); body.add(fem);
mesh(alongX(D.a,t=>.062*Math.pow(Math.sin(Math.PI*(.06+.88*t)),.5)*(1-.28*t)+.014,12,14),m.fem,fem).scale.set(1,1,.78);
for(let i=0;i<6;i++) [-1,1].forEach(zs=>{ const x=D.a*(.3+.11*i); spike(fem,V3(x,-.034,zs*.022),V3(.75,-.55,zs*.4),(.035+(i===5?.03:0))*D.ss,.007,mt.spine); });
// tibia
const tib=new T.Group(); body.add(tib);
const tr=t=>.04*(1-.35*t)+.005+.012*Math.exp(-((t-1)**2)/.004);
mesh(alongX(D.b,tr,10,16),m.tib,tib);
const rows=[-2.3,-1.35,-.35,.7,1.75];
rows.forEach((a,ri)=>{ const n=Math.round(D.sp/rows.length);
for(let k=0;k<n;k++){ const t=.14+(k+ri*.37%1)*(.78/n); const rad=V3(0,Math.cos(a),Math.sin(a));
const pos=rad.clone().multiplyScalar(tr(t)*.9); pos.x=t*D.b;
spike(tib,pos,rad.clone().multiplyScalar(.6).add(V3(.8,0,0)),(.06+.07*t)*D.ss*rr(.8,1.15),.0085,mt.spine); } });
for(let k=0;k<6;k++){ const a=k/6*6.28; spike(tib,V3(D.b*.97,Math.cos(a)*.04,Math.sin(a)*.04),V3(.9,Math.cos(a)*.45,Math.sin(a)*.45),.08*D.ss,.009,mt.spine); }
const th=[]; for(let i=0;i<40;i++){ const t=rnd(), a=rnd()*6.3; th.push([V3(t*D.b,Math.cos(a)*tr(t),Math.sin(a)*tr(t)),V3(1.2,Math.cos(a),Math.sin(a)).normalize(),rr(.02,.04)]); } hairs(tib,th);
// tarsus
const tar=new T.Group(); body.add(tar);
let x=0; const fr=[.36,.19,.15,.12,.18];
fr.forEach((f,k)=>{ const L=D.tl*f, r=.022-k*.0022;
mesh(alongX(L,t=>r*(.75+.25*t)+(t>.85?.004:0),8,6),m.tar,tar,V3(x,0,0));
if(k<4) mesh(SPH_LO,mt.pad,tar,V3(x+L*.85,-r*.9,0),V3(L*.25,.008,r*.9));
x+=L; });
[-1,1].forEach(zs=>{ const c=mesh(alongX(.06,t=>.009*(1-t)+.001,6,5),mt.claw,tar,V3(x,0,zs*.008)); c.rotation.set(0,zs*.35,-.9); });
mesh(SPH_LO,mt.pad,tar,V3(x+.01,-.006,0),V3(.016,.01,.014));
const tl=[]; for(let i=0;i<14;i++){ const t=rnd()*x; tl.push([V3(t,-.01,rr(-.01,.01)),V3(.4,-1,rr(-.6,.6)).normalize(),rr(.015,.03)]); } hairs(tar,tl);
const home=V3(s*D.foot[0],0,D.foot[1]);
legs.push({D,s,fem,tib,tar,tro,home,toe:home.clone(),lift:home.clone(),target:home.clone(),phase,swinging:false});
}
LEGDEF.forEach((D,i)=>{ buildLeg(D,-1,i===1?.5:0); buildLeg(D,1,i===1?0:.5); });
roach.scale.setScalar(1);
/* ---------------- floor & lights ---------------- */
const floor=new T.Mesh(new T.PlaneGeometry(160,160),new T.MeshStandardMaterial({map:floorT,bumpMap:floorB,bumpScale:.02,roughness:.9,metalness:0,color:0x9a8f84}));
floor.rotation.x=-Math.PI/2; floor.receiveShadow=true;
const floorPivot=new T.Group(); floorPivot.add(floor); scene.add(floorPivot);
const hemi=new T.HemisphereLight(0xffe7cc,0x1a1010,.55); scene.add(hemi);
const key=new T.DirectionalLight(0xfff0dc,2.0); key.position.set(3.5,8,4.5); key.castShadow=true;
key.shadow.mapSize.set(2048,2048); Object.assign(key.shadow.camera,{left:-4,right:4,top:4,bottom:-4,near:1,far:20}); key.shadow.bias=-.0004; key.shadow.normalBias=.02; key.shadow.radius=4;
scene.add(key);
const rim=new T.DirectionalLight(0x9cc8ff,1.3); rim.position.set(-5,3,-6); scene.add(rim);
const fill=new T.PointLight(0xffa860,.9,30); fill.position.set(4,1.5,6); scene.add(fill);
const iriA=new T.PointLight(0x33ccff,0,40); iriA.position.set(-6,3,-4); scene.add(iriA);
const iriB=new T.PointLight(0xff33aa,0,40); iriB.position.set(6,-1,-3); scene.add(iriB);
/* ---------------- finish switch ---------------- */
let finish='iri';
function applyFinish(){
const iri=finish==='iri';
for(const m of mats){ const u=m.userData;
if(u.hue===null){ continue; }
if(!iri){ m.color.copy(u.nat); m.map=u.mapN; m.roughness=u.rough; m.metalness=u.metal; }
else { m.map=u.mapN?u.mapI:null; m.roughness=Math.min(u.rough,.3); m.metalness=.55; }
m.needsUpdate=true; }
iriA.intensity=iri?1.6:0; iriB.intensity=iri?1.4:0; rim.intensity=iri?.6:1.3;
hairMat.color.set(iri?0x553366:0x2c170b);
}
/* ---------------- behaviour, gait & animation ---------------- */
let walkOn=true, state='walk', stateT=2.5, speed=0, tSpeed=.8, curv=0, tCurv=0, gphase=0, heading=0;
const worldPos={x:0,z:0}; let wingOpen=0, wingTarget=0, flutter=0, displayT=0;
function pickState(){
const r=rnd();
if(!walkOn){ state='pause'; tSpeed=0; stateT=rr(2,4); if(r<.25) startDisplay(); return; }
if(r<.38){ state='walk'; tSpeed=rr(.6,1.1); stateT=rr(2.5,5); }
else if(r<.62){ state='run'; tSpeed=rr(2.2,3.1); stateT=rr(1.2,2.4); }
else if(r<.88){ state='pause'; tSpeed=0; stateT=rr(1.5,3.5); }
else { state='pause'; tSpeed=0; stateT=4; startDisplay(); }
tCurv=rr(-.35,.35);
}
function startDisplay(){ displayT=3.4; }
const DUTY=.62;
function updateGait(dt){
const v=speed, w=v*curv, stride=clamp(.45+.12*v,.45,.85);
let rate=v*DUTY/stride;
const inSwing=legs.some(L=>L.swinging);
if(v<.08 && inSwing) rate=Math.max(rate,1.8);
gphase=(gphase+rate*dt)%1;
const Tst=DUTY/Math.max(rate,.001);
const ca=Math.cos(-w*dt), sa=Math.sin(-w*dt);
for(const L of legs){
const p=(gphase+L.phase)%1, sw=p>=DUTY && rate>0;
if(!sw){
if(L.swinging){ L.swinging=false; L.toe.copy(L.target); L.toe.y=0; }
const x=L.toe.x, z=L.toe.z; L.toe.x=x*ca+z*sa; L.toe.z=-x*sa+z*ca-v*dt;
} else {
if(!L.swinging){ L.swinging=true; L.lift.copy(L.toe); }
const s=(p-DUTY)/(1-DUTY), half=Math.min(.6,v*Tst*.5), ang=w*Tst*.5, c=Math.cos(ang), sn=Math.sin(ang);
L.target.set(L.home.x*c+L.home.z*sn, 0, -L.home.x*sn+L.home.z*c+half);
L.toe.lerpVectors(L.lift,L.target,smooth(s)); L.toe.y=Math.sin(Math.PI*s)*(.13+.04*Math.min(v,2));
}
}
heading+=w*dt; worldPos.x+=Math.sin(heading)*v*dt; worldPos.z+=Math.cos(heading)*v*dt;
}
const _t=V3(), _hd=V3(), _ank=V3(), _d=V3(), _w=V3(), _kn=V3(), _a2=V3(), _toe=V3();
function solveLegs(){
body.updateMatrixWorld(true);
for(const L of legs){
const {a,b,tl}=L.D;
_toe.copy(L.toe); roach.localToWorld(_toe); body.worldToLocal(_toe);
_hd.set(_toe.x-L.tro.x,0,_toe.z-L.tro.z).normalize();
const inc=.45+(L.swinging?.25*Math.sin(Math.PI*clamp(L.toe.y/.17,0,1)):0);
_ank.copy(_toe).addScaledVector(_hd,-tl*Math.cos(inc)); _ank.y+=tl*Math.sin(inc);
_d.subVectors(_ank,L.tro); let c=_d.length(); _d.divideScalar(c); c=clamp(c,Math.abs(a-b)+.03,(a+b)*.995);
_w.set(_hd.x*.4,1,_hd.z*.4+.15); _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);
}
}
const cam={dist:7.2,yaw:.75,pitch:.38,tYaw:.75,tPitch:.38,tDist:7.2,auto:0};
const reduce=matchMedia('(prefers-reduced-motion: reduce)').matches;
let dragging=false;
function fitCam(){ const w=innerWidth; camera.fov=w<480?56:w<768?48:40; camera.aspect=innerWidth/innerHeight; camera.updateProjectionMatrix(); if(w<480) cam.tDist=Math.max(cam.tDist,9); }
fitCam();
function applyCamera(){
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=clamp(cam.pitch,.04,1.4);
camera.position.set(Math.sin(y)*Math.cos(p)*cam.dist, Math.sin(p)*cam.dist+.35, Math.cos(y)*Math.cos(p)*cam.dist);
camera.lookAt(0,.35,-.1);
}
const clock=new T.Clock(); let time=0;
function frame(){
requestAnimationFrame(frame);
const dt=Math.min(clock.getDelta(),1/20); time+=dt; const t=time;
stateT-=dt; if(stateT<=0) pickState();
speed+=(tSpeed-speed)*(1-Math.exp(-dt*(tSpeed>speed?5:3)));
curv+=(tCurv-curv)*(1-Math.exp(-dt*1.2));
updateGait(dt);
// wing display
if(displayT>0){ displayT-=dt; wingTarget=displayT>.6?1:0; flutter=displayT>.9&&displayT<2.4?1:0; } else { wingTarget=0; flutter=0; }
wingOpen+=(wingTarget-wingOpen)*(1-Math.exp(-dt*(wingTarget?4:3)));
for(const W of wings){ const o=wingOpen, s=W.s, f=flutter*Math.sin(t*70+s)*.12*o;
W.tp.rotation.set(o*.32+f*.2, -s*o*.55, s*(o*.55+f*.3));
W.hp.visible=o>.03; W.hp.rotation.set(o*.22, -s*o*1.05, s*(o*.25+f)); W.hp.scale.x=lerp(.12,1,smooth(clamp(o*1.3-.2,0,1))); }
// floor treadmill (the world moves under a stationary roach)
const P=TILE, px=((worldPos.x%P)+P)%P, pz=((worldPos.z%P)+P)%P, ch=Math.cos(-heading), sh=Math.sin(-heading);
floorPivot.rotation.y=-heading; floorPivot.position.set(-(px*ch+pz*sh),0,-(-px*sh+pz*ch));
// body bob, roll, breathing
const busy=Math.min(1,speed);
body.position.y=BODY_Y-.02*clamp(speed-1,0,1)+.012*Math.cos(gphase*Math.PI*4)*busy;
body.rotation.z=.025*Math.sin(gphase*Math.PI*2)*busy + curv*speed*.02;
body.rotation.x=-.01*Math.sin(gphase*Math.PI*4)*busy + .015*Math.sin(t*.8)*(1-busy);
body.rotation.y=.03*Math.sin(gphase*Math.PI*2)*busy;
const breathe=Math.sin(t*2.1);
tergites.forEach((g,i)=>{ g.scale.y=1+.035*breathe*(i/8); g.scale.x=1+.012*breathe; });
abdomen.rotation.x=-.03*breathe*(1-busy)-.04*wingOpen;
cerci.forEach(({g,s})=>{ g.rotation.y=s*.06*Math.sin(t*1.7+s); g.rotation.x=.05*Math.sin(t*2.3+s*2); });
// antennae: wandering exploration + travelling wave + drag when running/turning
for(const A of antennae){
if(t>A.next){ A.ty=rr(-.35,.45)*A.s; A.tp=rr(-.25,.3); A.next=t+rr(.6,2.4); }
const run=clamp(speed/3,0,1);
A.yaw+=((A.ty*(1-run*.7))-A.yaw)*(1-Math.exp(-dt*2.5)); A.pitch+=((A.tp*(1-run)-run*.15)-A.pitch)*(1-Math.exp(-dt*2.5));
const J=A.joints; J[0].rotation.y=A.yaw; J[0].rotation.x=A.pitch;
for(let i=2;i<J.length;i++){ const u=i/J.length, j=J[i];
j.rotation.x=j.userData.bx+Math.sin(t*2.6-i*.32+A.s)*.018*u+run*.006;
j.rotation.y=j.userData.by+Math.sin(t*1.9-i*.28+A.s*1.7)*.022*u - curv*speed*.004*u - A.s*run*.004; }
}
palps.forEach(({joints,s,pi})=>joints.forEach((j,k)=>{ j.rotation.x=j.userData.b+Math.sin(t*(pi?7:5)+s+k*.6)*(.12+.04*k)*(1-busy*.6); }));
mandibles.forEach(({mg,s})=>{ mg.rotation.y=s*(.15+.15*Math.max(0,Math.sin(t*6)))*(1-busy); });
solveLegs();
if(finish==='iri'){ const h=(t*.05)%1; for(const m of mats){ const u=m.userData; if(u.hue===null) continue; m.color.setHSL((h+u.hue+10)%1,.85,u.light).convertSRGBToLinear(); } }
if(!dragging && !reduce) cam.auto+=dt*(.09+speed*.01);
applyCamera();
renderer.render(scene,camera);
}
/* ---------------- controls ---------------- */
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,3.2,16); pinch=d; return; }
cam.tYaw-=(e.clientX-lx)*.006; cam.tPitch=clamp(cam.tPitch+(e.clientY-ly)*.005,.04,1.4); 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*.006,3.2,16); },{passive:false});
addEventListener('resize',()=>{ renderer.setSize(innerWidth,innerHeight); fitCam(); });
applyFinish();
frame();
}
</script>
</body>
</html>