Prompt specification
Build or customize the Three.js 3D scene "Find a route through Alfama's connected stair lanes" 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: Find a route through Alfama's connected stair lanes
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/find-a-route-through-alfama-s-connected-stair-lanes-x2840
Scene Description Prompt:
Compare voxel walking routes through Lisbon's Alfama stairs, reporting distance and climb separately. Use Three.js from cdnjs in one HTML file.
Working Three.js Starter (find-a-route-through-alfama-s-connected-stair-lanes-x2840):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Alfama Voxel Route Comparison</title>
<style>
:root {
--ink: #18242b;
--muted: #68767d;
--paper: rgba(255, 252, 245, 0.94);
--line: rgba(24, 36, 43, 0.13);
--orange: #ff6846;
--blue: #3978e8;
--green: #08a982;
--shadow: 0 18px 50px rgba(29, 42, 49, 0.16);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #b9d5df;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
}
.hud {
position: fixed;
z-index: 10;
pointer-events: none;
}
.brand {
top: 22px;
left: 24px;
max-width: 390px;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.65);
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 7px;
color: #40525c;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.eyebrow::before {
width: 24px;
height: 3px;
border-radius: 2px;
background: var(--orange);
content: "";
}
h1 {
margin: 0;
font-size: clamp(28px, 3.4vw, 48px);
font-weight: 850;
letter-spacing: -0.055em;
line-height: 0.98;
}
.brand p {
max-width: 355px;
margin: 10px 0 0;
color: #435761;
font-size: 13px;
line-height: 1.5;
}
.panel {
top: 20px;
right: 20px;
width: min(450px, calc(100vw - 40px));
padding: 17px;
border: 1px solid rgba(255, 255, 255, 0.72);
border-radius: 20px;
background: var(--paper);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
pointer-events: auto;
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1px 2px 12px;
border-bottom: 1px solid var(--line);
}
.panel-heading strong {
font-size: 12px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.model-badge {
padding: 5px 8px;
border-radius: 999px;
background: #e9eee9;
color: #52615d;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
}
#route-list {
display: grid;
gap: 8px;
margin-top: 12px;
}
.route-row {
display: grid;
grid-template-columns: 18px 1fr;
gap: 9px;
align-items: start;
padding: 11px;
border: 1px solid transparent;
border-radius: 14px;
background: rgba(255, 255, 255, 0.54);
transition:
border-color 160ms ease,
background 160ms ease,
transform 160ms ease;
}
.route-row:hover {
transform: translateY(-1px);
border-color: var(--line);
}
.route-row.active {
border-color: var(--route-color);
background: #fff;
box-shadow: 0 8px 22px rgba(27, 40, 47, 0.08);
}
.route-row.hidden-route {
opacity: 0.48;
}
.route-toggle {
width: 15px;
height: 15px;
margin: 3px 0 0;
accent-color: var(--route-color);
cursor: pointer;
}
.route-main {
width: 100%;
padding: 0;
border: 0;
background: transparent;
color: inherit;
text-align: left;
cursor: pointer;
}
.route-title {
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
font-weight: 800;
}
.route-dot {
width: 9px;
height: 9px;
flex: 0 0 auto;
border-radius: 3px;
background: var(--route-color);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--route-color), transparent 84%);
}
.route-note {
margin: 4px 0 10px 17px;
color: var(--muted);
font-size: 11px;
}
.route-metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
position: relative;
overflow: hidden;
padding: 8px 9px 9px;
border-radius: 10px;
background: #f1f2ee;
}
.metric::after {
position: absolute;
right: 0;
bottom: 0;
left: 0;
height: 2px;
background: var(--route-color);
content: "";
opacity: 0.65;
}
.metric strong {
display: block;
font-size: 17px;
letter-spacing: -0.03em;
}
.metric span {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.insight {
margin-top: 12px;
padding: 11px 12px;
border-radius: 12px;
background: #edf1ec;
color: #43534f;
font-size: 11px;
line-height: 1.5;
}
.panel-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid var(--line);
}
.method-note {
color: var(--muted);
font-size: 9px;
line-height: 1.45;
}
.small-button {
flex: 0 0 auto;
padding: 8px 10px;
border: 1px solid var(--line);
border-radius: 9px;
background: #fff;
color: var(--ink);
font-size: 10px;
font-weight: 800;
cursor: pointer;
}
.small-button:hover {
border-color: #9aa7aa;
}
.profile {
bottom: 20px;
left: 24px;
width: min(555px, calc(100vw - 48px));
padding: 13px 15px 10px;
border: 1px solid rgba(255, 255, 255, 0.72);
border-radius: 17px;
background: var(--paper);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
pointer-events: auto;
}
.profile-heading {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 16px;
margin-bottom: 4px;
}
.profile-heading strong {
font-size: 11px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
#profile-subtitle {
color: var(--muted);
font-size: 10px;
}
#profile-chart {
display: block;
width: 100%;
height: 140px;
overflow: visible;
}
.controls {
bottom: 21px;
right: 490px;
padding: 8px 11px;
border: 1px solid rgba(255, 255, 255, 0.62);
border-radius: 999px;
background: rgba(255, 252, 245, 0.78);
color: #526169;
font-size: 10px;
box-shadow: 0 8px 25px rgba(29, 42, 49, 0.1);
backdrop-filter: blur(12px);
}
.loading {
position: fixed;
z-index: 30;
inset: 0;
display: grid;
place-items: center;
background: #bed7df;
color: #334850;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
@media (max-width: 1050px) {
.controls {
display: none;
}
.panel {
width: 390px;
}
.brand p {
display: none;
}
}
@media (max-width: 760px) {
.brand {
top: 15px;
left: 15px;
}
.brand h1 {
font-size: 30px;
}
.panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 48vh;
overflow: auto;
padding: 12px;
border-radius: 16px;
}
.profile {
display: none;
}
.route-row {
padding: 9px;
}
.panel-footer {
align-items: flex-start;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel model of Alfama walking routes"></canvas>
<header class="hud brand">
<div class="eyebrow">Lisbon · Alfama</div>
<h1>Stair route comparison</h1>
<p>
Select a voxel path to compare horizontal walking distance with accumulated
stair climb.
</p>
</header>
<aside class="hud panel">
<div class="panel-heading">
<strong>Route comparison</strong>
<span class="model-badge">Schematic model</span>
</div>
<div id="route-list"></div>
<div id="insight" class="insight"></div>
<div class="panel-footer">
<div class="method-note">
Distance is horizontal ground length. Climb is the sum of every positive
elevation change.
</div>
<button id="focus-button" class="small-button">Focus route</button>
</div>
</aside>
<section class="hud profile">
<div class="profile-heading">
<strong>Elevation profile</strong>
<span id="profile-subtitle"></span>
</div>
<svg id="profile-chart" viewBox="0 0 540 170" aria-label="Route elevation profiles"></svg>
</section>
<div class="hud controls">
Drag: rotate · Shift/right-drag: pan · Wheel: zoom · Click a route
</div>
<div id="loading" class="loading">Building Alfama voxel model…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const canvas = document.getElementById("scene");
const loading = document.getElementById("loading");
const COLORS = {
direct: 0xff6846,
ridge: 0x3978e8,
terrace: 0x08a982
};
/*
Coordinates are schematic local metres.
y is elevation in metres and x/z are horizontal map coordinates.
The route geometry and embedded elevations drive all reported metrics.
*/
const ROUTES = [
{
id: "direct",
name: "Escadinhas direct",
note: "Shortest · concentrated stair climb",
color: COLORS.direct,
points: [
{ x: 180, y: 42, z: 600, label: "Largo das Portas do Sol" },
{ x: 110, y: 49, z: 525, label: "Rua dos Remédios" },
{ x: 25, y: 57, z: 430, label: "Beco dos Aciprestes" },
{ x: -20, y: 65, z: 335, label: "São Miguel" },
{ x: -85, y: 70, z: 220, label: "Rua de São João" },
{ x: -115, y: 74, z: 115, label: "Escadinhas da Sé" },
{ x: -90, y: 76, z: 60, label: "Sé de Lisboa" }
],
stairSegments: [0, 1, 2, 3, 4, 5]
},
{
id: "ridge",
name: "São Miguel ridge",
note: "Quieter lanes · longer upper approach",
color: COLORS.ridge,
points: [
{ x: 180, y: 42, z: 600, label: "Largo das Portas do Sol" },
{ x: 265, y: 44, z: 540, label: "Beco dos Ratos" },
{ x: 230, y: 52, z: 465, label: "Rua da Rosa" },
{ x: 115, y: 59, z: 390, label: "Largo de São Miguel" },
{ x: 20, y: 64, z: 315, label: "Rua dos Bacalhoeiros" },
{ x: 5, y: 70, z: 220, label: "Rua de São João" },
{ x: -25, y: 74, z: 130, label: "Escadinhas da Sé" },
{ x: -90, y: 76, z: 60, label: "Sé de Lisboa" }
],
stairSegments: [2, 3, 4, 5]
},
{
id: "terrace",
name: "Low-terrace loop",
note: "Extra undulation · highest accumulated climb",
color: COLORS.terrace,
points: [
{ x: 180, y: 42, z: 600, label: "Largo das Portas do Sol" },
{ x: 220, y: 48, z: 510, label: "Rua de Santa Maria" },
{ x: 130, y: 54, z: 455, label: "Beco do Mexias" },
{ x: 35, y: 52, z: 455, label: "Travessa do Chão do Loureiro" },
{ x: -60, y: 60, z: 390, label: "Rua da Guia" },
{ x: -125, y: 66, z: 290, label: "Largo do Chafariz de Dentro" },
{ x: -135, y: 72, z: 170, label: "Rua de São João" },
{ x: -90, y: 76, z: 60, label: "Sé de Lisboa" }
],
stairSegments: [0, 1, 3, 4, 5, 6]
}
];
function calculateMetrics(route) {
let distance = 0;
let climb = 0;
let descent = 0;
let cumulative = 0;
route.points.forEach((point, index) => {
if (index === 0) {
point.cumulative = 0;
return;
}
const previous = route.points[index - 1];
const horizontal = Math.hypot(
point.x - previous.x,
point.z - previous.z
);
const elevationChange = point.y - previous.y;
distance += horizontal;
climb += Math.max(0, elevationChange);
descent += Math.max(0, -elevationChange);
cumulative += horizontal;
point.cumulative = cumulative;
});
route.metrics = { distance, climb, descent };
route.maxElevation = Math.max(...route.points.map((point) => point.y));
route.minElevation = Math.min(...route.points.map((point) => point.y));
}
ROUTES.forEach(calculateMetrics);
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.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xb9d5df);
scene.fog = new THREE.Fog(0xb9d5df, 1000, 2100);
const camera = new THREE.OrthographicCamera(-600, 600, 360, -360, 1, 3000);
const hemisphere = new THREE.HemisphereLight(0xeaf7ff, 0x9d765e, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff1d2, 3.3);
sun.position.set(-280, 650, 240);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -700;
sun.shadow.camera.right = 700;
sun.shadow.camera.top = 850;
sun.shadow.camera.bottom = -250;
sun.shadow.camera.near = 50;
sun.shadow.camera.far = 1700;
sun.shadow.bias = -0.0003;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xa9d7ff, 0.8);
fill.position.set(500, 250, -400);
scene.add(fill);
const cameraState = {
target: new THREE.Vector3(10, 50, 330),
azimuth: 0.58,
phi: 0.93,
radius: 1050,
zoom: 1
};
const VIEW_HEIGHT = 720;
function updateCamera() {
const { target, azimuth, phi, radius } = cameraState;
const sinPhi = Math.sin(phi);
camera.position.set(
target.x + radius * sinPhi * Math.sin(azimuth),
target.y + radius * Math.cos(phi),
target.z + radius * sinPhi * Math.cos(azimuth)
);
camera.lookAt(target);
camera.zoom = cameraState.zoom;
camera.updateProjectionMatrix();
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
camera.left = (-VIEW_HEIGHT * aspect) / 2;
camera.right = (VIEW_HEIGHT * aspect) / 2;
camera.top = VIEW_HEIGHT / 2;
camera.bottom = -VIEW_HEIGHT / 2;
updateCamera();
}
window.addEventListener("resize", resize);
resize();
function terrainHeight(x, z) {
return (
78 -
z * 0.06 +
Math.sin(x / 200) * 1.5
);
}
function seededRandom(seed) {
let value = seed >>> 0;
return () => {
value += 0x6d2b79f5;
let result = value;
result = Math.imul(result ^ (result >>> 15), result | 1);
result ^= result + Math.imul(result ^ (result >>> 7), result | 61);
return ((result ^ (result >>> 14)) >>> 0) / 4294967296;
};
}
const random = seededRandom(92741);
const dummy = new THREE.Object3D();
function setInstance(mesh, index, x, y, z, sx, sy, sz, rotation = 0) {
dummy.position.set(x, y, z);
dummy.rotation.set(0, rotation, 0);
dummy.scale.set(sx, sy, sz);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
}
// Stepped terrain tiles.
const tileSize = 60;
const tileColumns = 14;
const tileRows = 12;
const tileCount = tileColumns * tileRows;
const terrainGeometry = new THREE.BoxGeometry(1, 1, 1);
const terrainMaterial = new THREE.MeshStandardMaterial({
roughness: 0.97,
metalness: 0,
vertexColors: true
});
const terrain = new THREE.InstancedMesh(
terrainGeometry,
terrainMaterial,
tileCount
);
terrain.receiveShadow = true;
const terrainColors = [
0xcbbda7,
0xd7c8ae,
0xc4b49e,
0xd9ccb5,
0xb9ad9c
];
let tileIndex = 0;
for (let row = 0; row < tileRows; row++) {
for (let column = 0; column < tileColumns; column++) {
const x = -390 + column * tileSize;
const z = 30 + row * tileSize;
const top = terrainHeight(x, z);
setInstance(
terrain,
tileIndex,
x,
top - 7,
z,
59.7,
14,
59.7
);
terrain.setColorAt(
tileIndex,
new THREE.Color(
terrainColors[Math.floor(random() * terrainColors.length)]
)
);
tileIndex++;
}
}
terrain.instanceMatrix.needsUpdate = true;
terrain.instanceColor.needsUpdate = true;
scene.add(terrain);
// Route samples are also used to keep buildings away from the paths.
function sampleRoute(route, spacing = 10) {
const samples = [];
for (let index = 0; index < route.points.length - 1; index++) {
const start = route.points[index];
const end = route.points[index + 1];
const length = Math.hypot(end.x - start.x, end.z - start.z);
const count = Math.max(1, Math.ceil(length / spacing));
for (let step = 0; step < count; step++) {
const t = step / count;
const nextT = (step + 1) / count;
samples.push({
x: THREE.MathUtils.lerp(start.x, end.x, t),
y: THREE.MathUtils.lerp(start.y, end.y, t),
z: THREE.MathUtils.lerp(start.z, end.z, t),
distance: start.cumulative + length * t,
nextDistance: start.cumulative + length * nextT,
segment: index
});
}
}
const last = route.points.at(-1);
samples.push({
x: last.x,
y: last.y,
z: last.z,
distance: last.cumulative,
nextDistance: last.cumulative,
segment: route.points.length - 2
});
return samples;
}
const routeSamples = new Map(
ROUTES.map((route) => [route.id, sampleRoute(route)])
);
function isClearOfRoutes(x, z, clearance) {
for (const samples of routeSamples.values()) {
for (const point of samples) {
const dx = point.x - x;
const dz = point.z - z;
if (dx * dx + dz * dz < clearance * clearance) {
return false;
}
}
}
return true;
}
// Block-like Alfama buildings.
const buildingDescriptors = [];
const buildingPalette = [
0xf1e7d7,
0xe8d8bf,
0xd9b39d,
0xc8d0bc,
0xe9c76d,
0xd9d5c8
];
for (let z = 70; z <= 650; z += 58) {
for (let x = -330; x <= 330; x += 58) {
const offsetX = (random() - 0.5) * 9;
const offsetZ = (random() - 0.5) * 9;
const buildingX = x + offsetX;
const buildingZ = z + offsetZ;
const width = 25 + random() * 17;
const depth = 25 + random() * 17;
const clearance = 32 + Math.max(width, depth) * 0.35;
if (!isClearOfRoutes(buildingX, buildingZ, clearance)) {
continue;
}
const base = terrainHeight(buildingX, buildingZ);
const height = 9 + random() * 23;
buildingDescriptors.push({
x: buildingX,
z: buildingZ,
width,
depth,
height,
base,
color: buildingPalette[
Math.floor(random() * buildingPalette.length)
],
upper: random() > 0.72
});
}
}
const buildings = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
roughness: 0.88,
vertexColors: true
}),
buildingDescriptors.length
);
buildings.castShadow = true;
buildings.receiveShadow = true;
const roofs = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
color: 0xb9664e,
roughness: 0.9
}),
buildingDescriptors.length
);
roofs.castShadow = true;
roofs.receiveShadow = true;
const upperBlocks = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
color: 0xe7d8c1,
roughness: 0.9
}),
buildingDescriptors.length
);
upperBlocks.castShadow = true;
upperBlocks.receiveShadow = true;
buildingDescriptors.forEach((building, index) => {
setInstance(
buildings,
index,
building.x,
building.base + building.height / 2,
building.z,
building.width,
building.height,
building.depth
);
buildings.setColorAt(index, new THREE.Color(building.color));
setInstance(
roofs,
index,
building.x,
building.base + building.height + 1.25,
building.z,
building.width + 2.5,
2.5,
building.depth + 2.5
);
if (building.upper) {
setInstance(
upperBlocks,
index,
building.x,
building.base + building.height + 5,
building.z,
building.width * 0.62,
6,
building.depth * 0.62
);
} else {
setInstance(
upperBlocks,
index,
building.x,
-1000,
building.z,
0.001,
0.001,
0.001
);
}
});
buildings.instanceMatrix.needsUpdate = true;
buildings.instanceColor.needsUpdate = true;
roofs.instanceMatrix.needsUpdate = true;
upperBlocks.instanceMatrix.needsUpdate = true;
scene.add(buildings, roofs, upperBlocks);
// Voxel windows.
const windowsPerBuilding = 4;
const windowMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
color: 0x405866,
roughness: 0.45,
metalness: 0.12
}),
buildingDescriptors.length * windowsPerBuilding
);
let windowIndex = 0;
buildingDescriptors.forEach((building) => {
for (let window = 0; window < windowsPerBuilding; window++) {
const upperWindow = window >= 2;
const y = building.base + (upperWindow ? building.height - 5 : 4.5);
const offset = (window % 2 === 0 ? -1 : 1) * building.width * 0.22;
if (window % 2 === 0) {
setInstance(
windowMesh,
windowIndex++,
building.x + offset,
y,
building.z + building.depth / 2 + 0.35,
3.2,
3.1,
0.7
);
} else {
setInstance(
windowMesh,
windowIndex++,
building.x + building.width / 2 + 0.35,
y,
building.z + offset,
0.7,
3.1,
3.2
);
}
}
});
windowMesh.instanceMatrix.needsUpdate = true;
scene.add(windowMesh);
const routeMeshes = new Map();
const routeLines = new Map();
const stairMeshes = new Map();
ROUTES.forEach((route) => {
const samples = routeSamples.get(route.id);
const lineGeometry = new THREE.BufferGeometry().setFromPoints(
route.points.map(
(point) => new THREE.Vector3(point.x, point.y + 2, point.z)
)
);
const line = new THREE.Line(
lineGeometry,
new THREE.LineBasicMaterial({
color: route.color,
transparent: true,
opacity: 0.7
})
);
line.renderOrder = 3;
scene.add(line);
routeLines.set(route.id, line);
const routeMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
color: route.color,
emissive: route.color,
emissiveIntensity: 0.34,
roughness: 0.56,
transparent: true,
opacity: 0.98
}),
samples.length
);
routeMesh.userData.routeId = route.id;
routeMesh.castShadow = true;
routeMesh.receiveShadow = true;
samples.forEach((point, index) => {
setInstance(
routeMesh,
index,
point.x,
point.y + 1.3,
point.z,
7,
2.6,
7
);
});
routeMesh.instanceMatrix.needsUpdate = true;
scene.add(routeMesh);
routeMeshes.set(route.id, routeMesh);
// Wide, terraced stair blocks.
const stairSamples = [];
route.stairSegments.forEach((segmentIndex) => {
const start = route.points[segmentIndex];
const end = route.points[segmentIndex + 1];
const length = Math.hypot(end.x - start.x, end.z - start.z);
const count = Math.max(1, Math.floor(length / 9));
for (let step = 0; step < count; step++) {
const t = (step + 0.5) / count;
const x = THREE.MathUtils.lerp(start.x, end.x, t);
const y = THREE.MathUtils.lerp(start.y, end.y, t);
const z = THREE.MathUtils.lerp(start.z, end.z, t);
const ground = terrainHeight(x, z);
const height = Math.max(2.5, y - ground + 3);
stairSamples.push({
x,
y,
z,
height,
rotation: Math.atan2(end.x - start.x, end.z - start.z)
});
}
});
const stairMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
color: 0xd7c6a9,
roughness: 0.98
}),
stairSamples.length
);
stairSamples.forEach((step, index) => {
setInstance(
stairMesh,
index,
step.x,
step.y - step.height / 2,
step.z,
15,
step.height,
5.2,
step.rotation
);
});
stairMesh.instanceMatrix.needsUpdate = true;
stairMesh.receiveShadow = true;
scene.add(stairMesh);
stairMeshes.set(route.id, stairMesh);
});
function makeLabel(text, width = 115) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 768;
labelCanvas.height = 128;
const context = labelCanvas.getContext("2d");
context.clearRect(0, 0, labelCanvas.width, labelCanvas.height);
context.fillStyle = "rgba(255,252,245,0.93)";
context.strokeStyle = "rgba(24,36,43,0.18)";
context.lineWidth = 3;
context.beginPath();
context.roundRect(8, 12, 752, 104, 22);
context.fill();
context.stroke();
context.fillStyle = "#203039";
context.font = "700 35px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 384, 65);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(width, width / 6, 1);
sprite.renderOrder = 10;
return sprite;
}
function addLandmarkLabel(text, position, width) {
const label = makeLabel(text, width);
label.position.copy(position);
scene.add(label);
}
addLandmarkLabel(
"Largo das Portas do Sol",
new THREE.Vector3(180, 72, 600),
145
);
addLandmarkLabel(
"São Miguel",
new THREE.Vector3(20, 92, 335),
95
);
addLandmarkLabel(
"Sé de Lisboa",
new THREE.Vector3(-90, 104, 60),
105
);
function addEndpointMarker(position, color, label) {
const group = new THREE.Group();
group.position.copy(position);
const pedestal = new THREE.Mesh(
new THREE.BoxGeometry(15, 4, 15),
new THREE.MeshStandardMaterial({
color: 0xf4ecdb,
roughness: 0.8
})
);
pedestal.position.y = 2;
pedestal.castShadow = true;
const pole = new THREE.Mesh(
new THREE.BoxGeometry(2.4, 21, 2.4),
new THREE.MeshStandardMaterial({ color: 0x39474e })
);
pole.position.y = 13;
const flag = new THREE.Mesh(
new THREE.BoxGeometry(14, 8, 2),
new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.18
})
);
flag.position.set(7, 21, 0);
flag.castShadow = true;
group.add(pedestal, pole, flag);
scene.add(group);
const sprite = makeLabel(label, 48);
sprite.position.set(0, 34, 0);
group.add(sprite);
}
const start = ROUTES[0].points[0];
const end = ROUTES[0].points.at(-1);
addEndpointMarker(
new THREE.Vector3(start.x, start.y, start.z),
0x31b67f,
"START"
);
addEndpointMarker(
new THREE.Vector3(end.x, end.y, end.z),
0xffb54d,
"END"
);
// Animated voxel walker.
const walker = new THREE.Group();
const walkerBody = new THREE.Mesh(
new THREE.BoxGeometry(5.5, 8, 5.5),
new THREE.MeshStandardMaterial({
color: 0xffffff,
emissive: 0xffffff,
emissiveIntensity: 0.12
})
);
walkerBody.position.y = 5;
const walkerHead = new THREE.Mesh(
new THREE.BoxGeometry(4, 4, 4),
new THREE.MeshStandardMaterial({ color: 0xf5c7a5 })
);
walkerHead.position.y = 11;
walker.add(walkerBody, walkerHead);
walker.castShadow = true;
scene.add(walker);
let activeRouteId = "direct";
const visibleRoutes = new Set(ROUTES.map((route) => route.id));
function formatDistance(metres) {
return metres >= 1000
? `${(metres / 1000).toFixed(2)} km`
: `${Math.round(metres)} m`;
}
function routeById(id) {
return ROUTES.find((route) => route.id === id);
}
function selectRoute(id) {
activeRouteId = id;
const route = routeById(id);
walkerBody.material.color.setHex(route.color);
walkerBody.material.emissive.setHex(route.color);
updateRouteStyles();
updateProfile();
updateInsight();
}
function updateRouteStyles() {
ROUTES.forEach((route) => {
const active = route.id === activeRouteId;
const visible = visibleRoutes.has(route.id);
const line = routeLines.get(route.id);
const routeMesh = routeMeshes.get(route.id);
const stairMesh = stairMeshes.get(route.id);
line.visible = visible;
routeMesh.visible = visible;
stairMesh.visible = visible;
line.material.opacity = active ? 0.95 : 0.32;
routeMesh.material.opacity = active ? 1 : 0.42;
routeMesh.material.emissiveIntensity = active ? 0.42 : 0.15;
document
.querySelector(`.route-row[data-route="${route.id}"]`)
?.classList.toggle("active", active);
});
document.getElementById("profile-subtitle").textContent =
`${routeById(activeRouteId).name} · ${formatDistance(
routeById(activeRouteId).metrics.distance
)} · ${Math.round(
routeById(activeRouteId).metrics.climb
)} m climb`;
}
function updateInsight() {
const shortest = [...ROUTES].sort(
(a, b) => a.metrics.distance - b.metrics.distance
)[0];
const mostClimb = [...ROUTES].sort(
(a, b) => b.metrics.climb - a.metrics.climb
)[0];
const distanceDifference =
mostClimb.metrics.distance - shortest.metrics.distance;
const climbDifference =
mostClimb.metrics.climb - shortest.metrics.climb;
document.getElementById("insight").innerHTML = `
<strong>${shortest.name}</strong> is shortest at
${formatDistance(shortest.metrics.distance)}.
Compared with <strong>${mostClimb.name}</strong>, it saves
${formatDistance(distanceDifference)} and
${Math.round(climbDifference)} m of climb.
`;
}
function updateProfile() {
const width = 540;
const height = 170;
const margin = {
left: 39,
right: 12,
top: 12,
bottom: 25
};
const allPoints = ROUTES.flatMap((route) => route.points);
const minElevation =
Math.floor(Math.min(...allPoints.map((point) => point.y)) / 5) * 5 - 3;
const maxElevation =
Math.ceil(Math.max(...allPoints.map((point) => point.y)) / 5) * 5 + 3;
const maxDistance = Math.max(
...ROUTES.map((route) => route.metrics.distance)
);
const chartWidth = width - margin.left - margin.right;
const chartHeight = height - margin.top - margin.bottom;
const xFor = (distance) =>
margin.left + (distance / maxDistance) * chartWidth;
const yFor = (elevation) =>
margin.top +
chartHeight -
((elevation - minElevation) / (maxElevation - minElevation)) *
chartHeight;
let svg = "";
for (let index = 0; index < 4; index++) {
const elevation =
minElevation +
((maxElevation - minElevation) * index) / 3;
const y = yFor(elevation);
svg += `
<line
x1="${margin.left}"
x2="${width - margin.right}"
y1="${y}"
y2="${y}"
stroke="rgba(24,36,43,0.10)"
stroke-width="1"
/>
<text
x="${margin.left - 7}"
y="${y + 3}"
text-anchor="end"
fill="#778188"
font-size="8"
>${Math.round(elevation)}m</text>
`;
}
ROUTES.forEach((route) => {
const pathData = route.points
.map(
(point, index) =>
`${index === 0 ? "M" : "L"} ${xFor(point.cumulative).toFixed(
2
)} ${yFor(point.y).toFixed(2)}`
)
.join(" ");
const active = route.id === activeRouteId;
const visible = visibleRoutes.has(route.id);
svg += `
<path
d="${pathData}"
fill="none"
stroke="#${route.color.toString(16).padStart(6, "0")}"
stroke-width="${active ? 3.2 : 1.7}"
stroke-linecap="round"
stroke-linejoin="round"
opacity="${visible ? (active ? 1 : 0.25) : 0.07}"
/>
`;
});
svg += `
<text
x="${margin.left}"
y="${height - 5}"
fill="#778188"
font-size="8"
>START</text>
<text
x="${width - margin.right}"
y="${height - 5}"
text-anchor="end"
fill="#778188"
font-size="8"
>${formatDistance(maxDistance)}</text>
<text
x="${margin.left + chartWidth / 2}"
y="${height - 5}"
text-anchor="middle"
fill="#778188"
font-size="8"
letter-spacing="1"
>DISTANCE</text>
`;
document.getElementById("profile-chart").innerHTML = svg;
}
const routeList = document.getElementById("route-list");
ROUTES.forEach((route) => {
const row = document.createElement("div");
row.className = "route-row";
row.dataset.route = route.id;
row.style.setProperty(
"--route-color",
`#${route.color.toString(16).padStart(6, "0")}`
);
row.innerHTML = `
<input
class="route-toggle"
type="checkbox"
checked
aria-label="Show ${route.name}"
>
<button class="route-main" type="button">
<span class="route-title">
<span class="route-dot"></span>
${route.name}
</span>
<span class="route-note">${route.note}</span>
<span class="route-metrics">
<span class="metric">
<strong>${formatDistance(route.metrics.distance)}</strong>
<span>Distance</span>
</span>
<span class="metric">
<strong>${Math.round(route.metrics.climb)} m</strong>
<span>Climb</span>
</span>
</span>
</button>
`;
row.querySelector(".route-main").addEventListener("click", () => {
selectRoute(route.id);
});
row.querySelector(".route-toggle").addEventListener("change", (event) => {
const visible = event.target.checked;
if (visible) {
visibleRoutes.add(route.id);
} else {
visibleRoutes.delete(route.id);
}
row.classList.toggle("hidden-route", !visible);
if (!visible && activeRouteId === route.id) {
const nextVisible = ROUTES.find(
(candidate) => visibleRoutes.has(candidate.id)
);
if (nextVisible) {
selectRoute(nextVisible.id);
}
}
updateRouteStyles();
updateProfile();
});
routeList.appendChild(row);
});
document.getElementById("focus-button").addEventListener("click", () => {
const route = routeById(activeRouteId);
const points = route.points;
const center = new THREE.Vector3();
points.forEach((point) => center.add(new THREE.Vector3(point.x, point.y, point.z)));
center.multiplyScalar(1 / points.length);
cameraState.target.copy(center);
cameraState.zoom = 1.55;
updateCamera();
});
// Custom camera controls: no examples/addons modules.
let pointerDown = false;
let pointerMode = "rotate";
let pointerMoved = 0;
let previousPointer = { x: 0, y: 0 };
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
pointerDown = true;
pointerMoved = 0;
previousPointer = { x: event.clientX, y: event.clientY };
pointerMode =
event.button === 2 || event.shiftKey ? "pan" : "rotate";
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!pointerDown) return;
const dx = event.clientX - previousPointer.x;
const dy = event.clientY - previousPointer.y;
pointerMoved += Math.abs(dx) + Math.abs(dy);
previousPointer = { x: event.clientX, y: event.clientY };
if (pointerMode === "rotate") {
cameraState.azimuth -= dx * 0.005;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi + dy * 0.004,
0.38,
1.28
);
} else {
const units =
VIEW_HEIGHT / cameraState.zoom / window.innerHeight;
const right = new THREE.Vector3(
Math.cos(cameraState.azimuth),
0,
-Math.sin(cameraState.azimuth)
);
const forward = new THREE.Vector3(
-Math.sin(cameraState.azimuth),
0,
-Math.cos(cameraState.azimuth)
);
cameraState.target.addScaledVector(right, -dx * units);
cameraState.target.addScaledVector(forward, -dy * units);
cameraState.target.x = THREE.MathUtils.clamp(
cameraState.target.x,
-550,
550
);
cameraState.target.z = THREE.MathUtils.clamp(
cameraState.target.z,
-100,
800
);
}
updateCamera();
});
canvas.addEventListener("pointerup", (event) => {
pointerDown = false;
canvas.releasePointerCapture(event.pointerId);
if (pointerMoved < 5) {
const mouse = new THREE.Vector2(
(event.clientX / window.innerWidth) * 2 - 1,
-(event.clientY / window.innerHeight) * 2 + 1
);
const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mouse, camera);
const visibleRouteMeshes = ROUTES.map((route) =>
routeMeshes.get(route.id)
).filter((mesh) => mesh.visible);
const intersections = raycaster.intersectObjects(
visibleRouteMeshes,
false
);
if (intersections.length) {
selectRoute(intersections[0].object.userData.routeId);
}
}
});
canvas.addEventListener("pointercancel", () => {
pointerDown = false;
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * Math.exp(-event.deltaY * 0.001),
0.55,
3.1
);
updateCamera();
},
{ passive: false }
);
function positionAlongRoute(route, distance) {
const points = route.points;
for (let index = 0; index < points.length - 1; index++) {
const start = points[index];
const end = points[index + 1];
const segmentLength = end.cumulative - start.cumulative;
if (
distance <= end.cumulative ||
index === points.length - 2
) {
const localDistance = THREE.MathUtils.clamp(
distance - start.cumulative,
0,
segmentLength
);
const t = segmentLength === 0 ? 0 : localDistance / segmentLength;
return {
x: THREE.MathUtils.lerp(start.x, end.x, t),
y: THREE.MathUtils.lerp(start.y, end.y, t),
z: THREE.MathUtils.lerp(start.z, end.z, t),
rotation: Math.atan2(end.x - start.x, end.z - start.z)
};
}
}
return null;
}
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
const route = routeById(activeRouteId);
const routeDistance = route.metrics.distance;
const travel =
((elapsed * 27) % (routeDistance + 45)) - 15;
const position = positionAlongRoute(route, travel);
if (position && visibleRoutes.has(route.id)) {
walker.visible = true;
walker.position.set(position.x, position.y + 1, position.z);
walker.rotation.y = position.rotation;
walker.position.y += Math.abs(Math.sin(elapsed * 7)) * 1.4;
} else {
walker.visible = false;
}
renderer.render(scene, camera);
}
updateRouteStyles();
updateProfile();
updateInsight();
updateCamera();
animate();
loading.remove();
</script>
</body>
</html>
```