TRILOBITE BEETLE SOURCE CODE
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Trilobite Beetle</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% 40%, #0b140d 0%, #050806 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 = 6060;
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(0x040806, 0.06);
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,'#122016'); 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',.2]].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??.3, 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.16, 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, 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; }
function bumpy(r,amp){ const g=new T.IcosahedronGeometry(r,2), p=g.attributes.position, v=V3(); for(let i=0;i<p.count;i++){ v.fromBufferAttribute(p,i); v.multiplyScalar(1+amp*(Math.sin(v.x*40)*Math.sin(v.y*37)*Math.sin(v.z*43))); p.setXYZ(i,v.x,v.y,v.z); } g.computeVertexNormals(); return g; }
/* =====================================================================
ARMOUR PATTERN: dark three-lobed centre, contrasting lateral lobes, pitted
===================================================================== */
const plateC = makeCanvas(256,256,(g,W,H)=>{
g.fillStyle=D(.28,.0,1); g.fillRect(0,0,W,H);
[[0,.2],[.8,1]].forEach(([a,b])=>{ const gr=g.createLinearGradient(a*W,0,b*W,0); const inner=a===0?1:0;
gr.addColorStop(inner?1:0,D(.28,.0,1)); gr.addColorStop(inner?.0:1,D(.82,.42,1)); g.fillStyle=gr; g.fillRect(a*W,0,(b-a)*W,H); });
[.33,.67].forEach(u=>{ g.fillStyle=D(.5,.06,1); g.fillRect(u*W-6,0,12,H); });
g.fillStyle=D(.58,.08,1); g.fillRect(W*.495-4,0,8,H);
for(let i=0;i<1600;i++){ const x=rnd()*W, y=rnd()*H; g.fillStyle=D(rr(.1,.2),.0,.7); g.beginPath(); g.arc(x,y,rr(1,2.6),0,7); g.fill(); }
g.fillStyle=D(.14,.0,.7); g.fillRect(0,H*.92,W,H*.08); // dark posterior rim (canvas top = rear)
g.fillStyle=D(.14,.0,.7); g.fillRect(0,0,W,H*.04);
});
const plateT=dataTex(plateC), plateB=bumpOf(plateC);
/* =====================================================================
THE TRILOBITE BEETLE (larviform female)
===================================================================== */
const beetle=new T.Group(); scene.add(beetle);
const body=new T.Group(); beetle.add(body);
const BODY_Y=.12; body.position.y=BODY_Y;
const M = {
plate: iriMat({pat:plateT,bump:plateB,bumpScale:.004,hue:.04,light:.5,rough:.32,metal:.55,side:DS}),
under: iriMat({hue:.62,light:.18,iri:.6,rough:.5,metal:.3,side:DS}),
tub: iriMat({hue:.06,light:.38,iri:1,rough:.3}),
head: iriMat({hue:.02,light:.42,iri:.9,rough:.35}),
leg: iriMat({hue:.14,light:.5,iri:.9,rough:.4,metal:.45}),
legD: iriMat({hue:.1,light:.28,iri:.7,rough:.45}),
seta: iriMat({hue:.2,light:.62,sat:.5,iri:.5,rough:.5}),
claw: new T.MeshStandardMaterial({color:lin(0x140c08),roughness:.35,metalness:.4}),
};
// a plate surface: u across (−1…1), v along (front 0 … rear 1); arched, with a pointed lateral process
function plateGeo(hw,len,spine,vp,kind){
return gridGeo(30,16,(u,v)=>{ const s=u*2-1, a=Math.abs(s);
const tooth=spine*Math.pow(Math.max(0,1-Math.abs(v-vp)/.5),1.6);
let half=hw+tooth;
if(kind==='pron') half=hw*(.5+.5*Math.pow(Math.sin(Math.PI*clamp(v*.9+.1,0,1)),.6))+tooth;
if(kind==='tail') half=(hw+tooth)*Math.sqrt(Math.max(0,1-Math.pow(v,2.2)*.92));
const edge=smooth((a-.55)/.45);
const y=.12*Math.pow(Math.max(0,1-a*a*1.6),1.2)+.012-.035*edge+.06*(tooth/(spine||1))*smooth((a-.85)/.15);
const z=-v*len + (kind==='pron'?.12*(1-a*a)*(1-v):0);
return [s*half, y, z]; });
}
const plates=[];
function addPlate(cfg,z,y,idx){
const g=new T.Group(); g.position.set(0,y,z); body.add(g);
const geo=plateGeo(cfg.hw,cfg.len,cfg.spine,cfg.vp,cfg.kind);
mesh(geo, M.plate, g);
const under=mesh(geo, M.under, g, V3(0,-.035,0)); under.scale.set(.97,1,.97);
// tubercles: median keel + paramedian rows + lateral warts
const tl=[]; const rows=[[0,.03],[-.3,.026],[.3,.026],[-.62,.018],[.62,.018]];
rows.forEach(([s,r])=>{ const n=cfg.kind==='pron'?4:2; for(let k=0;k<n;k++){ const v=(k+.5)/n*.85+.05, half=cfg.hw*(cfg.kind==='pron'?.85:1), x=s*half, a=Math.abs(s);
tl.push(V3(x,.12*Math.pow(Math.max(0,1-a*a*1.6),1.2)+.02,-v*cfg.len+(cfg.kind==='pron'?.12*(1-a*a)*(1-v):0)).toArray().concat([r])); } });
const tg=bumpy(1,.12), im=new T.InstancedMesh(tg,M.tub,tl.length), m4=new T.Matrix4();
tl.forEach((p,i)=>{ m4.compose(V3(p[0],p[1],p[2]),_q.identity(),V3(p[3],p[3]*.8,p[3]*1.2)); im.setMatrixAt(i,m4); }); im.castShadow=true; g.add(im);
// stiff bristles at each lateral process
[-1,1].forEach(s=>{ const tipX=s*(cfg.hw+cfg.spine), tipZ=-cfg.vp*cfg.len;
instanced(g, HAIR, M.seta, [0,1,2].map(k=>[V3(tipX*(.9-k*.06),.02,tipZ+k*.04),V3(s*.8,.5,-.3+k*.2),rr(.06,.12),.006])); });
plates.push({g,baseY:y,baseZ:z,idx}); return g;
}
addPlate({hw:.7,len:.66,spine:.2,vp:.62,kind:'pron'},1.3,.14,0);
const N=8;
for(let i=0;i<N;i++){ const t=i/(N-1);
const hw=.66+.06*Math.sin(Math.min(1,i/2)*Math.PI*.5)-.06*Math.max(0,i-2), spine=.28+.1*Math.sin(t*Math.PI)-.08*t;
addPlate({hw,len:i===N-1?.48:.36,spine,vp:i===N-1?.25:.72,kind:i===N-1?'tail':'terg'}, .72-i*.31, .13-i*.008, i+1); }
// soft underbody
mesh(SPH, M.under, body, V3(0,-.0,-.4), V3(.42,.09,1.75));
// head: small, retractable under the pronotum
const headNeck=new T.Group(); headNeck.position.set(0,0,1.15); body.add(headNeck);
const headG=new T.Group(); headNeck.add(headG);
mesh(SPH, M.head, headG, null, V3(.15,.085,.13));
[-1,1].forEach(s=>{ mesh(SPH_LO, iriMat({hue:.5,light:.3,rough:.08,metal:.7,film:.7}), headG, V3(s*.12,.02,.06), .035);
const mg=new T.Group(); mg.position.set(s*.05,-.03,.12); headG.add(mg); mesh(alongZ(.08,u=>.016*(1-u)+.002,6,3), M.legD, mg).rotation.y=-s*.4; });
const antennae=[];
[-1,1].forEach(s=>{ const a=new T.Group(); a.position.set(s*.09,.02,.11); headG.add(a); a.rotation.y=s*.4;
let p=a; for(let k=0;k<6;k++){ const j=new T.Group(); j.rotation.x=-.05; p.add(j); mesh(alongZ(.045,u=>.016*(1-k*.1)*(.8+.2*Math.sin(u*Math.PI)),8,3), k%2?M.tub:M.head, j); const n=new T.Group(); n.position.z=.045; j.add(n); p=n; }
antennae.push({a,s}); });
// legs: short, mostly hidden under the armour, feet planted on the bark (two-bone IK)
const legs=[];
const LOG_R=3.2, logY=x=>Math.sqrt(Math.max(0,LOG_R*LOG_R-x*x))-LOG_R;
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=>.045*(1-.3*t)+.012,8,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=>.032*(1-.25*t)+.01,10,6), M.leg, fem);
mesh(alongX(D.b,t=>.022*(1-.3*t)+.006,8,6), M.leg, tib);
instanced(tib, HAIR, M.seta, Array.from({length:10},()=>{ const x=rnd()*D.b, a=rnd()*TAU; return [V3(x,Math.cos(a)*.02,Math.sin(a)*.02),V3(.6,Math.cos(a)-.4,Math.sin(a)),rr(.02,.035),.003]; }));
mesh(alongX(D.tl,u=>.014*(1-.4*u)+.003,6,3), M.legD, tar);
mesh(alongX(.03,u=>.006*(1-u)+.001,5,3), M.claw, tar, V3(D.tl,0,0)).rotation.z=-.9;
const home=V3(s*D.home[0],0,D.home[1]); home.y=logY(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:[.16,0,.95],tro:[.24,-.03,.98],a:.2,b:.22,tl:.1,home:[.5,1.22]},
{hip:[.2,0,.5],tro:[.28,-.03,.5],a:.22,b:.24,tl:.11,home:[.6,.55]},
{hip:[.2,0,.08],tro:[.28,-.03,.05],a:.22,b:.26,tl:.12,home:[.6,-.05]},
];
LEGDEF.forEach((D,i)=>[-1,1].forEach(s=>{ const L=buildLeg(D,s); L.phase=((i%2===0)===(s<0))?0:.5; }));
/* =====================================================================
THE LOG: rotting, mossy bark that scrolls beneath the beetle;
slime-mould patches, glowing Mycena, bracket fungi and moss ride on it
===================================================================== */
const LOG_L=26;
const barkC=makeCanvas(512,1024,(g,W,H)=>{ g.fillStyle='#2a1c12'; g.fillRect(0,0,W,H);
for(let i=0;i<220;i++){ g.strokeStyle=`rgba(${rnd()<.6?'12,8,4':'70,52,36'},${rr(.3,.7)})`; g.lineWidth=rr(1,5); let x=rnd()*W; g.beginPath(); g.moveTo(x,0); for(let y=0;y<=H;y+=32){ x+=rr(-4,4); g.lineTo(x,y);} g.stroke(); }
for(let i=0;i<10;i++){ const x=rnd()*W, y=rnd()*H, w=rr(20,60), h=rr(60,200); g.fillStyle='rgba(95,70,46,.45)'; g.beginPath(); for(let k=0;k<=14;k++){ const a=k/14*TAU, r=1+.25*Math.sin(a*3+i); k?g.lineTo(x+Math.cos(a)*w/2*r,y+Math.sin(a)*h/2*r):g.moveTo(x+Math.cos(a)*w/2*r,y+Math.sin(a)*h/2*r); } g.fill(); } // peeled bark showing soft wood
for(let i=0;i<45;i++){ const x=rnd()*W, y=rnd()*H, r=rr(15,60); for(let k=0;k<60;k++){ const a=rnd()*TAU, d=rnd()*r; g.fillStyle=`rgba(${rnd()<.5?'34,60,20':'52,80,28'},${rr(.25,.5)})`; g.beginPath(); g.arc(x+Math.cos(a)*d,y+Math.sin(a)*d,rr(1.5,3.5),0,7); g.fill(); } } });
const barkT=new T.CanvasTexture(barkC); barkT.encoding=T.sRGBEncoding; barkT.wrapS=barkT.wrapT=T.RepeatWrapping; barkT.repeat.set(3,LOG_L/5); barkT.anisotropy=ANISO;
const barkB=new T.CanvasTexture(barkC); barkB.wrapS=barkB.wrapT=T.RepeatWrapping; barkB.repeat.copy(barkT.repeat);
const log=new T.Mesh(new T.CylinderGeometry(LOG_R,LOG_R,LOG_L,72,1,true), new T.MeshStandardMaterial({map:barkT,bumpMap:barkB,bumpScale:.05,roughness:.92}));
log.rotation.x=Math.PI/2; log.position.y=-LOG_R; log.receiveShadow=true; scene.add(log);
// forest floor: dark leaf litter
(function(){ const litC=makeCanvas(512,512,(g,W,H)=>{ g.fillStyle='#120c08'; g.fillRect(0,0,W,H); for(let i=0;i<500;i++){ g.fillStyle=`rgba(${[[70,40,20],[50,35,15],[30,40,15],[90,60,30]][(rnd()*4)|0].join(',')},${rr(.3,.8)})`; g.save(); g.translate(rnd()*W,rnd()*H); g.rotate(rnd()*TAU); g.beginPath(); g.ellipse(0,0,rr(6,18),rr(3,7),0,0,7); g.fill(); g.restore(); } });
const t=new T.CanvasTexture(litC); t.encoding=T.sRGBEncoding; t.wrapS=t.wrapT=T.RepeatWrapping; t.repeat.set(10,10);
const f=new T.Mesh(new T.PlaneGeometry(240,240), new T.MeshStandardMaterial({map:t,roughness:.95})); f.rotation.x=-Math.PI/2; f.position.y=-LOG_R*1.6; scene.add(f); })();
// props live in log coordinates (angle around the log, z along it) and scroll with the bark
const onLog=(ang,z,lift=0)=>V3(Math.sin(ang)*(LOG_R+lift), -LOG_R+Math.cos(ang)*(LOG_R+lift), z);
const props=[];
function addProp(obj,ang,z,kind){ obj.userData={ang,z,kind}; scene.add(obj); props.push(obj); return obj; }
// slime mould: a yellow plasmodial network pressed onto the bark
const slimeC=makeCanvas(256,256,(g,W,H)=>{ g.clearRect(0,0,W,H); const grow=(x,y,a,w,d)=>{ if(d>7||w<.6) return; const l=rr(14,30), x2=x+Math.cos(a)*l, y2=y+Math.sin(a)*l;
g.strokeStyle=`rgba(255,${200+((rnd()*40)|0)},40,${.6+.4*w/6})`; g.lineWidth=w; g.lineCap='round'; g.beginPath(); g.moveTo(x,y); g.lineTo(x2,y2); g.stroke(); grow(x2,y2,a+rr(-.6,.6),w*.85,d+1); if(rnd()<.5) grow(x2,y2,a+rr(-1.4,1.4),w*.6,d+1); };
for(let k=0;k<9;k++) grow(W/2,H/2,k/9*TAU+rr(-.2,.2),6,0);
const gr=g.createRadialGradient(W/2,H/2,0,W/2,H/2,40); gr.addColorStop(0,'rgba(255,230,70,.9)'); gr.addColorStop(1,'rgba(255,220,60,0)'); g.fillStyle=gr; g.fillRect(0,0,W,H); });
const slimeT=new T.CanvasTexture(slimeC); slimeT.encoding=T.sRGBEncoding;
function slimePatch(){ const g=new T.Group(); const w=1.4;
const geo=gridGeo(16,16,(u,v)=>{ const x=(u-.5)*w; return [x, logY(x)+.012, (v-.5)*w]; });
const m=mesh(geo,new T.MeshStandardMaterial({map:slimeT,transparent:true,depthWrite:false,side:DS,roughness:.3,emissive:lin(0x6a5208),emissiveMap:slimeT,emissiveIntensity:.8}),g); m.castShadow=false;
for(let i=0;i<10;i++){ const x=rr(-.4,.4), z=rr(-.4,.4); mesh(SPH_LO,new T.MeshStandardMaterial({color:lin(0xf2c030),emissive:lin(0x5a3a00),roughness:.3}),g,V3(x,logY(x)+.02,z),V3(rr(.02,.05),.015,rr(.02,.05))); }
return g; }
// glowing Mycena cluster
const capMat=new T.MeshStandardMaterial({color:lin(0x1f5a24),emissive:lin(0x22d84a),emissiveIntensity:1.7,roughness:.5,envMapIntensity:.2});
const stemMat=new T.MeshStandardMaterial({color:lin(0x2a4a28),emissive:lin(0x0e5a1c),emissiveIntensity:.7,roughness:.6,envMapIntensity:.2});
function mycena(n,s){ const g=new T.Group();
for(let i=0;i<n;i++){ const h=rr(.25,.6)*s, x=rr(-.18,.18)*s, z=rr(-.18,.18)*s, lean=V3(rr(-.3,.3),1,rr(-.3,.3)).normalize();
const st=mesh(new T.CylinderGeometry(.012*s,.018*s,h,6).translate(0,h/2,0),stemMat,g,V3(x,0,z)); st.quaternion.setFromUnitVectors(UP,lean);
const cap=mesh(new T.SphereGeometry(.07*s,14,8,0,TAU,0,Math.PI*.5),capMat,g,V3(x,0,z).addScaledVector(lean,h)); cap.scale.y=1.3; cap.quaternion.copy(st.quaternion); cap.castShadow=false; }
return g; }
// bracket fungus shelves
const brC=makeCanvas(256,128,(g,W,H)=>{ for(let k=0;k<12;k++){ g.fillStyle=k%2?'#6a3c1a':'#9a5a24'; g.fillRect(0,k/12*H,W,H/12+1); } g.fillStyle='rgba(240,220,180,.9)'; g.fillRect(0,H*.94,W,H*.06); });
const brT=new T.CanvasTexture(brC); brT.encoding=T.sRGBEncoding;
function bracket(s){ const g=new T.Group(); for(let k=0;k<3;k++){ const r=rr(.35,.6)*s*(1-k*.2);
const geo=gridGeo(16,8,(u,v)=>{ const a=(u-.5)*Math.PI, rad=v*r; return [Math.sin(a)*rad, -.15*v*v*r-.04*(1-v)*r, Math.cos(a)*rad]; });
mesh(geo,new T.MeshStandardMaterial({map:brT,roughness:.75,side:DS}),g,V3(0,-k*.22*s,0)); } return g; }
const mossMat=new T.MeshStandardMaterial({color:0xffffff,roughness:.95});
function mossClump(s){ const g=new T.Group(); const n=420, im=new T.InstancedMesh(new T.ConeGeometry(.01,1,3).translate(0,.5,0),mossMat,n), m4=new T.Matrix4(), c=new T.Color();
for(let i=0;i<n;i++){ const a=rnd()*TAU, d=Math.sqrt(rnd())*.4*s; _q.setFromUnitVectors(UP,V3(rr(-.3,.3),1,rr(-.3,.3)).normalize()); const hh=.06*s*Math.sqrt(Math.max(0,1-(d/(.4*s))**2)); m4.compose(V3(Math.cos(a)*d,hh*.5,Math.sin(a)*d),_q,V3(1.4,rr(.06,.14)*s,1.4)); im.setMatrixAt(i,m4); c.set(rnd()<.5?0x2e5418:0x44702a).convertSRGBToLinear(); im.setColorAt(i,c); }
g.add(im); return g; }
// place props around the log (scrolling with the bark)
const glowLights=[];
for(let k=0;k<3;k++){ addProp(slimePatch(),rr(-.05,.05),-LOG_L/2+k*LOG_L/3+4,'slime'); }
[[.55,1],[-.62,4.5],[.48,8.5],[-.5,12.5],[.66,17],[-.58,21.5]].forEach(([a,z],i)=>{ const m=addProp(mycena(7,1.2),a,z-LOG_L/2,'myc');
if(i<3){ const l=new T.PointLight(0x4aff6a,1.2,4.5,2); l.position.set(0,.3,0); m.add(l); glowLights.push(l); } });
[[1.15,3],[-1.2,10],[1.2,15.5],[-1.1,22]].forEach(([a,z])=>addProp(bracket(1.3),a,z-LOG_L/2,'br'));
[[.3,2],[-.35,6.5],[.4,11],[-.28,16.5],[.32,20],[-.4,24]].forEach(([a,z])=>addProp(mossClump(1),a,z-LOG_L/2,'moss'));
function placeProp(o){ const {ang,z,kind}=o.userData; o.position.copy(onLog(ang,z)); o.rotation.set(0,0,0);
if(kind!=='slime') o.rotation.z=-ang; if(kind==='br'){ o.position.copy(onLog(ang,z,.05)); o.rotation.set(0,ang>0?Math.PI/2:-Math.PI/2,0); } }
props.forEach(placeProp);
// spores
const motes=(()=>{ const N=240,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(190,255,190,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:.05,map:sp,transparent:true,depthWrite:false,blending:T.AdditiveBlending,opacity:.45})); scene.add(p); return p; })();
/* lights */
scene.add(new T.HemisphereLight(0xffffff,0x101018,.45));
const key=new T.DirectionalLight(0xffffff,1.35); 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.5,70); rim.position.set(-7,4,-4); scene.add(rim);
const rim2=new T.PointLight(0xff33aa,1.3,70); rim2.position.set(7,-1,-3); scene.add(rim2);
const glint=new T.PointLight(0xffffff,1.0,55); glint.position.set(2,6,9); scene.add(glint);
/* =====================================================================
BEHAVIOUR: creep along the log (tripod gait, feet planted on the bark),
stop at slime mould to graze (head out, patch shrinks),
now and then clamp down flat in defence
===================================================================== */
let mode='walk', modeT=4, speed=0, tSpeed=.16, gphase=0, peek=0, clampAmt=0, feedPatch=null;
const DUTY=.66, HEAD_Z=1.45;
function pick(){ const r=rnd(); if(r<.65){ mode='walk'; tSpeed=rr(.12,.2); modeT=rr(4,8); } else if(r<.88){ mode='pause'; tSpeed=0; modeT=rr(2,4); } else { mode='clamp'; tSpeed=0; modeT=3; } }
const _t=V3(),_hd=V3(),_ank=V3(),_d=V3(),_w=V3(),_kn=V3(),_a2=V3(),_toe=V3();
function solve2(root,target,l1,l2,bend,outKnee,outEnd){
_d.subVectors(target,root); const c=clamp(_d.length(),Math.abs(l1-l2)+.01,(l1+l2)*.995); _d.normalize();
_w.copy(bend).addScaledVector(_d,-bend.dot(_d)).normalize();
const al=Math.acos(clamp((l1*l1+c*c-l2*l2)/(2*l1*c),-1,1));
outKnee.copy(root).addScaledVector(_d,l1*Math.cos(al)).addScaledVector(_w,l1*Math.sin(al)); outEnd.copy(root).addScaledVector(_d,c); return _w;
}
function update(dt,t){
modeT-=dt;
// slime patches ahead stop the beetle to feed
if(mode==='walk'){ for(const p of props){ if(p.userData.kind!=='slime'||p.userData.eaten) continue; const dz=p.userData.z-HEAD_Z; if(dz>-.15&&dz<.25){ mode='feed'; modeT=8; tSpeed=0; feedPatch=p; break; } } }
if(modeT<=0 && !reduceMotion){ if(mode==='feed'&&feedPatch){ feedPatch.userData.eaten=true; } pick(); }
speed+=(tSpeed-speed)*(1-Math.exp(-dt*2.5));
const v=speed;
// gait: alternating tripods, stance feet ride the bark as it scrolls
const stride=.16; let rate=v*DUTY/stride;
if(v<.02 && legs.some(L=>L.swinging)) rate=Math.max(rate,1.2);
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=logY(L.toe.x)-clampAmt*.0; }
else { if(!L.swinging){ L.swinging=true; L.lift.copy(L.toe); } const s=(p-DUTY)/(1-DUTY), half=Math.min(.12,v*Tst*.5);
L.target.set(L.home.x,0,L.home.z+half); L.target.y=logY(L.target.x); L.toe.lerpVectors(L.lift,L.target,smooth(s)); L.toe.y+=Math.sin(Math.PI*s)*.07; } }
// the bark and everything on it slides back
barkT.offset.y+=v*dt*barkT.repeat.y/LOG_L; barkB.offset.y=barkT.offset.y;
props.forEach(p=>{ p.userData.z-=v*dt; if(p.userData.z<-LOG_L/2){ p.userData.z+=LOG_L; p.userData.eaten=false; p.scale.setScalar(1); p.traverse(o=>{ if(o.material&&o.material.map===slimeT) o.material.opacity=1; }); } placeProp(p); });
if(mode==='feed'&&feedPatch){ const e=clamp(1-(8-modeT)/9,.35,1); feedPatch.traverse(o=>{ if(o.material&&o.material.map===slimeT) o.material.opacity=e; }); feedPatch.children.forEach((c,i)=>{ if(i>0) c.scale.y=.015*e; }); }
glowLights.forEach((l,i)=>{ l.intensity=1.1+.25*Math.sin(t*(.7+i*.3)+i*2); });
// armour ripple travels back along the plates; clamping presses the shell flat
clampAmt+=((mode==='clamp'?1:0)-clampAmt)*(1-Math.exp(-dt*4));
const busy=Math.min(1,v*6);
plates.forEach(P=>{ const ph=t*1.4-P.idx*.55, z=P.baseZ;
P.g.rotation.x=(Math.sin(ph)*.02+Math.sin(gphase*TAU*2-P.idx*.8)*.015*busy)*(1-clampAmt)-(z*z)/(2*LOG_R*LOG_R)*0;
P.g.position.y=P.baseY+Math.sin(ph)*.008*(1-clampAmt)-clampAmt*.06+(Math.sqrt(LOG_R*LOG_R-0)-LOG_R);
P.g.rotation.z=Math.sin(t*.9-P.idx*.3)*.01*(1-clampAmt); P.g.scale.x=1+clampAmt*.04; });
body.position.y=BODY_Y-clampAmt*.07+.008*Math.cos(gphase*TAU*2)*busy;
body.rotation.z=.012*Math.sin(gphase*TAU)*busy;
// head: peeks out to graze slime or look around; antennae tap
const wantPeek=mode==='feed'?1:(mode==='pause'?.6:mode==='walk'?.35:0);
peek+=(wantPeek-peek)*(1-Math.exp(-dt*2));
headNeck.position.set(0,-.02*peek,1.15+.3*peek);
headG.rotation.x=(mode==='feed'?.45+.08*Math.sin(t*4):.1)*peek; headG.rotation.y=Math.sin(t*.7)*.25*peek*(mode==='feed'?.3:1);
antennae.forEach(({a,s},i)=>{ a.rotation.y=s*(.4+.25*Math.sin(t*3+i))*(.3+.7*peek); a.rotation.x=(mode==='feed'?.45:0)+.15*Math.cos(t*2.6+i*1.7); });
// legs: IK from hips to the planted feet
body.updateMatrixWorld(true);
for(const L of legs){ const {a,b,tl}=L.D;
_toe.copy(L.toe); beetle.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*.8); _ank.y+=tl*.5;
const w=solve2(L.tro,_ank,a,b,V3(L.s*1.2,.7,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); }
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:.9,pitch:.62,tYaw:.9,tPitch:.62,tDist:5.4,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,8.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,1.8,16); pinch=d; return; }
cam.tYaw-=(e.clientX-lx)*.006; cam.tPitch=clamp(cam.tPitch+(e.clientY-ly)*.005,.02,1.4); 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,16); },{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*.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, tg=V3(0,.15,.1);
camera.position.set(tg.x+Math.sin(y)*Math.cos(p)*cam.dist, tg.y+Math.sin(p)*cam.dist, tg.z+Math.cos(y)*Math.cos(p)*cam.dist);
camera.lookAt(tg);
renderer.render(scene,camera);
}
frame();
}
</script>
</body>
</html>