Prompt specification
Build or customize the Three.js 3D scene "Inspect connectivity under different schematic water levels" 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: Inspect connectivity under different schematic water levels
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/inspect-connectivity-under-different-schematic-water-l-x3068
Scene Description Prompt:
Vary schematic water levels in a voxel Ganges–Brahmaputra delta; compare boat routes and dry paths. Three.js from cdnjs, one HTML file.
Working Three.js Starter (inspect-connectivity-under-different-schematic-water-l-x3068):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ganges–Brahmaputra Delta Water Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #07151d;
--panel: rgba(9, 28, 36, 0.82);
--panel-border: rgba(161, 220, 221, 0.16);
--text: #ecf7f4;
--muted: #96aaa9;
--cyan: #51dce0;
--cyan-dark: #168c98;
--amber: #ffbd67;
--green: #9bcf9b;
}
* {
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;
}
button,
input {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas:active {
cursor: grabbing;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 50% 43%, transparent 30%, rgba(2, 10, 15, 0.18) 72%),
linear-gradient(180deg, rgba(2, 10, 15, 0.24), transparent 28%, transparent 72%, rgba(2, 10, 15, 0.38));
}
.intro {
position: fixed;
top: 28px;
left: 30px;
z-index: 5;
width: min(530px, calc(100vw - 390px));
pointer-events: none;
}
.eyebrow {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 12px;
color: var(--cyan);
font-size: 11px;
font-weight: 750;
letter-spacing: 0.17em;
text-transform: uppercase;
}
.eyebrow::before {
width: 26px;
height: 1px;
content: "";
background: var(--cyan);
box-shadow: 0 0 10px rgba(81, 220, 224, 0.8);
}
h1 {
max-width: 520px;
margin: 0;
font-size: clamp(30px, 4vw, 56px);
font-weight: 620;
line-height: 0.98;
letter-spacing: -0.045em;
text-wrap: balance;
}
.intro p {
max-width: 490px;
margin: 15px 0 18px;
color: #adc0bd;
font-size: 14px;
line-height: 1.55;
}
.route-legend {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.legend-chip {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 11px;
border: 1px solid var(--panel-border);
border-radius: 999px;
background: rgba(7, 24, 31, 0.62);
color: #c9d8d5;
font-size: 11px;
font-weight: 650;
letter-spacing: 0.025em;
backdrop-filter: blur(10px);
}
.legend-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px rgba(81, 220, 224, 0.85);
}
.legend-dot.amber {
background: var(--amber);
box-shadow: 0 0 12px rgba(255, 189, 103, 0.75);
}
.metrics {
position: fixed;
top: 24px;
right: 24px;
z-index: 6;
width: 330px;
overflow: hidden;
border: 1px solid var(--panel-border);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(18px);
}
.panel-head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 17px 18px 14px;
border-bottom: 1px solid rgba(161, 220, 221, 0.11);
}
.panel-title {
color: #dce9e6;
font-size: 12px;
font-weight: 750;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.live-badge {
display: flex;
align-items: center;
gap: 6px;
color: var(--green);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.live-badge::before {
width: 6px;
height: 6px;
content: "";
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 9px rgba(155, 207, 155, 0.8);
}
.level-readout {
padding: 18px 18px 13px;
}
.level-readout small {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 11px;
}
.level-readout strong {
font-size: 31px;
font-weight: 580;
letter-spacing: -0.04em;
}
.level-readout span {
margin-left: 4px;
color: var(--muted);
font-size: 13px;
font-weight: 500;
}
.metric-list {
display: grid;
grid-template-columns: 1fr 1fr;
border-top: 1px solid rgba(161, 220, 221, 0.11);
border-bottom: 1px solid rgba(161, 220, 221, 0.11);
}
.metric {
min-height: 91px;
padding: 15px 18px;
}
.metric:nth-child(odd) {
border-right: 1px solid rgba(161, 220, 221, 0.11);
}
.metric:nth-child(-n + 2) {
border-bottom: 1px solid rgba(161, 220, 221, 0.11);
}
.metric-label {
display: block;
margin-bottom: 7px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric strong {
display: block;
font-size: 19px;
font-weight: 610;
letter-spacing: -0.025em;
}
.metric small {
display: block;
margin-top: 4px;
color: #a8b9b7;
font-size: 10px;
}
.metric.boat strong {
color: var(--cyan);
}
.metric.dry strong {
color: var(--amber);
}
.verdict {
padding: 15px 18px 17px;
background: rgba(255, 255, 255, 0.018);
}
.verdict-title {
margin-bottom: 5px;
color: var(--text);
font-size: 14px;
font-weight: 700;
}
.verdict-copy {
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.controls {
position: fixed;
left: 50%;
bottom: 24px;
z-index: 7;
display: flex;
align-items: center;
gap: 18px;
width: min(760px, calc(100vw - 40px));
padding: 14px 16px 14px 20px;
transform: translateX(-50%);
border: 1px solid var(--panel-border);
border-radius: 17px;
background: rgba(8, 26, 34, 0.88);
box-shadow: 0 16px 50px rgba(0, 0, 0, 0.32);
backdrop-filter: blur(18px);
}
.level-control {
flex: 1;
min-width: 240px;
}
.level-head {
display: flex;
align-items: baseline;
justify-content: space-between;
margin-bottom: 8px;
}
.level-head label {
color: #c8d8d5;
font-size: 11px;
font-weight: 750;
letter-spacing: 0.09em;
text-transform: uppercase;
}
#sliderValue {
color: var(--cyan);
font-size: 13px;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
border-radius: 99px;
outline: none;
appearance: none;
background:
linear-gradient(90deg, var(--cyan-dark), var(--cyan)) 0 / var(--fill, 37%) 100% no-repeat,
rgba(177, 210, 207, 0.16);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 16px;
height: 16px;
border: 3px solid #d8ffff;
border-radius: 50%;
appearance: none;
background: var(--cyan-dark);
box-shadow: 0 0 0 4px rgba(81, 220, 224, 0.13);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 3px solid #d8ffff;
border-radius: 50%;
background: var(--cyan-dark);
box-shadow: 0 0 0 4px rgba(81, 220, 224, 0.13);
}
.scale-labels {
display: flex;
justify-content: space-between;
margin-top: 8px;
color: #718987;
font-size: 9px;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.button-row {
display: flex;
gap: 7px;
padding-left: 18px;
border-left: 1px solid rgba(161, 220, 221, 0.12);
}
.control-button {
min-height: 34px;
padding: 8px 10px;
border: 1px solid rgba(161, 220, 221, 0.15);
border-radius: 9px;
background: rgba(255, 255, 255, 0.025);
color: #aebfbd;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.03em;
cursor: pointer;
transition: 160ms ease;
}
.control-button:hover,
.control-button.active {
border-color: rgba(81, 220, 224, 0.42);
background: rgba(81, 220, 224, 0.09);
color: var(--cyan);
}
.control-button.icon {
width: 34px;
padding: 0;
font-size: 16px;
}
.interaction-hint {
position: fixed;
right: 28px;
bottom: 27px;
z-index: 4;
color: rgba(183, 205, 202, 0.57);
font-size: 10px;
letter-spacing: 0.03em;
pointer-events: none;
}
.schematic-note {
position: fixed;
left: 30px;
bottom: 28px;
z-index: 4;
color: rgba(183, 205, 202, 0.52);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.13em;
text-transform: uppercase;
pointer-events: none;
}
.map-label {
position: fixed;
z-index: 3;
padding: 5px 8px;
transform: translate(-50%, -50%);
border: 1px solid rgba(190, 220, 217, 0.14);
border-radius: 5px;
background: rgba(5, 19, 26, 0.66);
color: rgba(222, 238, 235, 0.85);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.1em;
text-transform: uppercase;
white-space: nowrap;
pointer-events: none;
backdrop-filter: blur(7px);
}
.map-label.river {
border-color: rgba(81, 220, 224, 0.24);
color: #7de5e7;
background: rgba(5, 37, 44, 0.66);
}
.map-label.place {
color: #e6d4b8;
border-color: rgba(255, 189, 103, 0.2);
}
@media (max-width: 900px) {
.intro {
top: 22px;
left: 22px;
width: calc(100vw - 330px);
}
h1 {
font-size: 36px;
}
.intro p {
font-size: 12px;
}
.metrics {
top: 18px;
right: 18px;
width: 290px;
}
.interaction-hint,
.schematic-note {
display: none;
}
}
@media (max-width: 680px) {
.intro {
top: 16px;
left: 16px;
width: calc(100vw - 32px);
}
h1 {
max-width: 320px;
font-size: 30px;
}
.intro p,
.route-legend {
display: none;
}
.metrics {
top: 105px;
right: 12px;
width: 238px;
border-radius: 14px;
}
.panel-head {
padding: 12px 14px 10px;
}
.level-readout {
padding: 12px 14px 9px;
}
.level-readout strong {
font-size: 25px;
}
.metric {
min-height: 76px;
padding: 11px 14px;
}
.metric strong {
font-size: 16px;
}
.verdict {
padding: 12px 14px;
}
.controls {
bottom: 10px;
gap: 10px;
width: calc(100vw - 20px);
padding: 12px;
}
.level-control {
min-width: 0;
}
.button-row {
padding-left: 10px;
}
.control-button[data-level] {
display: none;
}
.control-button[data-level="2.20"] {
display: block;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="vignette"></div>
<header class="intro">
<div class="eyebrow">Delta transport lab · 2025</div>
<h1>Water changes everything.</h1>
<p>
Raise the schematic water level to reshape the Ganges–Brahmaputra delta,
then compare a depth-aware boat passage with the protected dry embankment.
</p>
<div class="route-legend">
<div class="legend-chip">
<span class="legend-dot"></span>
Navigable boat route
</div>
<div class="legend-chip">
<span class="legend-dot amber"></span>
Dry embankment
</div>
</div>
</header>
<aside class="metrics">
<div class="panel-head">
<span class="panel-title">Scenario comparison</span>
<span class="live-badge">Live model</span>
</div>
<div class="level-readout">
<small>Water level above local datum</small>
<strong id="levelValue">+2.20</strong><span>m</span>
</div>
<div class="metric-list">
<div class="metric">
<span class="metric-label">Wet grid</span>
<strong id="floodValue">—</strong>
<small id="navValue">— navigable cells</small>
</div>
<div class="metric boat">
<span class="metric-label">Boat passage</span>
<strong id="boatDistance">—</strong>
<small id="boatTime">—</small>
</div>
<div class="metric dry">
<span class="metric-label">Dry path</span>
<strong id="dryDistance">—</strong>
<small id="dryTime">—</small>
</div>
<div class="metric">
<span class="metric-label">Minimum depth</span>
<strong id="depthValue">—</strong>
<small id="draftValue">0.40 m vessel draft</small>
</div>
</div>
<div class="verdict">
<div class="verdict-title" id="verdictTitle">Calculating routes…</div>
<div class="verdict-copy" id="verdictCopy">
The model is finding the shallowest usable water passage.
</div>
</div>
</aside>
<div class="map-label river" id="labelGanges">Ganges</div>
<div class="map-label river" id="labelBrahmaputra">Brahmaputra</div>
<div class="map-label" id="labelBay">Bay of Bengal</div>
<div class="map-label place" id="labelOrigin">Baharalpur</div>
<div class="map-label place" id="labelDestination">Chittagong hub</div>
<section class="controls">
<div class="level-control">
<div class="level-head">
<label for="waterLevel">Water level</label>
<strong id="sliderValue">+2.20 m</strong>
</div>
<input
id="waterLevel"
type="range"
min="0.55"
max="4.80"
step="0.05"
value="2.20"
aria-label="Water level in meters"
>
<div class="scale-labels">
<span>Low channel</span>
<span>Normal flow</span>
<span>Monsoon surge</span>
</div>
</div>
<div class="button-row">
<button class="control-button" data-level="0.80">Low</button>
<button class="control-button active" data-level="2.20">Normal</button>
<button class="control-button" data-level="4.40">High</button>
<button class="control-button icon" id="zoomIn" aria-label="Zoom in">+</button>
<button class="control-button icon" id="zoomOut" aria-label="Zoom out">−</button>
<button class="control-button icon" id="resetCamera" aria-label="Reset camera">⌂</button>
</div>
</section>
<div class="schematic-note">Schematic model · not for navigation</div>
<div class="interaction-hint">Drag to orbit · Scroll to zoom</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const container = document.getElementById("scene");
const levelInput = document.getElementById("waterLevel");
const NX = 64;
const NZ = 48;
const CELL = 1.35;
const KM_PER_CELL = 1.35;
const VESSEL_DRAFT = 0.40;
const WALK_SPEED = 4.4;
const WORLD_W = NX * CELL;
const WORLD_D = NZ * CELL;
const TOTAL_CELLS = NX * NZ;
const clamp = THREE.MathUtils.clamp;
const lerp = THREE.MathUtils.lerp;
function smoothstep(min, max, value) {
const t = clamp((value - min) / (max - min), 0, 1);
return t * t * (3 - 2 * t);
}
function hash2(x, y) {
const n = Math.sin(x * 127.1 + y * 311.7) * 43758.5453123;
return n - Math.floor(n);
}
function noise2(x, y) {
const ix = Math.floor(x);
const iy = Math.floor(y);
const fx = x - ix;
const fy = y - iy;
const ux = fx * fx * (3 - 2 * fx);
const uy = fy * fy * (3 - 2 * fy);
const a = hash2(ix, iy);
const b = hash2(ix + 1, iy);
const c = hash2(ix, iy + 1);
const d = hash2(ix + 1, iy + 1);
return lerp(
lerp(a, b, ux),
lerp(c, d, ux),
uy
);
}
function distanceToPolyline(u, v, points) {
let minimum = Infinity;
for (let p = 0; p < points.length - 1; p++) {
const a = points[p];
const b = points[p + 1];
const dx = b[0] - a[0];
const dy = b[1] - a[1];
const lengthSq = dx * dx + dy * dy;
const t = clamp(
((u - a[0]) * dx + (v - a[1]) * dy) / Math.max(lengthSq, 1e-9),
0,
1
);
const x = a[0] + t * dx;
const y = a[1] + t * dy;
const distance = Math.hypot(u - x, v - y);
if (distance < minimum) minimum = distance;
}
return minimum;
}
const gangesPath = [
[-0.05, 0.34],
[0.10, 0.39],
[0.25, 0.49],
[0.39, 0.60],
[0.52, 0.72],
[0.66, 0.88],
[0.75, 1.06]
];
const brahmaputraPath = [
[0.50, -0.06],
[0.47, 0.10],
[0.55, 0.24],
[0.67, 0.36],
[0.74, 0.49],
[0.75, 0.66],
[0.80, 0.84],
[0.83, 1.06]
];
const dryPathDefinition = [
[0.02, 0.34],
[0.10, 0.28],
[0.20, 0.23],
[0.31, 0.18],
[0.42, 0.15],
[0.53, 0.14],
[0.63, 0.17],
[0.71, 0.23],
[0.76, 0.32],
[0.78, 0.43],
[0.79, 0.56],
[0.80, 0.68]
];
const heights = new Float32Array(TOTAL_CELLS);
const terrainColors = new Float32Array(TOTAL_CELLS * 3);
for (let j = 0; j < NZ; j++) {
for (let i = 0; i < NX; i++) {
const u = i / (NX - 1);
const v = j / (NZ - 1);
const n = noise2(u * 10.5, v * 10.5);
const n2 = noise2(u * 24.0 + 9.2, v * 24.0 - 3.1);
const ocean = smoothstep(0.72, 1.0, v);
let elevation =
2.05 +
1.50 * (1 - v) +
0.48 * (n - 0.5) -
3.15 * ocean;
const distanceGanges = distanceToPolyline(u, v, gangesPath);
const distanceBrahmaputra = distanceToPolyline(u, v, brahmaputraPath);
const gangesMask = Math.exp(-Math.pow(distanceGanges / 0.074, 2));
const brahmaputraMask =
Math.exp(-Math.pow(distanceBrahmaputra / 0.071, 2));
const channelMask = Math.max(gangesMask, brahmaputraMask);
const channelFloor = 0.08 + 0.14 * n2 + 0.06 * ocean;
elevation =
elevation * (1 - channelMask) +
channelFloor * channelMask;
// A protected, elevated embankment remains above the modeled surge.
const distanceDry = distanceToPolyline(u, v, dryPathDefinition);
if (distanceDry < 0.039) {
const embankment = 5.04 + 0.16 * Math.sin((u + v) * 57);
elevation = Math.max(elevation, embankment);
}
heights[j * NX + i] = elevation;
}
}
function gridToWorld(i, j, y = 0) {
return new THREE.Vector3(
(i - (NX - 1) / 2) * CELL,
y,
(j - (NZ - 1) / 2) * CELL
);
}
function normalizedToGrid(u, v) {
return {
i: clamp(Math.round(u * (NX - 1)), 0, NX - 1),
j: clamp(Math.round(v * (NZ - 1)), 0, NZ - 1)
};
}
function heightAt(i, j) {
return heights[j * NX + i];
}
// ---------------------------------------------------------------------
// Scene and renderer
// ---------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07151d);
scene.fog = new THREE.FogExp2(0x07151d, 0.0062);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
260
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.8));
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;
container.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(
0xa9e5ee,
0x153027,
1.55
);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffedc9, 2.1);
sun.position.set(-35, 65, 28);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -70;
sun.shadow.camera.right = 70;
sun.shadow.camera.top = 65;
sun.shadow.camera.bottom = -65;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 150;
sun.shadow.normalBias = 0.035;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x48cbd8, 0.55);
rim.position.set(45, 22, -40);
scene.add(rim);
const base = new THREE.Mesh(
new THREE.BoxGeometry(WORLD_W + 1.6, 1.4, WORLD_D + 1.6),
new THREE.MeshStandardMaterial({
color: 0x0b2027,
roughness: 0.93,
metalness: 0.02
})
);
base.position.y = -3.8;
base.receiveShadow = true;
scene.add(base);
const terrainMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.9,
metalness: 0.01
}),
TOTAL_CELLS
);
terrainMesh.castShadow = true;
terrainMesh.receiveShadow = true;
terrainMesh.frustumCulled = false;
scene.add(terrainMesh);
const waterMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
color: 0xffffff,
vertexColors: true,
transparent: true,
opacity: 0.76,
roughness: 0.23,
metalness: 0.12,
depthWrite: false
}),
TOTAL_CELLS
);
waterMesh.frustumCulled = false;
waterMesh.renderOrder = 2;
scene.add(waterMesh);
const dummy = new THREE.Object3D();
const color = new THREE.Color();
const shallowWater = new THREE.Color(0x4bb6b2);
const deepWater = new THREE.Color(0x125d76);
const routeGroup = new THREE.Group();
scene.add(routeGroup);
let animatedMarkers = [];
// ---------------------------------------------------------------------
// Custom camera controls — no addons
// ---------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(0, 1.4, 0),
azimuth: 0.72,
polar: 0.93,
radius: 91
};
function applyCamera() {
const sinPolar = Math.sin(cameraState.polar);
const cosPolar = Math.cos(cameraState.polar);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPolar * Math.sin(cameraState.azimuth),
cameraState.target.y + cameraState.radius * cosPolar,
cameraState.target.z +
cameraState.radius * sinPolar * Math.cos(cameraState.azimuth)
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.azimuth = 0.72;
cameraState.polar = 0.93;
cameraState.radius = 91;
applyCamera();
}
let dragging = false;
let previousX = 0;
let previousY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
cameraState.azimuth -= dx * 0.006;
cameraState.polar = clamp(
cameraState.polar - dy * 0.005,
0.34,
1.38
);
previousX = event.clientX;
previousY = event.clientY;
applyCamera();
});
function stopDragging(event) {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
47,
142
);
applyCamera();
},
{ passive: false }
);
document.getElementById("zoomIn").addEventListener("click", () => {
cameraState.radius = clamp(cameraState.radius - 8, 47, 142);
applyCamera();
});
document.getElementById("zoomOut").addEventListener("click", () => {
cameraState.radius = clamp(cameraState.radius + 8, 47, 142);
applyCamera();
});
document.getElementById("resetCamera").addEventListener("click", resetCamera);
// ---------------------------------------------------------------------
// Route construction and depth-aware pathfinding
// ---------------------------------------------------------------------
function buildDryPathPoints() {
const points = [];
const cellIndices = [];
for (let segment = 0; segment < dryPathDefinition.length - 1; segment++) {
const a = dryPathDefinition[segment];
const b = dryPathDefinition[segment + 1];
const cellDistance =
Math.hypot(
(b[0] - a[0]) * (NX - 1),
(b[1] - a[1]) * (NZ - 1)
);
const steps = Math.max(1, Math.ceil(cellDistance));
for (let step = 0; step <= steps; step++) {
if (segment > 0 && step === 0) continue;
const t = step / steps;
const u = lerp(a[0], b[0], t);
const v = lerp(a[1], b[1], t);
const grid = normalizedToGrid(u, v);
const index = grid.j * NX + grid.i;
if (cellIndices.length && cellIndices[cellIndices.length - 1] === index) {
continue;
}
cellIndices.push(index);
points.push(
gridToWorld(grid.i, grid.j, heightAt(grid.i, grid.j) + 0.38)
);
}
}
return { points, cellIndices };
}
const dryRoute = buildDryPathPoints();
function polylineLength(points) {
let length = 0;
for (let i = 1; i < points.length; i++) {
length += points[i].distanceTo(points[i - 1]);
}
return length;
}
const dryDistanceKm =
(polylineLength(dryRoute.points) / CELL) * KM_PER_CELL;
function nearestNavigableCell(u, v) {
let bestIndex = -1;
let bestDistance = Infinity;
for (let index = 0; index < TOTAL_CELLS; index++) {
const i = index % NX;
const j = Math.floor(index / NX);
const cellU = i / (NX - 1);
const cellV = j / (NZ - 1);
const distance = Math.hypot(cellU - u, cellV - v);
if (distance > 0.17 || distance >= bestDistance) continue;
if (state.waterLevel - heights[index] < VESSEL_DRAFT + 0.035) {
continue;
}
bestDistance = distance;
bestIndex = index;
}
return bestIndex;
}
function findBoatPath() {
const start = nearestNavigableCell(0.02, 0.34);
const end = nearestNavigableCell(0.80, 0.68);
if (start < 0 || end < 0) return null;
const gScore = new Float64Array(TOTAL_CELLS);
gScore.fill(Infinity);
const fScore = new Float64Array(TOTAL_CELLS);
fScore.fill(Infinity);
const cameFrom = new Int32Array(TOTAL_CELLS);
cameFrom.fill(-1);
const closed = new Uint8Array(TOTAL_CELLS);
const open = [start];
gScore[start] = 0;
const endI = end % NX;
const endJ = Math.floor(end / NX);
fScore[start] = Math.hypot(endI - (start % NX), endJ - Math.floor(start / NX));
const neighbors = [
[1, 0],
[-1, 0],
[0, 1],
[0, -1],
[1, 1],
[1, -1],
[-1, 1],
[-1, -1]
];
while (open.length) {
let bestOpen = 0;
for (let k = 1; k < open.length; k++) {
if (fScore[open[k]] < fScore[open[bestOpen]]) {
bestOpen = k;
}
}
const current = open.splice(bestOpen, 1)[0];
if (current === end) {
const cellIndices = [];
let node = end;
while (node !== -1) {
cellIndices.push(node);
node = cameFrom[node];
}
cellIndices.reverse();
const points = cellIndices.map((index) => {
const i = index % NX;
const j = Math.floor(index / NX);
return gridToWorld(i, j, state.waterLevel + 0.24);
});
let minDepth = Infinity;
let totalDepth = 0;
for (const index of cellIndices) {
const depth = state.waterLevel - heights[index];
minDepth = Math.min(minDepth, depth);
totalDepth += depth;
}
const worldLength = polylineLength(points);
const distanceKm = (worldLength / CELL) * KM_PER_CELL;
const averageDepth = totalDepth / cellIndices.length;
const boatSpeed = clamp(6 + averageDepth * 2.2, 7, 15);
return {
points,
cellIndices,
distanceKm,
travelHours: distanceKm / boatSpeed,
minDepth,
averageDepth
};
}
closed[current] = 1;
const currentI = current % NX;
const currentJ = Math.floor(current / NX);
for (const [di, dj] of neighbors) {
const ni = currentI + di;
const nj = currentJ + dj;
if (ni < 0 || ni >= NX || nj < 0 || nj >= NZ) continue;
const next = nj * NX + ni;
if (closed[next]) continue;
const depth = state.waterLevel - heights[next];
if (depth < VESSEL_DRAFT) continue;
// Prevent diagonal movement through blocked corner cells.
if (di !== 0 && dj !== 0) {
const sideA = currentJ * NX + ni;
const sideB = nj * NX + currentI;
if (
state.waterLevel - heights[sideA] < VESSEL_DRAFT ||
state.waterLevel - heights[sideB] < VESSEL_DRAFT
) {
continue;
}
}
const stepDistance = CELL * Math.hypot(di, dj);
const shallowPenalty = 1 + Math.max(0, 1 - depth) * 2.5;
const tentative = gScore[current] + stepDistance * shallowPenalty;
if (tentative < gScore[next]) {
cameFrom[next] = current;
gScore[next] = tentative;
const heuristic = CELL * Math.hypot(endI - ni, endJ - nj);
fScore[next] = tentative + heuristic;
if (!open.includes(next)) open.push(next);
}
}
}
return null;
}
function disposeRouteGroup() {
routeGroup.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const materials = Array.isArray(object.material)
? object.material
: [object.material];
materials.forEach((material) => material.dispose());
}
});
routeGroup.clear();
animatedMarkers = [];
}
function createPolylineCurve(points) {
const curve = new THREE.CurvePath();
for (let i = 1; i < points.length; i++) {
curve.add(new THREE.LineCurve3(points[i - 1], points[i]));
}
return curve;
}
function addRoute(points, routeColor, type) {
if (points.length < 2) return;
const curve = createPolylineCurve(points);
const segments = Math.max(32, points.length * 3);
const glow = new THREE.Mesh(
new THREE.TubeGeometry(curve, segments, type === "boat" ? 0.48 : 0.38, 8, false),
new THREE.MeshBasicMaterial({
color: routeColor,
transparent: true,
opacity: 0.16,
depthWrite: false
})
);
const tube = new THREE.Mesh(
new THREE.TubeGeometry(curve, segments, type === "boat" ? 0.19 : 0.16, 8, false),
new THREE.MeshStandardMaterial({
color: routeColor,
emissive: routeColor,
emissiveIntensity: 0.75,
roughness: 0.34,
metalness: 0.08
})
);
glow.renderOrder = 4;
tube.renderOrder = 5;
routeGroup.add(glow);
routeGroup.add(tube);
const markerGeometry =
type === "boat"
? new THREE.SphereGeometry(0.57, 16, 12)
: new THREE.OctahedronGeometry(0.66, 0);
const markerMaterial = new THREE.MeshStandardMaterial({
color: type === "boat" ? 0xc9ffff : 0xffd69a,
emissive: routeColor,
emissiveIntensity: 1.2,
roughness: 0.25
});
const marker = new THREE.Mesh(markerGeometry, markerMaterial);
routeGroup.add(marker);
animatedMarkers.push({
mesh: marker,
curve,
type,
phase: type === "boat" ? 0.16 : 0.48
});
}
// ---------------------------------------------------------------------
// Water and terrain updates
// ---------------------------------------------------------------------
const state = {
waterLevel: 2.20
};
const lowLand = new THREE.Color(0x315f4e);
const midLand = new THREE.Color(0x70825a);
const highLand = new THREE.Color(0xa18b68);
const seabed = new THREE.Color(0x173d45);
const floodedGround = new THREE.Color(0x24545a);
function updateTerrainAndWater() {
let wetCount = 0;
let navigableCount = 0;
for (let j = 0; j < NZ; j++) {
for (let i = 0; i < NX; i++) {
const index = j * NX + i;
const height = heights[index];
const depth = state.waterLevel - height;
const position = gridToWorld(i, j);
const bottom = -3.1;
const columnHeight = Math.max(0.12, height - bottom);
dummy.position.set(position.x, (height + bottom) / 2, position.z);
dummy.scale.set(CELL * 0.94, columnHeight, CELL * 0.94);
dummy.updateMatrix();
terrainMesh.setMatrixAt(index, dummy.matrix);
if (height < 0) {
color.copy(seabed);
} else if (height < 1.25) {
color.copy(lowLand).lerp(midLand, height / 1.25);
} else {
color.copy(midLand).lerp(highLand, clamp((height - 1.25) / 3.8, 0, 1));
}
if (depth > 0) {
wetCount++;
color.lerp(floodedGround, 0.32);
}
terrainMesh.setColorAt(index, color);
if (depth > 0) {
dummy.position.set(position.x, state.waterLevel, position.z);
dummy.scale.set(CELL * 0.945, 0.085, CELL * 0.945);
dummy.updateMatrix();
waterMesh.setMatrixAt(index, dummy.matrix);
const depthMix = clamp((depth - 0.1) / 2.2, 0, 1);
color.copy(shallowWater).lerp(deepWater, depthMix);
waterMesh.setColorAt(index, color);
} else {
dummy.position.set(position.x, state.waterLevel, position.z);
dummy.scale.set(0, 0, 0);
dummy.updateMatrix();
waterMesh.setMatrixAt(index, dummy.matrix);
}
if (depth >= VESSEL_DRAFT) navigableCount++;
}
}
terrainMesh.instanceMatrix.needsUpdate = true;
terrainMesh.instanceColor.needsUpdate = true;
waterMesh.instanceMatrix.needsUpdate = true;
waterMesh.instanceColor.needsUpdate = true;
return {
wetCount,
navigableCount
};
}
function formatHours(hours) {
if (!Number.isFinite(hours)) return "—";
if (hours < 1) return `${Math.round(hours * 60)} min`;
return `${hours.toFixed(1)} h`;
}
function setText(id, value) {
document.getElementById(id).textContent = value;
}
function updateMetrics(wetStats, boatPath) {
const wetPercent = (wetStats.wetCount / TOTAL_CELLS) * 100;
const dryHours = dryDistanceKm / WALK_SPEED;
setText("floodValue", `${wetPercent.toFixed(0)}%`);
setText(
"navValue",
`${wetStats.navigableCount.toLocaleString()} navigable cells`
);
if (boatPath) {
setText("boatDistance", `${boatPath.distanceKm.toFixed(1)} km`);
setText("boatTime", `${formatHours(boatPath.travelHours)} estimated passage`);
setText("depthValue", `${boatPath.minDepth.toFixed(2)} m`);
} else {
setText("boatDistance", "Closed");
setText("boatTime", "No connected deep-water path");
setText("depthValue", "—");
}
setText("dryDistance", `${dryDistanceKm.toFixed(1)} km`);
setText("dryTime", `${formatHours(dryHours)} on foot`);
let verdictTitle;
let verdictCopy;
if (!boatPath) {
verdictTitle = "Use the dry embankment";
verdictCopy =
"The connected channels are too shallow for the modeled vessel draft.";
} else {
const savings = dryHours - boatPath.travelHours;
if (savings > 0) {
verdictTitle = "Boat route is faster";
verdictCopy =
`The water passage saves about ${formatHours(savings)} over the dry route at this level.`;
} else {
verdictTitle = "Dry route is faster";
verdictCopy =
`The embankment saves about ${formatHours(Math.abs(savings))} over the modeled boat passage.`;
}
}
if (state.waterLevel < 1.25) {
verdictCopy += " Channels are shallow and fragmented.";
} else if (state.waterLevel > 3.7) {
verdictCopy += " Broad low-lying areas are inundated.";
} else {
verdictCopy += " The main channels remain navigable.";
}
setText("verdictTitle", verdictTitle);
setText("verdictCopy", verdictCopy);
}
function updateScenario() {
const wetStats = updateTerrainAndWater();
const boatPath = findBoatPath();
disposeRouteGroup();
if (boatPath) {
addRoute(boatPath.points, 0x51dce0, "boat");
}
addRoute(dryRoute.points, 0xffbd67, "dry");
updateMetrics(wetStats, boatPath);
const formattedLevel = `+${state.waterLevel.toFixed(2)} m`;
setText("levelValue", `+${state.waterLevel.toFixed(2)}`);
setText("sliderValue", formattedLevel);
levelInput.value = state.waterLevel.toFixed(2);
const fill =
((state.waterLevel - Number(levelInput.min)) /
(Number(levelInput.max) - Number(levelInput.min))) *
100;
levelInput.style.setProperty("--fill", `${fill}%`);
document.querySelectorAll("[data-level]").forEach((button) => {
button.classList.toggle(
"active",
Math.abs(Number(button.dataset.level) - state.waterLevel) < 0.03
);
});
}
levelInput.addEventListener("input", () => {
levelTween = null;
state.waterLevel = Number(levelInput.value);
updateScenario();
});
let levelTween = null;
document.querySelectorAll("[data-level]").forEach((button) => {
button.addEventListener("click", () => {
levelTween = {
from: state.waterLevel,
to: Number(button.dataset.level),
start: performance.now(),
duration: 420
};
});
});
// ---------------------------------------------------------------------
// Projected map labels
// ---------------------------------------------------------------------
const labelSpecs = [
{
element: document.getElementById("labelGanges"),
position: gridToWorld(18, 27, 1.1)
},
{
element: document.getElementById("labelBrahmaputra"),
position: gridToWorld(43, 18, 1.1)
},
{
element: document.getElementById("labelBay"),
position: gridToWorld(39, 46, 0.4)
},
{
element: document.getElementById("labelOrigin"),
position: gridToWorld(1, 16, 5.6)
},
{
element: document.getElementById("labelDestination"),
position: gridToWorld(51, 32, 5.6)
}
];
const projected = new THREE.Vector3();
function updateLabels() {
const width = window.innerWidth;
const height = window.innerHeight;
for (const spec of labelSpecs) {
projected.copy(spec.position).project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
projected.x > -1.1 &&
projected.x < 1.1 &&
projected.y > -1.1 &&
projected.y < 1.1;
spec.element.style.display = visible ? "block" : "none";
if (visible) {
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
spec.element.style.left = `${x}px`;
spec.element.style.top = `${y}px`;
}
}
}
// ---------------------------------------------------------------------
// Resize and render loop
// ---------------------------------------------------------------------
function onResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.8));
renderer.setSize(window.innerWidth, window.innerHeight);
}
window.addEventListener("resize", onResize);
const clock = new THREE.Clock();
function animate(now) {
requestAnimationFrame(animate);
if (levelTween) {
const t = clamp(
(now - levelTween.start) / levelTween.duration,
0,
1
);
const eased = t * t * (3 - 2 * t);
const nextLevel = lerp(levelTween.from, levelTween.to, eased);
if (Math.abs(nextLevel - state.waterLevel) > 0.025 || t >= 1) {
state.waterLevel = nextLevel;
updateScenario();
}
if (t >= 1) levelTween = null;
}
const elapsed = clock.getElapsedTime();
for (const marker of animatedMarkers) {
const progress = (elapsed * (marker.type === "boat" ? 0.065 : 0.035) + marker.phase) % 1;
const point = marker.curve.getPointAt(progress);
marker.mesh.position.copy(point);
if (marker.type === "dry") {
marker.mesh.rotation.y += 0.025;
marker.mesh.rotation.x += 0.018;
} else {
marker.mesh.position.y += Math.sin(elapsed * 4) * 0.035;
}
}
updateLabels();
renderer.render(scene, camera);
}
applyCamera();
updateScenario();
requestAnimationFrame(animate);
</script>
</body>
</html>
```