Prompt specification
Build or customize the Three.js 3D scene "Compare viewpoints along a lower and upper route" 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 viewpoints along a lower and upper route
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/compare-viewpoints-along-a-lower-and-upper-route-x2828
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows the Grassmarket beneath Edinburgh's castle ridge. Let users follow two schematic routes around the square and hillside. Show how height and occlusion change the visible castle silhouette while distance remains a separate measure. Voxel style.
Working Three.js Starter (compare-viewpoints-along-a-lower-and-upper-route-x2828):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Grassmarket Castle Sightlines</title>
<style>
:root {
--ink: #17211d;
--muted: #67736c;
--paper: rgba(248, 246, 236, 0.92);
--line: rgba(23, 33, 29, 0.14);
--orange: #ed6844;
--teal: #248d83;
--purple: #7756a8;
--shadow: 0 14px 45px rgba(28, 39, 33, 0.13);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dfe5dc;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#app,
#stage {
position: absolute;
inset: 0;
}
#stage > canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
}
.topbar {
position: absolute;
z-index: 5;
top: 0;
left: 0;
right: 0;
height: 66px;
padding: 15px 24px;
display: flex;
align-items: center;
justify-content: space-between;
pointer-events: none;
background: linear-gradient(
to bottom,
rgba(241, 244, 236, 0.96),
rgba(241, 244, 236, 0)
);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
}
.brand-mark {
width: 31px;
height: 31px;
display: grid;
place-items: center;
border: 2px solid var(--ink);
border-radius: 3px;
box-shadow: 4px 4px 0 rgba(23, 33, 29, 0.12);
font-weight: 900;
font-size: 13px;
}
.brand strong {
display: block;
font-size: 14px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.brand small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 10px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.location {
padding: 7px 10px;
border: 1px solid rgba(23, 33, 29, 0.17);
border-radius: 999px;
background: rgba(248, 246, 236, 0.65);
color: #4e5d54;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.panel {
position: absolute;
z-index: 4;
border: 1px solid rgba(23, 33, 29, 0.13);
border-radius: 10px;
background: var(--paper);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
}
.route-panel {
top: 86px;
left: 24px;
width: 326px;
padding: 20px;
}
.eyebrow {
margin-bottom: 7px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: 28px;
font-weight: 500;
line-height: 1.08;
letter-spacing: -0.025em;
}
.intro {
margin: 10px 0 17px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.route-tabs {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.route-tab {
min-height: 73px;
padding: 11px;
border: 1px solid var(--line);
border-radius: 7px;
background: rgba(255, 255, 255, 0.38);
cursor: pointer;
text-align: left;
transition: 160ms ease;
}
.route-tab:hover {
transform: translateY(-1px);
border-color: rgba(23, 33, 29, 0.28);
}
.route-tab[aria-pressed="true"] {
color: white;
border-color: transparent;
box-shadow: 0 7px 16px rgba(23, 33, 29, 0.15);
}
.route-tab[data-route="square"][aria-pressed="true"] {
background: var(--orange);
}
.route-tab[data-route="ridge"][aria-pressed="true"] {
background: var(--purple);
}
.route-number {
display: block;
margin-bottom: 6px;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
opacity: 0.68;
}
.route-name {
display: block;
font-size: 12px;
font-weight: 800;
}
.route-level {
display: block;
margin-top: 3px;
font-size: 9px;
opacity: 0.72;
}
.progress-label {
display: flex;
justify-content: space-between;
margin-top: 19px;
margin-bottom: 8px;
color: var(--muted);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#progress {
width: 100%;
height: 4px;
margin: 0;
accent-color: var(--orange);
cursor: pointer;
}
.control-row {
display: flex;
gap: 7px;
margin-top: 16px;
}
.control-button {
flex: 1;
min-height: 36px;
padding: 8px 9px;
border: 1px solid var(--line);
border-radius: 6px;
background: rgba(255, 255, 255, 0.45);
cursor: pointer;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.control-button:hover,
.control-button.active {
border-color: var(--ink);
background: var(--ink);
color: white;
}
#play {
flex: 0 0 88px;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 8px 13px;
margin-top: 16px;
padding-top: 13px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.legend span {
display: flex;
align-items: center;
gap: 5px;
}
.swatch {
width: 8px;
height: 8px;
border-radius: 2px;
}
.silhouette-panel {
top: 86px;
right: 24px;
width: 360px;
padding: 14px;
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
}
.panel-heading strong {
font-size: 10px;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.badge {
padding: 4px 7px;
border-radius: 999px;
background: #e4e8df;
color: #536158;
font-size: 8px;
font-weight: 850;
letter-spacing: 0.09em;
text-transform: uppercase;
}
#silhouette-wrap {
position: relative;
height: 218px;
overflow: hidden;
border: 1px solid rgba(23, 33, 29, 0.12);
border-radius: 7px;
background: #f1eee3;
}
#silhouetteCanvas {
display: block;
width: 100%;
height: 100%;
}
.reticle {
position: absolute;
top: 50%;
left: 50%;
width: 18px;
height: 18px;
transform: translate(-50%, -50%);
border: 1px solid rgba(237, 104, 68, 0.42);
border-radius: 50%;
pointer-events: none;
}
.reticle::before,
.reticle::after {
content: "";
position: absolute;
background: rgba(237, 104, 68, 0.55);
}
.reticle::before {
left: 8px;
top: -4px;
width: 1px;
height: 24px;
}
.reticle::after {
left: -4px;
top: 8px;
width: 24px;
height: 1px;
}
.silhouette-copy {
margin: 11px 2px 1px;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.silhouette-copy b {
color: var(--ink);
}
.metrics {
position: absolute;
z-index: 4;
left: 24px;
right: 408px;
bottom: 24px;
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
overflow: hidden;
border: 1px solid rgba(23, 33, 29, 0.13);
border-radius: 10px;
background: var(--paper);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
}
.metric {
min-width: 0;
padding: 15px 16px 14px;
border-right: 1px solid var(--line);
}
.metric:last-child {
border-right: 0;
}
.metric-label {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 8px;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.metric-value {
display: block;
overflow: hidden;
font-family: Georgia, "Times New Roman", serif;
font-size: 24px;
line-height: 1;
text-overflow: ellipsis;
white-space: nowrap;
}
.metric-note {
display: block;
min-height: 25px;
margin-top: 6px;
color: var(--muted);
font-size: 9px;
line-height: 1.3;
}
.map-hint {
position: absolute;
z-index: 3;
right: 402px;
bottom: 126px;
padding: 7px 10px;
border-radius: 5px;
background: rgba(248, 246, 236, 0.78);
color: #647068;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.05em;
pointer-events: none;
}
.north {
position: absolute;
z-index: 2;
left: 50%;
top: 83px;
width: 34px;
height: 34px;
display: grid;
place-items: center;
border: 1px solid rgba(23, 33, 29, 0.15);
border-radius: 50%;
background: rgba(248, 246, 236, 0.66);
color: #425048;
font-size: 9px;
font-weight: 900;
pointer-events: none;
}
.north::after {
content: "";
position: absolute;
top: 4px;
border-right: 4px solid transparent;
border-bottom: 8px solid var(--orange);
border-left: 4px solid transparent;
}
.north span {
margin-top: 8px;
}
@media (max-width: 1050px) {
.route-panel {
width: 295px;
}
.silhouette-panel {
width: 310px;
}
.metrics {
right: 350px;
}
.metric {
padding: 13px 11px;
}
.metric-value {
font-size: 20px;
}
.map-hint {
display: none;
}
}
@media (max-width: 760px) {
body {
overflow: auto;
}
#app {
min-height: 1050px;
}
#stage {
position: fixed;
}
.topbar {
padding: 13px;
}
.location,
.north {
display: none;
}
.route-panel {
top: 75px;
left: 12px;
width: calc(100% - 24px);
padding: 16px;
}
.route-panel h1 {
font-size: 24px;
}
.intro {
margin-bottom: 12px;
}
.silhouette-panel {
top: 435px;
right: 12px;
width: calc(100% - 24px);
}
#silhouette-wrap {
height: 190px;
}
.metrics {
position: absolute;
top: 820px;
left: 12px;
right: 12px;
bottom: auto;
grid-template-columns: 1fr 1fr;
}
.metric {
border-bottom: 1px solid var(--line);
}
.metric:nth-child(2) {
border-right: 0;
}
.metric:nth-child(3),
.metric:nth-child(4) {
border-bottom: 0;
}
}
</style>
</head>
<body>
<div id="app">
<div id="stage"></div>
<header class="topbar">
<div class="brand">
<div class="brand-mark">GM</div>
<div>
<strong>Grassmarket / Castle Sightlines</strong>
<small>Edinburgh old town · voxel field study</small>
</div>
</div>
<div class="location">55.949° N · 3.194° W</div>
</header>
<section class="panel route-panel" aria-label="Route controls">
<div class="eyebrow">Two schematic walks</div>
<h1>See the castle<br>from the square.</h1>
<p class="intro">
Follow either route to compare elevation, intervening façades,
and the changing outline of Edinburgh Castle.
</p>
<div class="route-tabs">
<button
class="route-tab"
data-route="square"
aria-pressed="true"
>
<span class="route-number">01 / MARKET</span>
<span class="route-name">Grassmarket loop</span>
<span class="route-level">Street level · around the square</span>
</button>
<button
class="route-tab"
data-route="ridge"
aria-pressed="false"
>
<span class="route-number">02 / RIDGE</span>
<span class="route-name">Castle ridge</span>
<span class="route-level">Climbing walk · higher view</span>
</button>
</div>
<div class="progress-label">
<span>Position on route</span>
<span id="progress-value">58%</span>
</div>
<input
id="progress"
type="range"
min="0"
max="1000"
value="580"
aria-label="Position along selected route"
>
<div class="control-row">
<button id="play" class="control-button">▶ Walk</button>
<button id="overview" class="control-button active">Overview</button>
<button id="eye" class="control-button">Eye view</button>
</div>
<div class="legend">
<span><i class="swatch" style="background:#ed6844"></i>Square route</span>
<span><i class="swatch" style="background:#7756a8"></i>Ridge route</span>
<span><i class="swatch" style="background:#17211d"></i>Castle</span>
</div>
</section>
<section class="panel silhouette-panel" aria-label="Castle silhouette">
<div class="panel-heading">
<strong>Visible silhouette</strong>
<span id="silhouette-badge" class="badge">Square route</span>
</div>
<div id="silhouette-wrap">
<canvas id="silhouetteCanvas"></canvas>
<div class="reticle"></div>
</div>
<p class="silhouette-copy">
Black is exposed castle; grey blocks are occluders.
<b>Height and blockage alter the outline.</b>
Straight-line distance is reported separately below.
</p>
</section>
<section class="metrics" aria-label="Visibility measurements">
<div class="metric">
<span class="metric-label">Eye elevation</span>
<span id="height-value" class="metric-value">1.7 m</span>
<span id="height-note" class="metric-note">Above ground level</span>
</div>
<div class="metric">
<span class="metric-label">Straight-line distance</span>
<span id="distance-value" class="metric-value">0.0 m</span>
<span class="metric-note">Independent of visibility</span>
</div>
<div class="metric">
<span class="metric-label">Castle exposed</span>
<span id="visible-value" class="metric-value">0%</span>
<span id="visible-note" class="metric-note">Calculating sightlines…</span>
</div>
<div class="metric">
<span class="metric-label">Route walked</span>
<span id="walked-value" class="metric-value">0 m</span>
<span id="walked-note" class="metric-note">Grassmarket loop</span>
</div>
</section>
<div class="map-hint">DRAG TO ORBIT · SCROLL TO ZOOM · EYE VIEW: DRAG TO LOOK</div>
<div class="north"><span>N</span></div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// DOM and shared state
// -------------------------------------------------------------------------
const stage = document.querySelector("#stage");
const progressInput = document.querySelector("#progress");
const progressValue = document.querySelector("#progress-value");
const playButton = document.querySelector("#play");
const overviewButton = document.querySelector("#overview");
const eyeButton = document.querySelector("#eye");
const silhouetteBadge = document.querySelector("#silhouette-badge");
const heightValue = document.querySelector("#height-value");
const heightNote = document.querySelector("#height-note");
const distanceValue = document.querySelector("#distance-value");
const visibleValue = document.querySelector("#visible-value");
const visibleNote = document.querySelector("#visible-note");
const walkedValue = document.querySelector("#walked-value");
const walkedNote = document.querySelector("#walked-note");
const state = {
route: "square",
progress: 0.58,
playing: false,
cameraMode: "overview"
};
const EYE_HEIGHT = 1.7;
const CASTLE_TARGET = new THREE.Vector3(0, 22, -29);
const routePaths = {
square: [
new THREE.Vector3(-22, 0, 8),
new THREE.Vector3(-16, 0, 9),
new THREE.Vector3(-8, 0, 9),
new THREE.Vector3(0, 0, 9),
new THREE.Vector3(8, 0, 9),
new THREE.Vector3(16, 0, 9),
new THREE.Vector3(22, 0, 7),
new THREE.Vector3(21, 0, 3),
new THREE.Vector3(12, 0, 2),
new THREE.Vector3(2, 0, 2),
new THREE.Vector3(-10, 0, 2),
new THREE.Vector3(-19, 0, 3),
new THREE.Vector3(-22, 0, 6)
],
ridge: [
new THREE.Vector3(-22, 0, 8),
new THREE.Vector3(-27, 0, 3),
new THREE.Vector3(-29, 2, -5),
new THREE.Vector3(-27, 6, -12),
new THREE.Vector3(-25, 12, -20),
new THREE.Vector3(-20, 16, -27),
new THREE.Vector3(-11, 16, -29)
]
};
const routeMeta = {
square: {
label: "Grassmarket loop",
color: 0xed6844,
css: "#ed6844"
},
ridge: {
label: "Castle ridge",
color: 0x7756a8,
css: "#7756a8"
}
};
function routeLength(path) {
let length = 0;
for (let i = 1; i < path.length; i++) {
length += path[i].distanceTo(path[i - 1]);
}
return length;
}
const routeLengths = {
square: routeLength(routePaths.square),
ridge: routeLength(routePaths.ridge)
};
function sampleRoute(path, t) {
const total = routeLength(path);
let remaining = THREE.MathUtils.clamp(t, 0, 1) * total;
for (let i = 1; i < path.length; i++) {
const a = path[i - 1];
const b = path[i];
const length = a.distanceTo(b);
if (remaining <= length || i === path.length - 1) {
const local = length === 0 ? 0 : remaining / length;
return {
position: a.clone().lerp(b, local),
direction: b.clone().sub(a).normalize()
};
}
remaining -= length;
}
return {
position: path[path.length - 1].clone(),
direction: new THREE.Vector3(0, 0, 1)
};
}
// -------------------------------------------------------------------------
// Main renderer, scene, lighting, and camera
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdde5dc);
scene.fog = new THREE.Fog(0xdde5dc, 68, 145);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 220);
const hemisphere = new THREE.HemisphereLight(0xf5f3df, 0x65756b, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff0ce, 3.0);
sun.position.set(34, 55, 30);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -48;
sun.shadow.camera.right = 48;
sun.shadow.camera.top = 48;
sun.shadow.camera.bottom = -48;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 130;
sun.shadow.normalBias = 0.035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xbfd8db, 0.65);
fill.position.set(-35, 18, -25);
scene.add(fill);
const overview = {
theta: 0.72,
phi: 0.77,
radius: 72,
target: new THREE.Vector3(0, 6, -8)
};
const eye = {
yaw: 0,
pitch: 0,
fov: 64
};
const observerPosition = new THREE.Vector3();
const observerDirection = new THREE.Vector3();
function updateOverviewCamera() {
const sinPhi = Math.sin(overview.phi);
camera.position.set(
overview.target.x + overview.radius * sinPhi * Math.sin(overview.theta),
overview.target.y + overview.radius * Math.cos(overview.phi),
overview.target.z + overview.radius * sinPhi * Math.cos(overview.theta)
);
camera.lookAt(overview.target);
}
function aimEyeAtCastle() {
const dx = CASTLE_TARGET.x - observerPosition.x;
const dy = CASTLE_TARGET.y - observerPosition.y;
const dz = CASTLE_TARGET.z - observerPosition.z;
const horizontal = Math.hypot(dx, dz);
eye.yaw = Math.atan2(dx, dz);
eye.pitch = Math.atan2(dy, horizontal);
}
function updateEyeCamera() {
const cosPitch = Math.cos(eye.pitch);
observerDirection.set(
Math.sin(eye.yaw) * cosPitch,
Math.sin(eye.pitch),
Math.cos(eye.yaw) * cosPitch
);
camera.position.copy(observerPosition);
camera.lookAt(
observerPosition.x + observerDirection.x,
observerPosition.y + observerDirection.y,
observerPosition.z + observerDirection.z
);
camera.fov = eye.fov;
camera.updateProjectionMatrix();
}
// Direct camera controls: no addon imports.
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
if (state.cameraMode === "overview") {
overview.theta -= dx * 0.005;
overview.phi = THREE.MathUtils.clamp(
overview.phi - dy * 0.004,
0.34,
1.35
);
} else {
eye.yaw -= dx * 0.004;
eye.pitch = THREE.MathUtils.clamp(
eye.pitch - dy * 0.0035,
-1.1,
1.1
);
}
});
function endDrag(event) {
dragging = false;
if (event.pointerId !== undefined) {
try {
renderer.domElement.releasePointerCapture(event.pointerId);
} catch (_) {}
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
if (state.cameraMode === "overview") {
overview.radius = THREE.MathUtils.clamp(
overview.radius * Math.exp(event.deltaY * 0.001),
35,
105
);
} else {
eye.fov = THREE.MathUtils.clamp(
eye.fov + event.deltaY * 0.025,
32,
82
);
}
},
{ passive: false }
);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
// -------------------------------------------------------------------------
// Procedural voxel scenery
// -------------------------------------------------------------------------
const blockers = [];
const castleMeshes = [];
function box(parent, size, position, material, castShadow = true) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size[0], size[1], size[2]),
material
);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function buildTerrain(parent, silhouette = false) {
const group = new THREE.Group();
const specs = [
{
size: [60, 1.2, 39],
position: [0, -0.6, 5],
main: 0x8f9c7e,
silhouette: 0xaaa99e,
source: "Grassmarket ground"
},
{
size: [60, 2, 10],
position: [0, 1, -4],
main: 0x819071,
silhouette: 0xa4a398,
source: "Castle ridge terraces"
},
{
size: [58, 6, 10],
position: [0, 3, -12],
main: 0x75836a,
silhouette: 0x99988e,
source: "Castle ridge terraces"
},
{
size: [56, 12, 10],
position: [0, 6, -20],
main: 0x697962,
silhouette: 0x8f8e85,
source: "Castle ridge terraces"
},
{
size: [54, 16, 12],
position: [0, 8, -31],
main: 0x7f826b,
silhouette: 0x9b9a90,
source: "Castle ridge terraces"
}
];
for (const spec of specs) {
const material = silhouette
? new THREE.MeshBasicMaterial({ color: spec.silhouette })
: new THREE.MeshStandardMaterial({
color: spec.main,
roughness: 0.94
});
const mesh = box(
group,
spec.size,
spec.position,
material,
!silhouette
);
mesh.userData.occluder = spec.source;
if (!silhouette) {
blockers.push(mesh);
}
}
parent.add(group);
return group;
}
function buildBuilding(
parent,
x,
z,
width,
depth,
height,
bodyColor,
roofColor,
silhouette,
source = "Grassmarket façades"
) {
const group = new THREE.Group();
const bodyMaterial = silhouette
? new THREE.MeshBasicMaterial({ color: 0x85847d })
: new THREE.MeshStandardMaterial({
color: bodyColor,
roughness: 0.86
});
const roofMaterial = silhouette
? new THREE.MeshBasicMaterial({ color: 0x74736e })
: new THREE.MeshStandardMaterial({
color: roofColor,
roughness: 0.9
});
const body = box(
group,
[width, height, depth],
[x, height / 2, z],
bodyMaterial,
!silhouette
);
body.userData.occluder = source;
if (!silhouette) blockers.push(body);
const roofY = height;
const roof1 = box(
group,
[width + 0.5, 1.1, depth + 0.5],
[x, roofY + 0.55, z],
roofMaterial,
!silhouette
);
roof1.userData.occluder = source;
if (!silhouette) blockers.push(roof1);
const roof2 = box(
group,
[width - 1.2, 1.1, depth - 1.2],
[x, roofY + 1.65, z],
roofMaterial,
!silhouette
);
roof2.userData.occluder = source;
if (!silhouette) blockers.push(roof2);
const roof3 = box(
group,
[Math.max(1.2, width - 3), 1.0, Math.max(1.2, depth - 3)],
[x, roofY + 2.7, z],
roofMaterial,
!silhouette
);
roof3.userData.occluder = source;
if (!silhouette) blockers.push(roof3);
if (!silhouette) {
const windowMaterial = new THREE.MeshStandardMaterial({
color: 0x33433f,
emissive: 0x15201d,
emissiveIntensity: 0.35,
roughness: 0.5
});
const rows = Math.max(1, Math.floor(height / 2.7));
const columns = Math.max(2, Math.floor(width / 2.3));
for (let row = 0; row < rows; row++) {
for (let column = 0; column < columns; column++) {
const windowX =
x - width / 2 + ((column + 0.5) * width) / columns;
const windowY = 1.35 + row * 2.45;
box(
group,
[0.65, 0.9, 0.08],
[windowX, windowY, z + depth / 2 + 0.05],
windowMaterial,
false
);
}
}
const chimneyMaterial = new THREE.MeshStandardMaterial({
color: 0x776d61,
roughness: 1
});
box(
group,
[0.9, 2.2, 0.9],
[x + width * 0.22, height + 2.3, z],
chimneyMaterial
);
}
parent.add(group);
return group;
}
function buildBuildings(parent, silhouette = false) {
const group = new THREE.Group();
const buildings = [
[-18, -1.5, 7, 5, 6.2, 0xc7aa83, 0x5b5b58],
[-9.5, -1.8, 7, 5, 7.1, 0xb68f70, 0x4e5554],
[0, -1.7, 8, 5, 5.5, 0xd0b18c, 0x675b55],
[10.5, -1.8, 7, 5, 7.8, 0xa77e67, 0x465254],
[19, -1.5, 6, 5, 6.3, 0xc5a27f, 0x594f4a],
[-18, 17, 8, 6, 7.2, 0xb88e73, 0x4e5653],
[-8, 17.5, 8, 6, 6.1, 0xd0b087, 0x62574f],
[2, 17, 8, 6, 8.0, 0xb9826e, 0x4b5050],
[12, 17.5, 8, 6, 6.8, 0xc6a783, 0x574f4b],
[21, 17, 6, 6, 7.4, 0xa98772, 0x4a5352],
[-26, 7.5, 5, 8, 7.6, 0xb39b7b, 0x515956],
[26, 7.5, 5, 8, 7.2, 0xc3a582, 0x515452]
];
for (const building of buildings) {
buildBuilding(
group,
...building,
silhouette
);
}
parent.add(group);
return group;
}
function buildCastle(parent, silhouette = false) {
const group = new THREE.Group();
const stone = new THREE.MeshStandardMaterial({
color: 0xb8aa8c,
roughness: 0.92
});
const lightStone = new THREE.MeshStandardMaterial({
color: 0xcfc0a0,
roughness: 0.88
});
const darkStone = new THREE.MeshStandardMaterial({
color: 0x8e826c,
roughness: 0.95
});
const roof = new THREE.MeshStandardMaterial({
color: 0x555c5a,
roughness: 0.86
});
const silhouetteMaterial = new THREE.MeshBasicMaterial({
color: 0x151a18
});
function add(size, position, material = stone) {
const mesh = box(
group,
size,
position,
silhouette ? silhouetteMaterial : material,
!silhouette
);
if (!silhouette) {
castleMeshes.push(mesh);
}
return mesh;
}
// Ridge foundation and main mass.
add([18, 4, 2], [0, 14, -24.6], darkStone);
add([12, 6, 8], [0, 19, -29], stone);
add([12.7, 1.2, 8.7], [0, 22.2, -29], lightStone);
add([6, 10, 7], [-5, 21, -31], lightStone);
add([6.6, 1.1, 7.6], [-5, 26.2, -31], stone);
add([5, 7, 5], [5, 22.5, -30], stone);
add([5.6, 1, 5.6], [5, 26.2, -30], darkStone);
// Curtain walls and towers.
add([4, 7, 5], [-8.5, 19.5, -27], lightStone);
add([4, 7, 5], [8.5, 19.5, -27], lightStone);
add([17.5, 2.5, 1.3], [0, 17.25, -24.7], darkStone);
// Gate.
add([3.5, 3.3, 0.35], [0, 17.65, -23.95], roof);
// Small pitched roofs.
add([4.5, 1.1, 5.5], [5, 26.2, -30], roof);
add([3.5, 1, 4.5], [5, 27.25, -30], roof);
// Battlements.
for (let x = -8; x <= 8; x += 2) {
add([1.05, 1.25, 1.35], [x, 19, -24.0], lightStone);
}
for (let x = -7.4; x <= -2.6; x += 1.55) {
add([0.85, 1.1, 0.85], [x, 26.7, -27.5], lightStone);
add([0.85, 1.1, 0.85], [x, 26.7, -34.2], lightStone);
}
for (let x = -7.5; x <= 7.5; x += 1.5) {
add([0.75, 1.15, 0.75], [x, 26.75, -27.6], lightStone);
}
for (const x of [-8.5, 8.5]) {
add([4.6, 0.9, 5.6], [x, 23.4, -27], stone);
add([3.4, 0.9, 4.4], [x, 24.2, -27], stone);
}
if (!silhouette) {
const windowMaterial = new THREE.MeshBasicMaterial({
color: 0x303a36
});
box(
group,
[0.55, 1.25, 0.1],
[-5, 21, -27.45],
windowMaterial,
false
);
box(
group,
[0.55, 1.25, 0.1],
[5, 21.5, -27.45],
windowMaterial,
false
);
box(
group,
[0.55, 1.25, 0.1],
[-5, 25, -27.45],
windowMaterial,
false
);
}
parent.add(group);
return group;
}
function buildGrassmarketPaving(parent) {
const geometry = new THREE.BoxGeometry(1.8, 0.08, 1.8);
const material = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 1
});
const tiles = new THREE.InstancedMesh(geometry, material, 144);
tiles.receiveShadow = true;
const matrix = new THREE.Matrix4();
const color = new THREE.Color();
let index = 0;
for (let row = 0; row < 8; row++) {
for (let column = 0; column < 18; column++) {
const x = -20.2 + column * 2.35;
const z = 4.2 + row * 2.35;
matrix.makeTranslation(x, 0.06, z);
tiles.setMatrixAt(index, matrix);
const shade = 0.73 + ((row * 7 + column * 11) % 5) * 0.045;
color.setRGB(shade, shade * 0.96, shade * 0.84);
tiles.setColorAt(index, color);
index++;
}
}
parent.add(tiles);
}
function buildTree(parent, x, z, scale = 1) {
const group = new THREE.Group();
const trunkMaterial = new THREE.MeshStandardMaterial({
color: 0x685541,
roughness: 1
});
const leafMaterial = new THREE.MeshStandardMaterial({
color: 0x3e6552,
roughness: 1
});
box(group, [0.7 * scale, 3 * scale, 0.7 * scale],
[0, 1.5 * scale, 0], trunkMaterial);
box(group, [3.3 * scale, 2.6 * scale, 3.1 * scale],
[0, 4 * scale, 0], leafMaterial);
box(group, [2.5 * scale, 2.1 * scale, 2.4 * scale],
[0.2 * scale, 5.7 * scale, 0], leafMaterial);
group.position.set(x, 0, z);
parent.add(group);
}
buildTerrain(scene, false);
buildBuildings(scene, false);
buildCastle(scene, false);
buildGrassmarketPaving(scene);
buildTree(scene, -21, 21, 0.9);
buildTree(scene, 20, 21, 0.85);
buildTree(scene, -32, 1, 1.05);
buildTree(scene, 32, 1, 1.0);
// -------------------------------------------------------------------------
// Schematic voxel routes
// -------------------------------------------------------------------------
function buildRoute(path, color) {
const group = new THREE.Group();
const lineMaterial = new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.9
});
const lineGeometry = new THREE.BufferGeometry().setFromPoints(path);
const line = new THREE.Line(lineGeometry, lineMaterial);
group.add(line);
const markerMaterial = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.2,
roughness: 0.65
});
const markerGeometry = new THREE.BoxGeometry(0.36, 0.36, 0.36);
for (let i = 1; i < path.length; i++) {
const a = path[i - 1];
const b = path[i];
const length = a.distanceTo(b);
const count = Math.max(1, Math.floor(length / 1.35));
for (let j = 0; j < count; j++) {
const marker = new THREE.Mesh(markerGeometry, markerMaterial);
marker.position.copy(a).lerp(b, j / count);
marker.position.y += 0.18;
marker.castShadow = true;
group.add(marker);
}
}
scene.add(group);
return {
group,
lineMaterial,
markerMaterial
};
}
const routeVisuals = {
square: buildRoute(routePaths.square, routeMeta.square.color),
ridge: buildRoute(routePaths.ridge, routeMeta.ridge.color)
};
// Voxel walker.
const avatar = new THREE.Group();
const coatMaterial = new THREE.MeshStandardMaterial({
color: 0xef6844,
roughness: 0.75
});
const skinMaterial = new THREE.MeshStandardMaterial({
color: 0xe8b48d,
roughness: 0.9
});
const trouserMaterial = new THREE.MeshStandardMaterial({
color: 0x263b39,
roughness: 0.9
});
const body = box(avatar, [0.7, 1.05, 0.45], [0, 1.35, 0], coatMaterial);
const head = box(avatar, [0.5, 0.5, 0.5], [0, 2.12, 0], skinMaterial);
const leftLeg = box(avatar, [0.24, 0.72, 0.25], [-0.2, 0.48, 0], trouserMaterial);
const rightLeg = box(avatar, [0.24, 0.72, 0.25], [0.2, 0.48, 0], trouserMaterial);
body.castShadow = true;
head.castShadow = true;
scene.add(avatar);
const currentMarker = new THREE.Mesh(
new THREE.BoxGeometry(0.85, 0.85, 0.85),
new THREE.MeshBasicMaterial({ color: 0xffffff })
);
scene.add(currentMarker);
// -------------------------------------------------------------------------
// Map labels made from canvas textures
// -------------------------------------------------------------------------
function makeLabel(text, position, width = 12) {
const canvas = document.createElement("canvas");
canvas.width = 640;
canvas.height = 128;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(248,246,236,0.90)";
context.fillRect(18, 24, 604, 80);
context.strokeStyle = "rgba(23,33,29,0.20)";
context.lineWidth = 3;
context.strokeRect(18, 24, 604, 80);
context.fillStyle = "#25312c";
context.font = "700 32px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 320, 65);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.position.copy(position);
sprite.scale.set(width, width * 0.2, 1);
sprite.renderOrder = 20;
scene.add(sprite);
}
makeLabel("GRASSMARKET", new THREE.Vector3(0, 1.5, 13), 12);
makeLabel("EDINBURGH CASTLE", new THREE.Vector3(0, 29, -33), 15);
makeLabel("CASTLE RIDGE", new THREE.Vector3(-23, 14.5, -18), 10);
// -------------------------------------------------------------------------
// Silhouette renderer
// -------------------------------------------------------------------------
const silhouetteCanvas = document.querySelector("#silhouetteCanvas");
const silhouetteRenderer = new THREE.WebGLRenderer({
canvas: silhouetteCanvas,
antialias: true
});
silhouetteRenderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
silhouetteRenderer.outputColorSpace = THREE.SRGBColorSpace;
const silhouetteScene = new THREE.Scene();
silhouetteScene.background = new THREE.Color(0xf1eee3);
const silhouetteCamera = new THREE.PerspectiveCamera(40, 1, 0.1, 200);
buildTerrain(silhouetteScene, true);
buildBuildings(silhouetteScene, true);
buildCastle(silhouetteScene, true);
// A faint ground line helps the ridge and street levels read differently.
const horizonMaterial = new THREE.LineBasicMaterial({
color: 0xc5c3b8,
transparent: true,
opacity: 0.7
});
const horizonGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-100, 0, 0),
new THREE.Vector3(100, 0, 0)
]);
const horizon = new THREE.Line(horizonGeometry, horizonMaterial);
silhouetteScene.add(horizon);
function updateSilhouetteCamera() {
const distance = observerPosition.distanceTo(CASTLE_TARGET);
const desiredVerticalSpan = 18;
const fov = THREE.MathUtils.clamp(
2 * Math.atan(desiredVerticalSpan / (2 * Math.max(distance, 1))) *
180 / Math.PI,
20,
82
);
silhouetteCamera.position.copy(observerPosition);
silhouetteCamera.fov = fov;
silhouetteCamera.updateProjectionMatrix();
silhouetteCamera.lookAt(CASTLE_TARGET);
}
// -------------------------------------------------------------------------
// Visibility calculation
// -------------------------------------------------------------------------
const visibilityRaycaster = new THREE.Raycaster();
function castleSamplePoints(viewPosition) {
const samples = [];
for (const mesh of castleMeshes) {
mesh.updateWorldMatrix(true, false);
mesh.geometry.computeBoundingBox();
const bounds = mesh.geometry.boundingBox;
const size = new THREE.Vector3();
const center = new THREE.Vector3();
bounds.getSize(size);
bounds.getCenter(center);
center.add(mesh.position);
const faces = [
{
n: new THREE.Vector3(1, 0, 0),
fixed: "maxX",
u: "y",
v: "z"
},
{
n: new THREE.Vector3(-1, 0, 0),
fixed: "minX",
u: "y",
v: "z"
},
{
n: new THREE.Vector3(0, 1, 0),
fixed: "maxY",
u: "x",
v: "z"
},
{
n: new THREE.Vector3(0, -1, 0),
fixed: "minY",
u: "x",
v: "z"
},
{
n: new THREE.Vector3(0, 0, 1),
fixed: "maxZ",
u: "x",
v: "y"
},
{
n: new THREE.Vector3(0, 0, -1),
fixed: "minZ",
u: "x",
v: "y"
}
];
for (const face of faces) {
const faceCenter = center.clone();
const axis = face.n.x !== 0 ? "x" : face.n.y !== 0 ? "y" : "z";
if (face.fixed.startsWith("max")) {
faceCenter[axis] += size[axis] / 2;
} else {
faceCenter[axis] -= size[axis] / 2;
}
const toObserver = viewPosition.clone().sub(faceCenter);
if (face.n.dot(toObserver) <= 0.04) continue;
const uCount = Math.min(4, Math.max(2, Math.ceil(size[face.u] / 1.8)));
const vCount = Math.min(4, Math.max(2, Math.ceil(size[face.v] / 1.8)));
for (let u = 0; u < uCount; u++) {
for (let v = 0; v < vCount; v++) {
const point = faceCenter.clone();
point[face.u] =
bounds.min[face.u] +
((u + 0.5) / uCount) * size[face.u];
point[face.v] =
bounds.min[face.v] +
((v + 0.5) / vCount) * size[face.v];
samples.push(point);
}
}
}
}
return samples;
}
function calculateVisibility() {
const samples = castleSamplePoints(observerPosition);
const sourceCounts = new Map();
let visible = 0;
for (const point of samples) {
const direction = point.clone().sub(observerPosition);
const targetDistance = direction.length();
direction.normalize();
visibilityRaycaster.set(observerPosition, direction);
visibilityRaycaster.near = 0.04;
visibilityRaycaster.far = Math.max(0.05, targetDistance - 0.08);
const hits = visibilityRaycaster.intersectObjects(blockers, false);
if (hits.length > 0) {
const source = hits[0].object.userData.occluder || "Intervening geometry";
sourceCounts.set(source, (sourceCounts.get(source) || 0) + 1);
} else {
visible++;
}
}
const percentage = samples.length
? Math.round((visible / samples.length) * 100)
: 0;
let mainSource = "";
let mainCount = 0;
for (const [source, count] of sourceCounts) {
if (count > mainCount) {
mainCount = count;
mainSource = source;
}
}
return {
percentage,
mainSource,
mainCount,
samples: samples.length
};
}
// -------------------------------------------------------------------------
// Route and measurement updates
// -------------------------------------------------------------------------
function updateRouteAppearance() {
for (const key of Object.keys(routeVisuals)) {
const active = key === state.route;
const visual = routeVisuals[key];
visual.lineMaterial.color.setHex(
active ? routeMeta[key].color : 0x8d9890
);
visual.lineMaterial.opacity = active ? 0.95 : 0.22;
visual.markerMaterial.color.setHex(
active ? routeMeta[key].color : 0x9aa39b
);
visual.markerMaterial.emissive.setHex(
active ? routeMeta[key].color : 0x000000
);
visual.markerMaterial.emissiveIntensity = active ? 0.23 : 0;
}
}
function updateMeasurements() {
const route = routePaths[state.route];
const sample = sampleRoute(route, state.progress);
observerPosition.copy(sample.position);
observerPosition.y += EYE_HEIGHT;
const visibility = calculateVisibility();
const distance = observerPosition.distanceTo(CASTLE_TARGET);
const walked = state.progress * routeLengths[state.route];
heightValue.textContent = `${observerPosition.y.toFixed(1)} m`;
heightNote.textContent =
`${sample.position.y.toFixed(1)} m ground · 1.7 m eye height`;
distanceValue.textContent = `${distance.toFixed(1)} m`;
visibleValue.textContent = `${visibility.percentage}%`;
if (visibility.mainCount > 0) {
const masked = Math.round(
(visibility.mainCount / Math.max(1, visibility.samples)) * 100
);
visibleNote.textContent = `${visibility.mainSource} mask ${masked}%`;
} else {
visibleNote.textContent = "No major intervening geometry";
}
walkedValue.textContent = `${walked.toFixed(0)} m`;
walkedNote.textContent = routeMeta[state.route].label;
progressValue.textContent = `${Math.round(state.progress * 100)}%`;
progressInput.value = Math.round(state.progress * 1000);
avatar.position.copy(sample.position);
avatar.rotation.y = Math.atan2(
CASTLE_TARGET.x - sample.position.x,
CASTLE_TARGET.z - sample.position.z
);
currentMarker.position.copy(sample.position);
currentMarker.position.y += 0.7;
currentMarker.rotation.y += 0.02;
silhouetteBadge.textContent = routeMeta[state.route].label;
updateSilhouetteCamera();
if (state.cameraMode === "eye") {
aimEyeAtCastle();
updateEyeCamera();
}
}
// -------------------------------------------------------------------------
// UI events
// -------------------------------------------------------------------------
document.querySelectorAll(".route-tab").forEach((button) => {
button.addEventListener("click", () => {
state.route = button.dataset.route;
document.querySelectorAll(".route-tab").forEach((tab) => {
tab.setAttribute(
"aria-pressed",
String(tab.dataset.route === state.route)
);
});
updateRouteAppearance();
updateMeasurements();
});
});
progressInput.addEventListener("input", () => {
state.progress = Number(progressInput.value) / 1000;
state.playing = false;
playButton.textContent = "▶ Walk";
updateMeasurements();
});
playButton.addEventListener("click", () => {
if (!state.playing && state.progress >= 0.999) {
state.progress = 0;
}
state.playing = !state.playing;
playButton.textContent = state.playing ? "❚❚ Pause" : "▶ Walk";
});
function setCameraMode(mode) {
state.cameraMode = mode;
overviewButton.classList.toggle("active", mode === "overview");
eyeButton.classList.toggle("active", mode === "eye");
if (mode === "overview") {
camera.fov = 42;
camera.updateProjectionMatrix();
updateOverviewCamera();
} else {
aimEyeAtCastle();
updateEyeCamera();
}
}
overviewButton.addEventListener("click", () => setCameraMode("overview"));
eyeButton.addEventListener("click", () => setCameraMode("eye"));
// -------------------------------------------------------------------------
// Resize and animation
// -------------------------------------------------------------------------
function resize() {
const width = stage.clientWidth;
const height = stage.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / Math.max(height, 1);
camera.updateProjectionMatrix();
const silhouetteWidth = silhouetteCanvas.clientWidth;
const silhouetteHeight = silhouetteCanvas.clientHeight;
silhouetteRenderer.setSize(
silhouetteWidth,
silhouetteHeight,
false
);
silhouetteCamera.aspect =
silhouetteWidth / Math.max(silhouetteHeight, 1);
silhouetteCamera.updateProjectionMatrix();
}
window.addEventListener("resize", resize);
const clock = new THREE.Clock();
let lastTime = 0;
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
const delta = Math.min(0.05, elapsed - lastTime);
lastTime = elapsed;
if (state.playing) {
state.progress += delta / 34;
if (state.progress >= 1) {
state.progress = 1;
state.playing = false;
playButton.textContent = "▶ Walk";
}
updateMeasurements();
}
const walkBob = state.playing
? Math.sin(elapsed * 11) * 0.08
: 0;
leftLeg.position.y = 0.48 + walkBob;
rightLeg.position.y = 0.48 - walkBob;
currentMarker.rotation.x += 0.01;
currentMarker.rotation.z += 0.007;
if (state.cameraMode === "overview") {
updateOverviewCamera();
} else {
updateEyeCamera();
}
renderer.render(scene, camera);
silhouetteRenderer.render(silhouetteScene, silhouetteCamera);
}
updateRouteAppearance();
updateMeasurements();
updateOverviewCamera();
resize();
animate();
</script>
</body>
</html>
```