• 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

GIRAFFE WEEVIL 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: Giraffe-Necked Weevil</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% 42%, #0c1a10 0%, #060b07 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); };
let seed = 8080;
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(0x050906, 0.05);
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,'#1c2418'); g.addColorStop(1,'#040804');
  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',.25],[400,400,300,'#3aff7a',.18]].forEach(b=>{
    const rg=x.createRadialGradient(b[0],b[1],0,b[0],b[1],b[2]); rg.addColorStop(0,b[3]); rg.addColorStop(1,'rgba(0,0,0,0)'); x.globalAlpha=b[4]; x.fillStyle=rg; x.beginPath(); x.arc(b[0],b[1],b[2],0,7); x.fill(); });
  const tex=new T.CanvasTexture(c); tex.mapping=T.EquirectangularReflectionMapping; tex.encoding=T.sRGBEncoding;
  const pm=new T.PMREMGenerator(renderer); pm.compileEquirectangularShader(); scene.environment=pm.fromEquirectangular(tex).texture; pm.dispose(); tex.dispose();
})();

/* =====================================================================
   IRIDESCENT MATERIAL
   Hue cycles with time and shifts with viewing angle (thin-film look).
   Data textures: R = brightness, G = hue offset, B = film strength.
   ===================================================================== */
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??.26, metalness:o.metal??.55, side:o.side??T.FrontSide, envMapIntensity:o.env??1.35 });
  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} };
  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;\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`).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.8);
    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, 30, 22), SPH_LO = new T.SphereGeometry(1, 10, 8);
const CONE = new T.ConeGeometry(1,1,5).translate(0,.5,0);
const HAIR = new T.CylinderGeometry(0, 1, 1, 3, 1).translate(0,.5,0);
const _q = new T.Quaternion(), _m = new T.Matrix4(), _x=V3(), _y=V3(), _z=V3();
function mesh(geo,mat,parent,pos,scl){ const m=new T.Mesh(geo,mat); if(pos) m.position.copy(pos); if(scl!==undefined) (typeof scl==='number'?m.scale.setScalar(scl):m.scale.copy(scl)); m.castShadow=true; m.receiveShadow=true; parent&&parent.add(m); return m; }
function orient(o,from,to,up){ _x.subVectors(to,from).normalize(); _z.crossVectors(_x,up).normalize(); _y.crossVectors(_z,_x); _m.makeBasis(_x,_y,_z); o.quaternion.setFromRotationMatrix(_m); o.position.copy(from); }
function instanced(parent,geo,mat,list){ const im=new T.InstancedMesh(geo,mat,list.length), m4=new T.Matrix4();
  list.forEach(([p,d,len,rad],i)=>{ _q.setFromUnitVectors(UP,d.clone().normalize()); m4.compose(p,_q,V3(rad,len,rad)); im.setMatrixAt(i,m4); });
  im.instanceMatrix.needsUpdate=true; im.castShadow=true; parent.add(im); return im; }
const randDir = () => V3(rr(-1,1),rr(-1,1),rr(-1,1)).normalize();
function gridGeo(NU,NV,fn){ const pos=[],uv=[],idx=[];
  for(let i=0;i<=NU;i++) for(let j=0;j<=NV;j++){ const u=i/NU, v=j/NV, p=fn(u,v); pos.push(p[0],p[1],p[2]); uv.push(u,v); }
  for(let i=0;i<NU;i++) for(let j=0;j<NV;j++){ const a=i*(NV+1)+j,b=a+NV+1; idx.push(a,b,a+1,b,b+1,a+1); }
  const g=new T.BufferGeometry(); g.setAttribute('position',new T.Float32BufferAttribute(pos,3)); g.setAttribute('uv',new T.Float32BufferAttribute(uv,2)); g.setIndex(idx); g.computeVertexNormals(); return g; }

/* =====================================================================
   PATTERN TEXTURES
   ===================================================================== */
// elytron (u across: suture → margin, v along): rows of deep punctures in striae, shoulder bump shading
const elyC = makeCanvas(256,512,(g,W,H)=>{ g.fillStyle=D(.56,.0,1); g.fillRect(0,0,W,H);
  for(let k=1;k<=9;k++){ const x=k/10*W; g.fillStyle=D(.42,.0,1); g.fillRect(x-3,0,6,H);
    for(let y=6;y<H;y+=rr(11,15)){ g.fillStyle=D(.12,.02,.6); g.beginPath(); g.ellipse(x+rr(-1,1),y,3.4,4.2,0,0,7); g.fill(); } }
  g.fillStyle=D(.18,.0,.7); g.fillRect(0,0,7,H);                                           // suture
  let gr=g.createLinearGradient(W*.8,0,W,0); gr.addColorStop(0,D(.56,0,1,0)); gr.addColorStop(1,D(.3,.02,.8)); g.fillStyle=gr; g.fillRect(W*.8,0,W*.2,H);
  g.globalCompositeOperation='multiply'; for(let i=0;i<4000;i++){ const v=Math.round(rr(200,255)); g.fillStyle=`rgb(${v},255,255)`; g.fillRect(rnd()*W,rnd()*H,2,2); } });
const elyT=dataTex(elyC), elyB=bumpOf(elyC);
// fine punctation for the black chitin
const puncC = makeCanvas(256,256,(g,W,H)=>{ g.fillStyle=D(.5,0,1); g.fillRect(0,0,W,H); for(let i=0;i<2200;i++){ g.fillStyle=D(rr(.3,.42),0,.9); g.beginPath(); g.arc(rnd()*W,rnd()*H,rr(1,2.2),0,7); g.fill(); } });
const puncT=dataTex(puncC), puncB=bumpOf(puncC); puncT.wrapS=puncT.wrapT=puncB.wrapS=puncB.wrapT=T.RepeatWrapping;
const eyeC = makeCanvas(128,128,(g,W,H)=>{ g.fillStyle=D(.2,.55,1); g.fillRect(0,0,W,H); const r=2.6;
  for(let row=0;row*r*1.5<H+r;row++) for(let col=0;col*r*1.75<W+r;col++){ const x=col*r*1.75+(row%2)*r*.87, y=row*r*1.5; g.fillStyle=D(.45,.6,1); g.beginPath(); g.arc(x,y,r*.6,0,7); g.fill(); } });
const eyeT=dataTex(eyeC), eyeB=bumpOf(eyeC);

/* =====================================================================
   THE WEEVIL
   ===================================================================== */
const weevil=new T.Group(); scene.add(weevil);
const body=new T.Group(); weevil.add(body);
const BODY_Y=.3; body.position.y=BODY_Y;

const M = {
  ink:   iriMat({pat:puncT,bump:puncB,bumpScale:.0015,hue:.62,light:.2,rough:.2,metal:.65}),
  ink2:  iriMat({hue:.7,light:.24,iri:.9,rough:.22,metal:.6}),
  ely:   iriMat({pat:elyT,bump:elyB,bumpScale:.004,hue:.98,light:.55,rough:.2,metal:.55,side:DS}),
  eye:   iriMat({pat:eyeT,bump:eyeB,bumpScale:.001,hue:.5,light:.35,rough:.06,metal:.7,env:1.8,film:.7}),
  joint: iriMat({hue:.55,light:.3,iri:.8,rough:.3}),
  pad:   iriMat({hue:.1,light:.55,iri:.6,rough:.5}),
  seta:  iriMat({hue:.1,light:.62,sat:.4,iri:.4,rough:.5}),
  claw:  new T.MeshStandardMaterial({color:lin(0x120c0a),roughness:.3,metalness:.5}),
};

// underside, metasternum, pronotum
mesh(SPH, M.ink2, body, V3(0,.0,-.42), V3(.33,.2,.5));
mesh(SPH, M.ink, body, V3(0,.06,.18), V3(.2,.19,.27));
mesh(SPH, M.ink2, body, V3(0,-.06,.1), V3(.17,.1,.22));
mesh(SPH, M.ink2, body, V3(0,.1,-.08), V3(.3,.2,.16));                      // mesothorax filling the elytral base
// elytra: two half-shells (pole along the body), striae of punctures, scutellum, humeral shoulders
const elytra=[];
[1,-1].forEach(s=>{
  const hinge=new T.Group(); hinge.position.set(0,.2,-.02); body.add(hinge);
  const side=new T.Group(); side.scale.x=s; hinge.add(side);
  const g=new T.SphereGeometry(1,32,24,Math.PI/2,Math.PI*.86,0,Math.PI*.62).rotateX(-Math.PI/2);
  const sh=mesh(g, M.ely, side, V3(.004,-.06,-.42+.02), V3(.36,.32,.52)); sh.material.side=DS;
  elytra.push({hinge,s});
});
mesh(new T.ConeGeometry(.045,.1,3), M.ink, body, V3(0,.27,.0)).rotation.x=-Math.PI/2;   // scutellum
// sparse setae along elytral edges
instanced(body, HAIR, M.seta, Array.from({length:80},()=>{ const a=rr(-.9,.9), z=rr(-.9,-.1); return [V3(Math.sin(a)*.35,.12+Math.cos(a)*.28,z), V3(Math.sin(a),Math.cos(a),-.6), rr(.02,.04), .003]; }));

// neck: pronotal extension (lower) + elongated head capsule (upper), solved as a 2-bone chain
const NECK={root:V3(0,.2,.4),L1:.66,L2:.5};
const neckLo=new T.Group(), neckUp=new T.Group(); body.add(neckLo,neckUp);
mesh(alongX(NECK.L1,t=>.075*(1-.38*t)+.006*Math.sin(t*20)*.2+(t<.12?.03*(1-t/.12):0),16,14), M.ink, neckLo);
mesh(SPH, M.ink2, neckLo, V3(NECK.L1,0,0), .05);
mesh(alongX(NECK.L2,t=>.044*(1-.3*t)+(t>.85?.012*(t-.85)/.15:0),14,12), M.ink2, neckUp);
instanced(neckLo, HAIR, M.seta, Array.from({length:30},()=>{ const x=rr(.05,NECK.L1), a=rnd()*TAU; return [V3(x,Math.cos(a)*.06,Math.sin(a)*.06),V3(.4,Math.cos(a),Math.sin(a)),rr(.015,.03),.0025]; }));
// head: eyes, rostrum, mandibles, elbowed clubbed antennae on the rostrum
const head=new T.Group(); body.add(head);
mesh(SPH, M.ink, head, V3(0,0,.05), V3(.065,.062,.09));
[-1,1].forEach(s=>{ mesh(SPH, M.eye, head, V3(s*.056,.012,.07), V3(.026,.03,.03)); mesh(SPH_LO, new T.MeshStandardMaterial({color:0xffffff,roughness:.05,envMapIntensity:2}), head, V3(s*.068,.03,.085), .006); });
const rost=new T.Group(); rost.position.set(0,-.01,.12); rost.rotation.x=.25; head.add(rost);
mesh(alongZ(.13,u=>.028*(1-.35*u)+(u>.85?.006:0),10,6), M.ink2, rost);
const mands=[]; [-1,1].forEach(s=>{ const mg=new T.Group(); mg.position.set(s*.01,0,.13); rost.add(mg); mesh(CONE, M.claw, mg, null, V3(.008,.025,.008)).rotation.set(Math.PI/2-.2,0,s*.5); mands.push({mg,s}); });
const antennae=[];
[-1,1].forEach(s=>{ const r=new T.Group(); r.position.set(s*.024,.008,.06); rost.add(r); r.rotation.set(-.5,s*.7,0);
  mesh(alongZ(.11,u=>.006*(1+.4*u),6,3), M.ink2, r);
  const f=new T.Group(); f.position.z=.11; r.add(f); f.rotation.set(.9,s*.2,0); let p=f; const J=[];
  for(let k=0;k<10;k++){ const j=new T.Group(); j.rotation.x=.05; p.add(j); const club=k>=7, L=club?.022:.016, rd=club?.012:.0055;
    mesh(alongZ(L,u=>rd*(.8+.2*Math.sin(u*Math.PI)),6,3), club?M.joint:M.ink2, j); const n=new T.Group(); n.position.z=L; j.add(n); p=n; J.push(j); }
  antennae.push({r,f,J,s}); });

// legs: club-shaped femora, hooked tibiae, bilobed spongy tarsal pads
const legs=[];
function buildLeg(D,s){
  const hip=V3(s*D.hip[0],D.hip[1],D.hip[2]), tro=V3(s*D.tro[0],D.tro[1],D.tro[2]);
  const cg=new T.Group(); body.add(cg); orient(cg,hip,tro,UP); mesh(alongX(hip.distanceTo(tro)+.02,t=>.04*(1-.3*t)+.012,8,5), M.ink2, cg);
  const fem=new T.Group(), tib=new T.Group(), tar=new T.Group(); body.add(fem,tib,tar);
  mesh(alongX(D.a,t=>.016+.03*Math.exp(-((t-.68)**2)/.04),12,14), M.ink, fem);
  mesh(alongX(D.b,t=>.014*(1-.15*t)+.004,8,8), M.ink2, tib);
  instanced(tib, CONE, M.claw, [[V3(D.b*.98,-.005,0),V3(.4,-1,0),.04,.007]]);                       // tibial uncus
  instanced(tib, HAIR, M.seta, Array.from({length:14},()=>{ const x=rr(.3,1)*D.b; return [V3(x,-.012,rr(-.008,.008)),V3(.6,-1,rr(-.3,.3)),rr(.01,.025),.002]; }));
  let x=0; [.3,.22,.24,.24].forEach((f,k)=>{ const L=D.tl*f; mesh(alongX(L,u=>(k===2?.016:.01)*(.85+.15*u),6,3), M.ink2, tar, V3(x,0,0));
    if(k<3) mesh(SPH_LO, M.pad, tar, V3(x+L*.5,-.01,0), V3(L*.45,.006,k===2?.02:.012)); x+=L; });
  [-1,1].forEach(cs=>{ const c=mesh(alongX(.025,u=>.004*(1-u)+.0006,5,3), M.claw, tar, V3(x,0,cs*.004)); c.rotation.set(0,cs*.4,-1.0); });
  const L={D,s,tro,fem,tib,tar,home:V3(s*D.home[0],0,D.home[1]),toeW:V3(),lift:V3(),target:V3(),step:-1,group:0}; legs.push(L); return L;
}
const LEGDEF=[
  {hip:[.1,-.08,.24],tro:[.15,-.12,.26],a:.3,b:.3,tl:.16,home:[.4,.52]},
  {hip:[.14,-.08,-.08],tro:[.2,-.12,-.1],a:.32,b:.32,tl:.17,home:[.5,-.08]},
  {hip:[.16,-.06,-.36],tro:[.22,-.1,-.4],a:.34,b:.36,tl:.18,home:[.46,-.68]},
];
LEGDEF.forEach((D,i)=>[-1,1].forEach(s=>{ const L=buildLeg(D,s); L.group=((i%2===0)===(s<0))?0:1; }));

/* =====================================================================
   THE TREE: a twig of Dichaetanthera; the work leaf rolls into a cradle
   ===================================================================== */
const leafC = makeCanvas(256,1024,(g,W,H)=>{
  let gr=g.createLinearGradient(0,0,W,0); gr.addColorStop(0,'#1f4a1a'); gr.addColorStop(.5,'#3a7a2a'); gr.addColorStop(1,'#1f4a1a'); g.fillStyle=gr; g.fillRect(0,0,W,H);
  for(let i=0;i<3000;i++){ g.fillStyle=`rgba(${rnd()<.5?'10,30,8':'120,170,80'},${rr(.03,.08)})`; g.fillRect(rnd()*W,rnd()*H,rr(2,6),rr(2,6)); }
  g.strokeStyle='rgba(190,220,140,.85)'; g.lineWidth=6; g.beginPath(); g.moveTo(W/2,0); g.lineTo(W/2,H); g.stroke();
  // melastome leaves: strong parallel arching veins + fine ladder cross-veins
  [-.33,-.18,.18,.33].forEach(o=>{ g.strokeStyle='rgba(170,210,120,.6)'; g.lineWidth=3; g.beginPath(); g.moveTo(W/2,H*.98); g.bezierCurveTo(W*(.5+o*1.4),H*.7,W*(.5+o*1.4),H*.3,W/2,H*.02); g.stroke(); });
  for(let y=10;y<H;y+=rr(14,22)){ g.strokeStyle=`rgba(150,200,110,${rr(.05,.12)})`; g.lineWidth=1; g.beginPath(); g.moveTo(W*.1,y); g.lineTo(W*.9,y+4); g.stroke(); }
  for(let i=0;i<6;i++){ const x=rr(.2,.8)*W, y=rr(.1,.9)*H, r=rr(4,10); g.fillStyle='rgba(120,90,30,.5)'; g.beginPath(); g.arc(x,y,r,0,7); g.fill(); } });
const leafT=new T.CanvasTexture(leafC); leafT.encoding=T.sRGBEncoding; leafT.anisotropy=ANISO;
const leafMat=new T.MeshPhysicalMaterial({map:leafT,roughness:.45,clearcoat:.6,clearcoatRoughness:.3,side:DS});
const LEAF={L:5,W:.9,R0:.22};
const leafHalf = b => LEAF.W*Math.pow(Math.sin(Math.PI*clamp((b/LEAF.L)*.95+.05,0,1)),.6)*(1-.12*b/LEAF.L);
const leafY = x => .07*Math.abs(x);
// position on the leaf: b = distance from the base, v in [-1,1] across; rolled from the tip down to contact bc
function leafPoint(b,v,len,rolled,out){
  const w=leafHalf(b)*v, bc=len-rolled; let x=w, y=leafY(w)+.015*Math.sin(b*3.1+v), z=b;
  if(b>bc){ const arc=b-bc; let phi=0, r=LEAF.R0, acc=0; const n=24; for(let i=0;i<n;i++){ r=LEAF.R0*Math.max(.32,1-.055*phi); const dphi=(arc/n)/r; phi+=dphi; acc+=arc/n; }
    z=bc+r*Math.sin(phi); y=r-r*Math.cos(phi)+leafY(w)*Math.max(0,1-phi); }
  return out.set(x,y,z);
}
const NU=90, NV=14;
function makeLeafGeo(){ const g=gridGeo(NU,NV,()=>[0,0,0]); g.attributes.position.setUsage(T.DynamicDrawUsage); return g; }
function fillLeaf(geo,len,rolled,collapseBelow){
  const p=geo.attributes.position, uv=geo.attributes.uv, tmp=V3(), bc=len-rolled; let k=0;
  for(let i=0;i<=NU;i++){ const b=i/NU*len; for(let j=0;j<=NV;j++){ const v=j/NV*2-1;
    leafPoint(collapseBelow!==undefined&&b<collapseBelow?collapseBelow:b,v,len,rolled,tmp); p.setXYZ(k,tmp.x,tmp.y,tmp.z); uv.setXY(k,j/NV,b/LEAF.L); k++; } }
  p.needsUpdate=true; uv.needsUpdate=true; geo.computeVertexNormals(); geo.computeBoundingSphere();
}
const leafG=new T.Group(); scene.add(leafG);
const workGeo=makeLeafGeo(); const workLeaf=mesh(workGeo,leafMat,leafG);
let cradle=null, cradleV=V3(), cradleSpin=V3(), cradleLife=0;
// twig, petiole, other leaves (two with finished cradles), dangling tendrils
(function(){
  const barkC=makeCanvas(128,512,(g,W,H)=>{ g.fillStyle='#3a2a1c'; g.fillRect(0,0,W,H); for(let i=0;i<120;i++){ g.strokeStyle=`rgba(${rnd()<.5?'20,12,6':'90,70,50'},.5)`; 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<60;i++){ g.fillStyle='rgba(160,150,110,.45)'; g.beginPath(); g.ellipse(rnd()*W,rnd()*H,2,4,0,0,7); g.fill(); } });
  const bt=new T.CanvasTexture(barkC); bt.encoding=T.sRGBEncoding; bt.wrapS=bt.wrapT=T.RepeatWrapping; bt.repeat.set(1,6);
  const bark=new T.MeshStandardMaterial({map:bt,bumpMap:bt,bumpScale:.02,roughness:.85});
  const twig=new T.CatmullRomCurve3([V3(-9,-.9,-.6),V3(-3,-.45,-.4),V3(0,-.3,-.35),V3(3,-.4,-.3),V3(9,-1.1,-.5)]);
  mesh(new T.TubeGeometry(twig,80,.12,12,false),bark,scene);
  mesh(new T.TubeGeometry(new T.CatmullRomCurve3([V3(0,-.3,-.35),V3(0,-.12,-.2),V3(0,-.02,0)]),12,.045,8,false),bark,scene);
  const other=[[-2.4,-.42,-.38,2.3,-.5,0],[2.3,-.38,-.3,-2.2,-.4,1.8],[-4.6,-.6,-.45,2.7,-.65,0],[4.8,-.75,-.4,-2.6,-.7,2.4],[-1,-.33,-.37,Math.PI+.4,-.35,0]];
  other.forEach(([x,y,z,yaw,pitch,roll])=>{ const g=new T.Group(); g.position.set(x,y,z); g.rotation.set(pitch,yaw,0,'YXZ'); scene.add(g);
    const geo=makeLeafGeo(); fillLeaf(geo,LEAF.L*rr(.75,.95),roll); mesh(geo,leafMat,g); });
})();

// glowing spores / bokeh
const motes=(()=>{ const N=220,pos=new Float32Array(N*3); for(let i=0;i<N;i++){ pos[i*3]=rr(-8,8); pos[i*3+1]=rr(-3,5); pos[i*3+2]=rr(-8,8); }
  const g=new T.BufferGeometry(); g.setAttribute('position',new T.BufferAttribute(pos,3));
  const sp=new T.CanvasTexture(makeCanvas(32,32,x=>{ const gr=x.createRadialGradient(16,16,0,16,16,16); gr.addColorStop(0,'rgba(200,255,200,1)'); gr.addColorStop(1,'rgba(0,0,0,0)'); x.fillStyle=gr; x.fillRect(0,0,32,32); }));
  const p=new T.Points(g,new T.PointsMaterial({size:.06,map:sp,transparent:true,depthWrite:false,blending:T.AdditiveBlending,opacity:.45})); scene.add(p); return p; })();

/* lights */
scene.add(new T.HemisphereLight(0xffffff,0x141020,.55));
const key=new T.DirectionalLight(0xffffff,1.5); key.position.set(4,8,6); 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:25}); key.shadow.bias=-.0004; key.shadow.normalBias=.02; key.shadow.radius=3; scene.add(key);
const rim=new T.PointLight(0x33ccff,1.6,60); rim.position.set(-6,3,-4); scene.add(rim);
const rim2=new T.PointLight(0xff7733,1.3,60); rim2.position.set(6,-1,-3); scene.add(rim2);
const glint=new T.PointLight(0xffffff,1.0,40); glint.position.set(2,4,8); scene.add(glint);

/* =====================================================================
   BEHAVIOUR: walk out to the leaf tip → grip it and haul the leaf into a roll
              with alternating front-leg strokes (the roll only turns while a
              foot is pulling) → crane-neck display → snip the cradle free →
              leaf regrows → repeat
   ===================================================================== */
const st={mode:'walk',t:0,dur:99}; let len=LEAF.L, rolled=0, wz=.9, flick=0, nextFlick=5, rollRate=0, press=0;
const RMAX=2.45, D_ROLL=.74, R0=LEAF.R0, RR=R0+.025, PSI0=-.6, PSI1=.95;
const _t=V3(),_hd=V3(),_ank=V3(),_d=V3(),_w=V3(),_kn=V3(),_a2=V3(),_toe=V3(),_hw=V3(),_nk=V3(),_ne=V3(),_rw=V3();
function homeWorld(L,out){ out.copy(L.home); body.localToWorld(out); out.y=leafY(out.x); return out; }
weevil.position.set(0,0,wz); weevil.updateMatrixWorld(true);
legs.forEach(L=>{ homeWorld(L,L.toeW); L.front=L.D===LEGDEF[0]; L.gb=0; L.psi=PSI0; L.sw=-1; L.psiStart=0; });
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;
}
// a front foot's grip point on the roll surface (psi measured from the top, positive toward the weevil)
function rollPoint(L,psi,r,out){ const bc=len-rolled, fx=Math.max(.12,Math.min(.26,leafHalf(Math.min(LEAF.L-.05,bc+.25))*.75));
  return out.set(L.s*fx, R0+r*Math.cos(psi), bc-r*Math.sin(psi)); }

function update(dt,t){
  st.t+=dt; const go=(m,d)=>{ st.mode=m; st.t=0; st.dur=d; };
  let headTarget, lookAt, wzT=wz;
  const front=legs.filter(L=>L.front);

  if(st.mode==='walk'){                                    // stroll out to the tip
    wzT=len-D_ROLL; const step=Math.sign(wzT-wz)*Math.min(Math.abs(wzT-wz),dt*.32); wz+=step;
    headTarget=V3(.12*Math.sin(t*.8), .95+.06*Math.sin(t*2), wz+.95); lookAt=V3(0,0,wz+2.2);
    if(Math.abs(wzT-wz)<.005){ go('roll',99); front.forEach((L,i)=>{ L.psi=i?PSI0:(PSI0+PSI1)/2; L.sw=-1; }); }
  }
  else if(st.mode==='roll'){
    // front legs: stance = foot rides the roll surface as it turns; swing = reach back over the top
    let pulling=0;
    front.forEach(L=>{ if(L.gb<.95) return;
      if(L.sw<0){ L.psi+=rollRate/R0*dt; pulling++; if(L.psi>=PSI1){ L.sw=0; L.psiStart=L.psi; } }
      else { L.sw+=dt/.45; if(L.sw>=1){ L.sw=-1; L.psi=PSI0; press=1; } } });
    rollRate+=((pulling&&rolled<RMAX?.17:0)-rollRate)*(1-Math.exp(-dt*8));
    rolled=Math.min(RMAX,rolled+rollRate*dt);
    wzT=len-rolled-D_ROLL; wz+=(wzT-wz)*(1-Math.exp(-dt*6));
    press*=Math.exp(-dt*3);
    const bc=len-rolled;
    headTarget=V3(.06*Math.sin(t*.9), 2*R0+.3-.1*press, bc+.2+.04*Math.sin(t*1.3)); lookAt=V3(0,2*R0-.05,bc-.02);
    if(rolled>=RMAX && rollRate<.01){ go('display',6); nextFlick=1.5; }
  } else if(st.mode==='display'){
    const bob=Math.sin(t*1.9), sway=Math.sin(t*.6);
    headTarget=V3(.25*sway, 1.25+.12*bob, wz+.75+.1*Math.sin(t*.8)); lookAt=headTarget.clone().add(V3(Math.sin(t*.5)*.6,-.15,.6));
    if(st.t>nextFlick){ flick=1; nextFlick=99; }
    if(st.t>=st.dur) go('snip',2.2);
  } else if(st.mode==='snip'){
    const bc=len-rolled;
    headTarget=V3(.06*Math.sin(t*6), .16, bc-R0-.1); lookAt=V3(0,.02,bc-R0+.05);
    if(st.t>=1.4 && !cradle){ // the cradle is cut free and drops away
      const g=workGeo.clone(); fillLeaf(g,len,rolled,bc);
      const m=leafMat.clone(); m.transparent=true; cradle=mesh(g,m,leafG); cradleV.set(rr(-.3,.3),.3,.4); cradleSpin.set(rr(-1,1),rr(-1,1),rr(-1,1)); cradleLife=3.5;
      len=bc; rolled=0; }
    if(st.t>=st.dur) go('regrow',4.5);
  } else if(st.mode==='regrow'){
    len=Math.min(LEAF.L, len+dt*RMAX/4);
    headTarget=V3(.2*Math.sin(t*.7), 1.1+.08*Math.sin(t*2.2), wz+.85); lookAt=headTarget.clone().add(V3(Math.sin(t*.4)*.5,-.2,.6));
    if(st.t>=st.dur){ len=LEAF.L; go('walk',99); }
  }
  fillLeaf(workGeo,len,rolled);
  if(cradle){ cradleLife-=dt; cradleV.y-=3*dt; cradle.position.addScaledVector(cradleV,dt); cradle.rotation.x+=cradleSpin.x*dt; cradle.rotation.z+=cradleSpin.z*dt;
    cradle.material.opacity=clamp(cradleLife/1.5,0,1); if(cradleLife<=0){ leafG.remove(cradle); cradle.geometry.dispose(); cradle=null; } }

  const prevZ=weevil.position.z; weevil.position.set(0,0,wz); const moving=Math.abs(wz-prevZ)>dt*.02;
  weevil.updateMatrixWorld(true);

  // legs: ground feet stay planted and step when they drift; front feet grip the roll while rolling
  for(const L of legs){
    if(L.front){ L.gb+=((st.mode==='roll'?1:0)-L.gb)*(1-Math.exp(-dt*5)); }
    const gripping=L.front&&L.gb>.01;
    if(gripping){ homeWorld(L,L.toeW); L.step=-1; continue; }
    if(L.step>=0){ L.step+=dt/.22; const s=smooth(L.step); L.toeW.lerpVectors(L.lift,L.target,s); L.toeW.y=lerp(L.lift.y,leafY(L.toeW.x),s)+Math.sin(Math.PI*Math.min(1,L.step))*.07; if(L.step>=1){ L.step=-1; L.toeW.y=leafY(L.toeW.x); } }
    else { homeWorld(L,_hw); const busy=legs.some(o=>o.step>=0&&o.group!==L.group&&!o.front); if(!busy&&L.toeW.distanceTo(_hw)>.08){ L.step=0; L.lift.copy(L.toeW); L.target.copy(_hw).addScaledVector(V3(0,0,Math.sign(_hw.z-L.toeW.z)),.03); } }
  }
  for(const L of legs){ const {a,b,tl}=L.D;
    let foot=L.toeW;
    if(L.front&&L.gb>.01){ const swing=L.sw>=0, s=smooth(Math.max(0,L.sw)), psi=swing?lerp(L.psiStart,PSI0,s):L.psi, r=RR+(swing?.14*Math.sin(Math.PI*s):0);
      rollPoint(L,psi,r,_rw); _toe.lerpVectors(L.toeW,_rw,smooth(L.gb)); _toe.y+=Math.sin(Math.PI*smooth(L.gb))*.12*(L.gb<.98?1:0); foot=_toe.clone(); }
    _toe.copy(foot); body.worldToLocal(_toe); _hd.set(_toe.x-L.tro.x,0,_toe.z-L.tro.z).normalize();
    _ank.copy(_toe).addScaledVector(_hd,-tl*.85); _ank.y+=tl*.45;
    const w=solve2(L.tro,_ank,a,b,V3(L.s*.5,1,0),_kn,_a2);
    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); }

  // neck & head: two-bone chain to the head target; the head aims at what it is working on
  const tgtL=body.worldToLocal(headTarget.clone());
  const nw=solve2(NECK.root,tgtL,NECK.L1,NECK.L2,V3(0,1,-.15),_nk,_ne);
  orient(neckLo,NECK.root,_nk,nw); orient(neckUp,_nk,_ne,nw);
  const lk=body.worldToLocal(lookAt.clone()); _z.subVectors(lk,_ne).normalize(); _x.crossVectors(UP,_z).normalize(); _y.crossVectors(_z,_x);
  _m.makeBasis(_x,_y,_z); const qT=new T.Quaternion().setFromRotationMatrix(_m); head.position.copy(_ne); head.quaternion.slerp(qT,1-Math.exp(-dt*6));

  // body: leans back into each pull; elytra flick; mouthparts; antennae
  flick=Math.max(0,flick-dt*1.2); const pop=Math.sin(Math.min(1,1-flick)*Math.PI)*(flick>0?1:0);
  elytra.forEach(E=>{ E.hinge.rotation.x=-pop*.18; E.hinge.rotation.z=E.s*pop*.12; });
  const pull=st.mode==='roll'?rollRate/.17:0;
  body.position.y=BODY_Y+(moving?.01*Math.sin(t*9):0)+.006*Math.sin(t*1.1)-.02*pull;
  body.rotation.z=(moving?.02*Math.sin(t*5):0)+.01*Math.sin(t*.7)+.02*pull*Math.sin(t*1.6);
  body.rotation.x=-.06*pull+(st.mode==='snip'?.06:-.02);
  const chew=(st.mode==='snip'||(st.mode==='roll'&&press>.3))?Math.max(0,Math.sin(t*9)):0;
  mands.forEach(({mg,s})=>{ mg.rotation.y=s*.4*chew; });
  antennae.forEach(({r,f,J,s},i)=>{ r.rotation.x=-.5+.2*Math.sin(t*3.1+i); r.rotation.y=s*(.7+.15*Math.sin(t*2.3+i*2)); f.rotation.x=.9+.25*Math.sin(t*2.7+i); });

  const mp=motes.geometry.attributes.position; for(let i=0;i<mp.count;i++){ let y=mp.getY(i)+dt*.04; if(y>5) y=-3; mp.setY(i,y); mp.setX(i,mp.getX(i)+Math.sin(t*.3+i)*.002); } mp.needsUpdate=true;
}

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

const clock=new T.Clock(); let time=0;
function frame(){
  requestAnimationFrame(frame);
  const dt=Math.min(clock.getDelta(),1/30); time+=dt; U_TIME.value=time;
  update(dt,time);
  camTarget.lerp(V3(0,.45,wz+.7),1-Math.exp(-dt*1.2));
  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(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.