Prompt specification
Build or customize the Three.js 3D scene "Ridgeline separating two gullies" 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: Ridgeline separating two gullies
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/ridgeline-separating-two-gullies-x1357
Scene Description Prompt:
Drop colored beads on opposite sides of a stylized ridge; each reaches a different drainage outlet. Three.js from cdnjs, one HTML file.
Working Three.js Starter (ridgeline-separating-two-gullies-x1357):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ridge & Runoff</title>
<style>
:root {
--bg: #071820;
--panel: rgba(12, 31, 40, 0.78);
--border: rgba(255, 255, 255, 0.13);
--text: #f5f1e8;
--muted: #a9bbc0;
--west: #ff8066;
--east: #57d6c7;
}
* {
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;
user-select: none;
}
canvas {
position: fixed;
inset: 0;
display: block;
touch-action: none;
cursor: crosshair;
}
.glass {
border: 1px solid var(--border);
background: var(--panel);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
#intro {
position: fixed;
z-index: 5;
top: 22px;
left: 22px;
width: 330px;
padding: 19px 20px;
border-radius: 18px;
pointer-events: none;
}
.eyebrow {
color: #79ded2;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.22em;
text-transform: uppercase;
}
h1 {
margin: 7px 0 9px;
font-size: clamp(25px, 3vw, 37px);
line-height: 0.98;
letter-spacing: -0.045em;
font-weight: 760;
}
#intro p {
margin: 0;
max-width: 275px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.route-key {
display: flex;
gap: 16px;
margin-top: 15px;
color: #d5dfe0;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.route-key span {
display: flex;
align-items: center;
gap: 7px;
}
.route-key i,
.swatch i {
width: 9px;
height: 9px;
display: inline-block;
border-radius: 50%;
box-shadow: 0 0 13px currentColor;
}
.west {
color: var(--west);
background: var(--west);
}
.east {
color: var(--east);
background: var(--east);
}
#stats {
position: fixed;
z-index: 5;
top: 22px;
right: 22px;
display: flex;
gap: 8px;
padding: 9px;
border-radius: 16px;
pointer-events: none;
}
.stat {
min-width: 72px;
padding: 9px 12px;
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
}
.stat span {
display: block;
color: #83999f;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.16em;
}
.stat b {
display: block;
margin-top: 2px;
font-size: 21px;
line-height: 1;
}
#westStat {
color: var(--west);
}
#eastStat {
color: var(--east);
}
#toolbar {
position: fixed;
z-index: 8;
left: 50%;
bottom: 20px;
display: flex;
align-items: center;
gap: 12px;
max-width: calc(100vw - 24px);
padding: 10px;
border-radius: 18px;
transform: translateX(-50%);
}
#palette {
display: flex;
align-items: center;
gap: 6px;
}
.swatch {
position: relative;
display: flex;
align-items: center;
gap: 8px;
height: 42px;
padding: 0 13px;
border: 1px solid transparent;
border-radius: 12px;
color: #c8d4d6;
background: transparent;
cursor: pointer;
font: inherit;
font-size: 11px;
font-weight: 700;
transition: 160ms ease;
}
.swatch:hover {
color: white;
background: rgba(255, 255, 255, 0.06);
}
.swatch.active {
color: white;
border-color: rgba(255, 255, 255, 0.2);
background: rgba(255, 255, 255, 0.09);
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.04);
}
.swatch i {
width: 13px;
height: 13px;
background: var(--c);
color: var(--c);
}
.actions {
display: flex;
gap: 7px;
padding-left: 11px;
border-left: 1px solid var(--border);
}
.action {
height: 42px;
padding: 0 15px;
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 11px;
color: #eaf0ef;
background: rgba(255, 255, 255, 0.055);
cursor: pointer;
font: inherit;
font-size: 11px;
font-weight: 750;
transition: 160ms ease;
}
.action:hover {
background: rgba(255, 255, 255, 0.11);
transform: translateY(-1px);
}
#dropPair {
border-color: rgba(87, 214, 199, 0.35);
color: #8af0e4;
}
.outlet-label {
position: fixed;
z-index: 4;
padding: 7px 11px;
border: 1px solid rgba(255, 255, 255, 0.16);
border-radius: 999px;
background: rgba(7, 24, 32, 0.78);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25);
color: white;
font-size: 9px;
font-weight: 850;
letter-spacing: 0.11em;
pointer-events: none;
transform: translate(-50%, -50%);
white-space: nowrap;
}
#westLabel {
border-color: rgba(255, 128, 102, 0.45);
color: #ffad9c;
}
#eastLabel {
border-color: rgba(87, 214, 199, 0.45);
color: #93f3e8;
}
#hint {
position: fixed;
z-index: 3;
left: 50%;
bottom: 92px;
padding: 6px 10px;
border-radius: 8px;
color: rgba(225, 237, 237, 0.65);
background: rgba(4, 15, 21, 0.42);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.09em;
text-transform: uppercase;
pointer-events: none;
transform: translateX(-50%);
}
@media (max-width: 760px) {
#intro {
top: 12px;
left: 12px;
width: 230px;
padding: 13px 15px;
}
#intro p,
.route-key {
display: none;
}
#stats {
top: auto;
right: 12px;
bottom: 119px;
padding: 6px;
}
.stat {
min-width: 56px;
padding: 7px 9px;
}
.stat b {
font-size: 17px;
}
#toolbar {
bottom: 10px;
width: calc(100vw - 20px);
flex-direction: column;
align-items: stretch;
gap: 7px;
}
#palette {
justify-content: center;
}
.swatch {
height: 38px;
padding: 0 9px;
}
.swatch .name {
display: none;
}
.actions {
padding: 7px 0 0;
border-top: 1px solid var(--border);
border-left: 0;
}
.action {
flex: 1;
height: 36px;
}
#hint {
bottom: 175px;
}
}
</style>
</head>
<body>
<div id="intro" class="glass">
<div class="eyebrow">Terrain study / 01</div>
<h1>Ridge &<br>Runoff</h1>
<p>
Choose a bead color, then click either face of the ridge.
Gravity carries it downhill to the outlet on its own side.
</p>
<div class="route-key">
<span><i class="west"></i> West drain</span>
<span><i class="east"></i> East drain</span>
</div>
</div>
<div id="stats" class="glass">
<div class="stat">
<span>Dropped</span>
<b id="totalCount">0</b>
</div>
<div class="stat">
<span>West</span>
<b id="westStat">0</b>
</div>
<div class="stat">
<span>East</span>
<b id="eastStat">0</b>
</div>
</div>
<div id="hint">Click terrain to drop · drag to orbit · scroll to zoom</div>
<div id="westLabel" class="outlet-label">WEST OUTFLOW · 0</div>
<div id="eastLabel" class="outlet-label">EAST OUTFLOW · 0</div>
<div id="toolbar" class="glass">
<div id="palette">
<button class="swatch active" data-color="#ff735f" style="--c:#ff735f" aria-label="Coral bead">
<i></i><span class="name">Coral</span>
</button>
<button class="swatch" data-color="#ffc857" style="--c:#ffc857" aria-label="Amber bead">
<i></i><span class="name">Amber</span>
</button>
<button class="swatch" data-color="#5dd6c7" style="--c:#5dd6c7" aria-label="Teal bead">
<i></i><span class="name">Teal</span>
</button>
<button class="swatch" data-color="#a991ff" style="--c:#a991ff" aria-label="Violet bead">
<i></i><span class="name">Violet</span>
</button>
<button class="swatch" data-color="#b8e46c" style="--c:#b8e46c" aria-label="Lime bead">
<i></i><span class="name">Lime</span>
</button>
</div>
<div class="actions">
<button id="dropPair" class="action">Drop pair</button>
<button id="clear" class="action">Reset</button>
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Scene
// ------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071820);
scene.fog = new THREE.Fog(0x071820, 24, 43);
const camera = new THREE.PerspectiveCamera(
42,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.domElement.style.touchAction = "none";
document.body.prepend(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xc9f4ff, 0x49382d, 2.25));
const sun = new THREE.DirectionalLight(0xfff0d2, 3.1);
sun.position.set(-7, 14, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -15;
sun.shadow.camera.right = 15;
sun.shadow.camera.top = 14;
sun.shadow.camera.bottom = -14;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 38;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x72d9dc, 1.1);
fill.position.set(10, 7, -8);
scene.add(fill);
// ------------------------------------------------------------
// Height field
// ------------------------------------------------------------
const WIDTH = 19.4;
const DEPTH = 12.4;
const HALF_WIDTH = WIDTH * 0.5;
const HALF_DEPTH = DEPTH * 0.5;
function terrainHeight(x, z) {
const ax = Math.abs(x);
// Main elongated ridge.
const ridge = 2.55 * Math.exp(-Math.pow(ax / 2.15, 2));
// Soft longitudinal folds.
const folds =
0.105 *
Math.sin(z * 0.82 + ax * 0.32) *
(ax / 8);
const ripple =
0.032 * Math.sin(z * 1.9 + x * 0.7) +
0.018 * Math.sin(x * 1.35 - z * 0.65);
// A shallow channel along z = 0 gathers beads toward each outlet.
const channel = 0.04 * z * z;
// Funnels near the two drainage points.
const basin =
-0.38 *
Math.exp(-Math.pow((ax - 8.55) / 0.95, 2)) *
Math.exp(-(z * z) / 1.4);
return 0.18 + ridge + folds + ripple + channel + basin;
}
function makeTerrainGeometry() {
const nx = 100;
const nz = 76;
const positions = [];
const colors = [];
const indices = [];
const leftLow = new THREE.Color(0x9f5d49);
const leftHigh = new THREE.Color(0xd4a16d);
const rightLow = new THREE.Color(0x39776f);
const rightHigh = new THREE.Color(0x88b89e);
const crest = new THREE.Color(0xf0d7a8);
const basin = new THREE.Color(0x263f42);
const color = new THREE.Color();
for (let iz = 0; iz <= nz; iz++) {
const z = -HALF_DEPTH + (iz / nz) * DEPTH;
for (let ix = 0; ix <= nx; ix++) {
const x = -HALF_WIDTH + (ix / nx) * WIDTH;
const y = terrainHeight(x, z);
const ax = Math.abs(x);
positions.push(x, y, z);
if (x < 0) {
color.copy(leftLow).lerp(leftHigh, THREE.MathUtils.clamp(y / 2.7, 0, 1));
} else {
color.copy(rightLow).lerp(rightHigh, THREE.MathUtils.clamp(y / 2.7, 0, 1));
}
const crestAmount = 1 - THREE.MathUtils.smoothstep(ax, 0.28, 0.78);
color.lerp(crest, crestAmount * 0.78);
const basinAmount =
1 -
THREE.MathUtils.smoothstep(
Math.hypot(ax - 8.55, z),
0.35,
1.5
);
color.lerp(basin, basinAmount * 0.8);
colors.push(color.r, color.g, color.b);
}
}
for (let iz = 0; iz < nz; iz++) {
for (let ix = 0; ix < nx; ix++) {
const a = iz * (nx + 1) + ix;
const b = a + 1;
const c = a + nx + 1;
const d = c + 1;
indices.push(a, c, b, b, c, d);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(colors, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
geometry.computeBoundingSphere();
return geometry;
}
const terrainMesh = new THREE.Mesh(
makeTerrainGeometry(),
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.88,
metalness: 0.02,
flatShading: true,
side: THREE.DoubleSide
})
);
terrainMesh.castShadow = true;
terrainMesh.receiveShadow = true;
scene.add(terrainMesh);
// Terrain skirt gives the scene a cutaway, model-like base.
function makeSkirtGeometry() {
const boundary = [];
const nx = 80;
const nz = 48;
for (let i = 0; i <= nx; i++) {
boundary.push([
-HALF_WIDTH + (i / nx) * WIDTH,
-HALF_DEPTH
]);
}
for (let i = 1; i <= nz; i++) {
boundary.push([
HALF_WIDTH,
-HALF_DEPTH + (i / nz) * DEPTH
]);
}
for (let i = 1; i <= nx; i++) {
boundary.push([
HALF_WIDTH - (i / nx) * WIDTH,
HALF_DEPTH
]);
}
for (let i = 1; i < nz; i++) {
boundary.push([
-HALF_WIDTH,
HALF_DEPTH - (i / nz) * DEPTH
]);
}
const positions = [];
const indices = [];
boundary.forEach(([x, z]) => {
positions.push(x, terrainHeight(x, z), z);
positions.push(x, -0.95, z);
});
for (let i = 0; i < boundary.length; i++) {
const next = (i + 1) % boundary.length;
const top = i * 2;
const bottom = top + 1;
const topNext = next * 2;
const bottomNext = topNext + 1;
indices.push(top, bottom, topNext, topNext, bottom, bottomNext);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
return geometry;
}
const skirt = new THREE.Mesh(
makeSkirtGeometry(),
new THREE.MeshStandardMaterial({
color: 0x344344,
roughness: 0.96,
side: THREE.DoubleSide
})
);
skirt.castShadow = true;
skirt.receiveShadow = true;
scene.add(skirt);
const base = new THREE.Mesh(
new THREE.BoxGeometry(WIDTH + 0.16, 0.18, DEPTH + 0.16),
new THREE.MeshStandardMaterial({
color: 0x172c31,
roughness: 0.82
})
);
base.position.y = -1.03;
base.castShadow = true;
base.receiveShadow = true;
scene.add(base);
const ground = new THREE.Mesh(
new THREE.CircleGeometry(31, 96),
new THREE.MeshStandardMaterial({
color: 0x0a1c25,
roughness: 1
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -1.13;
ground.receiveShadow = true;
scene.add(ground);
// Dashed crest line.
const crestPoints = [];
for (let i = 0; i <= 80; i++) {
const z = -HALF_DEPTH + (i / 80) * DEPTH;
crestPoints.push(
new THREE.Vector3(0, terrainHeight(0, z) + 0.035, z)
);
}
const crestLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(crestPoints),
new THREE.LineDashedMaterial({
color: 0xffe9bd,
dashSize: 0.18,
gapSize: 0.13,
transparent: true,
opacity: 0.62
})
);
crestLine.computeLineDistances();
scene.add(crestLine);
// Etched arrows showing the downhill direction.
const arrowPositions = [];
for (const side of [-1, 1]) {
for (const distance of [2.8, 4.6, 6.3]) {
const x = side * distance;
const tipX = side * (distance + 0.28);
const y = terrainHeight(x, 0) + 0.035;
arrowPositions.push(
x, y, -0.18,
tipX, terrainHeight(tipX, 0) + 0.035, 0,
x, y, 0.18,
tipX, terrainHeight(tipX, 0) + 0.035, 0
);
}
}
const arrows = new THREE.LineSegments(
new THREE.BufferGeometry().setAttribute(
"position",
new THREE.Float32BufferAttribute(arrowPositions, 3)
),
new THREE.LineBasicMaterial({
color: 0xe9f5e8,
transparent: true,
opacity: 0.28
})
);
scene.add(arrows);
// ------------------------------------------------------------
// Drainage outlets
// ------------------------------------------------------------
function createOutlet(x, color, emissive) {
const group = new THREE.Group();
group.position.set(x, terrainHeight(x, 0), 0);
const dark = new THREE.Mesh(
new THREE.CylinderGeometry(0.59, 0.59, 0.14, 40),
new THREE.MeshStandardMaterial({
color: 0x101d22,
roughness: 0.7
})
);
dark.position.y = 0.015;
dark.receiveShadow = true;
group.add(dark);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.64, 0.095, 12, 48),
new THREE.MeshStandardMaterial({
color,
emissive,
emissiveIntensity: 0.48,
metalness: 0.25,
roughness: 0.35
})
);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.11;
ring.castShadow = true;
group.add(ring);
const grateMaterial = new THREE.MeshStandardMaterial({
color: 0xa9b9b8,
metalness: 0.58,
roughness: 0.42
});
for (let i = -2; i <= 2; i++) {
const bar = new THREE.Mesh(
new THREE.BoxGeometry(0.055, 0.045, 0.86),
grateMaterial
);
bar.position.set(i * 0.17, 0.115, 0);
bar.castShadow = true;
group.add(bar);
}
scene.add(group);
return group;
}
const westOutlet = createOutlet(-8.65, 0xff8066, 0x8b241b);
const eastOutlet = createOutlet(8.65, 0x57d6c7, 0x14685f);
// ------------------------------------------------------------
// Dust particles
// ------------------------------------------------------------
let randomSeed = 17;
function random() {
randomSeed = (randomSeed * 16807) % 2147483647;
return (randomSeed - 1) / 2147483646;
}
const dustPositions = [];
for (let i = 0; i < 100; i++) {
dustPositions.push(
(random() - 0.5) * 31,
1 + random() * 12,
(random() - 0.5) * 27
);
}
const dust = new THREE.Points(
new THREE.BufferGeometry().setAttribute(
"position",
new THREE.Float32BufferAttribute(dustPositions, 3)
),
new THREE.PointsMaterial({
color: 0xcce9e5,
size: 0.035,
transparent: true,
opacity: 0.36,
depthWrite: false
})
);
scene.add(dust);
// ------------------------------------------------------------
// Camera controls, implemented without addons
// ------------------------------------------------------------
const cameraState = {
yaw: 0,
pitch: 0.69,
distance: 21.5,
target: new THREE.Vector3(0, 0.65, 0)
};
function updateCamera() {
const horizontal = Math.cos(cameraState.pitch) * cameraState.distance;
camera.position.set(
cameraState.target.x +
Math.sin(cameraState.yaw) * horizontal,
cameraState.target.y +
Math.sin(cameraState.pitch) * cameraState.distance,
cameraState.target.z +
Math.cos(cameraState.yaw) * horizontal
);
camera.lookAt(cameraState.target);
camera.updateMatrixWorld();
}
updateCamera();
let pointer = null;
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
pointer = {
id: event.pointerId,
startX: event.clientX,
startY: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
moved: false
};
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointer || pointer.id !== event.pointerId) return;
const dx = event.clientX - pointer.lastX;
const dy = event.clientY - pointer.lastY;
const totalDistance = Math.hypot(
event.clientX - pointer.startX,
event.clientY - pointer.startY
);
if (totalDistance > 4) pointer.moved = true;
if (pointer.moved) {
cameraState.yaw -= dx * 0.005;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.004,
0.28,
1.28
);
}
pointer.lastX = event.clientX;
pointer.lastY = event.clientY;
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (!pointer || pointer.id !== event.pointerId) return;
const wasClick = !pointer.moved;
pointer = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
if (wasClick) dropFromPointer(event.clientX, event.clientY);
});
renderer.domElement.addEventListener("pointercancel", () => {
pointer = null;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance + event.deltaY * 0.012,
12,
31
);
},
{ passive: false }
);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
// ------------------------------------------------------------
// Beads, trails, and effects
// ------------------------------------------------------------
const beads = [];
const trails = [];
const effects = [];
let selectedColor = "#ff735f";
let totalDrops = 0;
let westCount = 0;
let eastCount = 0;
const beadGeometry = new THREE.SphereGeometry(0.225, 24, 18);
function makeTrail(color) {
const positions = new Float32Array(180 * 3);
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.BufferAttribute(positions, 3)
);
geometry.setDrawRange(0, 0);
const line = new THREE.Line(
geometry,
new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.3,
depthWrite: false
})
);
line.frustumCulled = false;
scene.add(line);
const trail = {
line,
positions,
count: 0
};
trails.push(trail);
return trail;
}
function pushTrail(bead) {
const trail = bead.trail;
if (trail.count >= 180) return;
const index = trail.count * 3;
trail.positions[index] = bead.mesh.position.x;
trail.positions[index + 1] =
terrainHeight(bead.mesh.position.x, bead.mesh.position.z) + 0.035;
trail.positions[index + 2] = bead.mesh.position.z;
trail.count++;
trail.line.geometry.setDrawRange(0, trail.count);
trail.line.geometry.attributes.position.needsUpdate = true;
}
function pulse(x, z, color, size = 1) {
const ring = new THREE.Mesh(
new THREE.RingGeometry(0.18, 0.245, 40),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.68,
side: THREE.DoubleSide,
depthWrite: false
})
);
ring.rotation.x = -Math.PI / 2;
ring.position.set(x, terrainHeight(x, z) + 0.045, z);
ring.scale.setScalar(size);
scene.add(ring);
effects.push({
mesh: ring,
age: 0,
duration: 0.72,
size
});
}
function spawnBead(x, z, color = selectedColor, dropHeight = 3.4) {
const safeX = THREE.MathUtils.clamp(x, -9.08, 9.08);
const safeZ = THREE.MathUtils.clamp(z, -HALF_DEPTH + 0.25, HALF_DEPTH - 0.25);
const side =
safeX < -0.04 ? -1 :
safeX > 0.04 ? 1 :
Math.random() > 0.5 ? 1 : -1;
const material = new THREE.MeshPhysicalMaterial({
color,
roughness: 0.23,
metalness: 0.03,
clearcoat: 0.85,
clearcoatRoughness: 0.18
});
const mesh = new THREE.Mesh(beadGeometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.position.set(
safeX,
terrainHeight(safeX, safeZ) + dropHeight,
safeZ
);
scene.add(mesh);
const bead = {
mesh,
color,
side,
state: "falling",
radius: 0.225,
velocityY: 0,
vx: 0,
vz: 0,
trail: makeTrail(color),
trailClock: 0,
drainTime: 0,
drainStartY: 0
};
beads.push(bead);
totalDrops++;
pulse(safeX, safeZ, color, 0.8);
updateCounters();
return bead;
}
function dropFromPointer(clientX, clientY) {
const rect = renderer.domElement.getBoundingClientRect();
const mouse = new THREE.Vector2(
((clientX - rect.left) / rect.width) * 2 - 1,
-((clientY - rect.top) / rect.height) * 2 + 1
);
const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mouse, camera);
const hit = raycaster.intersectObject(terrainMesh, false)[0];
if (!hit) return;
spawnBead(hit.point.x, hit.point.z, selectedColor, 3.4);
}
function updateCounters() {
document.getElementById("totalCount").textContent = totalDrops;
document.getElementById("westStat").textContent = westCount;
document.getElementById("eastStat").textContent = eastCount;
document.getElementById("westLabel").textContent =
`WEST OUTFLOW · ${westCount}`;
document.getElementById("eastLabel").textContent =
`EAST OUTFLOW · ${eastCount}`;
}
// ------------------------------------------------------------
// Height-field bead physics
// ------------------------------------------------------------
function updateBeads(dt) {
const substeps = Math.max(1, Math.ceil(dt / (1 / 90)));
const step = dt / substeps;
for (let index = beads.length - 1; index >= 0; index--) {
const bead = beads[index];
if (bead.state === "falling") {
bead.velocityY -= 9.8 * step;
bead.mesh.position.y += bead.velocityY * step;
const ground =
terrainHeight(
bead.mesh.position.x,
bead.mesh.position.z
) + bead.radius;
if (bead.mesh.position.y <= ground) {
bead.mesh.position.y = ground;
bead.state = "rolling";
bead.vx = bead.side * 0.62;
bead.vz = (Math.random() - 0.5) * 0.09;
pulse(
bead.mesh.position.x,
bead.mesh.position.z,
bead.color,
1.25
);
}
} else if (bead.state === "rolling") {
let x = bead.mesh.position.x;
let z = bead.mesh.position.z;
const epsilon = 0.065;
const gradientX =
(terrainHeight(x + epsilon, z) -
terrainHeight(x - epsilon, z)) /
(2 * epsilon);
const gradientZ =
(terrainHeight(x, z + epsilon) -
terrainHeight(x, z - epsilon)) /
(2 * epsilon);
let accelerationX = -gradientX * 8.2;
let accelerationZ = -gradientZ * 8.2;
// Stronger collection near the two drainage basins.
if (Math.abs(x) > 7.1) {
accelerationZ += -z * 3.1;
}
if (Math.abs(x) > 8.05) {
accelerationZ += -z * 8.0;
}
bead.vx += accelerationX * step;
bead.vz += accelerationZ * step;
const damping = Math.exp(-0.38 * step);
bead.vx *= damping;
bead.vz *= damping;
const speed = Math.hypot(bead.vx, bead.vz);
if (speed > 5.2) {
bead.vx = (bead.vx / speed) * 5.2;
bead.vz = (bead.vz / speed) * 5.2;
}
x += bead.vx * step;
z += bead.vz * step;
// Keep beads on the modeled terrain.
if (x > 8.48) {
x = 8.48;
bead.vx = Math.min(0, bead.vx);
}
if (x < -8.48) {
x = -8.48;
bead.vx = Math.max(0, bead.vx);
}
z = THREE.MathUtils.clamp(z, -HALF_DEPTH + 0.2, HALF_DEPTH - 0.2);
bead.mesh.position.x = x;
bead.mesh.position.z = z;
bead.mesh.position.y =
terrainHeight(x, z) + bead.radius;
bead.mesh.rotation.z -= (bead.vx / bead.radius) * step;
bead.mesh.rotation.x += (bead.vz / bead.radius) * step;
bead.trailClock += step;
if (bead.trailClock >= 0.055) {
bead.trailClock = 0;
pushTrail(bead);
}
if (Math.abs(x) > 8.18 && Math.abs(z) < 1.45) {
bead.state = "draining";
bead.drainTime = 0;
bead.drainStartY = bead.mesh.position.y;
bead.vx = 0;
bead.vz = 0;
pulse(x, z, bead.color, 1.6);
}
} else if (bead.state === "draining") {
bead.drainTime += dt;
const t = THREE.MathUtils.clamp(bead.drainTime / 0.62, 0, 1);
const eased = t * t * (3 - 2 * t);
const drainX = Math.sign(bead.mesh.position.x) * 8.65;
const drainY = terrainHeight(drainX, 0);
bead.mesh.position.x = THREE.MathUtils.lerp(
bead.mesh.position.x,
drainX,
Math.min(1, dt * 12)
);
bead.mesh.position.y = THREE.MathUtils.lerp(
bead.drainStartY,
drainY - 0.45,
eased
);
bead.mesh.scale.setScalar(1 - eased * 0.72);
bead.mesh.rotation.y += dt * 5;
if (t >= 1) {
if (bead.side < 0) {
westCount++;
} else {
eastCount++;
}
updateCounters();
scene.remove(bead.mesh);
bead.mesh.material.dispose();
beads.splice(index, 1);
}
}
}
}
function updateEffects(dt) {
for (let index = effects.length - 1; index >= 0; index--) {
const effect = effects[index];
effect.age += dt;
const t = effect.age / effect.duration;
if (t >= 1) {
scene.remove(effect.mesh);
effect.mesh.geometry.dispose();
effect.mesh.material.dispose();
effects.splice(index, 1);
continue;
}
const scale = effect.size * (1 + t * 3.3);
effect.mesh.scale.setScalar(scale);
effect.mesh.material.opacity = (1 - t) * 0.68;
}
}
// ------------------------------------------------------------
// UI
// ------------------------------------------------------------
const paletteButtons = [
...document.querySelectorAll(".swatch")
];
function selectColor(color) {
selectedColor = color;
paletteButtons.forEach((button) => {
const active = button.dataset.color === color;
button.classList.toggle("active", active);
button.setAttribute("aria-pressed", String(active));
});
}
paletteButtons.forEach((button) => {
button.addEventListener("click", () => {
selectColor(button.dataset.color);
});
});
document.getElementById("dropPair").addEventListener("click", () => {
spawnBead(-2.15, -1.25, selectedColor, 2.9);
spawnBead(2.15, -1.25, selectedColor, 2.9);
});
document.getElementById("clear").addEventListener("click", () => {
for (const bead of beads) {
scene.remove(bead.mesh);
bead.mesh.material.dispose();
}
for (const trail of trails) {
scene.remove(trail.line);
trail.line.geometry.dispose();
trail.line.material.dispose();
}
beads.length = 0;
trails.length = 0;
totalDrops = 0;
westCount = 0;
eastCount = 0;
updateCounters();
});
addEventListener("keydown", (event) => {
const key = event.key.toLowerCase();
if (key >= "1" && key <= "5") {
const button = paletteButtons[Number(key) - 1];
if (button) selectColor(button.dataset.color);
}
if (key === "p") {
spawnBead(-2.15, -1.25, selectedColor, 2.9);
spawnBead(2.15, -1.25, selectedColor, 2.9);
}
if (key === "r") {
document.getElementById("clear").click();
}
if (event.code === "Space") {
event.preventDefault();
const side = Math.random() > 0.5 ? 1 : -1;
spawnBead(
side * (1.8 + Math.random() * 3.4),
(Math.random() - 0.5) * 4,
selectedColor,
3.4
);
}
});
// ------------------------------------------------------------
// Screen-space outlet labels
// ------------------------------------------------------------
const projected = new THREE.Vector3();
function updateOutletLabels() {
const width = innerWidth;
const height = innerHeight;
for (const [element, outlet] of [
[document.getElementById("westLabel"), westOutlet],
[document.getElementById("eastLabel"), eastOutlet]
]) {
projected.copy(outlet.position);
projected.y += 1.15;
projected.project(camera);
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
element.style.opacity = projected.z > 1 ? "0" : "1";
}
}
// ------------------------------------------------------------
// Resize and render loop
// ------------------------------------------------------------
addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
let previousTime = performance.now();
function animate(now) {
requestAnimationFrame(animate);
const dt = Math.min((now - previousTime) / 1000, 0.035);
previousTime = now;
updateCamera();
updateBeads(dt);
updateEffects(dt);
dust.rotation.y += dt * 0.009;
renderer.render(scene, camera);
updateOutletLabels();
}
updateCounters();
requestAnimationFrame(animate);
</script>
</body>
</html>
```