BRAZILIAN TREEHOPPER SOURCE CODE
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Brazilian Treehopper</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body { height: 100%; overflow: hidden; background: radial-gradient(ellipse at 50% 45%, #10091a 0%, #050309 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, TAU = Math.PI*2, GOLD = Math.PI*(3-Math.sqrt(5));
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 = 777;
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(0x06040b, 0.055);
const camera = new T.PerspectiveCamera(42, innerWidth/innerHeight, 0.03, 200);
(function(){
const c = document.createElement('canvas'); c.width = 1024; c.height = 512;
const x = c.getContext('2d');
const g = x.createLinearGradient(0,0,0,512);
g.addColorStop(0,'#3a2a63'); g.addColorStop(.3,'#1a1030'); g.addColorStop(.5,'#0a0612'); g.addColorStop(.62,'#1c1024'); g.addColorStop(1,'#040208');
x.fillStyle = g; x.fillRect(0,0,1024,512);
[[190,110,210,'#7a55ff',.6],[800,80,230,'#22d3ff',.5],[560,300,280,'#ff3fa4',.34],[960,250,200,'#ffd36e',.3],[80,340,240,'#2affc2',.2],[400,400,300,'#5522ff',.22]].forEach(b=>{
const rg = x.createRadialGradient(b[0],b[1],0,b[0],b[1],b[2]); rg.addColorStop(0,b[3]); rg.addColorStop(1,'rgba(0,0,0,0)');
x.globalAlpha = b[4]; x.fillStyle = rg; x.beginPath(); x.arc(b[0],b[1],b[2],0,7); x.fill(); });
const tex = new T.CanvasTexture(c); tex.mapping = T.EquirectangularReflectionMapping; tex.encoding = T.sRGBEncoding;
const pm = new T.PMREMGenerator(renderer); pm.compileEquirectangularShader();
scene.environment = pm.fromEquirectangular(tex).texture; pm.dispose(); tex.dispose();
})();
/* =====================================================================
IRIDESCENT MATERIAL
Hue cycles with time and shifts with viewing angle (thin-film look).
Data textures: R = brightness, G = hue offset, B = structural colour, A = alpha.
Vertex colours (R) darken pits; uAlpha fades ghost wings.
===================================================================== */
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??.32, metalness:o.metal??.5,
side:o.side??T.FrontSide, envMapIntensity:o.env??1.25, transparent:!!o.transparent, depthWrite:o.depthWrite??true, vertexColors:!!o.vcol });
m.defines = {};
if (o.pat){ m.map = o.pat; m.defines.USE_PAT = ''; }
if (o.bump){ m.bumpMap = o.bump; m.bumpScale = o.bumpScale ?? .002; }
const u = { uTime:U_TIME, uHue:{value:o.hue??0}, uSat:{value:o.sat??.85}, uLight:{value:o.light??.5}, uIri:{value:o.iri??1}, uAlpha:{value:o.alpha??1} };
m.userData.u = u;
m.onBeforeCompile = sh => {
Object.assign(sh.uniforms, u);
sh.fragmentShader = 'uniform float uTime; uniform float uHue; uniform float uSat; uniform float uLight; uniform float uIri; uniform float uAlpha;\n' + HSL_GLSL +
sh.fragmentShader.replace('#include <map_fragment>', `
#ifdef USE_PAT
vec4 patS = texture2D(map, vUv);
#else
vec4 patS = vec4(0.5263, 0.0, 1.0, 1.0);
#endif
diffuseColor.a *= patS.a * uAlpha;`).replace('#include <normal_fragment_maps>', `#include <normal_fragment_maps>
{
float ndv = clamp(abs(dot(normal, normalize(vViewPosition))), 0.0, 1.0);
float iriS = patS.b * uIri;
float h = fract(uTime*0.05 + uHue + patS.g + (1.0-ndv)*0.45*iriS);
float L = uLight * patS.r * 1.9;
#ifdef USE_COLOR
L *= vColor.r;
#endif
L = clamp(L, 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.vcol?'v':'');
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, 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).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; }
// tube swept along a curve with a varying radius
function sweep(curve, rf, N=72, M=14){
const fr=curve.computeFrenetFrames(N,false), pos=[], uv=[], idx=[];
for(let i=0;i<=N;i++){ const t=i/N, p=curve.getPointAt(t), r=rf(t), n=fr.normals[i], b=fr.binormals[i];
for(let j=0;j<=M;j++){ const a=j/M*TAU, c=Math.cos(a), s=Math.sin(a);
pos.push(p.x+r*(c*n.x+s*b.x), p.y+r*(c*n.y+s*b.y), p.z+r*(c*n.z+s*b.z)); uv.push(j/M,t); } }
for(let i=0;i<N;i++) for(let j=0;j<M;j++){ const a=i*(M+1)+j,b=a+M+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 { geo:g, frames:fr };
}
function sweepHairs(curve, rf, frames, N, n, l0, l1){ const out=[]; for(let i=0;i<n;i++){ const t=rr(.02,.98), k=Math.round(t*N), p=curve.getPointAt(t), a=rnd()*TAU;
const d=frames.normals[k].clone().multiplyScalar(Math.cos(a)).addScaledVector(frames.binormals[k],Math.sin(a));
out.push([p.clone().addScaledVector(d,rf(t)*.92), d.clone().addScaledVector(frames.tangents[k],rr(-.1,.5)).add(V3(0,.15,0)), rr(l0,l1), .006]); } return out; }
/* =====================================================================
PATTERN TEXTURES
===================================================================== */
// pronotum base: dense punctures, darker margins
const pronC = makeCanvas(512,256,(g,W,H)=>{ g.fillStyle=D(.5,.06,1); g.fillRect(0,0,W,H);
for(let i=0;i<5200;i++){ const x=rnd()*W,y=rnd()*H; g.fillStyle=D(rr(.3,.42),.04,.75); g.beginPath(); g.arc(x,y,rr(1.2,3),0,7); g.fill(); g.fillStyle=D(.75,.08,1,.6); g.beginPath(); g.arc(x-1,y-1,1,0,7); g.fill(); }
g.fillStyle=D(.3,.04,.7); g.fillRect(0,H*.88,W,H*.12); });
const pronT=dataTex(pronC), pronB=bumpOf(pronC);
// tegmen: clear cells, dark veins, smoky apex, more opaque base
const tegC = makeCanvas(512,160,(g,W,H)=>{
g.clearRect(0,0,W,H);
let gr=g.createLinearGradient(0,0,W,0); gr.addColorStop(0,D(.45,.46,1,.85)); gr.addColorStop(.3,D(.62,.46,1,.3)); gr.addColorStop(.85,D(.62,.5,1,.26)); gr.addColorStop(1,D(.4,.55,.9,.45));
g.fillStyle=gr; g.fillRect(0,0,W,H);
const vein=(pts,w)=>{ g.strokeStyle=D(.18,.4,.7,1); g.lineWidth=w; g.lineJoin=g.lineCap='round'; g.beginPath(); pts.forEach(([u,v],i)=>i?g.lineTo(u*W,(1-v)*H):g.moveTo(u*W,(1-v)*H)); g.stroke(); };
const L=[[.92,.5],[.78,.5],[.6,.5],[.42,.5],[.22,.5]];
[[[0,.5],[.3,.82],[.7,.9],[1,.7]],[[0,.5],[.35,.66],[.72,.68],[.98,.52]],[[0,.5],[.4,.48],[.75,.44],[.98,.32]],[[0,.48],[.35,.32],[.7,.24],[.95,.16]],[[0,.46],[.3,.18],[.6,.1]]].forEach(p=>vein(p,4));
[[.55,.9,.55,.67],[.72,.68,.72,.46],[.62,.47,.62,.27],[.8,.42,.8,.2],[.86,.86,.86,.6],[.42,.65,.42,.31],[.93,.6,.93,.38]].forEach(([u0,v0,u1,v1])=>vein([[u0,v0],[u1,v1]],3));
vein([[0,.98],[.5,1],[1,.75]],7); vein([[0,.02],[.5,0],[1,.25]],5);
for(let i=0;i<5000;i++){ g.fillStyle=D(.7,.46,1,.06); g.fillRect(rnd()*W,rnd()*H,2,2); } });
const tegT=dataTex(tegC);
const hindC = makeCanvas(256,128,(g,W,H)=>{ g.clearRect(0,0,W,H); g.fillStyle=D(.66,.6,1,.22); g.fillRect(0,0,W,H);
for(let k=0;k<6;k++){ g.strokeStyle=D(.2,.55,.7,1); g.lineWidth=3; g.beginPath(); g.moveTo(0,H*.5); g.quadraticCurveTo(W*.5,H*(.1+k*.16),W,H*(.05+k*.18)); g.stroke(); }
g.strokeStyle=D(.2,.55,.7,1); g.lineWidth=5; g.strokeRect(0,0,W,H); });
const hindT=dataTex(hindC);
const eyeC = makeCanvas(256,256,(g,W,H)=>{ g.fillStyle=D(.3,.15,1); g.fillRect(0,0,W,H); const r=3.4;
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(.62,.18,1); g.beginPath(); g.arc(x,y,r*.62,0,7); g.fill(); } });
const eyeT=dataTex(eyeC), eyeB=bumpOf(eyeC);
/* =====================================================================
THE TREEHOPPER
===================================================================== */
const root = new T.Group(); scene.add(root);
const body = new T.Group(); root.add(body);
const BODY_Y = .66;
body.position.y = BODY_Y;
const M = {
head: iriMat({hue:.02,light:.48,iri:.9,rough:.3,metal:.55}),
face: iriMat({hue:.96,light:.44,iri:.8,rough:.38}),
eye: iriMat({pat:eyeT,bump:eyeB,bumpScale:.0015,hue:.1,light:.5,rough:.08,metal:.7,env:1.8}),
pron: iriMat({pat:pronT,bump:pronB,bumpScale:.003,hue:.06,light:.5,rough:.28,metal:.6}),
thor: iriMat({hue:.1,light:.36,iri:.7,rough:.4}),
abd: [0,1,2,3,4,5,6].map(i=>iriMat({hue:.14+i*.035,light:i%2?.5:.42,iri:.8,rough:.36})),
memb: iriMat({hue:.1,light:.16,iri:.4,rough:.6}),
stalk: iriMat({hue:.2,light:.48,iri:.9,rough:.36,metal:.5}),
spine: iriMat({hue:.62,light:.48,iri:.9,rough:.36,metal:.5}),
hair: iriMat({hue:.26,light:.62,sat:.6,iri:.6,rough:.55,metal:.2}),
teg: iriMat({pat:tegT,hue:.46,light:.6,rough:.18,metal:.45,side:DS,transparent:true,depthWrite:false,env:1.6}),
hind: iriMat({pat:hindT,hue:.5,light:.62,rough:.15,metal:.4,side:DS,transparent:true,depthWrite:false}),
leg: [.16,.14,.12].map(h=>iriMat({hue:h,light:.56,iri:.8,rough:.4,metal:.45})),
legD: iriMat({hue:.1,light:.3,iri:.6,rough:.45}),
seta: iriMat({hue:.2,light:.64,sat:.5,iri:.5,rough:.55}),
claw: new T.MeshStandardMaterial({color:lin(0x120a08),roughness:.35,metalness:.4}),
pad: iriMat({hue:.9,light:.68,iri:.6,rough:.4}),
ocel: new T.MeshStandardMaterial({color:lin(0xffe0a0),emissive:lin(0x553311),roughness:.15,metalness:.3}),
};
/* ---- head: broad face, bulging eyes, ocelli, bristle antennae, rostrum ---- */
const head = new T.Group(); head.position.set(0,-.02,.66); head.rotation.x=.35; body.add(head);
mesh(SPH, M.head, head, null, V3(.25,.2,.17));
mesh(SPH, M.face, head, V3(0,-.05,.1), V3(.2,.17,.09));
mesh(SPH, M.face, head, V3(0,-.17,.11), V3(.09,.07,.06)); // clypeus
[-1,1].forEach(s=>{
mesh(SPH, M.eye, head, V3(s*.22,.04,.03), V3(.1,.11,.1));
mesh(SPH_LO, new T.MeshStandardMaterial({color:0xffffff,roughness:.05,metalness:.2,envMapIntensity:2}), head, V3(s*.27,.1,.08), .014);
mesh(SPH_LO, M.ocel, head, V3(s*.07,.13,.11), V3(.022,.022,.012));
});
const antennae=[];
[-1,1].forEach(s=>{ const a=new T.Group(); a.position.set(s*.15,-.01,.12); head.add(a);
mesh(SPH_LO, M.legD, a, null, V3(.03,.03,.03));
const ped=new T.Group(); ped.position.set(s*.015,0,.02); a.add(ped); mesh(SPH_LO, M.head, ped, V3(0,0,.02), V3(.022,.022,.032));
const ar=new T.Group(); ar.position.set(0,0,.045); ped.add(ar); mesh(alongZ(.22,u=>.008*(1-u)+.0008,5,4), M.seta, ar);
ar.rotation.set(-.2,s*.6,0); antennae.push({a,ar,s}); });
const rostrum = new T.Group(); rostrum.position.set(0,-.2,.04); head.add(rostrum);
(function(){ let p=rostrum; [.13,.14,.12].forEach((L,k)=>{ const j=new T.Group(); j.rotation.x=k?-.12:-2.0; p.add(j);
mesh(alongZ(L,u=>.026*(1-k*.22)*(1-.25*u),8,4), k===2?M.legD:M.face, j); const n=new T.Group(); n.position.z=L; j.add(n); p=n; }); })();
/* ---- thorax, pronotum base, abdomen ---- */
mesh(SPH, M.thor, body, V3(0,-.06,.24), V3(.27,.2,.4));
mesh(SPH, M.pron, body, V3(0,.08,.3), V3(.36,.27,.46));
[-1,1].forEach(s=>mesh(SPH, M.pron, body, V3(s*.32,.06,.36), V3(.09,.07,.1))); // humeral angles
mesh(SPH, M.pron, body, V3(0,.16,-.06), V3(.13,.07,.2)); // scutellar region
instanced(body, HAIR, M.seta, Array.from({length:140},()=>{ const d=randDir(); d.y=Math.abs(d.y); return [V3(d.x*.35,.08+d.y*.26,.3+d.z*.44), d.clone().add(V3(0,.3,-.3)), rr(.02,.05), .004]; }));
const abd=new T.Group(); abd.position.set(0,-.06,-.05); body.add(abd); const abdSegs=[];
for(let i=0;i<7;i++){ const t=i/6, w=.24*(1-t*.55), h=.18*(1-t*.45);
const g=new T.Group(); g.position.set(0,-t*.03,-i*.13); abd.add(g); abdSegs.push(g);
mesh(SPH, M.abd[i], g, null, V3(w,h,.1)); mesh(SPH_LO, M.memb, g, V3(0,0,-.07), V3(w*.88,h*.85,.05));
if(i>0&&i<6) [-1,1].forEach(s=>mesh(SPH_LO, M.claw, g, V3(s*w*.96,-.02,0), V3(.008,.012,.016))); }
mesh(CONE, M.legD, abd, V3(0,-.07,-.85), V3(.03,.12,.03)).rotation.x=-Math.PI/2-.3; // ovipositor sheath
/* ---- the helmet: stalk, four bristly globes, posterior spine (with secondary motion) ---- */
const helmet = new T.Group(); helmet.position.set(0,.32,.32); body.add(helmet);
const stalkCurve = new T.CatmullRomCurve3([V3(0,0,0),V3(0,.38,.05),V3(0,.82,.1),V3(0,1.22,.04)]);
{ const rf=t=>lerp(.1,.05,t)*(1+.25*Math.exp(-t*12)); const s=sweep(stalkCurve,rf,40,14); mesh(s.geo,M.stalk,helmet);
instanced(helmet, HAIR, M.hair, sweepHairs(stalkCurve,rf,s.frames,40,70,.08,.2)); }
const hub = new T.Group(); hub.position.set(0,1.24,.04); helmet.add(hub);
mesh(SPH, M.stalk, hub, null, .085);
function globeGeo(r){
const g=new T.SphereGeometry(r,72,52), pos=g.attributes.position, col=[], v=V3(), pits=[], N=64;
for(let i=0;i<N;i++){ const y=1-(i+.5)/N*2, rad=Math.sqrt(1-y*y), th=i*GOLD; pits.push(V3(Math.cos(th)*rad,y,Math.sin(th)*rad)); }
for(let i=0;i<pos.count;i++){ v.fromBufferAttribute(pos,i).normalize(); let best=9; for(const p of pits){ const d=Math.acos(clamp(v.dot(p),-1,1)); if(d<best) best=d; }
const pr=.17, depth=best<pr?1-(best/pr)**2:0, lip=best>=pr&&best<pr*1.35?Math.sin((best-pr)/(pr*.35)*Math.PI)*.5:0;
v.multiplyScalar(r*(1-.13*depth+.02*lip)); pos.setXYZ(i,v.x,v.y,v.z); const b=1-.72*depth+.15*lip; col.push(b,b,b); }
g.setAttribute('color',new T.Float32BufferAttribute(col,3)); g.computeVertexNormals(); return g;
}
const globes=[];
function makeGlobe(parent,pos,r,hue){
const g=new T.Group(); g.position.copy(pos); parent.add(g);
mesh(globeGeo(r), iriMat({vcol:true,hue,light:.52,iri:1,rough:.32,metal:.55}), g);
const hm=iriMat({hue:hue+.04,light:.66,sat:.6,iri:.6,rough:.5,metal:.25});
const list=[]; for(let i=0;i<150;i++){ const d=randDir(); list.push([d.clone().multiplyScalar(r*.96), d.clone().add(randDir().multiplyScalar(.35)), r*rr(.6,1.5), .0055]); }
for(let i=0;i<220;i++){ const d=randDir(); list.push([d.clone().multiplyScalar(r*.98), d.clone().add(randDir().multiplyScalar(.6)), r*rr(.12,.3), .004]); }
instanced(g, HAIR, hm, list);
globes.push({g,base:pos.clone(),ph:rnd()*TAU,spin:rr(-.15,.15)}); return g;
}
const cluster=new T.Group(); hub.add(cluster);
[[V3(0,.26,.28),.26,0],[V3(0,.3,-.26),.28,.12],[V3(-.3,.08,.0),.24,.3],[V3(.3,.08,.0),.24,.42]].forEach(([p,r,h])=>{
const c=new T.CatmullRomCurve3([V3(),p.clone().multiplyScalar(.45).add(V3(0,.05,0)),p.clone().multiplyScalar(.7)]); const s=sweep(c,t=>lerp(.045,.03,t),12,8); mesh(s.geo,M.stalk,cluster);
makeGlobe(cluster,p,r,h); });
const spineArm=new T.Group(); hub.add(spineArm);
const spineCurve=new T.CatmullRomCurve3([V3(0,.04,-.08),V3(0,.16,-.75),V3(0,.06,-1.55),V3(0,-.2,-2.4),V3(0,-.55,-3.15)]);
{ const rf=t=>lerp(.065,.006,t**.9)*(1+.3*Math.exp(-((t-.18)**2)/.004)); const s=sweep(spineCurve,rf,90,12); mesh(s.geo,M.spine,spineArm);
instanced(spineArm, HAIR, M.hair, sweepHairs(spineCurve,rf,s.frames,90,150,.08,.3)); }
makeGlobe(spineArm, V3(0,.16,-.62), .26, .76);
[-1,1].forEach(s=>{ const c=new T.CatmullRomCurve3([V3(0,.12,-.6),V3(s*.18,.1,-.95),V3(s*.32,0,-1.25)]); const sw=sweep(c,t=>lerp(.03,.004,t),20,8); mesh(sw.geo,M.spine,spineArm);
instanced(spineArm, HAIR, M.hair, sweepHairs(c,t=>lerp(.03,.004,t),sw.frames,20,18,.05,.12)); });
/* ---- wings (with motion-blur ghosts while buzzing) ---- */
const TW={L:1.55,W:.46};
const tegGeo = gridGeo(36,10,(u,v)=>{ const env=u<.1?Math.sin(u/.1*Math.PI/2)**.7:1, tip=u>.8?Math.sqrt(Math.max(0,1-((u-.8)/.2)**2)):1; const hw=.5*TW.W*Math.max(.05,env*tip*(1-.15*u));
const x=.5*TW.W-hw+2*hw*v+.04*u; return [x, .01*Math.sin(Math.PI*v), -u*TW.L]; });
const hindGeo = gridGeo(20,8,(u,v)=>{ const hw=.5*.42*Math.sin(Math.PI*Math.min(1,u*1.1+.05))**.6; const x=.21-hw+2*hw*v; return [x,0,-u*1.05]; });
const wings=[];
function makeWingSet(s, alpha){
const flap=new T.Group(); flap.position.set(s*.1,.22,.12); body.add(flap);
const roll=new T.Group(); flap.add(roll);
const mt=alpha<1?iriMat({pat:tegT,hue:.46,light:.62,rough:.2,metal:.45,side:DS,transparent:true,depthWrite:false,alpha}):M.teg;
const tm=mesh(tegGeo, mt, roll); tm.scale.x=s; tm.castShadow=alpha===1; tm.renderOrder=3;
const hf=new T.Group(); hf.position.set(s*.08,.16,.04); body.add(hf); const hr=new T.Group(); hf.add(hr);
const mh=alpha<1?iriMat({pat:hindT,hue:.5,light:.62,side:DS,transparent:true,depthWrite:false,alpha}):M.hind;
const hm=mesh(hindGeo, mh, hr); hm.scale.x=s; hm.castShadow=false; hm.renderOrder=2;
return {flap,roll,hf,hr,s,mt,mh,alpha};
}
[-1,1].forEach(s=>{ wings.push(Object.assign(makeWingSet(s,1),{lag:0})); [1,2].forEach(k=>wings.push(Object.assign(makeWingSet(s,.35),{lag:k*.7,ghost:true}))); });
/* ---- legs (two-bone IK, feet gripping the stem) ---- */
const STEM_R=.42;
const stemY = x => { const xx=clamp(x,-STEM_R*.98,STEM_R*.98); return Math.sqrt(STEM_R*STEM_R-xx*xx)-STEM_R; };
const legs=[];
function buildLeg(D,s,li){
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]), mt=M.leg[li];
const cg=new T.Group(); body.add(cg); orient(cg,hip,tro,UP); mesh(alongX(hip.distanceTo(tro)+.02,t=>.05*(1-.3*t)+.012,10,5), M.legD, cg);
const fem=new T.Group(), tib=new T.Group(), tar=new T.Group(); body.add(fem,tib,tar);
mesh(alongX(D.a,t=>.04*Math.sin(Math.PI*(.08+.86*t))**.5*(1-.25*t)+.012,10,10), mt, fem).scale.z=.8;
instanced(fem, HAIR, M.seta, Array.from({length:18},()=>{ const x=rnd()*D.a, a=rnd()*TAU; return [V3(x,Math.cos(a)*.03,Math.sin(a)*.03), V3(.8,Math.cos(a),Math.sin(a)), rr(.02,.04), .003]; }));
mesh(alongX(D.b,t=>.026*(1-.3*t)+.006,8,10), mt, tib);
const sp=[]; const rows=li===2?[-1.9,-1.2,-.5]:[-1.6,-.9];
rows.forEach(a=>{ for(let k=0;k<(li===2?9:6);k++){ const x=D.b*(.14+k*(.8/(li===2?9:6))); sp.push([V3(x,Math.cos(a)*.024,Math.sin(a)*.024),V3(.7,Math.cos(a),Math.sin(a)),li===2?.06:.04,.006]); } });
[-1,1].forEach(cs=>sp.push([V3(D.b*.98,-.01,cs*.015),V3(1,-.3,cs*.5),.05,.007])); instanced(tib, CONE, M.claw, sp);
let x=0; [.42,.24,.34].forEach((f,k)=>{ const L=D.tl*f; mesh(alongX(L,u=>.017*(1-k*.12)*(.8+.2*u),8,3), k===1?M.legD:mt, tar, V3(x,0,0)); mesh(SPH_LO,M.pad,tar,V3(x+L*.5,-.014,0),V3(L*.42,.008,.014)); x+=L; });
[-1,1].forEach(cs=>{ const c=mesh(alongX(.035,u=>.006*(1-u)+.0008,5,3),M.claw,tar,V3(x,0,cs*.006)); c.rotation.set(0,cs*.35,-.9); });
const home=V3(s*STEM_R*Math.sin(D.th),0,D.hz); home.y=stemY(home.x);
const L={D,s,tro,fem,tib,tar,home,toe:home.clone(),lift:V3(),target:V3(),swinging:false,phase:0}; legs.push(L); return L;
}
const LEGDEF=[
{hip:[.12,-.18,.46],tro:[.2,-.24,.5],a:.32,b:.34,tl:.15,th:.95,hz:.86,bend:[.5,1,.1]},
{hip:[.16,-.2,.18],tro:[.25,-.26,.16],a:.34,b:.38,tl:.16,th:1.1,hz:.2,bend:[.5,1,0]},
{hip:[.17,-.2,-.06],tro:[.26,-.25,-.12],a:.4,b:.56,tl:.19,th:1.05,hz:-.48,bend:[.3,.7,-1]},
];
LEGDEF.forEach((D,i)=>[-1,1].forEach(s=>{ const L=buildLeg(D,s,i); L.phase=((i%2===0)===(s<0))?0:.5; }));
/* =====================================================================
THE STEM (scrolls beneath the insect; nodes, leaves, thorns repeat)
===================================================================== */
const PERIOD=4, REPS=16;
const barkC = makeCanvas(256,512,(g,W,H)=>{ let gr=g.createLinearGradient(0,0,W,0); gr.addColorStop(0,'#1f2b14'); gr.addColorStop(.5,'#3b4a22'); gr.addColorStop(1,'#1f2b14'); g.fillStyle=gr; g.fillRect(0,0,W,H);
for(let i=0;i<260;i++){ g.strokeStyle=`rgba(${rnd()<.5?'15,20,8':'90,100,50'},${rr(.15,.4)})`; g.lineWidth=rr(.6,2); const x=rnd()*W; g.beginPath(); g.moveTo(x,0); g.lineTo(x+rr(-6,6),H); g.stroke(); }
for(let i=0;i<90;i++){ g.fillStyle=`rgba(170,160,110,${rr(.25,.5)})`; g.beginPath(); g.ellipse(rnd()*W,rnd()*H,rr(1,2),rr(2.5,5),0,0,7); g.fill(); } });
const barkT=new T.CanvasTexture(barkC); barkT.encoding=T.sRGBEncoding; barkT.wrapS=barkT.wrapT=T.RepeatWrapping; barkT.repeat.set(2,REPS); barkT.anisotropy=ANISO;
const barkB=new T.CanvasTexture(barkC); barkB.wrapS=barkB.wrapT=T.RepeatWrapping; barkB.repeat.set(2,REPS);
const stem=new T.Group(); scene.add(stem);
const stemMat=new T.MeshStandardMaterial({map:barkT,bumpMap:barkB,bumpScale:.015,roughness:.75,metalness:0});
const sm=new T.Mesh(new T.CylinderGeometry(STEM_R,STEM_R,PERIOD*REPS,40,1,true), stemMat); sm.rotation.x=Math.PI/2; sm.position.y=-STEM_R; sm.receiveShadow=true; stem.add(sm);
(function(){
const leafC=makeCanvas(256,512,(g,W,H)=>{ g.fillStyle='#2f5a1f'; g.fillRect(0,0,W,H); let gr=g.createLinearGradient(0,0,W,0); gr.addColorStop(0,'rgba(10,30,5,.5)'); gr.addColorStop(.5,'rgba(120,170,60,.25)'); gr.addColorStop(1,'rgba(10,30,5,.5)'); g.fillStyle=gr; g.fillRect(0,0,W,H);
g.strokeStyle='rgba(170,210,110,.7)'; g.lineWidth=5; g.beginPath(); g.moveTo(W/2,0); g.lineTo(W/2,H); g.stroke();
for(let k=1;k<12;k++){ const y=H*k/12; g.lineWidth=2; [-1,1].forEach(s=>{ g.beginPath(); g.moveTo(W/2,y); g.quadraticCurveTo(W/2+s*W*.25,y-H*.04,W/2+s*W*.48,y-H*.1); g.stroke(); }); } });
const leafT=new T.CanvasTexture(leafC); leafT.encoding=T.sRGBEncoding;
const leafMat=new T.MeshStandardMaterial({map:leafT,roughness:.6,side:DS});
const leafGeo=gridGeo(20,8,(u,v)=>{ const w=.55*Math.sin(Math.PI*u)**.7*(1-.25*u), x=(v*2-1)*w; return [x, .12*(v*2-1)**2*w*2 - .5*u*u, u*1.8]; });
const knot=new T.TorusGeometry(STEM_R*.99,.035,8,40), thorn=new T.ConeGeometry(.04,.22,6).translate(0,.11,0);
for(let k=0;k<REPS;k++){ const z=(k-REPS/2)*PERIOD;
const kn=mesh(knot,stemMat,stem,V3(0,-STEM_R,z)); kn.castShadow=false;
const side=k%2?1:-1, a=side*1.25;
const lg=new T.Group(); lg.position.set(Math.sin(a)*STEM_R,-STEM_R+Math.cos(a)*STEM_R,z); lg.rotation.set(0,0,-a); stem.add(lg);
const pet=new T.CatmullRomCurve3([V3(),V3(0,.25,.15),V3(0,.35,.45)]); mesh(new T.TubeGeometry(pet,10,.03,6,false),stemMat,lg);
const lf=mesh(leafGeo,leafMat,lg,V3(0,.35,.45)); lf.rotation.set(-.6,0,side*.5);
[1.4,2.6].forEach((dz,i)=>{ const ta=(i?-1:1)*side*.6+Math.PI*.0; const th=mesh(thorn,stemMat,stem,V3(Math.sin(ta)*STEM_R,-STEM_R+Math.cos(ta)*STEM_R,z+dz)); th.rotation.set(-.5,0,-ta); });
}
})();
/* lights */
scene.add(new T.HemisphereLight(0xffffff,0x101018,.5));
const key=new T.DirectionalLight(0xffffff,1.35); key.position.set(3,8,5); key.castShadow=true;
key.shadow.mapSize.set(2048,2048); Object.assign(key.shadow.camera,{left:-3.5,right:3.5,top:3.5,bottom:-3.5,near:1,far:20}); key.shadow.bias=-.0004; key.shadow.normalBias=.015; key.shadow.radius=3;
scene.add(key);
const rim=new T.PointLight(0x33ccff,1.8,70); rim.position.set(-7,4,-4); scene.add(rim);
const rim2=new T.PointLight(0xff33aa,1.5,70); rim2.position.set(7,-1,-3); scene.add(rim2);
const under=new T.PointLight(0x8855ff,.6,50); under.position.set(0,-5,3); scene.add(under);
const glint=new T.PointLight(0xffffff,1.0,55); glint.position.set(2,6,9); scene.add(glint);
/* =====================================================================
BEHAVIOUR: creep along the stem, pause, buzz, probe the stem with the rostrum
===================================================================== */
let mode='walk', modeT=3, speed=0, tSpeed=.3, gphase=0, dist=0, buzz=0, feed=0;
const DUTY=.62;
function pick(){ const r=rnd();
if(r<.45){ mode='walk'; tSpeed=rr(.2,.42); modeT=rr(3,6); }
else if(r<.65){ mode='pause'; tSpeed=0; modeT=rr(1.5,3); }
else if(r<.85){ mode='buzz'; tSpeed=0; modeT=rr(.8,1.8); }
else { mode='feed'; tSpeed=0; modeT=rr(3,5); } }
const helmS={ax:0,vx:0,az:0,vz:0}; let prevBodyY=BODY_Y, prevVy=0;
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); root.localToWorld(_toe); 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*.5;
_d.subVectors(_ank,L.tro); const c=clamp(_d.length(),Math.abs(a-b)+.02,(a+b)*.995); _d.normalize();
const B=L.D.bend; _w.set(L.s*B[0],B[1],B[2]); _w.addScaledVector(_d,-_w.dot(_d)).normalize();
const al=Math.acos(clamp((a*a+c*c-b*b)/(2*a*c),-1,1));
_kn.copy(L.tro).addScaledVector(_d,a*Math.cos(al)).addScaledVector(_w,a*Math.sin(al));
_a2.copy(L.tro).addScaledVector(_d,c);
orient(L.fem,L.tro,_kn,_w); orient(L.tib,_kn,_a2,_w);
_t.copy(_toe).sub(_ank).add(_a2); orient(L.tar,_a2,_t,UP);
}
}
function update(dt,t){
modeT-=dt; if(modeT<=0 && !reduceMotion) pick();
speed+=(tSpeed-speed)*(1-Math.exp(-dt*3));
buzz+=((mode==='buzz'?1:0)-buzz)*(1-Math.exp(-dt*9));
feed+=((mode==='feed'&&modeT>.6?1:0)-feed)*(1-Math.exp(-dt*2.5));
const v=speed; dist+=v*dt;
// gait
const stride=.2; let rate=v*DUTY/stride;
if(v<.03 && legs.some(L=>L.swinging)) rate=Math.max(rate,1.4);
gphase=(gphase+rate*dt)%1; const Tst=DUTY/Math.max(rate,.001);
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.z-=v*dt; L.toe.y=stemY(L.toe.x); }
else { if(!L.swinging){ L.swinging=true; L.lift.copy(L.toe); } const s=(p-DUTY)/(1-DUTY), half=Math.min(.16,v*Tst*.5);
L.target.set(L.home.x,0,L.home.z+half); L.target.y=stemY(L.target.x); L.toe.lerpVectors(L.lift,L.target,smooth(s)); L.toe.y+=Math.sin(Math.PI*s)*.09; }
}
stem.position.z=-((dist%PERIOD)+PERIOD)%PERIOD;
// body
const busy=Math.min(1,v*3);
const vib=buzz*(Math.sin(t*TAU*14*.5)*.012);
const by=BODY_Y+.012*Math.cos(gphase*TAU*2)*busy+.05*buzz+.01*Math.sin(t*1.1)-.05*feed;
body.position.set(vib,by,0);
body.rotation.z=.02*Math.sin(gphase*TAU)*busy+.025*Math.sin(t*.8)*(1-busy)+buzz*.012*Math.sin(t*TAU*4.7);
body.rotation.x=.015*Math.sin(t*.6)+.08*feed;
const vy=(by-prevBodyY)/Math.max(dt,1e-4), ay=(vy-prevVy)/Math.max(dt,1e-4); prevBodyY=by; prevVy=vy;
abdSegs.forEach((g,i)=>{ g.scale.y=1+.03*Math.sin(t*1.7-i*.3)*(i/6); });
// helmet: damped spring driven by body motion, plus slow sway
const kS=38, cS=3.2;
helmS.vx+=(-kS*helmS.ax-cS*helmS.vx-clamp(ay,-40,40)*.006+(gphase>0&&busy?Math.sin(gphase*TAU*2)*.4*busy:0))*dt; helmS.ax+=helmS.vx*dt;
helmS.vz+=(-kS*helmS.az-cS*helmS.vz-body.rotation.z*4+vib*30)*dt; helmS.az+=helmS.vz*dt;
helmet.rotation.x=helmS.ax+.03*Math.sin(t*.95); helmet.rotation.z=helmS.az+.03*Math.sin(t*1.15);
hub.rotation.x=.04*Math.sin(t*.95)+helmS.ax*.6; cluster.rotation.y=.06*Math.sin(t*1.05); cluster.rotation.x=.06*Math.sin(t*1.5)+helmS.ax*.8;
spineArm.rotation.x=.04*Math.sin(t*.85)-helmS.ax*.5; spineArm.rotation.z=.03*Math.sin(t*1.3)+helmS.az*.8;
globes.forEach(G=>{ G.g.rotation.y+=G.spin*dt; G.g.position.copy(G.base); G.g.position.y+=.02*Math.sin(t*2.1+G.ph)+helmS.ax*.05; });
// head, antennae, rostrum
head.rotation.x=.35+.02*Math.sin(t*1.3)+.12*feed; head.rotation.y=.04*Math.sin(t*.7);
antennae.forEach(({ar,s},i)=>{ ar.rotation.y=s*.6+.25*Math.sin(t*4+i*2); ar.rotation.x=-.2+.15*Math.cos(t*3+i); });
rostrum.rotation.x=-.7*feed+.04*Math.sin(t*6)*feed;
// wings: roof at rest, open + beat when buzzing; ghosts trail the beat
const beat=t*TAU*14;
wings.forEach(W=>{ const o=smooth(buzz), s=W.s, a=lerp(-.62,-.18,o)+.62*o*Math.sin(beat-W.lag)+(1-o)*.02*Math.sin(t*1.6);
W.roll.rotation.z=s*a; W.flap.rotation.y=-s*.12*o; W.hr.rotation.z=s*(lerp(-.7,-.1,o)+.7*o*Math.sin(beat-W.lag-.5));
if(W.ghost){ const on=o>.02; W.flap.visible=W.hf.visible=on; W.mt.userData.u.uAlpha.value=.35*o; W.mh.userData.u.uAlpha.value=.35*o; }
else W.hf.visible=o>.02; });
solveLegs();
}
/* =====================================================================
CAMERA / INPUT
===================================================================== */
const cam={dist:5.2,yaw:.85,pitch:.2,tYaw:.85,tPitch:.2,tDist:5.2,auto:0}; let 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,7.5); }
fitCam();
const pts=new Map(); let pinch=0,lx=0,ly=0;
canvas.addEventListener('pointerdown',e=>{ pts.set(e.pointerId,[e.clientX,e.clientY]); canvas.setPointerCapture(e.pointerId); dragging=true; lx=e.clientX; ly=e.clientY; pinch=0; });
canvas.addEventListener('pointermove',e=>{ if(!pts.has(e.pointerId)) return; pts.set(e.pointerId,[e.clientX,e.clientY]);
if(pts.size===2){ const [a,b]=[...pts.values()], d=Math.hypot(a[0]-b[0],a[1]-b[1]); if(pinch) cam.tDist=clamp(cam.tDist+(pinch-d)*.015,2.2,14); pinch=d; return; }
cam.tYaw-=(e.clientX-lx)*.006; cam.tPitch=clamp(cam.tPitch+(e.clientY-ly)*.005,-.9,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*.005,2.2,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);
if(!dragging&&!reduceMotion) cam.auto+=dt*.09;
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, ty=1.05;
camera.position.set(Math.sin(y)*Math.cos(p)*cam.dist, ty+Math.sin(p)*cam.dist, Math.cos(y)*Math.cos(p)*cam.dist-.4);
camera.lookAt(0,ty,-.4);
renderer.render(scene,camera);
}
frame();
}
</script>
</body>
</html>