Prompt specification
Build or customize the Three.js 3D scene "Selection before and after reproduction" 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 before and after reproduction
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/selection-before-and-after-reproduction-x0938
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring natural selection. Show an environment-dependent survival stage followed by reproduction with inherited tokens; track frequencies across stages and avoid implying that individuals transform into favored variants. Stylized solid forms.
Working Three.js Starter (selection-before-and-after-reproduction-x0938):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Selection Garden — Natural Selection</title>
<style>
:root {
color-scheme: dark;
--bg: #091316;
--panel: #101d20;
--panel-2: #142529;
--line: rgba(203, 235, 230, .12);
--text: #edf7f4;
--muted: #91aaa7;
--wet: #50d6c8;
--dry: #ffad66;
--accent: #b9f36b;
--radius: 14px;
}
* { 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 {
font: inherit;
color: inherit;
cursor: pointer;
}
#app {
width: 100%;
height: 100%;
display: grid;
grid-template-rows: 68px minmax(0, 1fr);
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 22px;
border-bottom: 1px solid var(--line);
background: rgba(8, 18, 21, .96);
z-index: 5;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-mark {
width: 35px;
height: 35px;
border-radius: 50% 50% 46% 54%;
background: linear-gradient(135deg, var(--wet) 0 49%, var(--dry) 51% 100%);
box-shadow: 0 0 0 4px rgba(185, 243, 107, .08);
flex: 0 0 auto;
}
.brand h1 {
margin: 0;
font-size: 17px;
line-height: 1.1;
letter-spacing: .01em;
}
.brand p {
margin: 4px 0 0;
color: var(--muted);
font-size: 12px;
}
.header-actions {
display: flex;
gap: 8px;
flex: 0 0 auto;
}
.small-button {
min-height: 34px;
padding: 0 13px;
border: 1px solid var(--line);
border-radius: 9px;
background: #142326;
transition: background .2s, border-color .2s;
}
.small-button:hover {
background: #1a3033;
border-color: rgba(203, 235, 230, .24);
}
.small-button.primary {
color: #122016;
background: var(--accent);
border-color: var(--accent);
font-weight: 750;
}
main {
min-height: 0;
display: grid;
grid-template-columns: minmax(0, 1fr) 370px;
}
#viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #162c31;
isolation: isolate;
}
#viewport canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
cursor: grab;
touch-action: none;
outline: none;
}
#viewport canvas:active { cursor: grabbing; }
.glass {
background: rgba(10, 22, 25, .83);
border: 1px solid rgba(218, 244, 239, .13);
box-shadow: 0 12px 35px rgba(0, 0, 0, .18);
backdrop-filter: blur(12px);
}
.scene-status {
position: absolute;
top: 18px;
left: 18px;
z-index: 2;
width: min(340px, calc(100% - 90px));
padding: 14px 15px;
border-radius: var(--radius);
pointer-events: none;
}
.eyebrow {
color: var(--accent);
text-transform: uppercase;
letter-spacing: .13em;
font-size: 10px;
font-weight: 800;
}
.scene-status h2 {
margin: 5px 0 3px;
font-size: 20px;
letter-spacing: -.02em;
}
.scene-status p {
margin: 0;
color: #bfd0cd;
font-size: 12px;
line-height: 1.45;
}
.view-tools {
position: absolute;
top: 18px;
right: 18px;
z-index: 3;
}
.view-tools button {
width: 38px;
height: 38px;
border-radius: 10px;
font-size: 18px;
}
.environment-dock {
position: absolute;
left: 50%;
bottom: 18px;
transform: translateX(-50%);
z-index: 3;
width: min(560px, calc(100% - 36px));
padding: 10px;
border-radius: 15px;
}
.dock-label {
display: flex;
justify-content: space-between;
gap: 10px;
padding: 1px 4px 8px;
color: var(--muted);
font-size: 10px;
text-transform: uppercase;
letter-spacing: .1em;
font-weight: 750;
}
.env-buttons {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
.env-button {
min-height: 42px;
border: 1px solid transparent;
border-radius: 10px;
background: rgba(255, 255, 255, .055);
transition: background .2s, border-color .2s, transform .15s;
}
.env-button:hover { transform: translateY(-1px); }
.env-button.active {
border-color: rgba(185, 243, 107, .6);
background: rgba(185, 243, 107, .12);
box-shadow: inset 0 0 0 1px rgba(185, 243, 107, .06);
}
.env-button strong {
display: block;
font-size: 12px;
}
.env-button span {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 10px;
}
.legend {
position: absolute;
left: 18px;
bottom: 18px;
z-index: 2;
display: flex;
gap: 12px;
padding: 9px 11px;
border-radius: 11px;
pointer-events: none;
font-size: 10px;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 50%;
}
.swatch.wet { background: var(--wet); }
.swatch.dry { background: var(--dry); }
.camera-hint {
position: absolute;
right: 18px;
bottom: 18px;
z-index: 2;
padding: 8px 10px;
border-radius: 9px;
color: #c5d4d1;
font-size: 10px;
pointer-events: none;
}
aside {
min-height: 0;
overflow-y: auto;
background: var(--panel);
border-left: 1px solid var(--line);
scrollbar-width: thin;
scrollbar-color: #345052 transparent;
}
.panel-section {
padding: 18px;
border-bottom: 1px solid var(--line);
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 13px;
}
.section-heading h3 {
margin: 0;
font-size: 13px;
letter-spacing: .01em;
}
.section-heading span,
.section-heading b {
color: var(--muted);
font-size: 10px;
font-weight: 650;
}
.phase-steps {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
.phase-step {
min-width: 0;
padding: 9px 7px;
border-radius: 10px;
border: 1px solid var(--line);
background: #0d191c;
opacity: .52;
transition: opacity .25s, border-color .25s, background .25s;
}
.phase-step.active {
opacity: 1;
border-color: rgba(185, 243, 107, .38);
background: rgba(185, 243, 107, .07);
}
.phase-step.done { opacity: .9; }
.phase-step i {
display: grid;
place-items: center;
width: 20px;
height: 20px;
margin-bottom: 7px;
border-radius: 50%;
background: #263b3d;
color: #d9e7e4;
font-style: normal;
font-size: 10px;
font-weight: 800;
}
.phase-step.active i {
background: var(--accent);
color: #142019;
}
.phase-step.done i { background: #42645e; }
.phase-step strong {
display: block;
font-size: 10px;
white-space: nowrap;
}
.phase-step small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
line-height: 1.3;
}
.progress-track {
height: 5px;
margin-top: 12px;
overflow: hidden;
border-radius: 10px;
background: #253638;
}
#progressFill {
width: 0;
height: 100%;
border-radius: inherit;
background: var(--accent);
transition: width .08s linear;
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin-top: 14px;
}
.stat {
padding: 10px;
border-radius: 10px;
background: var(--panel-2);
border: 1px solid rgba(255, 255, 255, .035);
}
.stat span {
display: block;
color: var(--muted);
font-size: 9px;
text-transform: uppercase;
letter-spacing: .08em;
}
.stat b {
display: block;
margin-top: 4px;
font-size: 19px;
font-variant-numeric: tabular-nums;
}
.environment-summary {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 14px;
margin-bottom: 13px;
}
.environment-summary strong {
display: block;
font-size: 14px;
}
.environment-summary p {
margin: 4px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.favored-pill {
flex: 0 0 auto;
padding: 6px 8px;
border-radius: 8px;
background: rgba(185, 243, 107, .09);
color: var(--accent);
font-size: 9px;
font-weight: 800;
text-align: center;
text-transform: uppercase;
letter-spacing: .05em;
}
.odds-row {
display: grid;
grid-template-columns: 1fr 48px;
gap: 5px 10px;
align-items: center;
margin-top: 9px;
font-size: 10px;
}
.odds-row b {
text-align: right;
font-variant-numeric: tabular-nums;
}
.odds-track {
grid-column: 1 / -1;
height: 5px;
overflow: hidden;
border-radius: 8px;
background: #263638;
}
.odds-track i {
display: block;
width: 50%;
height: 100%;
border-radius: inherit;
transition: width .45s ease;
}
#mOddsFill { background: var(--wet); }
#dOddsFill { background: var(--dry); }
.delta {
margin-top: 12px;
color: var(--muted);
font-size: 10px;
}
.delta b {
color: var(--text);
font-weight: 700;
}
.frequency-row {
margin-top: 12px;
}
.frequency-head {
display: flex;
justify-content: space-between;
gap: 12px;
margin-bottom: 6px;
color: var(--muted);
font-size: 10px;
}
.frequency-head b {
color: #cbd9d6;
font-weight: 650;
font-variant-numeric: tabular-nums;
}
.frequency-bar {
height: 9px;
overflow: hidden;
border-radius: 8px;
background: #263638;
}
.frequency-bar i {
display: block;
height: 100%;
width: 0;
transition: width .45s ease;
}
#startM, #surviveM, #reproM { background: var(--wet); }
#startD, #surviveD, #reproD { background: var(--dry); }
.chart-wrap {
position: relative;
width: 100%;
height: 160px;
border-radius: 11px;
background: #0b171a;
border: 1px solid rgba(255, 255, 255, .035);
overflow: hidden;
}
#historyChart {
display: block;
width: 100%;
height: 100%;
}
.chart-legend {
display: flex;
gap: 13px;
margin-top: 9px;
color: var(--muted);
font-size: 9px;
}
.chart-legend span {
display: flex;
align-items: center;
gap: 5px;
}
.chart-legend i {
width: 15px;
height: 2px;
border-radius: 2px;
}
.explanation {
display: grid;
grid-template-columns: 28px 1fr;
gap: 10px;
padding: 16px 18px 20px;
}
.explanation-icon {
display: grid;
place-items: center;
width: 28px;
height: 28px;
border-radius: 9px;
background: rgba(185, 243, 107, .12);
color: var(--accent);
font-weight: 900;
}
.explanation h4 {
margin: 1px 0 5px;
font-size: 11px;
}
.explanation p {
margin: 0;
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
@media (max-width: 980px) {
html, body { overflow: auto; }
#app {
height: auto;
min-height: 100%;
grid-template-rows: 68px auto;
}
main {
grid-template-columns: 1fr;
}
#viewport {
height: 64vh;
min-height: 480px;
}
aside {
border-left: 0;
border-top: 1px solid var(--line);
overflow: visible;
}
.legend { display: none; }
.camera-hint { display: none; }
}
@media (max-width: 560px) {
.topbar { padding: 0 12px; }
.brand p { display: none; }
.header-actions { gap: 5px; }
.small-button { padding: 0 9px; font-size: 11px; }
#viewport { min-height: 520px; }
.scene-status { left: 12px; top: 12px; width: calc(100% - 70px); }
.view-tools { right: 12px; top: 12px; }
.environment-dock { bottom: 12px; width: calc(100% - 24px); }
}
</style>
</head>
<body>
<div id="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>Selection Garden</h1>
<p>Environment → survival → inherited reproduction</p>
</div>
</div>
<div class="header-actions">
<button class="small-button primary" id="pauseButton" aria-pressed="false">Pause</button>
<button class="small-button" id="speedButton" aria-label="Change simulation speed">1×</button>
<button class="small-button" id="resetButton">Reset</button>
</div>
</header>
<main>
<section id="viewport" aria-label="Interactive natural selection habitat">
<div class="scene-status glass">
<div class="eyebrow" id="roundLabel">Round 1</div>
<h2 id="stageName">Survival test</h2>
<p id="stageMeta">The habitat is testing the inherited population.</p>
</div>
<div class="view-tools">
<button class="small-button glass" id="cameraReset" title="Reset camera" aria-label="Reset camera">⌖</button>
</div>
<div class="legend glass">
<div class="legend-item"><i class="swatch wet"></i> Moisture token</div>
<div class="legend-item"><i class="swatch dry"></i> Dry token</div>
</div>
<div class="environment-dock glass">
<div class="dock-label">
<span>Habitat for the next round</span>
<span id="envSelectionLabel">Choose conditions</span>
</div>
<div class="env-buttons">
<button class="env-button" data-env="wet">
<strong>Wet habitat</strong>
<span>Moisture favored</span>
</button>
<button class="env-button" data-env="dry">
<strong>Dry habitat</strong>
<span>Dry form favored</span>
</button>
<button class="env-button" data-env="mixed">
<strong>Balanced</strong>
<span>Both tested equally</span>
</button>
</div>
</div>
<div class="camera-hint glass">Drag to orbit · Scroll to zoom · Arrow keys to move</div>
</section>
<aside>
<section class="panel-section">
<div class="section-heading">
<h3>Selection cycle</h3>
<span id="phaseCaption">Stage 1 of 3</span>
</div>
<div class="phase-steps">
<div class="phase-step active" id="stepSurvival">
<i>1</i>
<strong>Survival</strong>
<small>Filter existing variants</small>
</div>
<div class="phase-step" id="stepReproduction">
<i>2</i>
<strong>Reproduction</strong>
<small>Copy inherited tokens</small>
</div>
<div class="phase-step" id="stepNext">
<i>3</i>
<strong>Next round</strong>
<small>New habitat conditions</small>
</div>
</div>
<div class="progress-track"><div id="progressFill"></div></div>
<div class="stats">
<div class="stat"><span>Population</span><b id="populationStat">60</b></div>
<div class="stat"><span>Survivors</span><b id="survivorStat">—</b></div>
<div class="stat"><span>Newborns</span><b id="birthStat">0</b></div>
</div>
</section>
<section class="panel-section">
<div class="section-heading">
<h3>Active environment</h3>
<span>Relative survival odds</span>
</div>
<div class="environment-summary">
<div>
<strong id="envName">Balanced habitat</strong>
<p id="envDescription">Both inherited tokens are tested equally.</p>
</div>
<div class="favored-pill" id="favoredText">No bias</div>
</div>
<div class="odds-row">
<span>Moisture token</span><b id="mOdds">74%</b>
<div class="odds-track"><i id="mOddsFill"></i></div>
</div>
<div class="odds-row">
<span>Dry token</span><b id="dOdds">74%</b>
<div class="odds-track"><i id="dOddsFill"></i></div>
</div>
<div class="delta">
Change after survival: <b id="selectionDelta">waiting for selection</b>
</div>
</section>
<section class="panel-section">
<div class="section-heading">
<h3>Token frequency by stage</h3>
<span>Current round</span>
</div>
<div class="frequency-row">
<div class="frequency-head"><span>Round start</span><b id="startText">50% M · 50% D</b></div>
<div class="frequency-bar"><i id="startM"></i><i id="startD"></i></div>
</div>
<div class="frequency-row">
<div class="frequency-head"><span>After survival</span><b id="surviveText">pending</b></div>
<div class="frequency-bar"><i id="surviveM"></i><i id="surviveD"></i></div>
</div>
<div class="frequency-row">
<div class="frequency-head"><span>After reproduction</span><b id="reproText">pending</b></div>
<div class="frequency-bar"><i id="reproM"></i><i id="reproD"></i></div>
</div>
</section>
<section class="panel-section">
<div class="section-heading">
<h3>Round history</h3>
<span>Frequency after reproduction</span>
</div>
<div class="chart-wrap">
<canvas id="historyChart" aria-label="History of inherited token frequencies"></canvas>
</div>
<div class="chart-legend">
<span><i style="background:var(--wet)"></i> Moisture token</span>
<span><i style="background:var(--dry)"></i> Dry token</span>
</div>
</section>
<section class="explanation">
<div class="explanation-icon" aria-hidden="true">i</div>
<div>
<h4>Selection does not transform individuals</h4>
<p>
Each creature keeps its inherited token and body form for life. The habitat
changes which individuals survive. Survivors then pass that token to offspring;
a small mutation rate can flip a token at birth.
</p>
</div>
</section>
</aside>
</main>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = id => document.getElementById(id);
const viewport = $("viewport");
const ENVIRONMENTS = {
wet: {
label: "Wet habitat",
description: "Water is plentiful. The moisture-adapted token survives more often.",
favored: "Moisture favored",
wetness: 1,
odds: { M: 0.92, D: 0.20 },
background: new THREE.Color(0x163942),
ground: new THREE.Color(0x315f51)
},
dry: {
label: "Dry habitat",
description: "Water is scarce. The dry-adapted token survives more often.",
favored: "Dry favored",
wetness: 0.12,
odds: { M: 0.20, D: 0.92 },
background: new THREE.Color(0x4b3526),
ground: new THREE.Color(0x8a603a)
},
mixed: {
label: "Balanced habitat",
description: "Resources are moderate. Both inherited tokens are tested equally.",
favored: "No bias",
wetness: 0.56,
odds: { M: 0.74, D: 0.74 },
background: new THREE.Color(0x263b3b),
ground: new THREE.Color(0x66704b)
}
};
const COLORS = {
wet: 0x50d6c8,
dry: 0xffad66,
accent: 0xb9f36b
};
const state = {
phase: "survival",
phaseElapsed: 0,
phaseDuration: 6,
simTime: 0,
visualTime: 0,
paused: false,
speed: 1,
round: 0,
selectedEnv: "mixed",
currentEnv: "mixed",
cullTriggered: false,
survivors: [],
doomed: [],
birthQueue: [],
newbornCount: 0,
mutationCount: 0,
history: [],
wetness: 0.56
};
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = ENVIRONMENTS.mixed.background.clone();
scene.fog = new THREE.Fog(scene.background.clone(), 19, 39);
const camera = new THREE.PerspectiveCamera(48, 1, 0.1, 100);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.domElement.tabIndex = 0;
renderer.domElement.setAttribute(
"aria-label",
"Three-dimensional selection habitat. Drag to orbit and scroll to zoom."
);
viewport.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xc9f4ff, 0x3f2b1d, 2.0);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffefd3, 2.8);
sun.position.set(-7, 12, 6);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.camera.left = -13;
sun.shadow.camera.right = 13;
sun.shadow.camera.top = 13;
sun.shadow.camera.bottom = -13;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
sun.shadow.bias = -0.0007;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x79b8c1, 0.75);
fill.position.set(8, 5, -8);
scene.add(fill);
const world = new THREE.Group();
scene.add(world);
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x66704b,
roughness: 0.95,
flatShading: true
});
const groundSideMaterial = new THREE.MeshStandardMaterial({
color: 0x443527,
roughness: 1,
flatShading: true
});
const groundBase = new THREE.Mesh(
new THREE.CylinderGeometry(9.35, 9.8, 0.62, 64),
groundSideMaterial
);
groundBase.position.y = -0.36;
groundBase.receiveShadow = true;
world.add(groundBase);
const ground = new THREE.Mesh(
new THREE.CircleGeometry(9.32, 64),
groundMaterial
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.035;
ground.receiveShadow = true;
world.add(ground);
const borderMaterial = new THREE.MeshStandardMaterial({
color: 0x90aa79,
roughness: 0.8
});
const border = new THREE.Mesh(
new THREE.TorusGeometry(9.47, 0.075, 8, 96),
borderMaterial
);
border.rotation.x = Math.PI / 2;
border.position.y = 0.005;
border.castShadow = true;
world.add(border);
const waterMaterial = new THREE.MeshStandardMaterial({
color: 0x248ca3,
roughness: 0.24,
metalness: 0.08
});
const waterGroup = new THREE.Group();
const waterPools = [];
const poolData = [
[-3.2, -1.7, 2.3, 1.35],
[2.3, -2.8, 2.0, 1.2],
[4.7, 2.4, 1.45, 0.95],
[-5.3, 3.0, 1.2, 0.8]
];
for (const [x, z, sx, sz] of poolData) {
const pool = new THREE.Mesh(
new THREE.CircleGeometry(1, 40),
waterMaterial
);
pool.rotation.x = -Math.PI / 2;
pool.position.set(x, 0.012, z);
pool.scale.set(sx, sz, 1);
pool.receiveShadow = true;
waterGroup.add(pool);
waterPools.push({ mesh: pool, sx, sz });
}
world.add(waterGroup);
const dryMaterial = new THREE.MeshStandardMaterial({
color: 0xc18b50,
roughness: 1,
flatShading: true
});
const dryPatch = new THREE.Mesh(
new THREE.CircleGeometry(3.0, 40),
dryMaterial
);
dryPatch.rotation.x = -Math.PI / 2;
dryPatch.position.set(3.8, 0.006, 3.3);
dryPatch.scale.set(1.15, 0.8, 1);
dryPatch.receiveShadow = true;
world.add(dryPatch);
const stemMaterial = new THREE.MeshStandardMaterial({
color: 0x587345,
roughness: 0.9,
flatShading: true
});
const leafMaterial = new THREE.MeshStandardMaterial({
color: 0x6c9c52,
roughness: 0.9,
flatShading: true
});
const stemGeometry = new THREE.CylinderGeometry(0.055, 0.08, 0.65, 6);
const leafGeometry = new THREE.SphereGeometry(0.24, 7, 5);
const plants = [];
for (let i = 0; i < 20; i++) {
const angle = (i / 20) * Math.PI * 2 + Math.random() * 0.18;
const radius = 6.1 + Math.random() * 2.4;
const plant = new THREE.Group();
plant.position.set(
Math.cos(angle) * radius,
0,
Math.sin(angle) * radius
);
const stem = new THREE.Mesh(stemGeometry, stemMaterial);
stem.position.y = 0.325;
stem.castShadow = true;
plant.add(stem);
for (let j = 0; j < 3; j++) {
const leaf = new THREE.Mesh(leafGeometry, leafMaterial);
const a = j * Math.PI * 2 / 3 + i;
leaf.position.set(Math.cos(a) * 0.17, 0.38 + j * 0.13, Math.sin(a) * 0.17);
leaf.scale.set(1.15, 0.24, 0.48);
leaf.rotation.y = -a;
leaf.castShadow = true;
plant.add(leaf);
}
const baseScale = 0.75 + Math.random() * 0.55;
plant.scale.set(baseScale, baseScale, baseScale);
plant.userData.baseScale = baseScale;
plants.push(plant);
world.add(plant);
}
const rockMaterial = new THREE.MeshStandardMaterial({
color: 0x766f64,
roughness: 1,
flatShading: true
});
const rockGeometry = new THREE.DodecahedronGeometry(0.42, 0);
for (let i = 0; i < 11; i++) {
const angle = Math.random() * Math.PI * 2;
const radius = 5.7 + Math.random() * 3.1;
const rock = new THREE.Mesh(rockGeometry, rockMaterial);
rock.position.set(Math.cos(angle) * radius, 0.2, Math.sin(angle) * radius);
rock.scale.set(
0.65 + Math.random() * 0.8,
0.5 + Math.random() * 0.65,
0.65 + Math.random() * 0.8
);
rock.rotation.set(Math.random(), Math.random(), Math.random());
rock.castShadow = true;
rock.receiveShadow = true;
world.add(rock);
}
// Shared geometry keeps the population inexpensive to render.
const bodyGeometry = new THREE.SphereGeometry(0.34, 10, 7);
const headGeometry = new THREE.SphereGeometry(0.19, 9, 6);
const eyeGeometry = new THREE.SphereGeometry(0.043, 7, 5);
const footGeometry = new THREE.CylinderGeometry(0.055, 0.072, 0.2, 7);
const markerGeometry = new THREE.ConeGeometry(0.11, 0.28, 3);
const tokenMaterials = {
M: new THREE.MeshStandardMaterial({
color: COLORS.wet,
roughness: 0.68,
flatShading: true
}),
D: new THREE.MeshStandardMaterial({
color: COLORS.dry,
roughness: 0.68,
flatShading: true
})
};
const eyeMaterial = new THREE.MeshStandardMaterial({
color: 0x101718,
roughness: 0.6
});
const footMaterial = new THREE.MeshStandardMaterial({
color: 0x263a36,
roughness: 0.9,
flatShading: true
});
let allAgents = [];
function randomPoint(maxRadius = 7.7) {
const angle = Math.random() * Math.PI * 2;
const radius = Math.sqrt(Math.random()) * maxRadius;
return new THREE.Vector3(
Math.cos(angle) * radius,
0,
Math.sin(angle) * radius
);
}
function createAgent(token, position, generation, newborn = false) {
const group = new THREE.Group();
// The token and its body proportions are fixed at birth.
// The simulation never changes tokenMaterials or these child scales later.
const body = new THREE.Mesh(bodyGeometry, tokenMaterials[token]);
body.position.y = 0.36;
body.scale.set(
token === "M" ? 0.79 : 1.08,
token === "M" ? 1.07 : 0.88,
token === "M" ? 0.85 : 1.02
);
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const head = new THREE.Mesh(headGeometry, tokenMaterials[token]);
head.position.set(0.25, 0.49, 0);
head.castShadow = true;
group.add(head);
for (const z of [-0.145, 0.145]) {
const eye = new THREE.Mesh(eyeGeometry, eyeMaterial);
eye.position.set(0.365, 0.515, z);
group.add(eye);
}
for (const x of [-0.12, 0.16]) {
for (const z of [-0.13, 0.13]) {
const foot = new THREE.Mesh(footGeometry, footMaterial);
foot.position.set(x, 0.1, z);
foot.castShadow = true;
group.add(foot);
}
}
const marker = new THREE.Mesh(markerGeometry, tokenMaterials[token]);
marker.castShadow = true;
if (token === "M") {
// Tall moisture form with a dorsal crest.
marker.position.set(-0.04, 0.76, 0);
marker.rotation.z = -0.08;
} else {
// Broad dry form with a short horn.
marker.position.set(0.32, 0.7, 0);
marker.rotation.z = -0.56;
}
group.add(marker);
group.position.copy(position);
group.rotation.y = Math.random() * Math.PI * 2;
scene.add(group);
const agent = {
token,
group,
generation,
alive: true,
dying: false,
removed: false,
newborn,
birthTime: state.simTime,
removeAt: null,
dieStart: 0,
bobOffset: Math.random() * Math.PI * 2,
parentPulseUntil: 0
};
group.scale.setScalar(newborn ? 0.08 : 1);
allAgents.push(agent);
return agent;
}
function livingAgents() {
return allAgents.filter(agent => agent.alive);
}
function frequencies(agents) {
const result = { M: 0, D: 0 };
for (const agent of agents) result[agent.token]++;
const total = agents.length || 1;
result.M /= total;
result.D /= total;
return result;
}
// -------------------------------------------------------------------------
// Direct camera controls — no addons or example modules are used.
// -------------------------------------------------------------------------
const cameraState = {
yaw: -0.62,
pitch: 0.77,
distance: 23.5,
target: new THREE.Vector3(0, 0.45, 0)
};
function updateCamera() {
const cp = Math.cos(cameraState.pitch);
camera.position.set(
cameraState.target.x + Math.sin(cameraState.yaw) * cp * cameraState.distance,
cameraState.target.y + Math.sin(cameraState.pitch) * cameraState.distance,
cameraState.target.z + Math.cos(cameraState.yaw) * cp * cameraState.distance
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.yaw = -0.62;
cameraState.pitch = 0.77;
cameraState.distance = viewport.clientWidth / viewport.clientHeight < 1 ? 28 : 23.5;
updateCamera();
}
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.focus({ preventScroll: true });
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(cameraState.pitch + dy * 0.0045, 0.38, 1.35);
updateCamera();
});
renderer.domElement.addEventListener("pointerup", event => {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance + event.deltaY * 0.012,
11,
34
);
updateCamera();
}, { passive: false });
renderer.domElement.addEventListener("keydown", event => {
let handled = true;
switch (event.key) {
case "ArrowLeft":
cameraState.yaw += 0.08;
break;
case "ArrowRight":
cameraState.yaw -= 0.08;
break;
case "ArrowUp":
cameraState.pitch = Math.min(1.35, cameraState.pitch + 0.05);
break;
case "ArrowDown":
cameraState.pitch = Math.max(0.38, cameraState.pitch - 0.05);
break;
case "+":
case "=":
cameraState.distance = Math.max(11, cameraState.distance - 1);
break;
case "-":
cameraState.distance = Math.min(34, cameraState.distance + 1);
break;
case "r":
case "R":
resetCamera();
break;
default:
handled = false;
}
if (handled) {
event.preventDefault();
updateCamera();
}
});
function resizeScene() {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
if (!width || !height) return;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
new ResizeObserver(resizeScene).observe(viewport);
resizeScene();
resetCamera();
// -------------------------------------------------------------------------
// Simulation stages
// -------------------------------------------------------------------------
function clearFrequencyRow(prefix) {
$(prefix + "M").style.width = "0%";
$(prefix + "D").style.width = "0%";
$(prefix + "Text").textContent = "pending";
}
function setFrequencyRow(prefix, frequency) {
$(prefix + "M").style.width = `${frequency.M * 100}%`;
$(prefix + "D").style.width = `${frequency.D * 100}%`;
$(prefix + "Text").textContent =
`${Math.round(frequency.M * 100)}% M · ${Math.round(frequency.D * 100)}% D`;
}
function updateSelectionDelta() {
const start = frequencies(livingAgents());
const survivors = state.cullTriggered
? state.survivors
: livingAgents();
const after = frequencies(survivors);
const mPoints = (after.M - start.M) * 100;
$("selectionDelta").textContent =
`${mPoints >= 0 ? "+" : ""}${mPoints.toFixed(1)} pts M · ` +
`${(-mPoints).toFixed(1)} pts D`;
}
function startRound() {
state.round++;
state.phase = "survival";
state.phaseElapsed = 0;
state.phaseDuration = 6;
state.currentEnv = state.selectedEnv;
state.cullTriggered = false;
state.survivors = [];
state.doomed = [];
state.birthQueue = [];
state.newbornCount = 0;
state.mutationCount = 0;
allAgents = allAgents.filter(agent => {
if (agent.removed) {
scene.remove(agent.group);
return false;
}
return true;
});
setFrequencyRow("start", frequencies(livingAgents()));
clearFrequencyRow("survive");
clearFrequencyRow("repro");
updateEnvironmentPanel();
updateInterface();
}
function triggerSurvivalSelection() {
state.cullTriggered = true;
state.survivors = [];
state.doomed = [];
const odds = ENVIRONMENTS[state.currentEnv].odds;
for (const agent of livingAgents()) {
if (Math.random() < odds[agent.token]) {
state.survivors.push(agent);
} else {
state.doomed.push(agent);
}
}
// Defensive fallback for an extremely unlikely all-doomed outcome.
if (state.survivors.length === 0 && state.doomed.length > 0) {
const rescued = state.doomed.splice(0, Math.min(4, state.doomed.length));
state.survivors.push(...rescued);
}
// Shuffle removal order so mortality is not spatially organized.
for (let i = state.doomed.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[state.doomed[i], state.doomed[j]] = [state.doomed[j], state.doomed[i]];
}
state.doomed.forEach((agent, index) => {
agent.removeAt = state.phaseElapsed + index * 0.045;
});
setFrequencyRow("survive", frequencies(state.survivors));
updateSelectionDelta();
updateInterface();
}
function beginReproduction() {
state.phase = "reproduction";
state.phaseElapsed = 0;
state.phaseDuration = 4.8;
state.birthQueue = [];
const targetPopulation = 64;
const needed = Math.max(0, targetPopulation - state.survivors.length);
const children = [];
// Every survivor is given at least one chance to reproduce.
for (const parent of state.survivors) {
if (children.length >= needed) break;
children.push(makeBirthRecord(parent));
}
while (children.length < needed) {
const parent = state.survivors[
Math.floor(Math.random() * state.survivors.length)
];
children.push(makeBirthRecord(parent));
}
children.forEach((birth, index) => {
birth.at = index * 0.075;
state.birthQueue.push(birth);
});
updateInterface();
}
function makeBirthRecord(parent) {
// The offspring token is copied from the parent at conception.
// A mutation can flip that copied token; it does not transform the parent.
let token = parent.token;
const mutated = Math.random() < 0.035;
if (mutated) {
token = token === "M" ? "D" : "M";
state.mutationCount++;
}
return {
parent,
token,
mutated
};
}
function spawnBirth(birth) {
const parentPosition = birth.parent.group.position;
const angle = Math.random() * Math.PI * 2;
const distance = 0.45 + Math.random() * 0.9;
const position = new THREE.Vector3(
parentPosition.x + Math.cos(angle) * distance,
0,
parentPosition.z + Math.sin(angle) * distance
);
const radius = Math.hypot(position.x, position.z);
if (radius > 8.0) {
position.x *= 8.0 / radius;
position.z *= 8.0 / radius;
}
createAgent(
birth.token,
position,
birth.parent.generation + 1,
true
);
birth.parent.parentPulseUntil = state.simTime + 0.35;
state.newbornCount++;
setFrequencyRow("repro", frequencies(livingAgents()));
updateSelectionDelta();
}
function finishReproduction() {
const frequency = frequencies(livingAgents());
setFrequencyRow("repro", frequency);
state.history.push({
round: state.round,
M: frequency.M,
D: frequency.D
});
drawHistory();
state.phase = "transition";
state.phaseElapsed = 0;
state.phaseDuration = 1.2;
updateInterface();
}
function updateSimulation(dt) {
state.simTime += dt;
state.phaseElapsed += dt;
if (state.phase === "survival") {
if (!state.cullTriggered && state.phaseElapsed >= 2.2) {
triggerSurvivalSelection();
}
if (state.phaseElapsed >= state.phaseDuration) {
beginReproduction();
}
} else if (state.phase === "reproduction") {
while (
state.birthQueue.length &&
state.phaseElapsed >= state.birthQueue[0].at
) {
spawnBirth(state.birthQueue.shift());
}
if (state.phaseElapsed >= state.phaseDuration) {
finishReproduction();
}
} else if (state.phase === "transition") {
if (state.phaseElapsed >= state.phaseDuration) {
startRound();
}
}
}
function updateAgentAnimations() {
for (const agent of allAgents) {
if (agent.removed) continue;
if (!agent.dying && agent.removeAt !== null && agent.alive &&
state.phaseElapsed >= agent.removeAt) {
agent.dying = true;
agent.alive = false;
agent.dieStart = state.phaseElapsed;
}
if (agent.dying) {
const progress = (state.phaseElapsed - agent.dieStart) / 0.3;
const scale = Math.max(0, 1 - progress);
agent.group.scale.setScalar(scale);
agent.group.position.y = -progress * 0.08;
if (progress >= 1) {
agent.removed = true;
scene.remove(agent.group);
}
continue;
}
const growth = agent.newborn
? THREE.MathUtils.clamp((state.simTime - agent.birthTime) / 0.6, 0.08, 1)
: 1;
const parentPulse = state.simTime < agent.parentPulseUntil
? 1 + Math.sin(state.simTime * 26) * 0.055
: 1;
agent.group.scale.setScalar(growth * parentPulse);
agent.group.position.y =
Math.sin(state.simTime * 2.1 + agent.bobOffset) * 0.025;
}
}
// -------------------------------------------------------------------------
// Environment visuals and interface
// -------------------------------------------------------------------------
const dryGroundColor = new THREE.Color(0x9b7145);
const wetGroundColor = new THREE.Color(0x315f51);
const dryLeafColor = new THREE.Color(0x9b884b);
const wetLeafColor = new THREE.Color(0x4f985e);
const wetSunColor = new THREE.Color(0xe7f5ff);
const drySunColor = new THREE.Color(0xffd18f);
function updateEnvironmentVisuals(dt) {
const environment = ENVIRONMENTS[state.currentEnv];
const blend = 1 - Math.exp(-dt * 2.4);
state.wetness += (environment.wetness - state.wetness) * blend;
const wetness = state.wetness;
groundMaterial.color.lerpColors(dryGroundColor, wetGroundColor, wetness);
groundMaterial.color.lerp(environment.ground, 0.28);
leafMaterial.color.lerpColors(dryLeafColor, wetLeafColor, wetness);
stemMaterial.color.lerpColors(
new THREE.Color(0x8b7042),
new THREE.Color(0x466f43),
wetness
);
scene.background.lerp(environment.background, blend);
scene.fog.color.copy(scene.background);
sun.color.lerpColors(drySunColor, wetSunColor, wetness);
sun.intensity = 2.35 + wetness * 0.75;
const poolScale = 0.24 + wetness * 0.76;
for (const pool of waterPools) {
pool.mesh.scale.set(pool.sx * poolScale, pool.sz * poolScale, 1);
}
waterGroup.visible = wetness > 0.035;
const dryScale = 0.28 + (1 - wetness) * 0.72;
dryPatch.scale.set(1.15 * dryScale, 0.8 * dryScale, 1);
dryPatch.visible = dryScale > 0.04;
for (const plant of plants) {
const base = plant.userData.baseScale;
plant.scale.y = base * (0.48 + wetness * 0.7);
}
}
function updateEnvironmentPanel() {
const environment = ENVIRONMENTS[state.currentEnv];
const m = Math.round(environment.odds.M * 100);
const d = Math.round(environment.odds.D * 100);
$("envName").textContent = environment.label;
$("envDescription").textContent = environment.description;
$("favoredText").textContent = environment.favored;
$("mOdds").textContent = `${m}%`;
$("dOdds").textContent = `${d}%`;
$("mOddsFill").style.width = `${m}%`;
$("dOddsFill").style.width = `${d}%`;
document.querySelectorAll(".env-button").forEach(button => {
button.classList.toggle("active", button.dataset.env === state.selectedEnv);
});
const canChangeNow =
state.phase === "survival" && !state.cullTriggered;
$("envSelectionLabel").textContent = canChangeNow
? "Active habitat"
: "Applies next round";
}
function updateInterface() {
const population = livingAgents().length;
$("populationStat").textContent = population;
$("survivorStat").textContent = state.cullTriggered
? state.survivors.length
: "—";
$("birthStat").textContent = state.newbornCount;
const progress = THREE.MathUtils.clamp(
state.phaseElapsed / state.phaseDuration,
0,
1
);
$("progressFill").style.width = `${progress * 100}%`;
const stepIndex =
state.phase === "survival" ? 0 :
state.phase === "reproduction" ? 1 : 2;
["stepSurvival", "stepReproduction", "stepNext"].forEach((id, index) => {
const element = $(id);
element.classList.toggle("active", index === stepIndex);
element.classList.toggle("done", index < stepIndex);
});
$("phaseCaption").textContent = `Stage ${stepIndex + 1} of 3`;
$("roundLabel").textContent = `Round ${state.round}`;
if (state.phase === "survival") {
$("stageName").textContent = "Survival test";
$("stageMeta").textContent =
`${ENVIRONMENTS[state.currentEnv].label}: the environment filters the inherited population.`;
} else if (state.phase === "reproduction") {
$("stageName").textContent = "Reproduction";
$("stageMeta").textContent =
`Survivors pass on their existing tokens. ${state.newbornCount} offspring born.`;
} else {
$("stageName").textContent = "Generation complete";
$("stageMeta").textContent =
"Frequencies are recorded. The next habitat will test the inherited population again.";
}
}
// -------------------------------------------------------------------------
// Frequency history chart
// -------------------------------------------------------------------------
const chart = $("historyChart");
const chartContext = chart.getContext("2d");
function drawHistory() {
const rect = chart.getBoundingClientRect();
if (!rect.width || !rect.height) return;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const width = rect.width;
const height = rect.height;
if (
chart.width !== Math.round(width * dpr) ||
chart.height !== Math.round(height * dpr)
) {
chart.width = Math.round(width * dpr);
chart.height = Math.round(height * dpr);
}
const ctx = chartContext;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, width, height);
const padding = { left: 31, right: 12, top: 13, bottom: 25 };
const plotWidth = width - padding.left - padding.right;
const plotHeight = height - padding.top - padding.bottom;
ctx.font = "9px system-ui";
ctx.lineWidth = 1;
for (const value of [0, 25, 50, 75, 100]) {
const y = padding.top + plotHeight * (1 - value / 100);
ctx.strokeStyle = "rgba(220,245,240,.09)";
ctx.beginPath();
ctx.moveTo(padding.left, y);
ctx.lineTo(width - padding.right, y);
ctx.stroke();
ctx.fillStyle = "#6f8985";
ctx.textAlign = "right";
ctx.fillText(`${value}`, padding.left - 6, y + 3);
}
if (!state.history.length) {
ctx.fillStyle = "#78908d";
ctx.textAlign = "center";
ctx.fillText(
"The first completed round will appear here.",
padding.left + plotWidth / 2,
padding.top + plotHeight / 2
);
return;
}
const pointX = index => {
if (state.history.length === 1) return padding.left + plotWidth / 2;
return padding.left + (index / (state.history.length - 1)) * plotWidth;
};
const pointY = value => padding.top + plotHeight * (1 - value);
function drawSeries(key, color) {
ctx.strokeStyle = color;
ctx.lineWidth = 2.2;
ctx.lineJoin = "round";
ctx.lineCap = "round";
ctx.beginPath();
state.history.forEach((entry, index) => {
const x = pointX(index);
const y = pointY(entry[key]);
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.stroke();
state.history.forEach((entry, index) => {
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(pointX(index), pointY(entry[key]), 3, 0, Math.PI * 2);
ctx.fill();
});
}
drawSeries("M", "#50d6c8");
drawSeries("D", "#ffad66");
ctx.fillStyle = "#6f8985";
ctx.textAlign = "left";
ctx.fillText(`R${state.history[0].round}`, padding.left, height - 7);
if (state.history.length > 1) {
ctx.textAlign = "right";
ctx.fillText(
`R${state.history[state.history.length - 1].round}`,
width - padding.right,
height - 7
);
}
}
// -------------------------------------------------------------------------
// Controls
// -------------------------------------------------------------------------
function resetSimulation() {
for (const agent of allAgents) {
scene.remove(agent.group);
}
allAgents = [];
state.round = 0;
state.paused = false;
state.speed = 1;
state.history = [];
state.selectedEnv = "mixed";
state.currentEnv = "mixed";
state.wetness = 0.56;
state.simTime = 0;
const initialCount = 60;
for (let i = 0; i < initialCount; i++) {
const token = i % 2 === 0 ? "M" : "D";
createAgent(token, randomPoint(), 0);
}
$("pauseButton").textContent = "Pause";
$("pauseButton").setAttribute("aria-pressed", "false");
$("speedButton").textContent = "1×";
drawHistory();
startRound();
}
$("pauseButton").addEventListener("click", () => {
state.paused = !state.paused;
$("pauseButton").textContent = state.paused ? "Resume" : "Pause";
$("pauseButton").setAttribute("aria-pressed", String(state.paused));
});
$("speedButton").addEventListener("click", () => {
state.speed = state.speed === 1 ? 2 : 1;
$("speedButton").textContent = `${state.speed}×`;
});
$("resetButton").addEventListener("click", resetSimulation);
$("cameraReset").addEventListener("click", resetCamera);
document.querySelectorAll(".env-button").forEach(button => {
button.addEventListener("click", () => {
state.selectedEnv = button.dataset.env;
// If selection has not started, the new habitat is used immediately.
if (state.phase === "survival" && !state.cullTriggered) {
state.currentEnv = state.selectedEnv;
}
updateEnvironmentPanel();
});
});
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const realDelta = Math.min(clock.getDelta(), 0.05);
state.visualTime += realDelta;
if (!state.paused) {
updateSimulation(realDelta * state.speed);
}
updateAgentAnimations();
updateEnvironmentVisuals(realDelta);
updateInterface();
renderer.render(scene, camera);
}
resetSimulation();
updateEnvironmentVisuals(1);
drawHistory();
animate();
</script>
</body>
</html>
```