Prompt specification
Build or customize the Three.js 3D scene "Disturbance-reset community sandbox" 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: Disturbance-reset community sandbox
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/disturbance-reset-community-sandbox-x0732
Scene Description Prompt:
Create an HTML voxel vegetation sandbox using Three.js from cdnjs; clear one patch and compare recovery under explicit toy colonization and shade rules.
Working Three.js Starter (disturbance-reset-community-sandbox-x0732):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Canopy — Recovery Lab</title>
<style>
:root {
--bg: #edf1e8;
--panel: #f9fbf6;
--panel-strong: #ffffff;
--ink: #193128;
--muted: #65756d;
--line: #dce4d8;
--green: #287453;
--green-dark: #19533a;
--lime: #b9db69;
--amber: #d99c47;
--blue: #4e8fb7;
--shadow: 0 18px 45px rgba(40, 68, 49, 0.09);
--radius: 18px;
}
* {
box-sizing: border-box;
}
html {
color-scheme: light;
}
body {
margin: 0;
min-height: 100vh;
color: var(--ink);
background:
radial-gradient(circle at 12% 5%, rgba(185, 219, 105, 0.2), transparent 24rem),
var(--bg);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
border: 0;
}
.app {
width: min(1540px, calc(100% - 32px));
margin: 0 auto;
padding: 24px 0 34px;
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
margin-bottom: 20px;
}
.brand {
display: flex;
align-items: center;
gap: 14px;
min-width: 0;
}
.brand-mark {
position: relative;
width: 48px;
height: 48px;
flex: 0 0 auto;
}
.brand-mark span {
position: absolute;
display: block;
border-radius: 4px;
box-shadow: 0 4px 10px rgba(28, 73, 51, 0.12);
}
.brand-mark span:nth-child(1) {
width: 25px;
height: 25px;
left: 1px;
top: 17px;
background: #739e51;
}
.brand-mark span:nth-child(2) {
width: 25px;
height: 25px;
right: 1px;
top: 17px;
background: #3f7d50;
}
.brand-mark span:nth-child(3) {
width: 25px;
height: 25px;
left: 11px;
top: 3px;
background: var(--lime);
}
.eyebrow {
margin: 0 0 3px;
color: var(--green);
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(1.45rem, 2.4vw, 2.1rem);
line-height: 1.08;
letter-spacing: -0.035em;
}
.subtitle {
margin: 5px 0 0;
color: var(--muted);
font-size: 0.9rem;
}
.top-actions,
.button-row {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.button {
min-height: 38px;
padding: 0 14px;
border: 1px solid var(--line);
border-radius: 10px;
color: var(--ink);
background: rgba(255, 255, 255, 0.78);
cursor: pointer;
font-size: 0.83rem;
font-weight: 750;
transition:
transform 120ms ease,
border-color 120ms ease,
background 120ms ease;
}
.button:hover {
border-color: #aebfac;
background: #fff;
transform: translateY(-1px);
}
.button:active {
transform: translateY(0);
}
.button.primary {
color: #fff;
border-color: var(--green);
background: var(--green);
}
.button.primary:hover {
border-color: var(--green-dark);
background: var(--green-dark);
}
.button.active {
color: var(--green-dark);
border-color: #a9c287;
background: #e6f2ce;
}
.workspace {
display: grid;
grid-template-columns: minmax(0, 1fr) 330px;
gap: 18px;
align-items: start;
}
.experiments {
min-width: 0;
}
.view-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16px;
}
.view-card,
.panel,
.chart-panel {
overflow: hidden;
border: 1px solid rgba(199, 212, 196, 0.85);
border-radius: var(--radius);
background: rgba(249, 251, 246, 0.94);
box-shadow: var(--shadow);
}
.view-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
min-height: 86px;
padding: 16px 17px 13px;
border-bottom: 1px solid var(--line);
}
.scenario-name {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 5px;
}
.scenario-letter {
display: inline-grid;
width: 25px;
height: 25px;
place-items: center;
border-radius: 7px;
color: #fff;
background: var(--green);
font-size: 0.76rem;
font-weight: 850;
}
.scenario-letter.blue {
background: var(--blue);
}
.view-header h2,
.panel h2,
.chart-panel h2 {
margin: 0;
font-size: 1rem;
letter-spacing: -0.015em;
}
.view-header p {
margin: 0;
color: var(--muted);
font-size: 0.76rem;
line-height: 1.45;
}
.live-dot {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 8px;
border-radius: 999px;
color: var(--green-dark);
background: #e5f0d5;
font-size: 0.65rem;
font-weight: 850;
letter-spacing: 0.08em;
white-space: nowrap;
}
.live-dot::before {
width: 6px;
height: 6px;
border-radius: 50%;
background: #5c9b50;
content: "";
box-shadow: 0 0 0 3px rgba(92, 155, 80, 0.14);
}
.live-dot.paused {
color: #785d31;
background: #f3e8d2;
}
.live-dot.paused::before {
background: var(--amber);
}
.view-stage {
position: relative;
height: clamp(360px, 53vh, 620px);
min-height: 360px;
overflow: hidden;
background: #edf2e7;
}
.view-stage canvas {
position: absolute;
inset: 0;
z-index: 0;
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
}
.world-note {
position: absolute;
z-index: 2;
left: 12px;
top: 12px;
padding: 7px 9px;
border: 1px solid rgba(255, 255, 255, 0.72);
border-radius: 9px;
color: #30493c;
background: rgba(250, 252, 247, 0.78);
box-shadow: 0 8px 24px rgba(40, 68, 49, 0.08);
backdrop-filter: blur(8px);
font-size: 0.66rem;
font-weight: 750;
pointer-events: none;
}
.hover-readout {
position: absolute;
z-index: 2;
right: 12px;
bottom: 12px;
min-width: 112px;
padding: 7px 9px;
border-radius: 8px;
color: #eef6eb;
background: rgba(25, 51, 40, 0.78);
backdrop-filter: blur(8px);
font-size: 0.67rem;
line-height: 1.45;
pointer-events: none;
}
.view-footer {
padding: 14px 16px 16px;
border-top: 1px solid var(--line);
background: rgba(255, 255, 255, 0.65);
}
.metric-row {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 16px;
}
.metric-label {
color: var(--muted);
font-size: 0.68rem;
font-weight: 750;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.metric-value {
margin-top: 2px;
font-size: 1.75rem;
font-weight: 850;
letter-spacing: -0.055em;
}
.metric-detail {
margin-top: 2px;
color: var(--muted);
font-size: 0.73rem;
}
.metric-total {
color: var(--muted);
font-size: 0.72rem;
text-align: right;
}
.metric-total strong {
display: block;
margin-bottom: 2px;
color: var(--ink);
font-size: 1rem;
}
.progress {
height: 7px;
margin-top: 11px;
overflow: hidden;
border-radius: 999px;
background: #e4e9df;
}
.progress > span {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
background: var(--green);
transition: width 260ms ease;
}
#progressB {
background: var(--blue);
}
.sidebar {
display: grid;
gap: 16px;
}
.panel {
padding: 17px;
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 14px;
}
.small-label {
color: var(--muted);
font-size: 0.67rem;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.control-group {
padding: 13px 0;
border-top: 1px solid var(--line);
}
.control-group:first-of-type {
padding-top: 0;
border-top: 0;
}
.control-label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 8px;
font-size: 0.8rem;
font-weight: 760;
}
.control-value {
color: var(--green);
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 5px 0 2px;
border-radius: 999px;
accent-color: var(--green);
cursor: pointer;
}
.range-hints {
display: flex;
justify-content: space-between;
margin-top: 6px;
color: var(--muted);
font-size: 0.64rem;
}
.segmented {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.segmented .button {
min-width: 0;
padding: 0 8px;
}
.hint {
margin: 9px 0 0;
color: var(--muted);
font-size: 0.7rem;
line-height: 1.5;
}
.status-strip {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 11px;
}
.status-box {
padding: 10px;
border-radius: 10px;
background: #edf2e8;
}
.status-box span {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 0.63rem;
font-weight: 750;
text-transform: uppercase;
}
.status-box strong {
font-size: 0.86rem;
}
details summary {
cursor: pointer;
list-style: none;
}
details summary::-webkit-details-marker {
display: none;
}
details summary::after {
float: right;
color: var(--muted);
content: "+";
font-size: 1.1rem;
line-height: 0.9;
}
details[open] summary::after {
content: "−";
}
.rule-list {
display: grid;
gap: 10px;
margin: 15px 0 0;
padding: 0;
list-style: none;
}
.rule-list li {
position: relative;
padding-left: 17px;
color: #4c6055;
font-size: 0.72rem;
line-height: 1.5;
}
.rule-list li::before {
position: absolute;
top: 0.47em;
left: 0;
width: 7px;
height: 7px;
border-radius: 2px;
background: var(--lime);
content: "";
}
.formula {
margin: 11px 0 0;
padding: 10px;
border: 1px solid #d8e3cf;
border-radius: 9px;
color: var(--green-dark);
background: #f0f6e8;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.68rem;
line-height: 1.65;
}
.chart-panel {
margin-top: 18px;
padding: 17px 18px 14px;
}
.chart-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
margin-bottom: 12px;
}
.chart-summary {
color: var(--muted);
font-size: 0.75rem;
text-align: right;
}
.chart-wrap {
position: relative;
height: 205px;
}
#historyChart {
display: block;
width: 100%;
height: 100%;
}
.chart-legend {
display: flex;
align-items: center;
gap: 18px;
margin-top: 8px;
color: var(--muted);
font-size: 0.68rem;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 6px;
}
.legend-swatch {
width: 18px;
height: 3px;
border-radius: 999px;
background: var(--green);
}
.legend-swatch.blue {
background: var(--blue);
}
.footer-note {
display: flex;
justify-content: space-between;
gap: 18px;
padding: 15px 3px 0;
color: var(--muted);
font-size: 0.68rem;
line-height: 1.5;
}
kbd {
padding: 2px 5px;
border: 1px solid #ccd6c8;
border-bottom-width: 2px;
border-radius: 5px;
color: #425a4c;
background: rgba(255, 255, 255, 0.7);
font-family: inherit;
font-size: 0.64rem;
font-weight: 750;
}
@media (max-width: 1100px) {
.workspace {
grid-template-columns: 1fr;
}
.sidebar {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
@media (max-width: 820px) {
.app {
width: min(100% - 20px, 720px);
padding-top: 15px;
}
.topbar {
align-items: flex-start;
flex-direction: column;
}
.view-grid,
.sidebar {
grid-template-columns: 1fr;
}
.view-stage {
height: 430px;
}
.chart-heading,
.footer-note {
align-items: flex-start;
flex-direction: column;
}
.chart-summary {
text-align: left;
}
}
@media (max-width: 480px) {
.view-stage {
height: 360px;
}
.brand-mark {
transform: scale(0.86);
transform-origin: left center;
}
.top-actions {
width: 100%;
}
.top-actions .button {
flex: 1;
}
}
</style>
</head>
<body>
<div class="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<span></span><span></span><span></span>
</div>
<div>
<p class="eyebrow">Voxel ecology sandbox</p>
<h1>Canopy Recovery Lab</h1>
<p class="subtitle">Clear one footprint. Compare paired recovery with and without shade.</p>
</div>
</div>
<div class="top-actions">
<button class="button" id="resetButton" type="button">Reset experiment</button>
<button class="button primary" id="clearCentralButton" type="button">Clear central patch</button>
</div>
</header>
<main class="workspace">
<section class="experiments" aria-label="Paired vegetation experiments">
<div class="view-grid">
<article class="view-card">
<header class="view-header">
<div>
<div class="scenario-name">
<span class="scenario-letter">A</span>
<h2>Colonization only</h2>
</div>
<p>Empty cells use the base germination chance.</p>
</div>
<span class="live-dot" id="liveBadge">LIVE</span>
</header>
<div class="view-stage" id="stageA">
<div class="world-note">Drag to orbit · scroll to zoom</div>
<div class="hover-readout" id="hoverReadout">Hover over the grid</div>
</div>
<footer class="view-footer">
<div class="metric-row">
<div>
<div class="metric-label">Patch recovered</div>
<div class="metric-value" id="recoveryA">0%</div>
<div class="metric-detail" id="detailA">0 of 25 cells</div>
</div>
<div class="metric-total">
<strong id="totalA">0</strong>
plants in plot
</div>
</div>
<div class="progress"><span id="progressA"></span></div>
</footer>
</article>
<article class="view-card">
<header class="view-header">
<div>
<div class="scenario-name">
<span class="scenario-letter blue">B</span>
<h2>Colonization + shade</h2>
</div>
<p>Taller neighbors reduce germination probability.</p>
</div>
<span class="live-dot" id="liveBadgeB">LIVE</span>
</header>
<div class="view-stage" id="stageB">
<div class="world-note">Drag to orbit · scroll to zoom</div>
<div class="hover-readout" id="hoverReadoutB">Hover over the grid</div>
</div>
<footer class="view-footer">
<div class="metric-row">
<div>
<div class="metric-label">Patch recovered</div>
<div class="metric-value" id="recoveryB">0%</div>
<div class="metric-detail" id="detailB">0 of 25 cells</div>
</div>
<div class="metric-total">
<strong id="totalB">0</strong>
plants in plot
</div>
</div>
<div class="progress"><span id="progressB"></span></div>
</footer>
</article>
</div>
<section class="chart-panel" aria-label="Recovery history chart">
<div class="chart-heading">
<div>
<p class="eyebrow">Paired outcome</p>
<h2>Recovery trace</h2>
</div>
<div class="chart-summary" id="chartSummary">
Waiting for the first comparison…
</div>
</div>
<div class="chart-wrap">
<canvas id="historyChart" aria-label="Chart of patch recovery over time"></canvas>
</div>
<div class="chart-legend">
<span class="legend-item"><span class="legend-swatch"></span> A · colonization only</span>
<span class="legend-item"><span class="legend-swatch blue"></span> B · shade-aware</span>
<span>Shared patch · shared random draws</span>
</div>
</section>
</section>
<aside class="sidebar" aria-label="Simulation controls">
<section class="panel">
<div class="panel-heading">
<h2>Simulation</h2>
<span class="small-label" id="tickLabel">Tick 0</span>
</div>
<div class="button-row">
<button class="button primary" id="playButton" type="button">Pause</button>
<button class="button" id="stepButton" type="button">Step</button>
</div>
<div class="status-strip">
<div class="status-box">
<span>Patch footprint</span>
<strong id="patchSizeLabel">25 cells</strong>
</div>
<div class="status-box">
<span>Recovery gap</span>
<strong id="gapLabel">0 cells</strong>
</div>
</div>
<div class="control-group">
<div class="control-label">
<label for="speedInput">Simulation speed</label>
<span class="control-value" id="speedValue">1.0×</span>
</div>
<input id="speedInput" type="range" min="0.5" max="2" step="0.25" value="1" />
<div class="range-hints"><span>0.5×</span><span>2×</span></div>
</div>
</section>
<section class="panel">
<div class="panel-heading">
<h2>Patch & brush</h2>
<span class="small-label">Matched edits</span>
</div>
<div class="control-group">
<div class="control-label">
<label for="patchInput">Central patch size</label>
<span class="control-value" id="patchValue">5 × 5</span>
</div>
<input id="patchInput" type="range" min="2" max="8" step="1" value="5" />
<div class="range-hints"><span>2 cells</span><span>8 cells</span></div>
</div>
<div class="control-group">
<div class="control-label">
<span>Pointer tool</span>
<span class="control-value">B / V</span>
</div>
<div class="segmented">
<button class="button active" id="orbitTool" data-tool="orbit" type="button">Orbit</button>
<button class="button" id="brushTool" data-tool="brush" type="button">Clear brush</button>
</div>
<div class="control-label" style="margin-top: 14px;">
<label for="brushInput">Brush radius</label>
<span class="control-value" id="brushValue">1 cell</span>
</div>
<input id="brushInput" type="range" min="1" max="4" step="1" value="1" />
<p class="hint">
In brush mode, editing either plot clears the matching cells in both plots.
The selected footprint is tracked in the recovery chart.
</p>
</div>
</section>
<section class="panel">
<div class="panel-heading">
<h2>Toy model</h2>
<span class="small-label">Explicit rules</span>
</div>
<div class="control-group">
<div class="control-label">
<label for="colonizationInput">Base colonization p₀</label>
<span class="control-value" id="colonizationValue">22%</span>
</div>
<input id="colonizationInput" type="range" min="0.05" max="0.5" step="0.01" value="0.22" />
</div>
<div class="control-group">
<div class="control-label">
<label for="shadeInput">Maximum shade penalty</label>
<span class="control-value" id="shadeValue">72%</span>
</div>
<input id="shadeInput" type="range" min="0" max="0.9" step="0.01" value="0.72" />
</div>
<details open>
<summary><strong>How the model works</strong></summary>
<ol class="rule-list">
<li>An empty cell can germinate only if at least one of its four orthogonal neighbors is occupied.</li>
<li>Plot A uses probability p₀. Plot B multiplies p₀ by its shade factor.</li>
<li>Plants have height 1–3 and grow one level every two ticks, up to height 3.</li>
<li>Shade changes germination only; it does not slow plant growth.</li>
<li>Both plots receive paired random draws, so differences come from the shade rule.</li>
</ol>
<div class="formula" id="formulaText">
S = clamp((mean neighbor height − 1) / 2, 0, 1)<br>
pA = p₀<br>
pB = p₀ × (1 − 0.72 × S)
</div>
</details>
</section>
</aside>
</main>
<footer class="footer-note">
<span>Educational toy model — not a biological forest simulator.</span>
<span>
<kbd>Space</kbd> play/pause ·
<kbd>V</kbd> orbit ·
<kbd>B</kbd> brush ·
<kbd>R</kbd> reset
</span>
</footer>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------
// Model configuration
// ---------------------------------------------------------------------
const GRID = 18;
const CELL = 0.72;
const BASE_INTERVAL = 1300;
const config = {
playing: true,
speed: 1,
colonization: 0.22,
shade: 0.72,
patchSize: 5,
brushRadius: 1
};
const $ = (id) => document.getElementById(id);
const clamp = (value, min, max) => Math.max(min, Math.min(max, value));
function hash01(a, b = 0, c = 0) {
let h =
Math.imul(a + 1, 374761393) ^
Math.imul(b + 1, 668265263) ^
Math.imul(c + 1, 2246822519);
h = Math.imul(h ^ (h >>> 13), 1274126177);
return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
}
function cellIndex(column, row) {
return row * GRID + column;
}
function cellColumn(index) {
return index % GRID;
}
function cellRow(index) {
return Math.floor(index / GRID);
}
function cellLabel(index) {
const column = cellColumn(index);
const row = cellRow(index);
return `${String.fromCharCode(65 + column)}${row + 1}`;
}
function centralPatch(size = config.patchSize) {
const start = Math.floor((GRID - size) / 2);
const cells = [];
for (let row = start; row < start + size; row++) {
for (let column = start; column < start + size; column++) {
cells.push(cellIndex(column, row));
}
}
return cells;
}
function makeInitialState() {
const heights = new Uint8Array(GRID * GRID);
const ages = new Uint16Array(GRID * GRID);
const patch = new Set(centralPatch());
const start = Math.floor((GRID - config.patchSize) / 2);
const end = start + config.patchSize - 1;
for (let row = 0; row < GRID; row++) {
for (let column = 0; column < GRID; column++) {
const index = cellIndex(column, row);
if (patch.has(index)) {
continue;
}
const cluster =
Math.sin(column * 0.68) +
Math.cos(row * 0.57) +
Math.sin((column + row) * 0.29);
const chance = clamp(0.49 + cluster * 0.115, 0.19, 0.81);
let occupied = hash01(column, row, 17) < chance;
// Guarantee a source ring around the cleared patch.
const nearPatch =
column >= start - 1 &&
column <= end + 1 &&
row >= start - 1 &&
row <= end + 1;
if (nearPatch) {
occupied = true;
}
if (occupied) {
heights[index] = 1 + Math.floor(hash01(column, row, 31) * 3);
ages[index] = Math.floor(hash01(column, row, 47) * 8);
}
}
}
return { heights, ages };
}
// ---------------------------------------------------------------------
// Three.js world
// ---------------------------------------------------------------------
class VoxelWorld {
constructor(stage, accentColor) {
this.stage = stage;
this.accentColor = accentColor;
this.scene = new THREE.Scene();
this.scene.background = new THREE.Color(0xedf2e7);
this.scene.fog = new THREE.Fog(0xedf2e7, 20, 42);
this.camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
this.renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.8));
this.renderer.outputColorSpace = THREE.SRGBColorSpace;
this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
this.renderer.toneMappingExposure = 1.08;
this.renderer.shadowMap.enabled = true;
this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
this.renderer.domElement.setAttribute("aria-label", "Interactive voxel vegetation plot");
this.renderer.domElement.tabIndex = 0;
stage.appendChild(this.renderer.domElement);
this.raycaster = new THREE.Raycaster();
this.pointer = new THREE.Vector2();
this.terrainTop = new Float32Array(GRID * GRID);
this.state = null;
this.addLighting();
this.addTerrain();
this.addVegetation();
this.addHoverMarker();
this.resizeObserver = new ResizeObserver(() => this.resize());
this.resizeObserver.observe(stage);
this.resize();
}
addLighting() {
const hemisphere = new THREE.HemisphereLight(0xffffff, 0x71806c, 2.15);
this.scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff4d9, 2.6);
sun.position.set(-7, 13, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.camera.left = -11;
sun.shadow.camera.right = 11;
sun.shadow.camera.top = 11;
sun.shadow.camera.bottom = -11;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
sun.shadow.normalBias = 0.035;
this.scene.add(sun);
const fill = new THREE.DirectionalLight(0xc8e5ef, 0.55);
fill.position.set(9, 6, -8);
this.scene.add(fill);
}
addTerrain() {
const span = GRID * CELL;
const plinth = new THREE.Mesh(
new THREE.BoxGeometry(span + 0.7, 0.42, span + 0.7),
new THREE.MeshStandardMaterial({
color: 0x879b7d,
roughness: 0.95
})
);
plinth.position.y = -0.48;
plinth.receiveShadow = true;
this.scene.add(plinth);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(100, 100),
new THREE.MeshStandardMaterial({
color: 0xccd8c5,
roughness: 1
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.3;
floor.receiveShadow = true;
this.scene.add(floor);
this.ground = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.96,
metalness: 0
}),
GRID * GRID
);
this.ground.instanceMatrix.setUsage(THREE.StaticDrawUsage);
this.ground.receiveShadow = true;
this.ground.castShadow = true;
this.ground.frustumCulled = false;
const dummy = new THREE.Object3D();
const color = new THREE.Color();
for (let row = 0; row < GRID; row++) {
for (let column = 0; column < GRID; column++) {
const index = cellIndex(column, row);
const x = (column - (GRID - 1) / 2) * CELL;
const z = (row - (GRID - 1) / 2) * CELL;
const elevation =
0.08 +
hash01(column, row, 91) * 0.16 +
Math.sin(column * 0.7 + row * 0.35) * 0.025;
const depth = 0.43 + elevation;
const top = elevation;
this.terrainTop[index] = top;
dummy.position.set(x, top - depth / 2, z);
dummy.scale.set(CELL * 0.94, depth, CELL * 0.94);
dummy.updateMatrix();
this.ground.setMatrixAt(index, dummy.matrix);
const hue = 0.235 + hash01(column, row, 93) * 0.025;
const saturation = 0.24 + hash01(column, row, 95) * 0.08;
const lightness = 0.43 + hash01(column, row, 97) * 0.09;
color.setHSL(hue, saturation, lightness);
this.ground.setColorAt(index, color);
}
}
this.ground.instanceMatrix.needsUpdate = true;
this.ground.instanceColor.needsUpdate = true;
this.scene.add(this.ground);
}
addVegetation() {
const capacity = GRID * GRID;
this.trunks = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.9
}),
capacity
);
this.leaves = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.82
}),
capacity
);
this.trunks.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
this.leaves.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
this.trunks.frustumCulled = false;
this.leaves.frustumCulled = false;
this.trunks.castShadow = true;
this.trunks.receiveShadow = true;
this.leaves.castShadow = true;
this.leaves.receiveShadow = true;
this.scene.add(this.trunks, this.leaves);
}
addHoverMarker() {
const geometry = new THREE.EdgesGeometry(
new THREE.BoxGeometry(CELL * 0.91, 1.35, CELL * 0.91)
);
this.hoverMarker = new THREE.LineSegments(
geometry,
new THREE.LineBasicMaterial({
color: this.accentColor,
transparent: true,
opacity: 0.9
})
);
this.hoverMarker.visible = false;
this.scene.add(this.hoverMarker);
}
setState(state) {
this.state = state;
this.updateVegetation();
}
updateVegetation() {
if (!this.state) {
return;
}
const dummy = new THREE.Object3D();
const trunkColor = new THREE.Color();
const leafColor = new THREE.Color();
const heightColors = [0xa8cf68, 0x65ad58, 0x347e50];
let trunkCount = 0;
let leafCount = 0;
for (let index = 0; index < GRID * GRID; index++) {
const height = this.state.heights[index];
if (height === 0) {
continue;
}
const column = cellColumn(index);
const row = cellRow(index);
const x = (column - (GRID - 1) / 2) * CELL;
const z = (row - (GRID - 1) / 2) * CELL;
const ground = this.terrainTop[index];
const trunkHeight = 0.2 + (height - 1) * 0.18;
const canopyHeight = 0.25 + (height - 1) * 0.29;
const canopyWidth = 0.46 + (height - 1) * 0.045;
dummy.position.set(x, ground + trunkHeight / 2, z);
dummy.scale.set(0.145, trunkHeight, 0.145);
dummy.updateMatrix();
this.trunks.setMatrixAt(trunkCount, dummy.matrix);
trunkColor.set(0x765139);
trunkColor.offsetHSL(0, 0, hash01(column, row, 111) * 0.06 - 0.03);
this.trunks.setColorAt(trunkCount, trunkColor);
trunkCount++;
dummy.position.set(
x,
ground + trunkHeight + canopyHeight / 2 - 0.045,
z
);
dummy.scale.set(canopyWidth, canopyHeight, canopyWidth);
dummy.updateMatrix();
this.leaves.setMatrixAt(leafCount, dummy.matrix);
leafColor.set(heightColors[height - 1]);
leafColor.offsetHSL(0, 0, hash01(column, row, 113) * 0.09 - 0.045);
this.leaves.setColorAt(leafCount, leafColor);
leafCount++;
}
this.trunks.count = trunkCount;
this.leaves.count = leafCount;
this.trunks.instanceMatrix.needsUpdate = true;
this.leaves.instanceMatrix.needsUpdate = true;
if (this.trunks.instanceColor) {
this.trunks.instanceColor.needsUpdate = true;
}
if (this.leaves.instanceColor) {
this.leaves.instanceColor.needsUpdate = true;
}
}
setHover(index) {
if (index === null) {
this.hoverMarker.visible = false;
return;
}
const column = cellColumn(index);
const row = cellRow(index);
const x = (column - (GRID - 1) / 2) * CELL;
const z = (row - (GRID - 1) / 2) * CELL;
this.hoverMarker.position.set(x, this.terrainTop[index] + 0.66, z);
this.hoverMarker.visible = true;
}
resize() {
const width = Math.max(1, this.stage.clientWidth);
const height = Math.max(1, this.stage.clientHeight);
this.renderer.setSize(width, height, false);
this.camera.aspect = width / height;
this.camera.updateProjectionMatrix();
}
render() {
this.renderer.render(this.scene, this.camera);
}
}
const worldA = new VoxelWorld($("stageA"), 0x287453);
const worldB = new VoxelWorld($("stageB"), 0x4e8fb7);
// ---------------------------------------------------------------------
// Shared camera and pointer tools
// ---------------------------------------------------------------------
const cameraState = {
yaw: 0.72,
pitch: 0.78,
radius: 19.5,
target: new THREE.Vector3(0, 0.4, 0)
};
let activeTool = "orbit";
let trackedPatch = new Set();
let tickCount = 0;
let history = [];
let accumulator = 0;
function updateCameras() {
const cosPitch = Math.cos(cameraState.pitch);
const sinPitch = Math.sin(cameraState.pitch);
const x =
cameraState.target.x +
cameraState.radius * cosPitch * Math.sin(cameraState.yaw);
const y =
cameraState.target.y +
cameraState.radius * sinPitch;
const z =
cameraState.target.z +
cameraState.radius * cosPitch * Math.cos(cameraState.yaw);
for (const world of [worldA, worldB]) {
world.camera.position.set(x, y, z);
world.camera.lookAt(cameraState.target);
}
}
function pointerToCell(world, event) {
const rect = world.renderer.domElement.getBoundingClientRect();
world.pointer.x =
((event.clientX - rect.left) / rect.width) * 2 - 1;
world.pointer.y =
-((event.clientY - rect.top) / rect.height) * 2 + 1;
world.raycaster.setFromCamera(world.pointer, world.camera);
const hits = world.raycaster.intersectObject(world.ground, false);
return hits.length ? hits[0].instanceId : null;
}
function brushCells(centerIndex) {
const centerColumn = cellColumn(centerIndex);
const centerRow = cellRow(centerIndex);
const radius = config.brushRadius;
const cells = [];
for (let row = centerRow - radius; row <= centerRow + radius; row++) {
for (let column = centerColumn - radius; column <= centerColumn + radius; column++) {
if (column < 0 || column >= GRID || row < 0 || row >= GRID) {
continue;
}
const dx = column - centerColumn;
const dy = row - centerRow;
if (Math.sqrt(dx * dx + dy * dy) <= radius - 0.15) {
cells.push(cellIndex(column, row));
}
}
}
return cells;
}
function clearCells(cells, resetHistory = true) {
for (const index of cells) {
trackedPatch.add(index);
worldA.state.heights[index] = 0;
worldB.state.heights[index] = 0;
worldA.state.ages[index] = 0;
worldB.state.ages[index] = 0;
}
worldA.updateVegetation();
worldB.updateVegetation();
if (resetHistory) {
history = [];
recordHistory();
}
updateMetrics();
drawChart();
}
function updateHover(world, event, otherWorld) {
const index = pointerToCell(world, event);
world.setHover(index);
otherWorld.setHover(index);
const readout = index === null
? "Hover over the grid"
: `${cellLabel(index)} · A h${worldA.state.heights[index]} · B h${worldB.state.heights[index]}`;
if (world === worldA) {
$("hoverReadout").textContent = readout;
$("hoverReadoutB").textContent = readout;
} else {
$("hoverReadoutB").textContent = readout;
$("hoverReadout").textContent = readout;
}
}
function attachControls(world, otherWorld) {
const canvas = world.renderer.domElement;
let dragging = false;
let lastX = 0;
let lastY = 0;
canvas.addEventListener("pointerdown", (event) => {
canvas.setPointerCapture(event.pointerId);
if (activeTool === "brush") {
dragging = true;
const index = pointerToCell(world, event);
if (index !== null) {
clearCells(brushCells(index), true);
}
} else {
dragging = true;
lastX = event.clientX;
lastY = event.clientY;
}
});
canvas.addEventListener("pointermove", (event) => {
updateHover(world, event, otherWorld);
if (!dragging) {
return;
}
if (activeTool === "brush") {
const index = pointerToCell(world, event);
if (index !== null) {
clearCells(brushCells(index), false);
}
} else {
const dx = event.clientX - lastX;
const dy = event.clientY - lastY;
cameraState.yaw -= dx * 0.006;
cameraState.pitch = clamp(
cameraState.pitch + dy * 0.005,
0.36,
1.32
);
lastX = event.clientX;
lastY = event.clientY;
updateCameras();
}
});
function endPointer(event) {
dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
recordHistory();
drawChart();
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener("pointerleave", () => {
if (!dragging) {
world.setHover(null);
otherWorld.setHover(null);
$("hoverReadout").textContent = "Hover over the grid";
$("hoverReadoutB").textContent = "Hover over the grid";
}
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = clamp(
cameraState.radius + event.deltaY * 0.012,
11,
29
);
updateCameras();
},
{ passive: false }
);
}
attachControls(worldA, worldB);
attachControls(worldB, worldA);
// ---------------------------------------------------------------------
// Simulation
// ---------------------------------------------------------------------
function neighborIndices(index) {
const column = cellColumn(index);
const row = cellRow(index);
const neighbors = [];
if (column > 0) neighbors.push(index - 1);
if (column < GRID - 1) neighbors.push(index + 1);
if (row > 0) neighbors.push(index - GRID);
if (row < GRID - 1) neighbors.push(index + GRID);
return neighbors;
}
function neighborShade(heights, index) {
const neighbors = neighborIndices(index);
let occupiedCount = 0;
let heightSum = 0;
for (const neighbor of neighbors) {
if (heights[neighbor] > 0) {
occupiedCount++;
heightSum += heights[neighbor];
}
}
if (occupiedCount === 0) {
return null;
}
const meanHeight = heightSum / occupiedCount;
const shadeIndex = clamp((meanHeight - 1) / 2, 0, 1);
return { occupiedCount, meanHeight, shadeIndex };
}
function pairedRandom(index) {
let h =
Math.imul(index + 1, 374761393) ^
Math.imul(tickCount + 1, 668265263);
h = Math.imul(h ^ (h >>> 13), 1274126177);
return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
}
function growState(state, snapshot, wasEmpty) {
for (let index = 0; index < GRID * GRID; index++) {
if (wasEmpty[index]) {
continue;
}
state.ages[index]++;
if (
state.ages[index] > 0 &&
state.ages[index] % 2 === 0 &&
state.heights[index] < 3
) {
state.heights[index]++;
}
}
}
function stepSimulation() {
tickCount++;
const snapshotA = worldA.state.heights.slice();
const snapshotB = worldB.state.heights.slice();
const emptyA = new Uint8Array(GRID * GRID);
const emptyB = new Uint8Array(GRID * GRID);
for (let index = 0; index < GRID * GRID; index++) {
emptyA[index] = snapshotA[index] === 0 ? 1 : 0;
emptyB[index] = snapshotB[index] === 0 ? 1 : 0;
const random = pairedRandom(index);
if (emptyA[index]) {
const shadeA = neighborShade(snapshotA, index);
if (shadeA && random < config.colonization) {
worldA.state.heights[index] = 1;
worldA.state.ages[index] = 0;
}
}
if (emptyB[index]) {
const shadeB = neighborShade(snapshotB, index);
if (shadeB) {
const probability =
config.colonization *
(1 - config.shade * shadeB.shadeIndex);
if (random < probability) {
worldB.state.heights[index] = 1;
worldB.state.ages[index] = 0;
}
}
}
}
growState(worldA.state, snapshotA, emptyA);
growState(worldB.state, snapshotB, emptyB);
worldA.updateVegetation();
worldB.updateVegetation();
recordHistory();
updateMetrics();
drawChart();
}
function recordHistory() {
const total = Math.max(1, trackedPatch.size);
let recoveredA = 0;
let recoveredB = 0;
for (const index of trackedPatch) {
if (worldA.state.heights[index] > 0) recoveredA++;
if (worldB.state.heights[index] > 0) recoveredB++;
}
history.push({
tick: tickCount,
a: recoveredA / total,
b: recoveredB / total,
cellsA: recoveredA,
cellsB: recoveredB
});
if (history.length > 120) {
history.shift();
}
}
function countPlants(state) {
let count = 0;
for (const height of state.heights) {
if (height > 0) count++;
}
return count;
}
function updateMetrics() {
const total = Math.max(1, trackedPatch.size);
let recoveredA = 0;
let recoveredB = 0;
for (const index of trackedPatch) {
if (worldA.state.heights[index] > 0) recoveredA++;
if (worldB.state.heights[index] > 0) recoveredB++;
}
const percentA = Math.round((recoveredA / total) * 100);
const percentB = Math.round((recoveredB / total) * 100);
$("recoveryA").textContent = `${percentA}%`;
$("recoveryB").textContent = `${percentB}%`;
$("detailA").textContent = `${recoveredA} of ${trackedPatch.size} cells`;
$("detailB").textContent = `${recoveredB} of ${trackedPatch.size} cells`;
$("progressA").style.width = `${percentA}%`;
$("progressB").style.width = `${percentB}%`;
$("totalA").textContent = countPlants(worldA.state);
$("totalB").textContent = countPlants(worldB.state);
$("tickLabel").textContent = `Tick ${tickCount}`;
$("patchSizeLabel").textContent = `${trackedPatch.size} cells`;
const gap = recoveredB - recoveredA;
const absoluteGap = Math.abs(gap);
$("gapLabel").textContent =
gap === 0
? "No gap yet"
: `${absoluteGap} cell${absoluteGap === 1 ? "" : "s"}`;
if (history.length > 1) {
const latest = history[history.length - 1];
if (gap < 0) {
$("chartSummary").textContent =
`B trails A by ${absoluteGap} recovered cell${absoluteGap === 1 ? "" : "s"}.`;
} else if (gap > 0) {
$("chartSummary").textContent =
`B leads A by ${absoluteGap} recovered cell${absoluteGap === 1 ? "" : "s"}.`;
} else {
$("chartSummary").textContent =
"A and B currently have equal patch recovery.";
}
} else {
$("chartSummary").textContent = "Clear or grow a patch to begin the comparison.";
}
}
// ---------------------------------------------------------------------
// History chart, drawn directly with Canvas 2D
// ---------------------------------------------------------------------
function drawChart() {
const canvas = $("historyChart");
const rect = canvas.getBoundingClientRect();
if (!rect.width || !rect.height) {
return;
}
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const width = rect.width;
const height = rect.height;
canvas.width = Math.round(width * dpr);
canvas.height = Math.round(height * dpr);
const ctx = canvas.getContext("2d");
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, width, height);
const padding = {
left: 42,
right: 18,
top: 15,
bottom: 31
};
const plotWidth = width - padding.left - padding.right;
const plotHeight = height - padding.top - padding.bottom;
ctx.font = "10px ui-sans-serif, system-ui, sans-serif";
ctx.lineWidth = 1;
for (const value of [0, 0.25, 0.5, 0.75, 1]) {
const y = padding.top + (1 - value) * plotHeight;
ctx.beginPath();
ctx.strokeStyle = value === 0 ? "#bdcabb" : "#e2e8de";
ctx.moveTo(padding.left, y);
ctx.lineTo(width - padding.right, y);
ctx.stroke();
ctx.fillStyle = "#718078";
ctx.textAlign = "right";
ctx.textBaseline = "middle";
ctx.fillText(`${Math.round(value * 100)}%`, padding.left - 8, y);
}
if (history.length === 0) {
return;
}
const xAt = (index) => {
if (history.length === 1) {
return padding.left + plotWidth / 2;
}
return (
padding.left +
(index / (history.length - 1)) * plotWidth
);
};
const yAt = (value) => padding.top + (1 - value) * plotHeight;
function drawLine(key, color) {
ctx.beginPath();
ctx.strokeStyle = color;
ctx.lineWidth = 2.5;
ctx.lineJoin = "round";
ctx.lineCap = "round";
history.forEach((point, index) => {
const x = xAt(index);
const y = yAt(point[key]);
if (index === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
});
ctx.stroke();
const last = history[history.length - 1];
ctx.beginPath();
ctx.fillStyle = color;
ctx.arc(
xAt(history.length - 1),
yAt(last[key]),
3.8,
0,
Math.PI * 2
);
ctx.fill();
}
drawLine("a", "#287453");
drawLine("b", "#4e8fb7");
ctx.fillStyle = "#718078";
ctx.textBaseline = "bottom";
const labelIndices = history.length <= 2
? history.map((_, index) => index)
: [0, Math.floor((history.length - 1) / 2), history.length - 1];
for (const index of labelIndices) {
const x = xAt(index);
ctx.textAlign =
index === 0 ? "left" : index === history.length - 1 ? "right" : "center";
ctx.fillText(
`tick ${history[index].tick}`,
x,
height - 4
);
}
}
// ---------------------------------------------------------------------
// Experiment controls
// ---------------------------------------------------------------------
function setPlaying(playing) {
config.playing = playing;
$("playButton").textContent = playing ? "Pause" : "Play";
for (const id of ["liveBadge", "liveBadgeB"]) {
$(id).textContent = playing ? "LIVE" : "PAUSED";
$(id).classList.toggle("paused", !playing);
}
}
function resetExperiment() {
const initial = makeInitialState();
worldA.setState({
heights: initial.heights.slice(),
ages: initial.ages.slice()
});
worldB.setState({
heights: initial.heights.slice(),
ages: initial.ages.slice()
});
trackedPatch = new Set(centralPatch());
tickCount = 0;
accumulator = 0;
history = [];
recordHistory();
updateMetrics();
drawChart();
}
function clearCentralPatch() {
const cells = centralPatch();
trackedPatch = new Set(cells);
clearCells(cells, true);
}
function setTool(tool) {
activeTool = tool;
$("orbitTool").classList.toggle("active", tool === "orbit");
$("brushTool").classList.toggle("active", tool === "brush");
}
function updateRuleText() {
$("colonizationValue").textContent =
`${Math.round(config.colonization * 100)}%`;
$("shadeValue").textContent =
`${Math.round(config.shade * 100)}%`;
$("formulaText").innerHTML =
`S = clamp((mean neighbor height − 1) / 2, 0, 1)<br>` +
`pA = ${config.colonization.toFixed(2)}<br>` +
`pB = ${config.colonization.toFixed(2)} × (1 − ${config.shade.toFixed(2)} × S)`;
}
$("playButton").addEventListener("click", () => {
setPlaying(!config.playing);
});
$("stepButton").addEventListener("click", () => {
setPlaying(false);
stepSimulation();
});
$("resetButton").addEventListener("click", () => {
resetExperiment();
});
$("clearCentralButton").addEventListener("click", () => {
clearCentralPatch();
});
$("speedInput").addEventListener("input", (event) => {
config.speed = Number(event.target.value);
$("speedValue").textContent = `${config.speed.toFixed(2).replace(/0$/, "")}×`;
});
$("patchInput").addEventListener("input", (event) => {
config.patchSize = Number(event.target.value);
$("patchValue").textContent = `${config.patchSize} × ${config.patchSize}`;
});
$("patchInput").addEventListener("change", () => {
resetExperiment();
});
$("brushInput").addEventListener("input", (event) => {
config.brushRadius = Number(event.target.value);
$("brushValue").textContent =
`${config.brushRadius} cell${config.brushRadius === 1 ? "" : "s"}`;
});
$("colonizationInput").addEventListener("input", (event) => {
config.colonization = Number(event.target.value);
updateRuleText();
});
$("shadeInput").addEventListener("input", (event) => {
config.shade = Number(event.target.value);
updateRuleText();
});
document.querySelectorAll("[data-tool]").forEach((button) => {
button.addEventListener("click", () => {
setTool(button.dataset.tool);
});
});
window.addEventListener("keydown", (event) => {
if (
event.target instanceof HTMLInputElement ||
event.target instanceof HTMLButtonElement
) {
return;
}
if (event.code === "Space") {
event.preventDefault();
setPlaying(!config.playing);
} else if (event.key.toLowerCase() === "v") {
setTool("orbit");
} else if (event.key.toLowerCase() === "b") {
setTool("brush");
} else if (event.key.toLowerCase() === "r") {
resetExperiment();
}
});
const chartObserver = new ResizeObserver(() => drawChart());
chartObserver.observe($("historyChart").parentElement);
// ---------------------------------------------------------------------
// Start
// ---------------------------------------------------------------------
updateRuleText();
resetExperiment();
updateCameras();
setPlaying(true);
let previousTime = performance.now();
function animate(now) {
const delta = Math.min(now - previousTime, 100);
previousTime = now;
if (config.playing) {
accumulator += delta;
const interval = BASE_INTERVAL / config.speed;
if (accumulator >= interval) {
accumulator %= interval;
stepSimulation();
}
}
worldA.render();
worldB.render();
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```