Prompt specification
Build or customize the Three.js 3D scene "Impervious and Permeable Surface Comparison" 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: Impervious and Permeable Surface Comparison
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/impervious-and-permeable-surface-comparison-x3982
Scene Description Prompt:
Use Three.js from cdnjs to animate equal synthetic rainfall on two surface models with stated infiltration rates. Track runoff and infiltration as separate volumes under explicitly simplified assumptions. Deliver one self-contained HTML file with a 3D cutaway.
Working Three.js Starter (impervious-and-permeable-surface-comparison-x3982):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Twin Catchment Rainfall Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(9, 22, 38, 0.88);
--panel-border: rgba(148, 180, 210, 0.16);
--text: #e7f0f8;
--muted: #91a7ba;
--cyan: #25d5e8;
--blue: #5c8dff;
--amber: #f4a261;
--violet: #b990ff;
--green: #7fc98a;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene.dragging { cursor: grabbing; }
.topbar {
position: fixed;
z-index: 5;
top: 18px;
left: 20px;
pointer-events: none;
}
.eyebrow {
color: var(--cyan);
font-size: 11px;
font-weight: 750;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 4px 0 5px;
font-size: clamp(21px, 2.4vw, 34px);
line-height: 1.05;
letter-spacing: -0.035em;
}
.subtitle {
color: var(--muted);
font-size: 12px;
}
.legend {
display: flex;
gap: 8px;
flex-wrap: wrap;
margin-top: 10px;
}
.legend span, .chip {
border: 1px solid rgba(255,255,255,.11);
background: rgba(4,12,22,.62);
border-radius: 999px;
padding: 5px 9px;
color: #c5d3df;
font-size: 10px;
backdrop-filter: blur(8px);
}
.dot {
display: inline-block;
width: 7px;
height: 7px;
margin-right: 6px;
border-radius: 50%;
vertical-align: 1px;
}
.panel {
position: fixed;
z-index: 6;
top: 18px;
right: 18px;
width: 366px;
max-height: calc(100vh - 112px);
overflow-y: auto;
padding: 16px;
border: 1px solid var(--panel-border);
border-radius: 17px;
background: var(--panel);
box-shadow: 0 20px 55px rgba(0,0,0,.32);
backdrop-filter: blur(18px) saturate(125%);
scrollbar-width: thin;
scrollbar-color: #31495e transparent;
}
.panel h2 {
margin: 0 0 11px;
font-size: 14px;
letter-spacing: .02em;
}
.storm-summary {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-bottom: 12px;
}
.summary-cell {
padding: 9px 8px;
border: 1px solid rgba(255,255,255,.08);
border-radius: 10px;
background: rgba(255,255,255,.035);
}
.summary-cell small {
display: block;
color: var(--muted);
font-size: 9px;
text-transform: uppercase;
letter-spacing: .08em;
}
.summary-cell b {
display: block;
margin-top: 3px;
font-size: 13px;
}
.model-card {
margin-top: 9px;
padding: 12px;
border: 1px solid rgba(255,255,255,.085);
border-radius: 13px;
background: rgba(255,255,255,.028);
}
.model-head {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 10px;
margin-bottom: 10px;
}
.model-title {
font-size: 13px;
font-weight: 720;
}
.model-subtitle {
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.model-badge {
flex: none;
border-radius: 999px;
padding: 5px 8px;
font-size: 10px;
font-weight: 750;
white-space: nowrap;
}
.model-badge.a {
color: #a8e0ad;
background: rgba(92,141,87,.15);
border: 1px solid rgba(127,201,138,.24);
}
.model-badge.b {
color: #f4bd88;
background: rgba(180,111,64,.15);
border: 1px solid rgba(244,162,97,.24);
}
.metric {
margin-top: 8px;
}
.metric-line {
display: flex;
justify-content: space-between;
align-items: baseline;
gap: 10px;
font-size: 10px;
}
.metric-line span { color: var(--muted); }
.metric-line b { font-size: 12px; font-variant-numeric: tabular-nums; }
.track {
height: 5px;
margin-top: 5px;
overflow: hidden;
border-radius: 999px;
background: rgba(255,255,255,.065);
}
.fill {
height: 100%;
width: 0;
border-radius: inherit;
transition: width .08s linear;
}
.fill.runoff-a { background: var(--cyan); }
.fill.runoff-b { background: var(--amber); }
.fill.infil-a { background: var(--blue); }
.fill.infil-b { background: var(--violet); }
.balance {
margin-top: 9px;
padding-top: 8px;
border-top: 1px solid rgba(255,255,255,.07);
color: var(--muted);
font-size: 9px;
line-height: 1.45;
}
.chart-wrap {
margin-top: 13px;
}
.chart-title {
display: flex;
justify-content: space-between;
gap: 8px;
font-size: 10px;
color: #c7d5e1;
}
#chart {
display: block;
width: 100%;
height: 154px;
margin-top: 5px;
border-radius: 10px;
background: rgba(0,0,0,.12);
}
.chart-legend {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 5px 10px;
margin-top: 7px;
color: var(--muted);
font-size: 9px;
}
.chart-legend .solid {
display: inline-block;
width: 16px;
height: 2px;
margin: 0 5px 3px 0;
background: currentColor;
}
.chart-legend .dashed {
display: inline-block;
width: 16px;
height: 0;
margin: 0 5px 3px 0;
border-top: 2px dashed currentColor;
}
.assumptions {
margin-top: 13px;
padding: 11px;
border-radius: 11px;
background: rgba(255,255,255,.028);
color: var(--muted);
font-size: 10px;
line-height: 1.52;
}
.assumptions strong {
display: block;
margin-bottom: 5px;
color: #d7e2eb;
font-size: 10px;
text-transform: uppercase;
letter-spacing: .08em;
}
.assumptions ul {
margin: 0;
padding-left: 15px;
}
.transport {
position: fixed;
z-index: 7;
left: 20px;
right: 402px;
bottom: 18px;
display: flex;
align-items: center;
gap: 11px;
padding: 11px 13px;
border: 1px solid var(--panel-border);
border-radius: 15px;
background: rgba(7, 17, 31, .84);
box-shadow: 0 15px 40px rgba(0,0,0,.27);
backdrop-filter: blur(15px);
}
button, select {
color: var(--text);
font: inherit;
}
button {
border: 1px solid rgba(255,255,255,.12);
border-radius: 9px;
background: rgba(255,255,255,.075);
cursor: pointer;
transition: background .15s, border-color .15s;
}
button:hover {
background: rgba(255,255,255,.13);
border-color: rgba(255,255,255,.22);
}
#play {
min-width: 88px;
padding: 9px 11px;
color: #05202a;
font-size: 12px;
font-weight: 780;
background: var(--cyan);
border-color: transparent;
}
#reset {
width: 38px;
height: 36px;
font-size: 18px;
}
#timeline {
flex: 1;
min-width: 70px;
accent-color: var(--cyan);
cursor: pointer;
}
#time {
min-width: 93px;
color: #dce7f0;
font-size: 11px;
font-variant-numeric: tabular-nums;
text-align: right;
}
#speed {
padding: 8px 7px;
border: 1px solid rgba(255,255,255,.12);
border-radius: 8px;
background: #102239;
font-size: 11px;
}
.camera-tools {
position: fixed;
z-index: 6;
left: 20px;
bottom: 86px;
display: flex;
gap: 6px;
}
.camera-tools button {
padding: 7px 9px;
color: #c8d7e4;
font-size: 10px;
background: rgba(7,17,31,.72);
backdrop-filter: blur(10px);
}
#status {
min-width: 54px;
text-align: center;
color: var(--cyan);
}
@media (max-width: 900px) {
.panel {
top: auto;
bottom: 91px;
right: 12px;
width: min(360px, calc(100vw - 24px));
max-height: 43vh;
}
.transport {
left: 12px;
right: 12px;
bottom: 12px;
}
.camera-tools {
left: 12px;
bottom: 85px;
}
.topbar {
top: 13px;
left: 14px;
max-width: calc(100vw - 28px);
}
.subtitle { display: none; }
}
@media (max-width: 560px) {
.legend { display: none; }
.panel { max-height: 36vh; }
#time { min-width: 74px; font-size: 10px; }
#play { min-width: 70px; }
#speed { max-width: 65px; }
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive 3D rainfall and runoff cutaway"></canvas>
<header class="topbar">
<div class="eyebrow">Synthetic Hydrology Laboratory</div>
<h1>Twin Catchment Rainfall</h1>
<div class="subtitle">Equal rainfall · separate runoff and infiltration accounting · interactive 3D cutaway</div>
<div class="legend">
<span><i class="dot" style="background:#25d5e8"></i>Runoff</span>
<span><i class="dot" style="background:#5c8dff"></i>Infiltration</span>
<span><i class="dot" style="background:#9ec5ff"></i>Rain</span>
</div>
</header>
<aside class="panel">
<h2>Storm & Volume Balance</h2>
<div class="storm-summary">
<div class="summary-cell">
<small>Rain intensity</small>
<b>60 mm/h</b>
</div>
<div class="summary-cell">
<small>Duration</small>
<b>30 min</b>
</div>
<div class="summary-cell">
<small>Each area</small>
<b>100 m²</b>
</div>
</div>
<div class="model-card">
<div class="model-head">
<div>
<div class="model-title">A · Open loam surface</div>
<div class="model-subtitle">Gentle swale and vegetated/open surface</div>
</div>
<div class="model-badge a">18 mm/h</div>
</div>
<div class="metric">
<div class="metric-line">
<span>Rain received</span><b><span id="aRain">0.000</span> m³</b>
</div>
<div class="track"><div class="fill runoff-a" id="aRainBar"></div></div>
</div>
<div class="metric">
<div class="metric-line">
<span>Runoff to outlet</span><b><span id="aRunoff">0.000</span> m³</b>
</div>
<div class="track"><div class="fill runoff-a" id="aRunoffBar"></div></div>
</div>
<div class="metric">
<div class="metric-line">
<span>Infiltrated into soil</span><b><span id="aInfil">0.000</span> m³</b>
</div>
<div class="track"><div class="fill infil-a" id="aInfilBar"></div></div>
</div>
<div class="balance" id="aBalance">Rain = runoff + infiltration</div>
</div>
<div class="model-card">
<div class="model-head">
<div>
<div class="model-title">B · Compacted clay surface</div>
<div class="model-subtitle">Smooth, low-permeability crowned surface</div>
</div>
<div class="model-badge b">5 mm/h</div>
</div>
<div class="metric">
<div class="metric-line">
<span>Rain received</span><b><span id="bRain">0.000</span> m³</b>
</div>
<div class="track"><div class="fill runoff-b" id="bRainBar"></div></div>
</div>
<div class="metric">
<div class="metric-line">
<span>Runoff to outlet</span><b><span id="bRunoff">0.000</span> m³</b>
</div>
<div class="track"><div class="fill runoff-b" id="bRunoffBar"></div></div>
</div>
<div class="metric">
<div class="metric-line">
<span>Infiltrated into soil</span><b><span id="bInfil">0.000</span> m³</b>
</div>
<div class="track"><div class="fill infil-b" id="bInfilBar"></div></div>
</div>
<div class="balance" id="bBalance">Rain = runoff + infiltration</div>
</div>
<div class="chart-wrap">
<div class="chart-title">
<span>Cumulative volume</span>
<span>m³</span>
</div>
<canvas id="chart"></canvas>
<div class="chart-legend">
<span style="color:#25d5e8"><i class="solid"></i>A runoff</span>
<span style="color:#5c8dff"><i class="dashed"></i>A infiltration</span>
<span style="color:#f4a261"><i class="solid"></i>B runoff</span>
<span style="color:#b990ff"><i class="dashed"></i>B infiltration</span>
</div>
</div>
<div class="assumptions">
<strong>Explicit simplified assumptions</strong>
<ul>
<li>Both 100 m² catchments receive exactly 60 mm/h for 30 minutes.</li>
<li>Infiltration capacities are constant at 18 and 5 mm/h and are not limited by soil moisture.</li>
<li>Excess rain becomes runoff immediately: there is no routing delay, depression storage, or infiltration of stored runoff.</li>
<li>No evaporation, initial soil moisture, subsurface flow, or post-storm drainage is modeled.</li>
<li>Volumes are cumulative: rainfall = runoff + infiltration. Geometry and particles are qualitative.</li>
</ul>
</div>
</aside>
<div class="camera-tools">
<button id="viewOverview">Overview</button>
<button id="viewCutaway">Cutaway</button>
<button id="viewTop">Top</button>
</div>
<div class="transport">
<button id="play" aria-label="Play or pause simulation">▶ Play</button>
<button id="reset" aria-label="Reset simulation">↺</button>
<input id="timeline" type="range" min="0" max="1800" step="1" value="0" aria-label="Storm timeline">
<div id="time">00:00 / 30:00</div>
<select id="speed" aria-label="Playback speed">
<option value="1">1×</option>
<option value="10">10×</option>
<option value="30" selected>30×</option>
<option value="60">60×</option>
</select>
<div class="chip" id="status">LIVE</div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
/* -------------------------- Configuration -------------------------- */
const RAIN_MM_H = 60;
const STORM_MINUTES = 30;
const AREA_M2 = 100;
const DURATION_SECONDS = STORM_MINUTES * 60;
const MODELS = [
{
id: "A",
centerX: -8,
width: 13,
depth: 10,
infiltration: 18,
surfaceColor: 0x58734d,
label: "A · OPEN LOAM",
rateLabel: "infiltration capacity 18 mm/h"
},
{
id: "B",
centerX: 8,
width: 13,
depth: 10,
infiltration: 5,
surfaceColor: 0x8a6046,
label: "B · COMPACTED CLAY",
rateLabel: "infiltration capacity 5 mm/h"
}
];
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 44, 82);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
150
);
/* ---------------------- Direct camera controls ---------------------- */
const cameraState = {
target: new THREE.Vector3(0, -0.45, 0),
radius: 33,
theta: 0.48,
phi: 0.93
};
function updateCamera() {
const s = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x + cameraState.radius * s * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z + cameraState.radius * s * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
updateCamera();
let pointerDown = false;
let pointerX = 0;
let pointerY = 0;
let shiftPressed = false;
canvas.addEventListener("pointerdown", event => {
pointerDown = true;
pointerX = event.clientX;
pointerY = event.clientY;
shiftPressed = event.shiftKey;
canvas.setPointerCapture(event.pointerId);
canvas.classList.add("dragging");
});
canvas.addEventListener("pointermove", event => {
if (!pointerDown) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
if (shiftPressed) {
const right = new THREE.Vector3(
Math.cos(cameraState.theta),
0,
-Math.sin(cameraState.theta)
);
const forward = new THREE.Vector3(
-Math.sin(cameraState.theta),
0,
-Math.cos(cameraState.theta)
);
cameraState.target.addScaledVector(right, -dx * 0.012);
cameraState.target.addScaledVector(forward, -dy * 0.012);
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.22,
1.48
);
}
updateCamera();
});
function releasePointer(event) {
pointerDown = false;
canvas.classList.remove("dragging");
if (event && canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", releasePointer);
canvas.addEventListener("pointercancel", releasePointer);
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
16,
55
);
updateCamera();
}, { passive: false });
function setView(name) {
if (name === "overview") {
cameraState.target.set(0, -0.45, 0);
cameraState.radius = 33;
cameraState.theta = 0.48;
cameraState.phi = 0.93;
} else if (name === "cutaway") {
cameraState.target.set(0, -0.9, 0);
cameraState.radius = 28;
cameraState.theta = 0.08;
cameraState.phi = 1.24;
} else {
cameraState.target.set(0, -0.2, 0);
cameraState.radius = 34;
cameraState.theta = 0.15;
cameraState.phi = 0.34;
}
updateCamera();
}
document.querySelector("#viewOverview").onclick = () => setView("overview");
document.querySelector("#viewCutaway").onclick = () => setView("cutaway");
document.querySelector("#viewTop").onclick = () => setView("top");
/* --------------------------- Scene lights -------------------------- */
scene.add(new THREE.HemisphereLight(0xbcd8ff, 0x263226, 2.0));
const sun = new THREE.DirectionalLight(0xffffff, 3.0);
sun.position.set(12, 24, 17);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -25;
sun.shadow.camera.right = 25;
sun.shadow.camera.top = 20;
sun.shadow.camera.bottom = -20;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 65;
sun.shadow.bias = -0.0004;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x5ea8ff, 1.25);
rim.position.set(-18, 9, -14);
scene.add(rim);
const platform = new THREE.Mesh(
new THREE.BoxGeometry(33, 0.4, 13.2),
new THREE.MeshStandardMaterial({
color: 0x101d2a,
roughness: 0.82,
metalness: 0.15
})
);
platform.position.y = -3.35;
platform.receiveShadow = true;
scene.add(platform);
const grid = new THREE.GridHelper(40, 40, 0x31516a, 0x1c3448);
grid.position.y = -3.14;
grid.material.transparent = true;
grid.material.opacity = 0.32;
scene.add(grid);
/* ---------------------- Terrain and cutaway ------------------------ */
function surfaceHeight(model, x, z) {
if (model.id === "A") {
const swale = -0.55 * Math.exp(
-((x + 1.2) ** 2 / 7 + (z + 0.3) ** 2 / 18)
);
return (
0.25 * Math.sin(x * 0.65) * Math.cos(z * 0.50) +
swale -
0.045 * z
);
}
const crown = 0.22 * (1 - Math.min(Math.abs(x) / 6.5, 1));
return (
0.16 * Math.cos(x * 0.55) * Math.sin(z * 0.45) +
crown -
0.04 * z
);
}
function makeSurfaceGeometry(model) {
const nx = 36;
const nz = 26;
const positions = [];
const indices = [];
for (let iz = 0; iz <= nz; iz++) {
const lz = -model.depth / 2 + model.depth * iz / nz;
for (let ix = 0; ix <= nx; ix++) {
const lx = -model.width / 2 + model.width * ix / nx;
positions.push(
model.centerX + lx,
surfaceHeight(model, lx, lz),
lz
);
}
}
for (let iz = 0; iz < nz; iz++) {
for (let ix = 0; ix < nx; ix++) {
const a = iz * (nx + 1) + ix;
const b = a + 1;
const c = a + nx + 1;
const d = c + 1;
indices.push(a, c, b, b, c, d);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.setIndex(indices);
geometry.computeVertexNormals();
return geometry;
}
function stripGeometry(topPoints, bottomPoints) {
const positions = [];
const indices = [];
for (let i = 0; i < topPoints.length; i++) {
const t = topPoints[i];
const b = bottomPoints[i];
positions.push(t.x, t.y, t.z, b.x, b.y, b.z);
}
for (let i = 0; i < topPoints.length - 1; i++) {
const a = i * 2;
indices.push(a, a + 2, a + 1, a + 1, a + 2, a + 3);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.setIndex(indices);
geometry.computeVertexNormals();
return geometry;
}
function makeLabel(text, subtext) {
const c = document.createElement("canvas");
c.width = 640;
c.height = 176;
const ctx = c.getContext("2d");
ctx.fillStyle = "rgba(8,20,34,0.88)";
ctx.fillRect(0, 0, c.width, c.height);
ctx.fillStyle = "#eaf3fa";
ctx.font = "700 46px system-ui";
ctx.textAlign = "center";
ctx.fillText(text, c.width / 2, 65);
ctx.fillStyle = "#9fb4c5";
ctx.font = "30px system-ui";
ctx.fillText(subtext, c.width / 2, 117);
ctx.strokeStyle = "rgba(130,220,240,0.55)";
ctx.lineWidth = 5;
ctx.strokeRect(3, 3, c.width - 6, c.height - 6);
const texture = new THREE.CanvasTexture(c);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(5.9, 1.62, 1);
return sprite;
}
function mulberry32(seed) {
return function() {
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 addSurfaceVegetation(model) {
if (model.id !== "A") return;
const count = 85;
const geometry = new THREE.ConeGeometry(0.055, 0.34, 3);
const material = new THREE.MeshStandardMaterial({
color: 0x91b36f,
roughness: 1
});
const mesh = new THREE.InstancedMesh(geometry, material, count);
const dummy = new THREE.Object3D();
const random = mulberry32(501);
for (let i = 0; i < count; i++) {
const x = (random() - 0.5) * model.width * 0.94;
const z = (random() - 0.5) * model.depth * 0.92;
dummy.position.set(
model.centerX + x,
surfaceHeight(model, x, z) + 0.14,
z
);
dummy.rotation.y = random() * Math.PI;
dummy.scale.setScalar(0.75 + random() * 0.55);
dummy.updateMatrix();
mesh.setMatrixAt(i, dummy.matrix);
}
mesh.castShadow = true;
scene.add(mesh);
}
function createCatchment(model) {
const surfaceMaterial = new THREE.MeshStandardMaterial({
color: model.surfaceColor,
roughness: model.id === "A" ? 0.98 : 0.82,
metalness: 0.02
});
const surface = new THREE.Mesh(makeSurfaceGeometry(model), surfaceMaterial);
surface.castShadow = true;
surface.receiveShadow = true;
scene.add(surface);
const wire = new THREE.LineSegments(
new THREE.WireframeGeometry(surface.geometry),
new THREE.LineBasicMaterial({
color: 0xb7c9b5,
transparent: true,
opacity: 0.055
})
);
scene.add(wire);
const layerMaterials = [
new THREE.MeshStandardMaterial({
color: model.id === "A" ? 0x5c4936 : 0x75513d,
roughness: 1,
side: THREE.DoubleSide
}),
new THREE.MeshStandardMaterial({
color: model.id === "A" ? 0x79654b : 0x916448,
roughness: 1,
side: THREE.DoubleSide
}),
new THREE.MeshStandardMaterial({
color: 0x424a50,
roughness: 1,
side: THREE.DoubleSide
})
];
const boundaries = [-0.74, -2.02, -3.14];
const segments = 26;
const front = model.depth / 2;
const back = -model.depth / 2;
const left = model.centerX - model.width / 2;
const right = model.centerX + model.width / 2;
for (let layer = 0; layer < 3; layer++) {
const upper = layer === 0 ? null : boundaries[layer - 1];
const lower = boundaries[layer];
const frontTop = [];
const frontBottom = [];
const backTop = [];
const backBottom = [];
const rightTop = [];
const rightBottom = [];
const leftTop = [];
const leftBottom = [];
for (let i = 0; i <= segments; i++) {
const x = -model.width / 2 + model.width * i / segments;
const yFront = surfaceHeight(model, x, front);
const yBack = surfaceHeight(model, x, back);
frontTop.push({ x: model.centerX + x, y: yFront, z: front });
frontBottom.push({ x: model.centerX + x, y: lower, z: front });
backTop.push({ x: model.centerX + x, y: yBack, z: back });
backBottom.push({ x: model.centerX + x, y: lower, z: back });
}
for (let i = 0; i <= segments; i++) {
const z = back + model.depth * i / segments;
const yRight = surfaceHeight(model, model.width / 2, z);
const yLeft = surfaceHeight(model, -model.width / 2, z);
rightTop.push({ x: right, y: yRight, z });
rightBottom.push({ x: right, y: lower, z });
leftTop.push({ x: left, y: yLeft, z });
leftBottom.push({ x: left, y: lower, z });
}
scene.add(new THREE.Mesh(stripGeometry(frontTop, frontBottom), layerMaterials[layer]));
scene.add(new THREE.Mesh(stripGeometry(backTop, backBottom), layerMaterials[layer]));
scene.add(new THREE.Mesh(stripGeometry(rightTop, rightBottom), layerMaterials[layer]));
scene.add(new THREE.Mesh(stripGeometry(leftTop, leftBottom), layerMaterials[layer]));
}
const edgePoints = [];
const edgeCount = 42;
for (let i = 0; i < edgeCount; i++) {
const x = -model.width / 2 + model.width * i / (edgeCount - 1);
edgePoints.push(new THREE.Vector3(
model.centerX + x,
surfaceHeight(model, x, front) + 0.015,
front
));
}
for (let i = 0; i < edgeCount; i++) {
const z = front - model.depth * i / (edgeCount - 1);
edgePoints.push(new THREE.Vector3(
right,
surfaceHeight(model, model.width / 2, z) + 0.015,
z
));
}
for (let i = 0; i < edgeCount; i++) {
const x = model.width / 2 - model.width * i / (edgeCount - 1);
edgePoints.push(new THREE.Vector3(
model.centerX + x,
surfaceHeight(model, x, back) + 0.015,
back
));
}
for (let i = 0; i < edgeCount; i++) {
const z = back + model.depth * i / (edgeCount - 1);
edgePoints.push(new THREE.Vector3(
left,
surfaceHeight(model, -model.width / 2, z) + 0.015,
z
));
}
scene.add(new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints(edgePoints),
new THREE.LineBasicMaterial({
color: model.id === "A" ? 0x9dc48c : 0xd49a6e,
transparent: true,
opacity: 0.65
})
));
const label = makeLabel(model.label, model.rateLabel);
label.position.set(model.centerX, 2.4, -4.65);
scene.add(label);
addSurfaceVegetation(model);
/* Infiltration saturation region in the visible cutaway. */
const infiltrationOverlay = new THREE.Mesh(
new THREE.BoxGeometry(model.width * 0.94, 0.8, 0.025),
new THREE.MeshBasicMaterial({
color: 0x287dff,
transparent: true,
opacity: 0.31,
depthWrite: false
})
);
infiltrationOverlay.position.set(model.centerX, -0.34, front + 0.035);
infiltrationOverlay.renderOrder = 3;
scene.add(infiltrationOverlay);
model.infiltrationOverlay = infiltrationOverlay;
/* Runoff channel at the front edge. */
const channel = new THREE.Mesh(
new THREE.BoxGeometry(10.8, 0.13, 0.35),
new THREE.MeshStandardMaterial({
color: 0x263744,
roughness: 0.78
})
);
channel.position.set(model.centerX, -0.49, front + 0.19);
channel.castShadow = true;
scene.add(channel);
const channelWater = new THREE.Mesh(
new THREE.BoxGeometry(1, 0.055, 0.25),
new THREE.MeshBasicMaterial({
color: model.id === "A" ? 0x25d5e8 : 0x32c9e0,
transparent: true,
opacity: 0.78,
depthWrite: false
})
);
channelWater.position.set(model.centerX, -0.405, front + 0.19);
channelWater.renderOrder = 4;
scene.add(channelWater);
model.channelWater = channelWater;
}
/* ---------------------- Rain and flow particles -------------------- */
function createRainField(model) {
const count = 145;
const random = mulberry32(9127);
const drops = [];
const positions = new Float32Array(count * 6);
for (let i = 0; i < count; i++) {
drops.push({
x: (random() - 0.5) * model.width,
z: (random() - 0.5) * model.depth,
phase: random(),
speed: 0.75 + random() * 0.5
});
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
const material = new THREE.LineBasicMaterial({
color: 0xaed4ff,
transparent: true,
opacity: 0.58,
depthWrite: false
});
const lines = new THREE.LineSegments(geometry, material);
lines.frustumCulled = false;
scene.add(lines);
model.rain = { count, drops, positions, geometry, material, lines };
}
function createRunoffField(model) {
const count = 58;
const random = mulberry32(2222);
const particles = [];
const positions = new Float32Array(count * 3);
for (let i = 0; i < count; i++) {
particles.push({
x: (random() - 0.5) * model.width * 0.86,
z: -4.4 + random() * 7.4,
phase: random(),
speed: 0.78 + random() * 0.55
});
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
const material = new THREE.PointsMaterial({
color: model.id === "A" ? 0x3ce7f4 : 0x55d4ea,
size: 0.14,
sizeAttenuation: true,
transparent: true,
opacity: 0.9,
depthWrite: false
});
const points = new THREE.Points(geometry, material);
points.frustumCulled = false;
scene.add(points);
model.runoff = { count, particles, positions, geometry, material, points };
}
function createInfiltrationField(model) {
const count = 31;
const random = mulberry32(7788);
const particles = [];
const positions = new Float32Array(count * 6);
for (let i = 0; i < count; i++) {
particles.push({
x: (random() - 0.5) * model.width * 0.91,
phase: random(),
speed: 0.8 + random() * 0.5
});
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
const material = new THREE.LineBasicMaterial({
color: model.id === "A" ? 0x6798ff : 0x9a8dff,
transparent: true,
opacity: 0.78,
depthWrite: false
});
const lines = new THREE.LineSegments(geometry, material);
lines.frustumCulled = false;
scene.add(lines);
model.infiltrationParticles = { count, particles, positions, geometry, material, lines };
}
for (const model of MODELS) {
createCatchment(model);
createRainField(model);
createRunoffField(model);
createInfiltrationField(model);
}
/* ------------------------ Hydrologic accounting -------------------- */
function calculateVolumes(model, elapsedSeconds) {
const stormSeconds = Math.min(elapsedSeconds, DURATION_SECONDS);
// 1 mm over 100 m² = 0.1 m³.
const rainVolume = RAIN_MM_H * stormSeconds / 3600 * AREA_M2 / 1000;
// Constant capacity, accepting the lesser of rainfall supply and capacity.
const infiltrationVolume =
Math.min(RAIN_MM_H, model.infiltration) *
stormSeconds / 3600 *
AREA_M2 / 1000;
const runoffVolume = Math.max(0, rainVolume - infiltrationVolume);
return { rainVolume, infiltrationVolume, runoffVolume };
}
let simulationSeconds = 0;
let playing = true;
let playbackSpeed = 30;
const playButton = document.querySelector("#play");
const timeline = document.querySelector("#timeline");
const timeLabel = document.querySelector("#time");
const statusLabel = document.querySelector("#status");
function formatTime(seconds) {
const s = Math.max(0, Math.floor(seconds));
const minutes = Math.floor(s / 60);
const remainder = s % 60;
return `${String(minutes).padStart(2, "0")}:${String(remainder).padStart(2, "0")}`;
}
function setPlaying(value) {
if (value && simulationSeconds >= DURATION_SECONDS) {
simulationSeconds = 0;
}
playing = value;
playButton.textContent = playing ? "❚❚ Pause" : "▶ Play";
statusLabel.textContent = playing ? "LIVE" : "PAUSED";
statusLabel.style.color = playing ? "#25d5e8" : "#f4a261";
}
playButton.onclick = () => setPlaying(!playing);
document.querySelector("#reset").onclick = () => {
simulationSeconds = 0;
setPlaying(true);
};
timeline.addEventListener("input", () => {
simulationSeconds = Number(timeline.value);
setPlaying(false);
});
document.querySelector("#speed").addEventListener("change", event => {
playbackSpeed = Number(event.target.value);
});
window.addEventListener("keydown", event => {
if (
event.code === "Space" &&
!["INPUT", "SELECT", "BUTTON"].includes(document.activeElement.tagName)
) {
event.preventDefault();
setPlaying(!playing);
}
});
/* ---------------------------- UI and chart -------------------------- */
const chart = document.querySelector("#chart");
const chartContext = chart.getContext("2d");
const maxRainVolume = RAIN_MM_H * DURATION_SECONDS / 3600 * AREA_M2 / 1000;
function drawChart() {
const width = chart.clientWidth;
const height = chart.clientHeight;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
if (chart.width !== Math.round(width * dpr) ||
chart.height !== Math.round(height * dpr)) {
chart.width = Math.round(width * dpr);
chart.height = Math.round(height * dpr);
}
chartContext.setTransform(dpr, 0, 0, dpr, 0, 0);
chartContext.clearRect(0, 0, width, height);
const pad = { left: 32, right: 10, top: 10, bottom: 24 };
const plotW = width - pad.left - pad.right;
const plotH = height - pad.top - pad.bottom;
const maxY = 3.2;
chartContext.font = "9px system-ui";
chartContext.lineWidth = 1;
for (let i = 0; i <= 4; i++) {
const y = pad.top + plotH * i / 4;
chartContext.strokeStyle = "rgba(150,180,205,.10)";
chartContext.beginPath();
chartContext.moveTo(pad.left, y);
chartContext.lineTo(width - pad.right, y);
chartContext.stroke();
chartContext.fillStyle = "#73899b";
chartContext.textAlign = "right";
chartContext.fillText((maxY * (1 - i / 4)).toFixed(1), pad.left - 6, y + 3);
}
for (let i = 0; i <= 3; i++) {
const x = pad.left + plotW * i / 3;
chartContext.strokeStyle = "rgba(150,180,205,.07)";
chartContext.beginPath();
chartContext.moveTo(x, pad.top);
chartContext.lineTo(x, pad.top + plotH);
chartContext.stroke();
chartContext.fillStyle = "#73899b";
chartContext.textAlign = "center";
chartContext.fillText(`${i * 10}m`, x, height - 6);
}
function drawSeries(model, key, color, dashed) {
chartContext.beginPath();
chartContext.strokeStyle = color;
chartContext.lineWidth = 2;
chartContext.setLineDash(dashed ? [5, 4] : []);
for (let i = 0; i <= 120; i++) {
const t = DURATION_SECONDS * i / 120;
const value = calculateVolumes(model, t)[key];
const x = pad.left + plotW * i / 120;
const y = pad.top + plotH * (1 - value / maxY);
if (i === 0) chartContext.moveTo(x, y);
else chartContext.lineTo(x, y);
}
chartContext.stroke();
chartContext.setLineDash([]);
}
drawSeries(MODELS[0], "runoffVolume", "#25d5e8", false);
drawSeries(MODELS[0], "infiltrationVolume", "#5c8dff", true);
drawSeries(MODELS[1], "runoffVolume", "#f4a261", false);
drawSeries(MODELS[1], "infiltrationVolume", "#b990ff", true);
const markerX = pad.left + plotW * simulationSeconds / DURATION_SECONDS;
chartContext.strokeStyle = "rgba(230,242,250,.45)";
chartContext.lineWidth = 1;
chartContext.beginPath();
chartContext.moveTo(markerX, pad.top);
chartContext.lineTo(markerX, pad.top + plotH);
chartContext.stroke();
}
function updateReadouts() {
for (const model of MODELS) {
const key = model.id.toLowerCase();
const values = calculateVolumes(model, simulationSeconds);
document.getElementById(`${key}Rain`).textContent = values.rainVolume.toFixed(3);
document.getElementById(`${key}Runoff`).textContent = values.runoffVolume.toFixed(3);
document.getElementById(`${key}Infil`).textContent = values.infiltrationVolume.toFixed(3);
document.getElementById(`${key}RainBar`).style.width =
`${100 * values.rainVolume / maxRainVolume}%`;
document.getElementById(`${key}RunoffBar`).style.width =
`${100 * values.runoffVolume / maxRainVolume}%`;
document.getElementById(`${key}InfilBar`).style.width =
`${100 * values.infiltrationVolume / maxRainVolume}%`;
document.getElementById(`${key}Balance`).textContent =
`Rain ${values.rainVolume.toFixed(3)} = ` +
`runoff ${values.runoffVolume.toFixed(3)} + ` +
`infiltration ${values.infiltrationVolume.toFixed(3)} m³`;
}
timeline.value = String(Math.round(simulationSeconds));
timeLabel.textContent = `${formatTime(simulationSeconds)} / 30:00`;
drawChart();
}
/* ----------------------- 3D animation update ----------------------- */
function updateModelVisuals(model, elapsedSeconds) {
const values = calculateVolumes(model, elapsedSeconds);
const raining = elapsedSeconds < DURATION_SECONDS;
/* Rain streaks: identical counts and random phases for both catchments. */
const rain = model.rain;
rain.lines.visible = raining;
if (raining) {
for (let i = 0; i < rain.count; i++) {
const drop = rain.drops[i];
const cycle = (elapsedSeconds * 0.42 * drop.speed + drop.phase) % 1;
const baseY = surfaceHeight(model, drop.x, drop.z);
const y = baseY + 0.22 + (1 - cycle) * 7.4;
const index = i * 6;
rain.positions[index] = model.centerX + drop.x;
rain.positions[index + 1] = y;
rain.positions[index + 2] = drop.z;
rain.positions[index + 3] = model.centerX + drop.x - 0.045;
rain.positions[index + 4] = y + 0.46;
rain.positions[index + 5] = drop.z + 0.02;
}
rain.geometry.attributes.position.needsUpdate = true;
}
/* Surface runoff particles moving toward the front outlet. */
const runoff = model.runoff;
const runoffFraction = values.runoffVolume / maxRainVolume;
runoff.points.visible = values.runoffVolume > 0.0001;
runoff.material.opacity = Math.min(0.96, 0.25 + runoffFraction * 0.8);
if (runoff.points.visible) {
for (let i = 0; i < runoff.count; i++) {
const particle = runoff.particles[i];
const cycle = (elapsedSeconds * 0.23 * particle.speed + particle.phase) % 1;
const x = THREE.MathUtils.lerp(particle.x, 0, cycle);
const z = THREE.MathUtils.lerp(particle.z, model.depth / 2 + 0.16, cycle);
let y = surfaceHeight(model, x, z) + 0.10;
if (z > model.depth / 2 - 0.12) {
const dropProgress = THREE.MathUtils.clamp(
(z - (model.depth / 2 - 0.12)) / 0.28,
0,
1
);
y = THREE.MathUtils.lerp(y, -0.34, dropProgress);
}
const index = i * 3;
runoff.positions[index] = model.centerX + x;
runoff.positions[index + 1] = y;
runoff.positions[index + 2] = z;
}
runoff.geometry.attributes.position.needsUpdate = true;
}
/* Infiltration streaks in the exposed front soil section. */
const infiltration = model.infiltrationParticles;
infiltration.lines.visible = raining;
infiltration.material.opacity = 0.25 + model.infiltration / RAIN_MM_H * 0.65;
if (raining) {
for (let i = 0; i < infiltration.count; i++) {
const particle = infiltration.particles[i];
const cycle = (elapsedSeconds * 0.43 * particle.speed + particle.phase) % 1;
const topY = surfaceHeight(model, particle.x, model.depth / 2) + 0.03;
const bottomY = -2.02;
const y = THREE.MathUtils.lerp(topY, bottomY, cycle);
const index = i * 6;
const z = model.depth / 2 + 0.075;
infiltration.positions[index] = model.centerX + particle.x;
infiltration.positions[index + 1] = y;
infiltration.positions[index + 2] = z;
infiltration.positions[index + 3] = model.centerX + particle.x;
infiltration.positions[index + 4] = Math.max(bottomY, y - 0.34);
infiltration.positions[index + 5] = z;
}
infiltration.geometry.attributes.position.needsUpdate = true;
}
/* Blue saturation overlay grows downward-to-upward within the top layer. */
const theoreticalInfiltration =
model.infiltration * DURATION_SECONDS / 3600 * AREA_M2 / 1000;
const infiltrationFill = theoreticalInfiltration > 0
? values.infiltrationVolume / theoreticalInfiltration
: 0;
model.infiltrationOverlay.visible = infiltrationFill > 0.001;
model.infiltrationOverlay.scale.y = Math.max(0.01, infiltrationFill);
model.infiltrationOverlay.position.y = -0.74 + 0.4 * infiltrationFill;
/* Channel water length provides a qualitative indication of runoff volume. */
const channelWidth = 10.8 * Math.min(1, runoffFraction);
model.channelWater.scale.x = Math.max(0.01, channelWidth);
model.channelWater.position.x =
model.centerX - 5.4 + Math.max(0.01, channelWidth) / 2;
model.channelWater.material.opacity = 0.35 + runoffFraction * 0.5;
}
/* ------------------------------- Loop ------------------------------- */
let previousTime = performance.now();
function animate(now) {
requestAnimationFrame(animate);
const dt = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (playing) {
simulationSeconds = Math.min(
DURATION_SECONDS,
simulationSeconds + dt * playbackSpeed
);
if (simulationSeconds >= DURATION_SECONDS) {
playing = false;
playButton.textContent = "▶ Replay";
statusLabel.textContent = "DONE";
statusLabel.style.color = "#7fc98a";
}
}
for (const model of MODELS) {
updateModelVisuals(model, simulationSeconds);
}
updateReadouts();
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
/* ----------------------------- Resizing ----------------------------- */
function resize() {
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
drawChart();
}
window.addEventListener("resize", resize);
resize();
</script>
</body>
</html>
```