Prompt specification
Build or customize the Three.js 3D scene "Mountain watershed ridge model" 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: Mountain watershed ridge model
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/mountain-watershed-ridge-model-x1193
Scene Description Prompt:
Use Three.js from cdnjs to build two sloping basins separated by a sharp ridge, with a raised watershed boundary; place drainage grooves that consistently descend away from the divide. Deliver one self-contained HTML file with low-poly forms.
Working Three.js Starter (mountain-watershed-ridge-model-x1193):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Twin Watersheds — Low-Poly Terrain</title>
<style>
:root {
color-scheme: light;
--ink: #25332f;
--muted: #5c6d67;
--paper: rgba(250, 248, 240, 0.88);
--line: rgba(37, 51, 47, 0.16);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dce5e1;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
#app,
canvas {
display: block;
width: 100%;
height: 100%;
}
canvas {
touch-action: none;
outline: none;
}
.overlay {
position: fixed;
inset: 0;
pointer-events: none;
}
.title-card {
position: absolute;
top: 22px;
left: 22px;
width: min(350px, calc(100vw - 44px));
padding: 18px 19px 16px;
border: 1px solid var(--line);
border-radius: 14px;
background: var(--paper);
backdrop-filter: blur(12px);
box-shadow: 0 12px 38px rgba(42, 57, 52, 0.11);
}
.eyebrow {
margin-bottom: 7px;
color: #657a70;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.2em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(23px, 3vw, 31px);
line-height: 1.02;
letter-spacing: -0.045em;
}
.subtitle {
margin: 9px 0 15px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.legend {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px 12px;
padding-top: 13px;
border-top: 1px solid var(--line);
color: #52645d;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.055em;
text-transform: uppercase;
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
}
.swatch {
width: 10px;
height: 10px;
flex: 0 0 auto;
border-radius: 2px;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.08);
}
.west {
background: #ad8257;
}
.east {
background: #87998a;
}
.ridge {
background: #ead8aa;
}
.groove {
background: #4e4439;
}
.controls {
position: absolute;
right: 20px;
bottom: 20px;
display: flex;
align-items: center;
gap: 8px;
pointer-events: auto;
}
.hint {
margin-right: 4px;
padding: 9px 11px;
border: 1px solid var(--line);
border-radius: 9px;
background: var(--paper);
color: #5a6b64;
font-size: 10px;
font-weight: 650;
letter-spacing: 0.025em;
backdrop-filter: blur(10px);
}
button {
min-height: 36px;
padding: 0 13px;
border: 1px solid rgba(37, 51, 47, 0.16);
border-radius: 9px;
background: rgba(250, 248, 240, 0.92);
color: var(--ink);
font: inherit;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
cursor: pointer;
backdrop-filter: blur(10px);
transition:
transform 140ms ease,
background 140ms ease;
}
button:hover {
transform: translateY(-1px);
background: #fffdf6;
}
button:active {
transform: translateY(0);
}
.plan-note {
position: absolute;
left: 22px;
bottom: 20px;
color: rgba(37, 51, 47, 0.64);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
@media (max-width: 700px) {
.title-card {
top: 12px;
left: 12px;
width: min(310px, calc(100vw - 24px));
padding: 14px 15px;
}
.subtitle {
margin-bottom: 10px;
}
.legend {
gap: 6px;
}
.hint,
.plan-note {
display: none;
}
.controls {
right: 12px;
bottom: 12px;
}
}
</style>
</head>
<body>
<div id="app"></div>
<div class="overlay">
<section class="title-card">
<div class="eyebrow">Low-poly hydrology study</div>
<h1>Twin Watersheds</h1>
<p class="subtitle">
Two catchments descend from a sharp central divide. Grooves deepen
downhill toward the western and eastern basin floors.
</p>
<div class="legend" aria-label="Terrain legend">
<div class="legend-item">
<span class="swatch west"></span>
West basin
</div>
<div class="legend-item">
<span class="swatch east"></span>
East basin
</div>
<div class="legend-item">
<span class="swatch ridge"></span>
Watershed ridge
</div>
<div class="legend-item">
<span class="swatch groove"></span>
Drainage groove
</div>
</div>
</section>
<div class="plan-note">Flow direction: ridge → basin</div>
<div class="controls">
<div class="hint">Drag to orbit · wheel to zoom · right-drag to pan</div>
<button id="planButton" type="button">Plan view</button>
<button id="resetButton" type="button">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";
// -------------------------------------------------------------------------
// Setup
// -------------------------------------------------------------------------
const container = document.getElementById("app");
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
container.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color("#dce5e1");
scene.fog = new THREE.Fog("#dce5e1", 58, 115);
const camera = new THREE.PerspectiveCamera(
40,
window.innerWidth / window.innerHeight,
0.1,
180
);
const hemisphere = new THREE.HemisphereLight(
"#f3fbff",
"#70513a",
2.05
);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight("#fff2d7", 3.25);
sun.position.set(-16, 28, 15);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -26;
sun.shadow.camera.right = 26;
sun.shadow.camera.top = 24;
sun.shadow.camera.bottom = -24;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 70;
sun.shadow.bias = -0.00035;
sun.shadow.normalBias = 0.035;
scene.add(sun);
const fill = new THREE.DirectionalLight("#c9e1e3", 0.75);
fill.position.set(20, 12, -18);
scene.add(fill);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(180, 180),
new THREE.MeshStandardMaterial({
color: "#d7e0dc",
roughness: 1,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -2.08;
ground.receiveShadow = true;
scene.add(ground);
const HALF_X = 18;
const HALF_Z = 14;
const BASIN_END = 10.8;
const RIDGE_HEIGHT = 7.5;
// -------------------------------------------------------------------------
// Drainage network
//
// The centerline of each channel may meander in Z, but its bed elevation
// depends only on distance from the divide. This guarantees that every
// groove continuously descends away from the central ridge.
// -------------------------------------------------------------------------
const channelSets = {
west: [
{ z: -9.1, phase: 0.20, amplitude: 0.48, slant: -0.55 },
{ z: -4.4, phase: 1.05, amplitude: 0.40, slant: 0.30 },
{ z: 0.3, phase: 2.00, amplitude: 0.52, slant: -0.25 },
{ z: 5.1, phase: 0.55, amplitude: 0.44, slant: 0.50 },
{ z: 9.0, phase: 1.55, amplitude: 0.38, slant: -0.35 }
],
east: [
{ z: -7.7, phase: 1.25, amplitude: 0.50, slant: 0.45 },
{ z: -2.9, phase: 0.10, amplitude: 0.42, slant: -0.30 },
{ z: 1.9, phase: 2.20, amplitude: 0.55, slant: 0.35 },
{ z: 6.8, phase: 0.80, amplitude: 0.45, slant: -0.45 }
]
};
const CHANNEL_WIDTH = 0.72;
const CHANNEL_DEPTH = 0.62;
function clamp01(v) {
return Math.max(0, Math.min(1, v));
}
function smoothstep(min, max, value) {
const t = clamp01((value - min) / (max - min));
return t * t * (3 - 2 * t);
}
function channelCenterZ(channel, distance) {
return (
channel.z +
channel.amplitude * Math.sin(distance * 0.52 + channel.phase) +
channel.slant * (distance / 10)
);
}
function nearestChannel(x, z) {
const channels = x < 0 ? channelSets.west : channelSets.east;
const distance = Math.abs(x);
let nearest = null;
for (const channel of channels) {
const delta = Math.abs(z - channelCenterZ(channel, distance));
if (!nearest || delta < nearest.distance) {
nearest = {
distance: delta,
channel,
side: x < 0 ? -1 : 1
};
}
}
return nearest;
}
function channelEnvelope(distance) {
// The source ramp and outlet taper are slower than the basin's
// cross-slope fall, so the actual groove bed never rises downhill.
const source = clamp01((distance - 0.28) / 1.45);
const outlet = 1 - smoothstep(9.15, 10.55, distance);
return source * outlet;
}
function terrainHeight(x, z) {
const distance = Math.abs(x);
let height;
if (distance <= BASIN_END) {
// A clean, monotonic slope from the ridge to each basin floor.
height =
1.2 +
(RIDGE_HEIGHT - 1.2) *
(1 - distance / BASIN_END);
} else {
// Raised outer watershed boundary.
height = 1.2 + 2.45 * smoothstep(BASIN_END, 16.5, distance);
}
// Raised boundary along the north and south ends.
height += 1.55 * smoothstep(11.6, HALF_Z, Math.abs(z));
// Carve the drainage grooves.
const nearest = nearestChannel(x, z);
if (nearest && nearest.distance < CHANNEL_WIDTH) {
const crossSection =
1 - nearest.distance / CHANNEL_WIDTH;
height -=
CHANNEL_DEPTH *
channelEnvelope(distance) *
crossSection;
}
return height;
}
// -------------------------------------------------------------------------
// Low-poly terrain mesh
// -------------------------------------------------------------------------
const xPositions = [];
for (let i = -36; i <= 36; i++) {
xPositions.push(i * 0.5);
}
// Extra vertices make the central divide read as a crisp ridge.
xPositions.push(-0.14, 0.14);
xPositions.sort((a, b) => a - b);
const zPositions = [];
for (let i = -28; i <= 28; i++) {
zPositions.push(i * 0.5);
}
const grid = [];
for (let iz = 0; iz < zPositions.length; iz++) {
const row = [];
for (let ix = 0; ix < xPositions.length; ix++) {
const x = xPositions[ix];
const z = zPositions[iz];
row.push({
x,
y: terrainHeight(x, z),
z
});
}
grid.push(row);
}
function hash2(x, z) {
const value = Math.sin(x * 127.1 + z * 311.7) * 43758.5453;
return value - Math.floor(value);
}
function faceColor(cx, cz, height, ix, iz) {
const nearest = nearestChannel(cx, cz);
if (nearest && nearest.distance < 0.37) {
return new THREE.Color("#493f35");
}
if (Math.abs(cx) < 0.38) {
return new THREE.Color("#ead8aa");
}
if (Math.abs(cx) > 13.8 || Math.abs(cz) > 12.45) {
return new THREE.Color("#8c7256");
}
const t = clamp01((height - 1.2) / (RIDGE_HEIGHT - 1.2));
const low = cx < 0
? new THREE.Color("#986b48")
: new THREE.Color("#6f8479");
const high = cx < 0
? new THREE.Color("#c9a570")
: new THREE.Color("#adb18d");
const color = low.clone().lerp(high, 0.12 + t * 0.76);
const shade = 0.93 + hash2(ix, iz) * 0.12;
color.multiplyScalar(shade);
return color;
}
const terrainPositions = [];
const terrainColors = [];
function pushTriangle(a, b, c, color) {
terrainPositions.push(
a.x, a.y, a.z,
b.x, b.y, b.z,
c.x, c.y, c.z
);
for (let i = 0; i < 3; i++) {
terrainColors.push(color.r, color.g, color.b);
}
}
for (let iz = 0; iz < zPositions.length - 1; iz++) {
for (let ix = 0; ix < xPositions.length - 1; ix++) {
const a = grid[iz][ix];
const b = grid[iz][ix + 1];
const c = grid[iz + 1][ix + 1];
const d = grid[iz + 1][ix];
const color = faceColor(
(a.x + b.x + c.x + d.x) * 0.25,
(a.z + b.z + c.z + d.z) * 0.25,
(a.y + b.y + c.y + d.y) * 0.25,
ix,
iz
);
// Winding chosen so the faces point upward.
pushTriangle(a, d, b, color);
pushTriangle(b, d, c, color);
}
}
const terrainGeometry = new THREE.BufferGeometry();
terrainGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(terrainPositions, 3)
);
terrainGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(terrainColors, 3)
);
terrainGeometry.computeVertexNormals();
const terrain = new THREE.Mesh(
terrainGeometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
flatShading: true,
roughness: 0.98,
metalness: 0
})
);
terrain.castShadow = true;
terrain.receiveShadow = true;
scene.add(terrain);
// -------------------------------------------------------------------------
// Earth-colored vertical skirt around the terrain tile
// -------------------------------------------------------------------------
const perimeter = [];
for (let i = 0; i < xPositions.length; i++) {
perimeter.push([xPositions[i], -HALF_Z]);
}
for (let i = 1; i < zPositions.length; i++) {
perimeter.push([HALF_X, zPositions[i]]);
}
for (let i = xPositions.length - 2; i >= 0; i--) {
perimeter.push([xPositions[i], HALF_Z]);
}
for (let i = zPositions.length - 2; i >= 1; i--) {
perimeter.push([-HALF_X, zPositions[i]]);
}
const skirtPositions = [];
const skirtColors = [];
const bottomY = -0.55;
function pushSkirtTriangle(a, b, c, color) {
skirtPositions.push(
a.x, a.y, a.z,
b.x, b.y, b.z,
c.x, c.y, c.z
);
for (let i = 0; i < 3; i++) {
skirtColors.push(color.r, color.g, color.b);
}
}
for (let i = 0; i < perimeter.length; i++) {
const next = (i + 1) % perimeter.length;
const p0 = perimeter[i];
const p1 = perimeter[next];
const a = {
x: p0[0],
y: terrainHeight(p0[0], p0[1]),
z: p0[1]
};
const b = {
x: p1[0],
y: terrainHeight(p1[0], p1[1]),
z: p1[1]
};
const aBottom = { x: a.x, y: bottomY, z: a.z };
const bBottom = { x: b.x, y: bottomY, z: b.z };
const color = new THREE.Color("#6f5843").multiplyScalar(
0.88 + hash2(i, 7) * 0.16
);
pushSkirtTriangle(a, b, bBottom, color);
pushSkirtTriangle(a, bBottom, aBottom, color);
}
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,
flatShading: true,
roughness: 1,
side: THREE.DoubleSide
})
);
skirt.castShadow = true;
skirt.receiveShadow = true;
scene.add(skirt);
const plinth = new THREE.Mesh(
new THREE.BoxGeometry(36.45, 1.5, 28.45),
new THREE.MeshStandardMaterial({
color: "#57483b",
roughness: 0.93,
metalness: 0
})
);
plinth.position.y = -1.3;
plinth.castShadow = true;
plinth.receiveShadow = true;
scene.add(plinth);
// -------------------------------------------------------------------------
// Dark, angular drainage-bed ribbons emphasize the descending channels.
// -------------------------------------------------------------------------
const ribbonPositions = [];
const ribbonColors = [];
const ribbonCenter = new THREE.Color("#403a33");
const ribbonEdge = new THREE.Color("#655547");
function pushRibbonTriangle(a, b, c, color) {
ribbonPositions.push(
a.x, a.y, a.z,
b.x, b.y, b.z,
c.x, c.y, c.z
);
for (let i = 0; i < 3; i++) {
ribbonColors.push(color.r, color.g, color.b);
}
}
function createDrainRibbon(side, channel) {
const sideSign = side === "west" ? -1 : 1;
const segments = 26;
const start = 0.34;
const end = 10.52;
const points = [];
for (let i = 0; i <= segments; i++) {
const distance = THREE.MathUtils.lerp(start, end, i / segments);
const x = sideSign * distance;
const z = channelCenterZ(channel, distance);
const halfWidth = 0.115;
points.push([
{
x,
y: terrainHeight(x, z - halfWidth) + 0.026,
z: z - halfWidth
},
{
x,
y: terrainHeight(x, z) + 0.035,
z
},
{
x,
y: terrainHeight(x, z + halfWidth) + 0.026,
z: z + halfWidth
}
]);
}
for (let i = 0; i < segments; i++) {
const p0 = points[i];
const p1 = points[i + 1];
pushRibbonTriangle(p0[0], p1[0], p1[1], ribbonEdge);
pushRibbonTriangle(p0[0], p1[1], p0[1], ribbonEdge);
pushRibbonTriangle(p0[1], p1[1], p1[2], ribbonCenter);
pushRibbonTriangle(p0[1], p1[2], p0[2], ribbonCenter);
}
}
for (const channel of channelSets.west) {
createDrainRibbon("west", channel);
}
for (const channel of channelSets.east) {
createDrainRibbon("east", channel);
}
const ribbonGeometry = new THREE.BufferGeometry();
ribbonGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(ribbonPositions, 3)
);
ribbonGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(ribbonColors, 3)
);
ribbonGeometry.computeVertexNormals();
const ribbons = new THREE.Mesh(
ribbonGeometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
flatShading: true,
roughness: 1,
side: THREE.DoubleSide,
polygonOffset: true,
polygonOffsetFactor: -1,
polygonOffsetUnits: -1
})
);
ribbons.receiveShadow = true;
scene.add(ribbons);
// -------------------------------------------------------------------------
// Faceted stones marking the ridge crest and raised outer boundary
// -------------------------------------------------------------------------
let randomSeed = 1927;
function random() {
randomSeed =
(randomSeed * 1664525 + 1013904223) >>> 0;
return randomSeed / 4294967296;
}
const rockGeometry = new THREE.DodecahedronGeometry(1, 0);
const rockMaterial = new THREE.MeshStandardMaterial({
color: "#ffffff",
flatShading: true,
roughness: 0.96,
metalness: 0
});
const dummy = new THREE.Object3D();
function addRockInstances(entries) {
const mesh = new THREE.InstancedMesh(
rockGeometry,
rockMaterial,
entries.length
);
entries.forEach((entry, index) => {
dummy.position.set(entry.x, entry.y, entry.z);
dummy.rotation.set(
entry.rx,
entry.ry,
entry.rz
);
dummy.scale.set(entry.sx, entry.sy, entry.sz);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
mesh.setColorAt(index, entry.color);
});
mesh.instanceMatrix.needsUpdate = true;
mesh.instanceColor.needsUpdate = true;
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
}
const ridgeRocks = [];
const ridgePalette = [
new THREE.Color("#d8c79f"),
new THREE.Color("#c9b68b"),
new THREE.Color("#e4d5ae")
];
for (let i = 0; i < 28; i++) {
const z = -12.7 + i * 0.94;
const x = (random() - 0.5) * 0.24;
const sx = 0.16 + random() * 0.24;
const sy = 0.13 + random() * 0.22;
const sz = 0.20 + random() * 0.31;
ridgeRocks.push({
x,
y: terrainHeight(x, z) + sy * 0.2,
z,
rx: random() * Math.PI,
ry: random() * Math.PI,
rz: random() * Math.PI,
sx,
sy,
sz,
color: ridgePalette[
Math.floor(random() * ridgePalette.length)
]
});
}
addRockInstances(ridgeRocks);
const boundaryRocks = [];
const boundaryPalette = [
new THREE.Color("#94785b"),
new THREE.Color("#a58a68"),
new THREE.Color("#80684f")
];
function addBoundaryRock(x, z) {
const sx = 0.22 + random() * 0.32;
const sy = 0.17 + random() * 0.28;
const sz = 0.25 + random() * 0.36;
boundaryRocks.push({
x,
y: terrainHeight(x, z) + sy * 0.12,
z,
rx: random() * Math.PI,
ry: random() * Math.PI,
rz: random() * Math.PI,
sx,
sy,
sz,
color: boundaryPalette[
Math.floor(random() * boundaryPalette.length)
]
});
}
for (let x = -16; x <= 16; x += 2.15) {
addBoundaryRock(x, -13.42);
addBoundaryRock(x, 13.42);
}
for (let z = -10.5; z <= 10.5; z += 2.25) {
addBoundaryRock(-17.42, z);
addBoundaryRock(17.42, z);
}
addRockInstances(boundaryRocks);
// -------------------------------------------------------------------------
// Custom camera controls — no addons or examples modules
// -------------------------------------------------------------------------
const controls = {
theta: 0.72,
phi: 0.91,
radius: 52,
target: new THREE.Vector3(0, 2.45, 0),
dragging: false,
panning: false,
lastX: 0,
lastY: 0,
pinchDistance: 0
};
const pointers = new Map();
function updateCamera() {
const sinPhi = Math.sin(controls.phi);
camera.position.set(
controls.target.x +
controls.radius * sinPhi * Math.sin(controls.theta),
controls.target.y +
controls.radius * Math.cos(controls.phi),
controls.target.z +
controls.radius * sinPhi * Math.cos(controls.theta)
);
camera.lookAt(controls.target);
}
function resetCamera() {
controls.theta = 0.72;
controls.phi = 0.91;
controls.radius = 52;
controls.target.set(0, 2.45, 0);
updateCamera();
}
function planView() {
controls.theta = 0;
controls.phi = 0.085;
controls.radius = 48;
controls.target.set(0, 2.45, 0);
updateCamera();
}
renderer.domElement.addEventListener("contextmenu", event => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", event => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 1) {
controls.dragging = true;
controls.panning = event.button === 2 || event.shiftKey;
controls.lastX = event.clientX;
controls.lastY = event.clientY;
} else if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
controls.pinchDistance = Math.hypot(
a.x - b.x,
a.y - b.y
);
}
});
renderer.domElement.addEventListener("pointermove", event => {
if (!pointers.has(event.pointerId)) {
return;
}
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
const distance = Math.hypot(
a.x - b.x,
a.y - b.y
);
if (controls.pinchDistance > 0) {
controls.radius = THREE.MathUtils.clamp(
controls.radius *
controls.pinchDistance /
Math.max(distance, 1),
22,
86
);
}
controls.pinchDistance = distance;
return;
}
if (!controls.dragging) {
return;
}
const dx = event.clientX - controls.lastX;
const dy = event.clientY - controls.lastY;
controls.lastX = event.clientX;
controls.lastY = event.clientY;
if (controls.panning) {
const scale = controls.radius * 0.00125;
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3()
.crossVectors(forward, camera.up)
.normalize();
controls.target.addScaledVector(right, -dx * scale);
controls.target.addScaledVector(forward, dy * scale);
controls.target.x = THREE.MathUtils.clamp(
controls.target.x,
-12,
12
);
controls.target.z = THREE.MathUtils.clamp(
controls.target.z,
-10,
10
);
} else {
controls.theta -= dx * 0.0055;
controls.phi = THREE.MathUtils.clamp(
controls.phi - dy * 0.0048,
0.08,
1.46
);
}
});
function releasePointer(event) {
pointers.delete(event.pointerId);
if (pointers.size === 0) {
controls.dragging = false;
controls.panning = false;
} else {
controls.pinchDistance = 0;
}
}
renderer.domElement.addEventListener(
"pointerup",
releasePointer
);
renderer.domElement.addEventListener(
"pointercancel",
releasePointer
);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
const factor = Math.exp(event.deltaY * 0.001);
controls.radius = THREE.MathUtils.clamp(
controls.radius * factor,
22,
86
);
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
document.getElementById("resetButton")
.addEventListener("click", resetCamera);
document.getElementById("planButton")
.addEventListener("click", planView);
window.addEventListener("keydown", event => {
if (event.key.toLowerCase() === "r") {
resetCamera();
}
if (event.key.toLowerCase() === "v") {
planView();
}
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(
Math.min(window.devicePixelRatio, 2)
);
renderer.setSize(
window.innerWidth,
window.innerHeight
);
});
// -------------------------------------------------------------------------
// Render loop
// -------------------------------------------------------------------------
updateCamera();
renderer.setAnimationLoop(() => {
updateCamera();
renderer.render(scene, camera);
});
</script>
</body>
</html>
```