Prompt specification
Build or customize the Three.js 3D scene "One Rainfall Pulse Fills a Tank" 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: One Rainfall Pulse Fills a Tank
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/one-rainfall-pulse-fills-a-tank-x3954
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing rainwater collection, tanks, and demand. Animate a declared rainfall event over a roof and calculate collected volume from stated assumptions. Track overflow explicitly and label losses and units. Voxel style.
Working Three.js Starter (one-rainfall-pulse-fills-a-tank-x3954):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Rainwater Collection</title>
<style>
:root {
--ink: #183139;
--muted: #60747b;
--paper: rgba(249, 252, 249, 0.94);
--line: #b8c8c8;
--rain: #248fb8;
--water: #159ebd;
--loss: #d99024;
--overflow: #df5353;
--demand: #73569a;
--shadow: rgba(24, 49, 57, 0.18);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
color: var(--ink);
background: #dce8e8;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input,
select {
font: inherit;
}
#stage,
#labels {
position: fixed;
inset: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#stage canvas:active {
cursor: grabbing;
}
#labels {
pointer-events: none;
overflow: hidden;
}
.topbar {
position: fixed;
z-index: 10;
top: 14px;
left: 18px;
right: 18px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
pointer-events: none;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
padding: 11px 14px;
background: var(--paper);
border: 2px solid var(--ink);
box-shadow: 4px 4px 0 var(--shadow);
}
.brand-icon {
width: 29px;
height: 29px;
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
gap: 2px;
}
.brand-icon i {
display: block;
background: var(--rain);
}
.brand-icon i:nth-child(2),
.brand-icon i:nth-child(4),
.brand-icon i:nth-child(6),
.brand-icon i:nth-child(8) {
background: #8ed4e5;
}
.brand-icon i:nth-child(3),
.brand-icon i:nth-child(5) {
background: var(--ink);
}
h1 {
margin: 0;
font-size: 17px;
line-height: 1.1;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.brand small {
display: block;
margin-top: 3px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
letter-spacing: 0.04em;
}
.event-chip {
padding: 10px 13px;
background: var(--ink);
color: white;
border: 2px solid var(--ink);
box-shadow: 4px 4px 0 rgba(36, 143, 184, 0.38);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.event-chip span {
color: #83d9ee;
}
.panel {
position: fixed;
z-index: 10;
background: var(--paper);
border: 2px solid var(--ink);
box-shadow: 5px 5px 0 var(--shadow);
backdrop-filter: blur(8px);
}
#assumptions {
top: 88px;
left: 18px;
width: 306px;
max-height: calc(100vh - 235px);
overflow: auto;
}
#ledger {
top: 88px;
right: 18px;
width: 294px;
max-height: calc(100vh - 235px);
overflow: auto;
}
.panel-heading {
padding: 10px 12px;
background: var(--ink);
color: white;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
details summary {
padding: 11px 12px;
cursor: pointer;
list-style: none;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
details summary::-webkit-details-marker {
display: none;
}
details summary::after {
content: "+";
float: right;
font-size: 16px;
line-height: 10px;
}
details[open] summary::after {
content: "−";
}
.panel-content {
padding: 0 12px 12px;
}
.assumption {
display: flex;
justify-content: space-between;
gap: 12px;
padding: 7px 0;
border-bottom: 1px dotted #bac8c8;
font-size: 12px;
}
.assumption:last-of-type {
border-bottom: 0;
}
.assumption span:first-child {
color: var(--muted);
}
.assumption strong {
white-space: nowrap;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.formula {
margin-top: 10px;
padding: 9px;
background: #e7f0ef;
border-left: 4px solid var(--rain);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10.5px;
line-height: 1.55;
}
.formula b {
color: var(--rain);
}
.note {
margin-top: 9px;
color: var(--muted);
font-size: 10.5px;
line-height: 1.45;
}
.balance {
margin-top: 10px;
padding: 9px;
background: #f0e8f7;
border-left: 4px solid var(--demand);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10.5px;
line-height: 1.55;
}
.metric {
padding: 9px 0;
border-bottom: 1px dotted #bac8c8;
}
.metric:last-of-type {
border-bottom: 0;
}
.metric-top {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 8px;
}
.metric-name {
color: var(--muted);
font-size: 10.5px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.035em;
}
.metric-value {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 15px;
font-weight: 900;
}
.meter {
height: 5px;
margin-top: 6px;
overflow: hidden;
background: #dbe4e3;
}
.meter > div {
width: 0;
height: 100%;
background: var(--rain);
transition: width 90ms linear;
}
.meter.water > div { background: var(--water); }
.meter.demand > div { background: var(--demand); }
.meter.overflow > div { background: var(--overflow); }
.meter.loss > div { background: var(--loss); }
.ledger-footer {
padding: 9px 12px;
color: var(--muted);
background: #edf3f1;
border-top: 1px solid var(--line);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.45;
}
#timeline {
left: 50%;
bottom: 18px;
width: min(740px, calc(100vw - 36px));
transform: translateX(-50%);
padding: 10px 12px 8px;
}
.timeline-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 15px;
}
.transport {
display: flex;
align-items: center;
gap: 7px;
}
button,
select {
min-height: 31px;
border: 2px solid var(--ink);
border-radius: 0;
background: white;
color: var(--ink);
padding: 5px 9px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10.5px;
font-weight: 800;
cursor: pointer;
box-shadow: 2px 2px 0 var(--shadow);
}
button:hover,
select:hover {
background: #eaf3f2;
}
button:active {
transform: translate(1px, 1px);
box-shadow: 1px 1px 0 var(--shadow);
}
#play {
min-width: 75px;
background: var(--ink);
color: white;
}
.clock {
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
text-transform: uppercase;
}
#timeDisplay {
display: inline-block;
min-width: 57px;
color: var(--ink);
font-size: 14px;
font-weight: 900;
text-align: right;
}
.track {
position: relative;
height: 27px;
}
.track-base,
#eventBand,
#played {
position: absolute;
left: 0;
top: 9px;
height: 8px;
}
.track-base {
right: 0;
background: #cbd8d7;
border: 1px solid #9aafaf;
}
#eventBand {
width: 33.333333%;
background: repeating-linear-gradient(
-45deg,
#248fb8,
#248fb8 5px,
#62bfd6 5px,
#62bfd6 10px
);
border: 1px solid #176e8e;
z-index: 1;
}
#eventBand span {
position: absolute;
top: -16px;
left: 0;
color: var(--rain);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 900;
text-transform: uppercase;
white-space: nowrap;
}
#played {
width: 0;
background: rgba(255, 255, 255, 0.58);
border-right: 2px solid var(--ink);
z-index: 2;
}
#timeSlider {
position: absolute;
z-index: 3;
inset: 0;
width: 100%;
height: 27px;
margin: 0;
background: transparent;
appearance: none;
cursor: ew-resize;
}
#timeSlider::-webkit-slider-runnable-track {
height: 8px;
background: transparent;
}
#timeSlider::-webkit-slider-thumb {
width: 15px;
height: 23px;
margin-top: -8px;
appearance: none;
border: 2px solid var(--ink);
border-radius: 0;
background: #f9fcf9;
box-shadow: 2px 2px 0 var(--shadow);
}
#timeSlider::-moz-range-track {
height: 8px;
background: transparent;
}
#timeSlider::-moz-range-thumb {
width: 12px;
height: 20px;
border: 2px solid var(--ink);
border-radius: 0;
background: #f9fcf9;
}
#needle {
position: absolute;
z-index: 4;
top: 3px;
left: 0;
width: 2px;
height: 20px;
background: var(--ink);
pointer-events: none;
}
.timeline-labels {
display: flex;
justify-content: space-between;
margin-top: 1px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
}
.anno {
position: absolute;
z-index: 5;
min-width: 142px;
max-width: 225px;
padding: 7px 9px;
transform: translate(-50%, -100%);
background: rgba(249, 252, 249, 0.94);
border: 2px solid var(--ink);
border-left: 6px solid var(--c, var(--rain));
box-shadow: 3px 3px 0 rgba(24, 49, 57, 0.18);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
line-height: 1.3;
}
.anno .kicker {
display: block;
color: var(--c, var(--rain));
font-size: 8px;
font-weight: 900;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.anno strong {
display: block;
margin: 2px 0;
font-size: 12px;
}
.anno small {
display: block;
color: var(--muted);
font-size: 8.5px;
}
#cameraHelp {
position: fixed;
z-index: 8;
left: 18px;
bottom: 18px;
display: flex;
align-items: center;
gap: 8px;
color: var(--ink);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 700;
}
#cameraHelp button {
min-height: 27px;
padding: 3px 7px;
background: var(--paper);
}
#loading {
position: fixed;
z-index: 100;
inset: 0;
display: grid;
place-items: center;
background: #dce8e8;
color: var(--ink);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 13px;
font-weight: 800;
letter-spacing: 0.06em;
}
@media (max-width: 760px) {
.topbar {
top: 9px;
left: 9px;
right: 9px;
}
.brand {
padding: 8px 10px;
}
.brand small {
display: none;
}
h1 {
font-size: 13px;
}
.event-chip {
padding: 8px 9px;
font-size: 8px;
}
#assumptions {
top: 66px;
left: 9px;
width: min(280px, calc(100vw - 18px));
max-height: 34vh;
}
#ledger {
top: auto;
right: 9px;
bottom: 123px;
width: min(258px, calc(100vw - 18px));
max-height: 34vh;
}
.metric {
padding: 6px 0;
}
.metric-value {
font-size: 12px;
}
#timeline {
bottom: 9px;
width: calc(100vw - 18px);
}
#cameraHelp {
display: none;
}
.clock .clock-label {
display: none;
}
.anno {
min-width: 112px;
max-width: 170px;
padding: 5px 7px;
}
.anno strong {
font-size: 10px;
}
.anno small {
font-size: 7.5px;
}
}
</style>
</head>
<body>
<div id="stage" aria-label="Interactive voxel rainwater collection scene"></div>
<div id="labels" aria-hidden="true"></div>
<header class="topbar">
<div class="brand">
<div class="brand-icon" aria-hidden="true">
<i></i><i></i><i></i>
<i></i><i></i><i></i>
<i></i><i></i><i></i>
</div>
<div>
<h1>Rainwater / Reserve</h1>
<small>Voxel catchment, storage, overflow & demand</small>
</div>
</div>
<div class="event-chip">
Declared event: <span>45 mm / 4 hours</span>
</div>
</header>
<section class="panel" id="assumptions">
<details open>
<summary>Event + stated assumptions</summary>
<div class="panel-content">
<div class="assumption">
<span>Roof catchment</span>
<strong>120 m²</strong>
</div>
<div class="assumption">
<span>Rainfall total</span>
<strong>45 mm</strong>
</div>
<div class="assumption">
<span>Rain duration</span>
<strong>4 h</strong>
</div>
<div class="assumption">
<span>Mean intensity</span>
<strong>11.25 mm/h</strong>
</div>
<div class="assumption">
<span>Runoff coefficient</span>
<strong>0.85</strong>
</div>
<div class="assumption">
<span>Tank A / Tank B</span>
<strong>1,500 L each</strong>
</div>
<div class="assumption">
<span>Initial storage</span>
<strong>600 L</strong>
</div>
<div class="assumption">
<span>Demand rate</span>
<strong>300 L/h</strong>
</div>
<div class="assumption">
<span>Display period</span>
<strong>12 h</strong>
</div>
<div class="formula">
Gross rain = 45 mm × 120 m²<br>
= <b>5,400 L</b><br><br>
Collectible runoff = 5,400 × 0.85<br>
= <b>4,590 L</b><br><br>
Runoff loss = 5,400 − 4,590<br>
= <b>810 L</b>
</div>
<div class="note">
1 mm falling on 1 m² equals 1 L. The model assumes no evaporation,
infiltration, or additional pipe losses.
</div>
<div class="balance">
Final balance at 12 h:<br>
600 L initial + 4,590 L runoff<br>
= 3,600 L demand + 990 L overflow<br>
+ 600 L remaining storage.
</div>
</div>
</details>
</section>
<aside class="panel" id="ledger">
<div class="panel-heading">Live water ledger</div>
<div class="panel-content">
<div class="metric">
<div class="metric-top">
<span class="metric-name">Gross rainfall</span>
<span class="metric-value" id="grossNow">0 L</span>
</div>
<div class="meter"><div id="grossBar"></div></div>
</div>
<div class="metric">
<div class="metric-top">
<span class="metric-name">Collected runoff</span>
<span class="metric-value" id="collectedNow">0 L</span>
</div>
<div class="meter water"><div id="collectedBar"></div></div>
</div>
<div class="metric">
<div class="metric-top">
<span class="metric-name">Stored in tanks</span>
<span class="metric-value" id="storedNow">600 L</span>
</div>
<div class="meter water"><div id="storedBar"></div></div>
</div>
<div class="metric">
<div class="metric-top">
<span class="metric-name">Demand served</span>
<span class="metric-value" id="demandNow">0 L</span>
</div>
<div class="meter demand"><div id="demandBar"></div></div>
</div>
<div class="metric">
<div class="metric-top">
<span class="metric-name">Explicit overflow</span>
<span class="metric-value" id="overflowNow" style="color:var(--overflow)">0 L</span>
</div>
<div class="meter overflow"><div id="overflowBar"></div></div>
</div>
<div class="metric">
<div class="metric-top">
<span class="metric-name">Runoff losses</span>
<span class="metric-value" id="lossNow" style="color:var(--loss)">0 L</span>
</div>
<div class="meter loss"><div id="lossBar"></div></div>
</div>
</div>
<div class="ledger-footer">
Unmet demand: <b id="unmetNow">0 L</b><br>
Tank capacity: 3,000 L total
</div>
</aside>
<div class="panel" id="timeline">
<div class="timeline-top">
<div class="transport">
<button id="play" type="button" aria-pressed="true">Pause</button>
<button id="restart" type="button">Restart</button>
<select id="speed" aria-label="Playback speed">
<option value="1">1×</option>
<option value="2">2×</option>
<option value="4" selected>4×</option>
</select>
</div>
<div class="clock">
<span class="clock-label">Simulation</span>
<span id="timeDisplay">00:00</span>
<span id="rainStatus">/ RAIN ACTIVE</span>
</div>
</div>
<div class="track">
<div class="track-base"></div>
<div id="eventBand"><span>Rainfall: 0–4 h</span></div>
<div id="played"></div>
<input
id="timeSlider"
type="range"
min="0"
max="12"
step="0.01"
value="0"
aria-label="Simulation time in hours"
>
<div id="needle"></div>
</div>
<div class="timeline-labels">
<span>0 h</span>
<span>4 h / rain ends</span>
<span>8 h</span>
<span>12 h</span>
</div>
</div>
<div id="cameraHelp">
<span>Drag to orbit · wheel to zoom</span>
<button id="resetCamera" type="button">Reset camera</button>
</div>
<div id="loading">BUILDING VOXEL WATERWORKS…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Declared assumptions and deterministic simulation
// ------------------------------------------------------------
const A = Object.freeze({
roofAreaM2: 120,
rainfallMm: 45,
rainHours: 4,
runoffCoefficient: 0.85,
tankCapacityL: 3000,
tankACapacityL: 1500,
tankBCapacityL: 1500,
initialStorageL: 600,
demandLPerHour: 300,
displayHours: 12
});
const grossRainTotalL = A.roofAreaM2 * A.rainfallMm;
const collectedTotalL = grossRainTotalL * A.runoffCoefficient;
const lossTotalL = grossRainTotalL - collectedTotalL;
const rainIntensityMmPerHour = A.rainfallMm / A.rainHours;
const demandPotentialTotalL = A.demandLPerHour * A.displayHours;
const SIM_DT_HOURS = 0.01;
const frameCount = Math.round(A.displayHours / SIM_DT_HOURS);
const frames = [];
const firstFrame = {
time: 0,
stored: A.initialStorageL,
gross: 0,
effective: 0,
loss: 0,
demandUsed: 0,
unmet: 0,
overflow: 0,
rainIntensity: rainIntensityMmPerHour,
grossRate: 0,
effectiveRate: 0,
lossRate: 0,
demandRate: 0,
overflowRate: 0
};
frames.push(firstFrame);
let stored = A.initialStorageL;
let gross = 0;
let effective = 0;
let loss = 0;
let demandUsed = 0;
let unmet = 0;
let overflow = 0;
for (let i = 1; i <= frameCount; i++) {
const previousTime = (i - 1) * SIM_DT_HOURS;
const isRaining = previousTime < A.rainHours;
const rainIntensity = isRaining ? rainIntensityMmPerHour : 0;
// 1 mm over 1 m² = 1 L.
const grossRate = rainIntensity * A.roofAreaM2;
const grossVolume = grossRate * SIM_DT_HOURS;
const effectiveVolume = grossVolume * A.runoffCoefficient;
const lossVolume = grossVolume - effectiveVolume;
gross += grossVolume;
effective += effectiveVolume;
loss += lossVolume;
const demandRequest = A.demandLPerHour * SIM_DT_HOURS;
const availableBeforeDemand = stored + effectiveVolume;
const servedThisStep = Math.min(demandRequest, availableBeforeDemand);
const unmetThisStep = demandRequest - servedThisStep;
demandUsed += servedThisStep;
unmet += unmetThisStep;
const afterDemand = availableBeforeDemand - servedThisStep;
const overflowThisStep = Math.max(0, afterDemand - A.tankCapacityL);
overflow += overflowThisStep;
stored = Math.min(A.tankCapacityL, afterDemand);
frames.push({
time: i * SIM_DT_HOURS,
stored,
gross,
effective,
loss,
demandUsed,
unmet,
overflow,
rainIntensity,
grossRate,
effectiveRate: effectiveVolume / SIM_DT_HOURS,
lossRate: lossVolume / SIM_DT_HOURS,
demandRate: servedThisStep / SIM_DT_HOURS,
overflowRate: overflowThisStep / SIM_DT_HOURS
});
}
const numericKeys = [
"time", "stored", "gross", "effective", "loss",
"demandUsed", "unmet", "overflow", "rainIntensity",
"grossRate", "effectiveRate", "lossRate",
"demandRate", "overflowRate"
];
function stateAt(timeHours) {
const position = THREE.MathUtils.clamp(
timeHours / SIM_DT_HOURS,
0,
frameCount
);
const index = Math.min(Math.floor(position), frameCount - 1);
const fraction = position - index;
const a = frames[index];
const b = frames[Math.min(index + 1, frameCount)];
const state = {};
for (const key of numericKeys) {
state[key] = THREE.MathUtils.lerp(a[key], b[key], fraction);
}
return state;
}
// ------------------------------------------------------------
// DOM references
// ------------------------------------------------------------
const $ = (id) => document.getElementById(id);
const ui = {
grossNow: $("grossNow"),
collectedNow: $("collectedNow"),
storedNow: $("storedNow"),
demandNow: $("demandNow"),
overflowNow: $("overflowNow"),
lossNow: $("lossNow"),
unmetNow: $("unmetNow"),
grossBar: $("grossBar"),
collectedBar: $("collectedBar"),
storedBar: $("storedBar"),
demandBar: $("demandBar"),
overflowBar: $("overflowBar"),
lossBar: $("lossBar"),
timeDisplay: $("timeDisplay"),
rainStatus: $("rainStatus"),
play: $("play"),
restart: $("restart"),
speed: $("speed"),
slider: $("timeSlider"),
played: $("played"),
needle: $("needle")
};
const formatL = (value) => `${Math.round(value).toLocaleString("en-US")} L`;
// ------------------------------------------------------------
// Renderer, scene, lights
// ------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce8e8);
scene.fog = new THREE.Fog(0xdce8e8, 35, 62);
const camera = new THREE.PerspectiveCamera(
42,
innerWidth / innerHeight,
0.1,
120
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
$("stage").appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xf7ffff, 0x708078, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff2d8, 3.1);
sun.position.set(-11, 20, 14);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -25;
sun.shadow.camera.right = 25;
sun.shadow.camera.top = 25;
sun.shadow.camera.bottom = -25;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 60;
sun.shadow.bias = -0.0003;
scene.add(sun);
const unitBox = new THREE.BoxGeometry(1, 1, 1);
function standardMaterial(color, extra = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.88,
metalness: 0.0,
flatShading: true,
...extra
});
}
const materials = {
ground: standardMaterial(0xffffff),
foundation: standardMaterial(0x71888b),
wall: standardMaterial(0xe8c985),
wallTrim: standardMaterial(0xf3deb0),
window: standardMaterial(0x497b91, { roughness: 0.32 }),
roof: standardMaterial(0xffffff),
roofEdge: standardMaterial(0x354f59),
pipe: standardMaterial(0x43565b),
pipeDemand: standardMaterial(0x6f558d),
pipeOverflow: standardMaterial(0xbf4a4a),
tankFrame: standardMaterial(0x567176),
tankBack: standardMaterial(0xaec2c1),
tankWater: standardMaterial(0x159ebd, {
roughness: 0.28,
transparent: true,
opacity: 0.83
}),
tankSurface: standardMaterial(0x60c6dc, {
roughness: 0.25,
transparent: true,
opacity: 0.94
}),
rain: standardMaterial(0x38a7d0, {
transparent: true,
opacity: 0.84,
roughness: 0.25
}),
flow: standardMaterial(0x62d3e8, {
emissive: 0x0a5a70,
emissiveIntensity: 0.22
}),
loss: standardMaterial(0xe09a2e),
overflow: standardMaterial(0xef5b55, {
emissive: 0x641616,
emissiveIntensity: 0.15
}),
demand: standardMaterial(0x8061a5),
cloud: standardMaterial(0xd6e0e1),
cloudDark: standardMaterial(0x9fb5ba),
trunk: standardMaterial(0x7d6348),
leaves: standardMaterial(0x5c8c72)
};
function box(parent, size, position, material, castShadow = true) {
const mesh = new THREE.Mesh(unitBox, material);
mesh.scale.set(size[0], size[1], size[2]);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// ------------------------------------------------------------
// Ground, building, and 120 m² voxel roof
// ------------------------------------------------------------
box(scene, [32, 0.3, 24], [0, -0.3, 0], materials.foundation);
const groundTiles = new THREE.InstancedMesh(
unitBox,
materials.ground,
16 * 12
);
const dummy = new THREE.Object3D();
let tileIndex = 0;
for (let row = 0; row < 12; row++) {
for (let col = 0; col < 16; col++) {
dummy.position.set(-15 + col * 2, -0.08, -11 + row * 2);
dummy.scale.set(1.96, 0.16, 1.96);
dummy.updateMatrix();
groundTiles.setMatrixAt(tileIndex, dummy.matrix);
groundTiles.setColorAt(
tileIndex,
new THREE.Color((row + col) % 2 === 0 ? 0xb9c9bf : 0xc7d3ca)
);
tileIndex++;
}
}
groundTiles.instanceMatrix.needsUpdate = true;
groundTiles.instanceColor.needsUpdate = true;
groundTiles.receiveShadow = true;
scene.add(groundTiles);
const building = new THREE.Group();
scene.add(building);
box(building, [8.7, 0.35, 10.7], [0, 0.17, 0], materials.foundation);
box(building, [8.4, 4.0, 10.4], [0, 2.15, 0], materials.wall);
box(building, [8.65, 0.25, 10.65], [0, 4.12, 0], materials.wallTrim);
// Front details.
for (const x of [-2.8, -1.1, 1.1, 2.8]) {
box(building, [0.95, 1.15, 0.14], [x, 2.55, 5.24], materials.window);
box(building, [1.12, 0.13, 0.2], [x, 2.0, 5.30], materials.wallTrim);
}
box(building, [1.35, 2.4, 0.18], [0, 1.35, 5.30], materials.roofEdge);
box(building, [0.12, 0.12, 0.18], [0.45, 1.4, 5.42], materials.wallTrim);
// Voxel roof: 10 columns × 12 rows = 120 one-square-metre tiles.
const roofTiles = new THREE.InstancedMesh(
unitBox,
materials.roof,
120
);
let roofIndex = 0;
for (let row = 0; row < 12; row++) {
for (let col = 0; col < 10; col++) {
dummy.position.set(-10.5 + col, 4.36, -5.5 + row);
dummy.scale.set(0.96, 0.25, 0.96);
dummy.updateMatrix();
roofTiles.setMatrixAt(roofIndex, dummy.matrix);
roofTiles.setColorAt(
roofIndex,
new THREE.Color((row + col) % 3 === 0 ? 0x45616b : 0x38535e)
);
roofIndex++;
}
}
roofTiles.instanceMatrix.needsUpdate = true;
roofTiles.instanceColor.needsUpdate = true;
roofTiles.castShadow = true;
roofTiles.receiveShadow = true;
building.add(roofTiles);
// Gutter along the near/right edge.
box(scene, [0.28, 0.28, 12.1], [-0.85, 4.48, 0], materials.roofEdge);
// ------------------------------------------------------------
// Tanks
// ------------------------------------------------------------
function createTank(x) {
const group = new THREE.Group();
group.position.set(x, 0, 0);
scene.add(group);
box(group, [3.3, 0.35, 3.3], [0, 0.18, 0], materials.foundation);
box(group, [3.15, 3.1, 0.22], [0, 1.82, -1.55], materials.tankBack);
box(group, [0.22, 3.1, 3.15], [-1.55, 1.82, 0], materials.tankFrame);
box(group, [0.22, 3.1, 3.15], [1.55, 1.82, 0], materials.tankFrame);
box(group, [0.25, 3.1, 0.25], [-1.55, 1.82, 1.55], materials.tankFrame);
box(group, [0.25, 3.1, 0.25], [1.55, 1.82, 1.55], materials.tankFrame);
box(group, [3.3, 0.25, 0.28], [0, 3.32, 1.55], materials.tankFrame);
box(group, [3.3, 0.25, 0.28], [0, 3.32, -1.55], materials.tankFrame);
box(group, [3.3, 0.28, 0.25], [0, 0.42, 1.55], materials.tankFrame);
const water = box(
group,
[2.65, 1, 2.65],
[0, 0.92, 0],
materials.tankWater,
false
);
const surface = box(
group,
[2.68, 0.07, 2.68],
[0, 1.42, 0],
materials.tankSurface,
false
);
// Front level marks.
for (let i = 0; i < 5; i++) {
box(
group,
[0.45, 0.06, 0.08],
[1.68, 0.7 + i * 0.58, 1.58],
materials.wallTrim,
false
);
}
return { group, water, surface };
}
const tankA = createTank(3.6);
const tankB = createTank(8.0);
function updateTank(tank, volumeL, capacityL) {
const fraction = THREE.MathUtils.clamp(volumeL / capacityL, 0, 1);
const height = Math.max(0.001, fraction * 2.55);
const bottom = 0.45;
tank.water.visible = fraction > 0.0005;
tank.surface.visible = fraction > 0.0005;
tank.water.scale.set(2.65, height, 2.65);
tank.water.position.set(0, bottom + height / 2, 0);
tank.surface.position.set(0, bottom + height, 0);
}
// ------------------------------------------------------------
// Demand building and voxel landscaping
// ------------------------------------------------------------
const demandBuilding = new THREE.Group();
demandBuilding.position.set(8, 0, -7);
scene.add(demandBuilding);
box(demandBuilding, [4.2, 0.3, 3.2], [0, 0.15, 0], materials.foundation);
box(demandBuilding, [4.0, 2.8, 3.0], [0, 1.6, 0], materials.wall);
box(demandBuilding, [4.4, 0.35, 3.4], [0, 3.18, 0], materials.demand);
box(demandBuilding, [3.2, 0.28, 3.0], [0, 3.48, 0], materials.demand);
box(demandBuilding, [1.1, 1.0, 0.14], [-0.8, 1.9, 1.54], materials.window);
box(demandBuilding, [1.1, 1.0, 0.14], [0.8, 1.9, 1.54], materials.window);
box(demandBuilding, [0.95, 1.9, 0.14], [0, 1.1, 1.54], materials.demand);
function addTree(x, z, scale = 1) {
const tree = new THREE.Group();
tree.position.set(x, 0, z);
tree.scale.setScalar(scale);
scene.add(tree);
box(tree, [0.45, 1.7, 0.45], [0, 0.85, 0], materials.trunk);
box(tree, [2.1, 1.4, 2.0], [0, 2.2, 0], materials.leaves);
box(tree, [1.4, 1.3, 1.5], [-0.65, 3.0, 0.1], materials.leaves);
box(tree, [1.3, 1.2, 1.4], [0.65, 3.05, -0.1], materials.leaves);
}
addTree(-13.4, 4.8, 0.9);
addTree(-13.7, -5.5, 1.05);
addTree(13.2, -8.3, 0.9);
addTree(-2.5, -9.4, 0.75);
// ------------------------------------------------------------
// Square pipe routes and moving flow blocks
// ------------------------------------------------------------
function makePipeRoute(points, material, width = 0.18) {
for (let i = 0; i < points.length - 1; i++) {
const a = new THREE.Vector3(...points[i]);
const b = new THREE.Vector3(...points[i + 1]);
const direction = b.clone().sub(a);
const length = direction.length();
const midpoint = a.clone().add(b).multiplyScalar(0.5);
const pipe = box(
scene,
[width, length, width],
midpoint.toArray(),
material
);
pipe.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
}
}
const roofRoute = [
[-0.85, 4.48, 5.6],
[-0.85, 0.82, 5.6],
[2.1, 0.82, 5.6],
[2.1, 0.82, 1.4],
[3.6, 0.82, 1.4]
];
const tankLinkRoute = [
[5.15, 0.82, 1.4],
[6.5, 0.82, 1.4]
];
const demandRoute = [
[3.6, 0.82, -1.4],
[6.3, 0.82, -4.4],
[8.0, 0.82, -5.55]
];
const overflowRoute = [
[9.55, 0.82, 0],
[11.2, 0.82, 0],
[11.2, 0.2, 3.4]
];
makePipeRoute(roofRoute, materials.pipe);
makePipeRoute(tankLinkRoute, materials.pipe);
makePipeRoute(demandRoute, materials.pipeDemand);
makePipeRoute(overflowRoute, materials.pipeOverflow);
// Overflow drain.
box(scene, [1.55, 0.12, 1.55], [11.2, 0.06, 3.55], materials.roofEdge);
for (let i = 0; i < 5; i++) {
box(
scene,
[1.35, 0.08, 0.1],
[11.2, 0.15, 2.95 + i * 0.3],
materials.pipe
);
}
function createFlow(route, material, count = 12, size = 0.16) {
const points = route.map((point) => new THREE.Vector3(...point));
const segments = [];
let totalLength = 0;
for (let i = 0; i < points.length - 1; i++) {
const length = points[i].distanceTo(points[i + 1]);
segments.push({
start: points[i],
end: points[i + 1],
length,
offset: totalLength
});
totalLength += length;
}
const meshes = [];
for (let i = 0; i < count; i++) {
const mesh = box(
scene,
[size, size, size],
[0, 0, 0],
material,
false
);
mesh.visible = false;
meshes.push(mesh);
}
return { segments, totalLength, meshes, phase: 0 };
}
const roofFlow = createFlow(roofRoute, materials.flow, 15, 0.14);
const demandFlow = createFlow(demandRoute, materials.demand, 12, 0.14);
const overflowFlow = createFlow(overflowRoute, materials.overflow, 12, 0.16);
function sampleFlowRoute(flow, u) {
let distance = ((u % 1) + 1) % 1 * flow.totalLength;
for (const segment of flow.segments) {
if (distance <= segment.length) {
const t = segment.length === 0 ? 0 : distance / segment.length;
return segment.start.clone().lerp(segment.end, t);
}
distance -= segment.length;
}
return flow.segments[flow.segments.length - 1].end.clone();
}
function updateFlow(flow, active, visualDt, rate = 0.28) {
flow.phase = (flow.phase + visualDt * rate) % 1;
flow.meshes.forEach((mesh, index) => {
mesh.visible = active;
if (active) {
const u = (index / flow.meshes.length + flow.phase) % 1;
mesh.position.copy(sampleFlowRoute(flow, u));
}
});
}
// ------------------------------------------------------------
// Rain cloud, voxel rain, runoff loss blocks, and splashes
// ------------------------------------------------------------
const cloud = new THREE.Group();
cloud.position.set(-6, 9.55, -0.8);
scene.add(cloud);
const cloudBlocks = [
[-2.0, 0.0, 0.0, 2.1, 1.0, 1.5],
[-0.6, 0.25, 0.1, 2.2, 1.4, 1.8],
[1.0, 0.05, 0.0, 2.0, 1.1, 1.5],
[-0.4, -0.55, 0.2, 3.3, 0.65, 1.7]
];
for (const block of cloudBlocks) {
box(
cloud,
[block[3], block[4], block[5]],
[block[0], block[1], block[2]],
materials.cloud
);
}
const rainDrops = [];
for (let i = 0; i < 180; i++) {
const mesh = box(
scene,
[0.065, 0.34, 0.065],
[0, 0, 0],
materials.rain,
false
);
rainDrops.push({
mesh,
x: THREE.MathUtils.randFloat(-10.8, -1.2),
z: THREE.MathUtils.randFloat(-5.8, 5.8),
y: THREE.MathUtils.randFloat(4.8, 10.2),
speed: THREE.MathUtils.randFloat(5.2, 8.2)
});
}
const splashes = [];
for (let i = 0; i < 26; i++) {
const mesh = box(
scene,
[0.12, 0.12, 0.12],
[0, 0, 0],
materials.flow,
false
);
splashes.push({
mesh,
x: THREE.MathUtils.randFloat(-10.5, -1.5),
z: THREE.MathUtils.randFloat(-5.5, 5.5),
phase: Math.random() * Math.PI * 2
});
}
const lossDrops = [];
for (let i = 0; i < 24; i++) {
const mesh = box(
scene,
[0.13, 0.22, 0.13],
[0, 0, 0],
materials.loss,
false
);
lossDrops.push({
mesh,
x: THREE.MathUtils.randFloat(-10.5, -1.5),
z: THREE.MathUtils.randFloat(5.8, 6.4),
y: THREE.MathUtils.randFloat(0.2, 4.4),
speed: THREE.MathUtils.randFloat(2.4, 4.0)
});
}
// ------------------------------------------------------------
// Projected HTML labels
// ------------------------------------------------------------
const labelRoot = $("labels");
const labels = [];
function createLabel(className, anchor, color) {
const element = document.createElement("div");
element.className = `anno ${className}`;
element.style.setProperty("--c", color);
labelRoot.appendChild(element);
const label = {
element,
anchor: new THREE.Vector3(...anchor)
};
labels.push(label);
return label;
}
const rainLabel = createLabel(
"rain-label",
[-6, 10.7, -0.8],
"#248fb8"
);
const lossLabel = createLabel(
"loss-label",
[-6.0, 3.2, 6.4],
"#d99024"
);
const tankALabel = createLabel(
"tank-a-label",
[3.6, 4.05, 1.3],
"#159ebd"
);
const tankBLabel = createLabel(
"tank-b-label",
[8.0, 4.05, 1.3],
"#159ebd"
);
const overflowLabel = createLabel(
"overflow-label",
[11.2, 2.5, 2.0],
"#df5353"
);
const demandLabel = createLabel(
"demand-label",
[8.0, 4.2, -6.7],
"#73569a"
);
function updateLabelContents(state) {
const tankAVolume = state.stored / 2;
const tankBVolume = state.stored / 2;
rainLabel.element.innerHTML = `
<span class="kicker">Declared rain event</span>
<strong>45 mm / 4 h</strong>
<small>120 m² roof · ${rainIntensityMmPerHour} mm/h</small>
`;
lossLabel.element.innerHTML = `
<span class="kicker">Uncollected runoff loss</span>
<strong>${formatL(state.loss)}</strong>
<small>15% of gross rainfall</small>
`;
tankALabel.element.innerHTML = `
<span class="kicker">Tank A</span>
<strong>${formatL(tankAVolume)}</strong>
<small>of 1,500 L capacity</small>
`;
tankBLabel.element.innerHTML = `
<span class="kicker">Tank B</span>
<strong>${formatL(tankBVolume)}</strong>
<small>of 1,500 L capacity</small>
`;
overflowLabel.element.innerHTML = `
<span class="kicker">Explicit overflow</span>
<strong>${formatL(state.overflow)}</strong>
<small>${state.overflowRate > 0.01 ? "OVERFLOWING NOW" : "No overflow now"}</small>
`;
demandLabel.element.innerHTML = `
<span class="kicker">Demand service</span>
<strong>${formatL(state.demandUsed)} used</strong>
<small>300 L/h · ${formatL(state.unmet)} unmet</small>
`;
}
function positionLabels() {
const width = innerWidth;
const height = innerHeight;
for (const label of labels) {
const projected = label.anchor.clone().project(camera);
const visible =
projected.z >= -1 &&
projected.z <= 1 &&
projected.x > -1.15 &&
projected.x < 1.15 &&
projected.y > -1.15 &&
projected.y < 1.15;
label.element.style.display = visible ? "block" : "none";
if (!visible) continue;
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
label.element.style.left = `${x}px`;
label.element.style.top = `${y}px`;
}
}
// ------------------------------------------------------------
// Camera controls implemented without Three.js addons
// ------------------------------------------------------------
const cameraTarget = new THREE.Vector3(-0.4, 2.65, 0);
let cameraYaw = 0.50;
let cameraPitch = 1.02;
let cameraRadius = 30;
function updateCamera() {
const horizontal = Math.sin(cameraPitch) * cameraRadius;
camera.position.set(
cameraTarget.x + horizontal * Math.sin(cameraYaw),
cameraTarget.y + Math.cos(cameraPitch) * cameraRadius,
cameraTarget.z + horizontal * Math.cos(cameraYaw)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraYaw = 0.50;
cameraPitch = 1.02;
cameraRadius = 30;
cameraTarget.set(-0.4, 2.65, 0);
updateCamera();
}
const pointers = new Map();
let pinchDistance = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 2) {
const values = [...pointers.values()];
pinchDistance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
const pointer = pointers.get(event.pointerId);
if (!pointer) return;
const dx = event.clientX - pointer.x;
const dy = event.clientY - pointer.y;
pointer.x = event.clientX;
pointer.y = event.clientY;
if (pointers.size === 2) {
const values = [...pointers.values()];
const distance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
if (distance > 0 && pinchDistance > 0) {
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * (pinchDistance / distance),
17,
48
);
pinchDistance = distance;
updateCamera();
}
} else {
cameraYaw -= dx * 0.006;
cameraPitch = THREE.MathUtils.clamp(
cameraPitch + dy * 0.005,
0.38,
1.43
);
updateCamera();
}
});
function endPointer(event) {
pointers.delete(event.pointerId);
if (pointers.size < 2) pinchDistance = 0;
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
17,
48
);
updateCamera();
},
{ passive: false }
);
$("resetCamera").addEventListener("click", resetCamera);
// ------------------------------------------------------------
// Playback and UI
// ------------------------------------------------------------
let simulationTime = 0;
let playing = true;
let playbackSpeed = 4;
const simulatedHoursPerRealSecond = 0.15;
function updatePlayButton() {
ui.play.textContent = playing
? "Pause"
: simulationTime >= A.displayHours
? "Replay"
: "Play";
ui.play.setAttribute("aria-pressed", String(playing));
}
ui.play.addEventListener("click", () => {
if (!playing && simulationTime >= A.displayHours) {
simulationTime = 0;
}
playing = !playing;
updatePlayButton();
});
ui.restart.addEventListener("click", () => {
simulationTime = 0;
playing = true;
updatePlayButton();
});
ui.speed.addEventListener("change", () => {
playbackSpeed = Number(ui.speed.value);
});
ui.slider.addEventListener("input", () => {
simulationTime = Number(ui.slider.value);
playing = false;
updatePlayButton();
});
function updateUI(state) {
const totalMinutes = Math.round(state.time * 60);
const hours = Math.floor(totalMinutes / 60);
const minutes = totalMinutes % 60;
ui.timeDisplay.textContent =
`${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}`;
ui.rainStatus.textContent =
state.rainIntensity > 0.01 ? "/ RAIN ACTIVE" : "/ DRY";
ui.grossNow.textContent = formatL(state.gross);
ui.collectedNow.textContent = formatL(state.effective);
ui.storedNow.textContent = formatL(state.stored);
ui.demandNow.textContent = formatL(state.demandUsed);
ui.overflowNow.textContent = formatL(state.overflow);
ui.lossNow.textContent = formatL(state.loss);
ui.unmetNow.textContent = formatL(state.unmet);
ui.grossBar.style.width =
`${100 * state.gross / grossRainTotalL}%`;
ui.collectedBar.style.width =
`${100 * state.effective / collectedTotalL}%`;
ui.storedBar.style.width =
`${100 * state.stored / A.tankCapacityL}%`;
ui.demandBar.style.width =
`${100 * state.demandUsed / demandPotentialTotalL}%`;
ui.overflowBar.style.width =
`${100 * state.overflow / 990}%`;
ui.lossBar.style.width =
`${100 * state.loss / lossTotalL}%`;
const timelinePercent = 100 * state.time / A.displayHours;
ui.played.style.width = `${timelinePercent}%`;
ui.needle.style.left = `${timelinePercent}%`;
ui.slider.value = state.time.toFixed(2);
updateLabelContents(state);
}
// ------------------------------------------------------------
// Scene animation
// ------------------------------------------------------------
function updateScene(state, visualDt, realTime) {
const raining = state.rainIntensity > 0.01;
cloud.position.x = -6 + Math.sin(realTime * 0.00035) * 0.2;
cloud.position.y = 9.55 + Math.sin(realTime * 0.0007) * 0.05;
for (const drop of rainDrops) {
drop.mesh.visible = raining;
if (!raining) continue;
drop.mesh.position.set(drop.x, drop.y, drop.z);
drop.y -= visualDt * drop.speed;
if (drop.y < 4.62) {
drop.y = THREE.MathUtils.randFloat(8.2, 10.5);
drop.x = THREE.MathUtils.randFloat(-10.8, -1.2);
drop.z = THREE.MathUtils.randFloat(-5.8, 5.8);
}
}
for (const splash of splashes) {
splash.mesh.visible = raining;
if (!raining) continue;
const pulse = 0.5 + 0.5 * Math.sin(realTime * 0.012 + splash.phase);
const size = 0.07 + pulse * 0.13;
splash.mesh.scale.set(size, size, size);
splash.mesh.position.set(splash.x, 4.54, splash.z);
}
for (const drop of lossDrops) {
drop.mesh.visible = raining;
if (!raining) continue;
drop.mesh.position.set(drop.x, drop.y, drop.z);
drop.y -= visualDt * drop.speed;
if (drop.y < 0.15) {
drop.y = THREE.MathUtils.randFloat(3.7, 4.5);
drop.x = THREE.MathUtils.randFloat(-10.5, -1.5);
drop.z = THREE.MathUtils.randFloat(5.8, 6.4);
}
}
updateTank(tankA, state.stored / 2, A.tankACapacityL);
updateTank(tankB, state.stored / 2, A.tankBCapacityL);
updateFlow(roofFlow, raining, visualDt, 0.32);
updateFlow(demandFlow, state.demandRate > 0.01, visualDt, 0.23);
updateFlow(
overflowFlow,
state.overflowRate > 0.01,
visualDt,
0.38
);
}
// ------------------------------------------------------------
// Main loop
// ------------------------------------------------------------
let previousTime = performance.now();
let lastUIUpdate = 0;
function animate(now) {
requestAnimationFrame(animate);
const delta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (playing) {
simulationTime +=
delta * simulatedHoursPerRealSecond * playbackSpeed;
if (simulationTime >= A.displayHours) {
simulationTime = A.displayHours;
playing = false;
updatePlayButton();
}
}
const state = stateAt(simulationTime);
const visualDt = playing
? delta * Math.min(playbackSpeed, 2)
: 0;
updateScene(state, visualDt, now);
if (now - lastUIUpdate > 70) {
updateUI(state);
lastUIUpdate = now;
}
positionLabels();
renderer.render(scene, camera);
}
function onResize() {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
}
addEventListener("resize", onResize);
resetCamera();
updateUI(stateAt(0));
updateScene(stateAt(0), 0, performance.now());
$("loading").remove();
requestAnimationFrame(animate);
</script>
</body>
</html>
```