Prompt specification
Build or customize the Three.js 3D scene "Open and close seasonal floodplain connections" 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: Open and close seasonal floodplain connections
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/open-and-close-seasonal-floodplain-connections-x3044
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring seasonal water connections across the Amazon floodplain. Let users vary water level across a fixed terrain model. Show which channels connect to the lake and distinguish hydrological connectivity from unsupported predictions about fish populations. Voxel style.
Working Three.js Starter (open-and-close-seasonal-floodplain-connections-x3044):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Amazon Floodplain — Seasonal Water Connectivity</title>
<style>
:root {
color-scheme: dark;
--panel: rgba(15, 29, 29, 0.90);
--panel-soft: rgba(31, 52, 49, 0.82);
--border: rgba(213, 235, 222, 0.16);
--text: #edf5ec;
--muted: #afc0b4;
--cyan: #19c9c2;
--amber: #efa33b;
--brown: #846048;
--slate: #71879c;
--green: #8fd28a;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #b8c9bd;
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
#labels {
position: fixed;
inset: 0;
pointer-events: none;
overflow: hidden;
}
.panel {
position: fixed;
z-index: 5;
background: var(--panel);
border: 1px solid var(--border);
border-radius: 16px;
box-shadow: 0 16px 45px rgba(15, 30, 25, 0.22);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
.brand {
top: 18px;
left: 18px;
width: min(390px, calc(100vw - 36px));
padding: 17px 18px 15px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 7px;
color: #b8d9ca;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.eyebrow::before {
width: 8px;
height: 8px;
border-radius: 2px;
background: var(--cyan);
box-shadow: 0 0 13px rgba(25, 201, 194, 0.65);
content: "";
}
h1 {
margin: 0;
font-size: clamp(20px, 2.3vw, 27px);
line-height: 1.08;
letter-spacing: -0.035em;
}
.brand p {
margin: 8px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.synthetic-badge {
display: inline-flex;
align-items: center;
margin-top: 11px;
padding: 5px 8px;
border: 1px solid rgba(239, 163, 59, 0.35);
border-radius: 7px;
background: rgba(239, 163, 59, 0.09);
color: #f5c880;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.controls {
bottom: 18px;
left: 18px;
width: min(390px, calc(100vw - 36px));
padding: 16px 18px 17px;
}
.control-heading {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 16px;
margin-bottom: 10px;
}
.control-heading label {
display: block;
color: #dce9df;
font-size: 12px;
font-weight: 750;
}
.level-value {
color: #fff;
font-variant-numeric: tabular-nums;
font-size: 23px;
font-weight: 800;
line-height: 1;
}
.level-value small {
color: var(--muted);
font-size: 11px;
font-weight: 650;
}
.season-name {
min-width: 105px;
margin-top: 4px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-align: right;
text-transform: uppercase;
}
#waterLevel {
width: 100%;
height: 22px;
margin: 0;
accent-color: var(--cyan);
cursor: pointer;
}
.range-labels {
display: flex;
justify-content: space-between;
margin-top: -2px;
color: #8fa499;
font-size: 10px;
}
.presets {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 6px;
margin-top: 13px;
}
.presets button,
.toggle {
border: 1px solid var(--border);
border-radius: 8px;
background: rgba(255, 255, 255, 0.045);
color: #c8d7cd;
cursor: pointer;
transition:
background 120ms ease,
border-color 120ms ease,
color 120ms ease;
}
.presets button {
padding: 8px 4px;
font-size: 10px;
font-weight: 700;
}
.presets button:hover,
.presets button.active,
.toggle:hover,
.toggle.active {
border-color: rgba(25, 201, 194, 0.55);
background: rgba(25, 201, 194, 0.11);
color: #f2fffb;
}
.toggles {
display: flex;
gap: 7px;
margin-top: 10px;
}
.toggle {
padding: 7px 9px;
font-size: 10px;
font-weight: 700;
}
.legend {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px 12px;
margin-top: 13px;
padding-top: 12px;
border-top: 1px solid var(--border);
color: #b9c8be;
font-size: 10px;
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
}
.swatch {
width: 11px;
height: 11px;
flex: 0 0 auto;
border-radius: 3px;
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.17);
}
.swatch.connected { background: var(--cyan); }
.swatch.disconnected { background: var(--amber); }
.swatch.dry { background: var(--brown); }
.swatch.isolated { background: var(--slate); }
.status {
top: 18px;
right: 18px;
width: min(375px, calc(100vw - 36px));
max-height: calc(100vh - 36px);
padding: 17px;
overflow: auto;
}
.status h2 {
margin: 0;
font-size: 16px;
letter-spacing: -0.02em;
}
.status-subtitle {
margin: 5px 0 12px;
color: var(--muted);
font-size: 11px;
line-height: 1.4;
}
.summary {
padding: 10px 11px;
border: 1px solid rgba(25, 201, 194, 0.25);
border-radius: 10px;
background: rgba(25, 201, 194, 0.08);
color: #d9fff9;
font-size: 11px;
line-height: 1.45;
}
.reach-list {
display: grid;
gap: 5px;
margin-top: 12px;
}
.reach-row {
display: grid;
grid-template-columns: 10px 1fr auto;
align-items: center;
gap: 9px;
min-height: 42px;
padding: 7px 8px;
border-radius: 9px;
background: rgba(255, 255, 255, 0.035);
}
.reach-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--slate);
box-shadow: 0 0 8px currentColor;
}
.reach-name {
display: block;
color: #e5eee7;
font-size: 11px;
font-weight: 750;
}
.reach-detail {
display: block;
margin-top: 2px;
color: #92a79a;
font-size: 9px;
line-height: 1.25;
}
.reach-state {
color: #b9c8be;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.06em;
text-align: right;
text-transform: uppercase;
}
.boundary-title {
margin: 16px 0 8px;
color: #e6eee8;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.boundary-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.boundary-card {
min-height: 126px;
padding: 11px;
border: 1px solid var(--border);
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
}
.boundary-card.supported {
border-color: rgba(143, 210, 138, 0.34);
background: rgba(143, 210, 138, 0.075);
}
.boundary-card.unsupported {
border-color: rgba(239, 163, 59, 0.34);
background: rgba(239, 163, 59, 0.065);
}
.boundary-tag {
display: inline-block;
margin-bottom: 7px;
color: #a9b8ae;
font-size: 8px;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.supported .boundary-tag { color: var(--green); }
.unsupported .boundary-tag { color: #f3bd69; }
.boundary-card strong {
display: block;
font-size: 11px;
line-height: 1.35;
}
.boundary-card p {
margin: 6px 0 0;
color: #9fb0a5;
font-size: 9px;
line-height: 1.45;
}
details {
margin-top: 12px;
padding-top: 10px;
border-top: 1px solid var(--border);
color: #a9baaf;
font-size: 10px;
line-height: 1.5;
}
summary {
color: #d7e3da;
cursor: pointer;
font-weight: 750;
}
details p {
margin: 8px 0 0;
}
.help {
position: fixed;
right: 18px;
bottom: 18px;
z-index: 4;
padding: 8px 11px;
border: 1px solid rgba(255, 255, 255, 0.16);
border-radius: 9px;
background: rgba(18, 32, 29, 0.74);
color: #d0ddd3;
font-size: 9px;
pointer-events: none;
}
.world-label {
position: absolute;
padding: 4px 7px;
border: 1px solid rgba(255, 255, 255, 0.24);
border-radius: 6px;
background: rgba(17, 32, 30, 0.78);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.18);
color: #f2fff8;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
transform: translate(-50%, -100%);
white-space: nowrap;
opacity: 0;
transition: opacity 150ms ease;
}
.world-label.visible {
opacity: 1;
}
.world-label.lake {
border-color: rgba(25, 201, 194, 0.6);
color: #a9fff8;
}
.world-label.pond {
border-color: rgba(113, 135, 156, 0.6);
color: #cad9e8;
}
@media (max-width: 820px) {
.brand {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 13px 14px;
}
.brand p {
display: none;
}
.synthetic-badge {
margin-top: 8px;
}
.status {
top: 116px;
right: 10px;
width: calc(100vw - 20px);
max-height: 38vh;
padding: 13px;
}
.controls {
bottom: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 13px 14px;
}
.legend {
grid-template-columns: repeat(4, 1fr);
gap: 5px;
}
.legend-item {
align-items: flex-start;
font-size: 8px;
}
.help {
display: none;
}
.boundary-card {
min-height: 0;
}
}
@media (max-width: 520px) {
.legend {
grid-template-columns: 1fr 1fr;
}
.presets {
gap: 4px;
}
.presets button {
font-size: 9px;
}
.boundary-grid {
grid-template-columns: 1fr;
}
}
</style>
</head>
<body>
<canvas id="scene" tabindex="0" aria-label="Interactive voxel model of a seasonal Amazon floodplain"></canvas>
<div id="labels" aria-hidden="true"></div>
<header class="brand panel">
<div class="eyebrow">Amazon floodplain study sandbox</div>
<h1>Seasonal water connections</h1>
<p>
Raise a synthetic floodwater level over fixed terrain and inspect which
modeled channel reaches have a continuous route to the lake.
</p>
<div class="synthetic-badge">Illustrative terrain · not a geographic forecast</div>
</header>
<section class="controls panel" aria-label="Scene controls">
<div class="control-heading">
<div>
<label for="waterLevel">Water level</label>
<div class="level-value">
<span id="levelValue">2.60</span> <small>m relative datum</small>
</div>
</div>
<div id="seasonName" class="season-name">Rising water</div>
</div>
<input
id="waterLevel"
type="range"
min="0.8"
max="4.9"
step="0.05"
value="2.6"
aria-label="Water level in meters"
>
<div class="range-labels">
<span>0.80 m · low</span>
<span>4.90 m · peak</span>
</div>
<div class="presets" aria-label="Seasonal presets">
<button type="button" data-level="1.15">Low water</button>
<button type="button" data-level="2.60" class="active">Rising</button>
<button type="button" data-level="3.80">High water</button>
<button type="button" data-level="4.65">Peak</button>
</div>
<div class="toggles">
<button id="toggleLabels" class="toggle active" type="button">Labels</button>
<button id="toggleFlow" class="toggle active" type="button">Flow markers</button>
</div>
<div class="legend" aria-label="Map legend">
<div class="legend-item">
<span class="swatch connected"></span>
<span>Lake-connected reach</span>
</div>
<div class="legend-item">
<span class="swatch disconnected"></span>
<span>Inundated, not connected</span>
</div>
<div class="legend-item">
<span class="swatch dry"></span>
<span>Above water level</span>
</div>
<div class="legend-item">
<span class="swatch isolated"></span>
<span>Isolated water</span>
</div>
</div>
</section>
<aside class="status panel" aria-label="Hydrological connectivity report">
<h2>Lake connectivity report</h2>
<p class="status-subtitle">
Reach status is computed from fixed channel-bed crest elevations and
continuous modeled paths to the lake.
</p>
<div id="summary" class="summary" aria-live="polite"></div>
<div id="reachList" class="reach-list"></div>
<div class="boundary-title">What this scene does and does not support</div>
<div class="boundary-grid">
<div class="boundary-card supported">
<span class="boundary-tag">Computed</span>
<strong>Hydrological connectivity</strong>
<p>
Whether a modeled reach is below the selected level and has a
continuous path to the lake.
</p>
</div>
<div class="boundary-card unsupported">
<span class="boundary-tag">Not computed</span>
<strong>Fish population outcomes</strong>
<p>
No fish abundance, movement, survival, recruitment, or population
change should be inferred from these colors or flow markers.
</p>
</div>
</div>
<details>
<summary>How the toy model works</summary>
<p>
The terrain is a fixed synthetic voxel field. Each named channel reach
has a bed elevation and a crest elevation. At the selected level, a
reach connects to the lake only when every crest along a continuous
route is at or below that level. Low cells may still contain isolated
water and are colored slate rather than lake-connected blue.
</p>
<p>
This is a threshold and path-connectivity demonstration, not a
hydrodynamic simulation, real Amazon survey, or ecological forecast.
</p>
</details>
</aside>
<div class="help">Drag: orbit · Shift/right-drag: pan · Wheel/pinch: zoom · R: reset</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const canvas = document.querySelector("#scene");
const levelInput = document.querySelector("#waterLevel");
const levelValue = document.querySelector("#levelValue");
const seasonName = document.querySelector("#seasonName");
const summary = document.querySelector("#summary");
const reachList = document.querySelector("#reachList");
const labelsRoot = document.querySelector("#labels");
// ------------------------------------------------------------
// Renderer, scene, and orthographic camera
// ------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xb8c9bd);
scene.fog = new THREE.Fog(0xb8c9bd, 36, 78);
const camera = new THREE.OrthographicCamera(-15, 15, 10, -10, 0.1, 120);
const cameraTarget = new THREE.Vector3(0, 1.0, 0);
let cameraYaw = 0.62;
let cameraPitch = 0.88;
let cameraDistance = 35;
const hemisphere = new THREE.HemisphereLight(0xe9f5ee, 0x5b503d, 2.25);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff1cf, 3.0);
sun.position.set(-10, 20, 11);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -18;
sun.shadow.camera.right = 18;
sun.shadow.camera.top = 15;
sun.shadow.camera.bottom = -15;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 55;
sun.shadow.bias = -0.00045;
sun.shadow.normalBias = 0.025;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x8ec8cf, 0.65);
rim.position.set(14, 8, -12);
scene.add(rim);
// ------------------------------------------------------------
// Fixed synthetic terrain and channel network
// ------------------------------------------------------------
const GRID_X = 42;
const GRID_Z = 32;
const CELL = 0.58;
const BASE_Y = -1.3;
const WATER_LEVEL_MIN = 0.8;
const WATER_LEVEL_MAX = 4.9;
const terrainHeights = new Float32Array(GRID_X * GRID_Z);
const nodes = {
lake: { x: 8.8, z: 0.0, elevation: 0.45 },
junction: { x: -4.2, z: 0.5, elevation: 1.35 },
north: { x: -7.0, z: -4.2, elevation: 2.55 },
ntip: { x: -13.0, z: -8.2, elevation: 3.65 },
south: { x: -8.0, z: 5.0, elevation: 2.25 },
stip: { x: -13.0, z: 8.5, elevation: 3.05 },
oxbow: { x: 1.0, z: 5.0, elevation: 2.70 },
otip: { x: 5.0, z: 8.2, elevation: 4.45 },
};
const edges = [
{
id: "lake-channel",
name: "Lake channel",
a: "junction",
b: "lake",
crest: 1.35,
},
{
id: "north-bend",
name: "North bend",
a: "north",
b: "junction",
crest: 2.55,
},
{
id: "north-wetland",
name: "North wetland",
a: "ntip",
b: "north",
crest: 3.65,
},
{
id: "south-bend",
name: "South bend",
a: "south",
b: "junction",
crest: 2.25,
},
{
id: "south-backwater",
name: "South backwater",
a: "stip",
b: "south",
crest: 3.05,
},
{
id: "oxbow-inlet",
name: "Oxbow inlet",
a: "oxbow",
b: "junction",
crest: 2.70,
},
{
id: "oxbow-basin",
name: "Oxbow basin",
a: "otip",
b: "oxbow",
crest: 4.45,
},
];
const edgeById = new Map(edges.map((edge) => [edge.id, edge]));
const adjacency = new Map();
for (const nodeId of Object.keys(nodes)) {
adjacency.set(nodeId, []);
}
for (const edge of edges) {
adjacency.get(edge.a).push({ edge, other: edge.b });
adjacency.get(edge.b).push({ edge, other: edge.a });
}
function gridWorldX(ix) {
return (ix - (GRID_X - 1) / 2) * CELL;
}
function gridWorldZ(iz) {
return (iz - (GRID_Z - 1) / 2) * CELL;
}
function terrainIndex(ix, iz) {
return iz * GRID_X + ix;
}
function pointSegmentInfo(x, z, a, b) {
const abx = b.x - a.x;
const abz = b.z - a.z;
const lengthSq = abx * abx + abz * abz;
const t = THREE.MathUtils.clamp(
((x - a.x) * abx + (z - a.z) * abz) / lengthSq,
0,
1
);
const px = a.x + abx * t;
const pz = a.z + abz * t;
const dx = x - px;
const dz = z - pz;
return {
distance: Math.hypot(dx, dz),
t,
bed: THREE.MathUtils.lerp(a.elevation, b.elevation, t),
};
}
function syntheticBaseHeight(x, z) {
let h =
2.58 +
0.40 * Math.sin(x * 0.53 + z * 0.31) +
0.31 * Math.cos(z * 0.78 - x * 0.22);
// Slightly higher terrain toward the western and northern margins.
h += 1.15 * Math.pow(Math.max(0, (-x - 5.5) / 7), 2);
h += 1.20 * Math.pow(Math.abs(z) / 8.8, 2.15);
h += 0.55 * Math.pow(Math.max(0, (x - 8) / 4), 2);
// Lake basin.
const lakeR = Math.hypot((x - 8.8) / 2.9, z / 3.6);
if (lakeR < 1.12) {
h = Math.min(h, 0.25 + 0.85 * Math.pow(lakeR / 1.12, 2));
}
// A deliberately isolated low basin.
const pondR = Math.hypot((x - 4.3) / 1.35, (z + 5.7) / 1.2);
if (pondR < 1.0) {
h = Math.min(h, 1.10 + 0.90 * pondR * pondR);
}
return h;
}
// Generate fixed terrain.
for (let iz = 0; iz < GRID_Z; iz++) {
for (let ix = 0; ix < GRID_X; ix++) {
const x = gridWorldX(ix);
const z = gridWorldZ(iz);
terrainHeights[terrainIndex(ix, iz)] = syntheticBaseHeight(x, z);
}
}
// Carve channels and add low natural shoulders around them.
for (let iz = 0; iz < GRID_Z; iz++) {
for (let ix = 0; ix < GRID_X; ix++) {
const x = gridWorldX(ix);
const z = gridWorldZ(iz);
const index = terrainIndex(ix, iz);
let nearestDistance = Infinity;
let nearestBed = Infinity;
for (const edge of edges) {
const a = nodes[edge.a];
const b = nodes[edge.b];
const info = pointSegmentInfo(x, z, a, b);
if (info.distance < nearestDistance) {
nearestDistance = info.distance;
nearestBed = info.bed;
}
if (info.distance <= 0.52) {
terrainHeights[index] = Math.min(
terrainHeights[index],
info.bed + 0.025
);
}
}
if (
nearestDistance > 0.52 &&
nearestDistance < 1.12 &&
Number.isFinite(nearestBed)
) {
terrainHeights[index] = Math.max(
terrainHeights[index],
nearestBed + 0.34
);
}
}
}
// Terrain blocks.
const terrainGeometry = new THREE.BoxGeometry(1, 1, 1);
const terrainMaterial = new THREE.MeshLambertMaterial({ color: 0xffffff });
const terrainMesh = new THREE.InstancedMesh(
terrainGeometry,
terrainMaterial,
GRID_X * GRID_Z
);
terrainMesh.castShadow = true;
terrainMesh.receiveShadow = true;
terrainMesh.frustumCulled = false;
scene.add(terrainMesh);
const dummy = new THREE.Object3D();
const color = new THREE.Color();
const mudColor = new THREE.Color(0x74613d);
const grassColor = new THREE.Color(0x607b43);
const highGrassColor = new THREE.Color(0x839052);
const dryColor = new THREE.Color(0x9a915a);
function deterministicNoise(ix, iz) {
const value = Math.sin(ix * 91.17 + iz * 47.31) * 43758.5453;
return value - Math.floor(value);
}
for (let iz = 0; iz < GRID_Z; iz++) {
for (let ix = 0; ix < GRID_X; ix++) {
const index = terrainIndex(ix, iz);
const h = terrainHeights[index];
const x = gridWorldX(ix);
const z = gridWorldZ(iz);
dummy.position.set(x, (BASE_Y + h) / 2, z);
dummy.scale.set(CELL * 0.955, h - BASE_Y, CELL * 0.955);
dummy.rotation.set(0, 0, 0);
dummy.updateMatrix();
terrainMesh.setMatrixAt(index, dummy.matrix);
const noise = deterministicNoise(ix, iz);
if (h < 1.65) {
color.copy(mudColor).lerp(grassColor, 0.35 + noise * 0.2);
} else if (h < 2.8) {
color.copy(grassColor).lerp(highGrassColor, noise * 0.35);
} else {
color.copy(highGrassColor).lerp(dryColor, noise * 0.35);
}
color.offsetHSL(0, 0, (noise - 0.5) * 0.035);
terrainMesh.setColorAt(index, color);
}
}
terrainMesh.instanceMatrix.needsUpdate = true;
terrainMesh.instanceColor.needsUpdate = true;
// Darker slab under the voxel columns.
const slab = new THREE.Mesh(
new THREE.BoxGeometry(
GRID_X * CELL + 0.4,
0.36,
GRID_Z * CELL + 0.4
),
new THREE.MeshLambertMaterial({ color: 0x4e4634 })
);
slab.position.y = BASE_Y - 0.18;
slab.receiveShadow = true;
scene.add(slab);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(120, 120),
new THREE.MeshLambertMaterial({ color: 0xaab8a5 })
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = BASE_Y - 0.38;
ground.receiveShadow = true;
scene.add(ground);
// ------------------------------------------------------------
// Channel trace blocks
// ------------------------------------------------------------
const channelSamples = [];
for (const edge of edges) {
const a = nodes[edge.a];
const b = nodes[edge.b];
const length = Math.hypot(b.x - a.x, b.z - a.z);
const count = Math.max(2, Math.ceil(length / 0.20));
const samples = [];
for (let i = 0; i <= count; i++) {
const t = i / count;
const x = THREE.MathUtils.lerp(a.x, b.x, t);
const z = THREE.MathUtils.lerp(a.z, b.z, t);
const bed = THREE.MathUtils.lerp(a.elevation, b.elevation, t);
samples.push({ x, z, bed });
}
channelSamples.push({ edge, samples });
}
const totalChannelSamples = channelSamples.reduce(
(sum, item) => sum + item.samples.length,
0
);
const channelGeometry = new THREE.BoxGeometry(1, 1, 1);
const channelMaterial = new THREE.MeshLambertMaterial({ color: 0xffffff });
const channelMesh = new THREE.InstancedMesh(
channelGeometry,
channelMaterial,
totalChannelSamples
);
channelMesh.castShadow = true;
channelMesh.receiveShadow = true;
channelMesh.frustumCulled = false;
channelMesh.renderOrder = 2;
scene.add(channelMesh);
let channelInstance = 0;
for (const { samples } of channelSamples) {
for (const sample of samples) {
dummy.position.set(sample.x, sample.bed + 0.085, sample.z);
dummy.scale.set(0.31, 0.105, 0.31);
dummy.rotation.set(0, 0, 0);
dummy.updateMatrix();
channelMesh.setMatrixAt(channelInstance, dummy.matrix);
channelInstance++;
}
}
channelMesh.instanceMatrix.needsUpdate = true;
// ------------------------------------------------------------
// Water surfaces
// ------------------------------------------------------------
const waterGeometry = new THREE.BoxGeometry(1, 1, 1);
const connectedWaterMaterial = new THREE.MeshLambertMaterial({
color: 0x48b9d5,
transparent: true,
opacity: 0.64,
depthWrite: false,
});
const isolatedWaterMaterial = new THREE.MeshLambertMaterial({
color: 0x71879c,
transparent: true,
opacity: 0.48,
depthWrite: false,
});
const connectedWaterMesh = new THREE.InstancedMesh(
waterGeometry,
connectedWaterMaterial,
GRID_X * GRID_Z
);
const isolatedWaterMesh = new THREE.InstancedMesh(
waterGeometry,
isolatedWaterMaterial,
GRID_X * GRID_Z
);
for (const mesh of [connectedWaterMesh, isolatedWaterMesh]) {
mesh.count = 0;
mesh.frustumCulled = false;
mesh.renderOrder = 1;
scene.add(mesh);
}
// ------------------------------------------------------------
// Connectivity and water update
// ------------------------------------------------------------
let currentLevel = Number(levelInput.value);
let labelsVisible = true;
let flowVisible = true;
let connectedEdges = new Set();
const flowParticles = [];
const connectedColor = new THREE.Color(0x19c9c2);
const disconnectedColor = new THREE.Color(0xefa33b);
const dryChannelColor = new THREE.Color(0x846048);
function computeConnectivity(level) {
const visitedNodes = new Set(["lake"]);
const connected = new Set();
const queue = ["lake"];
while (queue.length) {
const nodeId = queue.shift();
for (const { edge, other } of adjacency.get(nodeId)) {
if (
!visitedNodes.has(other) &&
edge.crest <= level
) {
visitedNodes.add(other);
connected.add(edge.id);
queue.push(other);
}
}
}
return {
visitedNodes,
connected,
};
}
function edgeStatus(edge, level, connected) {
if (connected.has(edge.id)) {
return {
key: "connected",
label: "Connected",
detail: `continuous route to lake · crest ${edge.crest.toFixed(2)} m`,
color: "#19c9c2",
};
}
if (edge.crest <= level) {
return {
key: "disconnected",
label: "Not connected",
detail: "below crest, but no continuous modeled lake route",
color: "#efa33b",
};
}
return {
key: "dry",
label: "Above level",
detail: `channel crest ${edge.crest.toFixed(2)} m is above selected level`,
color: "#846048",
};
}
function updateWater(level) {
const wet = new Uint8Array(GRID_X * GRID_Z);
const lakeConnected = new Uint8Array(GRID_X * GRID_Z);
const queue = [];
// Lake basin is the source for surface-water connectivity.
for (let iz = 0; iz < GRID_Z; iz++) {
for (let ix = 0; ix < GRID_X; ix++) {
const index = terrainIndex(ix, iz);
const h = terrainHeights[index];
if (h >= level) continue;
const x = gridWorldX(ix);
const z = gridWorldZ(iz);
const lakeR = Math.hypot((x - 8.8) / 2.9, z / 3.6);
if (lakeR < 1.02) {
wet[index] = 1;
queue.push(index);
lakeConnected[index] = 1;
}
}
}
// Four-neighbor flood fill over fixed terrain cells.
let head = 0;
while (head < queue.length) {
const index = queue[head++];
const ix = index % GRID_X;
const iz = Math.floor(index / GRID_X);
const neighbors = [];
if (ix > 0) neighbors.push(index - 1);
if (ix < GRID_X - 1) neighbors.push(index + 1);
if (iz > 0) neighbors.push(index - GRID_X);
if (iz < GRID_Z - 1) neighbors.push(index + GRID_X);
for (const neighbor of neighbors) {
if (
!lakeConnected[neighbor] &&
wet[neighbor] === 1
) {
lakeConnected[neighbor] = 1;
queue.push(neighbor);
}
}
}
let connectedCount = 0;
let isolatedCount = 0;
for (let iz = 0; iz < GRID_Z; iz++) {
for (let ix = 0; ix < GRID_X; ix++) {
const index = terrainIndex(ix, iz);
if (!wet[index]) continue;
const h = terrainHeights[index];
const x = gridWorldX(ix);
const z = gridWorldZ(iz);
dummy.position.set(x, (h + level) / 2, z);
dummy.scale.set(
CELL * 0.925,
Math.max(0.025, level - h),
CELL * 0.925
);
dummy.rotation.set(0, 0, 0);
dummy.updateMatrix();
if (lakeConnected[index]) {
connectedWaterMesh.setMatrixAt(connectedCount, dummy.matrix);
connectedCount++;
} else {
isolatedWaterMesh.setMatrixAt(isolatedCount, dummy.matrix);
isolatedCount++;
}
}
}
connectedWaterMesh.count = connectedCount;
isolatedWaterMesh.count = isolatedCount;
connectedWaterMesh.instanceMatrix.needsUpdate = true;
isolatedWaterMesh.instanceMatrix.needsUpdate = true;
}
const particleGeometry = new THREE.BoxGeometry(0.12, 0.12, 0.12);
const particleMaterial = new THREE.MeshBasicMaterial({
color: 0xeaffff,
transparent: true,
opacity: 0.95,
});
function clearFlowParticles() {
for (const particle of flowParticles) {
scene.remove(particle.mesh);
}
flowParticles.length = 0;
}
function rebuildFlowParticles(connected) {
clearFlowParticles();
if (!flowVisible) return;
for (const { edge } of channelSamples) {
if (!connected.has(edge.id)) continue;
for (let i = 0; i < 2; i++) {
const mesh = new THREE.Mesh(particleGeometry, particleMaterial);
mesh.renderOrder = 4;
scene.add(mesh);
flowParticles.push({
mesh,
edge,
offset: i * 0.5,
});
}
}
}
function updateChannelColors(level, connected) {
let instance = 0;
for (const { edge, samples } of channelSamples) {
const status = edgeStatus(edge, level, connected);
for (let i = 0; i < samples.length; i++) {
color.copy(
status.key === "connected"
? connectedColor
: status.key === "disconnected"
? disconnectedColor
: dryChannelColor
);
channelMesh.setColorAt(instance, color);
instance++;
}
}
channelMesh.instanceColor.needsUpdate = true;
}
function updateStatusPanel(level, connected) {
const count = connected.size;
const season =
level < 1.6
? "Low water"
: level < 2.8
? "Rising water"
: level < 3.8
? "High water"
: "Peak flood";
levelValue.textContent = level.toFixed(2);
seasonName.textContent = season;
summary.textContent =
`${count} of ${edges.length} modeled reaches have a continuous ` +
`below-level path to the lake at ${level.toFixed(2)} m. ` +
`Cyan flow markers indicate modeled connection only.`;
reachList.innerHTML = edges
.map((edge) => {
const status = edgeStatus(edge, level, connected);
return `
<div class="reach-row">
<span
class="reach-dot"
style="background:${status.color};color:${status.color}"
></span>
<div>
<span class="reach-name">${edge.name}</span>
<span class="reach-detail">${status.detail}</span>
</div>
<span class="reach-state">${status.label}</span>
</div>
`;
})
.join("");
document.querySelectorAll("[data-level]").forEach((button) => {
button.classList.toggle(
"active",
Math.abs(Number(button.dataset.level) - level) < 0.001
);
});
}
function updateScene() {
currentLevel = Number(levelInput.value);
const connectivity = computeConnectivity(currentLevel);
connectedEdges = connectivity.connected;
updateWater(currentLevel);
updateChannelColors(currentLevel, connectedEdges);
rebuildFlowParticles(connectedEdges);
updateStatusPanel(currentLevel, connectedEdges);
}
// ------------------------------------------------------------
// World labels
// ------------------------------------------------------------
const labelDefinitions = [
{
id: "lake-label",
text: "Lake",
x: nodes.lake.x,
z: nodes.lake.z,
className: "lake",
},
{
id: "north-label",
text: "North wetland",
x: nodes.ntip.x,
z: nodes.ntip.z,
className: "",
},
{
id: "south-label",
text: "South backwater",
x: nodes.stip.x,
z: nodes.stip.z,
className: "",
},
{
id: "oxbow-label",
text: "Oxbow basin",
x: nodes.otip.x,
z: nodes.otip.z,
className: "",
},
{
id: "pond-label",
text: "Isolated pond",
x: 4.3,
z: -5.7,
className: "pond",
},
];
const worldLabels = labelDefinitions.map((definition) => {
const element = document.createElement("div");
element.className = `world-label ${definition.className}`;
element.textContent = definition.text;
labelsRoot.appendChild(element);
return {
...definition,
element,
};
});
const projected = new THREE.Vector3();
function updateLabels() {
const width = canvas.clientWidth;
const height = canvas.clientHeight;
for (const label of worldLabels) {
projected.set(label.x, currentLevel + 0.36, label.z);
projected.project(camera);
const inView =
projected.z > -1 &&
projected.z < 1 &&
projected.x > -1.08 &&
projected.x < 1.08 &&
projected.y > -1.08 &&
projected.y < 1.08;
if (!labelsVisible || !inView) {
label.element.classList.remove("visible");
continue;
}
label.element.style.left = `${(projected.x * 0.5 + 0.5) * width}px`;
label.element.style.top = `${(-projected.y * 0.5 + 0.5) * height}px`;
label.element.classList.add("visible");
}
}
// ------------------------------------------------------------
// Direct camera controls: orbit, pan, wheel zoom, touch pinch
// ------------------------------------------------------------
function updateCamera() {
const horizontalDistance = cameraDistance * Math.cos(cameraPitch);
camera.position.set(
cameraTarget.x + horizontalDistance * Math.sin(cameraYaw),
cameraTarget.y + cameraDistance * Math.sin(cameraPitch),
cameraTarget.z + horizontalDistance * Math.cos(cameraYaw)
);
camera.lookAt(cameraTarget);
camera.updateProjectionMatrix();
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(width, height, false);
const viewHeight = Math.max(19, 27 / aspect);
camera.left = (-viewHeight * aspect) / 2;
camera.right = (viewHeight * aspect) / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
updateCamera();
}
function resetCamera() {
cameraTarget.set(0, 1.0, 0);
cameraYaw = 0.62;
cameraPitch = 0.88;
camera.zoom = 1;
updateCamera();
}
function panCamera(dx, dy) {
const rect = canvas.getBoundingClientRect();
const worldPerPixel =
(camera.top - camera.bottom) / camera.zoom / rect.height;
const right = new THREE.Vector3(
Math.cos(cameraYaw),
0,
-Math.sin(cameraYaw)
);
const groundForward = new THREE.Vector3(
-Math.sin(cameraYaw),
0,
-Math.cos(cameraYaw)
);
cameraTarget.addScaledVector(right, -dx * worldPerPixel);
cameraTarget.addScaledVector(groundForward, -dy * worldPerPixel);
updateCamera();
}
const pointers = new Map();
let singleDrag = null;
let pinchGesture = null;
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
canvas.focus();
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY,
});
if (pointers.size === 1) {
singleDrag = {
mode:
event.button === 2 || event.button === 1 || event.shiftKey
? "pan"
: "orbit",
x: event.clientX,
y: event.clientY,
};
} else if (pointers.size === 2) {
singleDrag = null;
const values = [...pointers.values()];
pinchGesture = {
distance: Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
),
centerX: (values[0].x + values[1].x) / 2,
centerY: (values[0].y + values[1].y) / 2,
};
}
});
canvas.addEventListener("pointermove", (event) => {
const pointer = pointers.get(event.pointerId);
if (!pointer) return;
pointer.x = event.clientX;
pointer.y = event.clientY;
if (pointers.size === 1 && singleDrag) {
const dx = event.clientX - singleDrag.x;
const dy = event.clientY - singleDrag.y;
if (singleDrag.mode === "pan") {
panCamera(dx, dy);
} else {
cameraYaw -= dx * 0.006;
cameraPitch = THREE.MathUtils.clamp(
cameraPitch + dy * 0.005,
0.38,
1.28
);
updateCamera();
}
singleDrag.x = event.clientX;
singleDrag.y = event.clientY;
} else if (pointers.size === 2 && pinchGesture) {
const values = [...pointers.values()];
const distance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
const centerX = (values[0].x + values[1].x) / 2;
const centerY = (values[0].y + values[1].y) / 2;
camera.zoom = THREE.MathUtils.clamp(
camera.zoom * (distance / Math.max(1, pinchGesture.distance)),
0.65,
2.6
);
panCamera(centerX - pinchGesture.centerX, centerY - pinchGesture.centerY);
pinchGesture = {
distance,
centerX,
centerY,
};
updateCamera();
}
});
function endPointer(event) {
pointers.delete(event.pointerId);
if (pointers.size === 0) {
singleDrag = null;
pinchGesture = null;
} else if (pointers.size === 1) {
pinchGesture = null;
const pointer = [...pointers.values()][0];
singleDrag = {
mode: "orbit",
x: pointer.x,
y: pointer.y,
};
}
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
camera.zoom = THREE.MathUtils.clamp(
camera.zoom * Math.exp(-event.deltaY * 0.001),
0.65,
2.6
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetCamera);
window.addEventListener("keydown", (event) => {
if (
event.target instanceof HTMLInputElement ||
event.target instanceof HTMLTextAreaElement
) {
return;
}
if (event.key.toLowerCase() === "r") {
resetCamera();
} else if (event.key === "ArrowLeft") {
cameraYaw += 0.08;
updateCamera();
} else if (event.key === "ArrowRight") {
cameraYaw -= 0.08;
updateCamera();
} else if (event.key === "ArrowUp") {
cameraPitch = THREE.MathUtils.clamp(cameraPitch + 0.06, 0.38, 1.28);
updateCamera();
} else if (event.key === "ArrowDown") {
cameraPitch = THREE.MathUtils.clamp(cameraPitch - 0.06, 0.38, 1.28);
updateCamera();
} else if (event.key === "+" || event.key === "=") {
camera.zoom = THREE.MathUtils.clamp(camera.zoom * 1.1, 0.65, 2.6);
updateCamera();
} else if (event.key === "-") {
camera.zoom = THREE.MathUtils.clamp(camera.zoom / 1.1, 0.65, 2.6);
updateCamera();
}
});
window.addEventListener("resize", resize);
// ------------------------------------------------------------
// UI events and animation
// ------------------------------------------------------------
levelInput.addEventListener("input", updateScene);
document.querySelectorAll("[data-level]").forEach((button) => {
button.addEventListener("click", () => {
levelInput.value = button.dataset.level;
updateScene();
});
});
document.querySelector("#toggleLabels").addEventListener("click", (event) => {
labelsVisible = !labelsVisible;
event.currentTarget.classList.toggle("active", labelsVisible);
event.currentTarget.setAttribute("aria-pressed", String(labelsVisible));
});
document.querySelector("#toggleFlow").addEventListener("click", (event) => {
flowVisible = !flowVisible;
event.currentTarget.classList.toggle("active", flowVisible);
event.currentTarget.setAttribute("aria-pressed", String(flowVisible));
rebuildFlowParticles(connectedEdges);
});
function animate(time) {
requestAnimationFrame(animate);
const seconds = time * 0.001;
for (const particle of flowParticles) {
const edge = particle.edge;
const a = nodes[edge.a];
const b = nodes[edge.b];
const t = (seconds * 0.13 + particle.offset) % 1;
particle.mesh.position.set(
THREE.MathUtils.lerp(a.x, b.x, t),
currentLevel + 0.095,
THREE.MathUtils.lerp(a.z, b.z, t)
);
}
updateLabels();
renderer.render(scene, camera);
}
resize();
resetCamera();
updateScene();
requestAnimationFrame(animate);
</script>
</body>
</html>
```