Prompt specification
Build or customize the Three.js 3D scene "Fictional population variation garden" 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: Fictional population variation garden
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/fictional-population-variation-garden-x0935
Scene Description Prompt:
Fictional population variation garden. Compose a population containing several pre-existing trait variants before an environmental change; show selection acting afterward without generating helpful mutations on demand. Please build this with Three.js from cdnjs in one self-contained HTML file, using visible voxel blocks.
Working Three.js Starter (fictional-population-variation-garden-x0935):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Variant Garden — Selection After an Environmental Change</title>
<style>
:root {
--ink: #20352d;
--muted: #64766f;
--panel: rgba(250, 252, 246, 0.88);
--line: rgba(41, 66, 56, 0.13);
--sun: #91cf4e;
--violet: #aa67b5;
--silver: #72a9a1;
--dry: #d8873d;
--wet: #4d9f9b;
--shadow: 0 18px 55px rgba(38, 57, 48, 0.15);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dce8df;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
select {
font: inherit;
}
button {
cursor: pointer;
}
button:focus-visible,
summary:focus-visible {
outline: 3px solid rgba(77, 159, 155, 0.35);
outline-offset: 2px;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas:active {
cursor: grabbing;
}
#ui {
position: fixed;
inset: 0;
pointer-events: none;
}
.panel {
pointer-events: auto;
border: 1px solid rgba(255, 255, 255, 0.72);
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(18px) saturate(1.15);
-webkit-backdrop-filter: blur(18px) saturate(1.15);
}
.intro {
position: absolute;
top: 22px;
left: 22px;
width: 370px;
padding: 22px;
border-radius: 24px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
color: #55736a;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.eyebrow-dot {
width: 8px;
height: 8px;
border-radius: 2px;
background: var(--sun);
box-shadow: 0 0 0 4px rgba(145, 207, 78, 0.16);
}
h1 {
margin: 13px 0 8px;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(34px, 3.4vw, 50px);
font-weight: 500;
line-height: 0.98;
letter-spacing: -0.045em;
}
.intro > p {
margin: 0;
max-width: 320px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.steps {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-top: 19px;
}
.step {
min-width: 0;
padding: 10px 8px 9px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255, 255, 255, 0.38);
color: #819089;
transition: 220ms ease;
}
.step b {
display: block;
margin-bottom: 5px;
font-size: 11px;
}
.step span {
display: block;
overflow: hidden;
font-size: 10px;
font-weight: 700;
line-height: 1.2;
text-overflow: ellipsis;
}
.step.active {
border-color: rgba(77, 159, 155, 0.45);
background: rgba(77, 159, 155, 0.1);
color: var(--ink);
}
.step.done {
border-color: rgba(145, 207, 78, 0.45);
background: rgba(145, 207, 78, 0.1);
color: #4f6d39;
}
.stats {
position: absolute;
top: 22px;
right: 22px;
width: 236px;
padding: 17px;
border-radius: 22px;
}
.status-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 14px;
}
.status {
display: inline-flex;
align-items: center;
gap: 7px;
color: #426e67;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.status::before {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--wet);
box-shadow: 0 0 0 4px rgba(77, 159, 155, 0.13);
content: "";
}
.status.dry::before {
background: var(--dry);
box-shadow: 0 0 0 4px rgba(216, 135, 61, 0.14);
}
.mutation-badge {
padding: 5px 8px;
border-radius: 999px;
background: #e9eee8;
color: #637168;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.stat-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.stat {
padding: 11px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(255, 255, 255, 0.38);
}
.stat-label {
display: block;
margin-bottom: 4px;
color: #7a8b83;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.stat-value {
font-size: 23px;
font-weight: 760;
letter-spacing: -0.04em;
}
.stat-value small {
margin-left: 2px;
color: var(--muted);
font-size: 11px;
font-weight: 700;
letter-spacing: 0;
}
.legend {
position: absolute;
bottom: 22px;
left: 22px;
width: 330px;
padding: 18px;
border-radius: 22px;
}
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
font-size: 11px;
font-weight: 850;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.panel-title span:last-child {
color: #829089;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: none;
}
.variant {
padding: 10px 0;
border-top: 1px solid var(--line);
}
.variant:first-of-type {
border-top: 0;
}
.variant-head {
display: grid;
grid-template-columns: 12px 1fr auto;
align-items: center;
gap: 9px;
}
.swatch {
width: 10px;
height: 10px;
border-radius: 3px;
background: var(--variant-color);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--variant-color) 18%, transparent);
}
.variant-name {
font-size: 12px;
font-weight: 800;
}
.variant-count {
font-size: 12px;
font-weight: 800;
}
.variant-count small {
margin-left: 3px;
color: #809087;
font-size: 9px;
font-weight: 700;
}
.variant-track {
height: 4px;
margin: 8px 0 6px 21px;
overflow: hidden;
border-radius: 999px;
background: rgba(47, 72, 62, 0.09);
}
.variant-fill {
width: 0;
height: 100%;
border-radius: inherit;
background: var(--variant-color);
transition: width 500ms cubic-bezier(0.2, 0.75, 0.3, 1);
}
.variant-detail {
display: flex;
justify-content: space-between;
gap: 10px;
margin-left: 21px;
color: #75857d;
font-size: 9px;
line-height: 1.35;
}
.variant-detail b {
color: #50675e;
font-weight: 750;
}
.method {
margin-top: 9px;
border-top: 1px solid var(--line);
padding-top: 10px;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.method summary {
cursor: pointer;
color: #4e685e;
font-weight: 800;
}
.method p {
margin: 8px 0 0;
}
.chart-card {
position: absolute;
right: 22px;
bottom: 22px;
width: 350px;
padding: 17px 17px 12px;
border-radius: 22px;
}
#chart {
display: block;
width: 100%;
height: 150px;
}
.chart-note {
margin-top: 4px;
color: #819087;
font-size: 9px;
line-height: 1.4;
}
.controls {
position: absolute;
bottom: 22px;
left: 50%;
width: min(510px, calc(100vw - 44px));
padding: 12px;
border-radius: 22px;
transform: translateX(-50%);
}
.event-line {
display: flex;
align-items: flex-start;
gap: 9px;
min-height: 34px;
padding: 3px 5px 11px;
color: #50675e;
font-size: 11px;
line-height: 1.42;
}
.event-line::before {
flex: 0 0 auto;
width: 8px;
height: 8px;
margin-top: 4px;
border-radius: 2px;
background: var(--sun);
content: "";
}
.button-row {
display: flex;
gap: 8px;
}
.button {
min-height: 42px;
padding: 0 15px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.68);
color: var(--ink);
font-size: 11px;
font-weight: 800;
transition:
transform 140ms ease,
background 140ms ease,
opacity 140ms ease;
}
.button:hover:not(:disabled) {
transform: translateY(-1px);
background: #fff;
}
.button:active:not(:disabled) {
transform: translateY(0);
}
.button:disabled {
cursor: default;
opacity: 0.45;
}
.button.primary {
flex: 1;
background: #294c40;
color: #f5faf4;
border-color: #294c40;
}
.button.primary:hover:not(:disabled) {
background: #365f50;
}
.speed {
display: flex;
align-items: center;
gap: 3px;
margin-left: auto;
padding: 3px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.42);
}
.speed button {
min-width: 35px;
height: 34px;
padding: 0 7px;
border: 0;
border-radius: 8px;
background: transparent;
color: #718179;
font-size: 10px;
font-weight: 800;
}
.speed button.active {
background: #fff;
color: var(--ink);
box-shadow: 0 2px 8px rgba(35, 53, 45, 0.1);
}
.camera-help {
position: absolute;
top: 24px;
left: 50%;
padding: 8px 12px;
border: 1px solid rgba(255, 255, 255, 0.55);
border-radius: 999px;
background: rgba(250, 252, 246, 0.54);
color: #5e746a;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.04em;
transform: translateX(-50%);
backdrop-filter: blur(10px);
}
@media (max-width: 1180px) {
.chart-card {
display: none;
}
.controls {
left: auto;
right: 22px;
width: 460px;
transform: none;
}
}
@media (max-width: 820px) {
.intro {
top: 12px;
left: 12px;
width: min(350px, calc(100vw - 24px));
padding: 17px;
}
.intro > p,
.steps {
display: none;
}
h1 {
margin-bottom: 0;
font-size: 34px;
}
.stats {
top: 101px;
right: 12px;
width: 180px;
padding: 12px;
}
.stat {
padding: 8px;
}
.stat-value {
font-size: 18px;
}
.legend {
bottom: 105px;
left: 12px;
width: 240px;
padding: 13px;
}
.variant-detail,
.method {
display: none;
}
.controls {
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
}
.camera-help {
display: none;
}
}
@media (max-width: 520px) {
.stats {
display: none;
}
.legend {
width: 210px;
}
.button-row {
flex-wrap: wrap;
}
.button {
padding: 0 10px;
}
.speed {
order: 3;
width: 100%;
justify-content: center;
}
.event-line {
font-size: 10px;
}
}
</style>
</head>
<body>
<div id="scene" aria-label="Interactive three-dimensional voxel garden"></div>
<div id="ui">
<header class="intro panel">
<div class="eyebrow">
<span class="eyebrow-dot"></span>
Population ecology / experiment 01
</div>
<h1>Variant Garden</h1>
<p>
A population assembled from traits that already exist. Then the
climate changes, revealing which inherited traits survive.
</p>
<div class="steps">
<div class="step active" id="step1">
<b>01</b>
<span>Standing variation</span>
</div>
<div class="step" id="step2">
<b>02</b>
<span>New environment</span>
</div>
<div class="step" id="step3">
<b>03</b>
<span>Selection</span>
</div>
</div>
</header>
<aside class="stats panel">
<div class="status-row">
<div class="status" id="environmentStatus">Moist habitat</div>
<div class="mutation-badge">Mutations off</div>
</div>
<div class="stat-grid">
<div class="stat">
<span class="stat-label">Population</span>
<span class="stat-value" id="populationStat">100</span>
</div>
<div class="stat">
<span class="stat-label">Generation</span>
<span class="stat-value" id="generationStat">0</span>
</div>
<div class="stat">
<span class="stat-label">Soil moisture</span>
<span class="stat-value" id="moistureStat">78<small>%</small></span>
</div>
<div class="stat">
<span class="stat-label">New variants</span>
<span class="stat-value" id="mutationStat">0</span>
</div>
</div>
</aside>
<div class="camera-help">Drag to orbit · Scroll to zoom · Double-click to reset view</div>
<aside class="legend panel">
<div class="panel-title">
<span>Pre-existing variants</span>
<span>count · population share</span>
</div>
<div
class="variant"
data-variant="sunleaf"
style="--variant-color: var(--sun)"
>
<div class="variant-head">
<span class="swatch"></span>
<span class="variant-name">Sunleaf</span>
<span class="variant-count">
<span id="count-sunleaf">42</span>
<small id="percent-sunleaf">42%</small>
</span>
</div>
<div class="variant-track">
<div class="variant-fill" id="fill-sunleaf"></div>
</div>
<div class="variant-detail">
<span><b>Trait:</b> broad, fast-growing leaves</span>
<span id="fitness-sunleaf">wet 88% · dry 20%</span>
</div>
</div>
<div
class="variant"
data-variant="violetbell"
style="--variant-color: var(--violet)"
>
<div class="variant-head">
<span class="swatch"></span>
<span class="variant-name">Violetbell</span>
<span class="variant-count">
<span id="count-violetbell">32</span>
<small id="percent-violetbell">32%</small>
</span>
</div>
<div class="variant-track">
<div class="variant-fill" id="fill-violetbell"></div>
</div>
<div class="variant-detail">
<span><b>Trait:</b> flexible leaves, moderate tolerance</span>
<span id="fitness-violetbell">wet 70% · dry 56%</span>
</div>
</div>
<div
class="variant"
data-variant="silverbud"
style="--variant-color: var(--silver)"
>
<div class="variant-head">
<span class="swatch"></span>
<span class="variant-name">Silverbud</span>
<span class="variant-count">
<span id="count-silverbud">26</span>
<small id="percent-silverbud">26%</small>
</span>
</div>
<div class="variant-track">
<div class="variant-fill" id="fill-silverbud"></div>
</div>
<div class="variant-detail">
<span><b>Trait:</b> waxy leaves, deep roots</span>
<span id="fitness-silverbud">wet 45% · dry 94%</span>
</div>
</div>
<details class="method">
<summary>How selection is modeled</summary>
<p>
Each variant has a fixed survival fitness. In drought, survival is
applied first. Reproduction then fills a smaller drought carrying
capacity using surviving variants as parents. Offspring inherit an
existing parent trait. There is no mutation step, so drought cannot
summon a new “helpful” variant.
</p>
</details>
</aside>
<aside class="chart-card panel">
<div class="panel-title">
<span>Population history</span>
<span>absolute counts</span>
</div>
<canvas id="chart" aria-label="Population counts across generations"></canvas>
<div class="chart-note">
Sunleaf · Violetbell · Silverbud. The chart records standing variation
at baseline and each post-change generation.
</div>
</aside>
<section class="controls panel">
<div class="event-line" id="eventText" aria-live="polite">
100 individuals were assembled from three variants that existed before
the environmental change.
</div>
<div class="button-row">
<button class="button primary" id="primaryButton">Introduce drought</button>
<button class="button" id="stepButton" disabled>Step one generation</button>
<button class="button" id="resetButton">Reset</button>
<div class="speed" aria-label="Animation speed">
<button data-speed="0.75">0.75×</button>
<button class="active" data-speed="1">1×</button>
<button data-speed="1.5">1.5×</button>
</div>
</div>
</section>
</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 host = $("scene");
// -------------------------------------------------------------------------
// Deterministic helpers
// -------------------------------------------------------------------------
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 shuffled(array, random) {
const result = [...array];
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}
const random = mulberry32(20250308);
// -------------------------------------------------------------------------
// Model state
// -------------------------------------------------------------------------
const VARIANTS = {
sunleaf: {
name: "Sunleaf",
color: "#91cf4e",
wetFitness: 0.88,
dryFitness: 0.20,
parts: [
{ color: "#3f7543", pos: [0, 0.14, 0], size: [0.17, 0.28, 0.17] },
{ color: "#4e9149", pos: [0, 0.40, 0], size: [0.17, 0.28, 0.17] },
{ color: "#83c94b", pos: [-0.17, 0.43, 0], size: [0.42, 0.15, 0.23] },
{ color: "#a9df5e", pos: [0.17, 0.59, 0], size: [0.42, 0.15, 0.23] },
{ color: "#77bd44", pos: [0, 0.66, 0], size: [0.35, 0.15, 0.22] },
{ color: "#f2d35f", pos: [0, 0.83, 0], size: [0.20, 0.14, 0.20] }
]
},
violetbell: {
name: "Violetbell",
color: "#aa67b5",
wetFitness: 0.70,
dryFitness: 0.56,
parts: [
{ color: "#47734e", pos: [0, 0.13, 0], size: [0.15, 0.26, 0.15] },
{ color: "#568a55", pos: [0, 0.37, 0], size: [0.15, 0.24, 0.15] },
{ color: "#5f9a5a", pos: [-0.16, 0.29, 0], size: [0.32, 0.12, 0.19] },
{ color: "#6ca45f", pos: [0.16, 0.43, 0], size: [0.32, 0.12, 0.19] },
{ color: "#9e5aaa", pos: [0, 0.58, 0], size: [0.31, 0.22, 0.27] },
{ color: "#ba79c2", pos: [-0.13, 0.69, 0], size: [0.18, 0.16, 0.18] },
{ color: "#c991ce", pos: [0.13, 0.68, 0], size: [0.18, 0.16, 0.18] }
]
},
silverbud: {
name: "Silverbud",
color: "#72a9a1",
wetFitness: 0.45,
dryFitness: 0.94,
parts: [
{ color: "#496f64", pos: [0, 0.09, 0], size: [0.20, 0.18, 0.20] },
{ color: "#78aaa0", pos: [0, 0.25, 0], size: [0.36, 0.22, 0.31] },
{ color: "#8bb8ac", pos: [-0.19, 0.29, 0], size: [0.28, 0.14, 0.24] },
{ color: "#9ac5b6", pos: [0.19, 0.34, 0], size: [0.28, 0.14, 0.24] },
{ color: "#b3cec0", pos: [0, 0.44, 0], size: [0.20, 0.13, 0.20] },
{ color: "#e2d8ae", pos: [0, 0.56, 0], size: [0.17, 0.12, 0.17] }
]
}
};
const INITIAL_COUNTS = {
sunleaf: 42,
violetbell: 32,
silverbud: 26
};
const state = {
environment: "wet",
envBlend: 0,
envTarget: 0,
counts: { ...INITIAL_COUNTS },
generation: 0,
running: false,
complete: false,
autoTimer: 0,
speed: 1,
maxGeneration: 4,
history: [{ counts: { ...INITIAL_COUNTS } }]
};
// -------------------------------------------------------------------------
// Renderer, scene, and camera
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(host.clientWidth, host.clientHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.domElement.setAttribute(
"aria-label",
"Voxel garden showing three pre-existing plant variants under selection"
);
host.appendChild(renderer.domElement);
const scene = new THREE.Scene();
const wetBackground = new THREE.Color("#c5deda");
const dryBackground = new THREE.Color("#e7c79f");
scene.background = wetBackground.clone();
scene.fog = new THREE.Fog(wetBackground.clone(), 23, 48);
const camera = new THREE.PerspectiveCamera(
42,
host.clientWidth / host.clientHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0, 0.75, 0);
let cameraTheta = 0.69;
let cameraPhi = 1.02;
let cameraRadius = 18.5;
function updateCamera() {
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x + cameraRadius * sinPhi * Math.sin(cameraTheta),
cameraTarget.y + cameraRadius * Math.cos(cameraPhi),
cameraTarget.z + cameraRadius * sinPhi * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
}
updateCamera();
// Camera controls implemented locally; no examples/addons are imported.
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
cameraTheta -= dx * 0.006;
cameraPhi = THREE.MathUtils.clamp(cameraPhi - dy * 0.005, 0.48, 1.42);
updateCamera();
});
function endDrag(event) {
dragging = false;
if (event.pointerId !== undefined) {
try {
renderer.domElement.releasePointerCapture(event.pointerId);
} catch (_) {}
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
11,
27
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
cameraTheta = 0.69;
cameraPhi = 1.02;
cameraRadius = 18.5;
updateCamera();
});
// -------------------------------------------------------------------------
// Lighting
// -------------------------------------------------------------------------
const hemisphere = new THREE.HemisphereLight(
0xd8f1ed,
0x69503b,
2.0
);
scene.add(hemisphere);
const sunlight = new THREE.DirectionalLight(0xfff0cb, 3.2);
sunlight.position.set(-6, 11, 5);
sunlight.castShadow = true;
sunlight.shadow.mapSize.set(2048, 2048);
sunlight.shadow.camera.left = -9;
sunlight.shadow.camera.right = 9;
sunlight.shadow.camera.top = 9;
sunlight.shadow.camera.bottom = -9;
sunlight.shadow.camera.near = 1;
sunlight.shadow.camera.far = 32;
sunlight.shadow.bias = -0.0005;
scene.add(sunlight);
const fillLight = new THREE.DirectionalLight(0xb5d9d4, 1.1);
fillLight.position.set(8, 5, -7);
scene.add(fillLight);
// -------------------------------------------------------------------------
// Voxel terrain
// -------------------------------------------------------------------------
const GRID = 12;
const SPACING = 1.04;
const TILE_SIZE = 0.96;
const dummy = new THREE.Object3D();
const tempColor = new THREE.Color();
const slots = [];
for (let z = 0; z < GRID; z++) {
for (let x = 0; x < GRID; x++) {
slots.push({
x: (x - (GRID - 1) / 2) * SPACING,
z: (z - (GRID - 1) / 2) * SPACING,
top: 0.17 + random() * 0.17,
rotation: Math.floor(random() * 4) * (Math.PI / 2)
});
}
}
const soilMaterial = new THREE.MeshStandardMaterial({
roughness: 1,
metalness: 0,
vertexColors: true
});
const soil = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
soilMaterial,
slots.length
);
soil.receiveShadow = true;
soil.castShadow = true;
soil.frustumCulled = false;
scene.add(soil);
const tileWetColors = [];
const tileDryColors = [];
slots.forEach((slot, index) => {
const bottom = -0.68;
const height = slot.top - bottom;
dummy.position.set(slot.x, (slot.top + bottom) / 2, slot.z);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(TILE_SIZE, height, TILE_SIZE);
dummy.updateMatrix();
soil.setMatrixAt(index, dummy.matrix);
const wet = new THREE.Color("#57483b");
wet.offsetHSL((random() - 0.5) * 0.025, 0, (random() - 0.5) * 0.045);
const dry = new THREE.Color("#986b4d");
dry.offsetHSL((random() - 0.5) * 0.025, 0, (random() - 0.5) * 0.045);
tileWetColors.push(wet);
tileDryColors.push(dry);
soil.setColorAt(index, wet);
});
soil.instanceMatrix.needsUpdate = true;
soil.instanceColor.needsUpdate = true;
// Small voxel moss caps.
const mossIndices = shuffled(
Array.from({ length: slots.length }, (_, index) => index),
random
).slice(0, 54);
const mossMaterial = new THREE.MeshStandardMaterial({
roughness: 1,
vertexColors: true
});
const moss = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
mossMaterial,
mossIndices.length
);
moss.castShadow = true;
moss.receiveShadow = true;
moss.frustumCulled = false;
scene.add(moss);
const mossData = mossIndices.map((slotIndex, index) => {
const slot = slots[slotIndex];
const data = {
x: slot.x + (random() - 0.5) * 0.44,
z: slot.z + (random() - 0.5) * 0.44,
y: slot.top + 0.065,
width: 0.08 + random() * 0.11,
height: 0.07 + random() * 0.09,
depth: 0.08 + random() * 0.11,
rotation: Math.floor(random() * 4) * (Math.PI / 2),
wet: new THREE.Color(random() > 0.5 ? "#73945c" : "#5c8355"),
dry: new THREE.Color("#9b7955")
};
tempColor.copy(data.wet);
moss.setColorAt(index, tempColor);
return data;
});
moss.instanceColor.needsUpdate = true;
// Puddles shrink away during drought.
const puddleIndices = shuffled(
Array.from({ length: slots.length }, (_, index) => index),
random
).slice(0, 15);
const puddleMaterial = new THREE.MeshStandardMaterial({
color: "#69aeb3",
roughness: 0.22,
metalness: 0,
transparent: true,
opacity: 0.72,
depthWrite: false
});
const puddles = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
puddleMaterial,
puddleIndices.length
);
puddles.frustumCulled = false;
scene.add(puddles);
const puddleData = puddleIndices.map((slotIndex) => {
const slot = slots[slotIndex];
return {
x: slot.x + (random() - 0.5) * 0.25,
z: slot.z + (random() - 0.5) * 0.25,
y: slot.top + 0.035,
width: 0.27 + random() * 0.17,
depth: 0.22 + random() * 0.15
};
});
// Voxel cracks emerge as the soil dries.
const crackIndices = shuffled(
Array.from({ length: slots.length }, (_, index) => index),
random
).slice(0, 31);
const crackData = [];
for (const slotIndex of crackIndices) {
const slot = slots[slotIndex];
crackData.push({
x: slot.x,
z: slot.z,
y: slot.top + 0.025,
angle: Math.floor(random() * 4) * (Math.PI / 2),
length: 0.28 + random() * 0.25,
offset: (random() - 0.5) * 0.18
});
}
const crackMaterial = new THREE.MeshStandardMaterial({
color: "#49362d",
roughness: 1
});
const cracks = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
crackMaterial,
crackData.length
);
cracks.frustumCulled = false;
scene.add(cracks);
// -------------------------------------------------------------------------
// Voxel plants
// -------------------------------------------------------------------------
const plantMeshes = {};
for (const [key, variant] of Object.entries(VARIANTS)) {
plantMeshes[key] = variant.parts.map((part) => {
const material = new THREE.MeshStandardMaterial({
color: part.color,
roughness: 0.88,
metalness: 0
});
const mesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
material,
slots.length
);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.frustumCulled = false;
scene.add(mesh);
return mesh;
});
}
const agents = slots.map((slot, index) => ({
slotIndex: index,
variant: null,
target: 0,
scale: 0
}));
function assignInitialPopulation() {
agents.forEach((agent) => {
agent.variant = null;
agent.target = 0;
agent.scale = 0;
});
const sequence = [];
for (const [key, count] of Object.entries(INITIAL_COUNTS)) {
for (let i = 0; i < count; i++) sequence.push(key);
}
const shuffledTraits = shuffled(sequence, random);
const slotOrder = shuffled(
agents.map((agent) => agent.slotIndex),
random
);
for (let i = 0; i < shuffledTraits.length; i++) {
const agent = agents[slotOrder[i]];
agent.variant = shuffledTraits[i];
agent.target = 1;
}
}
assignInitialPopulation();
function updatePlantMatrices() {
for (const [key, variant] of Object.entries(VARIANTS)) {
const meshes = plantMeshes[key];
variant.parts.forEach((part, partIndex) => {
const mesh = meshes[partIndex];
agents.forEach((agent, agentIndex) => {
if (agent.variant !== key || agent.scale < 0.0001) {
dummy.position.set(0, -100, 0);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(0, 0, 0);
} else {
const slot = slots[agent.slotIndex];
const scale = agent.scale;
const angle = slot.rotation;
const cosine = Math.cos(angle);
const sine = Math.sin(angle);
const rotatedX = part.pos[0] * cosine + part.pos[2] * sine;
const rotatedZ = -part.pos[0] * sine + part.pos[2] * cosine;
dummy.position.set(
slot.x + rotatedX * scale,
slot.top + part.pos[1] * scale,
slot.z + rotatedZ * scale
);
dummy.rotation.set(0, angle, 0);
dummy.scale.set(
part.size[0] * scale,
part.size[1] * scale,
part.size[2] * scale
);
}
dummy.updateMatrix();
mesh.setMatrixAt(agentIndex, dummy.matrix);
});
mesh.instanceMatrix.needsUpdate = true;
});
}
}
// -------------------------------------------------------------------------
// Voxel weather: clouds, sun, and square rain drops
// -------------------------------------------------------------------------
const cloudMaterial = new THREE.MeshLambertMaterial({
color: "#f5f4e9",
transparent: true,
opacity: 0.92,
depthWrite: false
});
const clouds = [];
const cloudConfigs = [
{ x: -6.5, y: 6.2, z: -6.4, scale: 0.95 },
{ x: 1.4, y: 7.1, z: -8.1, scale: 1.2 },
{ x: 7.5, y: 5.8, z: -5.4, scale: 0.8 },
{ x: -1.5, y: 8.1, z: -9.8, scale: 1.0 }
];
for (const config of cloudConfigs) {
const group = new THREE.Group();
const blocks = [
[-0.65, 0, 0, 0.72, 0.42, 0.56],
[0, 0.08, 0, 0.92, 0.60, 0.68],
[0.72, 0, 0, 0.72, 0.40, 0.52],
[-0.05, 0.38, 0, 0.58, 0.38, 0.54],
[0.43, 0.34, 0, 0.45, 0.32, 0.46]
];
for (const block of blocks) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(block[3], block[4], block[5]),
cloudMaterial
);
mesh.position.set(block[0], block[1], block[2]);
group.add(mesh);
}
group.position.set(config.x, config.y, config.z);
group.scale.setScalar(config.scale);
group.userData.baseX = config.x;
scene.add(group);
clouds.push(group);
}
const sunGroup = new THREE.Group();
const sunMaterial = new THREE.MeshStandardMaterial({
color: "#ffd25b",
emissive: "#f5a623",
emissiveIntensity: 0.8,
roughness: 0.8
});
const sunCore = new THREE.Mesh(
new THREE.BoxGeometry(0.78, 0.78, 0.78),
sunMaterial
);
sunGroup.add(sunCore);
for (const offset of [
[-0.55, 0, 0],
[0.55, 0, 0],
[0, 0.55, 0],
[0, -0.55, 0]
]) {
const block = new THREE.Mesh(
new THREE.BoxGeometry(0.25, 0.25, 0.25),
sunMaterial
);
block.position.set(...offset);
sunGroup.add(block);
}
sunGroup.position.set(-5.7, 7.4, -6.2);
scene.add(sunGroup);
const RAIN_COUNT = 44;
const rainMaterial = new THREE.MeshBasicMaterial({
color: "#80c2cc",
transparent: true,
opacity: 0.55,
depthWrite: false
});
const rain = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.045, 0.19, 0.045),
rainMaterial,
RAIN_COUNT
);
rain.frustumCulled = false;
scene.add(rain);
const rainDrops = Array.from({ length: RAIN_COUNT }, () => ({
x: (random() - 0.5) * 14,
z: (random() - 0.5) * 14,
offset: random() * 12,
speed: 5 + random() * 5
}));
// -------------------------------------------------------------------------
// Population transition
// -------------------------------------------------------------------------
function applyPopulationCounts(newCounts) {
// First retire surplus individuals, while retaining their inherited type
// until their voxel plants have finished shrinking.
for (const key of Object.keys(VARIANTS)) {
const active = agents.filter(
(agent) => agent.variant === key && agent.target === 1
);
active.slice(newCounts[key]).forEach((agent) => {
agent.target = 0;
});
}
// Reproduction only copies one of the pre-existing variant keys.
// No key can be introduced here.
const claimed = new Set();
for (const [key, requiredCount] of Object.entries(newCounts)) {
let activeCount = agents.filter(
(agent) =>
agent.variant === key &&
agent.target === 1 &&
!claimed.has(agent)
).length;
let needed = Math.max(0, requiredCount - activeCount);
if (!needed) continue;
const candidates = agents
.filter(
(agent) =>
agent.target === 0 &&
!claimed.has(agent) &&
agent.scale < 0.08
)
.sort((a, b) => {
const aNull = a.variant === null ? 0 : 1;
const bNull = b.variant === null ? 0 : 1;
return aNull - bNull || a.scale - b.scale;
});
for (const agent of candidates) {
if (!needed) break;
agent.variant = key;
agent.target = 1;
claimed.add(agent);
needed--;
}
// This fallback is only reached in unusually rapid manual steps.
if (needed > 0) {
const fallback = agents
.filter((agent) => agent.target === 0 && !claimed.has(agent))
.sort((a, b) => a.scale - b.scale);
for (const agent of fallback) {
if (!needed) break;
agent.variant = key;
agent.target = 1;
claimed.add(agent);
needed--;
}
}
}
state.counts = { ...newCounts };
}
function runGeneration() {
if (state.environment !== "dry" || state.complete) return;
const previous = { ...state.counts };
const survivors = {};
const reproductiveWeights = {};
for (const [key, variant] of Object.entries(VARIANTS)) {
survivors[key] = Math.round(previous[key] * variant.dryFitness);
reproductiveWeights[key] =
survivors[key] * variant.dryFitness;
}
const totalWeight = Object.values(reproductiveWeights).reduce(
(sum, value) => sum + value,
0
);
const droughtCapacity = 80;
const nextCounts = {};
const fractions = {};
if (totalWeight <= 0) {
for (const key of Object.keys(VARIANTS)) nextCounts[key] = 0;
} else {
for (const key of Object.keys(VARIANTS)) {
const raw = (droughtCapacity * reproductiveWeights[key]) / totalWeight;
nextCounts[key] = Math.floor(raw);
fractions[key] = raw - Math.floor(raw);
}
let assigned = Object.values(nextCounts).reduce(
(sum, value) => sum + value,
0
);
const remainderOrder = Object.keys(fractions).sort(
(a, b) => fractions[b] - fractions[a]
);
for (const key of remainderOrder) {
if (assigned >= droughtCapacity) break;
nextCounts[key]++;
assigned++;
}
}
applyPopulationCounts(nextCounts);
state.generation++;
state.history.push({ counts: { ...nextCounts } });
const changed = Object.keys(VARIANTS)
.filter((key) => previous[key] !== nextCounts[key])
.map((key) => `${VARIANTS[key].name} ${previous[key]}→${nextCounts[key]}`)
.join(", ");
$("eventText").textContent =
`Generation ${state.generation}: ${changed}. ` +
"Survival and reproduction reshaped the population; no new trait was created.";
if (state.generation >= state.maxGeneration) {
state.running = false;
state.complete = true;
$("eventText").textContent =
`Selection complete. ${VARIANTS.silverbud.name} now dominates while ` +
`all traits still descend from the original standing variation.`;
}
updateUI();
drawChart();
}
function applyDrought() {
if (state.environment === "dry") return;
state.environment = "dry";
state.envTarget = 1;
state.running = false;
state.complete = false;
$("eventText").textContent =
"Drought introduced. Soil moisture falls and carrying capacity drops. " +
"The three inherited traits now face different survival odds.";
updateUI();
}
function resetExperiment() {
state.environment = "wet";
state.envBlend = 0;
state.envTarget = 0;
state.counts = { ...INITIAL_COUNTS };
state.generation = 0;
state.running = false;
state.complete = false;
state.autoTimer = 0;
state.history = [{ counts: { ...INITIAL_COUNTS } }];
assignInitialPopulation();
$("eventText").textContent =
"100 individuals were assembled from three variants that existed before " +
"the environmental change.";
updateUI();
drawChart();
}
// -------------------------------------------------------------------------
// UI and chart
// -------------------------------------------------------------------------
function updateUI() {
const total = Object.values(state.counts).reduce(
(sum, value) => sum + value,
0
);
$("populationStat").textContent = total;
$("generationStat").textContent = state.generation;
$("mutationStat").textContent = "0";
if (state.environment === "wet") {
$("moistureStat").innerHTML = "78<small>%</small>";
$("environmentStatus").textContent = "Moist habitat";
$("environmentStatus").classList.remove("dry");
} else {
$("moistureStat").innerHTML = "18<small>%</small>";
$("environmentStatus").textContent = "Drought habitat";
$("environmentStatus").classList.add("dry");
}
for (const key of Object.keys(VARIANTS)) {
const count = state.counts[key];
const percent = total ? Math.round((count / total) * 100) : 0;
$(`count-${key}`).textContent = count;
$(`percent-${key}`).textContent = `${percent}%`;
$(`fill-${key}`).style.width = `${percent}%`;
}
const steps = [$("step1"), $("step2"), $("step3")];
steps.forEach((step) => step.classList.remove("active", "done"));
if (state.environment === "wet") {
steps[0].classList.add("active");
} else if (state.generation === 0) {
steps[0].classList.add("done");
steps[1].classList.add("active");
} else {
steps[0].classList.add("done");
steps[1].classList.add("done");
steps[2].classList.add(state.complete ? "done" : "active");
}
const primary = $("primaryButton");
primary.disabled = state.complete;
if (state.environment === "wet") {
primary.textContent = "Introduce drought";
} else if (state.complete) {
primary.textContent = "Selection complete";
} else if (state.running) {
primary.textContent = "Pause selection";
} else {
primary.textContent = "Run selection";
}
$("stepButton").disabled =
state.environment !== "dry" || state.running || state.complete;
}
function drawChart() {
const canvas = $("chart");
const rect = canvas.getBoundingClientRect();
if (!rect.width || !rect.height) return;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const pixelWidth = Math.round(rect.width * dpr);
const pixelHeight = Math.round(rect.height * dpr);
if (canvas.width !== pixelWidth || canvas.height !== pixelHeight) {
canvas.width = pixelWidth;
canvas.height = pixelHeight;
}
const ctx = canvas.getContext("2d");
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, rect.width, rect.height);
const left = 27;
const right = rect.width - 8;
const top = 10;
const bottom = rect.height - 24;
const plotWidth = right - left;
const plotHeight = bottom - top;
const maxValue = 100;
ctx.font = "9px system-ui, sans-serif";
ctx.textBaseline = "middle";
for (const value of [0, 25, 50, 75, 100]) {
const y = bottom - (value / maxValue) * plotHeight;
ctx.strokeStyle = "rgba(43, 67, 57, 0.09)";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(left, y);
ctx.lineTo(right, y);
ctx.stroke();
ctx.fillStyle = "rgba(72, 92, 82, 0.6)";
ctx.textAlign = "right";
ctx.fillText(String(value), left - 6, y);
}
const xFor = (index) => {
if (state.history.length === 1) return left + plotWidth * 0.25;
return left + (index / (state.history.length - 1)) * plotWidth;
};
for (const key of Object.keys(VARIANTS)) {
ctx.strokeStyle = VARIANTS[key].color;
ctx.lineWidth = 2.4;
ctx.lineJoin = "round";
ctx.lineCap = "round";
ctx.beginPath();
state.history.forEach((entry, index) => {
const x = xFor(index);
const y =
bottom - (entry.counts[key] / maxValue) * plotHeight;
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.stroke();
state.history.forEach((entry, index) => {
const x = xFor(index);
const y =
bottom - (entry.counts[key] / maxValue) * plotHeight;
ctx.fillStyle = "#fbfcf7";
ctx.strokeStyle = VARIANTS[key].color;
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(x, y, 3.2, 0, Math.PI * 2);
ctx.fill();
ctx.stroke();
});
}
ctx.fillStyle = "rgba(72, 92, 82, 0.7)";
ctx.textAlign = "left";
ctx.fillText("Baseline", left - 8, rect.height - 9);
if (state.history.length > 1) {
ctx.textAlign = "right";
ctx.fillText(
`Generation ${state.history.length - 1}`,
right,
rect.height - 9
);
}
}
$("primaryButton").addEventListener("click", () => {
if (state.environment === "wet") {
applyDrought();
} else if (state.complete) {
return;
} else if (state.running) {
state.running = false;
updateUI();
} else {
state.running = true;
state.autoTimer = 0;
updateUI();
}
});
$("stepButton").addEventListener("click", () => {
if (state.environment === "dry" && !state.running && !state.complete) {
runGeneration();
}
});
$("resetButton").addEventListener("click", resetExperiment);
document.querySelectorAll(".speed button").forEach((button) => {
button.addEventListener("click", () => {
state.speed = Number(button.dataset.speed);
document.querySelectorAll(".speed button").forEach((other) => {
other.classList.toggle("active", other === button);
});
});
});
if ("ResizeObserver" in window) {
new ResizeObserver(() => drawChart()).observe($("chart"));
}
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function updateEnvironment(delta, elapsed) {
const damping = 1 - Math.exp(-delta * 2.4);
state.envBlend += (state.envTarget - state.envBlend) * damping;
const blend = state.envBlend;
scene.background.copy(wetBackground).lerp(dryBackground, blend);
scene.fog.color.copy(scene.background);
hemisphere.color.set("#d8f1ed").lerp(new THREE.Color("#f1d6aa"), blend);
hemisphere.groundColor
.set("#69503b")
.lerp(new THREE.Color("#9b704c"), blend);
hemisphere.intensity = 2.0 - blend * 0.28;
sunlight.color
.set("#fff0cb")
.lerp(new THREE.Color("#ffd083"), blend);
sunlight.intensity = 3.2 + blend * 0.55;
fillLight.intensity = 1.1 - blend * 0.3;
for (let index = 0; index < slots.length; index++) {
tempColor.copy(tileWetColors[index]).lerp(tileDryColors[index], blend);
soil.setColorAt(index, tempColor);
}
soil.instanceColor.needsUpdate = true;
mossData.forEach((data, index) => {
const shrink = 1 - blend * 0.82;
dummy.position.set(data.x, data.y, data.z);
dummy.rotation.set(0, data.rotation, 0);
dummy.scale.set(
data.width,
data.height * shrink,
data.depth
);
dummy.updateMatrix();
moss.setMatrixAt(index, dummy.matrix);
tempColor.copy(data.wet).lerp(data.dry, blend);
moss.setColorAt(index, tempColor);
});
moss.instanceMatrix.needsUpdate = true;
moss.instanceColor.needsUpdate = true;
puddleData.forEach((data, index) => {
const shrink = Math.pow(1 - blend, 1.8);
dummy.position.set(data.x, data.y, data.z);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(
data.width * shrink,
0.025 * shrink,
data.depth * shrink
);
dummy.updateMatrix();
puddles.setMatrixAt(index, dummy.matrix);
});
puddles.instanceMatrix.needsUpdate = true;
crackData.forEach((data, index) => {
const cosine = Math.cos(data.angle);
const sine = Math.sin(data.angle);
const offsetX = data.offset * cosine;
const offsetZ = -data.offset * sine;
dummy.position.set(
data.x + offsetX,
data.y,
data.z + offsetZ
);
dummy.rotation.set(0, data.angle, 0);
dummy.scale.set(
data.length * blend,
0.025 * blend,
0.055 * blend
);
dummy.updateMatrix();
cracks.setMatrixAt(index, dummy.matrix);
});
cracks.instanceMatrix.needsUpdate = true;
cloudMaterial.opacity = 0.92 * (1 - blend);
clouds.forEach((cloud, index) => {
cloud.position.x =
cloud.userData.baseX +
elapsed * (0.055 + index * 0.007) +
blend * (16 + index * 3);
cloud.visible = blend < 0.995;
});
sunGroup.position.set(
-5.7 + blend * 1.2,
7.4 - blend * 1.1,
-6.2 + blend * 1.4
);
sunGroup.rotation.y = elapsed * 0.08;
sunGroup.scale.setScalar(1 + blend * 0.12);
rainMaterial.opacity = 0.55 * (1 - blend);
rain.visible = blend < 0.995;
rainDrops.forEach((drop, index) => {
const y =
7.5 -
((elapsed * drop.speed + drop.offset) % 12);
dummy.position.set(
drop.x + Math.sin(elapsed * 0.5 + drop.offset) * 0.08,
y,
drop.z
);
dummy.rotation.set(0, 0, 0);
dummy.scale.setScalar(Math.max(0.001, 1 - blend));
dummy.updateMatrix();
rain.setMatrixAt(index, dummy.matrix);
});
rain.instanceMatrix.needsUpdate = true;
}
function updateAgents(delta) {
const damping = 1 - Math.exp(-delta * 5.2);
for (const agent of agents) {
agent.scale += (agent.target - agent.scale) * damping;
if (agent.target === 0 && agent.scale < 0.003) {
agent.scale = 0;
agent.variant = null;
}
}
updatePlantMatrices();
}
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
if (state.running && state.environment === "dry") {
state.autoTimer -= delta * state.speed;
if (state.autoTimer <= 0) {
runGeneration();
state.autoTimer = 1.45;
}
}
updateEnvironment(delta, elapsed);
updateAgents(delta);
renderer.render(scene, camera);
}
function resize() {
const width = host.clientWidth;
const height = host.clientHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
drawChart();
}
window.addEventListener("resize", resize);
updateUI();
drawChart();
animate();
</script>
</body>
</html>
```