Prompt specification
Build or customize the Three.js 3D scene "Mutation-and-selection separation 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: Mutation-and-selection separation explorer
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/mutation-and-selection-separation-explorer-x0936
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring genetic mutations. Provide independent random-variation and survival-rule controls in a synthetic population model; show that variation events do not know which traits the next environment will favor. Low-poly.
Working Three.js Starter (mutation-and-selection-separation-explorer-x0936):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Blind Variation — Synthetic Population</title>
<style>
:root {
color-scheme: dark;
--bg: #091117;
--panel: #101a21;
--panel-2: #16232c;
--line: #263945;
--text: #e8f2f5;
--muted: #8da5b1;
--mint: #7ce6b1;
--cyan: #67d9f4;
--amber: #ffc76a;
--pink: #ff8eae;
--danger: #ff7285;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input,
select {
font: inherit;
}
#app {
display: grid;
grid-template-columns: minmax(0, 1fr) 370px;
width: 100%;
height: 100%;
}
#stage {
position: relative;
min-width: 0;
overflow: hidden;
background: #101a22;
}
#scene {
position: absolute;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas:active {
cursor: grabbing;
}
.glass {
background: rgba(9, 17, 23, 0.78);
border: 1px solid rgba(151, 190, 204, 0.15);
box-shadow: 0 18px 45px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
#masthead {
position: absolute;
top: 22px;
left: 24px;
max-width: 530px;
padding: 16px 18px;
border-radius: 16px;
pointer-events: none;
}
.eyebrow {
margin-bottom: 5px;
color: var(--mint);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(20px, 2.2vw, 30px);
line-height: 1.05;
letter-spacing: -0.035em;
}
#masthead p {
max-width: 490px;
margin: 8px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
#environment-card {
position: absolute;
top: 22px;
right: 22px;
width: 230px;
padding: 14px 15px;
border-radius: 15px;
transition:
border-color 0.35s,
background 0.35s,
transform 0.35s;
}
#environment-card.sealed {
border-color: rgba(255, 199, 106, 0.35);
}
#environment-card.revealed {
border-color: rgba(124, 230, 177, 0.48);
transform: translateY(2px);
}
.card-label {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
#environment-name {
margin-top: 6px;
font-size: 17px;
font-weight: 850;
letter-spacing: -0.02em;
}
#environment-detail {
margin-top: 5px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
#stats {
position: absolute;
left: 24px;
bottom: 22px;
display: grid;
grid-template-columns: repeat(4, minmax(78px, 1fr));
width: min(510px, calc(100% - 48px));
overflow: hidden;
border-radius: 15px;
}
.stat {
padding: 12px 13px;
border-right: 1px solid rgba(151, 190, 204, 0.13);
}
.stat:last-child {
border-right: 0;
}
.stat-label {
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.stat-value {
margin-top: 4px;
font-size: 20px;
font-weight: 800;
}
#inspector {
position: absolute;
right: 22px;
bottom: 22px;
width: 230px;
padding: 14px;
border-radius: 15px;
}
#inspector-title {
margin: 4px 0 10px;
font-size: 13px;
font-weight: 800;
}
.trait-row {
margin-top: 8px;
}
.trait-label {
display: flex;
justify-content: space-between;
margin-bottom: 4px;
color: var(--muted);
font-size: 10px;
}
.trait-track {
height: 5px;
overflow: hidden;
border-radius: 999px;
background: rgba(255, 255, 255, 0.08);
}
.trait-fill {
width: 0;
height: 100%;
border-radius: inherit;
transition: width 0.2s ease;
}
#speed-fill {
background: var(--cyan);
}
#color-fill {
background: var(--amber);
}
#size-fill {
background: var(--pink);
}
#panel {
position: relative;
z-index: 3;
height: 100%;
overflow-y: auto;
padding: 20px;
background: var(--panel);
border-left: 1px solid var(--line);
scrollbar-width: thin;
scrollbar-color: #38505e transparent;
}
.panel-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 16px;
}
.panel-heading h2 {
margin: 0;
font-size: 18px;
letter-spacing: -0.025em;
}
.panel-heading p {
margin: 5px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.live-dot {
display: flex;
align-items: center;
gap: 6px;
flex: 0 0 auto;
padding: 6px 8px;
border: 1px solid rgba(124, 230, 177, 0.25);
border-radius: 999px;
color: var(--mint);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.live-dot::before {
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 10px currentColor;
content: "";
}
fieldset {
min-width: 0;
margin: 0 0 13px;
padding: 14px;
border: 1px solid var(--line);
border-radius: 14px;
background: var(--panel-2);
}
fieldset:disabled {
opacity: 0.58;
}
legend {
padding: 0 6px;
color: var(--mint);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.control {
margin-top: 12px;
}
.control:first-of-type {
margin-top: 3px;
}
.control-label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 7px;
color: #c8d7de;
font-size: 11px;
}
output {
min-width: 45px;
color: var(--text);
font-variant-numeric: tabular-nums;
text-align: right;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 5px 0;
appearance: none;
border-radius: 999px;
background: #2a3d48;
outline: none;
}
input[type="range"]::-webkit-slider-thumb {
width: 14px;
height: 14px;
appearance: none;
border: 2px solid #132229;
border-radius: 50%;
background: var(--mint);
box-shadow: 0 0 0 1px rgba(124, 230, 177, 0.35);
cursor: pointer;
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border: 2px solid #132229;
border-radius: 50%;
background: var(--mint);
cursor: pointer;
}
select,
input[type="number"] {
width: 100%;
height: 36px;
padding: 0 10px;
border: 1px solid #304550;
border-radius: 9px;
outline: none;
background: #101a21;
color: var(--text);
font-size: 11px;
}
select:focus,
input[type="number"]:focus {
border-color: var(--mint);
}
.split {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.mini-note {
margin: 9px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
#proof {
margin-bottom: 13px;
padding: 13px 14px;
border: 1px solid rgba(103, 217, 244, 0.24);
border-radius: 14px;
background: rgba(103, 217, 244, 0.055);
}
#proof-title {
color: var(--cyan);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
}
#proof-code {
margin-top: 8px;
color: #bdebf7;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.65;
}
#proof p {
margin: 8px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.button-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 9px;
margin: 14px 0;
}
button {
min-height: 39px;
padding: 0 14px;
border: 0;
border-radius: 10px;
color: #092119;
background: var(--mint);
font-size: 11px;
font-weight: 850;
cursor: pointer;
transition:
transform 0.15s,
filter 0.15s;
}
button:hover:not(:disabled) {
filter: brightness(1.07);
transform: translateY(-1px);
}
button:disabled {
opacity: 0.45;
cursor: wait;
}
#reset-button {
min-width: 70px;
border: 1px solid var(--line);
background: transparent;
color: var(--muted);
}
#timeline {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 4px;
margin: 13px 0;
}
.phase {
position: relative;
padding-top: 11px;
color: #617783;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.08em;
text-align: center;
text-transform: uppercase;
}
.phase::before {
position: absolute;
top: 0;
left: 50%;
width: 7px;
height: 7px;
border-radius: 50%;
background: #304550;
transform: translateX(-50%);
content: "";
}
.phase.active {
color: var(--amber);
}
.phase.active::before {
background: var(--amber);
box-shadow: 0 0 10px rgba(255, 199, 106, 0.7);
}
.phase.done {
color: var(--mint);
}
.phase.done::before {
background: var(--mint);
}
#phase-message {
min-height: 38px;
margin: 0 0 12px;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
#log-title {
margin: 16px 0 8px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
#log {
display: flex;
flex-direction: column;
gap: 6px;
}
.log-entry {
padding: 8px 9px;
border-left: 2px solid #38505e;
background: rgba(255, 255, 255, 0.025);
color: #9fb2bc;
font-size: 10px;
line-height: 1.45;
}
.log-entry strong {
color: var(--text);
}
.hint {
position: absolute;
left: 50%;
bottom: 25px;
padding: 7px 11px;
border-radius: 999px;
color: rgba(226, 241, 246, 0.62);
background: rgba(9, 17, 23, 0.55);
font-size: 9px;
pointer-events: none;
transform: translateX(-50%);
}
@media (max-width: 900px) {
#app {
grid-template-columns: 1fr;
grid-template-rows: 60vh 40vh;
}
#panel {
height: 40vh;
border-top: 1px solid var(--line);
border-left: 0;
}
#inspector {
display: none;
}
#environment-card {
top: auto;
right: 16px;
bottom: 98px;
}
#masthead {
top: 16px;
left: 16px;
}
#stats {
left: 16px;
bottom: 16px;
width: calc(100% - 32px);
}
.hint {
display: none;
}
}
@media (max-width: 520px) {
#masthead {
right: 16px;
max-width: none;
}
#masthead p {
display: none;
}
#environment-card {
width: 190px;
}
#stats {
grid-template-columns: repeat(2, 1fr);
}
.stat:nth-child(2) {
border-right: 0;
}
}
</style>
</head>
<body>
<div id="app">
<main id="stage">
<div id="scene"></div>
<section id="masthead" class="glass">
<div class="eyebrow">Synthetic population laboratory</div>
<h1>Blind Variation</h1>
<p>
Variation is sampled before the next environment is revealed.
The mutation function never receives an environment or survival rule.
</p>
</section>
<section id="environment-card" class="glass sealed">
<div class="card-label">Next environment</div>
<div id="environment-name">SEALED</div>
<div id="environment-detail">
Its favored traits will be hidden until random variation is complete.
</div>
</section>
<section id="stats" class="glass">
<div class="stat">
<div class="stat-label">Population</div>
<div class="stat-value" id="population-stat">0</div>
</div>
<div class="stat">
<div class="stat-label">Mutations</div>
<div class="stat-value" id="mutation-stat">0</div>
</div>
<div class="stat">
<div class="stat-label">Survivors</div>
<div class="stat-value" id="survivor-stat">—</div>
</div>
<div class="stat">
<div class="stat-label">Environment</div>
<div class="stat-value" id="environment-stat">Hidden</div>
</div>
</section>
<section id="inspector" class="glass">
<div class="card-label">Individual inspector</div>
<div id="inspector-title">Click a creature</div>
<div class="trait-row">
<div class="trait-label">
<span>Speed</span>
<span id="inspect-speed">—</span>
</div>
<div class="trait-track"><div id="speed-fill" class="trait-fill"></div></div>
</div>
<div class="trait-row">
<div class="trait-label">
<span>Warm camouflage</span>
<span id="inspect-color">—</span>
</div>
<div class="trait-track"><div id="color-fill" class="trait-fill"></div></div>
</div>
<div class="trait-row">
<div class="trait-label">
<span>Size</span>
<span id="inspect-size">—</span>
</div>
<div class="trait-track"><div id="size-fill" class="trait-fill"></div></div>
</div>
</section>
<div class="hint">Drag to orbit · Shift/right-drag to pan · Scroll to zoom</div>
</main>
<aside id="panel">
<div class="panel-heading">
<div>
<h2>Experiment controls</h2>
<p>Change either system without coupling the other.</p>
</div>
<div class="live-dot">Live</div>
</div>
<fieldset id="mutation-controls">
<legend>1 · Random variation</legend>
<div class="control">
<label class="control-label" for="mutation-chance">
<span>Chance per trait</span>
<output id="mutation-chance-output">45%</output>
</label>
<input id="mutation-chance" type="range" min="0" max="100" value="45" />
</div>
<div class="control">
<label class="control-label" for="mutation-spread">
<span>Trait spread</span>
<output id="mutation-spread-output">25%</output>
</label>
<input id="mutation-spread" type="range" min="5" max="60" value="25" />
</div>
<p class="mini-note">
Each trait is independently tested and, when changed, receives a
random signed delta.
</p>
</fieldset>
<fieldset id="environment-controls">
<legend>2 · Future environment</legend>
<div class="control">
<label class="control-label" for="environment-choice">
<span>Environment schedule</span>
</label>
<select id="environment-choice">
<option value="surprise">Surprise draw — sealed</option>
<option value="sun">Sunscorched</option>
<option value="flood">Rising tide</option>
<option value="current">Flash current</option>
</select>
</div>
<p class="mini-note">
The environment is selected before variation, but it is sampled from
a separate random stream and hidden during mutation.
</p>
</fieldset>
<fieldset id="survival-controls">
<legend>3 · Survival rule</legend>
<div class="control">
<label class="control-label" for="survival-rule">
<span>Favored strategy</span>
</label>
<select id="survival-rule">
<option value="environment">Use environment's rule</option>
<option value="speed">Favor speed</option>
<option value="size">Favor size</option>
<option value="camouflage">Favor camouflage</option>
<option value="balanced">Favor balanced traits</option>
</select>
</div>
<div class="control">
<label class="control-label" for="selection-pressure">
<span>Selection pressure</span>
<output id="selection-pressure-output">60%</output>
</label>
<input id="selection-pressure" type="range" min="0" max="100" value="60" />
</div>
<div class="control">
<label class="control-label" for="minimum-survivors">
<span>Minimum survivors</span>
<output id="minimum-survivors-output">6</output>
</label>
<input id="minimum-survivors" type="range" min="2" max="30" value="6" />
</div>
</fieldset>
<fieldset id="population-controls">
<legend>Population & seed</legend>
<div class="split">
<div class="control">
<label class="control-label" for="population-size">
<span>Target size</span>
</label>
<input id="population-size" type="number" min="18" max="60" value="36" />
</div>
<div class="control">
<label class="control-label" for="seed">
<span>Seed</span>
</label>
<input id="seed" type="number" min="1" max="999999" value="202503" />
</div>
</div>
</fieldset>
<section id="proof">
<div id="proof-title">Independence receipt</div>
<div id="proof-code">
mutate(members, chance, spread, rng)<br />
survive(members, rule, environment)
</div>
<p>
There is no environment argument or edge into <code>mutate()</code>.
The environment can affect survival only after variation closes.
</p>
</section>
<div class="button-row">
<button id="run-button" type="button">Run full generation</button>
<button id="reset-button" type="button">Reset</button>
</div>
<div id="timeline">
<div class="phase" data-phase="variation">Variation</div>
<div class="phase" data-phase="reveal">Reveal</div>
<div class="phase" data-phase="survival">Survival</div>
<div class="phase" data-phase="breed">Breed</div>
</div>
<p id="phase-message">
Ready. The next run will seal the environment, vary traits randomly,
reveal the environment, and only then apply survival.
</p>
<div id="log-title">Experiment log</div>
<div id="log"></div>
</aside>
</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);
// ---------------------------------------------------------------------
// Deterministic and independent random streams
// ---------------------------------------------------------------------
function mulberry32(seed) {
let a = seed >>> 0;
return function () {
a += 0x6d2b79f5;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function hashSeed(value) {
const text = String(value);
let hash = 2166136261;
for (let i = 0; i < text.length; i++) {
hash ^= text.charCodeAt(i);
hash = Math.imul(hash, 16777619);
}
return hash >>> 0;
}
let mutationRng;
let environmentRng;
let survivalRng;
let populationRng;
function configureRandomStreams() {
const seed = hashSeed($("seed").value || 1);
mutationRng = mulberry32(seed);
environmentRng = mulberry32(seed ^ 0x9e3779b9);
survivalRng = mulberry32(seed ^ 0x85ebca6b);
populationRng = mulberry32(seed ^ 0xc2b2ae35);
}
// ---------------------------------------------------------------------
// Environment definitions
// ---------------------------------------------------------------------
const ENVIRONMENTS = {
sun: {
key: "sun",
name: "SUNSCORCHED",
detail: "Dry heat favors warm camouflage and moderate body size.",
favored: "warm camouflage",
ground: 0x8b704b,
sky: 0x2b2320,
fog: 0x7a5a3e,
accent: 0xffc76a,
weights: { speed: 0.28, color: 0.86, size: 0.30 },
targets: { speed: 0.52, color: 0.94, size: 0.48 }
},
flood: {
key: "flood",
name: "RISING TIDE",
detail: "Deep water favors a large body and moderate speed.",
favored: "large body",
ground: 0x315d61,
sky: 0x10252f,
fog: 0x214c57,
accent: 0x67d9f4,
weights: { speed: 0.30, color: 0.18, size: 0.90 },
targets: { speed: 0.45, color: 0.12, size: 0.93 }
},
current: {
key: "current",
name: "FLASH CURRENT",
detail: "Fast water strongly favors speed, with some preference for size.",
favored: "high speed",
ground: 0x3f684e,
sky: 0x102721,
fog: 0x2c5842,
accent: 0x7ce6b1,
weights: { speed: 0.95, color: 0.14, size: 0.28 },
targets: { speed: 0.95, color: 0.18, size: 0.45 }
}
};
const environmentKeys = Object.keys(ENVIRONMENTS);
function chooseEnvironment(choice, rng) {
if (choice === "surprise") {
return ENVIRONMENTS[environmentKeys[Math.floor(rng() * environmentKeys.length)]];
}
return ENVIRONMENTS[choice];
}
// ---------------------------------------------------------------------
// Three.js scene
// ---------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x101a22);
scene.fog = new THREE.FogExp2(0x101a22, 0.032);
const camera = new THREE.PerspectiveCamera(43, 1, 0.1, 100);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
$("scene").appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xc7efff, 0x334034, 2.0);
scene.add(hemisphere);
const sunLight = new THREE.DirectionalLight(0xffe2aa, 3.0);
sunLight.position.set(-6, 11, 7);
sunLight.castShadow = true;
sunLight.shadow.mapSize.set(1024, 1024);
sunLight.shadow.camera.left = -10;
sunLight.shadow.camera.right = 10;
sunLight.shadow.camera.top = 10;
sunLight.shadow.camera.bottom = -10;
sunLight.shadow.camera.near = 1;
sunLight.shadow.camera.far = 30;
scene.add(sunLight);
const rimLight = new THREE.DirectionalLight(0x67d9f4, 0.8);
rimLight.position.set(7, 5, -7);
scene.add(rimLight);
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x455b45,
roughness: 0.96,
metalness: 0,
flatShading: true
});
const ground = new THREE.Mesh(
new THREE.CylinderGeometry(8.2, 8.65, 0.7, 24, 1, false),
groundMaterial
);
ground.position.y = -0.35;
ground.receiveShadow = true;
scene.add(ground);
const lowerGround = new THREE.Mesh(
new THREE.CylinderGeometry(8.65, 7.7, 1.2, 24),
new THREE.MeshStandardMaterial({
color: 0x29352f,
roughness: 1,
flatShading: true
})
);
lowerGround.position.y = -1.22;
lowerGround.receiveShadow = true;
scene.add(lowerGround);
const worldRng = mulberry32(90125);
const trunkGeometry = new THREE.CylinderGeometry(0.13, 0.19, 1, 5);
const canopyGeometry = new THREE.ConeGeometry(0.68, 1.45, 6);
const trunkMaterial = new THREE.MeshStandardMaterial({
color: 0x65513a,
roughness: 1,
flatShading: true
});
const canopyMaterial = new THREE.MeshStandardMaterial({
color: 0x315e48,
roughness: 1,
flatShading: true
});
for (let i = 0; i < 13; i++) {
const angle = worldRng() * Math.PI * 2;
const radius = 6.25 + worldRng() * 1.15;
const tree = new THREE.Group();
const trunk = new THREE.Mesh(trunkGeometry, trunkMaterial);
trunk.position.y = 0.52;
trunk.castShadow = true;
tree.add(trunk);
const canopy = new THREE.Mesh(canopyGeometry, canopyMaterial);
canopy.position.y = 1.35;
canopy.rotation.y = worldRng() * Math.PI;
canopy.castShadow = true;
tree.add(canopy);
tree.position.set(
Math.cos(angle) * radius,
0,
Math.sin(angle) * radius
);
tree.scale.setScalar(0.65 + worldRng() * 0.55);
scene.add(tree);
}
const rockGeometry = new THREE.DodecahedronGeometry(0.38, 0);
const rockMaterial = new THREE.MeshStandardMaterial({
color: 0x66706b,
roughness: 1,
flatShading: true
});
for (let i = 0; i < 17; i++) {
const angle = worldRng() * Math.PI * 2;
const radius = 5.7 + worldRng() * 2.0;
const rock = new THREE.Mesh(rockGeometry, rockMaterial);
rock.position.set(
Math.cos(angle) * radius,
0.1,
Math.sin(angle) * radius
);
rock.scale.set(
0.6 + worldRng() * 1.1,
0.45 + worldRng() * 0.8,
0.6 + worldRng() * 1.1
);
rock.rotation.set(worldRng(), worldRng(), worldRng());
rock.castShadow = true;
rock.receiveShadow = true;
scene.add(rock);
}
const water = new THREE.Mesh(
new THREE.CircleGeometry(8.12, 32),
new THREE.MeshStandardMaterial({
color: 0x4dcce4,
transparent: true,
opacity: 0,
roughness: 0.25,
metalness: 0.12,
side: THREE.DoubleSide
})
);
water.rotation.x = -Math.PI / 2;
water.position.y = 0.015;
scene.add(water);
const rushGroup = new THREE.Group();
const rushMaterial = new THREE.MeshBasicMaterial({
color: 0xa1ffd1,
transparent: true,
opacity: 0
});
const rushGeometry = new THREE.BoxGeometry(0.8, 0.025, 0.045);
for (let i = 0; i < 28; i++) {
const angle = worldRng() * Math.PI * 2;
const radius = 1.8 + worldRng() * 5.8;
const streak = new THREE.Mesh(rushGeometry, rushMaterial);
streak.position.set(
Math.cos(angle) * radius,
0.05 + worldRng() * 0.04,
Math.sin(angle) * radius
);
streak.rotation.y = -angle + Math.PI / 2;
rushGroup.add(streak);
}
scene.add(rushGroup);
const moteCount = 150;
const motePositions = new Float32Array(moteCount * 3);
const moteBase = new Float32Array(moteCount * 3);
for (let i = 0; i < moteCount; i++) {
const angle = worldRng() * Math.PI * 2;
const radius = worldRng() * 7.7;
const x = Math.cos(angle) * radius;
const y = 0.2 + worldRng() * 3.8;
const z = Math.sin(angle) * radius;
motePositions.set([x, y, z], i * 3);
moteBase.set([x, y, z], i * 3);
}
const moteGeometry = new THREE.BufferGeometry();
moteGeometry.setAttribute(
"position",
new THREE.BufferAttribute(motePositions, 3)
);
const moteMaterial = new THREE.PointsMaterial({
color: 0xbde8cf,
size: 0.065,
transparent: true,
opacity: 0.58,
depthWrite: false
});
const motes = new THREE.Points(moteGeometry, moteMaterial);
scene.add(motes);
let targetGroundColor = new THREE.Color(0x455b45);
let targetFogColor = new THREE.Color(0x101a22);
let targetAccentColor = new THREE.Color(0xbde8cf);
let targetWaterOpacity = 0;
let targetRushOpacity = 0;
function applyEnvironmentVisual(environment) {
targetGroundColor.set(environment.ground);
targetFogColor.set(environment.fog);
targetAccentColor.set(environment.accent);
targetWaterOpacity = environment.key === "flood" ? 0.42 : 0;
targetRushOpacity = environment.key === "current" ? 0.65 : 0;
}
// ---------------------------------------------------------------------
// Population and low-poly creatures
// ---------------------------------------------------------------------
const TRAITS = ["speed", "color", "size"];
const coolColor = new THREE.Color(0x72cc94);
const warmColor = new THREE.Color(0xb8794d);
const bodyGeometry = new THREE.IcosahedronGeometry(0.31, 0);
const crestGeometry = new THREE.ConeGeometry(0.16, 0.38, 5);
const eyeGeometry = new THREE.IcosahedronGeometry(0.045, 0);
const eyeMaterial = new THREE.MeshBasicMaterial({ color: 0x102027 });
const ringGeometry = new THREE.TorusGeometry(0.43, 0.025, 4, 18);
let population = [];
let nextCreatureId = 1;
let busy = false;
let currentPhase = "idle";
let lastMutationCount = 0;
let lastSurvivorCount = null;
let currentEnvironment = null;
function randomPosition(rng) {
const angle = rng() * Math.PI * 2;
const radius = 0.5 + Math.sqrt(rng()) * 5.55;
return new THREE.Vector3(
Math.cos(angle) * radius,
0.08,
Math.sin(angle) * radius
);
}
function randomTraits(rng) {
return {
speed: 0.12 + rng() * 0.78,
color: rng(),
size: 0.62 + rng() * 0.68
};
}
function makeIndividual(traits, id = nextCreatureId++) {
const group = new THREE.Group();
const material = new THREE.MeshStandardMaterial({
color: coolColor,
roughness: 0.88,
metalness: 0,
flatShading: true
});
const body = new THREE.Mesh(bodyGeometry, material);
body.position.y = 0.35;
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const crest = new THREE.Mesh(crestGeometry, material);
crest.position.set(0, 0.68, -0.03);
crest.rotation.z = -0.15;
crest.castShadow = true;
group.add(crest);
const leftEye = new THREE.Mesh(eyeGeometry, eyeMaterial);
leftEye.position.set(-0.13, 0.42, 0.265);
group.add(leftEye);
const rightEye = new THREE.Mesh(eyeGeometry, eyeMaterial);
rightEye.position.set(0.13, 0.42, 0.265);
group.add(rightEye);
const ring = new THREE.Mesh(
ringGeometry,
new THREE.MeshBasicMaterial({
color: 0x7ce6b1,
transparent: true,
opacity: 0.8,
depthWrite: false
})
);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.025;
ring.visible = false;
group.add(ring);
const individual = {
id,
group,
body,
bodyMaterial: material,
ring,
traits: { ...traits },
home: new THREE.Vector3(),
baseScale: traits.size,
phase: Math.random() * Math.PI * 2,
dying: false,
deathProgress: 0,
birthProgress: 1
};
body.userData.individual = individual;
crest.userData.individual = individual;
scene.add(group);
updateIndividualAppearance(individual);
return individual;
}
function updateIndividualAppearance(individual) {
const t = individual.traits;
individual.bodyMaterial.color.copy(coolColor).lerp(warmColor, t.color);
individual.baseScale = t.size;
}
function seedPopulation() {
for (const individual of population) {
scene.remove(individual.group);
}
population = [];
nextCreatureId = 1;
const target = clamp(
Math.round(Number($("population-size").value)),
18,
60
);
for (let i = 0; i < target; i++) {
const individual = makeIndividual(randomTraits(populationRng));
individual.home.copy(randomPosition(populationRng));
individual.group.position.copy(individual.home);
population.push(individual);
}
updateStats();
}
// ---------------------------------------------------------------------
// The important independence boundary
//
// This function intentionally has no environment or survival arguments.
// It cannot consult the next environment.
// ---------------------------------------------------------------------
function mutatePopulation(members, chance, spread, rng) {
const events = [];
for (const individual of members) {
for (const trait of TRAITS) {
if (rng() < chance) {
const before = individual.traits[trait];
const delta = (rng() * 2 - 1) * spread;
let after;
if (trait === "speed") {
after = THREE.MathUtils.clamp(before + delta, 0.08, 1);
} else if (trait === "color") {
after = THREE.MathUtils.clamp(before + delta, 0, 1);
} else {
after = THREE.MathUtils.clamp(before + delta, 0.55, 1.5);
}
individual.traits[trait] = after;
events.push({
individual,
trait,
before,
after,
delta
});
}
}
updateIndividualAppearance(individual);
}
return events;
}
// ---------------------------------------------------------------------
// Survival rules
// ---------------------------------------------------------------------
function buildRule(ruleName, environment) {
if (ruleName === "speed") {
return {
label: "Favor speed",
weights: { speed: 1, color: 0, size: 0 },
targets: { speed: 1, color: 0.5, size: 0.5 }
};
}
if (ruleName === "size") {
return {
label: "Favor size",
weights: { speed: 0, color: 0, size: 1 },
targets: { speed: 0.5, color: 0.5, size: 1 }
};
}
if (ruleName === "camouflage") {
return {
label: "Favor camouflage",
weights: { speed: 0, color: 1, size: 0 },
targets: { speed: 0.5, color: environment.targets.color, size: 0.5 }
};
}
if (ruleName === "balanced") {
return {
label: "Favor balanced traits",
weights: { speed: 0.8, color: 0.8, size: 0.8 },
targets: { speed: 0.55, color: 0.55, size: 0.72 }
};
}
return {
label: `${environment.name} environment rule`,
weights: environment.weights,
targets: environment.targets
};
}
function scoreIndividual(individual, rule, pressure, rng) {
let score = 0;
let totalWeight = 0;
for (const trait of TRAITS) {
const weight = rule.weights[trait];
score +=
weight *
(1 - Math.abs(individual.traits[trait] - rule.targets[trait]));
totalWeight += weight;
}
score /= Math.max(totalWeight, 0.0001);
// Survival has its own randomness. It is not fed into mutation.
score += (rng() - 0.5) * (1 - pressure) * 0.18;
return score;
}
// ---------------------------------------------------------------------
// Mutation burst effects
// ---------------------------------------------------------------------
const burstGeometry = new THREE.TetrahedronGeometry(0.075, 0);
const bursts = [];
function spawnBurst(position, color) {
const group = new THREE.Group();
const material = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.95
});
for (let i = 0; i < 6; i++) {
const shard = new THREE.Mesh(burstGeometry, material);
const angle = (i / 6) * Math.PI * 2;
shard.userData.velocity = new THREE.Vector3(
Math.cos(angle) * (0.7 + Math.random() * 0.4),
0.65 + Math.random() * 0.7,
Math.sin(angle) * (0.7 + Math.random() * 0.4)
);
shard.rotation.set(
Math.random() * Math.PI,
Math.random() * Math.PI,
Math.random() * Math.PI
);
group.add(shard);
}
group.position.copy(position);
scene.add(group);
bursts.push({ group, material, life: 0.8 });
}
function updateBursts(dt) {
for (let i = bursts.length - 1; i >= 0; i--) {
const burst = bursts[i];
burst.life -= dt;
for (const shard of burst.group.children) {
shard.position.addScaledVector(shard.userData.velocity, dt);
shard.userData.velocity.y -= dt * 1.8;
shard.rotation.x += dt * 3;
shard.rotation.y += dt * 4;
}
burst.material.opacity = Math.max(0, burst.life / 0.8);
if (burst.life <= 0) {
scene.remove(burst.group);
burst.material.dispose();
bursts.splice(i, 1);
}
}
}
// ---------------------------------------------------------------------
// UI helpers and logs
// ---------------------------------------------------------------------
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function log(message, title = "") {
const entry = document.createElement("div");
entry.className = "log-entry";
if (title) {
const strong = document.createElement("strong");
strong.textContent = title + " ";
entry.appendChild(strong);
}
entry.appendChild(document.createTextNode(message));
$("log").prepend(entry);
while ($("log").children.length > 7) {
$("log").lastElementChild.remove();
}
}
function setPhase(phase) {
currentPhase = phase;
const order = ["variation", "reveal", "survival", "breed"];
const activeIndex = order.indexOf(phase);
document.querySelectorAll(".phase").forEach((element) => {
const index = order.indexOf(element.dataset.phase);
element.classList.toggle("active", index === activeIndex);
element.classList.toggle(
"done",
activeIndex >= 0 && index < activeIndex
);
});
}
function updateStats() {
$("population-stat").textContent = population.length;
$("mutation-stat").textContent = lastMutationCount;
$("survivor-stat").textContent =
lastSurvivorCount === null ? "—" : lastSurvivorCount;
$("environment-stat").textContent = currentEnvironment
? currentEnvironment.name.split(" ")[0]
: "Hidden";
}
function updateOutputs() {
$("mutation-chance-output").textContent = `${$("mutation-chance").value}%`;
$("mutation-spread-output").textContent = `${$("mutation-spread").value}%`;
$("selection-pressure-output").textContent =
`${$("selection-pressure").value}%`;
$("minimum-survivors-output").textContent =
$("minimum-survivors").value;
}
function setBusy(value) {
busy = value;
$("run-button").disabled = value;
$("reset-button").disabled = value;
document.querySelectorAll("fieldset").forEach((fieldset) => {
fieldset.disabled = value;
});
$("run-button").textContent = value
? "Generation running…"
: "Run full generation";
}
function updateEnvironmentCard(environment) {
currentEnvironment = environment;
$("environment-card").classList.remove("sealed");
$("environment-card").classList.add("revealed");
$("environment-name").textContent = environment.name;
$("environment-detail").textContent = environment.detail;
updateStats();
}
// ---------------------------------------------------------------------
// Full generation: variation -> reveal -> survival -> breeding
// ---------------------------------------------------------------------
async function runGeneration() {
if (busy) return;
setBusy(true);
lastMutationCount = 0;
lastSurvivorCount = null;
currentEnvironment = null;
$("environment-card").classList.add("sealed");
$("environment-card").classList.remove("revealed");
$("environment-name").textContent = "SEALED";
$("environment-detail").textContent =
"The environment draw exists, but variation cannot access it.";
updateStats();
const chance = Number($("mutation-chance").value) / 100;
const spread = Number($("mutation-spread").value) / 100;
const pressure = Number($("selection-pressure").value) / 100;
const minimum = Number($("minimum-survivors").value);
const ruleName = $("survival-rule").value;
const environmentChoice = $("environment-choice").value;
const targetPopulation = clamp(
Math.round(Number($("population-size").value)),
18,
60
);
// Environment is drawn first, but from an independent RNG stream.
// Its identity is deliberately not passed into mutatePopulation().
const sealedEnvironment = chooseEnvironment(
environmentChoice,
environmentRng
);
log(
"A future environment was sealed using a separate random stream. " +
"The variation function will not receive its identity."
);
// ---------------------- Variation ----------------------
setPhase("variation");
$("phase-message").textContent =
"Variation is sampling traits using only chance, spread, and the mutation RNG. " +
"No environment or survival rule is in scope.";
const events = mutatePopulation(
population,
chance,
spread,
mutationRng
);
lastMutationCount = events.length;
updateStats();
const traitColors = {
speed: 0x67d9f4,
color: 0xffc76a,
size: 0xff8eae
};
events.slice(0, 100).forEach((event, index) => {
setTimeout(() => {
if (busy) {
const position = event.individual.group.position.clone();
position.y += 0.45 * event.individual.baseScale;
spawnBurst(position, traitColors[event.trait]);
}
}, index * 24);
});
log(
`${events.length} random trait writes across ${population.length} individuals. ` +
`Inputs: chance ${Math.round(chance * 100)}%, spread ${Math.round(spread * 100)}%, mutation RNG. ` +
`Environment and rule: not passed.`,
"Blind variation complete."
);
await sleep(1700 + Math.min(events.length, 100) * 12);
// ---------------------- Reveal ----------------------
setPhase("reveal");
updateEnvironmentCard(sealedEnvironment);
$("phase-message").textContent =
`Now revealed: ${sealedEnvironment.name}. It favors ${sealedEnvironment.favored}. ` +
`The same population carries the already-sampled traits into this environment.`;
log(
`${sealedEnvironment.name} revealed. Favored strategy: ${sealedEnvironment.favored}. ` +
`This information became available only after variation closed.`,
"Environment revealed."
);
await sleep(1050);
// ---------------------- Survival ----------------------
setPhase("survival");
const rule = buildRule(ruleName, sealedEnvironment);
const ranked = population
.map((individual) => ({
individual,
score: scoreIndividual(
individual,
rule,
pressure,
survivalRng
)
}))
.sort((a, b) => b.score - a.score);
const pressureKeepFraction = 0.92 - pressure * 0.72;
let keepCount = Math.round(population.length * pressureKeepFraction);
keepCount = Math.max(minimum, keepCount);
keepCount = Math.min(keepCount, Math.max(1, targetPopulation - 1));
keepCount = clamp(keepCount, 1, population.length - 1);
const survivors = ranked
.slice(0, keepCount)
.map((entry) => entry.individual);
const losers = ranked
.slice(keepCount)
.map((entry) => entry.individual);
for (const individual of survivors) {
individual.ring.visible = true;
individual.ring.material.opacity = 0.85;
}
for (const individual of losers) {
individual.dying = true;
individual.deathProgress = 0;
individual.bodyMaterial.transparent = true;
}
lastSurvivorCount = survivors.length;
updateStats();
$("phase-message").textContent =
`${rule.label}. ${survivors.length} individuals survived and ${losers.length} were removed. ` +
`Selection pressure: ${Math.round(pressure * 100)}%.`;
log(
`${rule.label} was applied after reveal. ${survivors.length} survived; ` +
`${losers.length} did not. Survival uses a separate RNG from mutation.`,
"Survival rule applied."
);
await sleep(1250);
for (const individual of losers) {
scene.remove(individual.group);
individual.bodyMaterial.dispose();
individual.ring.material.dispose();
}
population = population.filter((individual) => !individual.dying);
// ---------------------- Breeding ----------------------
setPhase("breed");
$("phase-message").textContent =
"Survivors reproduce without new mutation here. Copying inherited traits " +
"restores the target population; fresh random variation begins only in the next cycle.";
const breeders = [...survivors];
let birthIndex = 0;
while (population.length < targetPopulation) {
const parent = breeders[birthIndex % breeders.length];
const child = makeIndividual({ ...parent.traits });
child.home.copy(randomPosition(populationRng));
child.group.position.copy(child.home);
child.birthProgress = 0;
child.ring.visible = false;
population.push(child);
birthIndex++;
}
log(
`Population restored to ${population.length}. Offspring inherited survivor traits exactly; ` +
`no mutation was mixed into reproduction.`,
"Breeding complete."
);
await sleep(750);
setPhase("idle");
$("phase-message").textContent =
"Generation complete. Change variation or survival controls independently, " +
"then run again to compare outcomes.";
updateStats();
setBusy(false);
}
// ---------------------------------------------------------------------
// Individual inspection
// ---------------------------------------------------------------------
function inspectIndividual(individual) {
$("inspector-title").textContent = `Creatter #${individual.id}`;
const speed = Math.round(individual.traits.speed * 100);
const color = Math.round(individual.traits.color * 100);
const size = Math.round((individual.traits.size / 1.5) * 100);
$("inspect-speed").textContent = `${speed}%`;
$("inspect-color").textContent = `${color}%`;
$("inspect-size").textContent = `${size}%`;
$("speed-fill").style.width = `${speed}%`;
$("color-fill").style.width = `${color}%`;
$("size-fill").style.width = `${size}%`;
}
// ---------------------------------------------------------------------
// Direct camera controls — no Three.js addons
// ---------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 0.3, 0);
let cameraYaw = 0.58;
let cameraPitch = 0.96;
let cameraDistance = 13.6;
let pointerDown = false;
let pointerMode = "rotate";
let pointerX = 0;
let pointerY = 0;
let pointerMoved = 0;
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
renderer.domElement.addEventListener("pointerdown", (event) => {
pointerDown = true;
pointerMode = event.button === 2 || event.shiftKey ? "pan" : "rotate";
pointerX = event.clientX;
pointerY = event.clientY;
pointerMoved = 0;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointerDown) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
pointerMoved += Math.abs(dx) + Math.abs(dy);
if (pointerMode === "rotate") {
cameraYaw -= dx * 0.006;
cameraPitch = clamp(cameraPitch + dy * 0.0045, 0.42, 1.35);
} else {
const right = new THREE.Vector3(
Math.cos(cameraYaw),
0,
-Math.sin(cameraYaw)
);
const forward = new THREE.Vector3(
Math.sin(cameraYaw),
0,
Math.cos(cameraYaw)
);
const scale = cameraDistance * 0.0012;
cameraTarget.addScaledVector(right, -dx * scale);
cameraTarget.addScaledVector(forward, -dy * scale);
cameraTarget.x = clamp(cameraTarget.x, -4, 4);
cameraTarget.z = clamp(cameraTarget.z, -4, 4);
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
pointerDown = false;
if (pointerMoved < 6 && event.button === 0) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x =
((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y =
-((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const bodies = population
.filter((individual) => !individual.dying)
.map((individual) => individual.body);
const hits = raycaster.intersectObjects(bodies, false);
if (hits.length) {
inspectIndividual(hits[0].object.userData.individual);
}
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = false;
});
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraDistance = clamp(
cameraDistance + event.deltaY * 0.009,
7.5,
23
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
cameraYaw = 0.58;
cameraPitch = 0.96;
cameraDistance = 13.6;
cameraTarget.set(0, 0.3, 0);
});
function updateCamera() {
const horizontal = cameraDistance * Math.sin(cameraPitch);
camera.position.set(
cameraTarget.x + horizontal * Math.sin(cameraYaw),
cameraTarget.y + cameraDistance * Math.cos(cameraPitch),
cameraTarget.z + horizontal * Math.cos(cameraYaw)
);
camera.lookAt(cameraTarget);
}
// ---------------------------------------------------------------------
// Animation
// ---------------------------------------------------------------------
const clock = new THREE.Clock();
function updateIndividuals(dt, elapsed) {
for (const individual of population) {
if (individual.dying) {
individual.deathProgress = Math.min(
1,
individual.deathProgress + dt * 1.25
);
const eased =
individual.deathProgress * individual.deathProgress;
individual.group.scale.setScalar(
Math.max(0.001, individual.baseScale * (1 - eased))
);
individual.group.position.y = 0.08 - eased * 0.8;
individual.bodyMaterial.opacity = 1 - individual.deathProgress;
individual.ring.visible = false;
continue;
}
if (individual.birthProgress < 1) {
individual.birthProgress = Math.min(
1,
individual.birthProgress + dt * 2.4
);
const t = individual.birthProgress;
const eased = t * t * (3 - 2 * t);
individual.group.scale.setScalar(
individual.baseScale * Math.max(0.001, eased)
);
}
const motion = 0.025 + individual.traits.speed * 0.075;
individual.phase += dt * (0.35 + individual.traits.speed * 0.8);
individual.group.position.x =
individual.home.x + Math.cos(individual.phase * 1.3) * motion;
individual.group.position.z =
individual.home.z + Math.sin(individual.phase) * motion;
individual.group.rotation.y =
Math.sin(individual.phase * 0.7) * 0.12;
individual.group.rotation.z =
Math.sin(individual.phase * 2.2) * 0.025;
if (individual.ring.visible) {
individual.ring.rotation.z = elapsed * 0.5;
individual.ring.material.opacity =
0.58 + Math.sin(elapsed * 3 + individual.id) * 0.2;
}
}
}
function updateEnvironment(dt, elapsed) {
groundMaterial.color.lerp(targetGroundColor, 0.035);
scene.fog.color.lerp(targetFogColor, 0.035);
scene.background.lerp(targetFogColor, 0.025);
moteMaterial.color.lerp(targetAccentColor, 0.045);
water.material.opacity = THREE.MathUtils.lerp(
water.material.opacity,
targetWaterOpacity,
0.04
);
rushMaterial.opacity = THREE.MathUtils.lerp(
rushMaterial.opacity,
targetRushOpacity,
0.05
);
rushGroup.rotation.y += dt * 0.22;
const positions = moteGeometry.attributes.position.array;
for (let i = 0; i < moteCount; i++) {
const offset = i * 3;
positions[offset + 1] =
moteBase[offset + 1] +
Math.sin(elapsed * 0.45 + i * 0.61) * 0.12;
positions[offset] =
moteBase[offset] + Math.sin(elapsed * 0.18 + i) * 0.08;
}
moteGeometry.attributes.position.needsUpdate = true;
}
function animate() {
const dt = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
updateCamera();
updateIndividuals(dt, elapsed);
updateBursts(dt);
updateEnvironment(dt, elapsed);
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
// ---------------------------------------------------------------------
// Resize and controls
// ---------------------------------------------------------------------
function resize() {
const rect = $("scene").getBoundingClientRect();
camera.aspect = rect.width / Math.max(rect.height, 1);
camera.updateProjectionMatrix();
renderer.setSize(rect.width, rect.height, false);
}
new ResizeObserver(resize).observe($("scene"));
resize();
[
"mutation-chance",
"mutation-spread",
"selection-pressure",
"minimum-survivors"
].forEach((id) => {
$(id).addEventListener("input", updateOutputs);
});
$("run-button").addEventListener("click", runGeneration);
$("reset-button").addEventListener("click", () => {
if (busy) return;
configureRandomStreams();
seedPopulation();
lastMutationCount = 0;
lastSurvivorCount = null;
currentEnvironment = null;
$("environment-card").classList.add("sealed");
$("environment-card").classList.remove("revealed");
$("environment-name").textContent = "SEALED";
$("environment-detail").textContent =
"Its favored traits will be hidden until random variation is complete.";
$("inspector-title").textContent = "Click a creature";
["inspect-speed", "inspect-color", "inspect-size"].forEach((id) => {
$(id).textContent = "—";
});
["speed-fill", "color-fill", "size-fill"].forEach((id) => {
$(id).style.width = "0%";
});
setPhase("idle");
$("phase-message").textContent =
"Reset complete. The environment, mutation, survival, and population random streams were reseeded.";
log("Experiment reset with independent random streams.", "Reset.");
});
$("population-size").addEventListener("change", () => {
if (!busy) seedPopulation();
});
$("seed").addEventListener("change", () => {
if (busy) return;
configureRandomStreams();
seedPopulation();
log("Random streams reseeded. Mutation and environment remain separate.", "Seed changed.");
});
updateOutputs();
configureRandomStreams();
seedPopulation();
log(
"Mutation and environment use separate random streams. The next environment is hidden during variation.",
"Experiment ready."
);
log(
"Use the environment schedule for a fixed challenge, or leave it as a surprise draw to conceal the favored traits."
);
animate();
</script>
</body>
</html>
```