Prompt specification
Build or customize the Three.js 3D scene "Village upstream and town downstream" 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: Village upstream and town downstream
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/village-upstream-and-town-downstream-x1359
Scene Description Prompt:
Use Three.js from cdnjs to arrange a watershed with a headwater village, tributary junction, and downstream town. Trace water paths to show which settlements share the same drainage basin. Deliver one self-contained HTML file with low-poly forms.
Working Three.js Starter (village-upstream-and-town-downstream-x1359):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Alder Watershed — Three.js</title>
<style>
:root {
--ink: #17343b;
--muted: #567077;
--panel: rgba(248, 251, 247, 0.88);
--line: rgba(29, 69, 74, 0.16);
--teal: #147f91;
--mint: #63e2d3;
--amber: #c77b38;
--shadow: 0 18px 48px rgba(25, 54, 58, 0.15);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dde8e4;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button { font: inherit; }
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 52% 45%, transparent 48%, rgba(31, 65, 66, 0.08) 100%),
linear-gradient(180deg, rgba(255,255,255,0.07), transparent 28%);
z-index: 2;
}
.ui {
position: fixed;
z-index: 10;
pointer-events: none;
}
.panel {
background: var(--panel);
border: 1px solid rgba(255, 255, 255, 0.7);
box-shadow: var(--shadow);
backdrop-filter: blur(16px) saturate(120%);
-webkit-backdrop-filter: blur(16px) saturate(120%);
}
.intro {
top: 20px;
left: 20px;
width: min(360px, calc(100vw - 40px));
padding: 19px 21px 18px;
border-radius: 19px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
color: var(--teal);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 18px;
height: 2px;
border-radius: 2px;
background: var(--teal);
}
h1 {
margin: 0;
font-size: clamp(24px, 3vw, 34px);
line-height: 1;
letter-spacing: -0.045em;
}
.intro p {
margin: 10px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.legend {
top: 20px;
right: 20px;
width: 220px;
padding: 14px 16px;
border-radius: 16px;
}
.legend-title {
margin-bottom: 10px;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
color: var(--muted);
}
.legend-row {
display: flex;
align-items: center;
gap: 10px;
margin: 8px 0;
font-size: 12px;
}
.swatch {
width: 25px;
height: 4px;
border-radius: 4px;
flex: none;
}
.swatch.water { background: #287f98; }
.swatch.flow { background: #63e2d3; box-shadow: 0 0 8px rgba(99,226,211,.5); }
.swatch.divide {
height: 2px;
background: repeating-linear-gradient(90deg, var(--amber) 0 6px, transparent 6px 10px);
}
.legend-note {
margin-top: 11px;
padding-top: 10px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
#labels {
position: fixed;
inset: 0;
z-index: 6;
pointer-events: none;
}
.map-label {
position: absolute;
transform: translate(-50%, -100%);
display: flex;
align-items: center;
gap: 8px;
max-width: 210px;
padding: 8px 11px 8px 9px;
border: 1px solid rgba(255,255,255,.86);
border-radius: 12px;
background: rgba(250, 253, 249, .92);
box-shadow: 0 9px 24px rgba(30, 59, 61, .16);
color: var(--ink);
text-align: left;
white-space: nowrap;
pointer-events: auto;
cursor: pointer;
transition: transform .18s ease, background .18s ease, box-shadow .18s ease;
}
.map-label::after {
content: "";
position: absolute;
left: 50%;
top: 100%;
width: 1px;
height: 17px;
background: linear-gradient(var(--ink), transparent);
opacity: .55;
}
.map-label:hover,
.map-label.selected {
transform: translate(-50%, -100%) translateY(-3px);
background: #fff;
box-shadow: 0 12px 30px rgba(30, 59, 61, .22);
}
.map-label.selected {
border-color: rgba(20,127,145,.45);
}
.label-dot {
width: 9px;
height: 9px;
border-radius: 50%;
flex: none;
background: var(--teal);
box-shadow: 0 0 0 4px rgba(20,127,145,.13);
}
.label-dot.town { background: #e28b42; box-shadow: 0 0 0 4px rgba(226,139,66,.14); }
.label-dot.junction { background: #6657a8; box-shadow: 0 0 0 4px rgba(102,87,168,.14); }
.label-text strong {
display: block;
font-size: 12px;
line-height: 1.1;
}
.label-text small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: .08em;
text-transform: uppercase;
}
.minor-label {
position: absolute;
transform: translate(-50%, -50%);
padding: 4px 7px;
border-radius: 6px;
background: rgba(244,247,239,.74);
color: rgba(42,75,77,.78);
font-size: 9px;
font-weight: 800;
letter-spacing: .1em;
text-transform: uppercase;
pointer-events: none;
white-space: nowrap;
}
.info {
left: 20px;
bottom: 20px;
width: min(390px, calc(100vw - 40px));
padding: 17px 18px 15px;
border-radius: 18px;
pointer-events: auto;
}
.info-top {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 14px;
}
.info-kicker {
margin-bottom: 4px;
color: var(--teal);
font-size: 9px;
font-weight: 800;
letter-spacing: .13em;
text-transform: uppercase;
}
.info h2 {
margin: 0;
font-size: 20px;
letter-spacing: -.03em;
}
.basin-badge {
flex: none;
padding: 6px 8px;
border-radius: 999px;
background: rgba(99,226,211,.15);
color: #28776f;
font-size: 9px;
font-weight: 800;
letter-spacing: .06em;
text-transform: uppercase;
}
.info p {
margin: 9px 0 11px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.route {
padding: 10px 11px;
border-radius: 11px;
background: rgba(31, 95, 105, .07);
color: #315f65;
font-size: 11px;
font-weight: 700;
line-height: 1.45;
}
.info-bottom {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 12px;
}
.metric {
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.metric strong {
display: block;
color: var(--ink);
font-size: 12px;
}
.small-button {
padding: 8px 10px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255,255,255,.7);
color: var(--ink);
font-size: 10px;
font-weight: 800;
cursor: pointer;
transition: background .15s ease, transform .15s ease;
}
.small-button:hover {
background: white;
transform: translateY(-1px);
}
.controls {
right: 20px;
bottom: 20px;
display: flex;
gap: 8px;
pointer-events: auto;
}
.control-button {
height: 40px;
padding: 0 13px;
border: 1px solid rgba(255,255,255,.72);
border-radius: 12px;
background: rgba(248,251,247,.9);
box-shadow: 0 10px 28px rgba(28,58,61,.13);
color: var(--ink);
font-size: 11px;
font-weight: 800;
cursor: pointer;
transition: background .15s ease, transform .15s ease;
}
.control-button:hover { transform: translateY(-2px); background: white; }
.control-button.active {
background: #1b5962;
color: white;
}
.hint {
right: 20px;
bottom: 70px;
padding: 7px 10px;
border-radius: 8px;
background: rgba(248,251,247,.68);
color: rgba(38,70,74,.67);
font-size: 9px;
font-weight: 700;
letter-spacing: .02em;
}
#loading {
position: fixed;
inset: 0;
z-index: 100;
display: grid;
place-items: center;
background: #dde8e4;
color: #315f65;
font-size: 12px;
font-weight: 800;
letter-spacing: .08em;
text-transform: uppercase;
transition: opacity .35s ease;
}
#loading.hidden { opacity: 0; pointer-events: none; }
.spinner {
width: 28px;
height: 28px;
margin: 0 auto 12px;
border: 3px solid rgba(20,127,145,.15);
border-top-color: var(--teal);
border-radius: 50%;
animation: spin .8s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
@media (max-width: 760px) {
.intro {
top: 12px;
left: 12px;
width: calc(100vw - 24px);
padding: 14px 16px;
}
.intro p { display: none; }
.legend { display: none; }
.info {
left: 12px;
bottom: 62px;
width: calc(100vw - 24px);
padding: 14px;
}
.info p { display: none; }
.route { font-size: 10px; }
.controls { right: 12px; bottom: 12px; }
.hint { display: none; }
.map-label { transform: translate(-50%, -100%) scale(.84); }
.map-label:hover,
.map-label.selected { transform: translate(-50%, -100%) translateY(-3px) scale(.84); }
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="vignette"></div>
<div id="labels"></div>
<header class="ui panel intro">
<div class="eyebrow">Connected Waters</div>
<h1>Alder Watershed</h1>
<p>Follow the streams from their highland source to the shared lowland outlet.</p>
</header>
<aside class="ui panel legend">
<div class="legend-title">Map key</div>
<div class="legend-row"><span class="swatch water"></span> Watercourse</div>
<div class="legend-row"><span class="swatch flow"></span> Animated flow trace</div>
<div class="legend-row"><span class="swatch divide"></span> Drainage divide</div>
<div class="legend-note">Every blue route stays inside the same Alder drainage basin.</div>
</aside>
<section class="ui panel info" aria-live="polite">
<div class="info-top">
<div>
<div id="infoKicker" class="info-kicker">Upstream settlement</div>
<h2 id="infoTitle">Highwater Village</h2>
</div>
<div class="basin-badge">Alder basin</div>
</div>
<p id="infoDescription"></p>
<div id="infoRoute" class="route"></div>
<div class="info-bottom">
<div class="metric"><strong id="infoMetric">Source elevation 7.2 m</strong><span id="infoMetricSub">First permanent headwater stream</span></div>
<button id="focusButton" class="small-button">Focus view</button>
</div>
</section>
<div class="ui hint">Drag to orbit · Right-drag to pan · Scroll to zoom</div>
<nav class="ui controls" aria-label="Map controls">
<button id="basinToggle" class="control-button active" aria-pressed="true">Basin trace on</button>
<button id="topButton" class="control-button">Plan view</button>
<button id="resetButton" class="control-button">Reset</button>
</nav>
<div id="loading"><div><div class="spinner"></div>Building watershed</div></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const sceneHost = document.getElementById("scene");
const labelsHost = document.getElementById("labels");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdde8e4);
scene.fog = new THREE.Fog(0xdde8e4, 115, 205);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute("aria-label", "Interactive low-poly watershed map");
sceneHost.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
300
);
const hemi = new THREE.HemisphereLight(0xf6fbf2, 0x6d735f, 2.15);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff2d5, 2.5);
sun.position.set(-35, 62, 28);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -62;
sun.shadow.camera.right = 62;
sun.shadow.camera.top = 52;
sun.shadow.camera.bottom = -52;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 150;
sun.shadow.normalBias = 0.035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x9bd9df, 0.65);
fill.position.set(45, 25, -40);
scene.add(fill);
const TERRAIN_W = 104;
const TERRAIN_D = 78;
const HALF_W = TERRAIN_W / 2;
const HALF_D = TERRAIN_D / 2;
const mainPoints = [
[-35, -27, 7.2],
[-31, -21, 6.55],
[-27, -14, 5.65],
[-22, -7, 4.72],
[-16, 0, 3.72],
[-9, 6, 2.88],
[-2, 9, 2.15],
[5, 12, 1.72],
[12, 16, 1.34],
[19, 19, 1.02],
[25, 22, 0.75],
[30, 25, 0.55]
].map(([x, z, y]) => new THREE.Vector3(x, y, z));
const tributaryPoints = [
[23, -21, 5.25],
[19, -15, 4.72],
[13, -9, 3.92],
[7, -3, 3.18],
[2, 3, 2.62],
[-2, 9, 2.15]
].map(([x, z, y]) => new THREE.Vector3(x, y, z));
const mainCurve = new THREE.CatmullRomCurve3(mainPoints, false, "catmullrom", 0.5);
const tributaryCurve = new THREE.CatmullRomCurve3(tributaryPoints, false, "catmullrom", 0.5);
const routeSamples = [
mainCurve.getPoints(120),
tributaryCurve.getPoints(80)
];
const smoothstep = (a, b, x) => {
const t = THREE.MathUtils.clamp((x - a) / (b - a), 0, 1);
return t * t * (3 - 2 * t);
};
function hill(x, z, cx, cz, sx, sz, amount) {
const dx = (x - cx) / sx;
const dz = (z - cz) / sz;
return amount * Math.exp(-(dx * dx + dz * dz));
}
function nearestRiver(x, z) {
let bestDistance = Infinity;
let bestY = 0;
for (const samples of routeSamples) {
for (let i = 0; i < samples.length - 1; i++) {
const a = samples[i];
const b = samples[i + 1];
const dx = b.x - a.x;
const dz = b.z - a.z;
const lengthSq = dx * dx + dz * dz;
const t = lengthSq === 0
? 0
: THREE.MathUtils.clamp(((x - a.x) * dx + (z - a.z) * dz) / lengthSq, 0, 1);
const px = a.x + dx * t;
const pz = a.z + dz * t;
const distance = Math.hypot(x - px, z - pz);
if (distance < bestDistance) {
bestDistance = distance;
bestY = THREE.MathUtils.lerp(a.y, b.y, t);
}
}
}
return { distance: bestDistance, y: bestY };
}
function heightAt(x, z) {
let base =
0.9 + (20 - z) * 0.035 +
Math.sin(x * 0.11) * 0.18 +
Math.cos(z * 0.16) * 0.13;
base += hill(x, z, -44, -3, 9, 16, 5.5);
base += hill(x, z, 43, -4, 10, 17, 5.5);
base += hill(x, z, -38, 22, 10, 14, 3.0);
base += hill(x, z, 41, 24, 9, 13, 3.4);
base += hill(x, z, -34, -29, 12, 11, 4.4);
base += hill(x, z, 21, -25, 12, 11, 4.0);
base += hill(x, z, 0, -37, 18, 5, 2.8);
base += hill(x, z, -46, 12, 7, 15, 2.8);
const river = nearestRiver(x, z);
if (river.distance < 4.8) {
const bankBlend = smoothstep(1.15, 4.8, river.distance);
return THREE.MathUtils.lerp(river.y - 0.27, base, bankBlend);
}
return base;
}
function hash2(x, z) {
const value = Math.sin(x * 12.9898 + z * 78.233) * 43758.5453;
return value - Math.floor(value);
}
function groundColor(x, z, y) {
const low = new THREE.Color(0x6f9368);
const middle = new THREE.Color(0x91a570);
const high = new THREE.Color(0xb9ad82);
let color;
if (y < 2.5) {
color = low.clone().lerp(middle, THREE.MathUtils.clamp(y / 2.5, 0, 1));
} else if (y < 5.2) {
color = middle.clone().lerp(high, (y - 2.5) / 2.7);
} else {
color = high.clone();
}
color.multiplyScalar(0.91 + hash2(x, z) * 0.15);
return color;
}
// Faceted terrain.
let terrainGeometry = new THREE.PlaneGeometry(TERRAIN_W, TERRAIN_D, 52, 40);
terrainGeometry.rotateX(-Math.PI / 2);
const terrainPosition = terrainGeometry.attributes.position;
for (let i = 0; i < terrainPosition.count; i++) {
const x = terrainPosition.getX(i);
const z = terrainPosition.getZ(i);
terrainPosition.setY(i, heightAt(x, z));
}
terrainPosition.needsUpdate = true;
terrainGeometry = terrainGeometry.toNonIndexed();
const trianglePositions = terrainGeometry.attributes.position;
const terrainColors = new Float32Array(trianglePositions.count * 3);
for (let i = 0; i < trianglePositions.count; i += 3) {
const x = (
terrainGeometry.attributes.position.getX(i) +
terrainGeometry.attributes.position.getX(i + 1) +
terrainGeometry.attributes.position.getX(i + 2)
) / 3;
const z = (
terrainGeometry.attributes.position.getZ(i) +
terrainGeometry.attributes.position.getZ(i + 1) +
terrainGeometry.attributes.position.getZ(i + 2)
) / 3;
const y = (
terrainGeometry.attributes.position.getY(i) +
terrainGeometry.attributes.position.getY(i + 1) +
terrainGeometry.attributes.position.getY(i + 2)
) / 3;
const color = groundColor(x, z, y);
for (let j = 0; j < 3; j++) {
terrainColors[(i + j) * 3] = color.r;
terrainColors[(i + j) * 3 + 1] = color.g;
terrainColors[(i + j) * 3 + 2] = color.b;
}
}
terrainGeometry.setAttribute("color", new THREE.BufferAttribute(terrainColors, 3));
terrainGeometry.computeVertexNormals();
const terrainMaterial = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.98,
metalness: 0,
flatShading: true
});
const terrain = new THREE.Mesh(terrainGeometry, terrainMaterial);
terrain.receiveShadow = true;
scene.add(terrain);
// Dark earth skirt around the raised map.
const perimeter = [];
const edgeSegments = 32;
for (let i = 0; i < edgeSegments; i++) {
perimeter.push(new THREE.Vector2(
THREE.MathUtils.lerp(-HALF_W, HALF_W, i / edgeSegments),
-HALF_D
));
}
for (let i = 0; i < 28; i++) {
perimeter.push(new THREE.Vector2(
HALF_W,
THREE.MathUtils.lerp(-HALF_D, HALF_D, i / 28)
));
}
for (let i = 0; i < edgeSegments; i++) {
perimeter.push(new THREE.Vector2(
THREE.MathUtils.lerp(HALF_W, -HALF_W, i / edgeSegments),
HALF_D
));
}
for (let i = 0; i < 28; i++) {
perimeter.push(new THREE.Vector2(
-HALF_W,
THREE.MathUtils.lerp(HALF_D, -HALF_D, i / 28)
));
}
const skirtPositions = [];
const skirtColors = [];
const skirtTop = new THREE.Color(0x827858);
const skirtBottom = new THREE.Color(0x514f43);
for (let i = 0; i < perimeter.length; i++) {
const a = perimeter[i];
const b = perimeter[(i + 1) % perimeter.length];
const ay = heightAt(a.x, a.y);
const by = heightAt(b.x, b.y);
const bottom = -2.9;
skirtPositions.push(
a.x, ay, a.y,
a.x, bottom, a.y,
b.x, by, b.y,
b.x, by, b.y,
a.x, bottom, a.y,
b.x, bottom, b.y
);
for (let j = 0; j < 6; j++) {
const color = skirtTop.clone().lerp(skirtBottom, j % 3 === 2 ? 0.8 : 0.25);
skirtColors.push(color.r, color.g, color.b);
}
}
const skirtGeometry = new THREE.BufferGeometry();
skirtGeometry.setAttribute("position", new THREE.Float32BufferAttribute(skirtPositions, 3));
skirtGeometry.setAttribute("color", new THREE.Float32BufferAttribute(skirtColors, 3));
skirtGeometry.computeVertexNormals();
const skirt = new THREE.Mesh(
skirtGeometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 1,
flatShading: true,
side: THREE.DoubleSide
})
);
skirt.receiveShadow = true;
scene.add(skirt);
const groundPlane = new THREE.Mesh(
new THREE.PlaneGeometry(280, 240),
new THREE.MeshStandardMaterial({ color: 0xd8ded1, roughness: 1 })
);
groundPlane.rotation.x = -Math.PI / 2;
groundPlane.position.y = -2.95;
groundPlane.receiveShadow = true;
scene.add(groundPlane);
// Water and the optional animated drainage trace.
const waterMaterial = new THREE.MeshStandardMaterial({
color: 0x267e98,
emissive: 0x0d3444,
emissiveIntensity: 0.4,
roughness: 0.3,
metalness: 0.08
});
const mainRiver = new THREE.Mesh(
new THREE.TubeGeometry(mainCurve, 150, 0.57, 7, false),
waterMaterial
);
mainRiver.receiveShadow = true;
scene.add(mainRiver);
const tributaryRiver = new THREE.Mesh(
new THREE.TubeGeometry(tributaryCurve, 100, 0.43, 7, false),
waterMaterial
);
tributaryRiver.receiveShadow = true;
scene.add(tributaryRiver);
const flowGroup = new THREE.Group();
scene.add(flowGroup);
const mainTraceMaterial = new THREE.MeshBasicMaterial({
color: 0x74f0df,
transparent: true,
opacity: 0.32,
depthWrite: false
});
const tributaryTraceMaterial = new THREE.MeshBasicMaterial({
color: 0x8cf5dc,
transparent: true,
opacity: 0.29,
depthWrite: false
});
const mainTrace = new THREE.Mesh(
new THREE.TubeGeometry(mainCurve, 150, 0.68, 7, false),
mainTraceMaterial
);
mainTrace.renderOrder = 2;
flowGroup.add(mainTrace);
const tributaryTrace = new THREE.Mesh(
new THREE.TubeGeometry(tributaryCurve, 100, 0.53, 7, false),
tributaryTraceMaterial
);
tributaryTrace.renderOrder = 2;
flowGroup.add(tributaryTrace);
const arrowGeometry = new THREE.ConeGeometry(0.22, 0.76, 3);
const arrowMaterial = new THREE.MeshBasicMaterial({
color: 0xe7fff5,
transparent: true,
opacity: 0.92
});
const flowArrows = [];
function addFlowArrows(curve, count, phaseOffset) {
for (let i = 0; i < count; i++) {
const arrow = new THREE.Mesh(arrowGeometry, arrowMaterial);
arrow.renderOrder = 3;
flowGroup.add(arrow);
flowArrows.push({
mesh: arrow,
curve,
offset: phaseOffset + i / count
});
}
}
addFlowArrows(mainCurve, 22, 0);
addFlowArrows(tributaryCurve, 11, 0.09);
// Approximate drainage divide surrounding the connected Alder basin.
const basinGroup = new THREE.Group();
scene.add(basinGroup);
const divideXZ = [
[-46, -18], [-35, -34], [-13, -37], [10, -34], [31, -27],
[42, -10], [40, 10], [31, 29], [10, 36], [-12, 34],
[-32, 24], [-45, 7]
];
const dividePoints = divideXZ.map(([x, z]) =>
new THREE.Vector3(x, heightAt(x, z) + 0.55, z)
);
dividePoints.push(dividePoints[0].clone());
const divideGeometry = new THREE.BufferGeometry().setFromPoints(dividePoints);
const divideMaterial = new THREE.LineDashedMaterial({
color: 0xc77b38,
dashSize: 1.7,
gapSize: 1.05,
transparent: true,
opacity: 0.9
});
const divideLine = new THREE.Line(divideGeometry, divideMaterial);
divideLine.computeLineDistances();
basinGroup.add(divideLine);
// Low-poly settlement construction.
const wallMaterials = [
new THREE.MeshStandardMaterial({ color: 0xe8d7b5, roughness: 0.9 }),
new THREE.MeshStandardMaterial({ color: 0xd9c39e, roughness: 0.9 }),
new THREE.MeshStandardMaterial({ color: 0xf0dfbd, roughness: 0.9 }),
new THREE.MeshStandardMaterial({ color: 0xcbb892, roughness: 0.9 })
];
const roofMaterials = [
new THREE.MeshStandardMaterial({
color: 0xb95e42, roughness: 0.86, side: THREE.DoubleSide
}),
new THREE.MeshStandardMaterial({
color: 0x4f6970, roughness: 0.86, side: THREE.DoubleSide
}),
new THREE.MeshStandardMaterial({
color: 0x8b5943, roughness: 0.86, side: THREE.DoubleSide
})
];
const windowMaterial = new THREE.MeshStandardMaterial({
color: 0xffd78c,
emissive: 0xf1a842,
emissiveIntensity: 0.32,
roughness: 0.5
});
const doorMaterial = new THREE.MeshStandardMaterial({
color: 0x604a39,
roughness: 0.95
});
const settlementTargets = [];
function makeRoofGeometry(w, d, wallHeight, roofHeight) {
const geometry = new THREE.BufferGeometry();
const positions = [
-w / 2, wallHeight, -d / 2,
w / 2, wallHeight, -d / 2,
0, wallHeight + roofHeight, -d / 2,
-w / 2, wallHeight, d / 2,
w / 2, wallHeight, d / 2,
0, wallHeight + roofHeight, d / 2
];
const indices = [
0, 2, 1,
3, 4, 5,
0, 3, 5, 0, 5, 2,
1, 2, 5, 1, 5, 4
];
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.setIndex(indices);
geometry.computeVertexNormals();
return geometry;
}
function addHouse(options) {
const {
x, z, w = 2.5, d = 2.8, h = 2.15,
rotation = 0, settlement, wallIndex = 0, roofIndex = 0
} = options;
const group = new THREE.Group();
group.position.set(x, heightAt(x, z), z);
group.rotation.y = rotation;
const body = new THREE.Mesh(
new THREE.BoxGeometry(w, h, d),
wallMaterials[wallIndex % wallMaterials.length]
);
body.position.y = h / 2;
body.castShadow = true;
body.receiveShadow = true;
body.userData.settlement = settlement;
group.add(body);
const roof = new THREE.Mesh(
makeRoofGeometry(w + 0.25, d + 0.25, h, Math.max(w, d) * 0.42),
roofMaterials[roofIndex % roofMaterials.length]
);
roof.castShadow = true;
roof.userData.settlement = settlement;
group.add(roof);
const door = new THREE.Mesh(
new THREE.BoxGeometry(0.48, 0.9, 0.08),
doorMaterial
);
door.position.set(0, 0.45, d / 2 + 0.045);
group.add(door);
for (const side of [-1, 1]) {
const window = new THREE.Mesh(
new THREE.BoxGeometry(0.42, 0.42, 0.06),
windowMaterial
);
window.position.set(side * w * 0.26, h * 0.58, d / 2 + 0.05);
group.add(window);
}
if (Math.random() > 0.48) {
const chimney = new THREE.Mesh(
new THREE.BoxGeometry(0.35, 0.8, 0.35),
roofMaterials[roofIndex % roofMaterials.length]
);
chimney.position.set(w * 0.24, h + 0.5, -d * 0.18);
chimney.castShadow = true;
group.add(chimney);
}
settlementTargets.push(body, roof);
scene.add(group);
return group;
}
function addSettlementPad(x, z, radius, color) {
const pad = new THREE.Mesh(
new THREE.CircleGeometry(radius, 12),
new THREE.MeshStandardMaterial({
color,
roughness: 1,
transparent: true,
opacity: 0.62,
polygonOffset: true,
polygonOffsetFactor: -1
})
);
pad.rotation.x = -Math.PI / 2;
pad.position.set(x, heightAt(x, z) + 0.07, z);
pad.receiveShadow = true;
scene.add(pad);
}
addSettlementPad(-37, -28, 5.2, 0xb8a982);
addSettlementPad(-2.5, 10, 3.8, 0xa99a7b);
addSettlementPad(32, 28, 7.1, 0xb7a27c);
const headwaterHouses = [
{ x: -40.0, z: -28.0, w: 2.4, d: 2.9, rotation: 0.12 },
{ x: -37.1, z: -31.3, w: 2.6, d: 2.8, rotation: -0.08 },
{ x: -39.0, z: -24.6, w: 2.2, d: 2.6, rotation: 0.05 },
{ x: -34.6, z: -32.3, w: 2.5, d: 3.0, rotation: 0.2 },
{ x: -33.9, z: -28.8, w: 2.3, d: 2.7, rotation: -0.18 }
];
headwaterHouses.forEach((h, i) => addHouse({
...h, settlement: "headwater", wallIndex: i, roofIndex: i % 2
}));
const junctionHouses = [
{ x: -4.8, z: 11.8, w: 2.6, d: 2.8, rotation: 0.08 },
{ x: -0.7, z: 13.2, w: 2.3, d: 2.6, rotation: -0.12 },
{ x: -5.5, z: 8.0, w: 2.1, d: 2.4, rotation: 0.2 },
{ x: 0.4, z: 7.2, w: 2.2, d: 2.5, rotation: -0.15 }
];
junctionHouses.forEach((h, i) => addHouse({
...h, settlement: "junction", wallIndex: i + 1, roofIndex: 1
}));
const townHouses = [
{ x: 32.0, z: 27.0, w: 3.0, d: 3.2, rotation: 0.03 },
{ x: 35.7, z: 29.3, w: 2.8, d: 3.0, rotation: -0.12 },
{ x: 36.0, z: 24.7, w: 2.5, d: 2.8, rotation: 0.11 },
{ x: 29.6, z: 31.1, w: 3.1, d: 3.2, rotation: -0.06 },
{ x: 26.9, z: 28.5, w: 2.7, d: 2.8, rotation: 0.16 },
{ x: 33.7, z: 33.0, w: 2.6, d: 2.9, rotation: 0.08 },
{ x: 39.1, z: 30.1, w: 2.4, d: 2.8, rotation: -0.1 },
{ x: 23.7, z: 26.7, w: 2.8, d: 2.9, rotation: 0.05 },
{ x: 38.5, z: 35.0, w: 2.3, d: 2.5, rotation: -0.15 }
];
townHouses.forEach((h, i) => addHouse({
...h, settlement: "town", wallIndex: i % wallMaterials.length, roofIndex: i % 3
}));
// A small clock tower makes the downstream town easy to recognize.
const tower = new THREE.Group();
const towerX = 34.2;
const towerZ = 32.0;
tower.position.set(towerX, heightAt(towerX, towerZ), towerZ);
const towerBody = new THREE.Mesh(
new THREE.CylinderGeometry(1.05, 1.2, 5.2, 8),
wallMaterials[2]
);
towerBody.position.y = 2.6;
towerBody.castShadow = true;
towerBody.userData.settlement = "town";
tower.add(towerBody);
settlementTargets.push(towerBody);
const towerRoof = new THREE.Mesh(
new THREE.ConeGeometry(1.5, 2.0, 8),
roofMaterials[0]
);
towerRoof.position.y = 6.0;
towerRoof.castShadow = true;
towerRoof.userData.settlement = "town";
tower.add(towerRoof);
settlementTargets.push(towerRoof);
const clockFace = new THREE.Mesh(
new THREE.CircleGeometry(0.5, 12),
windowMaterial
);
clockFace.position.set(0, 3.8, 1.17);
tower.add(clockFace);
scene.add(tower);
// Junction marker and signpost.
const markerX = -4.1;
const markerZ = 9.0;
const marker = new THREE.Mesh(
new THREE.CylinderGeometry(1.55, 1.85, 0.38, 8),
new THREE.MeshStandardMaterial({ color: 0x796c55, roughness: 0.95 })
);
marker.position.set(markerX, heightAt(markerX, markerZ) + 0.16, markerZ);
marker.castShadow = true;
scene.add(marker);
const post = new THREE.Mesh(
new THREE.CylinderGeometry(0.1, 0.13, 2.8, 6),
new THREE.MeshStandardMaterial({ color: 0x74563a, roughness: 1 })
);
post.position.set(-5.1, heightAt(-5.1, 8.7) + 1.4, 8.7);
post.castShadow = true;
scene.add(post);
const sign = new THREE.Mesh(
new THREE.BoxGeometry(2.1, 0.8, 0.15),
new THREE.MeshStandardMaterial({ color: 0xe2c681, roughness: 0.9 })
);
sign.position.set(-5.1, post.position.y + 1.0, 8.78);
sign.rotation.y = -0.14;
sign.castShadow = true;
scene.add(sign);
// A footbridge at the town crossing.
const bridgePoint = mainCurve.getPointAt(0.91);
const bridgeTangent = mainCurve.getTangentAt(0.91);
const bridge = new THREE.Group();
bridge.position.set(bridgePoint.x, bridgePoint.y + 0.18, bridgePoint.z);
bridge.rotation.y = -Math.atan2(bridgeTangent.z, bridgeTangent.x);
const bridgeDeck = new THREE.Mesh(
new THREE.BoxGeometry(6.2, 0.24, 1.15),
new THREE.MeshStandardMaterial({ color: 0x8e6948, roughness: 1 })
);
bridgeDeck.castShadow = true;
bridge.add(bridgeDeck);
for (const side of [-1, 1]) {
const rail = new THREE.Mesh(
new THREE.BoxGeometry(6.1, 0.16, 0.16),
new THREE.MeshStandardMaterial({ color: 0x694b36, roughness: 1 })
);
rail.position.set(0, 0.55, side * 0.53);
bridge.add(rail);
for (const x of [-2.5, 0, 2.5]) {
const support = new THREE.Mesh(
new THREE.BoxGeometry(0.16, 0.8, 0.16),
new THREE.MeshStandardMaterial({ color: 0x694b36, roughness: 1 })
);
support.position.set(x, 0.3, side * 0.53);
bridge.add(support);
}
}
scene.add(bridge);
// Instanced low-poly conifers.
let randomSeed = 7183;
function random() {
randomSeed = (randomSeed * 1664525 + 1013904223) >>> 0;
return randomSeed / 4294967296;
}
const treePositions = [];
let attempts = 0;
while (treePositions.length < 125 && attempts < 2500) {
attempts++;
const x = THREE.MathUtils.lerp(-48, 48, random());
const z = THREE.MathUtils.lerp(-36, 36, random());
const river = nearestRiver(x, z);
const nearHeadwater = Math.hypot(x + 37, z + 28) < 7;
const nearJunction = Math.hypot(x + 2.5, z - 10) < 6;
const nearTown = Math.hypot(x - 32, z - 28) < 9;
if (river.distance < 3.6 || nearHeadwater || nearJunction || nearTown) continue;
const y = heightAt(x, z);
const slopeX = Math.abs(heightAt(x + 1, z) - y);
const slopeZ = Math.abs(heightAt(x, z + 1) - y);
if (slopeX + slopeZ > 2.3) continue;
treePositions.push({ x, y, z, scale: 0.72 + random() * 0.72 });
}
const trunkGeometry = new THREE.CylinderGeometry(0.16, 0.23, 1.55, 5);
const crownGeometry = new THREE.ConeGeometry(0.9, 2.65, 6);
const trunkMesh = new THREE.InstancedMesh(
trunkGeometry,
new THREE.MeshStandardMaterial({ color: 0x6b5239, roughness: 1 }),
treePositions.length
);
const crownMesh = new THREE.InstancedMesh(
crownGeometry,
new THREE.MeshStandardMaterial({ color: 0x4f7658, roughness: 1, flatShading: true }),
treePositions.length
);
const dummy = new THREE.Object3D();
treePositions.forEach((tree, i) => {
const rotation = random() * Math.PI * 2;
dummy.position.set(tree.x, tree.y + 0.72 * tree.scale, tree.z);
dummy.rotation.set(0, rotation, 0);
dummy.scale.setScalar(tree.scale);
dummy.updateMatrix();
trunkMesh.setMatrixAt(i, dummy.matrix);
dummy.position.set(tree.x, tree.y + 2.05 * tree.scale, tree.z);
dummy.rotation.set(0, rotation, 0);
dummy.scale.setScalar(tree.scale);
dummy.updateMatrix();
crownMesh.setMatrixAt(i, dummy.matrix);
const tint = new THREE.Color().setHSL(
0.28 + random() * 0.035,
0.24 + random() * 0.13,
0.27 + random() * 0.12
);
crownMesh.setColorAt(i, tint);
});
trunkMesh.castShadow = true;
crownMesh.castShadow = true;
trunkMesh.instanceMatrix.needsUpdate = true;
crownMesh.instanceMatrix.needsUpdate = true;
if (crownMesh.instanceColor) crownMesh.instanceColor.needsUpdate = true;
scene.add(trunkMesh, crownMesh);
// A scatter of angular rocks.
const rockGeometry = new THREE.DodecahedronGeometry(0.75, 0);
const rockMaterial = new THREE.MeshStandardMaterial({
color: 0x85877a,
roughness: 1,
flatShading: true
});
const rocks = new THREE.InstancedMesh(rockGeometry, rockMaterial, 34);
for (let i = 0; i < 34; i++) {
const x = THREE.MathUtils.lerp(-47, 47, random());
const z = THREE.MathUtils.lerp(-35, 35, random());
const river = nearestRiver(x, z);
if (river.distance < 1.8) continue;
const scale = 0.25 + random() * 0.7;
dummy.position.set(x, heightAt(x, z) + scale * 0.35, z);
dummy.rotation.set(random(), random() * Math.PI, random());
dummy.scale.set(scale * 1.2, scale * 0.65, scale);
dummy.updateMatrix();
rocks.setMatrixAt(i, dummy.matrix);
}
rocks.instanceMatrix.needsUpdate = true;
rocks.castShadow = true;
scene.add(rocks);
// HTML labels projected from 3D anchors.
const labelEntries = [];
function addSettlementLabel(id, title, subtitle, x, z, elevationOffset, dotClass) {
const element = document.createElement("button");
element.className = "map-label";
element.type = "button";
element.setAttribute("aria-label", `Select ${title}`);
element.innerHTML = `
<span class="label-dot ${dotClass}"></span>
<span class="label-text"><strong>${title}</strong><small>${subtitle}</small></span>
`;
element.addEventListener("click", () => selectSettlement(id));
labelsHost.appendChild(element);
labelEntries.push({
element,
anchor: new THREE.Vector3(x, heightAt(x, z) + elevationOffset, z),
major: true
});
}
function addMinorLabel(text, x, z, elevationOffset) {
const element = document.createElement("div");
element.className = "minor-label";
element.textContent = text;
labelsHost.appendChild(element);
labelEntries.push({
element,
anchor: new THREE.Vector3(x, heightAt(x, z) + elevationOffset, z),
major: false
});
}
addSettlementLabel(
"headwater", "Highwater Village", "Headwater settlement",
-37, -28, 8.2, ""
);
addSettlementLabel(
"junction", "Fork Junction", "Tributary confluence",
-2.5, 10, 6.8, "junction"
);
addSettlementLabel(
"town", "Riverside Town", "Downstream outlet",
32, 28, 10.5, "town"
);
addMinorLabel("North Fork spring", 23, -21, 3.2);
addMinorLabel("Drainage divide", 40, -9, 3.0);
const settlementInfo = {
headwater: {
kicker: "Upstream settlement",
title: "Highwater Village",
description: "The first homes cluster around a cold upland stream. Water leaving the village flows steadily toward the central confluence.",
route: "Highwater Village → Fork Junction → Riverside Town",
metric: "Source elevation 7.2 m",
metricSub: "First permanent headwater stream",
focus: new THREE.Vector3(-35, 3, -25),
radius: 43,
theta: 0.58,
phi: 0.78
},
junction: {
kicker: "Tributary junction",
title: "Fork Junction",
description: "A timber camp and mill stand where the North Fork meets the highland creek. Both branches belong to the same drainage basin.",
route: "Highwater Creek + North Fork → Riverside Town",
metric: "Confluence elevation 2.2 m",
metricSub: "Two tributary networks merge",
focus: new THREE.Vector3(-1, 2, 7),
radius: 38,
theta: 0.5,
phi: 0.82
},
town: {
kicker: "Downstream settlement",
title: "Riverside Town",
description: "The town occupies the shared basin outlet. Every traced path from the village and the northern tributary ultimately reaches this market town.",
route: "All headwater and tributary routes → Riverside Town",
metric: "Outlet elevation 0.6 m",
metricSub: "Shared downstream receiving water",
focus: new THREE.Vector3(30, 1, 25),
radius: 42,
theta: 0.62,
phi: 0.78
}
};
const selectionRings = {};
function createSelectionRing(id, x, z, radius, color) {
const ring = new THREE.Mesh(
new THREE.TorusGeometry(radius, 0.11, 5, 42),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.75,
depthWrite: false
})
);
ring.rotation.x = Math.PI / 2;
ring.position.set(x, heightAt(x, z) + 0.32, z);
ring.visible = false;
ring.renderOrder = 4;
scene.add(ring);
selectionRings[id] = ring;
}
createSelectionRing("headwater", -37, -28, 4.8, 0x21a8b6);
createSelectionRing("junction", -2.5, 10, 3.5, 0x7866bd);
createSelectionRing("town", 32, 28, 6.3, 0xe39a54);
const infoKicker = document.getElementById("infoKicker");
const infoTitle = document.getElementById("infoTitle");
const infoDescription = document.getElementById("infoDescription");
const infoRoute = document.getElementById("infoRoute");
const infoMetric = document.getElementById("infoMetric");
const infoMetricSub = document.getElementById("infoMetricSub");
let selectedSettlement = "headwater";
function selectSettlement(id) {
selectedSettlement = id;
const info = settlementInfo[id];
infoKicker.textContent = info.kicker;
infoTitle.textContent = info.title;
infoDescription.textContent = info.description;
infoRoute.textContent = info.route;
infoMetric.textContent = info.metric;
infoMetricSub.textContent = info.metricSub;
for (const [ringId, ring] of Object.entries(selectionRings)) {
ring.visible = ringId === id;
}
labelEntries.forEach(entry => {
if (!entry.major) return;
const matchingButton = [...labelsHost.querySelectorAll(".map-label")]
.find(button => button.getAttribute("aria-label") === `Select ${settlementInfo[id].title}`);
if (matchingButton) matchingButton.classList.toggle("selected", matchingButton === matchingButton);
});
const selectedButtons = [...labelsHost.querySelectorAll(".map-label")];
const titleOrder = ["Highwater Village", "Fork Junction", "Riverside Town"];
selectedButtons.forEach(button => {
const title = button.getAttribute("aria-label").replace("Select ", "");
button.classList.toggle("selected", title === info.title);
});
mainTraceMaterial.opacity = id === "town" ? 0.4 : 0.31;
tributaryTraceMaterial.opacity = id === "junction" ? 0.48 : 0.27;
}
// Camera rig and direct, addon-free controls.
const cameraRig = {
target: new THREE.Vector3(0, 2.5, 1),
radius: 84,
theta: 0.56,
phi: 0.78
};
let cameraTween = null;
function updateCamera() {
const sinPhi = Math.sin(cameraRig.phi);
camera.position.set(
cameraRig.target.x + cameraRig.radius * sinPhi * Math.sin(cameraRig.theta),
cameraRig.target.y + cameraRig.radius * Math.cos(cameraRig.phi),
cameraRig.target.z + cameraRig.radius * sinPhi * Math.cos(cameraRig.theta)
);
camera.lookAt(cameraRig.target);
}
function tweenCamera(goal) {
cameraTween = {
elapsed: 0,
duration: 0.9,
start: {
target: cameraRig.target.clone(),
radius: cameraRig.radius,
theta: cameraRig.theta,
phi: cameraRig.phi
},
goal
};
}
function resetView() {
tweenCamera({
target: new THREE.Vector3(0, 2.5, 1),
radius: 84,
theta: 0.56,
phi: 0.78
});
}
function focusSelected() {
const info = settlementInfo[selectedSettlement];
tweenCamera({
target: info.focus.clone(),
radius: info.radius,
theta: info.theta,
phi: info.phi
});
}
document.getElementById("resetButton").addEventListener("click", resetView);
document.getElementById("focusButton").addEventListener("click", focusSelected);
let planView = false;
document.getElementById("topButton").addEventListener("click", () => {
planView = !planView;
const button = document.getElementById("topButton");
button.textContent = planView ? "3D view" : "Plan view";
if (planView) {
tweenCamera({
target: new THREE.Vector3(0, 0, 0),
radius: 91,
theta: 0,
phi: 0.13
});
} else {
resetView();
}
});
let basinVisible = true;
const basinButton = document.getElementById("basinToggle");
basinButton.addEventListener("click", () => {
basinVisible = !basinVisible;
flowGroup.visible = basinVisible;
basinGroup.visible = basinVisible;
basinButton.textContent = basinVisible ? "Basin trace on" : "Basin trace off";
basinButton.classList.toggle("active", basinVisible);
basinButton.setAttribute("aria-pressed", String(basinVisible));
});
const pointers = new Map();
let twoPointerGesture = null;
function pointerDistance() {
const values = [...pointers.values()];
if (values.length < 2) return 0;
return Math.hypot(values[0].x - values[1].x, values[0].y - values[1].y);
}
function pointerMidpoint() {
const values = [...pointers.values()];
if (values.length < 2) return { x: 0, y: 0 };
return {
x: (values[0].x + values[1].x) / 2,
y: (values[0].y + values[1].y) / 2
};
}
function panCamera(dx, dy) {
const scale = cameraRig.radius / Math.max(renderer.domElement.clientHeight, 1) * 1.35;
const right = new THREE.Vector3(Math.cos(cameraRig.theta), 0, -Math.sin(cameraRig.theta));
const forward = new THREE.Vector3(-Math.sin(cameraRig.theta), 0, -Math.cos(cameraRig.theta));
cameraRig.target.addScaledVector(right, -dx * scale);
cameraRig.target.addScaledVector(forward, -dy * scale);
cameraRig.target.x = THREE.MathUtils.clamp(cameraRig.target.x, -44, 44);
cameraRig.target.z = THREE.MathUtils.clamp(cameraRig.target.z, -34, 34);
}
renderer.domElement.addEventListener("pointerdown", event => {
cameraTween = null;
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY,
startX: event.clientX,
startY: event.clientY,
button: event.button,
shift: event.shiftKey,
type: event.pointerType,
travel: 0
});
if (pointers.size === 2) {
twoPointerGesture = {
distance: pointerDistance(),
midpoint: pointerMidpoint()
};
}
});
renderer.domElement.addEventListener("pointermove", event => {
const pointer = pointers.get(event.pointerId);
if (!pointer) return;
const dx = event.clientX - pointer.x;
const dy = event.clientY - pointer.y;
pointer.travel += Math.hypot(dx, dy);
pointer.x = event.clientX;
pointer.y = event.clientY;
if (pointers.size >= 2) {
const distance = pointerDistance();
const midpoint = pointerMidpoint();
if (twoPointerGesture && distance > 0 && twoPointerGesture.distance > 0) {
cameraRig.radius = THREE.MathUtils.clamp(
cameraRig.radius * (twoPointerGesture.distance / distance),
30,
135
);
panCamera(
midpoint.x - twoPointerGesture.midpoint.x,
midpoint.y - twoPointerGesture.midpoint.y
);
}
twoPointerGesture = { distance, midpoint };
return;
}
const wantsPan = pointer.type === "mouse" && (pointer.button !== 0 || pointer.shift);
if (wantsPan) {
panCamera(dx, dy);
} else {
cameraRig.theta -= dx * 0.005;
cameraRig.phi = THREE.MathUtils.clamp(cameraRig.phi + dy * 0.004, 0.13, 1.46);
}
});
renderer.domElement.addEventListener("pointerup", event => {
const pointer = pointers.get(event.pointerId);
if (pointer && pointer.travel < 6 && event.button === 0) {
const bounds = renderer.domElement.getBoundingClientRect();
pointerNDC.x = ((event.clientX - bounds.left) / bounds.width) * 2 - 1;
pointerNDC.y = -((event.clientY - bounds.top) / bounds.height) * 2 + 1;
raycaster.setFromCamera(pointerNDC, camera);
const hits = raycaster.intersectObjects(settlementTargets, false);
if (hits.length && hits[0].object.userData.settlement) {
selectSettlement(hits[0].object.userData.settlement);
}
}
pointers.delete(event.pointerId);
if (pointers.size < 2) twoPointerGesture = null;
});
renderer.domElement.addEventListener("pointercancel", event => {
pointers.delete(event.pointerId);
if (pointers.size < 2) twoPointerGesture = null;
});
renderer.domElement.addEventListener("contextmenu", event => event.preventDefault());
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraTween = null;
cameraRig.radius = THREE.MathUtils.clamp(
cameraRig.radius * Math.exp(event.deltaY * 0.001),
30,
135
);
}, { passive: false });
const raycaster = new THREE.Raycaster();
const pointerNDC = new THREE.Vector2();
window.addEventListener("keydown", event => {
if (event.key.toLowerCase() === "r") resetView();
if (event.key.toLowerCase() === "t") document.getElementById("topButton").click();
if (event.key.toLowerCase() === "b") basinButton.click();
if (event.key === "1") selectSettlement("headwater");
if (event.key === "2") selectSettlement("junction");
if (event.key === "3") selectSettlement("town");
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
const projected = new THREE.Vector3();
function updateLabels() {
for (const entry of labelEntries) {
projected.copy(entry.anchor).project(camera);
const visible = projected.z > -1 && projected.z < 1;
entry.element.style.display = visible ? "" : "none";
if (!visible) continue;
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
entry.element.style.left = `${x}px`;
entry.element.style.top = `${y}px`;
}
}
selectSettlement("headwater");
updateCamera();
const clock = new THREE.Clock();
const up = new THREE.Vector3(0, 1, 0);
function animate() {
requestAnimationFrame(animate);
const delta = clock.getDelta();
const elapsed = clock.elapsedTime;
if (cameraTween) {
cameraTween.elapsed += delta;
const t = THREE.MathUtils.clamp(cameraTween.elapsed / cameraTween.duration, 0, 1);
const eased = 1 - Math.pow(1 - t, 3);
cameraRig.target.lerpVectors(
cameraTween.start.target,
cameraTween.goal.target,
eased
);
cameraRig.radius = THREE.MathUtils.lerp(
cameraTween.start.radius,
cameraTween.goal.radius,
eased
);
cameraRig.theta = THREE.MathUtils.lerp(
cameraTween.start.theta,
cameraTween.goal.theta,
eased
);
cameraRig.phi = THREE.MathUtils.lerp(
cameraTween.start.phi,
cameraTween.goal.phi,
eased
);
if (t >= 1) cameraTween = null;
}
updateCamera();
if (basinVisible) {
for (const arrowData of flowArrows) {
const t = (elapsed * 0.045 + arrowData.offset) % 1;
const point = arrowData.curve.getPointAt(t);
const tangent = arrowData.curve.getTangentAt(t).normalize();
arrowData.mesh.position.copy(point);
arrowData.mesh.position.y += 0.32;
arrowData.mesh.quaternion.setFromUnitVectors(up, tangent);
}
const pulse = 0.28 + Math.sin(elapsed * 2.1) * 0.045;
mainTraceMaterial.opacity = selectedSettlement === "town" ? pulse + 0.1 : pulse;
tributaryTraceMaterial.opacity = selectedSettlement === "junction"
? pulse + 0.18
: pulse - 0.025;
}
const activeRing = selectionRings[selectedSettlement];
if (activeRing) {
const ringPulse = 1 + Math.sin(elapsed * 2.5) * 0.035;
activeRing.scale.setScalar(ringPulse);
activeRing.material.opacity = 0.63 + Math.sin(elapsed * 2.5) * 0.14;
}
updateLabels();
renderer.render(scene, camera);
}
animate();
requestAnimationFrame(() => {
document.getElementById("loading").classList.add("hidden");
setTimeout(() => document.getElementById("loading").remove(), 450);
});
</script>
</body>
</html>
```