Prompt specification
Build or customize the Three.js 3D scene "Recovery after a bottleneck" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Recovery after a bottleneck
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/recovery-after-a-bottleneck-x0886
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts population bottlenecks. Expand a randomly reduced fictional population through reproduction from survivors; show that recovered headcount does not automatically restore the original variant diversity. Stylized solid forms.
Working Three.js Starter (recovery-after-a-bottleneck-x0886):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Population Bottleneck — Three.js</title>
<style>
:root{
--panel: rgba(13,17,25,.74);
--line: rgba(255,255,255,.10);
--txt:#e9eef8;
--dim:#96a4bb;
--accent:#5fd7c0;
}
*{box-sizing:border-box}
html,body{margin:0;height:100%;background:#080b11;color:var(--txt);overflow:hidden;
font-family:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif}
#scene{position:fixed;inset:0;width:100%;height:100%;display:block;touch-action:none;cursor:grab}
#scene:active{cursor:grabbing}
.glass{background:var(--panel);backdrop-filter:blur(12px) saturate(1.2);
border:1px solid var(--line);border-radius:14px;box-shadow:0 18px 40px rgba(0,0,0,.45)}
header{position:fixed;top:16px;left:16px;padding:14px 16px;max-width:400px;z-index:5}
h1{margin:0 0 6px;font-size:13px;letter-spacing:.16em;text-transform:uppercase;font-weight:700}
header p{margin:0;font-size:12px;color:var(--dim);line-height:1.55}
.phase{margin-top:10px;display:flex;flex-direction:column;gap:5px}
.phase span{font-size:11px;letter-spacing:.06em;color:var(--accent);text-transform:uppercase}
.phase i{display:block;height:3px;background:rgba(255,255,255,.12);border-radius:3px;overflow:hidden}
.phase i b{display:block;height:100%;width:0;background:var(--accent);border-radius:3px}
#tip{margin-top:9px;font-size:11.5px;color:var(--dim);border-top:1px solid var(--line);padding-top:8px;min-height:34px}
#tip b{color:var(--txt)}
#controls{position:fixed;top:16px;right:16px;z-index:6;display:flex;gap:7px;flex-wrap:wrap;justify-content:flex-end;max-width:520px}
button{font:inherit;font-size:11.5px;letter-spacing:.04em;color:var(--txt);background:rgba(255,255,255,.06);
border:1px solid var(--line);border-radius:9px;padding:7px 11px;cursor:pointer;transition:.15s}
button:hover{background:rgba(95,215,192,.16);border-color:rgba(95,215,192,.45)}
button.on{background:rgba(95,215,192,.22);border-color:rgba(95,215,192,.6)}
.grp{display:flex;gap:6px;padding:5px;border-radius:11px}
#hud{position:fixed;left:50%;transform:translateX(-50%);bottom:14px;z-index:5;
width:min(1180px,calc(100vw - 28px));padding:14px;display:grid;
grid-template-columns:repeat(3,minmax(0,1fr)) minmax(0,1.55fr);gap:12px}
.card{padding:11px 13px;border-radius:12px;background:rgba(255,255,255,.035);border:1px solid var(--line)}
.card h2{margin:0 0 8px;font-size:11px;letter-spacing:.1em;text-transform:uppercase;color:var(--dim);font-weight:600;
display:flex;align-items:center;gap:7px}
.dot{width:9px;height:9px;border-radius:50%;display:inline-block}
.big{font-size:30px;font-weight:700;letter-spacing:-.02em;line-height:1}
.big small{font-size:12px;font-weight:500;color:var(--dim);margin-left:6px;letter-spacing:0}
.kv{display:flex;justify-content:space-between;font-size:11.5px;color:var(--dim);margin-top:7px}
.kv b{color:var(--txt);font-weight:600}
.meter{height:5px;border-radius:4px;background:rgba(255,255,255,.10);overflow:hidden;margin-top:5px}
.meter i{display:block;height:100%;width:0;background:linear-gradient(90deg,#4f86ff,#5fd7c0);transition:width .4s}
.note{font-size:11px;color:var(--dim);margin-top:7px;line-height:1.45}
.barlabel{display:flex;justify-content:space-between;font-size:11px;color:var(--dim);margin:9px 0 4px}
.barlabel span{color:var(--txt)}
.bar{display:flex;height:15px;border-radius:5px;overflow:hidden;background:rgba(255,255,255,.06)}
.bar span{min-width:0;height:100%;position:relative}
.legend{display:flex;flex-wrap:wrap;gap:4px 12px;margin-top:9px}
.legend div{display:flex;align-items:center;gap:5px;font-size:10.5px;color:var(--dim)}
.legend i{width:8px;height:8px;border-radius:2px;display:inline-block}
.ladder{display:flex;align-items:center;gap:5px;margin-top:9px;font-size:10.5px;color:var(--dim);flex-wrap:wrap}
.ladder span{display:flex;flex-direction:column;align-items:center;padding:3px 7px;border-radius:7px;
background:rgba(255,255,255,.05);border:1px solid var(--line)}
.ladder span b{color:var(--txt);font-size:12.5px}
.ladder span em{font-style:normal;font-size:9.5px;opacity:.75}
.ladder span.hot{background:rgba(255,107,87,.18);border-color:rgba(255,107,87,.45)}
.ladder i{font-style:normal;opacity:.45}
.verdict{margin-top:9px;font-size:11.5px;line-height:1.5;border-top:1px solid var(--line);padding-top:8px}
.verdict b{color:#ff8d6b}
.verdict u{color:var(--accent);text-decoration:none;font-weight:600}
#labels{position:fixed;inset:0;pointer-events:none;z-index:3}
.tag{position:absolute;transform:translate(-50%,-50%);text-align:center;white-space:nowrap}
.tag b{display:block;font-size:11px;letter-spacing:.13em;text-transform:uppercase;font-weight:700}
.tag span{display:block;font-size:10.5px;color:var(--dim);margin-top:2px}
@media (max-width:980px){
#hud{grid-template-columns:1fr 1fr}
header{max-width:330px}
#controls{max-width:250px}
}
@media (max-width:640px){
#hud{grid-template-columns:1fr;max-height:52vh;overflow:auto}
header{max-width:calc(100vw - 32px)}
#controls{top:auto;bottom:auto;right:16px;top:16px}
}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<div id="labels"></div>
<header class="glass">
<h1>Population Bottleneck</h1>
<p>A random catastrophe wipes out most of a population. The few survivors rebuild the numbers —
but the <b>variants</b> they carry are only a sample of the original gene pool.</p>
<div class="phase"><span id="phaseName">Ancestral population</span><i><b id="phaseFill"></b></i></div>
<div id="tip">Click any individual to inspect it · drag to orbit · wheel to zoom · shift-drag to pan</div>
</header>
<div id="controls">
<div class="grp glass">
<button id="btnPlay">⏸ Pause</button>
<button id="btnReplay">↺ Replay</button>
<button id="btnNew">⚄ New bottleneck</button>
</div>
<div class="grp glass">
<button data-speed="0.5">0.5×</button>
<button data-speed="1" class="on">1×</button>
<button data-speed="2">2×</button>
</div>
<div class="grp glass">
<button data-focus="A">Ancestral</button>
<button data-focus="B">Colony</button>
<button data-focus="C">Recovered</button>
<button data-focus="all">Overview</button>
</div>
</div>
<div id="hud" class="glass">
<div class="card">
<h2><span class="dot" style="background:#6ea8ff"></span>Ancestral population</h2>
<div class="big"><span id="aCount">96</span><small>individuals</small></div>
<div class="kv"><span>Variant richness</span><b id="aRich">8 / 8</b></div>
<div class="meter"><i id="aMeter"></i></div>
<div class="kv"><span>Diversity index</span><b id="aDiv">1.00</b></div>
<div class="note" id="aNote">Perfectly balanced across all eight variants.</div>
</div>
<div class="card">
<h2><span class="dot" style="background:#ffa14f"></span>After the bottleneck</h2>
<div class="big"><span id="bCount">10</span><small>survivors</small></div>
<div class="kv"><span>Variant richness</span><b id="bRich">— / 8</b></div>
<div class="meter"><i id="bMeter"></i></div>
<div class="kv"><span>Diversity index</span><b id="bDiv">—</b></div>
<div class="note" id="bNote">Only the lineages that happened to be in the safe zone survive.</div>
</div>
<div class="card">
<h2><span class="dot" style="background:#49d6b0"></span>Recovered population</h2>
<div class="big"><span id="cCount">0</span><small>individuals</small></div>
<div class="kv"><span>Variant richness</span><b id="cRich">0 / 8</b></div>
<div class="meter"><i id="cMeter"></i></div>
<div class="kv"><span>Diversity index</span><b id="cDiv">0.00</b></div>
<div class="note" id="cNote">Numbers climb back — the palette of variants does not.</div>
</div>
<div class="card">
<h2>Variant composition · founder effect</h2>
<div class="barlabel">Ancestral <span id="barALabel">8 variants</span></div>
<div class="bar" id="barA"></div>
<div class="barlabel">Recovered <span id="barCLabel">0 variants</span></div>
<div class="bar" id="barC"></div>
<div class="legend" id="legend"></div>
<div class="ladder" id="ladder"></div>
<div class="verdict" id="verdict">Headcount returns to <u>96 / 96</u>, but only <b>—</b> of the 8 original variants remain.</div>
</div>
</div>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
/* ============================================================
Palette + constants
============================================================ */
const VARIANTS = [
{ name:'Ember', hex:0xff6b57 },
{ name:'Amber', hex:0xffb03a },
{ name:'Lime', hex:0xb6e14a },
{ name:'Mint', hex:0x43d9a3 },
{ name:'Cyan', hex:0x3ec6f0 },
{ name:'Azure', hex:0x4f86ff },
{ name:'Violet', hex:0x9a6bff },
{ name:'Rose', hex:0xff6bb5 }
];
const NV = VARIANTS.length;
const TOTAL = 96; // ancestral headcount
const K = 10; // bottleneck survivors
const GENS = 4; // generations of re-growth
const GEN_DUR = 2.4;
const ST = {
A: { x:-8.4, r:3.5, y:0.18, c:0x6ea8ff, title:'Ancestral population' },
B: { x: 0.0, r:3.5, y:0.18, c:0xffa14f, title:'Surviving colony' },
C: { x: 8.4, r:4.2, y:0.18, c:0x49d6b0, title:'Recovered population' }
};
ST.B.title = 'Surviving colony';
const $ = id => document.getElementById(id);
/* ============================================================
Renderer / scene
============================================================ */
const canvas = $('scene');
const renderer = new THREE.WebGLRenderer({ canvas, antialias:true, powerPreference:'high-performance' });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x080b11);
scene.fog = new THREE.Fog(0x080b11, 36, 105);
const camera = new THREE.PerspectiveCamera(46, innerWidth/innerHeight, 0.1, 400);
/* lights */
scene.add(new THREE.HemisphereLight(0x9fc6ff, 0x131722, 0.62));
const key = new THREE.DirectionalLight(0xffffff, 1.45);
key.position.set(11, 19, 9);
key.castShadow = true;
key.shadow.mapSize.set(2048, 2048);
key.shadow.camera.left = -22; key.shadow.camera.right = 22;
key.shadow.camera.top = 18; key.shadow.camera.bottom = -18;
key.shadow.camera.near = 1; key.shadow.camera.far = 60;
key.shadow.bias = -0.0012;
scene.add(key);
const fill = new THREE.DirectionalLight(0x4fd6ff, 0.55); fill.position.set(-15, 7, -9); scene.add(fill);
const rim = new THREE.DirectionalLight(0xff9a6b, 0.55); rim.position.set(2, 5, -17); scene.add(rim);
/* ============================================================
Environment geometry (stylized solid forms)
============================================================ */
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(160, 160),
new THREE.MeshStandardMaterial({ color:0x0b0e15, roughness:1 })
);
ground.rotation.x = -Math.PI/2; ground.position.y = -0.62; ground.receiveShadow = true;
scene.add(ground);
const slab = new THREE.Mesh(
new THREE.BoxGeometry(31, 0.5, 12.5),
new THREE.MeshStandardMaterial({ color:0x151a24, roughness:.85, metalness:.05 })
);
slab.position.set(0, -0.25, 0); slab.receiveShadow = true; scene.add(slab);
const grid = new THREE.GridHelper(31, 31, 0x2a3346, 0x1b2231);
grid.position.set(0, 0.005, 0);
grid.material.transparent = true; grid.material.opacity = 0.35;
scene.add(grid);
const stationGroup = new THREE.Group(); scene.add(stationGroup);
function buildStation(s){
const disc = new THREE.Mesh(
new THREE.CylinderGeometry(s.r, s.r, 0.18, 64),
new THREE.MeshStandardMaterial({ color:0x1c2432, roughness:.7, metalness:.1 })
);
disc.position.set(s.x, 0.09, 0); disc.receiveShadow = true; stationGroup.add(disc);
const edge = new THREE.Mesh(
new THREE.TorusGeometry(s.r, 0.045, 8, 96),
new THREE.MeshStandardMaterial({ color:s.c, emissive:s.c, emissiveIntensity:1.1, roughness:.4 })
);
edge.rotation.x = Math.PI/2; edge.position.set(s.x, 0.185, 0); stationGroup.add(edge);
const inner = new THREE.Mesh(
new THREE.RingGeometry(s.r*0.62, s.r*0.645, 96),
new THREE.MeshBasicMaterial({ color:s.c, transparent:true, opacity:.22, side:THREE.DoubleSide })
);
inner.rotation.x = -Math.PI/2; inner.position.set(s.x, 0.185, 0); stationGroup.add(inner);
}
buildStation(ST.A); buildStation(ST.B); buildStation(ST.C);
/* the funnel: the bottleneck itself */
const funnelMat = new THREE.MeshStandardMaterial({
color:0xff7a4d, emissive:0xff5a2e, emissiveIntensity:.45, transparent:true,
opacity:.30, roughness:.35, metalness:.15, side:THREE.DoubleSide, depthWrite:false
});
const funnel = new THREE.Mesh(new THREE.CylinderGeometry(1.85, 0.8, 1.75, 40, 1, true), funnelMat);
funnel.rotation.z = Math.PI/2; funnel.position.set(-4.2, 0.55, 0); scene.add(funnel);
const funnelLip = new THREE.Mesh(
new THREE.TorusGeometry(0.8, 0.07, 10, 40),
new THREE.MeshStandardMaterial({ color:0xffb27a, emissive:0xff7a3d, emissiveIntensity:1.6 })
);
funnelLip.rotation.y = Math.PI/2; funnelLip.position.set(-3.32, 0.55, 0); scene.add(funnelLip);
/* walkway B -> C with flow chevrons */
const walk = new THREE.Mesh(
new THREE.BoxGeometry(1.5, 0.18, 2.6),
new THREE.MeshStandardMaterial({ color:0x1b2230, roughness:.8 })
);
walk.position.set(3.85, 0.09, 0); walk.receiveShadow = true; scene.add(walk);
const chevrons = [];
const chevMat = new THREE.MeshStandardMaterial({ color:0x5fd7c0, emissive:0x5fd7c0, emissiveIntensity:1.2, roughness:.4 });
for(let i=0;i<3;i++){
const ch = new THREE.Mesh(new THREE.ConeGeometry(0.28, 0.46, 3), chevMat);
ch.rotation.z = -Math.PI/2; ch.position.set(3.4 + i*0.45, 0.26, 0); scene.add(ch); chevrons.push(ch);
}
/* ============================================================
Individual "pawn" geometry (solid, faceted)
============================================================ */
const bodyGeo = new THREE.CylinderGeometry(0.13, 0.195, 0.36, 10);
const headGeo = new THREE.IcosahedronGeometry(0.145, 0);
const baseGeo = new THREE.CylinderGeometry(0.20, 0.225, 0.035, 14);
const ringGeo = new THREE.TorusGeometry(0.30, 0.028, 6, 28);
const bodyMats = VARIANTS.map(v => new THREE.MeshStandardMaterial({
color:v.hex, roughness:.45, metalness:.05, flatShading:true }));
const headMats = VARIANTS.map(v => {
const c = new THREE.Color(v.hex).lerp(new THREE.Color(0xffffff), 0.42);
return new THREE.MeshStandardMaterial({ color:c, roughness:.32, metalness:.05, flatShading:true });
});
const baseMat = new THREE.MeshStandardMaterial({ color:0x1a2130, roughness:.85 });
const ringMat = new THREE.MeshStandardMaterial({ color:0xffe6b0, emissive:0xffc46b, emissiveIntensity:1.4, roughness:.4 });
const ghostGroup = new THREE.Group(); scene.add(ghostGroup);
function createPerson(variant){
const root = new THREE.Group();
const inner = new THREE.Group();
root.add(inner);
const base = new THREE.Mesh(baseGeo, baseMat); base.position.y = 0.0175;
const body = new THREE.Mesh(bodyGeo, bodyMats[variant]); body.position.y = 0.215; body.castShadow = true;
const head = new THREE.Mesh(headGeo, headMats[variant]); head.position.y = 0.50; head.castShadow = true;
inner.add(base, body, head);
body.userData.p = head.userData.p = base.userData.p = null;
scene.add(root);
return {
root, inner, variant,
loc:'A', lineage:-1, cslot:0, colonyIdx:0,
target:new THREE.Vector3(), from:new THREE.Vector3(), to:new THREE.Vector3(),
moving:false, t0:0, dur:1, arc:0, onArrive:null,
dying:false, dyingT0:0, deathDur:1.4, deathAt:null, moveAt:null,
birthT0:null, bob:Math.random()*6.28, ring:null, isSurvivor:false, removed:false, bornGen:0
};
}
/* ============================================================
Math helpers
============================================================ */
function mulberry32(a){ return function(){ a|=0; a=a+0x6D2B79F5|0;
let t=Math.imul(a^a>>>15,1|a); t=t+Math.imul(t^t>>>7,61|t)^t; return ((t^t>>>14)>>>0)/4294967296; }; }
const clamp=(v,a,b)=>Math.max(a,Math.min(b,v));
const easeInOutCubic=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;
const easeOutBack=t=>{const c1=1.70158,c3=c1+1;return 1+c3*Math.pow(t-1,3)+c1*Math.pow(t-1,2);};
const easeIn=t=>t*t*t;
function shuffle(arr,rng){ for(let i=arr.length-1;i>0;i--){ const j=Math.floor(rng()*(i+1)); [arr[i],arr[j]]=[arr[j],arr[i]]; } return arr; }
function phyllo(count, radius){
const out=[], ga=Math.PI*(3-Math.sqrt(5));
for(let i=0;i<count;i++){
const r=radius*Math.sqrt((i+0.5)/count), a=i*ga;
out.push(new THREE.Vector3(Math.cos(a)*r,0,Math.sin(a)*r));
}
return out;
}
function countsOf(list){ const c=new Array(NV).fill(0); list.forEach(p=>c[p.variant]++); return c; }
function richness(c){ return c.filter(x=>x>0).length; }
function divIndex(c){
let n=0,H=0; c.forEach(x=>{n+=x;});
if(!n) return 0;
c.forEach(x=>{ if(x>0){ const p=x/n; H -= p*Math.log(p); } });
return H/Math.log(NV);
}
function effectiveVariants(c){ let n=0,H=0; c.forEach(x=>n+=x); if(!n) return 0;
c.forEach(x=>{ if(x>0){ const p=x/n; H -= p*Math.log(p); } }); return Math.exp(H); }
/* ============================================================
Simulation state
============================================================ */
let rng = mulberry32(1);
let alive = [];
let simTime = 0, phaseIndex = 0, phaseTime = 0, playing = true, speed = 1;
let genIndex = 0, nextGenAt = 0, pendingDispersal = null;
let survivors = [], ancestralCounts = new Array(NV).fill(12);
let ledger = [];
const nextSlot = new Array(NV).fill(0);
let colonyCounter = 0;
const PHASES = [
{ id:'ancestral', dur:4.0, label:'1 · Ancestral population' },
{ id:'bottleneck', dur:3.8, label:'2 · Bottleneck event' },
{ id:'colony', dur:2.4, label:'3 · The surviving colony' },
{ id:'expansion', dur:9.6, label:'4 · Re-growth, generation by generation' },
{ id:'recovery', dur:3.4, label:'5 · Headcount restored — diversity not' },
{ id:'done', dur:Infinity, label:'6 · Founder effect' }
];
function reset(seed){
for(const p of alive){ scene.remove(p.root); if(p.ring) p.ring.parent && p.ring.parent.remove(p.ring); }
alive = [];
for(const g of [...ghostGroup.children]){ ghostGroup.remove(g); if(g.material) g.material.dispose(); }
simTime=0; phaseIndex=0; phaseTime=0; genIndex=0; pendingDispersal=null;
survivors=[]; ledger=[]; colonyCounter=0; nextSlot.fill(0);
rng = mulberry32(seed);
const slots = shuffle(phyllo(TOTAL, ST.A.r*0.88), rng);
let k=0;
for(let v=0; v<NV; v++){
for(let j=0;j<TOTAL/NV;j++){
const p = createPerson(v);
p.loc='A'; p.cslot=j;
const s = slots[k++];
p.root.position.set(ST.A.x+s.x, ST.A.y, s.z);
p.root.rotation.y = rng()*Math.PI*2;
p.bob = rng()*6.28;
alive.push(p);
}
}
ancestralCounts = countsOf(alive);
ledger.push({ n:alive.length, r:richness(ancestralCounts) });
selected = null;
enterPhase('ancestral');
updateHUD(true);
}
/* ---------- phase logic ---------- */
function enterPhase(id){
if(id==='bottleneck') selectSurvivors();
if(id==='expansion'){ genIndex=0; nextGenAt = simTime+0.35; }
if(id==='recovery'){
// last colony members finally join the new range
const colony = alive.filter(p=>p.loc==='B');
if(colony.length){ dispatchToC(colony, 1.2); }
}
if(id==='done'){ playing=false; syncPlayButton(); }
$('phaseName').textContent = PHASES[phaseIndex].label;
}
function selectSurvivors(){
const pool = alive.filter(p=>p.loc==='A');
const front = pool.filter(p=> Math.abs(p.root.position.z)<1.9 && p.root.position.x>ST.A.x);
const chosen = [];
for(const p of shuffle(front.slice(), rng)){ if(chosen.length>=K) break; chosen.push(p); }
if(chosen.length<K){
const rest = shuffle(pool.filter(p=>!chosen.includes(p)), rng);
for(const p of rest){ if(chosen.length>=K) break; chosen.push(p); }
}
survivors = chosen;
survivors.forEach((p,i)=>{
p.isSurvivor = true; p.lineage = i; p.deathAt = null;
p.moveAt = simTime + 0.95 + i*0.075;
const ring = new THREE.Mesh(ringGeo, ringMat);
ring.rotation.x = Math.PI/2; ring.position.y = 0.03;
p.root.add(ring); p.ring = ring;
p.colonyIdx = colonyCounter++;
});
const doomed = pool.filter(p=>!p.isSurvivor);
doomed.forEach((p,i)=>{ p.deathAt = simTime + 0.30 + i*0.016; });
ledger.push({ n:K, r:richness(countsOf(survivors)) });
}
/* ---------- movement ---------- */
function moveTo(p, x,y,z, dur, arc){
p.from.copy(p.root.position);
p.to.set(x,y,z);
p.t0 = simTime; p.dur = dur; p.arc = arc; p.moving = true;
}
function colonyTarget(idx){
const ga = Math.PI*(3-Math.sqrt(5));
const r = 2.85*Math.sqrt((idx+0.5)/46);
return new THREE.Vector3(ST.B.x + Math.cos(idx*ga)*r, ST.B.y, Math.sin(idx*ga)*r);
}
/* sector packing: each surviving variant owns a wedge of the new range */
function assignSectors(members){
const byV = new Map();
for(const p of members){ if(!byV.has(p.variant)) byV.set(p.variant, []); byV.get(p.variant).push(p); }
const total = members.length || 1;
const keys = [...byV.keys()].sort((a,b)=>a-b);
let a0 = 0;
for(const v of keys){
const list = byV.get(v).sort((a,b)=>a.cslot-b.cslot);
const span = list.length/total*Math.PI*2;
const perRow = Math.max(3, Math.ceil(Math.sqrt(list.length*2.2)));
const rows = Math.ceil(list.length/perRow);
list.forEach((p,i)=>{
const row = Math.floor(i/perRow), col = i%perRow;
const inRow = Math.min(perRow, list.length-row*perRow);
const rad = ST.C.r*0.9*(0.15+0.85*(row+0.5)/rows);
const jitter = ((p.cslot%7)/7-0.5)*span*0.12;
const ang = a0 + (col+0.5)/inRow*span + jitter;
p.target.set(ST.C.x+Math.cos(ang)*rad, ST.C.y, Math.sin(ang)*rad);
});
a0 += span;
}
}
function dispatchToC(movers, dur){
const proj = alive.filter(p=>!p.dying && (p.loc==='C' || movers.includes(p)));
proj.forEach(p=>{ if(p.cslot===undefined) p.cslot = nextSlot[p.variant]++; });
assignSectors(proj);
for(const p of movers){
if(p.cslot===undefined) p.cslot = nextSlot[p.variant]++;
p.loc = 'C';
moveTo(p, p.target.x, ST.C.y, p.target.z, dur*(0.85+rng()*0.4), 1.1+rng()*0.6);
}
}
/* ---------- generations ---------- */
function doGeneration(){
const target = Math.min(TOTAL, K*Math.pow(2, genIndex+1));
const colony = alive.filter(p=>p.loc==='B');
const births = Math.max(0, target - alive.filter(p=>!p.dying).length);
for(let i=0;i<births;i++){
const pool = colony.length ? colony : alive.filter(p=>!p.dying);
const parent = pool[Math.floor(rng()*pool.length)];
let v = parent.variant;
if(rng() < 0.004) v = Math.floor(rng()*NV); // rare new mutation
const p = createPerson(v);
p.lineage = parent.lineage >= 0 ? parent.lineage : 0;
p.loc = 'B'; p.bornGen = genIndex+1; p.colonyIdx = colonyCounter++;
p.birthT0 = simTime + rng()*0.3;
p.root.position.set(parent.root.position.x+(rng()-.5)*0.55, ST.B.y, parent.root.position.z+(rng()-.5)*0.55);
p.inner.scale.setScalar(0.001);
p.target.copy(colonyTarget(p.colonyIdx));
alive.push(p);
}
// drift: a variant represented by a single individual may be lost
if(genIndex < GENS-1){
const living = alive.filter(p=>!p.dying);
const cc = countsOf(living);
for(let v=0; v<NV; v++){
if(cc[v]===1 && rng()<0.35){
const victim = living.find(p=>p.variant===v);
if(victim){ victim.dying = true; victim.dyingT0 = simTime; }
}
}
}
pendingDispersal = { at: simTime + 1.0 };
ledger.push({ n:alive.filter(p=>!p.dying).length, r:richness(countsOf(alive.filter(p=>!p.dying))) });
}
/* ============================================================
Per-frame update
============================================================ */
const removals = [];
function updatePeople(dt){
removals.length = 0;
for(const p of alive){
if(p.dying){
const u = clamp((simTime - p.dyingT0)/p.deathDur, 0, 1);
p.inner.scale.setScalar(Math.max(0, 1-easeIn(u)));
if(u>=1 && !p.removed){ p.removed = true; removals.push(p); }
continue;
}
if(p.birthT0 !== null){
const u = clamp((simTime-p.birthT0)/0.55, 0, 1);
p.inner.scale.setScalar(easeOutBack(u));
if(u>=1) p.birthT0 = null;
} else p.inner.scale.setScalar(1);
if(p.moving){
let u = (simTime-p.t0)/p.dur;
if(u>=1){ u=1; p.moving=false; p.root.position.copy(p.to); if(p.onArrive){ p.onArrive(); p.onArrive=null; } }
else {
const e = easeInOutCubic(u);
p.root.position.lerpVectors(p.from, p.to, e);
p.root.position.y += Math.sin(Math.PI*u)*p.arc;
const dx = p.to.x-p.from.x, dz = p.to.z-p.from.z;
if(dx*dx+dz*dz > 1e-6){
const ang = Math.atan2(dx,dz);
let diff = ang - p.root.rotation.y;
while(diff>Math.PI) diff-=2*Math.PI; while(diff<-Math.PI) diff+=2*Math.PI;
p.root.rotation.y += diff*Math.min(1, dt*7);
}
}
} else if(p.loc==='C'){
const k = 1-Math.exp(-3.5*dt);
p.root.position.x += (p.target.x-p.root.position.x)*k;
p.root.position.z += (p.target.z-p.root.position.z)*k;
p.root.position.y += (ST.C.y-p.root.position.y)*k;
} else if(p.loc==='B' && p.colonyIdx!==undefined){
const t = colonyTarget(p.colonyIdx);
const k = 1-Math.exp(-3.0*dt);
p.root.position.x += (t.x-p.root.position.x)*k;
p.root.position.z += (t.z-p.root.position.z)*k;
}
p.inner.position.y = Math.sin(simTime*1.7 + p.bob)*0.028;
if(p.ring){ const s = 1 + Math.sin(simTime*3 + p.bob)*0.12; p.ring.scale.setScalar(s); }
}
for(const p of removals){
// leave a faint ghost of the lost individual
const gm = new THREE.MeshBasicMaterial({ color:0x93b6e8, transparent:true, opacity:0.0, depthWrite:false });
const g = new THREE.Mesh(bodyGeo, gm);
g.position.copy(p.root.position); g.rotation.y = p.root.rotation.y;
ghostGroup.add(g);
g.userData.t0 = simTime;
scene.remove(p.root);
}
if(removals.length) alive = alive.filter(p=>!p.removed);
for(const g of [...ghostGroup.children]){
const o = clamp((simTime-g.userData.t0)/0.8, 0, 1);
g.material.opacity = 0.16*o;
}
}
function step(dt){
if(playing && phaseIndex < PHASES.length){
simTime += dt*speed;
phaseTime += dt*speed;
// scheduled events
for(const p of alive){
if(p.loc==='A' && !p.isSurvivor && p.deathAt!==null && !p.dying && simTime>=p.deathAt){
p.dying = true; p.dyingT0 = simTime;
const gm = new THREE.MeshBasicMaterial({ color:0xff8f9a, transparent:true, opacity:0.0, depthWrite:false });
const g = new THREE.Mesh(bodyGeo, gm);
g.position.copy(p.root.position); g.rotation.y = p.root.rotation.y; ghostGroup.add(g);
g.userData.t0 = simTime;
}
if(p.isSurvivor && p.moveAt!==null && !p.moving && simTime>=p.moveAt){
p.moveAt = null; p.loc = 'B';
const t = colonyTarget(p.colonyIdx);
moveTo(p, t.x, ST.B.y, t.z, 1.9+rng()*0.4, 1.0);
}
}
if(pendingDispersal && simTime >= pendingDispersal.at){
pendingDispersal = null;
const colony = alive.filter(p=>p.loc==='B');
if(colony.length>1){
const keep = colony[Math.floor(rng()*colony.length)];
dispatchToC(colony.filter(p=>p!==keep), 1.5);
}
}
const ph = PHASES[phaseIndex];
if(ph.id==='expansion' && genIndex<GENS && simTime>=nextGenAt){
doGeneration(); genIndex++; nextGenAt += GEN_DUR;
}
if(ph.dur!==Infinity && phaseTime>=ph.dur){
phaseIndex++; phaseTime=0;
if(phaseIndex<PHASES.length) enterPhase(PHASES[phaseIndex].id);
}
}
updatePeople(dt);
}
/* ============================================================
HUD
============================================================ */
const legendEl = $('legend');
VARIANTS.forEach(v=>{
const d = document.createElement('div');
d.innerHTML = `<i style="background:#${v.hex.toString(16).padStart(6,'0')}"></i>${v.name}`;
legendEl.appendChild(d);
});
function renderBar(el, counts){
el.innerHTML='';
const total = counts.reduce((a,b)=>a+b,0) || 1;
for(let i=0;i<NV;i++){
const s = document.createElement('span');
const frac = counts[i]/total;
s.style.flexGrow = String(counts[i] ? Math.max(frac,0.004) : 0.018);
s.style.flexBasis = '0';
s.style.background = counts[i]
? `#${VARIANTS[i].hex.toString(16).padStart(6,'0')}`
: `repeating-linear-gradient(45deg, #${VARIANTS[i].hex.toString(16).padStart(6,'0')}44 0 3px, transparent 3px 6px)`;
s.title = `${VARIANTS[i].name}: ${counts[i]}`;
el.appendChild(s);
}
}
function setText(id, v){ const e=$(id); if(e.textContent!==v) e.textContent=v; }
let hudTimer = 0;
function updateHUD(force){
const living = alive.filter(p=>!p.dying);
const cCounts = countsOf(living);
const cRich = richness(cCounts);
const cDiv = divIndex(cCounts);
const bCounts = countsOf(survivors);
const bRich = richness(bCounts);
const bDiv = divIndex(bCounts);
const aRich = richness(ancestralCounts), aDiv = divIndex(ancestralCounts);
setText('aCount', alive.length?TOTAL:TOTAL);
setText('aRich', `${aRich} / ${NV}`);
setText('aDiv', aDiv.toFixed(2));
$('aMeter').style.width = (aDiv*100).toFixed(0)+'%';
setText('bCount', survivors.length?K:0);
setText('bRich', survivors.length?`${bRich} / ${NV}`:'— / 8');
setText('bDiv', survivors.length?bDiv.toFixed(2):'—');
$('bMeter').style.width = ((survivors.length?bDiv:0)*100).toFixed(0)+'%';
setText('cCount', living.length);
setText('cRich', `${cRich} / ${NV}`);
setText('cDiv', cDiv.toFixed(2));
$('cMeter').style.width = (cDiv*100).toFixed(0)+'%';
setText('barALabel', `${aRich} variants`);
setText('barCLabel', `${cRich} variants`);
renderBar($('barA'), ancestralCounts);
renderBar($('barC'), cCounts);
const lost = NV - cRich;
$('verdict').innerHTML = `Headcount returns to <u>${living.length} / ${TOTAL}</u>, but only <b>${cRich}</b> of the ${NV} original variants remain (<b>${lost}</b> lost). Effective diversity: <u>${effectiveVariants(ancestralCounts).toFixed(1)} → ${effectiveVariants(cCounts).toFixed(1)}</u> variants.`;
// ladder
const lad = $('ladder');
lad.innerHTML = '';
ledger.forEach((L,idx)=>{
const sp = document.createElement('span');
sp.innerHTML = `<b>${L.n}</b><em>${L.r} var</em>`;
if(idx===1) sp.className='hot';
lad.appendChild(sp);
if(idx<ledger.length-1){ const a=document.createElement('i'); a.textContent='→'; lad.appendChild(a); }
});
// station labels
const inA = alive.filter(p=>p.loc==='A'&&!p.dying).length;
const inB = alive.filter(p=>p.loc==='B'&&!p.dying).length;
const inC = alive.filter(p=>p.loc==='C'&&!p.dying).length;
setText('lA', `${inA} of ${TOTAL} remain · ${aRich} variants`);
setText('lB', `${inB} individuals · ${bRich} variants`);
setText('lC', `${inC} individuals · ${cRich} variants`);
}
/* ============================================================
Station labels (projected to screen)
============================================================ */
const labelEls = {};
for(const key of ['A','B','C']){
const d = document.createElement('div');
d.className = 'tag';
const c = ST[key].c.toString(16).padStart(6,'0');
d.innerHTML = `<b style="color:#${c}">${ST[key].title}</b><span id="l${key}"></span>`;
$('labels').appendChild(d);
labelEls[key] = d;
}
const _v = new THREE.Vector3();
function updateLabels(){
for(const key of ['A','B','C']){
const s = ST[key];
_v.set(s.x, 2.55, 0).project(camera);
const el = labelEls[key];
if(_v.z > 1){ el.style.display='none'; continue; }
el.style.display='block';
el.style.left = ((_v.x*0.5+0.5)*innerWidth)+'px';
el.style.top = ((-_v.y*0.5+0.5)*innerHeight)+'px';
}
}
/* ============================================================
Camera: hand-rolled orbit / pan / zoom
============================================================ */
const cam = { theta:0.62, phi:1.08, dist:27, target:new THREE.Vector3(0,1.2,0),
tTheta:0.62, tPhi:1.08, tDist:27, tTarget:new THREE.Vector3(0,1.2,0) };
function updateCamera(dt){
const k = 1-Math.pow(0.0009, dt);
cam.theta += (cam.tTheta-cam.theta)*k;
cam.phi += (cam.tPhi-cam.phi)*k;
cam.dist += (cam.tDist-cam.dist)*k;
cam.target.lerp(cam.tTarget, k);
const sp = Math.sin(cam.phi);
camera.position.set(
cam.target.x + cam.dist*sp*Math.sin(cam.theta),
cam.target.y + cam.dist*Math.cos(cam.phi),
cam.target.z + cam.dist*sp*Math.cos(cam.theta)
);
camera.lookAt(cam.target);
}
const pointers = new Map();
let dragDist = 0, panning = false;
canvas.addEventListener('contextmenu', e=>e.preventDefault());
canvas.addEventListener('pointerdown', e=>{
canvas.setPointerCapture(e.pointerId);
pointers.set(e.pointerId, {x:e.clientX, y:e.clientY});
dragDist = 0; panning = (e.button===2 || e.shiftKey);
});
canvas.addEventListener('pointermove', e=>{
if(!pointers.has(e.pointerId)) return;
const prev = pointers.get(e.pointerId);
const dx = e.clientX-prev.x, dy = e.clientY-prev.y;
pointers.set(e.pointerId, {x:e.clientX, y:e.clientY});
dragDist += Math.abs(dx)+Math.abs(dy);
if(pointers.size===2){ handlePinch(); return; }
if(panning){
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0);
const up = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 1);
const s = cam.dist*0.0013;
cam.tTarget.addScaledVector(right, -dx*s).addScaledVector(up, dy*s);
cam.tTarget.y = clamp(cam.tTarget.y, -1, 8);
} else {
cam.tTheta -= dx*0.005;
cam.tPhi = clamp(cam.tPhi - dy*0.005, 0.12, 1.48);
}
});
function handlePinch(){
const ps = [...pointers.values()];
if(ps.length<2) return;
const d = Math.hypot(ps[0].x-ps[1].x, ps[0].y-ps[1].y);
if(pinchPrev){ cam.tDist = clamp(cam.tDist * (pinchPrev/d), 9, 70); }
pinchPrev = d;
}
let pinchPrev = null;
canvas.addEventListener('pointerup', e=>{
pointers.delete(e.pointerId); if(pointers.size<2) pinchPrev=null;
if(dragDist < 6) pick(e);
});
canvas.addEventListener('pointercancel', e=>{ pointers.delete(e.pointerId); pinchPrev=null; });
canvas.addEventListener('wheel', e=>{
e.preventDefault();
cam.tDist = clamp(cam.tDist * (1 + e.deltaY*0.0011), 9, 70);
}, {passive:false});
/* ---------- picking ---------- */
const ray = new THREE.Raycaster();
let selected = null, selRing = null;
const selRingMat = new THREE.MeshBasicMaterial({ color:0xffffff, transparent:true, opacity:.85 });
function pick(e){
const r = canvas.getBoundingClientRect();
const nd = new THREE.Vector2(((e.clientX-r.left)/r.width)*2-1, -((e.clientY-r.top)/r.height)*2+1);
ray.setFromCamera(nd, camera);
const hits = ray.intersectObjects(scene.children, true);
for(const h of hits){
let o = h.object;
while(o && !o.userData.p) o = o.parent;
if(o && o.userData.p){ select(o.userData.p); return; }
}
select(null);
}
function select(p){
selected = p;
if(selRing){ scene.remove(selRing); selRing=null; }
if(p){
selRing = new THREE.Mesh(new THREE.TorusGeometry(0.42,0.03,6,32), selRingMat);
selRing.rotation.x = Math.PI/2; scene.add(selRing);
const v = VARIANTS[p.variant];
$('tip').innerHTML = `<b>${v.name}</b> variant · lineage from survivor <b>#${p.lineage+1}</b> ·
${p.loc==='A'?'ancestral range':p.loc==='B'?'colony site':'new range'} ·
${p.bornGen?`born in generation ${p.bornGen}`:'ancestral individual'}`;
} else {
$('tip').innerHTML = 'Click any individual to inspect it · drag to orbit · wheel to zoom · shift-drag to pan';
}
}
/* ============================================================
Controls
============================================================ */
function syncPlayButton(){ $('btnPlay').textContent = playing ? '⏸ Pause' : '▶ Play'; }
$('btnPlay').onclick = ()=>{ if(phaseIndex>=PHASES.length-1){ reset(Math.floor(Math.random()*1e6)); playing=true; } else playing=!playing; syncPlayButton(); };
$('btnReplay').onclick = ()=>{ const s = Math.floor(Math.random()*1e6); seedKeep = s; reset(s); playing=true; syncPlayButton(); };
$('btnNew').onclick = ()=>{ reset(Math.floor(Math.random()*1e6)); playing=true; syncPlayButton(); };
document.querySelectorAll('[data-speed]').forEach(b=>{
b.onclick = ()=>{ speed = parseFloat(b.dataset.speed);
document.querySelectorAll('[data-speed]').forEach(x=>x.classList.toggle('on', x===b)); };
});
document.querySelectorAll('[data-focus]').forEach(b=>{
b.onclick = ()=>{
const f = b.dataset.focus;
if(f==='all'){ cam.tTarget.set(0,1.2,0); cam.tDist=27; cam.tTheta=0.62; cam.tPhi=1.08; }
else { const s=ST[f]; cam.tTarget.set(s.x,1.1,0); cam.tDist=15; }
};
});
window.addEventListener('keydown', e=>{
if(e.code==='Space'){ e.preventDefault(); $('btnPlay').click(); }
if(e.key==='r'||e.key==='R'){ $('btnReplay').click(); }
});
window.addEventListener('resize', ()=>{
camera.aspect = innerWidth/innerHeight; camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
});
/* ============================================================
Main loop
============================================================ */
reset(Math.floor(Math.random()*1e6));
syncPlayButton();
const clock = new THREE.Clock();
let hudAcc = 0;
function animate(){
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
step(dt);
updateCamera(dt);
// ambient motion
funnelMat.emissiveIntensity = 0.35 + Math.sin(simTime*2.2)*0.2;
funnelLip.rotation.z += dt*0.9;
chevrons.forEach((c,i)=>{ c.material.emissiveIntensity = 0.6 + 1.2*Math.max(0, Math.sin(simTime*3 - i*0.7)); });
if(selRing && selected){ selRing.position.set(selected.root.position.x, selected.root.position.y+0.03, selected.root.position.z); }
hudAcc += dt;
if(hudAcc > 0.12){ hudAcc = 0; updateHUD(); }
const ph = PHASES[phaseIndex];
$('phaseFill').style.width = (ph.dur===Infinity?100:clamp(phaseTime/ph.dur*100,0,100))+'%';
updateLabels();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```