Prompt specification
Build or customize the Three.js 3D scene "Compare carrying routes across a hillside craft district" 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: Compare carrying routes across a hillside craft district
Category: Architecture & Cities · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/compare-carrying-routes-across-a-hillside-craft-distri-x2736
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows San Blas in Cusco. Let users move a fictional delivery between two shops using stairs or a longer gentler route. Display distance and elevation changes independently. Low-poly.
Working Three.js Starter (compare-carrying-routes-across-a-hillside-craft-distri-x2736):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#173d3b">
<title>San Blas Delivery — Cusco</title>
<style>
:root {
--ink: #173d3b;
--muted: #61706c;
--paper: #fffaf0;
--paper-strong: #fffdf7;
--orange: #e96f45;
--orange-soft: #f8d4bd;
--teal: #287b75;
--gold: #e4a84c;
--line: rgba(23, 61, 59, 0.12);
--shadow: 0 18px 50px rgba(26, 48, 43, 0.16);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #b9d8d2;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input,
select {
font: inherit;
}
button {
color: inherit;
}
#scene {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene.dragging {
cursor: grabbing;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
linear-gradient(180deg, rgba(255, 250, 240, 0.12), transparent 24%),
radial-gradient(circle at 45% 45%, transparent 55%, rgba(26, 50, 43, 0.08));
}
.glass {
background: rgba(255, 250, 240, 0.92);
border: 1px solid rgba(255, 255, 255, 0.72);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
#intro {
position: fixed;
top: 24px;
left: 24px;
width: min(430px, calc(100vw - 48px));
padding: 21px 23px 20px;
border-radius: 22px;
pointer-events: none;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 9px;
color: var(--teal);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.eyebrow::before {
width: 22px;
height: 2px;
content: "";
border-radius: 999px;
background: var(--orange);
}
h1 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(30px, 4vw, 44px);
font-weight: 500;
line-height: 0.98;
letter-spacing: -0.035em;
}
#intro p {
max-width: 360px;
margin: 12px 0 0;
color: var(--muted);
font-size: 14px;
line-height: 1.55;
}
#planner {
position: fixed;
top: 24px;
right: 24px;
width: 372px;
max-height: calc(100vh - 48px);
padding: 21px;
overflow: auto;
border-radius: 24px;
scrollbar-width: thin;
}
.panel-kicker {
color: var(--orange);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
#planner h2 {
margin: 5px 0 15px;
font-family: Georgia, "Times New Roman", serif;
font-size: 27px;
font-weight: 500;
letter-spacing: -0.025em;
}
.od-card {
display: grid;
grid-template-columns: 28px 1fr;
gap: 0 10px;
margin-bottom: 16px;
padding: 12px 13px;
border: 1px solid var(--line);
border-radius: 15px;
background: rgba(255, 255, 255, 0.47);
}
.od-rail {
position: relative;
grid-row: 1 / 3;
width: 10px;
height: 50px;
margin: 2px auto 0;
}
.od-rail::before,
.od-rail::after {
position: absolute;
left: 50%;
width: 9px;
height: 9px;
content: "";
border-radius: 50%;
transform: translateX(-50%);
}
.od-rail::before {
top: 0;
background: var(--teal);
box-shadow: 0 0 0 4px rgba(40, 123, 117, 0.12);
}
.od-rail::after {
bottom: 0;
background: var(--orange);
box-shadow: 0 0 0 4px rgba(233, 111, 69, 0.12);
}
.od-rail span {
position: absolute;
top: 9px;
bottom: 8px;
left: 50%;
border-left: 2px dashed rgba(23, 61, 59, 0.24);
}
.od-stop small {
display: block;
margin-bottom: 1px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.od-stop strong {
font-size: 13px;
font-weight: 750;
}
.section-label {
display: flex;
align-items: center;
justify-content: space-between;
margin: 15px 0 8px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.section-label span:last-child {
color: rgba(23, 61, 59, 0.45);
font-weight: 650;
letter-spacing: 0;
text-transform: none;
}
.route-list {
display: grid;
gap: 9px;
}
.route-card {
position: relative;
width: 100%;
padding: 13px 13px 12px;
overflow: hidden;
text-align: left;
border: 1px solid var(--line);
border-radius: 15px;
background: rgba(255, 255, 255, 0.52);
cursor: pointer;
transition:
border-color 160ms ease,
background 160ms ease,
transform 160ms ease,
box-shadow 160ms ease;
}
.route-card:hover {
transform: translateY(-1px);
border-color: rgba(40, 123, 117, 0.35);
}
.route-card.active {
border-color: var(--teal);
background: #fffdf8;
box-shadow: 0 7px 20px rgba(40, 123, 117, 0.11);
}
.route-card.active::after {
position: absolute;
top: 12px;
right: 12px;
width: 9px;
height: 9px;
content: "";
border: 3px solid #d7efea;
border-radius: 50%;
background: var(--teal);
box-sizing: content-box;
}
.route-name {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 9px;
font-size: 14px;
font-weight: 800;
}
.route-icon {
display: grid;
width: 29px;
height: 29px;
place-items: center;
border-radius: 9px;
color: white;
font-size: 16px;
}
.route-card[data-route="stairs"] .route-icon {
background: var(--orange);
}
.route-card[data-route="gentle"] .route-icon {
background: var(--gold);
}
.route-metrics {
display: grid;
grid-template-columns: 1fr 1.35fr;
gap: 8px;
}
.route-metrics div {
min-width: 0;
padding-left: 10px;
border-left: 2px solid rgba(23, 61, 59, 0.11);
}
.route-metrics small {
display: block;
margin-bottom: 2px;
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.route-metrics strong {
display: block;
overflow: hidden;
font-size: 11px;
font-weight: 750;
text-overflow: ellipsis;
white-space: nowrap;
}
.summary-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 6px;
margin-top: 12px;
}
.summary-stat {
min-width: 0;
padding: 10px 7px;
text-align: center;
border-radius: 12px;
background: rgba(23, 61, 59, 0.055);
}
.summary-stat small {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.summary-stat strong {
font-size: 13px;
font-weight: 800;
white-space: nowrap;
}
.progress-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 15px;
font-size: 10px;
font-weight: 750;
}
#status {
color: var(--teal);
}
#progressValue {
color: var(--muted);
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 11px 0 14px;
border-radius: 999px;
outline: none;
appearance: none;
background:
linear-gradient(
to right,
var(--teal) 0 var(--progress, 0%),
rgba(23, 61, 59, 0.13) var(--progress, 0%) 100%
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 17px;
height: 17px;
border: 3px solid white;
border-radius: 50%;
appearance: none;
background: var(--teal);
box-shadow: 0 2px 8px rgba(23, 61, 59, 0.28);
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border: 3px solid white;
border-radius: 50%;
background: var(--teal);
box-shadow: 0 2px 8px rgba(23, 61, 59, 0.28);
}
.action-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
}
.primary-button,
.secondary-button,
.icon-button {
border: 0;
cursor: pointer;
transition:
transform 140ms ease,
background 140ms ease,
box-shadow 140ms ease;
}
.primary-button:hover,
.secondary-button:hover,
.icon-button:hover {
transform: translateY(-1px);
}
.primary-button {
padding: 12px 15px;
border-radius: 12px;
color: white;
background: var(--teal);
box-shadow: 0 8px 18px rgba(40, 123, 117, 0.2);
font-size: 12px;
font-weight: 800;
}
.secondary-button {
padding: 0 13px;
border-radius: 12px;
background: rgba(23, 61, 59, 0.08);
font-size: 12px;
font-weight: 800;
}
.speed-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 11px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
}
select {
padding: 5px 9px;
color: var(--ink);
border: 1px solid var(--line);
border-radius: 8px;
outline: none;
background: white;
font-size: 10px;
font-weight: 800;
}
#cameraTools {
position: fixed;
right: 420px;
bottom: 24px;
display: flex;
gap: 7px;
}
.icon-button {
display: grid;
width: 38px;
height: 38px;
place-items: center;
border-radius: 12px;
color: var(--ink);
background: rgba(255, 250, 240, 0.9);
box-shadow: 0 8px 22px rgba(26, 48, 43, 0.12);
font-size: 17px;
font-weight: 800;
}
#hint {
position: fixed;
bottom: 25px;
left: 24px;
display: flex;
align-items: center;
gap: 9px;
padding: 9px 13px;
border-radius: 999px;
color: rgba(23, 61, 59, 0.78);
background: rgba(255, 250, 240, 0.78);
box-shadow: 0 8px 22px rgba(26, 48, 43, 0.08);
font-size: 10px;
font-weight: 700;
pointer-events: none;
}
#hint b {
color: var(--orange);
font-size: 14px;
}
#labels {
position: fixed;
inset: 0;
overflow: hidden;
pointer-events: none;
}
.map-label {
position: absolute;
padding: 6px 9px;
border: 1px solid rgba(255, 255, 255, 0.7);
border-radius: 999px;
color: var(--ink);
background: rgba(255, 250, 240, 0.88);
box-shadow: 0 5px 14px rgba(24, 48, 43, 0.12);
font-size: 10px;
font-weight: 800;
white-space: nowrap;
transform: translate(-50%, -50%);
transition: opacity 120ms ease;
}
.map-label::before {
display: inline-block;
width: 6px;
height: 6px;
margin-right: 6px;
content: "";
border-radius: 50%;
background: var(--teal);
vertical-align: 1px;
}
.map-label.shop::before {
background: var(--orange);
}
.map-label.route {
color: white;
border-color: transparent;
background: rgba(23, 61, 59, 0.86);
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#loading {
position: fixed;
z-index: 20;
inset: 0;
display: grid;
place-items: center;
background: #b9d8d2;
transition: opacity 400ms ease;
}
#loading.hidden {
opacity: 0;
pointer-events: none;
}
.loader {
text-align: center;
}
.loader-mark {
width: 43px;
height: 43px;
margin: 0 auto 15px;
border: 4px solid rgba(255, 250, 240, 0.45);
border-top-color: var(--orange);
border-radius: 50%;
animation: spin 0.85s linear infinite;
}
.loader strong {
font-family: Georgia, "Times New Roman", serif;
font-size: 22px;
font-weight: 500;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
@media (max-width: 820px) {
#intro {
top: 12px;
left: 12px;
width: calc(100vw - 24px);
padding: 15px 17px;
border-radius: 18px;
}
#intro p {
display: none;
}
#intro h1 {
font-size: 29px;
}
#planner {
top: auto;
right: 12px;
bottom: 12px;
width: calc(100vw - 24px);
max-height: 45vh;
padding: 16px;
border-radius: 19px;
}
#planner h2 {
margin-bottom: 11px;
font-size: 22px;
}
.od-card {
margin-bottom: 12px;
}
#cameraTools {
top: 112px;
right: 12px;
bottom: auto;
}
#hint {
display: none;
}
.route-list {
grid-template-columns: 1fr 1fr;
}
.route-card {
padding: 10px;
}
.route-metrics {
grid-template-columns: 1fr;
}
.route-metrics div:last-child {
display: none;
}
}
@media (max-height: 720px) and (min-width: 821px) {
#planner {
padding: 16px;
}
#planner h2 {
margin-bottom: 10px;
}
.od-card {
margin-bottom: 10px;
}
.route-card {
padding-block: 10px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive low-poly map of San Blas, Cusco"></canvas>
<div class="vignette"></div>
<header id="intro" class="glass">
<div class="eyebrow">San Blas · Cusco</div>
<h1>A delivery uphill</h1>
<p>
Move a fictional parcel from Wasi Panadería to Koriq Café.
Compare the short stairway with the longer, gentler neighborhood loop.
</p>
</header>
<aside id="planner" class="glass" aria-label="Delivery route planner">
<div class="panel-kicker">Delivery planner</div>
<h2>Two ways uphill</h2>
<div class="od-card">
<div class="od-rail"><span></span></div>
<div class="od-stop">
<small>Pick up</small>
<strong>Wasi Panadería</strong>
</div>
<div class="od-stop">
<small>Deliver to</small>
<strong>Koriq Café</strong>
</div>
</div>
<div class="section-label">
<span>Choose a route</span>
<span>Click the map too</span>
</div>
<div class="route-list">
<button
class="route-card"
data-route="stairs"
type="button"
aria-pressed="true"
>
<div class="route-name">
<span class="route-icon">⌁</span>
<span>Stairway</span>
</div>
<div class="route-metrics">
<div>
<small>Distance</small>
<strong data-distance>—</strong>
</div>
<div>
<small>Elevation</small>
<strong data-elevation>—</strong>
</div>
</div>
</button>
<button
class="route-card"
data-route="gentle"
type="button"
aria-pressed="false"
>
<div class="route-name">
<span class="route-icon">↝</span>
<span>Gentle loop</span>
</div>
<div class="route-metrics">
<div>
<small>Distance</small>
<strong data-distance>—</strong>
</div>
<div>
<small>Elevation</small>
<strong data-elevation>—</strong>
</div>
</div>
</button>
</div>
<div class="summary-grid" aria-label="Selected route statistics">
<div class="summary-stat">
<small>Distance</small>
<strong id="statDistance">—</strong>
</div>
<div class="summary-stat">
<small>Ascent</small>
<strong id="statAscent">—</strong>
</div>
<div class="summary-stat">
<small>Descent</small>
<strong id="statDescent">—</strong>
</div>
<div class="summary-stat">
<small>Max grade</small>
<strong id="statGrade">—</strong>
</div>
</div>
<div class="progress-row">
<span id="status" aria-live="polite">Parcel waiting at pickup</span>
<span id="progressValue">0%</span>
</div>
<input
id="progress"
type="range"
min="0"
max="100"
value="0"
step="0.1"
aria-label="Delivery progress"
>
<div class="action-row">
<button id="playButton" class="primary-button" type="button">
Start delivery
</button>
<button id="resetButton" class="secondary-button" type="button">
Reset
</button>
</div>
<div class="speed-row">
<span>Animation speed</span>
<select id="speed" aria-label="Animation speed">
<option value="0.75">0.75×</option>
<option value="1" selected>1×</option>
<option value="1.5">1.5×</option>
<option value="2">2×</option>
</select>
</div>
</aside>
<div id="cameraTools" aria-label="Camera controls">
<button class="icon-button" data-camera="in" type="button" aria-label="Zoom in">+</button>
<button class="icon-button" data-camera="out" type="button" aria-label="Zoom out">−</button>
<button class="icon-button" data-camera="home" type="button" aria-label="Reset camera">⌂</button>
</div>
<div id="hint">
<b>↕</b>
Drag to orbit · Shift-drag to pan · Scroll to zoom
</div>
<div id="labels">
<div class="map-label shop" id="labelStart">Wasi Panadería</div>
<div class="map-label shop" id="labelEnd">Koriq Café</div>
<div class="map-label" id="labelChurch">San Blas Church</div>
<div class="map-label route" id="labelRoute">Stairway</div>
</div>
<div id="loading">
<div class="loader">
<div class="loader-mark"></div>
<strong>Building San Blas…</strong>
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Basic setup
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
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;
const scene = new THREE.Scene();
scene.background = new THREE.Color("#b9d8d2");
scene.fog = new THREE.Fog("#b9d8d2", 175, 330);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
500
);
const hemi = new THREE.HemisphereLight("#fff9df", "#4e7566", 2.25);
scene.add(hemi);
const sun = new THREE.DirectionalLight("#fff0c5", 3.1);
sun.position.set(75, 115, 65);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -135;
sun.shadow.camera.right = 135;
sun.shadow.camera.top = 135;
sun.shadow.camera.bottom = -135;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 300;
sun.shadow.bias = -0.00025;
scene.add(sun);
const clamp = THREE.MathUtils.clamp;
const lerp = THREE.MathUtils.lerp;
const METERS_PER_UNIT = 1.55;
let randomSeed = 74193;
function random() {
randomSeed = (randomSeed * 16807) % 2147483647;
return (randomSeed - 1) / 2147483646;
}
function terrainHeight(x, z) {
const slope = clamp((48 - z) / 100, 0, 1);
return 2 + 31 * slope + Math.sin(x * 0.075) * 0.35;
}
function pointAtXZ(x, z, lift = 0.42) {
return new THREE.Vector3(x, terrainHeight(x, z) + lift, z);
}
// -------------------------------------------------------------------------
// Terrain and base
// -------------------------------------------------------------------------
const terrainGeometry = new THREE.PlaneGeometry(240, 220, 38, 34);
terrainGeometry.rotateX(-Math.PI / 2);
const terrainPositions = terrainGeometry.attributes.position;
for (let i = 0; i < terrainPositions.count; i++) {
const x = terrainPositions.getX(i);
const z = terrainPositions.getZ(i);
terrainPositions.setY(i, terrainHeight(x, z));
}
const flatTerrain = terrainGeometry.toNonIndexed();
flatTerrain.computeVertexNormals();
const terrainColors = [];
const color = new THREE.Color();
const lowColor = new THREE.Color("#a8b979");
const highColor = new THREE.Color("#d3c58f");
for (let i = 0; i < flatTerrain.attributes.position.count; i += 3) {
const cx =
(flatTerrain.attributes.position.getX(i) +
flatTerrain.attributes.position.getX(i + 1) +
flatTerrain.attributes.position.getX(i + 2)) /
3;
const cz =
(flatTerrain.attributes.position.getZ(i) +
flatTerrain.attributes.position.getZ(i + 1) +
flatTerrain.attributes.position.getZ(i + 2)) /
3;
const t = clamp((terrainHeight(cx, cz) - 2) / 31, 0, 1);
for (let j = 0; j < 3; j++) {
color.copy(lowColor).lerp(highColor, t);
const variation = 0.92 + random() * 0.13;
color.multiplyScalar(variation);
terrainColors.push(color.r, color.g, color.b);
}
}
flatTerrain.setAttribute(
"color",
new THREE.Float32BufferAttribute(terrainColors, 3)
);
const terrain = new THREE.Mesh(
flatTerrain,
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 1,
flatShading: true
})
);
terrain.receiveShadow = true;
scene.add(terrain);
const base = new THREE.Mesh(
new THREE.BoxGeometry(240, 8, 220),
new THREE.MeshStandardMaterial({
color: "#77715d",
roughness: 1,
flatShading: true
})
);
base.position.y = -2;
base.receiveShadow = true;
scene.add(base);
// -------------------------------------------------------------------------
// Reusable geometry helpers
// -------------------------------------------------------------------------
function makeMaterial(colorValue, extra = {}) {
return new THREE.MeshStandardMaterial({
color: colorValue,
roughness: 0.86,
flatShading: true,
...extra
});
}
function addBox(parent, width, height, depth, x, y, z, material, cast = true) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = cast;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function pitchedRoof(width, depth, height, material) {
const w = width / 2;
const d = depth / 2;
const positions = new Float32Array([
-w, 0, -d,
0, height, -d,
w, 0, -d,
-w, 0, d,
0, height, d,
w, 0, d
]);
const indices = [
0, 1, 2,
3, 5, 4,
0, 3, 4,
0, 4, 1,
2, 1, 5,
2, 5, 3
];
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.BufferAttribute(positions, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
const mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
const wallPalette = [
"#c77950",
"#e5b66e",
"#d8c994",
"#9aaf91",
"#b85f52",
"#e0d4b2",
"#789b91",
"#ca8d68"
];
const roofPalette = ["#8f4f3e", "#a86145", "#536b5f", "#7e594a"];
const windowMaterial = makeMaterial("#294d4b", { roughness: 0.45 });
const trimMaterial = makeMaterial("#f2dfb8");
const woodMaterial = makeMaterial("#68483b");
function makeBuilding(
x,
z,
width,
depth,
height,
wallColor,
roofColor,
options = {}
) {
const group = new THREE.Group();
const ground = terrainHeight(x, z);
const wall = makeMaterial(wallColor);
const roofMat = makeMaterial(roofColor);
const foundation = makeMaterial("#85795f");
addBox(
group,
width + 1.3,
1.25,
depth + 1.3,
0,
ground - 0.2,
0,
foundation
);
addBox(
group,
width,
height,
depth,
0,
ground + 0.35 + height / 2,
0,
wall
);
const roofY = ground + height + 0.42;
if (options.pitched) {
const roof = pitchedRoof(width + 1.4, depth + 1.2, 3.2, roofMat);
roof.position.y = roofY;
group.add(roof);
} else {
addBox(
group,
width + 0.9,
0.65,
depth + 0.9,
0,
roofY,
0,
roofMat
);
addBox(
group,
width + 1.3,
0.8,
depth + 1.3,
0,
roofY + 0.55,
0,
wall
);
}
// Front door and simple windows.
addBox(
group,
1.7,
2.7,
0.22,
0,
ground + 1.7,
depth / 2 + 0.13,
woodMaterial
);
const windowCount = Math.max(1, Math.floor(width / 3.6));
for (let i = 0; i < windowCount; i++) {
const wx =
-width / 2 + ((i + 1) * width) / (windowCount + 1);
addBox(
group,
1.25,
1.35,
0.18,
wx,
ground + height * 0.62,
depth / 2 + 0.13,
windowMaterial
);
addBox(
group,
1.55,
0.18,
0.25,
wx,
ground + height * 0.62 + 0.75,
depth / 2 + 0.18,
trimMaterial,
false
);
}
if (options.awning) {
const awning = addBox(
group,
width * 0.8,
0.22,
2.1,
0,
ground + 3.55,
depth / 2 + 0.9,
roofMat
);
awning.rotation.x = 0.08;
const stripeCount = 6;
for (let i = 0; i < stripeCount; i++) {
const stripe = addBox(
group,
width * 0.8 / stripeCount - 0.04,
0.07,
2.05,
-width * 0.4 + ((i + 0.5) * width * 0.8) / stripeCount,
ground + 3.69,
depth / 2 + 0.9,
i % 2 ? trimMaterial : roofMat,
false
);
stripe.rotation.x = 0.08;
}
}
if (options.balcony) {
addBox(
group,
width * 0.55,
0.18,
1.1,
width * 0.15,
ground + height * 0.62,
depth / 2 + 0.52,
trimMaterial
);
for (let i = 0; i < 5; i++) {
addBox(
group,
0.09,
0.8,
0.09,
width * 0.15 - width * 0.25 + i * width * 0.125,
ground + height * 0.62 + 0.45,
depth / 2 + 1.02,
woodMaterial,
false
);
}
}
group.position.set(x, 0, z);
scene.add(group);
return group;
}
// Buildings intentionally sit around the two paths.
const buildingSites = [
[-82, 61, 12, 10, 9],
[-61, 65, 10, 9, 8],
[-35, 61, 13, 10, 11],
[-13, 64, 11, 9, 8],
[11, 62, 13, 10, 10],
[34, 61, 11, 10, 9],
[57, 57, 13, 11, 10],
[77, 43, 11, 12, 12],
[-91, 27, 11, 12, 9],
[-83, 10, 13, 11, 11],
[-87, -10, 12, 10, 10],
[-72, -25, 11, 12, 9],
[-73, -44, 13, 11, 11],
[-57, -53, 12, 10, 9],
[-39, -62, 12, 10, 10],
[-19, -68, 10, 9, 9],
[11, -72, 12, 10, 10],
[34, -73, 12, 10, 9],
[57, -66, 13, 11, 11],
[77, -48, 12, 12, 13],
[83, -25, 10, 12, 11],
[73, -5, 12, 10, 9],
[64, 16, 13, 11, 11],
[54, 34, 11, 11, 10],
[34, 38, 13, 10, 10],
[12, 40, 11, 9, 8],
[-10, 37, 12, 10, 9],
[-33, 34, 11, 9, 8],
[-89, 48, 10, 10, 8]
];
buildingSites.forEach((site, index) => {
makeBuilding(
site[0],
site[1],
site[2],
site[3],
site[4],
wallPalette[index % wallPalette.length],
roofPalette[index % roofPalette.length],
{
pitched: index % 4 === 0,
balcony: index % 5 === 0
}
);
});
// A small central plaza.
const plaza = new THREE.Mesh(
new THREE.CircleGeometry(10, 12),
makeMaterial("#b9aa85")
);
plaza.rotation.x = -Math.PI / 2;
plaza.position.set(-2, terrainHeight(-2, 25) + 0.1, 25);
plaza.receiveShadow = true;
scene.add(plaza);
// -------------------------------------------------------------------------
// Shops
// -------------------------------------------------------------------------
const startShop = makeBuilding(
-56,
50,
15,
11,
8.5,
"#c86548",
"#684b3c",
{ awning: true }
);
const endShop = makeBuilding(
49,
-51,
16,
12,
9.5,
"#e2b658",
"#7b493a",
{ awning: true, balcony: true }
);
addBox(
startShop,
7.2,
1.1,
0.25,
0,
6.2,
5.65,
makeMaterial("#f4dfae")
);
addBox(
endShop,
7.5,
1.1,
0.25,
0,
7.2,
6.15,
makeMaterial("#f4dfae")
);
// Church landmark.
const church = new THREE.Group();
const churchGround = terrainHeight(0, -69);
const churchWall = makeMaterial("#e7d8b4");
const churchRoof = makeMaterial("#98513f");
const churchStone = makeMaterial("#9a8b70");
addBox(church, 20, 15, 22, 0, churchGround + 7.5, 0, churchWall);
addBox(church, 8, 24, 8, -5, churchGround + 12, -4, churchWall);
addBox(church, 9, 1.5, 9, -5, churchGround + 24.5, -4, churchStone);
const churchRoofMesh = pitchedRoof(21, 23, 5, churchRoof);
churchRoofMesh.position.y = churchGround + 15;
church.add(churchRoofMesh);
const towerRoof = pitchedRoof(9.5, 9.5, 4.5, churchRoof);
towerRoof.position.set(-5, churchGround + 25.2, -4);
church.add(towerRoof);
addBox(church, 3.1, 6.5, 0.3, 0, churchGround + 3.3, 11.1, woodMaterial);
addBox(church, 1.5, 2.1, 0.25, 0, churchGround + 12, 11.15, windowMaterial);
for (const x of [-7, 7]) {
addBox(church, 1.7, 3.2, 0.25, x, churchGround + 8.5, 11.15, windowMaterial);
}
church.position.z = -69;
scene.add(church);
// -------------------------------------------------------------------------
// Trees, lamps, rocks, mountains and clouds
// -------------------------------------------------------------------------
const trunkMaterial = makeMaterial("#75513b");
const leafMaterials = [
makeMaterial("#527c5a"),
makeMaterial("#6d8f58"),
makeMaterial("#819657")
];
function makeTree(x, z, size = 1) {
const group = new THREE.Group();
const ground = terrainHeight(x, z);
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.22 * size, 0.32 * size, 2.6 * size, 5),
trunkMaterial
);
trunk.position.y = ground + 1.3 * size;
trunk.castShadow = true;
group.add(trunk);
const crown = new THREE.Mesh(
new THREE.IcosahedronGeometry(1.65 * size, 0),
leafMaterials[Math.floor(random() * leafMaterials.length)]
);
crown.position.y = ground + 3.4 * size;
crown.scale.set(0.9, 1.15, 0.9);
crown.rotation.y = random() * Math.PI;
crown.castShadow = true;
group.add(crown);
group.position.set(x, 0, z);
scene.add(group);
}
const treeSites = [
[-95, 54], [-93, 4], [-88, -35], [-66, -67], [-47, -69],
[-25, -77], [3, -82], [26, -82], [47, -78], [69, -59],
[90, -37], [88, -11], [87, 19], [86, 51], [69, 66],
[44, 70], [18, 70], [-3, 69], [-27, 68], [-48, 69],
[-98, 34], [-97, -14], [94, 5], [77, 31], [49, 47],
[-22, 25], [8, 31], [22, 48], [-41, 48], [-57, 34]
];
treeSites.forEach(([x, z]) => makeTree(x, z, 0.85 + random() * 0.55));
function makeLamp(x, z) {
const group = new THREE.Group();
const ground = terrainHeight(x, z);
const pole = new THREE.Mesh(
new THREE.CylinderGeometry(0.09, 0.12, 3.8, 5),
makeMaterial("#44534d")
);
pole.position.y = ground + 1.9;
pole.castShadow = true;
group.add(pole);
const bulb = new THREE.Mesh(
new THREE.OctahedronGeometry(0.42, 0),
new THREE.MeshStandardMaterial({
color: "#ffd47a",
emissive: "#f2a63f",
emissiveIntensity: 0.7,
flatShading: true
})
);
bulb.position.y = ground + 3.95;
group.add(bulb);
group.position.set(x, 0, z);
scene.add(group);
}
const lampSites = [
[-51, 39], [-66, 23], [-62, 1], [-45, -7], [-29, -20],
[-14, -34], [1, -48], [17, -62], [33, -65], [40, -51],
[-35, 29], [-18, 24], [1, 29], [18, 38], [37, 50]
];
lampSites.forEach(([x, z]) => makeLamp(x, z));
const rockMaterial = makeMaterial("#8f8970");
for (let i = 0; i < 32; i++) {
const x = -108 + random() * 216;
const z = -102 + random() * 204;
const rock = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.5 + random() * 1.15, 0),
rockMaterial
);
rock.position.set(x, terrainHeight(x, z) + 0.3, z);
rock.rotation.set(random(), random(), random());
rock.scale.y = 0.65 + random() * 0.45;
rock.castShadow = true;
scene.add(rock);
}
const mountainMaterial = makeMaterial("#77968b");
const mountainBackMaterial = makeMaterial("#90aaa0");
const mountainSites = [
[-91, -112, 42, 52],
[-43, -124, 49, 68],
[13, -124, 54, 62],
[67, -116, 46, 56],
[108, -101, 36, 46]
];
mountainSites.forEach(([x, z, radius, height], index) => {
const mountain = new THREE.Mesh(
new THREE.ConeGeometry(radius, height, index % 2 ? 5 : 6),
index % 2 ? mountainMaterial : mountainBackMaterial
);
mountain.position.set(x, height / 2 - 1, z);
mountain.rotation.y = random() * Math.PI;
mountain.receiveShadow = true;
scene.add(mountain);
});
const cloudMaterial = new THREE.MeshStandardMaterial({
color: "#f7f1dc",
roughness: 1,
flatShading: true
});
function makeCloud(x, y, z, scale = 1) {
const group = new THREE.Group();
for (let i = 0; i < 4; i++) {
const puff = new THREE.Mesh(
new THREE.IcosahedronGeometry(2.6 + random() * 1.7, 0),
cloudMaterial
);
puff.position.set((i - 1.5) * 3.3, random() * 1.5, random() * 1.4);
puff.scale.y = 0.65;
group.add(puff);
}
group.position.set(x, y, z);
group.scale.setScalar(scale);
scene.add(group);
}
makeCloud(-65, 58, -74, 1.4);
makeCloud(40, 64, -98, 1.1);
makeCloud(95, 52, -42, 0.85);
// -------------------------------------------------------------------------
// Route definitions and statistics
// -------------------------------------------------------------------------
const stairsRaw = [
[-47, 44],
[-31, 36],
[-31, 27],
[-18, 27],
[-18, 16],
[-5, 16],
[-5, 5],
[7, 5],
[7, -6],
[19, -6],
[19, -18],
[31, -18],
[31, -30],
[41, -43]
].map(([x, z]) => pointAtXZ(x, z));
const gentleRaw = [
[-47, 44],
[-60, 42],
[-70, 30],
[-65, 16],
[-53, 5],
[-37, 0],
[-28, -13],
[-18, -27],
[-5, -41],
[10, -54],
[27, -59],
[37, -55],
[41, -43]
].map(([x, z]) => pointAtXZ(x, z));
const gentleCurve = new THREE.CatmullRomCurve3(
gentleRaw,
false,
"centripetal",
0.18
);
const gentlePoints = gentleCurve.getPoints(110);
function makePolyline(points) {
const cumulative = [0];
for (let i = 1; i < points.length; i++) {
cumulative.push(
cumulative[i - 1] + points[i].distanceTo(points[i - 1])
);
}
const total = cumulative[cumulative.length - 1];
function getPoint(t) {
const target = clamp(t, 0, 1) * total;
let low = 0;
let high = cumulative.length - 1;
while (low < high - 1) {
const mid = (low + high) >> 1;
if (cumulative[mid] <= target) low = mid;
else high = mid;
}
const segmentLength = cumulative[high] - cumulative[low] || 1;
const local = (target - cumulative[low]) / segmentLength;
const position = points[low].clone().lerp(points[high], local);
const tangent = points[high].clone().sub(points[low]).normalize();
return { position, tangent };
}
return { points, cumulative, total, getPoint };
}
function calculateStats(points) {
let distance = 0;
let ascent = 0;
let descent = 0;
let maxGrade = 0;
for (let i = 1; i < points.length; i++) {
const a = points[i - 1];
const b = points[i];
const horizontal = Math.hypot(b.x - a.x, b.z - a.z);
const vertical = b.y - a.y;
distance += horizontal * METERS_PER_UNIT;
if (vertical >= 0) ascent += vertical;
else descent -= vertical;
if (horizontal > 0.01) {
maxGrade = Math.max(
maxGrade,
Math.abs(vertical) / horizontal
);
}
}
return {
distance: Math.round(distance),
ascent: Math.round(ascent),
descent: Math.round(descent),
net: Math.round(points.at(-1).y - points[0].y),
grade: Math.round(maxGrade * 100)
};
}
const routes = {
stairs: {
name: "Stairway",
points: stairsRaw,
path: makePolyline(stairsRaw),
stats: calculateStats(stairsRaw),
duration: 12
},
gentle: {
name: "Gentle loop",
points: gentlePoints,
path: makePolyline(gentlePoints),
stats: calculateStats(gentlePoints),
duration: 18
}
};
// -------------------------------------------------------------------------
// Route geometry
// -------------------------------------------------------------------------
const routeHitMeshes = [];
const routeMeshes = {};
function makeRibbon(points, width, material, yOffset = 0) {
const positions = [];
const indices = [];
const left = new THREE.Vector3();
const right = new THREE.Vector3();
for (let i = 0; i < points.length; i++) {
const previous = points[Math.max(0, i - 1)];
const next = points[Math.min(points.length - 1, i + 1)];
const tangent = next.clone().sub(previous);
tangent.y = 0;
tangent.normalize();
const normal = new THREE.Vector3(-tangent.z, 0, tangent.x);
left.copy(points[i]).addScaledVector(normal, width / 2);
right.copy(points[i]).addScaledVector(normal, -width / 2);
left.y += yOffset;
right.y += yOffset;
positions.push(left.x, left.y, left.z);
positions.push(right.x, right.y, right.z);
if (i < points.length - 1) {
const a = i * 2;
indices.push(a, a + 2, a + 1, a + 2, a + 3, a + 1);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
const mesh = new THREE.Mesh(geometry, material);
mesh.receiveShadow = true;
scene.add(mesh);
return mesh;
}
// Gentle road: a muted road underneath and a bright selectable surface.
const gentleRoadBaseMaterial = makeMaterial("#9f8e71");
const gentleRoadMaterial = makeMaterial("#e4a84c", {
emissive: "#9d5d20",
emissiveIntensity: 0.1
});
const gentleBase = makeRibbon(
gentlePoints,
5.2,
gentleRoadBaseMaterial,
-0.08
);
const gentleRoad = makeRibbon(
gentlePoints,
3.8,
gentleRoadMaterial,
0
);
gentleRoad.userData.route = "gentle";
routeHitMeshes.push(gentleRoad);
const gentleHitMaterial = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false
});
const gentleHit = new THREE.Mesh(
new THREE.TubeGeometry(gentleCurve, 150, 2.1, 4, false),
gentleHitMaterial
);
gentleHit.userData.route = "gentle";
scene.add(gentleHit);
routeHitMeshes.push(gentleHit);
// Stairway: individual stone steps.
const stairStepMaterial = makeMaterial("#e96f45", {
emissive: "#8d321d",
emissiveIntensity: 0.12
});
const stairLineMaterial = makeMaterial("#ffd28a", {
emissive: "#e96f45",
emissiveIntensity: 0.25
});
const stairsGroup = new THREE.Group();
scene.add(stairsGroup);
for (let i = 1; i < stairsRaw.length; i++) {
const a = stairsRaw[i - 1];
const b = stairsRaw[i];
const dx = b.x - a.x;
const dz = b.z - a.z;
const horizontalLength = Math.hypot(dx, dz);
const stepCount = Math.max(2, Math.ceil(horizontalLength / 1.65));
const angle = Math.atan2(dx, dz);
for (let step = 0; step < stepCount; step++) {
const t = (step + 0.5) / stepCount;
const stepMesh = new THREE.Mesh(
new THREE.BoxGeometry(
2.9,
0.34,
(horizontalLength / stepCount) * 1.08
),
stairStepMaterial
);
stepMesh.position.set(
lerp(a.x, b.x, t),
lerp(a.y, b.y, t) + 0.06,
lerp(a.z, b.z, t)
);
stepMesh.rotation.y = angle;
stepMesh.castShadow = true;
stepMesh.receiveShadow = true;
stairsGroup.add(stepMesh);
}
}
const stairCurve = new THREE.CurvePath();
for (let i = 1; i < stairsRaw.length; i++) {
stairCurve.add(new THREE.LineCurve3(stairsRaw[i - 1], stairsRaw[i]));
}
const stairLine = new THREE.Mesh(
new THREE.TubeGeometry(stairCurve, 180, 0.17, 5, false),
stairLineMaterial
);
scene.add(stairLine);
const stairHit = new THREE.Mesh(
new THREE.TubeGeometry(stairCurve, 180, 2, 4, false),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false
})
);
stairHit.userData.route = "stairs";
scene.add(stairHit);
routeHitMeshes.push(stairHit);
routeMeshes.stairs = {
stepMaterial: stairStepMaterial,
lineMaterial: stairLineMaterial
};
routeMeshes.gentle = {
roadMaterial: gentleRoadMaterial,
baseMaterial: gentleRoadBaseMaterial
};
// -------------------------------------------------------------------------
// Courier and parcel
// -------------------------------------------------------------------------
const courier = new THREE.Group();
courier.scale.setScalar(2.1);
const courierBody = new THREE.Mesh(
new THREE.BoxGeometry(0.85, 1.05, 0.55),
makeMaterial("#247b75", { emissive: "#123e3b", emissiveIntensity: 0.12 })
);
courierBody.position.y = 1.08;
courierBody.castShadow = true;
courier.add(courierBody);
const courierHead = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.34, 1),
makeMaterial("#b97551")
);
courierHead.position.y = 1.91;
courierHead.castShadow = true;
courier.add(courierHead);
const hat = new THREE.Mesh(
new THREE.CylinderGeometry(0.3, 0.38, 0.18, 8),
makeMaterial("#f0c858")
);
hat.position.y = 2.18;
hat.castShadow = true;
courier.add(hat);
const brim = new THREE.Mesh(
new THREE.CylinderGeometry(0.43, 0.43, 0.07, 8),
makeMaterial("#e6b748")
);
brim.position.y = 2.09;
courier.add(brim);
const legMaterial = makeMaterial("#263f48");
for (const x of [-0.22, 0.22]) {
const leg = new THREE.Mesh(
new THREE.CylinderGeometry(0.11, 0.13, 0.65, 5),
legMaterial
);
leg.position.set(x, 0.33, 0);
leg.castShadow = true;
courier.add(leg);
}
const armMaterial = makeMaterial("#b97551");
for (const x of [-0.55, 0.55]) {
const arm = new THREE.Mesh(
new THREE.CylinderGeometry(0.09, 0.11, 0.8, 5),
armMaterial
);
arm.position.set(x, 1.05, 0);
arm.rotation.z = x > 0 ? -0.15 : 0.15;
arm.castShadow = true;
courier.add(arm);
}
const parcel = new THREE.Mesh(
new THREE.BoxGeometry(0.85, 0.72, 0.65),
makeMaterial("#e58b42")
);
parcel.position.set(0, 1.18, -0.58);
parcel.castShadow = true;
courier.add(parcel);
const parcelStrap = new THREE.Mesh(
new THREE.BoxGeometry(0.13, 0.75, 0.68),
makeMaterial("#f4d27d")
);
parcelStrap.position.copy(parcel.position);
parcel.add(parcelStrap);
const halo = new THREE.Mesh(
new THREE.TorusGeometry(1.35, 0.11, 5, 28),
new THREE.MeshBasicMaterial({
color: "#fff2b8",
transparent: true,
opacity: 0.9
})
);
halo.rotation.x = Math.PI / 2;
halo.position.y = 0.08;
courier.add(halo);
const shadow = new THREE.Mesh(
new THREE.CircleGeometry(1.05, 18),
new THREE.MeshBasicMaterial({
color: "#30463c",
transparent: true,
opacity: 0.2,
depthWrite: false
})
);
shadow.rotation.x = -Math.PI / 2;
shadow.position.y = 0.02;
courier.add(shadow);
scene.add(courier);
// -------------------------------------------------------------------------
// UI state
// -------------------------------------------------------------------------
const routeButtons = [...document.querySelectorAll(".route-card")];
const playButton = document.querySelector("#playButton");
const resetButton = document.querySelector("#resetButton");
const progressInput = document.querySelector("#progress");
const progressValue = document.querySelector("#progressValue");
const speedSelect = document.querySelector("#speed");
const statusElement = document.querySelector("#status");
const statDistance = document.querySelector("#statDistance");
const statAscent = document.querySelector("#statAscent");
const statDescent = document.querySelector("#statDescent");
const statGrade = document.querySelector("#statGrade");
const labelRoute = document.querySelector("#labelRoute");
const state = {
selectedRoute: "stairs",
progress: 0,
playing: false
};
function formatElevation(stats) {
return `${stats.ascent} m ↑ · ${stats.descent} m ↓`;
}
Object.entries(routes).forEach(([id, route]) => {
const button = document.querySelector(`[data-route="${id}"]`);
button.querySelector("[data-distance]").textContent =
`${route.stats.distance} m`;
button.querySelector("[data-elevation]").textContent =
formatElevation(route.stats);
});
function updateSelectedRouteUI() {
const route = routes[state.selectedRoute];
const stats = route.stats;
routeButtons.forEach((button) => {
const active = button.dataset.route === state.selectedRoute;
button.classList.toggle("active", active);
button.setAttribute("aria-pressed", String(active));
});
statDistance.textContent = `${stats.distance} m`;
statAscent.textContent = `${stats.ascent} m`;
statDescent.textContent = `${stats.descent} m`;
statGrade.textContent = `${stats.grade}%`;
labelRoute.textContent = route.name;
const isStairs = state.selectedRoute === "stairs";
routeMeshes.stairs.stepMaterial.color.set(
isStairs ? "#e96f45" : "#b8ad9c"
);
routeMeshes.stairs.stepMaterial.emissive.set(
isStairs ? "#8d321d" : "#000000"
);
routeMeshes.stairs.stepMaterial.emissiveIntensity = isStairs ? 0.14 : 0;
routeMeshes.stairs.lineMaterial.color.set(
isStairs ? "#ffd28a" : "#d0c5ae"
);
routeMeshes.stairs.lineMaterial.emissive.set(
isStairs ? "#e96f45" : "#000000"
);
routeMeshes.gentle.roadMaterial.color.set(
isStairs ? "#c2a66f" : "#e4a84c"
);
routeMeshes.gentle.roadMaterial.emissive.set(
isStairs ? "#000000" : "#9d5d20"
);
routeMeshes.gentle.baseMaterial.color.set(
isStairs ? "#9f8e71" : "#877b64"
);
}
function updateProgressUI() {
const percent = state.progress * 100;
progressInput.value = percent.toFixed(1);
progressInput.style.setProperty("--progress", `${percent}%`);
progressValue.textContent = `${Math.round(percent)}%`;
if (state.progress >= 0.999) {
statusElement.textContent = "Delivered to Koriq Café";
} else if (state.progress <= 0.001) {
statusElement.textContent = "Parcel waiting at pickup";
} else if (state.selectedRoute === "stairs") {
statusElement.textContent = "Climbing the stairway";
} else {
statusElement.textContent = "Taking the gentle loop";
}
}
function selectRoute(id) {
if (!routes[id]) return;
state.selectedRoute = id;
state.progress = 0;
state.playing = false;
playButton.textContent = "Start delivery";
updateSelectedRouteUI();
updateProgressUI();
updateDelivery();
}
function togglePlayback() {
if (state.progress >= 0.999) {
state.progress = 0;
state.playing = true;
} else {
state.playing = !state.playing;
}
playButton.textContent = state.playing
? "Pause delivery"
: state.progress >= 0.999
? "Deliver again"
: "Start delivery";
}
routeButtons.forEach((button) => {
button.addEventListener("click", () => selectRoute(button.dataset.route));
});
playButton.addEventListener("click", togglePlayback);
resetButton.addEventListener("click", () => {
state.progress = 0;
state.playing = false;
playButton.textContent = "Start delivery";
updateProgressUI();
updateDelivery();
});
progressInput.addEventListener("input", () => {
state.progress = Number(progressInput.value) / 100;
state.playing = false;
playButton.textContent =
state.progress >= 0.999 ? "Deliver again" : "Start delivery";
updateProgressUI();
updateDelivery();
});
window.addEventListener("keydown", (event) => {
if (
event.code === "Space" &&
!["INPUT", "SELECT", "BUTTON"].includes(document.activeElement.tagName)
) {
event.preventDefault();
togglePlayback();
}
});
// -------------------------------------------------------------------------
// Custom camera controls: orbit, pan and zoom
// -------------------------------------------------------------------------
const cameraState = {
yaw: 0.72,
pitch: 0.69,
radius: 154,
target: new THREE.Vector3(0, 14, 0)
};
function updateCamera() {
const { yaw, pitch, radius, target } = cameraState;
const horizontal = Math.cos(pitch) * radius;
camera.position.set(
target.x + Math.sin(yaw) * horizontal,
target.y + Math.sin(pitch) * radius,
target.z + Math.cos(yaw) * horizontal
);
camera.lookAt(target);
}
function resetCamera() {
cameraState.yaw = 0.72;
cameraState.pitch = 0.69;
cameraState.radius = 154;
cameraState.target.set(0, 14, 0);
updateCamera();
}
document.querySelectorAll("[data-camera]").forEach((button) => {
button.addEventListener("click", () => {
const action = button.dataset.camera;
if (action === "in") cameraState.radius = clamp(cameraState.radius - 15, 65, 240);
if (action === "out") cameraState.radius = clamp(cameraState.radius + 15, 65, 240);
if (action === "home") resetCamera();
updateCamera();
});
});
const pointer = new THREE.Vector2();
const raycaster = new THREE.Raycaster();
let dragging = false;
let panning = false;
let pointerMoved = 0;
let previousX = 0;
let previousY = 0;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
panning = event.shiftKey || event.button === 2;
pointerMoved = 0;
previousX = event.clientX;
previousY = event.clientY;
canvas.setPointerCapture(event.pointerId);
canvas.classList.add("dragging");
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
pointerMoved += Math.abs(dx) + Math.abs(dy);
previousX = event.clientX;
previousY = event.clientY;
if (panning) {
const scale = cameraState.radius * 0.0017;
const right = new THREE.Vector3(
Math.cos(cameraState.yaw),
0,
-Math.sin(cameraState.yaw)
);
const forward = new THREE.Vector3(
Math.sin(cameraState.yaw),
0,
Math.cos(cameraState.yaw)
);
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(forward, dy * scale);
} else {
cameraState.yaw -= dx * 0.006;
cameraState.pitch = clamp(cameraState.pitch + dy * 0.005, 0.32, 1.22);
}
updateCamera();
});
canvas.addEventListener("pointerup", (event) => {
dragging = false;
canvas.classList.remove("dragging");
if (pointerMoved < 6) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(routeHitMeshes, false);
if (hits.length) {
const routeId = hits[0].object.userData.route;
if (routeId) selectRoute(routeId);
}
}
});
canvas.addEventListener("pointercancel", () => {
dragging = false;
canvas.classList.remove("dragging");
});
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = clamp(
cameraState.radius + event.deltaY * 0.1,
65,
240
);
updateCamera();
},
{ passive: false }
);
// -------------------------------------------------------------------------
// Labels
// -------------------------------------------------------------------------
const labelAnchors = {
labelStart: new THREE.Vector3(
-56,
terrainHeight(-56, 50) + 12,
50
),
labelEnd: new THREE.Vector3(
49,
terrainHeight(49, -51) + 12,
-51
),
labelChurch: new THREE.Vector3(
0,
terrainHeight(0, -69) + 28,
-69
)
};
function positionLabel(element, worldPosition) {
const projected = worldPosition.clone().project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.15 &&
Math.abs(projected.y) < 1.15;
element.style.opacity = visible ? "1" : "0";
if (!visible) return;
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function updateDelivery() {
const route = routes[state.selectedRoute];
const sample = route.path.getPoint(state.progress);
courier.position.copy(sample.position);
courier.rotation.y = Math.atan2(sample.tangent.x, sample.tangent.z);
if (state.progress >= 0.999) {
courier.position.y += Math.sin(clock.elapsedTime * 3) * 0.06;
halo.material.color.set("#bff3cf");
} else {
halo.material.color.set("#fff2b8");
}
}
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (state.playing) {
const route = routes[state.selectedRoute];
const speed = Number(speedSelect.value);
state.progress = Math.min(
1,
state.progress + (delta * speed) / route.duration
);
if (state.progress >= 1) {
state.playing = false;
playButton.textContent = "Deliver again";
}
updateProgressUI();
}
updateDelivery();
positionLabel(
document.querySelector("#labelStart"),
labelAnchors.labelStart
);
positionLabel(
document.querySelector("#labelEnd"),
labelAnchors.labelEnd
);
positionLabel(
document.querySelector("#labelChurch"),
labelAnchors.labelChurch
);
const routeSample = routes[state.selectedRoute].path.getPoint(0.53);
positionLabel(labelRoute, routeSample.position);
renderer.render(scene, camera);
}
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", resize);
updateSelectedRouteUI();
updateProgressUI();
updateDelivery();
updateCamera();
animate();
requestAnimationFrame(() => {
document.querySelector("#loading").classList.add("hidden");
});
</script>
</body>
</html>
```