Prompt specification
Build or customize the Three.js 3D scene "Contour route planning challenge" 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: Contour route planning challenge
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/contour-route-planning-challenge-x1296
Scene Description Prompt:
Trace low-poly contour-map walks, comparing a short steep path with a longer gentle route; report distance and climb separately. Three.js from cdnjs, standalone HTML.
Working Three.js Starter (contour-route-planning-challenge-x1296):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Contour Walk — Route Comparison</title>
<style>
:root {
--ink: #26362f;
--muted: #68766d;
--paper: #f5f1e4;
--paper-dark: #e8e2d2;
--short: #e7673f;
--gentle: #167b83;
--shadow: 0 18px 55px rgba(38, 54, 47, 0.17);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e8eadf;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.brand {
position: fixed;
top: 24px;
left: 28px;
z-index: 5;
max-width: 430px;
pointer-events: none;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 8px;
color: #52665b;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
width: 28px;
height: 2px;
background: var(--short);
content: "";
}
h1 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(34px, 4vw, 58px);
font-weight: 500;
line-height: 0.96;
letter-spacing: -0.045em;
}
.brand p {
max-width: 390px;
margin: 13px 0 0;
color: #65736b;
font-size: 13px;
line-height: 1.55;
}
.panel {
position: fixed;
top: 20px;
right: 20px;
z-index: 6;
width: 370px;
padding: 20px;
overflow: auto;
border: 1px solid rgba(69, 83, 73, 0.17);
border-radius: 20px;
background: rgba(248, 246, 237, 0.93);
box-shadow: var(--shadow);
backdrop-filter: blur(15px);
}
.panel-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 15px;
}
.panel-heading h2 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: 24px;
font-weight: 500;
letter-spacing: -0.025em;
}
.panel-heading p {
margin: 5px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.badge {
flex: 0 0 auto;
padding: 6px 8px;
border-radius: 999px;
background: #e7eadc;
color: #53655a;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.route-card {
--route: var(--short);
position: relative;
margin-bottom: 12px;
padding: 16px 15px 14px 18px;
overflow: hidden;
border: 1px solid rgba(60, 74, 64, 0.13);
border-radius: 14px;
background: rgba(255, 255, 255, 0.48);
}
.route-card::before {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 5px;
background: var(--route);
content: "";
}
.route-card.gentle {
--route: var(--gentle);
}
.route-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 13px;
}
.route-title h3 {
display: flex;
align-items: center;
gap: 9px;
margin: 0;
font-size: 14px;
font-weight: 800;
}
.route-dot {
width: 10px;
height: 10px;
border: 3px solid white;
border-radius: 50%;
background: var(--route);
box-shadow: 0 0 0 1px var(--route);
}
.route-type {
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.metric {
padding: 10px 11px;
border-radius: 10px;
background: rgba(229, 231, 216, 0.65);
}
.metric span {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.metric strong {
font-size: 22px;
font-weight: 750;
letter-spacing: -0.04em;
}
.metric strong small {
margin-left: 2px;
color: var(--muted);
font-size: 11px;
font-weight: 700;
letter-spacing: 0;
}
.grade-row {
display: grid;
grid-template-columns: 58px 1fr 35px;
align-items: center;
gap: 8px;
margin-top: 11px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.grade-row output {
color: var(--ink);
text-align: right;
}
.track {
height: 5px;
overflow: hidden;
border-radius: 999px;
background: #dfe1d3;
}
.fill {
width: 0;
height: 100%;
border-radius: inherit;
background: var(--route);
transition: width 700ms cubic-bezier(0.2, 0.8, 0.2, 1);
}
.comparison {
margin-top: 15px;
padding: 14px 15px;
border-radius: 13px;
background: #2e4439;
color: #f3f0e4;
}
.comparison strong {
display: block;
margin-bottom: 5px;
font-family: Georgia, "Times New Roman", serif;
font-size: 17px;
font-weight: 500;
}
.comparison p {
margin: 0;
color: #ced8cf;
font-size: 11px;
line-height: 1.55;
}
.comparison b {
color: #fff7df;
}
.legend {
position: fixed;
bottom: 24px;
left: 28px;
z-index: 5;
display: flex;
flex-wrap: wrap;
gap: 15px;
max-width: 450px;
padding: 10px 13px;
border: 1px solid rgba(65, 79, 68, 0.13);
border-radius: 12px;
background: rgba(248, 246, 237, 0.82);
color: #53635a;
box-shadow: 0 8px 25px rgba(38, 54, 47, 0.09);
backdrop-filter: blur(10px);
pointer-events: none;
font-size: 10px;
font-weight: 700;
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
}
.legend-line {
width: 23px;
height: 4px;
border-radius: 99px;
background: var(--short);
}
.legend-line.gentle {
background: var(--gentle);
}
.legend-line.contour {
height: 1px;
background: #667c68;
}
.hint {
position: fixed;
right: 25px;
bottom: 23px;
z-index: 5;
color: rgba(48, 66, 55, 0.67);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.04em;
pointer-events: none;
}
.controls {
position: fixed;
right: 410px;
bottom: 20px;
z-index: 7;
display: flex;
gap: 7px;
}
button {
padding: 9px 11px;
border: 1px solid rgba(54, 71, 60, 0.18);
border-radius: 9px;
background: rgba(248, 246, 237, 0.9);
color: #43584b;
box-shadow: 0 5px 15px rgba(38, 54, 47, 0.08);
cursor: pointer;
font: inherit;
font-size: 10px;
font-weight: 800;
transition:
transform 150ms ease,
background 150ms ease;
}
button:hover {
transform: translateY(-1px);
background: #fffdf4;
}
button:active {
transform: translateY(0);
}
button[aria-pressed="false"] {
color: #9b9d91;
text-decoration: line-through;
}
.compass {
position: fixed;
top: 29px;
left: 50%;
z-index: 5;
width: 42px;
height: 42px;
border: 1px solid rgba(52, 70, 58, 0.18);
border-radius: 50%;
color: #506359;
pointer-events: none;
font-size: 9px;
font-weight: 900;
text-align: center;
}
.compass::before {
position: absolute;
top: 5px;
left: 18px;
width: 0;
height: 0;
border-right: 4px solid transparent;
border-bottom: 12px solid var(--short);
border-left: 4px solid transparent;
content: "";
}
.compass span {
position: absolute;
right: 0;
bottom: 3px;
left: 0;
}
@media (max-width: 900px) {
.brand {
top: 18px;
left: 18px;
}
.brand p {
display: none;
}
.panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 45vh;
padding: 15px;
border-radius: 16px;
}
.panel-heading {
margin-bottom: 10px;
}
.panel-heading h2 {
font-size: 20px;
}
.route-card {
margin-bottom: 8px;
padding: 12px;
}
.route-title {
margin-bottom: 9px;
}
.metric {
padding: 7px 9px;
}
.metric strong {
font-size: 19px;
}
.comparison {
margin-top: 10px;
}
.controls {
top: 18px;
right: 14px;
bottom: auto;
}
.hint,
.legend {
display: none;
}
.compass {
display: none;
}
}
@media (max-width: 520px) {
h1 {
font-size: 36px;
}
.panel-heading p,
.badge,
.grade-row {
display: none;
}
.metrics {
gap: 6px;
}
}
</style>
</head>
<body>
<header class="brand">
<div class="eyebrow">Topographic route study</div>
<h1>Two ways up.</h1>
<p>
Compare a direct, steep ascent with a longer contouring route.
Distance and elevation gain are calculated independently.
</p>
</header>
<aside class="panel" aria-label="Route comparison">
<div class="panel-heading">
<div>
<h2>Route comparison</h2>
<p>Same trailhead. Same summit. Different effort.</p>
</div>
<div class="badge">Live terrain</div>
</div>
<section class="route-card">
<div class="route-title">
<h3><span class="route-dot"></span>Short / steep</h3>
<span class="route-type">Direct ridge</span>
</div>
<div class="metrics">
<div class="metric">
<span>Distance</span>
<strong><span id="shortDistance">—</span><small>km</small></strong>
</div>
<div class="metric">
<span>Climb</span>
<strong><span id="shortClimb">—</span><small>m</small></strong>
</div>
</div>
<div class="grade-row">
<span>Avg grade</span>
<div class="track"><div class="fill" id="shortDistanceBar"></div></div>
<output id="shortGrade">—</output>
</div>
</section>
<section class="route-card gentle">
<div class="route-title">
<h3><span class="route-dot"></span>Long / gentle</h3>
<span class="route-type">Contour traverse</span>
</div>
<div class="metrics">
<div class="metric">
<span>Distance</span>
<strong><span id="gentleDistance">—</span><small>km</small></strong>
</div>
<div class="metric">
<span>Climb</span>
<strong><span id="gentleClimb">—</span><small>m</small></strong>
</div>
</div>
<div class="grade-row">
<span>Avg grade</span>
<div class="track"><div class="fill" id="gentleDistanceBar"></div></div>
<output id="gentleGrade">—</output>
</div>
</section>
<section class="comparison">
<strong>The trade-off</strong>
<p id="comparisonText">
The longer route reduces the average gradient while adding distance.
</p>
</section>
</aside>
<div class="legend">
<div class="legend-item"><span class="legend-line"></span>Short / steep</div>
<div class="legend-item"><span class="legend-line gentle"></span>Long / gentle</div>
<div class="legend-item"><span class="legend-line contour"></span>Contour</div>
<div class="legend-item">500 m scale · 100 m contours</div>
</div>
<div class="controls">
<button id="resetView" type="button">Reset view</button>
<button id="topView" type="button">Top view</button>
<button id="toggleContours" type="button" aria-pressed="true">Contours</button>
</div>
<div class="hint">Drag to orbit · scroll to zoom · double-click to reset</div>
<div class="compass"><span>N</span></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(0xe8eadf);
scene.fog = new THREE.Fog(0xe8eadf, 20, 38);
const camera = new THREE.PerspectiveCamera(
39,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.prepend(renderer.domElement);
const hemi = new THREE.HemisphereLight(0xfff6dc, 0x657360, 2.05);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xffefd0, 2.65);
sun.position.set(-7, 12, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -12;
sun.shadow.camera.right = 12;
sun.shadow.camera.top = 11;
sun.shadow.camera.bottom = -11;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
sun.shadow.bias = -0.0007;
scene.add(sun);
// ------------------------------------------------------------
// Terrain definition
// 1 world unit horizontally = 250 m.
// 1 world unit vertically = 250 m.
// ------------------------------------------------------------
const MAP_W = 13;
const MAP_D = 10;
const HALF_W = MAP_W / 2;
const HALF_D = MAP_D / 2;
const METERS_PER_UNIT = 250;
const BASE_ELEVATION = 120;
const CONTOUR_INTERVAL = 0.4; // 100 m
function terrainHeight(x, z) {
const summit =
3.05 * Math.exp(-(x * x / 8.5 + z * z / 11.0));
const ridge =
0.32 *
Math.exp(-(
Math.pow(x + 1.55, 2) / 2.8 +
Math.pow(z - 1.75, 2) / 3.5
));
const southernSwell =
0.22 *
Math.exp(-(
Math.pow(x - 2.2, 2) / 5.5 +
Math.pow(z + 2.1, 2) / 4.2
));
return 0.14 + summit + ridge + southernSwell;
}
function elevationAt(x, z) {
return BASE_ELEVATION + terrainHeight(x, z) * METERS_PER_UNIT;
}
// ------------------------------------------------------------
// Low-poly terrain mesh
// ------------------------------------------------------------
const terrainSegmentsX = 48;
const terrainSegmentsZ = 36;
function terrainColor(height) {
const t = THREE.MathUtils.clamp(
(height - 0.12) / (3.65 - 0.12),
0,
1
);
const palette = [
new THREE.Color(0xcbd9b4),
new THREE.Color(0xd4d7aa),
new THREE.Color(0xdccb9e),
new THREE.Color(0xcdb78a),
new THREE.Color(0xb79b78),
new THREE.Color(0x9d856b)
];
const scaled = t * (palette.length - 1);
const index = Math.min(
palette.length - 2,
Math.floor(scaled)
);
return palette[index]
.clone()
.lerp(palette[index + 1], scaled - index);
}
function buildTerrain() {
const positions = [];
const indices = [];
for (let iz = 0; iz <= terrainSegmentsZ; iz++) {
const z = -HALF_D + (iz / terrainSegmentsZ) * MAP_D;
for (let ix = 0; ix <= terrainSegmentsX; ix++) {
const x = -HALF_W + (ix / terrainSegmentsX) * MAP_W;
positions.push(x, terrainHeight(x, z), z);
}
}
const row = terrainSegmentsX + 1;
for (let iz = 0; iz < terrainSegmentsZ; iz++) {
for (let ix = 0; ix < terrainSegmentsX; ix++) {
const a = iz * row + ix;
const b = a + 1;
const c = a + row;
const d = c + 1;
indices.push(a, c, b, b, c, d);
}
}
const indexed = new THREE.BufferGeometry();
indexed.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
indexed.setIndex(indices);
const geometry = indexed.toNonIndexed();
indexed.dispose();
geometry.computeVertexNormals();
const position = geometry.getAttribute("position");
const colors = [];
for (let i = 0; i < position.count; i += 3) {
const averageHeight =
(position.getY(i) +
position.getY(i + 1) +
position.getY(i + 2)) / 3;
const color = terrainColor(averageHeight);
const random = Math.sin(i * 12.9898) * 43758.5453;
color.offsetHSL(0, 0, (random - Math.floor(random) - 0.5) * 0.025);
for (let j = 0; j < 3; j++) {
colors.push(color.r, color.g, color.b);
}
}
geometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(colors, 3)
);
return geometry;
}
const terrain = new THREE.Mesh(
buildTerrain(),
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.96,
metalness: 0,
flatShading: true
})
);
terrain.castShadow = true;
terrain.receiveShadow = true;
scene.add(terrain);
// Terrain side walls.
const skirtPositions = [];
function addSkirtSegment(ax, az, bx, bz) {
const ay = terrainHeight(ax, az);
const by = terrainHeight(bx, bz);
const bottom = -0.05;
skirtPositions.push(
ax, ay, az,
ax, bottom, az,
bx, by, bz,
bx, by, bz,
ax, bottom, az,
bx, bottom, bz
);
}
const edgeStep = 0.5;
for (let x = -HALF_W; x < HALF_W; x += edgeStep) {
addSkirtSegment(x, HALF_D, x + edgeStep, HALF_D);
addSkirtSegment(x, -HALF_D, x + edgeStep, -HALF_D);
}
for (let z = -HALF_D; z < HALF_D; z += edgeStep) {
addSkirtSegment(HALF_W, z, HALF_W, z + edgeStep);
addSkirtSegment(-HALF_W, z, -HALF_W, z + edgeStep);
}
const skirtGeometry = new THREE.BufferGeometry();
skirtGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(skirtPositions, 3)
);
skirtGeometry.computeVertexNormals();
const skirt = new THREE.Mesh(
skirtGeometry,
new THREE.MeshStandardMaterial({
color: 0x707864,
roughness: 1,
flatShading: true,
side: THREE.DoubleSide
})
);
skirt.castShadow = true;
skirt.receiveShadow = true;
scene.add(skirt);
const base = new THREE.Mesh(
new THREE.BoxGeometry(MAP_W, 0.54, MAP_D),
new THREE.MeshStandardMaterial({
color: 0x68705f,
roughness: 1
})
);
base.position.y = -0.32;
base.castShadow = true;
base.receiveShadow = true;
scene.add(base);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(60, 60),
new THREE.ShadowMaterial({
color: 0x435044,
opacity: 0.15
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.605;
ground.receiveShadow = true;
scene.add(ground);
// ------------------------------------------------------------
// Marching-squares contour lines
// ------------------------------------------------------------
function buildContours() {
const vertices = [];
let minHeight = Infinity;
let maxHeight = -Infinity;
for (let iz = 0; iz <= terrainSegmentsZ; iz++) {
for (let ix = 0; ix <= terrainSegmentsX; ix++) {
const x = -HALF_W + (ix / terrainSegmentsX) * MAP_W;
const z = -HALF_D + (iz / terrainSegmentsZ) * MAP_D;
const h = terrainHeight(x, z);
minHeight = Math.min(minHeight, h);
maxHeight = Math.max(maxHeight, h);
}
}
const firstLevel =
Math.ceil(minHeight / CONTOUR_INTERVAL) * CONTOUR_INTERVAL;
for (
let level = firstLevel;
level <= maxHeight;
level += CONTOUR_INTERVAL
) {
for (let iz = 0; iz < terrainSegmentsZ; iz++) {
const z0 =
-HALF_D + (iz / terrainSegmentsZ) * MAP_D;
const z1 =
-HALF_D + ((iz + 1) / terrainSegmentsZ) * MAP_D;
for (let ix = 0; ix < terrainSegmentsX; ix++) {
const x0 =
-HALF_W + (ix / terrainSegmentsX) * MAP_W;
const x1 =
-HALF_W + ((ix + 1) / terrainSegmentsX) * MAP_W;
const p = [
[x0, z0],
[x1, z0],
[x1, z1],
[x0, z1]
];
const values = p.map(([x, z]) =>
terrainHeight(x, z)
);
const intersections = [];
for (let edge = 0; edge < 4; edge++) {
const nextEdge = (edge + 1) % 4;
const va = values[edge];
const vb = values[nextEdge];
const crosses =
(va < level && vb >= level) ||
(vb < level && va >= level);
if (!crosses) continue;
const t = (level - va) / (vb - va);
intersections.push([
p[edge][0] +
(p[nextEdge][0] - p[edge][0]) * t,
p[edge][1] +
(p[nextEdge][1] - p[edge][1]) * t
]);
}
for (let i = 0; i + 1 < intersections.length; i += 2) {
const a = intersections[i];
const b = intersections[i + 1];
vertices.push(
a[0], level + 0.055, a[1],
b[0], level + 0.055, b[1]
);
}
}
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(vertices, 3)
);
const lines = new THREE.LineSegments(
geometry,
new THREE.LineBasicMaterial({
color: 0x496253,
transparent: true,
opacity: 0.38,
depthWrite: false
})
);
lines.renderOrder = 1;
scene.add(lines);
return lines;
}
const contours = buildContours();
// ------------------------------------------------------------
// Route curves and statistics
// ------------------------------------------------------------
const trailhead = [-4.8, 3.6];
const summit = [0, 0];
const shortControls = [
[-4.8, 3.6],
[-4.15, 2.9],
[-3.45, 2.2],
[-2.75, 1.55],
[-2.0, 1.0],
[-1.2, 0.5],
[-0.45, 0.1],
[0, 0]
];
const gentleControls = [
[-4.8, 3.6],
[-5.45, 2.45],
[-5.55, 1.1],
[-5.35, -0.45],
[-4.85, -1.85],
[-3.9, -3.05],
[-2.55, -4.15],
[-1.0, -4.65],
[0.65, -4.55],
[2.0, -3.85],
[3.0, -2.75],
[3.55, -1.4],
[3.65, 0],
[3.2, 1.15],
[2.35, 1.65],
[1.45, 1.2],
[0.65, 0.55],
[0, 0]
];
function createRoute(controlPoints, colorHex) {
const xzCurve = new THREE.CatmullRomCurve3(
controlPoints.map(
([x, z]) => new THREE.Vector3(x, 0, z)
),
false,
"centripetal"
);
// The route follows the terrain continuously rather than
// interpolating independently in the vertical axis.
const routeCurve = new THREE.Curve();
routeCurve.getPoint = function (
t,
target = new THREE.Vector3()
) {
const point = xzCurve.getPoint(t);
target.set(
point.x,
terrainHeight(point.x, point.z) + 0.09,
point.z
);
return target;
};
const samples = routeCurve.getPoints(700);
let distance = 0;
let ascent = 0;
let descent = 0;
for (let i = 1; i < samples.length; i++) {
const previous = samples[i - 1];
const current = samples[i];
const dx = current.x - previous.x;
const dy = current.y - previous.y;
const dz = current.z - previous.z;
distance +=
Math.hypot(dx, dy, dz) * METERS_PER_UNIT;
if (dy > 0) {
ascent += dy * METERS_PER_UNIT;
} else {
descent -= dy * METERS_PER_UNIT;
}
}
const stats = {
distance,
ascent,
descent,
grade: (ascent / distance) * 100
};
const guideGeometry = new THREE.TubeGeometry(
routeCurve,
360,
0.057,
5,
false
);
const guide = new THREE.Mesh(
guideGeometry,
new THREE.MeshBasicMaterial({
color: colorHex,
transparent: true,
opacity: 0.18,
depthWrite: false
})
);
guide.renderOrder = 2;
scene.add(guide);
const activeGeometry = new THREE.TubeGeometry(
routeCurve,
360,
0.035,
5,
false
);
const activeMaterial = new THREE.ShaderMaterial({
uniforms: {
uColor: { value: new THREE.Color(colorHex) },
uProgress: { value: 0 }
},
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position =
projectionMatrix *
modelViewMatrix *
vec4(position, 1.0);
}
`,
fragmentShader: `
uniform vec3 uColor;
uniform float uProgress;
varying vec2 vUv;
void main() {
if (vUv.x > uProgress) discard;
gl_FragColor = vec4(uColor, 1.0);
}
`,
side: THREE.DoubleSide
});
const active = new THREE.Mesh(
activeGeometry,
activeMaterial
);
active.renderOrder = 3;
scene.add(active);
const tracer = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.105, 1),
new THREE.MeshBasicMaterial({
color: 0xfff8df
})
);
tracer.castShadow = true;
scene.add(tracer);
const tracerCore = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.07, 0),
new THREE.MeshBasicMaterial({
color: colorHex
})
);
tracer.add(tracerCore);
scene.add(tracer);
return {
curve: routeCurve,
stats,
activeMaterial,
tracer,
delay: 0
};
}
const shortRoute = createRoute(shortControls, 0xe7673f);
const gentleRoute = createRoute(gentleControls, 0x167b83);
shortRoute.delay = 0.25;
gentleRoute.delay = 1.1;
// ------------------------------------------------------------
// Trailhead and summit markers
// ------------------------------------------------------------
function createGroundMarker(x, z, color) {
const group = new THREE.Group();
const disk = new THREE.Mesh(
new THREE.CylinderGeometry(0.13, 0.15, 0.045, 8),
new THREE.MeshStandardMaterial({
color,
roughness: 0.72
})
);
group.add(disk);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.22, 0.026, 5, 18),
new THREE.MeshBasicMaterial({ color })
);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.035;
group.add(ring);
group.position.set(
x,
terrainHeight(x, z) + 0.045,
z
);
scene.add(group);
return group;
}
createGroundMarker(
trailhead[0],
trailhead[1],
0xe7673f
);
createGroundMarker(
summit[0],
summit[1],
0x167b83
);
function roundedRect(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
}
function createLabel(text, x, y, z, accent) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "rgba(248, 246, 237, 0.94)";
roundedRect(ctx, 8, 18, 496, 86, 30);
ctx.fill();
ctx.strokeStyle = "rgba(55, 73, 61, 0.18)";
ctx.lineWidth = 3;
ctx.stroke();
ctx.fillStyle = accent;
ctx.beginPath();
ctx.arc(43, 61, 10, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = "#34483c";
ctx.font = "800 29px system-ui, sans-serif";
ctx.textBaseline = "middle";
ctx.fillText(text, 70, 62);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.position.set(x, y, z);
sprite.scale.set(2.55, 0.64, 1);
sprite.renderOrder = 10;
scene.add(sprite);
return sprite;
}
createLabel(
"TRAILHEAD",
trailhead[0],
terrainHeight(trailhead[0], trailhead[1]) + 0.55,
trailhead[1],
"#e7673f"
);
createLabel(
`SUMMIT ${Math.round(elevationAt(...summit))} m`,
summit[0],
terrainHeight(...summit) + 0.68,
summit[1],
"#167b83"
);
// ------------------------------------------------------------
// Statistics in the interface
// ------------------------------------------------------------
const shortStats = shortRoute.stats;
const gentleStats = gentleRoute.stats;
document.getElementById("shortDistance").textContent =
(shortStats.distance / 1000).toFixed(2);
document.getElementById("shortClimb").textContent =
Math.round(shortStats.ascent).toLocaleString();
document.getElementById("gentleDistance").textContent =
(gentleStats.distance / 1000).toFixed(2);
document.getElementById("gentleClimb").textContent =
Math.round(gentleStats.ascent).toLocaleString();
document.getElementById("shortGrade").textContent =
`${Math.round(shortStats.grade)}%`;
document.getElementById("gentleGrade").textContent =
`${Math.round(gentleStats.grade)}%`;
requestAnimationFrame(() => {
document.getElementById("shortDistanceBar").style.width =
`${(shortStats.distance / gentleStats.distance) * 100}%`;
document.getElementById("gentleDistanceBar").style.width = "100%";
});
const extraDistance =
(gentleStats.distance - shortStats.distance) / 1000;
const gradeReduction =
shortStats.grade - gentleStats.grade;
const climbDifference =
gentleStats.ascent - shortStats.ascent;
const climbText =
Math.abs(climbDifference) < 25
? "Both routes gain almost the same elevation."
: `The longer route records ${Math.round(
Math.abs(climbDifference)
)} m ${climbDifference > 0 ? "more" : "less"} total ascent.`;
document.getElementById("comparisonText").innerHTML =
`The gentle route adds <b>${extraDistance.toFixed(
1
)} km</b> and lowers average gradient by <b>${Math.round(
gradeReduction
)} percentage points</b>. ${climbText}`;
// ------------------------------------------------------------
// Direct orbit controls: no external controls addon
// ------------------------------------------------------------
const defaultView = {
theta: 0.68,
phi: 0.73,
radius: 17.4,
target: new THREE.Vector3(0, 1.05, 0)
};
const desired = {
theta: defaultView.theta,
phi: defaultView.phi,
radius: defaultView.radius,
target: defaultView.target.clone()
};
const current = {
theta: defaultView.theta,
phi: defaultView.phi,
radius: defaultView.radius,
target: defaultView.target.clone()
};
function applyView(view) {
desired.theta = view.theta;
desired.phi = view.phi;
desired.radius = view.radius;
desired.target.copy(view.target);
}
function resetView() {
applyView(defaultView);
}
const canvas = renderer.domElement;
const pointer = {
active: false,
id: null,
x: 0,
y: 0
};
canvas.addEventListener("pointerdown", (event) => {
pointer.active = true;
pointer.id = event.pointerId;
pointer.x = event.clientX;
pointer.y = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!pointer.active || event.pointerId !== pointer.id) {
return;
}
const dx = event.clientX - pointer.x;
const dy = event.clientY - pointer.y;
pointer.x = event.clientX;
pointer.y = event.clientY;
desired.theta -= dx * 0.006;
desired.phi = THREE.MathUtils.clamp(
desired.phi + dy * 0.005,
0.08,
1.36
);
});
function endPointer(event) {
if (event.pointerId !== pointer.id) return;
pointer.active = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
desired.radius = THREE.MathUtils.clamp(
desired.radius * Math.exp(event.deltaY * 0.001),
8.5,
28
);
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetView);
canvas.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
document.getElementById("resetView").addEventListener(
"click",
resetView
);
document.getElementById("topView").addEventListener(
"click",
() => {
applyView({
theta: 0,
phi: 0.085,
radius: 18,
target: new THREE.Vector3(0, 0.55, 0)
});
}
);
const contourButton =
document.getElementById("toggleContours");
contourButton.addEventListener("click", () => {
contours.visible = !contours.visible;
contourButton.setAttribute(
"aria-pressed",
String(contours.visible)
);
});
// ------------------------------------------------------------
// Animation
// ------------------------------------------------------------
const reduceMotion = matchMedia(
"(prefers-reduced-motion: reduce)"
).matches;
const clock = new THREE.Clock();
function updateCamera() {
current.theta +=
(desired.theta - current.theta) * 0.12;
current.phi +=
(desired.phi - current.phi) * 0.12;
current.radius +=
(desired.radius - current.radius) * 0.12;
current.target.lerp(
desired.target,
0.12
);
const sinPhi = Math.sin(current.phi);
const cosPhi = Math.cos(current.phi);
camera.position.set(
current.target.x +
current.radius * sinPhi * Math.sin(current.theta),
current.target.y + current.radius * cosPhi,
current.target.z +
current.radius * sinPhi * Math.cos(current.theta)
);
camera.lookAt(current.target);
}
function animateRoute(route, elapsed, duration) {
const progress = reduceMotion
? 1
: THREE.MathUtils.clamp(
(elapsed - route.delay) / duration,
0,
1
);
route.activeMaterial.uniforms.uProgress.value = progress;
const position = route.curve.getPointAt(progress);
route.tracer.position.copy(position);
const pulse = 1 + Math.sin(elapsed * 6) * 0.08;
route.tracer.scale.setScalar(pulse);
}
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
updateCamera();
animateRoute(shortRoute, elapsed, 5.2);
animateRoute(gentleRoute, elapsed, 6.4);
renderer.render(scene, camera);
}
function resize() {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
}
addEventListener("resize", resize);
animate();
</script>
</body>
</html>
```