Prompt specification
Build or customize the Three.js 3D scene "Cycling routes through a small valley" 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: Cycling routes through a small valley
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/cycling-routes-through-a-small-valley-x1299
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts route distance and travel-time tradeoffs. Create a valley with direct steep and longer level routes. Animate identical riders using explicitly stated speed assumptions and display distance, ascent, and estimated time separately. Voxel style.
Working Three.js Starter (cycling-routes-through-a-small-valley-x1299):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Valley — Route Tradeoff</title>
<style>
:root {
--ink: #101b25;
--panel: rgba(12, 23, 33, 0.94);
--line: rgba(220, 237, 245, 0.18);
--text: #eef6f7;
--muted: #9fb5bd;
--direct: #ff8438;
--level: #32d5c1;
--cream: #ffe8ad;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #9fc7d6;
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
cursor: grab;
touch-action: none;
}
#scene canvas:active {
cursor: grabbing;
}
.topbar {
position: fixed;
top: 18px;
left: 18px;
right: 18px;
z-index: 10;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 18px;
pointer-events: none;
}
.brand,
.controls {
background: var(--panel);
border: 1px solid var(--line);
box-shadow: 0 8px 0 rgba(6, 13, 19, 0.18);
pointer-events: auto;
}
.brand {
max-width: 440px;
padding: 15px 18px;
}
.eyebrow {
color: var(--cream);
font: 700 11px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 7px 0 4px;
font-size: clamp(22px, 2.5vw, 34px);
line-height: 1;
letter-spacing: -0.04em;
}
.brand p {
margin: 0;
color: var(--muted);
font-size: 12px;
}
.controls {
min-width: 290px;
padding: 11px 12px;
}
.control-row {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.control-button {
min-height: 33px;
padding: 7px 10px;
border: 1px solid var(--line);
border-radius: 0;
background: #172733;
color: var(--text);
cursor: pointer;
font-size: 12px;
font-weight: 700;
}
.control-button:hover {
background: #213744;
border-color: rgba(255, 255, 255, 0.35);
}
.speed-control {
display: flex;
align-items: center;
gap: 8px;
color: var(--muted);
font: 11px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.speed-control input {
width: 92px;
accent-color: var(--cream);
}
#speedValue {
min-width: 31px;
color: var(--cream);
font-weight: 700;
}
#simStatus {
margin-top: 9px;
color: var(--muted);
font: 10px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.03em;
}
#simStatus strong {
color: var(--text);
}
.route-panel {
position: fixed;
z-index: 10;
left: 50%;
bottom: 16px;
width: min(900px, calc(100vw - 36px));
transform: translateX(-50%);
}
.route-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.route-card {
position: relative;
display: block;
width: 100%;
min-width: 0;
padding: 15px 16px 13px;
overflow: hidden;
border: 1px solid var(--line);
border-top: 4px solid var(--route-color);
border-radius: 0;
background: var(--panel);
color: var(--text);
text-align: left;
box-shadow: 0 8px 0 rgba(6, 13, 19, 0.18);
cursor: pointer;
transition: transform 120ms ease, border-color 120ms ease;
}
.route-card:hover,
.route-card.active {
transform: translateY(-2px);
border-color: var(--route-color);
}
.route-card.direct {
--route-color: var(--direct);
}
.route-card.level {
--route-color: var(--level);
}
.route-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
}
.route-name {
color: var(--route-color);
font: 800 12px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.route-subtitle {
margin-top: 4px;
font-size: 18px;
font-weight: 800;
letter-spacing: -0.025em;
}
.grade-chip {
flex: 0 0 auto;
padding: 4px 7px;
border: 1px solid color-mix(in srgb, var(--route-color) 55%, transparent);
color: var(--route-color);
background: color-mix(in srgb, var(--route-color) 10%, transparent);
font: 700 10px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.route-explanation {
min-height: 32px;
margin: 8px 0 12px;
color: var(--muted);
font-size: 11px;
line-height: 1.4;
}
.metrics {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 8px;
}
.metric {
min-width: 0;
padding-left: 9px;
border-left: 2px solid rgba(255, 255, 255, 0.13);
}
.metric span {
display: block;
margin-bottom: 4px;
color: var(--muted);
font: 700 9px ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.metric strong {
display: block;
overflow: hidden;
color: var(--text);
font: 800 clamp(15px, 1.6vw, 20px) ui-monospace, SFMono-Regular, Menlo, monospace;
white-space: nowrap;
text-overflow: ellipsis;
}
.ride-progress {
height: 3px;
margin-top: 13px;
overflow: hidden;
background: rgba(255, 255, 255, 0.1);
}
.ride-progress i {
display: block;
width: 0;
height: 100%;
background: var(--route-color);
}
.model-note {
display: flex;
align-items: center;
gap: 16px;
flex-wrap: wrap;
margin-top: 10px;
padding: 9px 12px;
border: 1px solid var(--line);
background: rgba(12, 23, 33, 0.88);
color: var(--muted);
font: 10px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.model-note strong {
color: var(--cream);
font-size: 10px;
letter-spacing: 0.06em;
}
.model-note .formula {
color: var(--text);
}
.world-label {
position: fixed;
z-index: 4;
pointer-events: none;
transform: translate(-50%, -50%);
padding: 4px 7px;
border: 1px solid rgba(255, 255, 255, 0.35);
background: rgba(12, 23, 33, 0.82);
color: #fff;
box-shadow: 3px 3px 0 rgba(5, 10, 14, 0.25);
font: 800 9px ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.1em;
white-space: nowrap;
transition: opacity 120ms ease;
}
.world-label.direct {
border-color: var(--direct);
color: var(--direct);
}
.world-label.level {
border-color: var(--level);
color: var(--level);
}
.help {
position: fixed;
z-index: 8;
left: 18px;
bottom: 222px;
padding: 7px 9px;
border: 1px solid rgba(12, 23, 33, 0.22);
background: rgba(238, 246, 247, 0.8);
color: #263944;
font: 700 10px ui-monospace, SFMono-Regular, Menlo, monospace;
pointer-events: none;
}
#webglError {
position: fixed;
z-index: 100;
inset: 0;
display: none;
place-items: center;
padding: 30px;
background: #101b25;
color: white;
text-align: center;
}
@media (max-width: 760px) {
.topbar {
top: 10px;
left: 10px;
right: 10px;
gap: 8px;
}
.brand {
max-width: 55%;
padding: 11px 12px;
}
.brand p {
display: none;
}
.controls {
min-width: 0;
max-width: 45%;
padding: 8px;
}
.control-button {
padding: 6px 8px;
font-size: 10px;
}
.speed-control {
width: 100%;
font-size: 9px;
}
.speed-control input {
min-width: 0;
width: 80px;
}
.route-panel {
bottom: 8px;
width: calc(100vw - 16px);
max-height: 53vh;
overflow-y: auto;
}
.route-grid {
grid-template-columns: 1fr;
}
.route-explanation {
min-height: 0;
}
.model-note {
gap: 5px 12px;
font-size: 9px;
}
.help {
display: none;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<header class="topbar">
<div class="brand">
<div class="eyebrow">Alpine Route Lab / 01</div>
<h1>Two ways. One rider.</h1>
<p>Compare a short ridge cut with a longer, gentler contour route.</p>
</div>
<div class="controls">
<div class="control-row">
<button class="control-button" id="pauseButton" type="button">Pause</button>
<button class="control-button" id="resetView" type="button">Reset view</button>
<label class="speed-control">
<span>Playback</span>
<input id="playback" type="range" min="1" max="30" step="1" value="20">
<output id="speedValue">20×</output>
</label>
</div>
<div id="simStatus">
<strong>RUNNING</strong> · identical riders · modeled clock <span id="simClock">00:00</span>
</div>
</div>
</header>
<section class="route-panel" aria-label="Route comparison">
<div class="route-grid">
<button
class="route-card direct"
id="directCard"
type="button"
aria-label="Focus the direct steep route"
>
<div class="route-heading">
<div>
<div class="route-name">Route A / Direct</div>
<div class="route-subtitle">Short ridge cut</div>
</div>
<div class="grade-chip" id="directGrade">0% avg grade</div>
</div>
<div class="route-explanation">
Crosses the central divide directly. Less distance, but the steep climb
causes a large modeled speed penalty.
</div>
<div class="metrics">
<div class="metric">
<span>Distance</span>
<strong id="directDistance">—</strong>
</div>
<div class="metric">
<span>Ascent</span>
<strong id="directAscent">—</strong>
</div>
<div class="metric">
<span>Est. time</span>
<strong id="directTime">—</strong>
</div>
</div>
<div class="ride-progress"><i id="directProgress"></i></div>
</button>
<button
class="route-card level"
id="levelCard"
type="button"
aria-label="Focus the longer level route"
>
<div class="route-heading">
<div>
<div class="route-name">Route B / Contour</div>
<div class="route-subtitle">Longer level bypass</div>
</div>
<div class="grade-chip" id="levelGrade">0% avg grade</div>
</div>
<div class="route-explanation">
Follows the southern flank around the divide. Extra distance is offset
by a much lower climb and better sustained speed.
</div>
<div class="metrics">
<div class="metric">
<span>Distance</span>
<strong id="levelDistance">—</strong>
</div>
<div class="metric">
<span>Ascent</span>
<strong id="levelAscent">—</strong>
</div>
<div class="metric">
<span>Est. time</span>
<strong id="levelTime">—</strong>
</div>
</div>
<div class="ride-progress"><i id="levelProgress"></i></div>
</button>
</div>
<div class="model-note">
<strong>IDENTICAL RIDER + BIKE MODEL</strong>
<span>Same 75 kg rider/bike, dry trail, no stops, fatigue, wind, or braking.</span>
<span class="formula">
Flat/downhill: 5.0 m/s · Uphill: max(1.0, 5.0 − 20g) m/s · g = rise/run
</span>
<span>Distance, ascent, and time are calculated separately from 700-point route samples.</span>
</div>
</section>
<div class="help">Drag: orbit · Wheel: zoom · Arrow keys: move · Click a route: focus</div>
<div id="worldLabels"></div>
<div id="webglError">
<div>
<h2>WebGL could not be initialized.</h2>
<p>Try opening this file in a browser with hardware acceleration enabled.</p>
</div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Constants and scene
// -------------------------------------------------------------------------
const METERS_PER_UNIT = 10;
const ROUTE_COLOR_DIRECT = 0xff8438;
const ROUTE_COLOR_LEVEL = 0x32d5c1;
const sceneContainer = document.getElementById("scene");
const worldLabels = document.getElementById("worldLabels");
let renderer;
try {
renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
} catch (error) {
document.getElementById("webglError").style.display = "grid";
throw error;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
sceneContainer.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x9fc7d6);
scene.fog = new THREE.Fog(0x9fc7d6, 115, 235);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
500
);
const hemiLight = new THREE.HemisphereLight(0xd8f3ff, 0x455342, 2.0);
scene.add(hemiLight);
const sun = new THREE.DirectionalLight(0xffedc8, 2.7);
sun.position.set(-48, 85, 32);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -80;
sun.shadow.camera.right = 80;
sun.shadow.camera.top = 80;
sun.shadow.camera.bottom = -80;
sun.shadow.camera.near = 10;
sun.shadow.camera.far = 220;
sun.shadow.normalBias = 0.035;
scene.add(sun);
const ambient = new THREE.AmbientLight(0xffffff, 0.22);
scene.add(ambient);
// -------------------------------------------------------------------------
// Deterministic helpers
// -------------------------------------------------------------------------
let randomSeed = 73491;
function random() {
randomSeed = (randomSeed * 1664525 + 1013904223) >>> 0;
return randomSeed / 4294967296;
}
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
function smoothstep(edge0, edge1, value) {
const t = clamp((value - edge0) / (edge1 - edge0), 0, 1);
return t * t * (3 - 2 * t);
}
function formatDistance(meters) {
if (meters >= 1000) {
return `${(meters / 1000).toFixed(2)} km`;
}
return `${Math.round(meters)} m`;
}
function formatDuration(seconds) {
const rounded = Math.max(0, Math.round(seconds));
const minutes = Math.floor(rounded / 60);
const remainder = rounded % 60;
return `${minutes}m ${String(remainder).padStart(2, "0")}s`;
}
function formatClock(seconds) {
const rounded = Math.max(0, Math.floor(seconds));
const minutes = Math.floor(rounded / 60);
const remainder = rounded % 60;
return `${String(minutes).padStart(2, "0")}:${String(remainder).padStart(2, "0")}`;
}
// -------------------------------------------------------------------------
// Continuous terrain height field
//
// The valley runs broadly along X. A central rocky divide forces a choice:
// cross it directly or contour around its southern end.
// -------------------------------------------------------------------------
function terrainHeight(x, z) {
const valleyFloor = 1.35 + 0.010 * (x + 60);
const outerValleyWall =
9.0 * smoothstep(32, 58, Math.abs(z));
const centralDivide =
30.0 *
Math.exp(
-Math.pow((x + 3) / 16, 2) -
Math.pow((z + 9) / 20, 2)
);
const easternHill =
10.0 *
Math.exp(
-Math.pow((x - 42) / 18, 2) -
Math.pow((z - 27) / 15, 2)
);
const roughness =
(
0.75 * Math.sin(x * 0.22) * Math.cos(z * 0.19) +
0.35 * Math.sin((x - z) * 0.37)
) * clamp(centralDivide / 10, 0, 1);
return valleyFloor + outerValleyWall + centralDivide + easternHill + roughness;
}
// Voxel terrain: one square column per grid cell.
const terrainGeometry = new THREE.BoxGeometry(3.88, 1, 3.88);
const terrainMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 1,
metalness: 0,
flatShading: true,
vertexColors: true
});
const terrain = new THREE.InstancedMesh(
terrainGeometry,
terrainMaterial,
31 * 25
);
const dummy = new THREE.Object3D();
const instanceColor = new THREE.Color();
let terrainIndex = 0;
for (let ix = 0; ix < 31; ix++) {
const x = -60 + ix * 4;
for (let iz = 0; iz < 25; iz++) {
const z = -48 + iz * 4;
const height = terrainHeight(x, z);
dummy.position.set(x, height * 0.5, z);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, height, 1);
dummy.updateMatrix();
terrain.setMatrixAt(terrainIndex, dummy.matrix);
const variation = (random() - 0.5) * 0.055;
if (height < 5.5) {
instanceColor.setHSL(0.285 + variation, 0.36, 0.31 + variation);
} else if (height < 13) {
instanceColor.setHSL(0.235 + variation, 0.29, 0.39 + variation);
} else if (height < 25) {
instanceColor.setHSL(0.095 + variation, 0.12, 0.43 + variation);
} else {
instanceColor.setHSL(0.12, 0.16, 0.76 + variation);
}
terrain.setColorAt(terrainIndex, instanceColor);
terrainIndex++;
}
}
terrain.instanceMatrix.needsUpdate = true;
terrain.instanceColor.needsUpdate = true;
terrain.receiveShadow = true;
terrain.computeBoundingSphere();
scene.add(terrain);
// Dark block beneath the diorama.
const plinth = new THREE.Mesh(
new THREE.BoxGeometry(126, 2.2, 102),
new THREE.MeshStandardMaterial({
color: 0x26373b,
roughness: 1
})
);
plinth.position.y = -1.05;
plinth.receiveShadow = true;
scene.add(plinth);
// -------------------------------------------------------------------------
// Route construction and time model
// -------------------------------------------------------------------------
function createRoute(controlPoints, color) {
const controls = controlPoints.map(
([x, z]) => new THREE.Vector3(x, 0, z)
);
const curve = new THREE.CatmullRomCurve3(
controls,
false,
"catmullrom",
0.30
);
const rawPoints = curve.getPoints(700);
const points = rawPoints.map((point) => {
const x = clamp(point.x, -59.5, 59.5);
const z = clamp(point.z, -47.5, 47.5);
return new THREE.Vector3(x, terrainHeight(x, z) + 1.15, z);
});
const cumulativeDistance = [0];
const cumulativeTime = [0];
const cumulativeHorizontal = [0];
let ascent = 0;
let descent = 0;
for (let i = 0; i < points.length - 1; i++) {
const a = points[i];
const b = points[i + 1];
const dx = b.x - a.x;
const dy = b.y - a.y;
const dz = b.z - a.z;
const sceneDistance = Math.sqrt(
dx * dx + dy * dy + dz * dz
);
const meters = sceneDistance * METERS_PER_UNIT;
const horizontalMeters =
Math.sqrt(dx * dx + dz * dz) * METERS_PER_UNIT;
const riseMeters = dy * METERS_PER_UNIT;
const grade = horizontalMeters > 0
? riseMeters / horizontalMeters
: 0;
// Explicit model:
// flat/downhill = 5 m/s
// uphill = max(1, 5 - 20 * grade) m/s
const modeledSpeed = grade > 0
? Math.max(1.0, 5.0 - 20.0 * grade)
: 5.0;
const segmentTime = meters / modeledSpeed;
cumulativeDistance.push(
cumulativeDistance[i] + sceneDistance
);
cumulativeHorizontal.push(
cumulativeHorizontal[i] + horizontalMeters
);
cumulativeTime.push(
cumulativeTime[i] + segmentTime
);
if (riseMeters > 0) {
ascent += riseMeters;
} else {
descent -= riseMeters;
}
}
const totalDistance =
cumulativeDistance[cumulativeDistance.length - 1] * METERS_PER_UNIT;
const totalHorizontal = cumulativeHorizontal[
cumulativeHorizontal.length - 1
];
return {
points,
color,
cumulativeDistance,
cumulativeTime,
distanceMeters: totalDistance,
horizontalMeters: totalHorizontal,
ascentMeters: ascent,
descentMeters: descent,
averageGrade: ascent / Math.max(1, totalHorizontal),
duration: cumulativeTime[cumulativeTime.length - 1],
focusPoint: points[Math.floor(points.length * 0.46)]
};
}
const directRoute = createRoute(
[
[-48, 9],
[-31, 5],
[-15, 0],
[-3, -8],
[11, -11],
[28, -14],
[39, -16],
[50, -16]
],
ROUTE_COLOR_DIRECT
);
const levelRoute = createRoute(
[
[-48, 9],
[-56, -3],
[-59, -18],
[-54, -31],
[-41, -40],
[-24, -43],
[-7, -40],
[9, -42],
[25, -36],
[39, -27],
[47, -20],
[50, -16]
],
ROUTE_COLOR_LEVEL
);
const routes = [directRoute, levelRoute];
function buildRouteBlocks(route) {
const roadbedGeometry = new THREE.BoxGeometry(1, 1, 1);
const roadbedMaterial = new THREE.MeshStandardMaterial({
color: 0x33443f,
roughness: 1
});
const lineGeometry = new THREE.BoxGeometry(0.56, 0.13, 1);
const lineMaterial = new THREE.MeshStandardMaterial({
color: route.color,
emissive: route.color,
emissiveIntensity: 0.15,
roughness: 0.75
});
const step = 2;
const segmentCount = Math.ceil(route.points.length / step);
const roadbed = new THREE.InstancedMesh(
roadbedGeometry,
roadbedMaterial,
segmentCount
);
const line = new THREE.InstancedMesh(
lineGeometry,
lineMaterial,
segmentCount
);
const midpoint = new THREE.Vector3();
const direction = new THREE.Vector3();
const forward = new THREE.Vector3(0, 0, 1);
let instance = 0;
for (let i = 0; i < route.points.length - 1; i += step) {
const a = route.points[i];
const b = route.points[Math.min(i + step, route.points.length - 1)];
midpoint.copy(a).add(b).multiplyScalar(0.5);
direction.copy(b).sub(a);
const length = direction.length();
if (length < 0.0001) continue;
direction.normalize();
dummy.position.copy(midpoint);
dummy.quaternion.setFromUnitVectors(forward, direction);
dummy.scale.set(1.02, 0.22, length * 1.08);
dummy.updateMatrix();
roadbed.setMatrixAt(instance, dummy.matrix);
dummy.position.copy(midpoint);
dummy.position.y += 0.18;
dummy.quaternion.setFromUnitVectors(forward, direction);
dummy.scale.set(1, 1, length * 1.10);
dummy.updateMatrix();
line.setMatrixAt(instance, dummy.matrix);
instance++;
}
roadbed.count = instance;
line.count = instance;
roadbed.instanceMatrix.needsUpdate = true;
line.instanceMatrix.needsUpdate = true;
roadbed.receiveShadow = true;
line.receiveShadow = true;
roadbed.computeBoundingSphere();
line.computeBoundingSphere();
scene.add(roadbed, line);
}
routes.forEach(buildRouteBlocks);
// -------------------------------------------------------------------------
// Route gates
// -------------------------------------------------------------------------
const unitBox = new THREE.BoxGeometry(1, 1, 1);
function makeGate(route, pointIndex, color) {
const group = new THREE.Group();
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.1,
roughness: 0.8
});
const point = route.points[pointIndex];
for (const side of [-1, 1]) {
const post = new THREE.Mesh(unitBox, material);
post.scale.set(0.38, 3.1, 0.38);
post.position.set(0, 1.55, side * 1.45);
post.castShadow = true;
group.add(post);
}
const crossbar = new THREE.Mesh(unitBox, material);
crossbar.scale.set(0.38, 0.38, 3.25);
crossbar.position.set(0, 3.05, 0);
crossbar.castShadow = true;
group.add(crossbar);
group.position.copy(point);
const previous = route.points[Math.max(0, pointIndex - 5)];
const next = route.points[
Math.min(route.points.length - 1, pointIndex + 5)
];
const tangent = next.clone().sub(previous).normalize();
const heading = Math.atan2(-tangent.z, tangent.x);
const pitch = Math.atan2(
tangent.y,
Math.sqrt(tangent.x * tangent.x + tangent.z * tangent.z)
);
group.rotation.order = "YXZ";
group.rotation.y = heading;
group.rotation.z = pitch;
scene.add(group);
}
makeGate(directRoute, 0, ROUTE_COLOR_DIRECT);
makeGate(directRoute, directRoute.points.length - 1, ROUTE_COLOR_DIRECT);
makeGate(levelRoute, 0, ROUTE_COLOR_LEVEL);
makeGate(levelRoute, levelRoute.points.length - 1, ROUTE_COLOR_LEVEL);
// -------------------------------------------------------------------------
// Voxel village buildings
// -------------------------------------------------------------------------
const wallMaterials = [
new THREE.MeshStandardMaterial({ color: 0xe4d6b6, roughness: 1 }),
new THREE.MeshStandardMaterial({ color: 0xc9b996, roughness: 1 }),
new THREE.MeshStandardMaterial({ color: 0x9eb8b1, roughness: 1 }),
new THREE.MeshStandardMaterial({ color: 0xc7a889, roughness: 1 })
];
const roofMaterial = new THREE.MeshStandardMaterial({
color: 0x985843,
roughness: 1
});
const roofTopMaterial = new THREE.MeshStandardMaterial({
color: 0x70453d,
roughness: 1
});
function makeHouse(x, z, width, depth, height, rotation = 0) {
const group = new THREE.Group();
const wall = new THREE.Mesh(
unitBox,
wallMaterials[Math.floor(random() * wallMaterials.length)]
);
wall.scale.set(width, height, depth);
wall.position.y = height * 0.5;
wall.castShadow = true;
wall.receiveShadow = true;
group.add(wall);
const roof = new THREE.Mesh(unitBox, roofMaterial);
roof.scale.set(width + 0.9, 0.6, depth + 0.9);
roof.position.y = height + 0.3;
roof.castShadow = true;
group.add(roof);
const roofTop = new THREE.Mesh(unitBox, roofTopMaterial);
roofTop.scale.set(width * 0.65, 0.55, depth * 0.65);
roofTop.position.y = height + 0.87;
roofTop.castShadow = true;
group.add(roofTop);
group.position.set(x, terrainHeight(x, z), z);
group.rotation.y = rotation;
scene.add(group);
}
const startHouses = [
[-56, 4, 3.5, 4.0, 3.0, 0.1],
[-54, 14, 4.0, 3.5, 3.4, -0.15],
[-46, 17, 3.4, 4.2, 2.8, 0.2],
[-42, 11, 3.0, 3.4, 3.1, -0.1],
[-57, 19, 4.2, 3.6, 2.7, 0.3],
[-43, 3, 3.8, 3.1, 3.5, 0.05]
];
const finishHouses = [
[55, -18, 3.8, 4.0, 3.2, -0.15],
[56, -10, 4.1, 3.5, 2.9, 0.1],
[48, -25, 3.4, 4.0, 3.4, 0.15],
[58, -25, 3.8, 3.7, 3.0, -0.2],
[45, -22, 3.2, 3.6, 2.7, 0.1]
];
startHouses.forEach((house) => makeHouse(...house));
finishHouses.forEach((house) => makeHouse(...house));
// -------------------------------------------------------------------------
// Instanced voxel trees
// -------------------------------------------------------------------------
function nearRoute(x, z, margin) {
for (const route of routes) {
for (let i = 0; i < route.points.length; i += 7) {
const point = route.points[i];
const dx = point.x - x;
const dz = point.z - z;
if (dx * dx + dz * dz < margin * margin) {
return true;
}
}
}
return false;
}
const treePositions = [];
for (let attempt = 0; attempt < 900 && treePositions.length < 110; attempt++) {
const x = random() * 116 - 58;
const z = random() * 92 - 46;
const height = terrainHeight(x, z);
if (height < 1.8 || height > 15) continue;
if (nearRoute(x, z, 3.8)) continue;
const nearVillage =
Math.hypot(x + 49, z - 9) < 13 ||
Math.hypot(x - 51, z + 17) < 13;
if (nearVillage) continue;
treePositions.push({ x, z, height });
}
const trunkGeometry = new THREE.BoxGeometry(0.45, 1.8, 0.45);
const trunkMaterial = new THREE.MeshStandardMaterial({
color: 0x6a4934,
roughness: 1
});
const foliageGeometry = new THREE.BoxGeometry(2.2, 2.0, 2.2);
const foliageMaterial = new THREE.MeshStandardMaterial({
color: 0x2f7753,
roughness: 1,
flatShading: true
});
const trunkMesh = new THREE.InstancedMesh(
trunkGeometry,
trunkMaterial,
treePositions.length
);
const foliageMesh = new THREE.InstancedMesh(
foliageGeometry,
foliageMaterial,
treePositions.length
);
const topFoliageMesh = new THREE.InstancedMesh(
foliageGeometry,
foliageMaterial,
treePositions.length
);
treePositions.forEach((tree, index) => {
const scale = 0.75 + random() * 0.55;
dummy.position.set(tree.x, tree.height + 0.9 * scale, tree.z);
dummy.rotation.set(0, random() * Math.PI, 0);
dummy.scale.set(scale, scale, scale);
dummy.updateMatrix();
trunkMesh.setMatrixAt(index, dummy.matrix);
dummy.position.set(tree.x, tree.height + 2.45 * scale, tree.z);
dummy.rotation.set(0, random() * Math.PI, 0);
dummy.scale.set(scale, scale, scale);
dummy.updateMatrix();
foliageMesh.setMatrixAt(index, dummy.matrix);
dummy.position.set(tree.x, tree.height + 3.25 * scale, tree.z);
dummy.rotation.set(0, random() * Math.PI, 0);
dummy.scale.set(scale * 0.72, scale * 0.72, scale * 0.72);
dummy.updateMatrix();
topFoliageMesh.setMatrixAt(index, dummy.matrix);
});
trunkMesh.instanceMatrix.needsUpdate = true;
foliageMesh.instanceMatrix.needsUpdate = true;
topFoliageMesh.instanceMatrix.needsUpdate = true;
trunkMesh.castShadow = true;
foliageMesh.castShadow = true;
topFoliageMesh.castShadow = true;
scene.add(trunkMesh, foliageMesh, topFoliageMesh);
// -------------------------------------------------------------------------
// Block clouds
// -------------------------------------------------------------------------
const cloudCount = 54;
const cloudGeometry = new THREE.BoxGeometry(1, 1, 1);
const cloudMaterial = new THREE.MeshStandardMaterial({
color: 0xf2f6ed,
roughness: 1
});
const clouds = new THREE.InstancedMesh(
cloudGeometry,
cloudMaterial,
cloudCount
);
for (let i = 0; i < cloudCount; i++) {
dummy.position.set(
random() * 150 - 75,
37 + random() * 15,
random() * 140 - 70
);
dummy.rotation.set(0, random() * Math.PI, 0);
dummy.scale.set(
2.5 + random() * 4.5,
0.8 + random() * 1.5,
2.0 + random() * 4.0
);
dummy.updateMatrix();
clouds.setMatrixAt(i, dummy.matrix);
}
clouds.instanceMatrix.needsUpdate = true;
scene.add(clouds);
// -------------------------------------------------------------------------
// Identical voxel cyclists
// -------------------------------------------------------------------------
const riderMaterials = {
tire: new THREE.MeshStandardMaterial({
color: 0x1c2428,
roughness: 0.95
}),
frame: new THREE.MeshStandardMaterial({
color: 0xe7b44b,
roughness: 0.75
}),
jersey: new THREE.MeshStandardMaterial({
color: 0xf2eee0,
roughness: 0.9
}),
shorts: new THREE.MeshStandardMaterial({
color: 0x284b60,
roughness: 0.9
}),
skin: new THREE.MeshStandardMaterial({
color: 0xc98f66,
roughness: 1
}),
helmet: new THREE.MeshStandardMaterial({
color: 0x243b4d,
roughness: 0.85
})
};
function createRider() {
const rider = new THREE.Group();
function part(material, size, position, rotation = null) {
const mesh = new THREE.Mesh(unitBox, material);
mesh.scale.set(size[0], size[1], size[2]);
mesh.position.set(position[0], position[1], position[2]);
if (rotation) {
mesh.rotation.set(rotation[0], rotation[1], rotation[2]);
}
mesh.castShadow = true;
rider.add(mesh);
return mesh;
}
// Cube wheels.
part(riderMaterials.tire, [0.48, 0.48, 0.48], [-0.67, 0.40, 0]);
part(riderMaterials.tire, [0.48, 0.48, 0.48], [0.67, 0.40, 0]);
// Block bicycle frame.
part(riderMaterials.frame, [1.35, 0.16, 0.18], [0, 0.72, 0]);
part(riderMaterials.frame, [0.17, 0.90, 0.17], [-0.10, 0.88, 0], [0, 0, -0.34]);
part(riderMaterials.frame, [0.17, 0.90, 0.17], [0.43, 0.86, 0], [0, 0, 0.28]);
// Rider.
part(riderMaterials.shorts, [0.68, 0.38, 0.50], [0.02, 0.98, 0]);
part(riderMaterials.jersey, [0.65, 0.62, 0.54], [0.10, 1.42, 0], [0, 0, -0.12]);
part(riderMaterials.skin, [0.42, 0.42, 0.42], [0.22, 1.92, 0]);
part(riderMaterials.helmet, [0.56, 0.18, 0.54], [0.22, 2.16, 0]);
// Arms and handlebar.
part(riderMaterials.jersey, [0.72, 0.18, 0.18], [0.35, 1.55, 0], [0, 0, -0.16]);
part(riderMaterials.frame, [0.18, 0.18, 0.95], [0.66, 1.46, 0]);
return rider;
}
const directRider = createRider();
const levelRider = createRider();
scene.add(directRider, levelRider);
// -------------------------------------------------------------------------
// Route sampling by modeled time
// -------------------------------------------------------------------------
function sampleRouteAtTime(route, elapsedSeconds) {
const time = ((elapsedSeconds % route.duration) + route.duration) %
route.duration;
let low = 0;
let high = route.cumulativeTime.length - 1;
while (low < high - 1) {
const middle = Math.floor((low + high) * 0.5);
if (route.cumulativeTime[middle] <= time) {
low = middle;
} else {
high = middle;
}
}
const startTime = route.cumulativeTime[low];
const endTime = route.cumulativeTime[low + 1];
const alpha = clamp((time - startTime) / (endTime - startTime), 0, 1);
const point = route.points[low].clone().lerp(
route.points[low + 1],
alpha
);
const tangent = route.points[low + 1].clone().sub(
route.points[low]
).normalize();
return { point, tangent };
}
function placeRider(rider, sample) {
rider.position.copy(sample.point);
const heading = Math.atan2(-sample.tangent.z, sample.tangent.x);
const pitch = Math.atan2(
sample.tangent.y,
Math.sqrt(
sample.tangent.x * sample.tangent.x +
sample.tangent.z * sample.tangent.z
)
);
rider.rotation.order = "YXZ";
rider.rotation.y = heading;
rider.rotation.z = pitch;
}
// -------------------------------------------------------------------------
// DOM labels projected from 3D points
// -------------------------------------------------------------------------
function addWorldLabel(text, className) {
const element = document.createElement("div");
element.className = `world-label ${className}`;
element.textContent = text;
worldLabels.appendChild(element);
return element;
}
const startLabel = addWorldLabel("START", "");
const finishLabel = addWorldLabel("FINISH", "");
const peakIndex = directRoute.points.reduce(
(bestIndex, point, index, points) =>
point.y > points[bestIndex].y ? index : bestIndex,
0
);
const ridgeLabel = addWorldLabel("STEEP CUT", "direct");
const contourLabel = addWorldLabel("LEVEL BYPASS", "level");
const projectedLabels = [
{
element: startLabel,
position: directRoute.points[0].clone().add(new THREE.Vector3(0, 4.2, 0))
},
{
element: finishLabel,
position: directRoute.points.at(-1).clone().add(new THREE.Vector3(0, 4.2, 0))
},
{
element: ridgeLabel,
position: directRoute.points[peakIndex].clone().add(new THREE.Vector3(0, 4.5, 0))
},
{
element: contourLabel,
position: levelRoute.points[Math.floor(levelRoute.points.length * 0.55)]
.clone()
.add(new THREE.Vector3(0, 4.0, 0))
}
];
function updateWorldLabels() {
for (const label of projectedLabels) {
const projected = label.position.clone().project(camera);
const visible = projected.z > -1 && projected.z < 1;
label.element.style.opacity = visible ? "1" : "0";
label.element.style.left =
`${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
label.element.style.top =
`${(-projected.y * 0.5 + 0.5) * window.innerHeight}px`;
}
}
// -------------------------------------------------------------------------
// UI statistics
// -------------------------------------------------------------------------
const ui = {
directDistance: document.getElementById("directDistance"),
directAscent: document.getElementById("directAscent"),
directTime: document.getElementById("directTime"),
directGrade: document.getElementById("directGrade"),
directProgress: document.getElementById("directProgress"),
levelDistance: document.getElementById("levelDistance"),
levelAscent: document.getElementById("levelAscent"),
levelTime: document.getElementById("levelTime"),
levelGrade: document.getElementById("levelGrade"),
levelProgress: document.getElementById("levelProgress"),
pauseButton: document.getElementById("pauseButton"),
playback: document.getElementById("playback"),
speedValue: document.getElementById("speedValue"),
simStatus: document.getElementById("simStatus"),
simClock: document.getElementById("simClock")
};
ui.directDistance.textContent = formatDistance(directRoute.distanceMeters);
ui.directAscent.textContent = `${Math.round(directRoute.ascentMeters)} m`;
ui.directTime.textContent = formatDuration(directRoute.duration);
ui.directGrade.textContent =
`${(directRoute.averageGrade * 100).toFixed(0)}% avg grade`;
ui.levelDistance.textContent = formatDistance(levelRoute.distanceMeters);
ui.levelAscent.textContent = `${Math.round(levelRoute.ascentMeters)} m`;
ui.levelTime.textContent = formatDuration(levelRoute.duration);
ui.levelGrade.textContent =
`${(levelRoute.averageGrade * 100).toFixed(0)}% avg grade`;
// -------------------------------------------------------------------------
// Custom camera controls, implemented without Three.js addons
// -------------------------------------------------------------------------
const orbit = {
target: new THREE.Vector3(0, 7, -4),
desiredTarget: new THREE.Vector3(0, 7, -4),
yaw: 0.72,
pitch: 1.0,
radius: 137,
desiredRadius: 137
};
const defaultTarget = orbit.target.clone();
const defaultRadius = orbit.radius;
function updateCamera() {
orbit.target.lerp(orbit.desiredTarget, 0.12);
orbit.radius += (orbit.desiredRadius - orbit.radius) * 0.12;
const horizontal = Math.sin(orbit.pitch) * orbit.radius;
camera.position.set(
orbit.target.x + horizontal * Math.sin(orbit.yaw),
orbit.target.y + Math.cos(orbit.pitch) * orbit.radius,
orbit.target.z + horizontal * Math.cos(orbit.yaw)
);
camera.lookAt(orbit.target);
}
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
orbit.desiredTarget.copy(orbit.target);
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - lastPointerX;
const deltaY = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
orbit.yaw -= deltaX * 0.006;
orbit.pitch = clamp(orbit.pitch + deltaY * 0.005, 0.38, 1.36);
});
function endDrag(event) {
dragging = false;
if (event.pointerId !== undefined &&
renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.desiredRadius = clamp(
orbit.desiredRadius * Math.exp(event.deltaY * 0.001),
65,
225
);
},
{ passive: false }
);
function resetView() {
orbit.desiredTarget.copy(defaultTarget);
orbit.desiredRadius = defaultRadius;
orbit.yaw = 0.72;
orbit.pitch = 1.0;
document.getElementById("directCard").classList.remove("active");
document.getElementById("levelCard").classList.remove("active");
}
document.getElementById("resetView").addEventListener("click", resetView);
renderer.domElement.addEventListener("dblclick", resetView);
function focusRoute(route, card, radius) {
orbit.desiredTarget.copy(route.focusPoint);
orbit.desiredRadius = radius;
document.getElementById("directCard").classList.remove("active");
document.getElementById("levelCard").classList.remove("active");
card.classList.add("active");
}
document.getElementById("directCard").addEventListener("click", () => {
focusRoute(directRoute, document.getElementById("directCard"), 94);
});
document.getElementById("levelCard").addEventListener("click", () => {
focusRoute(levelRoute, document.getElementById("levelCard"), 116);
});
window.addEventListener("keydown", (event) => {
if (["INPUT", "BUTTON"].includes(document.activeElement?.tagName)) {
return;
}
if (event.key === "ArrowLeft") orbit.yaw += 0.08;
if (event.key === "ArrowRight") orbit.yaw -= 0.08;
if (event.key === "ArrowUp") {
orbit.pitch = clamp(orbit.pitch - 0.06, 0.38, 1.36);
}
if (event.key === "ArrowDown") {
orbit.pitch = clamp(orbit.pitch + 0.06, 0.38, 1.36);
}
if (event.key === "+" || event.key === "=") {
orbit.desiredRadius = clamp(orbit.desiredRadius - 8, 65, 225);
}
if (event.key === "-") {
orbit.desiredRadius = clamp(orbit.desiredRadius + 8, 65, 225);
}
});
// -------------------------------------------------------------------------
// Animation and playback
// -------------------------------------------------------------------------
let running = true;
let playbackRate = Number(ui.playback.value);
let simulationTime = 0;
ui.speedValue.textContent = `${playbackRate}×`;
ui.playback.addEventListener("input", () => {
playbackRate = Number(ui.playback.value);
ui.speedValue.textContent = `${playbackRate}×`;
});
ui.pauseButton.addEventListener("click", () => {
running = !running;
ui.pauseButton.textContent = running ? "Pause" : "Play";
ui.simStatus.innerHTML =
`<strong>${running ? "RUNNING" : "PAUSED"}</strong> · ` +
`identical riders · modeled clock ` +
`<span id="simClock">${formatClock(simulationTime)}</span>`;
});
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (running) {
simulationTime += delta * playbackRate;
}
const directSample = sampleRouteAtTime(
directRoute,
simulationTime
);
const levelSample = sampleRouteAtTime(
levelRoute,
simulationTime
);
placeRider(directRider, directSample);
placeRider(levelRider, levelSample);
const directProgress =
(simulationTime % directRoute.duration) / directRoute.duration;
const levelProgress =
(simulationTime % levelRoute.duration) / levelRoute.duration;
ui.directProgress.style.width = `${directProgress * 100}%`;
ui.levelProgress.style.width = `${levelProgress * 100}%`;
const currentClock = document.getElementById("simClock");
if (currentClock) {
currentClock.textContent = formatClock(simulationTime);
}
updateCamera();
camera.updateMatrixWorld();
updateWorldLabels();
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
animate();
</script>
</body>
</html>
```