Prompt specification
Build or customize the Three.js 3D scene "Selection-rule 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: Selection-rule counterfactual explorer
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/selection-rule-counterfactual-explorer-x0940
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring natural selection. Let users change which trait is favored while holding the initial population and random seed fixed; compare generation-by-generation frequencies and retain clearly labeled model assumptions. Low-poly.
Working Three.js Starter (selection-rule-counterfactual-explorer-x0940):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Selection Field Lab — Natural Selection Explorer</title>
<style>
:root {
--bg: #edf0e8;
--panel: #fafbf7;
--panel-2: #f2f4ed;
--ink: #24322d;
--muted: #6f7d76;
--line: #dce2d8;
--dark: #20352e;
--speed: #efad3d;
--camouflage: #3f9b7d;
--endurance: #8068b3;
--shadow: 0 16px 44px rgba(39, 58, 49, 0.10);
}
* { box-sizing: border-box; }
html, body {
margin: 0;
min-height: 100%;
background: var(--bg);
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
height: 100vh;
overflow: hidden;
}
button, input, select { font: inherit; }
button {
color: inherit;
cursor: pointer;
}
.app-header {
height: 72px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 0 24px;
background: rgba(250, 251, 247, 0.94);
border-bottom: 1px solid var(--line);
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
width: 42px;
height: 42px;
display: grid;
place-items: center;
border-radius: 13px;
background: var(--dark);
color: #f6d57b;
box-shadow: inset 0 0 0 1px rgba(255,255,255,.08);
}
.brand-mark svg {
width: 25px;
height: 25px;
}
.eyebrow {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: .16em;
text-transform: uppercase;
}
.brand h1 {
margin: 2px 0 0;
font-size: 17px;
line-height: 1.1;
letter-spacing: -.02em;
}
.header-badges {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
justify-content: flex-end;
}
.badge {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 7px 10px;
border: 1px solid var(--line);
border-radius: 999px;
background: #fff;
color: var(--muted);
font-size: 11px;
font-weight: 750;
white-space: nowrap;
}
.badge strong {
color: var(--ink);
font-variant-numeric: tabular-nums;
}
.status-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: #53ad75;
box-shadow: 0 0 0 4px rgba(83,173,117,.13);
}
.layout {
height: calc(100vh - 72px);
display: grid;
grid-template-columns: 318px minmax(0, 1fr);
}
.sidebar {
min-height: 0;
overflow-y: auto;
padding: 20px;
background: var(--panel);
border-right: 1px solid var(--line);
scrollbar-width: thin;
}
.section-title {
margin: 0 0 5px;
font-size: 13px;
font-weight: 850;
letter-spacing: -.01em;
}
.section-copy {
margin: 0 0 14px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.control-section {
padding-bottom: 19px;
margin-bottom: 19px;
border-bottom: 1px solid var(--line);
}
.scenario-list {
display: grid;
gap: 8px;
}
.scenario-button {
width: 100%;
display: grid;
grid-template-columns: 34px 1fr auto;
align-items: center;
gap: 10px;
padding: 10px;
border: 1px solid var(--line);
border-radius: 12px;
background: #fff;
text-align: left;
transition: transform .15s ease, border-color .15s ease, box-shadow .15s ease;
}
.scenario-button:hover {
transform: translateY(-1px);
border-color: #c8d1c7;
}
.scenario-button.active {
border-color: var(--scenario-color);
box-shadow: 0 0 0 2px color-mix(in srgb, var(--scenario-color) 18%, transparent);
background: color-mix(in srgb, var(--scenario-color) 7%, white);
}
.trait-icon {
width: 34px;
height: 34px;
display: grid;
place-items: center;
border-radius: 10px;
color: #fff;
background: var(--scenario-color);
font-weight: 900;
font-size: 11px;
box-shadow: inset 0 -8px 15px rgba(0,0,0,.08);
}
.scenario-name {
display: block;
font-size: 12px;
font-weight: 850;
}
.scenario-description {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 10px;
}
.selected-indicator {
width: 16px;
height: 16px;
display: grid;
place-items: center;
border: 1.5px solid #cbd3ca;
border-radius: 50%;
}
.active .selected-indicator {
border-color: var(--scenario-color);
}
.active .selected-indicator::after {
content: "";
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--scenario-color);
}
.locked-fields {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.locked-field {
min-width: 0;
padding: 10px;
border: 1px solid var(--line);
border-radius: 10px;
background: var(--panel-2);
}
.locked-field span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: .10em;
text-transform: uppercase;
}
.locked-field strong {
display: block;
margin-top: 4px;
font-size: 13px;
font-variant-numeric: tabular-nums;
}
.locked-field small {
color: #7d8b84;
font-size: 9px;
font-weight: 750;
}
.timeline-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
}
.timeline-head output {
padding: 4px 8px;
border-radius: 7px;
background: var(--dark);
color: white;
font-size: 11px;
font-weight: 800;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
accent-color: var(--dark);
cursor: pointer;
}
.transport {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
margin-top: 12px;
}
.transport button {
border: 0;
border-radius: 9px;
padding: 9px 12px;
font-size: 11px;
font-weight: 800;
}
#playButton {
color: white;
background: var(--dark);
}
#resetButton {
background: #e8ece5;
}
.rate-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 10px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
}
.rate-row select {
border: 1px solid var(--line);
border-radius: 7px;
padding: 4px 7px;
background: white;
color: var(--ink);
font-size: 10px;
}
details {
border: 1px solid var(--line);
border-radius: 12px;
background: #fff;
overflow: hidden;
}
summary {
padding: 12px;
cursor: pointer;
font-size: 11px;
font-weight: 850;
list-style: none;
}
summary::-webkit-details-marker { display: none; }
summary::after {
content: "+";
float: right;
color: var(--muted);
font-size: 16px;
line-height: 12px;
}
details[open] summary::after { content: "−"; }
.assumptions {
padding: 0 12px 12px;
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
.assumptions ul {
margin: 0;
padding-left: 16px;
}
.assumptions li + li { margin-top: 6px; }
.assumptions strong { color: var(--ink); }
.workspace {
min-width: 0;
min-height: 0;
display: grid;
grid-template-rows: minmax(390px, 1fr) 330px;
gap: 14px;
padding: 14px;
overflow: hidden;
}
.stage-card,
.chart-card,
.summary-card {
position: relative;
min-width: 0;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 17px;
background: var(--panel);
box-shadow: var(--shadow);
}
#viewport {
position: absolute;
inset: 0;
overflow: hidden;
background:
radial-gradient(circle at 48% 28%, rgba(255,255,255,.95), rgba(221,231,220,.82) 54%, rgba(195,210,197,.9));
}
#viewport canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#viewport canvas:active { cursor: grabbing; }
.stage-overlay {
position: absolute;
z-index: 2;
pointer-events: none;
}
.stage-top {
top: 17px;
left: 17px;
right: 17px;
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 15px;
}
.stage-label {
padding: 10px 12px;
border: 1px solid rgba(255,255,255,.65);
border-radius: 11px;
background: rgba(250,252,247,.78);
backdrop-filter: blur(12px);
box-shadow: 0 8px 25px rgba(50,70,59,.08);
}
.stage-label strong {
display: block;
margin-top: 2px;
font-size: 14px;
}
.generation-pill {
padding: 9px 12px;
border-radius: 10px;
background: rgba(32,53,46,.9);
color: white;
font-size: 11px;
font-weight: 800;
box-shadow: 0 8px 25px rgba(32,53,46,.16);
}
.stage-bottom {
bottom: 17px;
left: 17px;
right: 17px;
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 12px;
}
.population-legend {
display: flex;
flex-wrap: wrap;
gap: 7px;
max-width: 520px;
}
.legend-chip {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 8px 10px;
border: 1px solid rgba(255,255,255,.6);
border-radius: 9px;
background: rgba(250,252,247,.82);
backdrop-filter: blur(10px);
font-size: 10px;
font-weight: 800;
}
.legend-swatch {
width: 9px;
height: 9px;
border-radius: 3px;
background: var(--swatch);
}
.camera-hint {
padding: 8px 10px;
border-radius: 9px;
background: rgba(250,252,247,.72);
color: #64746c;
backdrop-filter: blur(10px);
font-size: 9px;
font-weight: 750;
text-align: right;
}
.analysis-grid {
min-width: 0;
min-height: 0;
display: grid;
grid-template-columns: minmax(0, 1.65fr) minmax(280px, .85fr);
gap: 14px;
}
.chart-card,
.summary-card {
display: flex;
flex-direction: column;
padding: 16px;
box-shadow: none;
}
.chart-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 5px;
}
.chart-header h2,
.summary-card h2 {
margin: 0;
font-size: 13px;
letter-spacing: -.01em;
}
.chart-subtitle {
margin: 4px 0 0;
color: var(--muted);
font-size: 10px;
}
.metric-tabs {
display: flex;
gap: 4px;
padding: 3px;
border-radius: 9px;
background: var(--panel-2);
}
.metric-tab {
border: 0;
border-radius: 7px;
padding: 6px 8px;
background: transparent;
color: var(--muted);
font-size: 9px;
font-weight: 850;
}
.metric-tab.active {
background: white;
color: var(--ink);
box-shadow: 0 2px 8px rgba(40,60,50,.09);
}
.chart-wrap {
position: relative;
flex: 1;
min-height: 0;
margin-top: 4px;
}
#chart {
width: 100%;
height: 100%;
display: block;
cursor: crosshair;
touch-action: none;
}
.chart-tooltip {
position: absolute;
z-index: 4;
min-width: 145px;
display: none;
padding: 9px 10px;
border: 1px solid rgba(255,255,255,.7);
border-radius: 9px;
background: rgba(31,49,43,.94);
color: white;
box-shadow: 0 12px 30px rgba(30,45,38,.18);
pointer-events: none;
font-size: 9px;
line-height: 1.55;
}
.chart-tooltip strong {
display: block;
margin-bottom: 3px;
font-size: 10px;
}
.chart-legend {
display: flex;
gap: 13px;
flex-wrap: wrap;
padding-top: 3px;
}
.chart-legend button {
display: inline-flex;
align-items: center;
gap: 6px;
border: 0;
padding: 0;
background: transparent;
color: var(--muted);
font-size: 9px;
font-weight: 750;
}
.chart-legend button.active { color: var(--ink); }
.chart-legend i {
width: 15px;
height: 3px;
border-radius: 3px;
background: var(--legend-color);
}
.summary-card {
overflow-y: auto;
}
.summary-label {
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.stacked-bar {
height: 12px;
display: flex;
margin: 13px 0 10px;
overflow: hidden;
border-radius: 999px;
background: #e5eae3;
}
.stacked-bar span {
height: 100%;
transition: width .25s ease;
}
.summary-list {
display: grid;
gap: 6px;
}
.summary-row {
display: grid;
grid-template-columns: 9px 1fr auto auto;
align-items: center;
gap: 7px;
padding: 7px 8px;
border-radius: 8px;
font-size: 10px;
}
.summary-row.favored {
background: color-mix(in srgb, var(--row-color) 8%, white);
}
.summary-row .dot {
width: 8px;
height: 8px;
border-radius: 3px;
background: var(--row-color);
}
.summary-row .delta {
min-width: 42px;
color: var(--muted);
text-align: right;
font-variant-numeric: tabular-nums;
}
.summary-row .value {
min-width: 42px;
text-align: right;
font-weight: 850;
font-variant-numeric: tabular-nums;
}
.comparison-box {
margin-top: 12px;
padding-top: 11px;
border-top: 1px solid var(--line);
}
.comparison-title {
margin: 0 0 7px;
font-size: 10px;
font-weight: 850;
}
.comparison-table {
width: 100%;
border-collapse: collapse;
font-size: 9px;
}
.comparison-table th {
padding: 4px 3px;
color: var(--muted);
font-size: 8px;
font-weight: 750;
text-align: right;
text-transform: uppercase;
letter-spacing: .06em;
}
.comparison-table th:first-child,
.comparison-table td:first-child { text-align: left; }
.comparison-table td {
padding: 6px 3px;
border-top: 1px solid #e6ebe4;
text-align: right;
font-variant-numeric: tabular-nums;
}
.comparison-table tr.active td { font-weight: 850; }
.model-note {
margin-top: 10px;
padding: 9px;
border-radius: 8px;
background: var(--panel-2);
color: var(--muted);
font-size: 9px;
line-height: 1.5;
}
@media (max-width: 1050px) {
body { height: auto; overflow: auto; }
.layout {
height: auto;
grid-template-columns: 1fr;
}
.sidebar {
border-right: 0;
border-bottom: 1px solid var(--line);
}
.workspace {
grid-template-rows: 570px auto;
overflow: visible;
}
.analysis-grid {
grid-template-columns: 1fr;
}
.summary-card { min-height: 320px; }
}
@media (max-width: 620px) {
.app-header {
height: auto;
min-height: 72px;
padding: 12px 14px;
}
.header-badges { display: none; }
.sidebar { padding: 16px; }
.workspace { padding: 8px; gap: 8px; grid-template-rows: 510px auto; }
.analysis-grid { gap: 8px; }
.chart-card, .summary-card { padding: 13px; }
.chart-header { flex-direction: column; }
.camera-hint { display: none; }
}
</style>
</head>
<body>
<header class="app-header">
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none">
<path d="M5 17.5c2.2-6.1 5.4-9.2 9.6-9.2 2.2 0 3.8.8 5.4 2.3"
stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/>
<path d="M5.2 12.6c2.7.1 4.6 1.1 5.8 3.1M11 6.4c.2 2.3 1.2 4 3.2 5"
stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/>
<circle cx="5" cy="17.5" r="2" fill="currentColor"/>
<circle cx="14.8" cy="8" r="2" fill="currentColor"/>
</svg>
</div>
<div>
<div class="eyebrow">Interactive population ecology</div>
<h1>Selection Field Lab</h1>
</div>
</div>
<div class="header-badges">
<span class="badge"><span class="status-dot"></span> Deterministic model</span>
<span class="badge">Founder population <strong>120</strong></span>
<span class="badge">Seed <strong>271828</strong></span>
<span class="badge">Horizon <strong>60 generations</strong></span>
</div>
</header>
<main class="layout">
<aside class="sidebar">
<section class="control-section">
<h2 class="section-title">Favored trait</h2>
<p class="section-copy">
Change the environmental pressure. The founder population, seed, and random draw stream remain fixed.
</p>
<div class="scenario-list" id="scenarioList">
<button class="scenario-button active"
data-scenario="0"
style="--scenario-color: var(--speed)"
aria-pressed="true">
<span class="trait-icon">SPD</span>
<span>
<span class="scenario-name">Speed</span>
<span class="scenario-description">Fast movement is favored</span>
</span>
<span class="selected-indicator" aria-hidden="true"></span>
</button>
<button class="scenario-button"
data-scenario="1"
style="--scenario-color: var(--camouflage)"
aria-pressed="false">
<span class="trait-icon">CAM</span>
<span>
<span class="scenario-name">Camouflage</span>
<span class="scenario-description">Blending into cover is favored</span>
</span>
<span class="selected-indicator" aria-hidden="true"></span>
</button>
<button class="scenario-button"
data-scenario="2"
style="--scenario-color: var(--endurance)"
aria-pressed="false">
<span class="trait-icon">END</span>
<span>
<span class="scenario-name">Endurance</span>
<span class="scenario-description">Resilient survival is favored</span>
</span>
<span class="selected-indicator" aria-hidden="true"></span>
</button>
</div>
</section>
<section class="control-section">
<h2 class="section-title">Locked experiment</h2>
<p class="section-copy">Every pressure regime starts from exactly the same founders.</p>
<div class="locked-fields">
<div class="locked-field">
<span>Population</span>
<strong>120</strong>
<small>FIXED</small>
</div>
<div class="locked-field">
<span>Random seed</span>
<strong>271828</strong>
<small>FIXED</small>
</div>
</div>
</section>
<section class="control-section">
<div class="timeline-head">
<h2 class="section-title">Generation</h2>
<output id="generationOutput">0 / 60</output>
</div>
<input id="generationSlider"
type="range"
min="0"
max="60"
step="1"
value="0"
aria-label="Generation">
<div class="transport">
<button id="playButton" type="button">▶ Play selection</button>
<button id="resetButton" type="button">↺ Reset</button>
</div>
<div class="rate-row">
<label for="playbackRate">Playback speed</label>
<select id="playbackRate">
<option value="0.5">0.5×</option>
<option value="1" selected>1×</option>
<option value="2">2×</option>
<option value="4">4×</option>
</select>
</div>
</section>
<details open>
<summary>Model assumptions</summary>
<div class="assumptions">
<ul>
<li><strong>Traits are mutually exclusive:</strong> each individual is speed, camouflage, or endurance.</li>
<li><strong>Fixed founders:</strong> 120 individuals, initially 40 of each trait. The seed fixes their shuffled order.</li>
<li><strong>Relative fitness:</strong> favored trait = 1.00; each alternative = 0.62.</li>
<li><strong>Wright–Fisher reproduction:</strong> 120 offspring replace the adult population each generation.</li>
<li><strong>Mutation:</strong> 2% probability per offspring; mutation selects either alternative trait uniformly.</li>
<li><strong>Matched comparisons:</strong> all three regimes use the same pre-generated random draws.</li>
<li><strong>Excluded:</strong> no migration, mating preference, density dependence, or trait linkage.</li>
<li><strong>Interpretation:</strong> frequencies are model outputs, not biological forecasts.</li>
</ul>
</div>
</details>
</aside>
<section class="workspace">
<div class="stage-card">
<div id="viewport" aria-label="Interactive low-poly population visualization"></div>
<div class="stage-overlay stage-top">
<div class="stage-label">
<div class="eyebrow">Active environmental regime</div>
<strong id="stageScenario">Speed favored</strong>
</div>
<div class="generation-pill" id="stageGeneration">GEN 00</div>
</div>
<div class="stage-overlay stage-bottom">
<div class="population-legend" id="populationLegend"></div>
<div class="camera-hint">Drag to orbit · Scroll to zoom</div>
</div>
</div>
<div class="analysis-grid">
<section class="chart-card">
<div class="chart-header">
<div>
<h2 id="chartTitle">Speed frequency across selection regimes</h2>
<p class="chart-subtitle">Click or drag the chart to inspect a generation.</p>
</div>
<div class="metric-tabs" id="metricTabs" aria-label="Trait measured in chart">
<button class="metric-tab active" data-metric="0">Speed</button>
<button class="metric-tab" data-metric="1">Camouflage</button>
<button class="metric-tab" data-metric="2">Endurance</button>
</div>
</div>
<div class="chart-wrap">
<canvas id="chart"></canvas>
<div class="chart-tooltip" id="chartTooltip"></div>
</div>
<div class="chart-legend" id="chartLegend"></div>
</section>
<section class="summary-card">
<div class="eyebrow">Active regime</div>
<h2 id="summaryTitle">Speed favored</h2>
<div class="summary-label" id="summaryLabel">Population composition</div>
<div class="stacked-bar" id="stackedBar"></div>
<div class="summary-list" id="summaryList"></div>
<div class="comparison-box">
<h3 class="comparison-title" id="comparisonTitle">Speed at current generation</h3>
<table class="comparison-table">
<thead>
<tr>
<th>Regime</th>
<th>Frequency</th>
<th>Δ gen 0</th>
</tr>
</thead>
<tbody id="comparisonBody"></tbody>
</table>
</div>
<div class="model-note" id="modelNote"></div>
</section>
</div>
</section>
</main>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Deterministic population model
// -------------------------------------------------------------------------
const TRAITS = [
{
id: "speed",
label: "Speed",
short: "SPD",
color: "#efad3d",
description: "Fast movement is favored"
},
{
id: "camouflage",
label: "Camouflage",
short: "CAM",
color: "#3f9b7d",
description: "Blending into cover is favored"
},
{
id: "endurance",
label: "Endurance",
short: "END",
color: "#8068b3",
description: "Resilient survival is favored"
}
];
const POPULATION = 120;
const MAX_GENERATION = 60;
const SEED = 271828;
const MUTATION_RATE = 0.02;
const FAVORED_FITNESS = 1.0;
const ALTERNATIVE_FITNESS = 0.62;
function mulberry32(seed) {
return function random() {
let t = seed += 0x6D2B79F5;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function shuffle(array, random) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
const founderRandom = mulberry32(SEED);
const initialTraits = [];
for (let trait = 0; trait < TRAITS.length; trait++) {
for (let i = 0; i < POPULATION / TRAITS.length; i++) {
initialTraits.push(trait);
}
}
shuffle(initialTraits, founderRandom);
// Common random numbers: reused by all three selection regimes.
const eventRandom = mulberry32(SEED ^ 0x9E3779B9);
const eventCount = MAX_GENERATION * POPULATION;
const reproductionRandoms = Array.from({ length: eventCount }, () => eventRandom());
const mutationRandoms = Array.from({ length: eventCount }, () => eventRandom());
const mutationChoiceRandoms = Array.from({ length: eventCount }, () => eventRandom());
function simulate(favoredTrait) {
const fitness = TRAITS.map((_, trait) =>
trait === favoredTrait ? FAVORED_FITNESS : ALTERNATIVE_FITNESS
);
let counts = TRAITS.map((_, trait) =>
initialTraits.reduce((sum, value) => sum + (value === trait ? 1 : 0), 0)
);
const history = [counts.slice()];
for (let generation = 0; generation < MAX_GENERATION; generation++) {
const weighted = counts.map((count, trait) => count * fitness[trait]);
const total = weighted[0] + weighted[1] + weighted[2];
const cumulative = [
weighted[0] / total,
(weighted[0] + weighted[1]) / total,
1
];
const nextCounts = [0, 0, 0];
for (let individual = 0; individual < POPULATION; individual++) {
const eventIndex = generation * POPULATION + individual;
const reproductionDraw = reproductionRandoms[eventIndex];
let trait;
if (reproductionDraw < cumulative[0]) trait = 0;
else if (reproductionDraw < cumulative[1]) trait = 1;
else trait = 2;
if (mutationRandoms[eventIndex] < MUTATION_RATE) {
const alternatives = trait === 0 ? [1, 2] : trait === 1 ? [0, 2] : [0, 1];
trait = alternatives[Math.floor(mutationChoiceRandoms[eventIndex] * 2)];
}
nextCounts[trait]++;
}
counts = nextCounts;
history.push(counts.slice());
}
return history;
}
const histories = TRAITS.map((_, scenario) => simulate(scenario));
// -------------------------------------------------------------------------
// UI state
// -------------------------------------------------------------------------
let activeScenario = 0;
let chartMetric = 0;
let currentGeneration = 0;
let playing = false;
let hoverGeneration = null;
let playbackRate = 1;
const viewport = document.getElementById("viewport");
const generationSlider = document.getElementById("generationSlider");
const generationOutput = document.getElementById("generationOutput");
const stageScenario = document.getElementById("stageScenario");
const stageGeneration = document.getElementById("stageGeneration");
const populationLegend = document.getElementById("populationLegend");
const chart = document.getElementById("chart");
const chartContext = chart.getContext("2d");
const chartTooltip = document.getElementById("chartTooltip");
const chartTitle = document.getElementById("chartTitle");
const chartLegend = document.getElementById("chartLegend");
const summaryTitle = document.getElementById("summaryTitle");
const summaryLabel = document.getElementById("summaryLabel");
const stackedBar = document.getElementById("stackedBar");
const summaryList = document.getElementById("summaryList");
const comparisonTitle = document.getElementById("comparisonTitle");
const comparisonBody = document.getElementById("comparisonBody");
const modelNote = document.getElementById("modelNote");
document.querySelectorAll("[data-scenario]").forEach(button => {
button.addEventListener("click", () => {
activeScenario = Number(button.dataset.scenario);
updateScenarioButtons();
updatePopulationColors();
updateInterface();
});
});
document.querySelectorAll("[data-metric]").forEach(button => {
button.addEventListener("click", () => {
chartMetric = Number(button.dataset.metric);
updateMetricButtons();
updateInterface();
});
});
function updateScenarioButtons() {
document.querySelectorAll("[data-scenario]").forEach(button => {
const active = Number(button.dataset.scenario) === activeScenario;
button.classList.toggle("active", active);
button.setAttribute("aria-pressed", String(active));
});
}
function updateMetricButtons() {
document.querySelectorAll("[data-metric]").forEach(button => {
button.classList.toggle("active", Number(button.dataset.metric) === chartMetric);
});
}
generationSlider.addEventListener("input", () => {
currentGeneration = Number(generationSlider.value);
updateInterface();
});
document.getElementById("playButton").addEventListener("click", () => {
if (currentGeneration >= MAX_GENERATION) currentGeneration = 0;
playing = !playing;
document.getElementById("playButton").textContent = playing
? "❚❚ Pause selection"
: "▶ Play selection";
updateInterface();
});
document.getElementById("resetButton").addEventListener("click", () => {
playing = false;
currentGeneration = 0;
document.getElementById("playButton").textContent = "▶ Play selection";
updateInterface();
});
document.getElementById("playbackRate").addEventListener("change", event => {
playbackRate = Number(event.target.value);
});
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0xdce7dd, 26, 49);
const camera = new THREE.PerspectiveCamera(38, 1, 0.1, 100);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.setClearColor(0x000000, 0);
viewport.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xf7fff2, 0x657563, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff2d3, 3.0);
sun.position.set(-8, 15, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -17;
sun.shadow.camera.right = 17;
sun.shadow.camera.top = 17;
sun.shadow.camera.bottom = -17;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 45;
sun.shadow.bias = -0.0007;
scene.add(sun);
const terrainMaterial = new THREE.MeshStandardMaterial({
color: 0x8ea56f,
roughness: 0.96,
flatShading: true
});
const island = new THREE.Mesh(
new THREE.CylinderGeometry(11.8, 12.7, 1.8, 14),
terrainMaterial
);
island.position.y = -0.9;
island.receiveShadow = true;
island.castShadow = true;
scene.add(island);
const topMaterial = new THREE.MeshStandardMaterial({
color: 0xa9ba80,
roughness: 1,
flatShading: true
});
const islandTop = new THREE.Mesh(
new THREE.CircleGeometry(11.8, 14),
topMaterial
);
islandTop.rotation.x = -Math.PI / 2;
islandTop.position.y = 0.012;
islandTop.receiveShadow = true;
scene.add(islandTop);
const selectionRingMaterial = new THREE.MeshBasicMaterial({
color: TRAITS[activeScenario].color,
transparent: true,
opacity: 0.68
});
const selectionRing = new THREE.Mesh(
new THREE.TorusGeometry(11.85, 0.075, 5, 48),
selectionRingMaterial
);
selectionRing.rotation.x = Math.PI / 2;
selectionRing.position.y = 0.075;
scene.add(selectionRing);
const shore = new THREE.Mesh(
new THREE.CircleGeometry(1.86, 11),
new THREE.MeshStandardMaterial({ color: 0xd2c38f, roughness: 1, flatShading: true })
);
shore.rotation.x = -Math.PI / 2;
shore.position.set(-3.25, 0.035, 2.25);
shore.receiveShadow = true;
scene.add(shore);
const pond = new THREE.Mesh(
new THREE.CircleGeometry(1.58, 11),
new THREE.MeshStandardMaterial({
color: 0x65a7a4,
roughness: 0.28,
metalness: 0.05,
flatShading: true
})
);
pond.rotation.x = -Math.PI / 2;
pond.position.set(-3.25, 0.047, 2.25);
scene.add(pond);
const layoutRandom = mulberry32(SEED ^ 0xC0FFEE);
const treeAngles = [0.1, 0.72, 1.3, 2.0, 2.62, 3.35, 4.0, 4.75, 5.45];
treeAngles.forEach((angle, index) => {
const radius = 10.25 + layoutRandom() * 0.55;
const x = Math.cos(angle) * radius;
const z = Math.sin(angle) * radius;
const size = 0.78 + layoutRandom() * 0.38;
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.14, 0.19, 1.25, 5),
new THREE.MeshStandardMaterial({ color: 0x72563d, roughness: 1, flatShading: true })
);
trunk.position.set(x, 0.63 * size, z);
trunk.castShadow = true;
scene.add(trunk);
const canopy = new THREE.Mesh(
new THREE.ConeGeometry(0.78 * size, 1.75 * size, 6),
new THREE.MeshStandardMaterial({
color: index % 3 === 0 ? 0x547d55 : 0x668b5b,
roughness: 1,
flatShading: true
})
);
canopy.position.set(x, 1.55 * size, z);
canopy.castShadow = true;
scene.add(canopy);
});
for (let i = 0; i < 15; i++) {
const angle = layoutRandom() * Math.PI * 2;
const radius = 7.7 + layoutRandom() * 2.8;
const rock = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.22 + layoutRandom() * 0.28, 0),
new THREE.MeshStandardMaterial({
color: i % 2 ? 0x8b9181 : 0xa6aa96,
roughness: 1,
flatShading: true
})
);
rock.position.set(
Math.cos(angle) * radius,
0.12,
Math.sin(angle) * radius
);
rock.scale.y = 0.65 + layoutRandom() * 0.4;
rock.rotation.set(layoutRandom(), layoutRandom(), layoutRandom());
rock.castShadow = true;
rock.receiveShadow = true;
scene.add(rock);
}
// -------------------------------------------------------------------------
// Instanced low-poly creatures
// -------------------------------------------------------------------------
const creatureMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.82,
flatShading: true
});
const headMaterial = creatureMaterial.clone();
const crestMaterial = creatureMaterial.clone();
const eyeMaterial = new THREE.MeshStandardMaterial({
color: 0x202b27,
roughness: 0.5
});
const bodyMesh = new THREE.InstancedMesh(
new THREE.IcosahedronGeometry(0.42, 0),
creatureMaterial,
POPULATION
);
const headMesh = new THREE.InstancedMesh(
new THREE.DodecahedronGeometry(0.22, 0),
headMaterial,
POPULATION
);
const crestLeftMesh = new THREE.InstancedMesh(
new THREE.ConeGeometry(0.12, 0.42, 5),
crestMaterial,
POPULATION
);
const crestRightMesh = new THREE.InstancedMesh(
new THREE.ConeGeometry(0.12, 0.42, 5),
crestMaterial,
POPULATION
);
const eyeMesh = new THREE.InstancedMesh(
new THREE.SphereGeometry(0.035, 6, 4),
eyeMaterial,
POPULATION * 2
);
const haloMesh = new THREE.InstancedMesh(
new THREE.RingGeometry(0.49, 0.56, 10),
new THREE.MeshBasicMaterial({
color: TRAITS[activeScenario].color,
transparent: true,
opacity: 0.78,
depthWrite: false,
side: THREE.DoubleSide
}),
POPULATION
);
[bodyMesh, headMesh, crestLeftMesh, crestRightMesh].forEach(mesh => {
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.frustumCulled = false;
mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
scene.add(mesh);
});
eyeMesh.frustumCulled = false;
eyeMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
scene.add(eyeMesh);
haloMesh.frustumCulled = false;
haloMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
scene.add(haloMesh);
const layout = [];
for (let i = 0; i < POPULATION; i++) {
const angle = layoutRandom() * Math.PI * 2;
const radius = 2.7 + Math.sqrt(layoutRandom()) * 7.3;
let x = Math.cos(angle) * radius;
let z = Math.sin(angle) * radius;
const pondDistance = Math.hypot(x + 3.25, z - 2.25);
if (pondDistance < 2.05) {
x += x < -3.25 ? -1.3 : 1.3;
z += z < 2.25 ? -1.0 : 1.0;
}
layout.push({
x,
z,
heading: layoutRandom() * Math.PI * 2
});
}
let slotTraits = initialTraits.slice();
const dummy = new THREE.Object3D();
const bodyColors = TRAITS.map(trait => new THREE.Color(trait.color));
const headColors = TRAITS.map(trait => new THREE.Color(trait.color).lerp(new THREE.Color(0xffffff), 0.14));
const crestColors = TRAITS.map(trait => new THREE.Color(trait.color).lerp(new THREE.Color(0xffffff), 0.28));
function updatePopulationColors() {
for (let i = 0; i < POPULATION; i++) {
const trait = slotTraits[i];
bodyMesh.setColorAt(i, bodyColors[trait]);
headMesh.setColorAt(i, headColors[trait]);
crestLeftMesh.setColorAt(i, crestColors[trait]);
crestRightMesh.setColorAt(i, crestColors[trait]);
}
bodyMesh.instanceColor.needsUpdate = true;
headMesh.instanceColor.needsUpdate = true;
crestLeftMesh.instanceColor.needsUpdate = true;
crestRightMesh.instanceColor.needsUpdate = true;
selectionRingMaterial.color.set(TRAITS[activeScenario].color);
haloMesh.material.color.set(TRAITS[activeScenario].color);
}
function assignTraitsToSlots(counts) {
const slotsByTrait = TRAITS.map(() => []);
slotTraits.forEach((trait, slot) => slotsByTrait[trait].push(slot));
const nextTraits = new Array(POPULATION).fill(-1);
const keptCounts = [0, 0, 0];
TRAITS.forEach((_, trait) => {
const keep = Math.min(counts[trait], slotsByTrait[trait].length);
for (let i = 0; i < keep; i++) {
nextTraits[slotsByTrait[trait][i]] = trait;
}
keptCounts[trait] = keep;
});
const remaining = counts.map((count, trait) => count - keptCounts[trait]);
const openSlots = [];
nextTraits.forEach((trait, slot) => {
if (trait === -1) openSlots.push(slot);
});
let openIndex = 0;
for (let trait = 0; trait < TRAITS.length; trait++) {
for (let i = 0; i < remaining[trait]; i++) {
nextTraits[openSlots[openIndex++]] = trait;
}
}
slotTraits = nextTraits;
updatePopulationColors();
}
function setLocalMatrix(mesh, index, base, heading, local, scale, rotationX = 0, rotationZ = 0) {
const cos = Math.cos(heading);
const sin = Math.sin(heading);
const worldX = base.x + local.x * cos + local.z * sin;
const worldZ = base.z - local.x * sin + local.z * cos;
dummy.position.set(worldX, base.y + local.y, worldZ);
dummy.rotation.set(rotationX, heading, rotationZ, "YXZ");
dummy.scale.set(scale.x, scale.y, scale.z);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
}
function renderCreatures(time) {
const bobTime = time * 0.003;
for (let i = 0; i < POPULATION; i++) {
const trait = slotTraits[i];
const base = layout[i];
const bob = Math.sin(bobTime + i * 1.71) * 0.025;
const bodyBase = { x: base.x, y: 0.055 + bob, z: base.z };
let bodyScale;
let headScale;
let crestScale;
let crestOffset;
let crestHeight;
let crestTilt;
if (trait === 0) {
bodyScale = { x: 0.76, y: 0.70, z: 1.08 };
headScale = { x: 0.88, y: 0.88, z: 0.92 };
crestScale = { x: 0.78, y: 1.16, z: 0.70 };
crestOffset = 0.17;
crestHeight = 0.70;
crestTilt = 0.08;
} else if (trait === 1) {
bodyScale = { x: 1.00, y: 0.78, z: 0.86 };
headScale = { x: 0.92, y: 0.82, z: 0.90 };
crestScale = { x: 0.95, y: 1.05, z: 0.55 };
crestOffset = 0.10;
crestHeight = 0.61;
crestTilt = 0.50;
} else {
bodyScale = { x: 1.08, y: 0.92, z: 0.98 };
headScale = { x: 0.92, y: 0.92, z: 0.88 };
crestScale = { x: 0.65, y: 1.20, z: 0.65 };
crestOffset = 0.18;
crestHeight = 0.69;
crestTilt = 0.18;
}
setLocalMatrix(
bodyMesh, i, bodyBase, base.heading,
{ x: 0, y: 0.34, z: 0 },
bodyScale
);
setLocalMatrix(
headMesh, i, bodyBase, base.heading,
{ x: 0, y: 0.48, z: 0.34 },
headScale
);
setLocalMatrix(
crestLeftMesh, i, bodyBase, base.heading,
{ x: -crestOffset, y: crestHeight, z: -0.03 },
crestScale, 0, crestTilt
);
setLocalMatrix(
crestRightMesh, i, bodyBase, base.heading,
{ x: crestOffset, y: crestHeight, z: -0.03 },
crestScale, 0, -crestTilt
);
setLocalMatrix(
eyeMesh, i * 2, bodyBase, base.heading,
{ x: -0.105, y: 0.51, z: 0.49 },
{ x: 1, y: 1, z: 1 }
);
setLocalMatrix(
eyeMesh, i * 2 + 1, bodyBase, base.heading,
{ x: 0.105, y: 0.51, z: 0.49 },
{ x: 1, y: 1, z: 1 }
);
const haloScale = trait === activeScenario ? 0.78 : 0.0001;
dummy.position.set(base.x, 0.025, base.z);
dummy.rotation.set(-Math.PI / 2, 0, 0);
dummy.scale.setScalar(haloScale);
dummy.updateMatrix();
haloMesh.setMatrixAt(i, dummy.matrix);
}
bodyMesh.instanceMatrix.needsUpdate = true;
headMesh.instanceMatrix.needsUpdate = true;
crestLeftMesh.instanceMatrix.needsUpdate = true;
crestRightMesh.instanceMatrix.needsUpdate = true;
eyeMesh.instanceMatrix.needsUpdate = true;
haloMesh.instanceMatrix.needsUpdate = true;
}
// -------------------------------------------------------------------------
// Direct camera controls: drag orbit and wheel zoom
// -------------------------------------------------------------------------
const cameraState = {
radius: 23,
phi: 0.91,
theta: 0.55,
target: new THREE.Vector3(0, 0.3, 0),
dragging: false,
previousX: 0,
previousY: 0
};
renderer.domElement.addEventListener("pointerdown", event => {
cameraState.dragging = true;
cameraState.previousX = event.clientX;
cameraState.previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!cameraState.dragging) return;
const deltaX = event.clientX - cameraState.previousX;
const deltaY = event.clientY - cameraState.previousY;
cameraState.previousX = event.clientX;
cameraState.previousY = event.clientY;
cameraState.theta -= deltaX * 0.006;
cameraState.phi = THREE.MathUtils.clamp(cameraState.phi - deltaY * 0.005, 0.34, 1.38);
});
function stopDragging() {
cameraState.dragging = false;
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener("lostpointercapture", stopDragging);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.012,
14,
34
);
}, { passive: false });
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.radius * Math.cos(cameraState.phi),
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
const resizeObserver = new ResizeObserver(() => {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
});
resizeObserver.observe(viewport);
// -------------------------------------------------------------------------
// Frequency chart
// -------------------------------------------------------------------------
let chartWidth = 0;
let chartHeight = 0;
let chartDpr = 1;
function resizeChart() {
const rect = chart.getBoundingClientRect();
chartWidth = Math.max(1, rect.width);
chartHeight = Math.max(1, rect.height);
chartDpr = Math.min(window.devicePixelRatio || 1, 2);
chart.width = Math.round(chartWidth * chartDpr);
chart.height = Math.round(chartHeight * chartDpr);
chartContext.setTransform(chartDpr, 0, 0, chartDpr, 0, 0);
drawChart();
}
const chartObserver = new ResizeObserver(resizeChart);
chartObserver.observe(chart.parentElement);
function chartPlot() {
return {
left: 43,
right: chartWidth - 16,
top: 15,
bottom: chartHeight - 31,
width: Math.max(1, chartWidth - 59),
height: Math.max(1, chartHeight - 46)
};
}
function drawChart() {
if (!chartWidth || !chartHeight) return;
const ctx = chartContext;
const plot = chartPlot();
ctx.clearRect(0, 0, chartWidth, chartHeight);
ctx.font = "9px Inter, system-ui, sans-serif";
ctx.textBaseline = "middle";
// Horizontal grid and percentage labels.
for (let percent = 0; percent <= 100; percent += 25) {
const y = plot.bottom - (percent / 100) * plot.height;
ctx.strokeStyle = "#e2e7df";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(plot.left, y);
ctx.lineTo(plot.right, y);
ctx.stroke();
ctx.fillStyle = "#849089";
ctx.textAlign = "right";
ctx.fillText(`${percent}%`, plot.left - 9, y);
}
// Generation ticks.
for (let generation = 0; generation <= MAX_GENERATION; generation += 10) {
const x = plot.left + (generation / MAX_GENERATION) * plot.width;
ctx.strokeStyle = "#edf0eb";
ctx.beginPath();
ctx.moveTo(x, plot.top);
ctx.lineTo(x, plot.bottom);
ctx.stroke();
ctx.fillStyle = "#849089";
ctx.textAlign = "center";
ctx.fillText(String(generation), x, plot.bottom + 17);
}
ctx.fillStyle = "#849089";
ctx.textAlign = "left";
ctx.fillText("Generation", plot.left, 6);
// Frequency lines.
histories.forEach((history, scenario) => {
const active = scenario === activeScenario;
ctx.strokeStyle = TRAITS[scenario].color;
ctx.globalAlpha = active ? 1 : 0.48;
ctx.lineWidth = active ? 3 : 1.8;
ctx.lineJoin = "round";
ctx.lineCap = "round";
ctx.beginPath();
history.forEach((counts, generation) => {
const x = plot.left + (generation / MAX_GENERATION) * plot.width;
const y = plot.bottom - (counts[chartMetric] / POPULATION) * plot.height;
if (generation === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.stroke();
ctx.globalAlpha = 1;
});
// Current generation marker.
const currentX = plot.left + (currentGeneration / MAX_GENERATION) * plot.width;
ctx.strokeStyle = "rgba(32,53,46,.48)";
ctx.lineWidth = 1;
ctx.setLineDash([3, 4]);
ctx.beginPath();
ctx.moveTo(currentX, plot.top);
ctx.lineTo(currentX, plot.bottom);
ctx.stroke();
ctx.setLineDash([]);
histories.forEach((history, scenario) => {
const frequency = history[currentGeneration][chartMetric] / POPULATION;
const y = plot.bottom - frequency * plot.height;
ctx.fillStyle = TRAITS[scenario].color;
ctx.beginPath();
ctx.arc(currentX, y, scenario === activeScenario ? 4 : 2.5, 0, Math.PI * 2);
ctx.fill();
if (scenario === activeScenario) {
ctx.strokeStyle = "#fff";
ctx.lineWidth = 1.5;
ctx.stroke();
}
});
// Hover marker.
if (hoverGeneration !== null) {
const hoverX = plot.left + (hoverGeneration / MAX_GENERATION) * plot.width;
ctx.strokeStyle = "rgba(32,53,46,.25)";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(hoverX, plot.top);
ctx.lineTo(hoverX, plot.bottom);
ctx.stroke();
}
}
function generationFromChartEvent(event) {
const rect = chart.getBoundingClientRect();
const plot = chartPlot();
const x = event.clientX - rect.left;
const fraction = THREE.MathUtils.clamp(
(x - plot.left) / plot.width,
0,
1
);
return Math.round(fraction * MAX_GENERATION);
}
let chartDragging = false;
chart.addEventListener("pointerdown", event => {
chartDragging = true;
chart.setPointerCapture(event.pointerId);
currentGeneration = generationFromChartEvent(event);
updateInterface();
});
chart.addEventListener("pointermove", event => {
const generation = generationFromChartEvent(event);
hoverGeneration = generation;
drawChart();
const plot = chartPlot();
const rect = chart.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
chartTooltip.innerHTML = `
<strong>Generation ${generation}</strong>
${histories.map((history, scenario) => {
const value = (history[generation][chartMetric] / POPULATION * 100).toFixed(1);
return `
<div style="display:flex;justify-content:space-between;gap:12px">
<span>${TRAITS[scenario].label} favored</span>
<strong>${value}%</strong>
</div>`;
}).join("")}
`;
chartTooltip.style.display = "block";
const tooltipWidth = 165;
chartTooltip.style.left = `${Math.min(Math.max(4, x + 10), chartWidth - tooltipWidth - 4)}px`;
chartTooltip.style.top = `${Math.min(Math.max(4, y - 58), chartHeight - 115)}px`;
if (chartDragging) {
currentGeneration = generation;
updateInterface();
}
});
chart.addEventListener("pointerup", () => { chartDragging = false; });
chart.addEventListener("pointercancel", () => { chartDragging = false; });
chart.addEventListener("pointerleave", () => {
hoverGeneration = null;
chartTooltip.style.display = "none";
drawChart();
});
// -------------------------------------------------------------------------
// Interface and statistics
// -------------------------------------------------------------------------
function signedPoints(value) {
const rounded = Math.round(value * 10) / 10;
return `${rounded > 0 ? "+" : ""}${rounded.toFixed(1)} pp`;
}
function updateInterface() {
const activeHistory = histories[activeScenario];
const counts = activeHistory[currentGeneration];
const initialCounts = activeHistory[0];
generationSlider.value = currentGeneration;
generationOutput.textContent = `${currentGeneration} / ${MAX_GENERATION}`;
stageGeneration.textContent = `GEN ${String(currentGeneration).padStart(2, "0")}`;
stageScenario.textContent = `${TRAITS[activeScenario].label} favored`;
summaryTitle.textContent = `${TRAITS[activeScenario].label} favored`;
populationLegend.innerHTML = TRAITS.map((trait, index) => `
<span class="legend-chip" style="--swatch:${trait.color}">
<span class="legend-swatch"></span>
${trait.label} · ${counts[index]}
</span>
`).join("");
stackedBar.innerHTML = TRAITS.map((trait, index) => `
<span
title="${trait.label}: ${(counts[index] / POPULATION * 100).toFixed(1)}%"
style="width:${counts[index] / POPULATION * 100}%;background:${trait.color}">
</span>
`).join("");
summaryList.innerHTML = TRAITS.map((trait, index) => {
const current = counts[index] / POPULATION * 100;
const delta = current - initialCounts[index] / POPULATION * 100;
const favored = index === activeScenario;
return `
<div class="summary-row ${favored ? "favored" : ""}" style="--row-color:${trait.color}">
<span class="dot"></span>
<span>${trait.label}${favored ? " · favored" : ""}</span>
<span class="value">${current.toFixed(1)}%</span>
<span class="delta">${signedPoints(delta)}</span>
</div>
`;
}).join("");
chartTitle.textContent = `${TRAITS[chartMetric].label} frequency across selection regimes`;
comparisonTitle.textContent = `${TRAITS[chartMetric].label} at generation ${currentGeneration}`;
comparisonBody.innerHTML = histories.map((history, scenario) => {
const frequency = history[currentGeneration][chartMetric] / POPULATION * 100;
const delta = frequency - history[0][chartMetric] / POPULATION * 100;
return `
<tr class="${scenario === activeScenario ? "active" : ""}">
<td>${TRAITS[scenario].label} favored</td>
<td>${frequency.toFixed(1)}%</td>
<td>${signedPoints(delta)}</td>
</tr>
`;
}).join("");
const favoredFrequency = counts[activeScenario] / POPULATION * 100;
const favoredDelta = favoredFrequency - initialCounts[activeScenario] / POPULATION * 100;
modelNote.textContent =
`In the active regime, ${TRAITS[activeScenario].label.toLowerCase()} changes by ` +
`${signedPoints(favoredDelta)} from generation 0 to ${currentGeneration}. ` +
`The same 120 founders and random seed are used in every comparison.`;
chartLegend.innerHTML = histories.map((history, scenario) => `
<button
class="${scenario === activeScenario ? "active" : ""}"
data-chart-scenario="${scenario}"
style="--legend-color:${TRAITS[scenario].color}">
<i></i>${TRAITS[scenario].label} favored
</button>
`).join("");
chartLegend.querySelectorAll("[data-chart-scenario]").forEach(button => {
button.addEventListener("click", () => {
activeScenario = Number(button.dataset.chartScenario);
updateScenarioButtons();
updatePopulationColors();
updateInterface();
});
});
assignTraitsToSlots(counts);
drawChart();
}
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
let previousTime = performance.now();
let generationTimer = 0;
function animate(time) {
const delta = Math.min(0.1, (time - previousTime) / 1000);
previousTime = time;
if (playing) {
generationTimer += delta;
const secondsPerGeneration = 0.85 / playbackRate;
if (generationTimer >= secondsPerGeneration) {
generationTimer -= secondsPerGeneration;
currentGeneration = Math.min(MAX_GENERATION, currentGeneration + 1);
if (currentGeneration >= MAX_GENERATION) {
playing = false;
document.getElementById("playButton").textContent = "▶ Play selection";
}
updateInterface();
}
}
updateCamera();
renderCreatures(time);
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
updateScenarioButtons();
updateMetricButtons();
updatePopulationColors();
updateInterface();
resizeChart();
requestAnimationFrame(animate);
</script>
</body>
</html>
```