Prompt specification
Build or customize the Three.js 3D scene "Evolutionary replay counterfactual explorer" 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: Evolutionary replay counterfactual explorer
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/evolutionary-replay-counterfactual-explorer-x0900
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts evolutionary timescales. Run several seeded versions of a simple mutation-drift-selection model from the same start; display divergent outcomes and emphasize that the simulation has no preset final organism. Low-poly.
Working Three.js Starter (evolutionary-replay-counterfactual-explorer-x0900):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Evolution in Parallel — A Seeded Lineage Study</title>
<style>
:root {
color-scheme: dark;
--bg: #07110f;
--panel: rgba(9, 24, 21, 0.82);
--panel-strong: rgba(10, 29, 25, 0.94);
--line: rgba(164, 226, 204, 0.17);
--text: #e8f3ed;
--muted: #91aaa0;
--mint: #8fe2c1;
--warm: #ffd49a;
--shadow: 0 22px 70px rgba(0, 0, 0, 0.35);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input { font: inherit; }
button {
color: inherit;
cursor: pointer;
}
#stage {
position: fixed;
inset: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
linear-gradient(90deg, rgba(4, 12, 10, 0.75), transparent 30%, transparent 72%, rgba(4, 12, 10, 0.45)),
linear-gradient(0deg, rgba(4, 12, 10, 0.8), transparent 30%);
z-index: 2;
}
.intro {
position: fixed;
z-index: 5;
top: 30px;
left: 32px;
width: min(470px, calc(100vw - 64px));
pointer-events: none;
text-shadow: 0 3px 22px rgba(0, 0, 0, 0.55);
}
.kicker {
display: flex;
align-items: center;
gap: 10px;
color: var(--mint);
font: 700 11px/1.2 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.pulse {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--mint);
box-shadow: 0 0 0 0 rgba(143, 226, 193, 0.55);
animation: pulse 2s infinite;
}
@keyframes pulse {
0% { box-shadow: 0 0 0 0 rgba(143, 226, 193, 0.45); }
70% { box-shadow: 0 0 0 9px rgba(143, 226, 193, 0); }
100% { box-shadow: 0 0 0 0 rgba(143, 226, 193, 0); }
}
h1 {
margin: 15px 0 13px;
font-size: clamp(38px, 5vw, 68px);
font-weight: 680;
line-height: 0.96;
letter-spacing: -0.055em;
}
h1 em {
color: var(--warm);
font-style: normal;
font-weight: 480;
}
.intro > p {
max-width: 430px;
margin: 0;
color: #b5c9c0;
font-size: 14px;
line-height: 1.55;
}
.badges {
display: flex;
flex-wrap: wrap;
gap: 7px;
margin-top: 18px;
}
.badge {
border: 1px solid var(--line);
border-radius: 999px;
padding: 6px 9px;
background: rgba(9, 25, 21, 0.52);
color: #a9c1b7;
font: 600 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.1em;
text-transform: uppercase;
backdrop-filter: blur(10px);
}
.panel {
position: fixed;
z-index: 6;
top: 24px;
right: 24px;
width: 320px;
max-height: calc(100vh - 205px);
overflow: auto;
border: 1px solid var(--line);
border-radius: 18px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(18px) saturate(120%);
scrollbar-width: thin;
scrollbar-color: rgba(143, 226, 193, 0.3) transparent;
}
.panel-section {
padding: 17px;
border-bottom: 1px solid var(--line);
}
.panel-section:last-child { border-bottom: 0; }
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
color: #b8ccc3;
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.panel-title span:last-child {
color: #6f8b80;
font-weight: 500;
letter-spacing: 0.06em;
}
.seed-control {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
}
.seed-control input {
min-width: 0;
border: 1px solid var(--line);
border-radius: 9px;
outline: none;
padding: 9px 11px;
background: rgba(0, 0, 0, 0.18);
color: var(--text);
font: 600 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.seed-control input:focus {
border-color: rgba(143, 226, 193, 0.55);
}
.primary {
border: 1px solid rgba(143, 226, 193, 0.35);
border-radius: 9px;
padding: 9px 12px;
background: rgba(143, 226, 193, 0.12);
color: #bff3de;
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
text-transform: uppercase;
transition: background 150ms ease, transform 150ms ease;
}
.primary:hover {
background: rgba(143, 226, 193, 0.2);
transform: translateY(-1px);
}
.runs {
display: grid;
gap: 5px;
}
.run-row {
position: relative;
display: grid;
grid-template-columns: 9px minmax(0, 1fr) 48px;
align-items: center;
gap: 9px;
min-height: 46px;
padding: 7px 8px;
border: 1px solid transparent;
border-radius: 10px;
cursor: pointer;
transition: background 140ms ease, border-color 140ms ease;
}
.run-row:hover,
.run-row.selected {
border-color: var(--line);
background: rgba(255, 255, 255, 0.035);
}
.run-dot {
width: 7px;
height: 25px;
border-radius: 8px;
background: var(--run);
box-shadow: 0 0 12px color-mix(in srgb, var(--run) 45%, transparent);
}
.run-name {
overflow: hidden;
font: 700 10px/1.1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
white-space: nowrap;
}
.run-seed {
margin-top: 4px;
overflow: hidden;
color: #708b80;
font: 500 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
text-overflow: ellipsis;
white-space: nowrap;
}
.trait-strip {
display: flex;
gap: 2px;
width: 73px;
margin-top: 5px;
}
.trait-strip i {
display: block;
width: 16px;
height: 2px;
border-radius: 2px;
background: var(--run);
opacity: 0.85;
}
.measure {
text-align: right;
}
.measure b {
display: block;
font: 700 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.measure small {
display: block;
margin-top: 5px;
color: #6d877d;
font: 500 8px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.no-final {
margin: 13px;
padding: 14px;
border: 1px solid rgba(255, 212, 154, 0.24);
border-radius: 12px;
background:
radial-gradient(circle at 100% 0%, rgba(255, 212, 154, 0.11), transparent 55%),
rgba(255, 212, 154, 0.035);
}
.no-final strong {
color: var(--warm);
font: 750 10px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.12em;
}
.no-final p {
margin: 8px 0 0;
color: #b8c5bd;
font-size: 11px;
line-height: 1.48;
}
details summary {
color: #a9c2b7;
cursor: pointer;
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
text-transform: uppercase;
}
details p,
details ul {
color: #8fa89d;
font-size: 11px;
line-height: 1.55;
}
details p { margin-bottom: 8px; }
details ul {
margin: 0;
padding-left: 16px;
}
details li { margin: 5px 0; }
.timeline {
position: fixed;
z-index: 7;
left: 30px;
right: 30px;
bottom: 22px;
display: grid;
grid-template-columns: auto minmax(260px, 1fr) auto;
align-items: center;
gap: 20px;
padding: 14px 16px;
border: 1px solid var(--line);
border-radius: 17px;
background: var(--panel-strong);
box-shadow: var(--shadow);
backdrop-filter: blur(18px) saturate(125%);
}
.transport {
display: flex;
align-items: center;
gap: 8px;
}
.icon-button {
display: grid;
place-items: center;
width: 38px;
height: 38px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
color: #cde0d7;
font-size: 13px;
transition: background 140ms ease;
}
.icon-button:hover { background: rgba(143, 226, 193, 0.12); }
#play {
width: 44px;
border-color: rgba(143, 226, 193, 0.32);
background: rgba(143, 226, 193, 0.12);
color: #bff3de;
}
.time-readout {
min-width: 78px;
margin-left: 3px;
}
.time-readout b {
display: block;
font: 700 13px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.time-readout small {
display: block;
margin-top: 6px;
color: #718b80;
font: 600 8px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.scrubber-wrap { min-width: 0; }
.scrubber-labels {
display: flex;
justify-content: space-between;
margin-bottom: 8px;
color: #6f897e;
font: 600 8px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.1em;
text-transform: uppercase;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
border-radius: 4px;
outline: none;
appearance: none;
background: linear-gradient(
90deg,
var(--mint) 0%,
var(--mint) var(--progress, 0%),
rgba(151, 186, 172, 0.18) var(--progress, 0%),
rgba(151, 186, 172, 0.18) 100%
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
border: 3px solid #10251f;
border-radius: 50%;
appearance: none;
background: #b8f4dc;
box-shadow: 0 0 0 1px rgba(184, 244, 220, 0.5), 0 0 18px rgba(143, 226, 193, 0.45);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 3px solid #10251f;
border-radius: 50%;
background: #b8f4dc;
}
.timeline-right {
display: flex;
align-items: center;
gap: 13px;
}
.horizon-copy {
max-width: 145px;
color: #758e83;
font: 600 8px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
text-align: right;
text-transform: uppercase;
}
.speed {
display: flex;
gap: 3px;
padding: 3px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(0, 0, 0, 0.15);
}
.speed button {
border: 0;
border-radius: 6px;
padding: 6px 7px;
background: transparent;
color: #718a80;
font: 700 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.speed button.active {
background: rgba(143, 226, 193, 0.13);
color: #bff3de;
}
.toast {
position: fixed;
z-index: 20;
left: 50%;
top: 25px;
transform: translate(-50%, -15px);
padding: 10px 15px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(8, 25, 20, 0.92);
color: #bdd3c9;
box-shadow: var(--shadow);
opacity: 0;
pointer-events: none;
font: 600 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
transition: opacity 180ms ease, transform 180ms ease;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 900px) {
.intro { top: 20px; left: 20px; }
.panel { top: auto; right: 16px; bottom: 112px; width: 285px; max-height: 48vh; }
.timeline { left: 16px; right: 16px; bottom: 12px; gap: 10px; }
.horizon-copy { display: none; }
.badges { display: none; }
.intro > p { max-width: 360px; }
}
@media (max-width: 650px) {
h1 { font-size: 36px; }
.intro > p { display: none; }
.panel {
top: 106px;
right: 12px;
bottom: auto;
width: min(285px, calc(100vw - 24px));
max-height: 43vh;
}
.panel-section { padding: 12px; }
.no-final { margin: 9px; }
.timeline {
grid-template-columns: auto 1fr;
padding: 11px;
}
.timeline-right { display: none; }
.time-readout { min-width: 69px; }
}
</style>
</head>
<body>
<div id="stage"></div>
<div class="vignette"></div>
<header class="intro">
<div class="kicker"><span class="pulse"></span> Seeded lineage study / live model</div>
<h1>Many futures.<br><em>No fixed form.</em></h1>
<p>
Six populations begin with the same founder. Mutation, drift and a
shifting ecological field send each lineage toward a different—but
entirely unprescribed—future.
</p>
<div class="badges">
<span class="badge">Low-poly populations</span>
<span class="badge">40 individuals / run</span>
<span class="badge">6 reproducible histories</span>
</div>
</header>
<aside class="panel" aria-label="Simulation controls and outcomes">
<section class="panel-section">
<div class="panel-title">
<span>Reproducible batch</span>
<span>Master seed</span>
</div>
<div class="seed-control">
<input id="seedInput" type="number" min="1" max="999999999" value="4172"
aria-label="Master seed" />
<button class="primary" id="runButton">Run batch</button>
</div>
</section>
<section class="panel-section">
<div class="panel-title">
<span>Divergent outcomes</span>
<span id="outcomeGeneration">Gen 00</span>
</div>
<div class="runs" id="runs"></div>
</section>
<div class="no-final">
<strong>NO PRESET FINAL ORGANISM</strong>
<p>
The right edge is only the view horizon. These populations have no
destination, endpoint organism, or scripted evolution path.
</p>
</div>
<section class="panel-section">
<details>
<summary>What is being simulated?</summary>
<p>
Every run starts with 40 identical five-locus genomes. A different
pseudorandom seed changes the subsequent stochastic events.
</p>
<ul>
<li><strong>Mutation:</strong> copied loci can change.</li>
<li><strong>Drift:</strong> random reproduction changes frequencies.</li>
<li><strong>Selection:</strong> fitness follows a niche that itself moves; no fixed optimum is encoded.</li>
</ul>
</details>
</section>
</aside>
<footer class="timeline">
<div class="transport">
<button class="icon-button" id="rewind" aria-label="Return to beginning">↺</button>
<button class="icon-button" id="play" aria-label="Play or pause">▶</button>
<div class="time-readout">
<b id="generation">00 / 80</b>
<small>generation</small>
</div>
</div>
<div class="scrubber-wrap">
<div class="scrubber-labels">
<span>Common founder</span>
<span>Finite view · not an endpoint</span>
</div>
<input id="timeline" type="range" min="0" max="80" step="1" value="0"
aria-label="Evolutionary generation" />
</div>
<div class="timeline-right">
<div class="horizon-copy">Drag to orbit<br>Shift-drag to pan<br>Scroll to zoom</div>
<div class="speed" aria-label="Playback speed">
<button data-speed="0.5">½×</button>
<button data-speed="1" class="active">1×</button>
<button data-speed="2">2×</button>
</div>
</div>
</footer>
<div class="toast" id="toast"></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Model constants
// -------------------------------------------------------------------------
const RUN_COUNT = 6;
const POPULATION_SIZE = 40;
const GENE_COUNT = 5;
const MAX_GENERATION = 80;
const SNAPSHOT_INTERVAL = 2;
const SNAPSHOT_COUNT = MAX_GENERATION / SNAPSHOT_INTERVAL + 1;
const VISIBLE_INDIVIDUALS = 5;
const ORIGIN_X = -8.2;
const TIMELINE_LENGTH = 16.0;
const LANE_SPACING = 2.08;
const RUN_COLORS = [
0x83e2c1, 0xffb56f, 0x7ebcff,
0xf493bb, 0xe6dc79, 0xb39aff
];
const RUN_CSS_COLORS = [
"#83e2c1", "#ffb56f", "#7ebcff",
"#f493bb", "#e6dc79", "#b39aff"
];
const $ = (selector) => document.querySelector(selector);
const stage = $("#stage");
const seedInput = $("#seedInput");
const runButton = $("#runButton");
const runsElement = $("#runs");
const timeline = $("#timeline");
const playButton = $("#play");
const rewindButton = $("#rewind");
const generationLabel = $("#generation");
const outcomeGeneration = $("#outcomeGeneration");
const toast = $("#toast");
// -------------------------------------------------------------------------
// Seeded stochastic utilities
// -------------------------------------------------------------------------
function mulberry32(seed) {
let a = seed >>> 0;
return function () {
a += 0x6D2B79F5;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function gaussian(rng) {
let u = 0;
let v = 0;
while (u === 0) u = rng();
while (v === 0) v = rng();
return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
}
function deriveSeed(masterSeed, runIndex) {
const mixed = (masterSeed ^ Math.imul(runIndex + 1, 0x9E3779B1)) >>> 0;
return mixed;
}
function clamp01(value) {
return Math.max(0.02, Math.min(0.98, value));
}
function mean(values) {
let total = 0;
for (const value of values) total += value;
return total / values.length;
}
function distanceSquared(a, b) {
let total = 0;
for (let i = 0; i < a.length; i++) {
const d = a[i] - b[i];
total += d * d;
}
return total / a.length;
}
function populationDiversity(population) {
let total = 0;
let pairs = 0;
for (let i = 0; i < population.length; i++) {
for (let j = i + 1; j < population.length; j++) {
total += Math.sqrt(distanceSquared(population[i], population[j]));
pairs++;
}
}
return pairs ? total / pairs : 0;
}
// -------------------------------------------------------------------------
// Mutation–drift–selection simulation.
// The selection niche moves as a random walk and has no final coordinate.
// -------------------------------------------------------------------------
function simulateRun(seed) {
const rng = mulberry32(seed);
let population = Array.from(
{ length: POPULATION_SIZE },
() => Array(GENE_COUNT).fill(0.5)
);
// All runs begin with the same neutral niche and identical founder genomes.
let niche = Array(GENE_COUNT).fill(0.5);
const history = [];
for (let generation = 0; generation <= MAX_GENERATION; generation++) {
const geneMeans = Array.from(
{ length: GENE_COUNT },
(_, geneIndex) => mean(population.map(individual => individual[geneIndex]))
);
const geneVariances = Array.from(
{ length: GENE_COUNT },
(_, geneIndex) => mean(
population.map(individual =>
Math.pow(individual[geneIndex] - geneMeans[geneIndex], 2)
)
)
);
const meanFitness = mean(population.map(individual =>
Math.exp(-3.2 * distanceSquared(individual, niche))
));
const diversity = populationDiversity(population);
const founderDistance = Math.sqrt(mean(
geneMeans.map(value => Math.pow(value - 0.5, 2))
));
history.push({
population: population.map(individual => individual.slice()),
geneMeans,
geneVariances,
meanFitness,
diversity,
founderDistance,
niche: niche.slice()
});
if (generation === MAX_GENERATION) break;
// The ecological niche wanders without being assigned a destination.
niche = niche.map(value =>
clamp01(value + gaussian(rng) * 0.030 + (rng() - 0.5) * 0.012)
);
// Frequency-dependent selection toward the current moving niche.
const weights = population.map(individual =>
Math.exp(-4.0 * distanceSquared(individual, niche)) + 0.012 + rng() * 0.008
);
const cumulative = [];
let totalWeight = 0;
for (const weight of weights) {
totalWeight += weight;
cumulative.push(totalWeight);
}
const nextPopulation = [];
for (let childIndex = 0; childIndex < POPULATION_SIZE; childIndex++) {
const target = rng() * totalWeight;
let parentIndex = 0;
while (
parentIndex < cumulative.length - 1 &&
target > cumulative[parentIndex]
) {
parentIndex++;
}
const parent = population[parentIndex];
const child = parent.slice();
for (let geneIndex = 0; geneIndex < GENE_COUNT; geneIndex++) {
if (rng() < 0.17) {
let delta = gaussian(rng) * 0.075;
if (rng() < 0.018) delta += (rng() < 0.5 ? -1 : 1) * 0.16;
child[geneIndex] = clamp01(child[geneIndex] + delta);
}
}
nextPopulation.push(child);
}
population = nextPopulation;
}
return { seed, history };
}
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07110f);
scene.fog = new THREE.FogExp2(0x07110f, 0.031);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.18;
stage.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xc5f4e4, 0x07100e, 1.65);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffefd2, 2.25);
keyLight.position.set(-5, 11, 8);
scene.add(keyLight);
const coolLight = new THREE.DirectionalLight(0x79c9ff, 1.15);
coolLight.position.set(9, 4, -9);
scene.add(coolLight);
const warmLight = new THREE.PointLight(0xffa96f, 1.25, 24);
warmLight.position.set(-4, 3, -5);
scene.add(warmLight);
const grid = new THREE.GridHelper(38, 38, 0x315149, 0x142b26);
grid.position.y = -2.2;
grid.material.transparent = true;
grid.material.opacity = 0.25;
scene.add(grid);
const axisGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(ORIGIN_X, -2.12, 6.25),
new THREE.Vector3(ORIGIN_X + TIMELINE_LENGTH, -2.12, 6.25)
]);
const axisLine = new THREE.Line(
axisGeometry,
new THREE.LineBasicMaterial({
color: 0x75b9a3,
transparent: true,
opacity: 0.34
})
);
scene.add(axisLine);
// Sparse atmospheric points.
const particleCount = 420;
const particlePositions = new Float32Array(particleCount * 3);
const atmosphereRng = mulberry32(99117);
for (let i = 0; i < particleCount; i++) {
particlePositions[i * 3] = (atmosphereRng() - 0.5) * 30;
particlePositions[i * 3 + 1] = (atmosphereRng() - 0.5) * 14;
particlePositions[i * 3 + 2] = (atmosphereRng() - 0.5) * 25;
}
const particleGeometry = new THREE.BufferGeometry();
particleGeometry.setAttribute(
"position",
new THREE.BufferAttribute(particlePositions, 3)
);
const particles = new THREE.Points(
particleGeometry,
new THREE.PointsMaterial({
color: 0xa4d8c6,
size: 0.035,
transparent: true,
opacity: 0.34,
depthWrite: false
})
);
scene.add(particles);
// Low-poly population instances: one body and one four-sided crest per symbol.
const totalVisibleInstances = RUN_COUNT * SNAPSHOT_COUNT * VISIBLE_INDIVIDUALS;
const bodyGeometry = new THREE.IcosahedronGeometry(1, 0);
const crestGeometry = new THREE.ConeGeometry(0.55, 1, 4);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.76,
metalness: 0.03,
flatShading: true
});
const crestMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.82,
metalness: 0.02,
flatShading: true
});
const bodyMesh = new THREE.InstancedMesh(
bodyGeometry,
bodyMaterial,
totalVisibleInstances
);
bodyMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
bodyMesh.frustumCulled = false;
const crestMesh = new THREE.InstancedMesh(
crestGeometry,
crestMaterial,
totalVisibleInstances
);
crestMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
crestMesh.frustumCulled = false;
scene.add(bodyMesh, crestMesh);
// Common founder population.
const founderBody = new THREE.InstancedMesh(
bodyGeometry,
new THREE.MeshStandardMaterial({
color: 0xe6d6a8,
roughness: 0.78,
flatShading: true
}),
9
);
const founderCrest = new THREE.InstancedMesh(
crestGeometry,
new THREE.MeshStandardMaterial({
color: 0xb99f72,
roughness: 0.8,
flatShading: true
}),
9
);
const founderDummy = new THREE.Object3D();
for (let i = 0; i < 9; i++) {
const angle = i * Math.PI * 2 / 9;
const radius = i === 0 ? 0 : 0.43;
founderDummy.position.set(
ORIGIN_X + Math.cos(angle) * radius,
0.28 + Math.sin(angle * 1.7) * 0.07,
Math.sin(angle) * radius
);
founderDummy.rotation.set(0, angle, 0);
founderDummy.scale.set(0.20, 0.16, 0.14);
founderDummy.updateMatrix();
founderBody.setMatrixAt(i, founderDummy.matrix);
founderDummy.position.y += 0.145;
founderDummy.scale.set(0.065, 0.19, 0.065);
founderDummy.updateMatrix();
founderCrest.setMatrixAt(i, founderDummy.matrix);
}
founderBody.instanceMatrix.needsUpdate = true;
founderCrest.instanceMatrix.needsUpdate = true;
scene.add(founderBody, founderCrest);
const founderRing = new THREE.Mesh(
new THREE.TorusGeometry(0.76, 0.018, 4, 40),
new THREE.MeshBasicMaterial({
color: 0xe6d6a8,
transparent: true,
opacity: 0.45
})
);
founderRing.rotation.x = Math.PI / 2;
founderRing.position.set(ORIGIN_X, -0.04, 0);
scene.add(founderRing);
// -------------------------------------------------------------------------
// Labels made from canvas textures
// -------------------------------------------------------------------------
function createLabel(text, color = "#bff3de", scale = 3.1) {
const canvas = document.createElement("canvas");
canvas.width = 640;
canvas.height = 128;
const context = canvas.getContext("2d");
context.fillStyle = "rgba(6, 20, 16, 0.78)";
context.strokeStyle = "rgba(184, 244, 220, 0.22)";
context.lineWidth = 2;
context.beginPath();
context.roundRect(3, 3, 634, 122, 22);
context.fill();
context.stroke();
context.fillStyle = color;
context.font = "700 30px ui-monospace, SFMono-Regular, Menlo, monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 320, 65);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(scale, scale * 0.2, 1);
sprite.renderOrder = 20;
return sprite;
}
const founderLabel = createLabel("COMMON FOUNDER · 40 IDENTICAL GENOMES", "#f0ddb2", 4.4);
founderLabel.position.set(ORIGIN_X, 1.35, 0);
scene.add(founderLabel);
const horizonLabel = createLabel("VIEW HORIZON ≠ DESTINATION", "#ffd49a", 3.7);
horizonLabel.position.set(ORIGIN_X + TIMELINE_LENGTH + 0.5, 1.45, 0);
scene.add(horizonLabel);
for (const generation of [0, 20, 40, 60, 80]) {
const x = ORIGIN_X + generation / MAX_GENERATION * TIMELINE_LENGTH;
const label = createLabel(`${generation}G`, "#7ea797", 1.05);
label.position.set(x, -1.72, 6.25);
scene.add(label);
}
// -------------------------------------------------------------------------
// Direct camera controls — no external controls addon
// -------------------------------------------------------------------------
const controls = {
target: new THREE.Vector3(-0.2, 0.1, 0),
yaw: 0.24,
pitch: 0.51,
radius: 24.0
};
function updateCamera() {
const horizontalRadius = Math.cos(controls.pitch) * controls.radius;
camera.position.set(
controls.target.x + Math.sin(controls.yaw) * horizontalRadius,
controls.target.y + Math.sin(controls.pitch) * controls.radius,
controls.target.z + Math.cos(controls.yaw) * horizontalRadius
);
camera.lookAt(controls.target);
}
const pointers = new Map();
let previousPinchDistance = 0;
renderer.domElement.addEventListener("contextmenu", event => event.preventDefault());
renderer.domElement.addEventListener("pointerdown", event => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 2) {
const values = [...pointers.values()];
previousPinchDistance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
});
renderer.domElement.addEventListener("pointermove", event => {
const previous = pointers.get(event.pointerId);
if (!previous) return;
const dx = event.clientX - previous.x;
const dy = event.clientY - previous.y;
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 1) {
if (event.shiftKey || event.buttons === 2) {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3().crossVectors(forward, camera.up).normalize();
const panScale = controls.radius * 0.0014;
controls.target.addScaledVector(right, -dx * panScale);
controls.target.addScaledVector(forward, -dy * panScale);
controls.target.y += dy * panScale;
} else {
controls.yaw -= dx * 0.005;
controls.pitch += dy * 0.004;
controls.pitch = Math.max(0.12, Math.min(1.25, controls.pitch));
}
} else if (pointers.size === 2) {
const values = [...pointers.values()];
const distance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
if (previousPinchDistance > 0) {
controls.radius *= previousPinchDistance / Math.max(1, distance);
controls.radius = Math.max(11, Math.min(45, controls.radius));
}
previousPinchDistance = distance;
}
updateCamera();
});
function releasePointer(event) {
pointers.delete(event.pointerId);
previousPinchDistance = 0;
}
renderer.domElement.addEventListener("pointerup", releasePointer);
renderer.domElement.addEventListener("pointercancel", releasePointer);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
controls.radius *= Math.exp(event.deltaY * 0.001);
controls.radius = Math.max(11, Math.min(45, controls.radius));
updateCamera();
}, { passive: false });
// -------------------------------------------------------------------------
// Dynamic simulation state and visual rebuilding
// -------------------------------------------------------------------------
let simulations = [];
let visualSnapshots = [];
let trajectoryLines = [];
let runLabels = [];
let currentMarkers = [];
let currentGeneration = 0;
let isPlaying = false;
let playbackSpeed = 1;
let selectedRun = null;
let lastAppliedGeneration = -1;
const matrixDummy = new THREE.Object3D();
const hiddenMatrix = new THREE.Matrix4().makeScale(0.00001, 0.00001, 0.00001);
function snapshotCenter(runIndex, snapshotIndex) {
const generation = snapshotIndex * SNAPSHOT_INTERVAL;
const fanProgress = Math.min(1, generation / 8);
const fan = 1 - Math.pow(1 - fanProgress, 3);
const laneZ = (runIndex - (RUN_COUNT - 1) / 2) * LANE_SPACING;
return new THREE.Vector3(
ORIGIN_X + generation / MAX_GENERATION * TIMELINE_LENGTH,
0.28 + Math.sin(generation * 0.09 + runIndex * 0.8) * 0.14 * fan,
laneZ * fan
);
}
function removeDynamicObjects() {
for (const line of trajectoryLines) {
scene.remove(line);
line.geometry.dispose();
line.material.dispose();
}
trajectoryLines = [];
for (const label of runLabels) {
scene.remove(label);
label.material.map.dispose();
label.material.dispose();
}
runLabels = [];
for (const marker of currentMarkers) {
scene.remove(marker);
marker.geometry.dispose();
marker.material.dispose();
}
currentMarkers = [];
}
function rebuildBatch(masterSeed) {
isPlaying = false;
playButton.textContent = "▶";
currentGeneration = 0;
selectedRun = null;
lastAppliedGeneration = -1;
removeDynamicObjects();
simulations = Array.from({ length: RUN_COUNT }, (_, runIndex) =>
simulateRun(deriveSeed(masterSeed, runIndex))
);
visualSnapshots = [];
let instanceIndex = 0;
for (let runIndex = 0; runIndex < RUN_COUNT; runIndex++) {
const runSnapshots = [];
for (let snapshotIndex = 0; snapshotIndex < SNAPSHOT_COUNT; snapshotIndex++) {
const generation = snapshotIndex * SNAPSHOT_INTERVAL;
const state = simulations[runIndex].history[generation];
const center = snapshotCenter(runIndex, snapshotIndex);
const snapshot = { generation, center, state, instances: [] };
for (let visibleIndex = 0; visibleIndex < VISIBLE_INDIVIDUALS; visibleIndex++) {
const individual = state.population[visibleIndex];
const angle = visibleIndex * 2.39996 + snapshotIndex * 0.17;
const spread = 0.21 + state.diversity * 0.45;
const position = new THREE.Vector3(
center.x + Math.cos(angle) * spread,
center.y + Math.sin(angle * 1.7) * 0.10,
center.z + Math.sin(angle) * spread * 0.72
);
const bodyScale = new THREE.Vector3(
0.15 + individual[0] * 0.16,
0.11 + individual[1] * 0.17,
0.11 + individual[2] * 0.15
);
const bodyQuaternion = new THREE.Quaternion().setFromEuler(
new THREE.Euler(
(individual[4] - 0.5) * 0.35,
(individual[3] - 0.5) * 2.2 + visibleIndex * 0.55,
(individual[4] - 0.5) * 0.8
)
);
const bodyMatrix = new THREE.Matrix4().compose(
position,
bodyQuaternion,
bodyScale
);
const crestPosition = position.clone();
crestPosition.y += bodyScale.y * 0.72;
const crestQuaternion = new THREE.Quaternion().setFromEuler(
new THREE.Euler(
0,
bodyQuaternion.y,
(individual[4] - 0.5) * 1.2
)
);
const crestMatrix = new THREE.Matrix4().compose(
crestPosition,
crestQuaternion,
new THREE.Vector3(
0.055 + individual[2] * 0.035,
0.12 + individual[2] * 0.23,
0.055 + individual[2] * 0.035
)
);
const hue = (
0.08 +
individual[3] * 0.82 +
(individual[0] - 0.5) * 0.06 +
runIndex * 0.012 +
1
) % 1;
const bodyColor = new THREE.Color().setHSL(
hue,
0.62,
0.49 + (individual[4] - 0.5) * 0.08
);
const crestColor = new THREE.Color().setHSL(
(hue + 0.035) % 1,
0.68,
0.34
);
bodyMesh.setMatrixAt(instanceIndex, bodyMatrix);
bodyMesh.setColorAt(instanceIndex, bodyColor);
crestMesh.setMatrixAt(instanceIndex, crestMatrix);
crestMesh.setColorAt(instanceIndex, crestColor);
snapshot.instances.push({
bodyMatrix,
crestMatrix,
generation
});
instanceIndex++;
}
runSnapshots.push(snapshot);
}
visualSnapshots.push(runSnapshots);
const points = [
new THREE.Vector3(ORIGIN_X, 0.28, 0),
...runSnapshots.slice(1).map(snapshot => snapshot.center)
];
const lineGeometry = new THREE.BufferGeometry().setFromPoints(points);
const lineMaterial = new THREE.LineBasicMaterial({
color: RUN_COLORS[runIndex],
transparent: true,
opacity: 0.48,
depthWrite: false
});
const line = new THREE.Line(lineGeometry, lineMaterial);
line.geometry.setDrawRange(0, 0);
scene.add(line);
trajectoryLines.push(line);
const marker = new THREE.Mesh(
new THREE.TorusGeometry(0.48, 0.023, 4, 36),
new THREE.MeshBasicMaterial({
color: RUN_COLORS[runIndex],
transparent: true,
opacity: 0.72,
depthWrite: false
})
);
marker.rotation.x = Math.PI / 2;
scene.add(marker);
currentMarkers.push(marker);
const label = createLabel(
`RUN ${String.fromCharCode(65 + runIndex)} · ${simulations[runIndex].seed}`,
RUN_CSS_COLORS[runIndex],
2.8
);
label.position.set(
ORIGIN_X + TIMELINE_LENGTH + 0.8,
0.75,
(runIndex - (RUN_COUNT - 1) / 2) * LANE_SPACING
);
scene.add(label);
runLabels.push(label);
}
bodyMesh.instanceMatrix.needsUpdate = true;
crestMesh.instanceMatrix.needsUpdate = true;
bodyMesh.instanceColor.needsUpdate = true;
crestMesh.instanceColor.needsUpdate = true;
refreshTimeline(true);
updateRunCards();
}
// -------------------------------------------------------------------------
// Timeline rendering
// -------------------------------------------------------------------------
function pointOnTrajectory(runIndex, generation) {
const origin = new THREE.Vector3(ORIGIN_X, 0.28, 0);
const snapshots = visualSnapshots[runIndex];
if (generation <= 0) return origin.clone();
if (generation < SNAPSHOT_INTERVAL) {
return origin.clone().lerp(snapshots[0].center, generation / SNAPSHOT_INTERVAL);
}
const index = Math.min(
snapshots.length - 1,
Math.floor((generation - SNAPSHOT_INTERVAL) / SNAPSHOT_INTERVAL)
);
const nextIndex = Math.min(snapshots.length - 1, index + 1);
const startGeneration = SNAPSHOT_INTERVAL + index * SNAPSHOT_INTERVAL;
const fraction = Math.max(
0,
Math.min(1, (generation - startGeneration) / SNAPSHOT_INTERVAL)
);
return snapshots[index].center.clone().lerp(snapshots[nextIndex].center, fraction);
}
function refreshTimeline(force = false) {
const integerGeneration = Math.floor(currentGeneration);
if (force || integerGeneration !== lastAppliedGeneration) {
let instanceIndex = 0;
for (let runIndex = 0; runIndex < RUN_COUNT; runIndex++) {
for (const snapshot of visualSnapshots[runIndex]) {
const visible = snapshot.generation <= integerGeneration;
for (const instance of snapshot.instances) {
if (visible) {
bodyMesh.setMatrixAt(instanceIndex, instance.bodyMatrix);
crestMesh.setMatrixAt(instanceIndex, instance.crestMatrix);
} else {
bodyMesh.setMatrixAt(instanceIndex, hiddenMatrix);
crestMesh.setMatrixAt(instanceIndex, hiddenMatrix);
}
instanceIndex++;
}
}
}
bodyMesh.instanceMatrix.needsUpdate = true;
crestMesh.instanceMatrix.needsUpdate = true;
for (let runIndex = 0; runIndex < RUN_COUNT; runIndex++) {
let pointCount = 0;
if (integerGeneration >= 1) {
if (integerGeneration < SNAPSHOT_INTERVAL) {
pointCount = 2;
} else {
const latestSnapshot = Math.min(
SNAPSHOT_COUNT - 1,
Math.floor((integerGeneration - SNAPSHOT_INTERVAL) / SNAPSHOT_INTERVAL)
);
pointCount = latestSnapshot + 2;
}
}
trajectoryLines[runIndex].geometry.setDrawRange(0, pointCount);
}
lastAppliedGeneration = integerGeneration;
}
for (let runIndex = 0; runIndex < RUN_COUNT; runIndex++) {
const point = pointOnTrajectory(runIndex, currentGeneration);
currentMarkers[runIndex].position.set(point.x, point.y - 0.48, point.z);
const selected = selectedRun === null || selectedRun === runIndex;
trajectoryLines[runIndex].material.opacity = selected ? 0.62 : 0.12;
currentMarkers[runIndex].material.opacity = selected ? 0.86 : 0.25;
}
const displayGeneration = String(integerGeneration).padStart(2, "0");
generationLabel.textContent = `${displayGeneration} / ${MAX_GENERATION}`;
outcomeGeneration.textContent = `Gen ${displayGeneration}`;
const progress = currentGeneration / MAX_GENERATION * 100;
timeline.style.setProperty("--progress", `${progress}%`);
timeline.value = integerGeneration;
}
function updateRunCards() {
const generation = Math.floor(currentGeneration);
for (let runIndex = 0; runIndex < RUN_COUNT; runIndex++) {
const row = document.querySelector(`.run-row[data-run="${runIndex}"]`);
const state = simulations[runIndex].history[generation];
const divergence = Math.min(99, Math.round(state.founderDistance * 170));
const value = row.querySelector(".measure b");
const traits = row.querySelectorAll(".trait-strip i");
value.textContent = `${divergence}%`;
for (let geneIndex = 0; geneIndex < traits.length; geneIndex++) {
const trait = state.geneMeans[geneIndex];
const hue = ((0.08 + trait * 0.82) * 360) % 360;
traits[geneIndex].style.background = `hsl(${hue} 58% 58%)`;
traits[geneIndex].style.opacity = String(0.42 + trait * 0.58);
}
}
}
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
for (let runIndex = 0; runIndex < RUN_COUNT; runIndex++) {
const row = document.createElement("div");
row.className = "run-row";
row.dataset.run = String(runIndex);
row.style.setProperty("--run", RUN_CSS_COLORS[runIndex]);
row.innerHTML = `
<span class="run-dot"></span>
<div>
<div class="run-name">RUN ${String.fromCharCode(65 + runIndex)}</div>
<div class="run-seed"></div>
<div class="trait-strip"><i></i><i></i><i></i><i></i></div>
</div>
<div class="measure">
<b>0%</b>
<small>from start</small>
</div>
`;
row.addEventListener("click", () => {
selectedRun = selectedRun === runIndex ? null : runIndex;
document.querySelectorAll(".run-row").forEach(element => {
element.classList.toggle(
"selected",
Number(element.dataset.run) === selectedRun
);
});
refreshTimeline(true);
});
runsElement.appendChild(row);
}
function updateSeedsInCards() {
document.querySelectorAll(".run-row").forEach((row, runIndex) => {
row.querySelector(".run-seed").textContent =
`seed ${simulations[runIndex].seed}`;
});
}
function showToast(message) {
toast.textContent = message;
toast.classList.add("show");
clearTimeout(showToast.timeout);
showToast.timeout = setTimeout(() => toast.classList.remove("show"), 1800);
}
runButton.addEventListener("click", () => {
const seed = Math.max(1, Math.min(999999999, parseInt(seedInput.value, 10) || 1));
seedInput.value = String(seed);
rebuildBatch(seed);
updateSeedsInCards();
showToast(`Six new histories seeded from ${seed}`);
});
timeline.addEventListener("input", () => {
isPlaying = false;
playButton.textContent = "▶";
currentGeneration = Number(timeline.value);
refreshTimeline(true);
updateRunCards();
});
playButton.addEventListener("click", () => {
if (currentGeneration >= MAX_GENERATION) currentGeneration = 0;
isPlaying = !isPlaying;
playButton.textContent = isPlaying ? "Ⅱ" : "▶";
refreshTimeline(true);
});
rewindButton.addEventListener("click", () => {
isPlaying = false;
playButton.textContent = "▶";
currentGeneration = 0;
refreshTimeline(true);
updateRunCards();
});
document.querySelectorAll(".speed button").forEach(button => {
button.addEventListener("click", () => {
playbackSpeed = Number(button.dataset.speed);
document.querySelectorAll(".speed button").forEach(other => {
other.classList.toggle("active", other === button);
});
});
});
window.addEventListener("keydown", event => {
if (event.code === "Space" && event.target !== seedInput) {
event.preventDefault();
playButton.click();
}
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
// -------------------------------------------------------------------------
// Initialize and animate
// -------------------------------------------------------------------------
rebuildBatch(Number(seedInput.value));
updateSeedsInCards();
updateCamera();
let previousTime = performance.now();
function animate(now) {
const delta = Math.min(0.05, (now - previousTime) / 1000);
previousTime = now;
if (isPlaying) {
currentGeneration += delta * 8 * playbackSpeed;
if (currentGeneration >= MAX_GENERATION) {
currentGeneration = MAX_GENERATION;
isPlaying = false;
playButton.textContent = "▶";
showToast("View horizon reached · no final organism");
}
refreshTimeline();
updateRunCards();
}
const pulse = 1 + Math.sin(now * 0.0035) * 0.07;
for (const marker of currentMarkers) marker.scale.setScalar(pulse);
founderRing.material.opacity = 0.37 + Math.sin(now * 0.002) * 0.08;
particles.rotation.y += delta * 0.006;
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```