Prompt specification
Build or customize the Three.js 3D scene "Compare rebuilding layouts after the Lisbon disaster" 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 rebuilding layouts after the Lisbon disaster
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/compare-rebuilding-layouts-after-the-lisbon-disaster-x2440
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring a voxel comparison of rebuilding layouts after the Lisbon disaster. Present two small street-network models on adjacent tables, with buildings, public spaces, and entrances represented consistently. Base the historical planning principles on references and label any alternative arrangement as a hypothetical comparison rather than a documented outcome. Let users inspect street widths, count connected routes between selected points, and trace paths through each model. Keep building heights and the comparison area similar so differences in network organization remain visible. Use a restrained historical presentation without graphic destruction or invented eyewitness scenes.
Working Three.js Starter (compare-rebuilding-layouts-after-the-lisbon-disaster-x2440):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>After 1755 Lisbon — Voxel Street-Network Comparison</title>
<style>
:root {
--paper: #eee8dc;
--paper-deep: #e3dbc9;
--ink: #292a27;
--muted: #6f6c61;
--line: #c9c0ae;
--accent: #9a6043;
--gold: #c49338;
--teal: #397572;
--slate: #454b4c;
--sage: #929e82;
--cream: #d8c8a8;
--panel: rgba(247, 243, 234, 0.96);
}
* { box-sizing: border-box; }
html, body {
margin: 0;
min-height: 100%;
color: var(--ink);
background: var(--paper);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
display: grid;
grid-template-columns: 300px minmax(460px, 1fr) 330px;
grid-template-rows: 78px minmax(0, 1fr) 54px;
height: 100vh;
overflow: hidden;
}
header {
grid-column: 1 / -1;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 12px 22px;
border-bottom: 1px solid var(--line);
background: rgba(247, 243, 234, 0.97);
z-index: 5;
}
header h1 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(20px, 2vw, 29px);
font-weight: 500;
letter-spacing: 0.01em;
}
header p {
margin: 4px 0 0;
color: var(--muted);
font-size: 12px;
}
.badges {
display: flex;
gap: 7px;
flex-wrap: wrap;
justify-content: flex-end;
}
.badge {
padding: 5px 8px;
border: 1px solid var(--line);
border-radius: 999px;
color: #5f5b52;
background: #f3eee4;
font-size: 10px;
font-weight: 650;
letter-spacing: 0.04em;
text-transform: uppercase;
white-space: nowrap;
}
.badge.alert {
color: #7c512e;
border-color: #c89b62;
background: #f3e7d5;
}
#viewport {
position: relative;
grid-column: 2;
grid-row: 2;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #e8e1d3;
border-right: 1px solid var(--line);
border-left: 1px solid var(--line);
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#viewport canvas:active { cursor: grabbing; }
.viewport-note {
position: absolute;
left: 14px;
bottom: 13px;
z-index: 2;
max-width: calc(100% - 28px);
padding: 7px 10px;
border: 1px solid rgba(108, 102, 90, 0.28);
border-radius: 4px;
background: rgba(245, 240, 229, 0.84);
color: #625f57;
font-size: 10px;
line-height: 1.45;
pointer-events: none;
backdrop-filter: blur(4px);
}
.panel {
min-height: 0;
overflow-y: auto;
padding: 18px;
background: var(--panel);
scrollbar-width: thin;
scrollbar-color: #b9af9c transparent;
}
#controls {
grid-column: 1;
grid-row: 2;
border-right: 1px solid var(--line);
}
#results {
grid-column: 3;
grid-row: 2;
border-left: 1px solid var(--line);
}
.eyebrow {
margin: 0 0 6px;
color: var(--accent);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.13em;
text-transform: uppercase;
}
h2 {
margin: 0 0 9px;
font-family: Georgia, "Times New Roman", serif;
font-size: 21px;
font-weight: 500;
}
h3 {
margin: 0 0 7px;
font-size: 11px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
p {
margin: 0 0 12px;
color: #5f5d55;
font-size: 12px;
line-height: 1.55;
}
.section {
padding: 14px 0;
border-top: 1px solid var(--line);
}
.section:first-of-type {
border-top: 0;
padding-top: 2px;
}
.segmented {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 5px;
margin-bottom: 12px;
}
.segmented.three {
grid-template-columns: 1fr 1fr 1fr;
}
button {
appearance: none;
border: 1px solid #bcb3a2;
border-radius: 4px;
padding: 9px 8px;
color: #514e46;
background: #eee8dd;
font: inherit;
font-size: 11px;
font-weight: 650;
cursor: pointer;
transition: background 140ms ease, border-color 140ms ease, color 140ms ease;
}
button:hover {
border-color: #9e927e;
background: #e6ddce;
}
button.active {
color: #fffaf0;
border-color: var(--slate);
background: var(--slate);
}
button.primary {
width: 100%;
margin-top: 9px;
color: #fffaf0;
border-color: var(--teal);
background: var(--teal);
}
button.secondary {
width: 100%;
margin-top: 6px;
}
button:focus-visible,
a:focus-visible {
outline: 2px solid var(--teal);
outline-offset: 2px;
}
.selection-list {
display: grid;
gap: 6px;
margin: 10px 0;
}
.selection {
display: flex;
align-items: center;
gap: 9px;
padding: 8px 9px;
border: 1px solid var(--line);
border-radius: 4px;
background: rgba(255, 255, 255, 0.28);
font-size: 11px;
}
.selection strong {
font-size: 11px;
font-weight: 700;
}
.marker-disc {
display: inline-grid;
place-items: center;
width: 21px;
height: 21px;
flex: 0 0 auto;
border-radius: 50%;
color: white;
font-size: 10px;
font-weight: 800;
}
.marker-disc.source { background: var(--gold); }
.marker-disc.target { background: var(--teal); }
.waypoints {
min-height: 24px;
margin: 6px 0 10px;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.waypoints span {
display: inline-block;
margin: 2px 4px 2px 0;
padding: 3px 6px;
border: 1px solid #c7bca8;
border-radius: 999px;
background: #f4eee2;
color: #5d594f;
}
.model-card {
margin-top: 9px;
padding: 11px;
border: 1px solid var(--line);
border-left: 4px solid #8b9183;
border-radius: 4px;
background: rgba(255, 255, 255, 0.22);
}
.model-card.active {
border-left-color: var(--gold);
background: rgba(255, 255, 255, 0.42);
}
.model-card.alternative {
border-left-color: var(--accent);
}
.model-card h4 {
margin: 0 0 6px;
font-size: 12px;
line-height: 1.35;
}
.model-card p {
margin: 0;
font-size: 11px;
}
.status-line {
margin-top: 7px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 11px;
}
th, td {
padding: 9px 5px;
border-bottom: 1px solid var(--line);
text-align: right;
vertical-align: top;
}
th:first-child, td:first-child {
text-align: left;
}
th {
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.05em;
text-transform: uppercase;
}
td strong {
font-family: Georgia, "Times New Roman", serif;
font-size: 20px;
font-weight: 500;
}
.metric-note {
margin-top: 8px;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.inspector {
min-height: 74px;
padding: 11px;
border: 1px solid var(--line);
border-radius: 4px;
background: rgba(255, 255, 255, 0.25);
}
.inspector .big {
margin: 5px 0 2px;
color: var(--ink);
font-family: Georgia, "Times New Roman", serif;
font-size: 23px;
}
.inspector .small {
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.trace-status {
margin-top: 10px;
padding: 10px;
border-left: 3px solid var(--teal);
background: #e3ece6;
color: #45625c;
font-size: 11px;
line-height: 1.5;
}
details {
margin-top: 10px;
font-size: 11px;
}
summary {
cursor: pointer;
color: #504d46;
font-weight: 700;
}
details p,
details ul {
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
details ul {
padding-left: 17px;
}
a {
color: #416c69;
text-decoration-thickness: 1px;
text-underline-offset: 2px;
}
#legend {
grid-column: 1 / -1;
grid-row: 3;
display: flex;
align-items: center;
justify-content: center;
gap: 19px;
padding: 8px 16px;
border-top: 1px solid var(--line);
background: #f4efe5;
color: #666258;
font-size: 10px;
z-index: 5;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
white-space: nowrap;
}
.swatch {
width: 12px;
height: 12px;
border: 1px solid rgba(0, 0, 0, 0.14);
border-radius: 2px;
}
.swatch.road { background: #454b4c; }
.swatch.building { background: #c3b397; }
.swatch.space { background: #929e82; }
.swatch.entrance { background: #d3a43e; }
.swatch.source { background: #c49338; border-radius: 50%; }
.swatch.target { background: #397572; border-radius: 50%; }
#tooltip {
position: fixed;
z-index: 20;
display: none;
max-width: 250px;
padding: 7px 9px;
border: 1px solid #b8ae9c;
border-radius: 4px;
color: #3f3d37;
background: rgba(250, 247, 239, 0.96);
box-shadow: 0 5px 18px rgba(45, 39, 29, 0.13);
font-size: 10px;
line-height: 1.45;
pointer-events: none;
}
#loading {
position: absolute;
inset: 0;
display: grid;
place-items: center;
color: #625d53;
background: #e8e1d3;
font-family: Georgia, "Times New Roman", serif;
font-size: 16px;
z-index: 8;
}
@media (max-width: 1120px) {
body {
grid-template-columns: 265px minmax(390px, 1fr) 285px;
}
.panel { padding: 14px; }
}
@media (max-width: 850px) {
body {
display: grid;
grid-template-columns: 1fr;
grid-template-rows: auto 58vh auto auto;
height: auto;
min-height: 100vh;
overflow: auto;
}
header {
grid-column: 1;
grid-row: 1;
align-items: flex-start;
flex-direction: column;
gap: 9px;
}
.badges { justify-content: flex-start; }
#viewport {
grid-column: 1;
grid-row: 2;
border: 0;
border-bottom: 1px solid var(--line);
}
#controls {
grid-column: 1;
grid-row: 3;
overflow: visible;
border: 0;
}
#results {
grid-column: 1;
grid-row: 4;
overflow: visible;
border: 0;
}
#legend {
position: fixed;
left: 0;
right: 0;
bottom: 0;
flex-wrap: wrap;
gap: 8px 14px;
}
body { padding-bottom: 54px; }
}
@media (prefers-reduced-motion: reduce) {
* { transition: none !important; }
}
</style>
</head>
<body>
<header>
<div>
<h1>After the 1755 Lisbon earthquake</h1>
<p>A voxel comparison of street-network organization — reconstruction logic and a hypothetical counterfactual</p>
</div>
<div class="badges">
<span class="badge">Schematic, not cadastral</span>
<span class="badge">No destruction imagery</span>
<span class="badge alert">Alternative is hypothetical</span>
</div>
</header>
<aside id="controls" class="panel">
<p class="eyebrow">Interactive study</p>
<h2>Inspect and compare</h2>
<p>
Select a numbered junction in either model. Corresponding point numbers refer to
the same analytical location across both networks.
</p>
<div class="section">
<h3>Model under inspection</h3>
<div class="segmented">
<button id="active-reference" class="active">Reference-based</button>
<button id="active-alternative">Hypothetical</button>
</div>
<h3>Selection action</h3>
<div class="segmented three">
<button id="pick-source" class="active">Start</button>
<button id="pick-target">End</button>
<button id="pick-waypoint">Waypoint</button>
</div>
<div class="selection-list">
<div class="selection">
<span class="marker-disc source">S</span>
<strong id="source-label">Point 01</strong>
</div>
<div class="selection">
<span class="marker-disc target">T</span>
<strong id="target-label">Point 16</strong>
</div>
</div>
<div id="waypoints" class="waypoints">Waypoints: none</div>
<button id="trace-button" class="primary">Trace shortest path in both models</button>
<button id="clear-waypoints" class="secondary">Clear waypoints</button>
<div id="trace-status" class="status-line">
Trace the direct shortest route, or add waypoints before tracing.
</div>
</div>
<div class="section">
<div id="reference-note" class="model-card active">
<h4>Reference-based reconstruction logic</h4>
<p>
A schematic regular block system, differentiated street hierarchy and civic
open space condense themes associated with the 1758 rebuilding plans of
Manuel da Maia and the Mardel engraving. It is not a reconstruction of a
specific Lisbon district.
</p>
</div>
<div id="alternative-note" class="model-card alternative">
<h4>Hypothetical alternative — not a documented outcome</h4>
<p>
Irregular alignments, varied widths and two omitted links form a deliberate
counterfactual. This arrangement was not a documented plan, proposal or
historical result.
</p>
</div>
</div>
<div class="section">
<details>
<summary>Reference basis and reading notes</summary>
<p>
The reference model reads the rebuilding drawings at the level of street
hierarchy, legible alignments, regularized blocks and civic space. The
widths shown are illustrative schematic metres, not measured widths from
a parcel or street survey.
</p>
<p>
The timber-cage <em>gaiola pombalina</em> is a construction system rather
than a street-network rule, so it is not modeled here. Neutral voxel masses
keep building height and comparison area similar.
</p>
<ul>
<li>
Manuel da Maia,
<em>Plano de reconstrução da cidade de Lisboa</em> (1758), and
Carlos Mardel’s reconstruction plan/engraving.
</li>
<li>
<a href="https://www.britannica.com/place/Lisbon/Expansion-and-rebuilding"
target="_blank" rel="noopener noreferrer">
Encyclopaedia Britannica: Lisbon — expansion and rebuilding
</a>
</li>
<li>
<a href="https://bibliotecadigital.bnportugal.gov.pt/"
target="_blank" rel="noopener noreferrer">
Biblioteca Nacional de Portugal digital collections
</a>
</li>
<li>
<a href="https://www.am-lisboa.pt/"
target="_blank" rel="noopener noreferrer">
Arquivo Municipal de Lisboa
</a>
</li>
</ul>
<p>
The numbered junctions, blocks and square are analytical abstractions.
They should not be read as a historical map.
</p>
</details>
</div>
</aside>
<main id="viewport" aria-label="Interactive 3D comparison of two Lisbon street-network models">
<div id="loading">Preparing the comparison models…</div>
<div class="viewport-note">
Drag to orbit · Wheel to zoom · Right-drag to pan · Click a numbered junction
or street segment
</div>
</main>
<aside id="results" class="panel">
<p class="eyebrow">Network comparison</p>
<h2>Routes and street sections</h2>
<div class="section">
<h3>Connected routes</h3>
<table aria-label="Connected route counts">
<thead>
<tr>
<th>Network</th>
<th>Routes</th>
<th>Shortest</th>
</tr>
</thead>
<tbody>
<tr>
<td>Reference-based</td>
<td><strong id="reference-route-count">—</strong></td>
<td id="reference-shortest">—</td>
</tr>
<tr>
<td>Hypothetical</td>
<td><strong id="alternative-route-count">—</strong></td>
<td id="alternative-shortest">—</td>
</tr>
</tbody>
</table>
<div class="metric-note">
“Routes” counts every unique simple path between the selected points:
no junction or street segment is repeated. “Shortest” gives the number of
segments in the minimum path.
</div>
</div>
<div class="section">
<h3>Street-width inspector</h3>
<div id="width-inspector" class="inspector">
<div class="small">Move the pointer over a street segment.</div>
<div class="big">—</div>
<div class="small">A dimension line appears on the selected model.</div>
</div>
<div class="metric-note">
Widths are schematic translations of a street hierarchy, not surveyed
dimensions. The two models use the same visual scale.
</div>
</div>
<div class="section">
<h3>How to read the models</h3>
<p>
Both tables use the same footprint, similar building heights and the same
symbols. Their principal differences are street alignment, street width,
block regularity, civic-space form and connectivity.
</p>
<p>
The reference model is based on themes visible in historical rebuilding
plans. The adjacent model is explicitly hypothetical and must not be read
as an actual Lisbon proposal or outcome.
</p>
</div>
<div class="section">
<h3>Historical restraint</h3>
<p>
The scene begins with post-event rebuilding principles. It contains no
collapsing structures, fire, tsunami depiction, bodies, disaster spectacle
or invented eyewitness scene.
</p>
</div>
</aside>
<footer id="legend">
<span class="legend-item"><span class="swatch road"></span>Street</span>
<span class="legend-item"><span class="swatch building"></span>Voxel building</span>
<span class="legend-item"><span class="swatch space"></span>Public space</span>
<span class="legend-item"><span class="swatch entrance"></span>Entrance</span>
<span class="legend-item"><span class="swatch source"></span>Start point</span>
<span class="legend-item"><span class="swatch target"></span>End point</span>
</footer>
<div id="tooltip" role="status"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const viewport = document.getElementById("viewport");
const tooltip = document.getElementById("tooltip");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe8e1d3);
scene.fog = new THREE.Fog(0xe8e1d3, 42, 78);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
viewport.prepend(renderer.domElement);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 150);
const cameraTarget = new THREE.Vector3(0, 0.85, 0);
const spherical = new THREE.Spherical(35, 1.02, 0.18);
let viewInitialized = false;
scene.add(new THREE.HemisphereLight(0xfff7e8, 0x8b8a80, 2.05));
const sun = new THREE.DirectionalLight(0xfff0d6, 3.1);
sun.position.set(-12, 20, 10);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -18;
sun.shadow.camera.right = 18;
sun.shadow.camera.top = 14;
sun.shadow.camera.bottom = -14;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 55;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xc9dce2, 0.75);
fill.position.set(14, 10, -12);
scene.add(fill);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(90, 90),
new THREE.MeshStandardMaterial({
color: 0xded6c7,
roughness: 1,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.03;
ground.receiveShadow = true;
scene.add(ground);
const pickables = [];
const models = {};
const pointName = id => `Point ${String(id + 1).padStart(2, "0")}`;
const referenceNodes = [
[-4.5, -3.75], [-1.5, -3.75], [1.5, -3.75], [4.5, -3.75],
[-4.5, -1.25], [-1.5, -1.25], [1.5, -1.25], [4.5, -1.25],
[-4.5, 1.25], [-1.5, 1.25], [1.5, 1.25], [4.5, 1.25],
[-4.5, 3.75], [-1.5, 3.75], [1.5, 3.75], [4.5, 3.75]
];
const alternativeNodes = [
[-4.55, -3.55], [-1.75, -3.75], [1.35, -3.45], [4.45, -3.60],
[-4.65, -1.05], [-1.65, -1.35], [1.55, -1.10], [4.55, -1.25],
[-4.35, 1.25], [-1.70, 1.50], [1.40, 1.15], [4.40, 1.35],
[-4.50, 3.65], [-1.45, 3.80], [1.55, 3.50], [4.55, 3.70]
];
const referenceEdges = [];
const horizontalWidths = [12, 20, 15, 12];
const verticalWidths = [14, 24, 16, 12];
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 3; col++) {
const width = horizontalWidths[row];
referenceEdges.push({
id: `R-H${row}-${col}`,
a: row * 4 + col,
b: row * 4 + col + 1,
width,
class: width >= 20 ? "principal street" :
width >= 15 ? "secondary street" : "local street"
});
}
}
for (let col = 0; col < 4; col++) {
for (let row = 0; row < 3; row++) {
const width = verticalWidths[col];
referenceEdges.push({
id: `R-V${col}-${row}`,
a: row * 4 + col,
b: (row + 1) * 4 + col,
width,
class: width >= 20 ? "principal street" :
width >= 15 ? "secondary street" : "local street"
});
}
}
const alternativeEdges = [];
const altHorizontal = [
[11, 13, 10],
[9, 18, 12],
[13, 15, 9],
[10, 14, 12]
];
const altVertical = [
[12, 11, 13],
[15, 14, 18],
[12, 13, 11],
[10, 12, 14]
];
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 3; col++) {
const width = altHorizontal[row][col];
alternativeEdges.push({
id: `H-H${row}-${col}`,
a: row * 4 + col,
b: row * 4 + col + 1,
width,
class: width >= 18 ? "broad connector" :
width >= 14 ? "medium connector" : "narrow local street"
});
}
}
for (let col = 0; col < 4; col++) {
for (let row = 0; row < 3; row++) {
// Two deliberate omissions create a less-connected counterfactual.
if ((col === 1 && row === 2) || (col === 3 && row === 2)) continue;
const width = altVertical[col][row];
alternativeEdges.push({
id: `H-V${col}-${row}`,
a: row * 4 + col,
b: (row + 1) * 4 + col,
width,
class: width >= 18 ? "broad connector" :
width >= 14 ? "medium connector" : "narrow local street"
});
}
}
function makeAdjacency(edges) {
const adjacency = Array.from({ length: 16 }, () => []);
for (const edge of edges) {
adjacency[edge.a].push({ to: edge.b, edge });
adjacency[edge.b].push({ to: edge.a, edge });
}
return adjacency;
}
function hash01(a, b, c = 0) {
const n = Math.sin(a * 127.1 + b * 311.7 + c * 74.7) * 43758.5453;
return n - Math.floor(n);
}
function createTexture(canvas) {
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
return texture;
}
function makeTextSprite(text, options = {}) {
const {
width = 768,
height = 160,
background = "#303331",
foreground = "#f4ecdb",
accent = null,
fontSize = 52,
subtitle = null
} = options;
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, width, height);
ctx.fillStyle = background;
ctx.fillRect(0, 0, width, height);
if (accent) {
ctx.fillStyle = accent;
ctx.fillRect(0, 0, 15, height);
}
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = foreground;
ctx.font = `600 ${fontSize}px Georgia, serif`;
ctx.fillText(text, width / 2, subtitle ? height * 0.40 : height / 2);
if (subtitle) {
ctx.fillStyle = "#c9c0af";
ctx.font = `500 ${Math.round(fontSize * 0.38)}px system-ui, sans-serif`;
ctx.fillText(subtitle, width / 2, height * 0.72);
}
const texture = createTexture(canvas);
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.renderOrder = 20;
return sprite;
}
function makeNumberSprite(number) {
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 96;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, 128, 96);
ctx.beginPath();
ctx.arc(64, 48, 30, 0, Math.PI * 2);
ctx.fillStyle = "#f1eadc";
ctx.fill();
ctx.lineWidth = 4;
ctx.strokeStyle = "#6f716a";
ctx.stroke();
ctx.fillStyle = "#303330";
ctx.font = "700 29px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(String(number + 1).padStart(2, "0"), 64, 49);
const texture = createTexture(canvas);
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
}));
sprite.scale.set(0.55, 0.41);
sprite.renderOrder = 15;
return sprite;
}
function box(width, height, depth, material, x, y, z) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(width, height, depth), material);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
function orientSegment(mesh, a, b) {
const dx = b[0] - a[0];
const dz = b[1] - a[1];
const length = Math.hypot(dx, dz);
mesh.position.set((a[0] + b[0]) / 2, mesh.position.y, (a[1] + b[1]) / 2);
mesh.rotation.y = Math.atan2(-dz, dx);
return length;
}
function pointToSegmentDistance(point, a, b) {
const abx = b[0] - a[0];
const abz = b[1] - a[1];
const apx = point[0] - a[0];
const apz = point[1] - a[1];
const lengthSq = abx * abx + abz * abz;
const t = lengthSq ? THREE.MathUtils.clamp((apx * abx + apz * abz) / lengthSq, 0, 1) : 0;
const qx = a[0] + abx * t;
const qz = a[1] + abz * t;
return {
distance: Math.hypot(point[0] - qx, point[1] - qz),
closest: [qx, qz]
};
}
function clearGroup(group) {
while (group.children.length) {
const child = group.children.pop();
child.traverse(object => {
if (object.geometry) object.geometry.dispose();
});
}
}
function addTree(group, x, z, materials, baseY = 0.84) {
const trunk = box(
0.13, 0.36, 0.13, materials.trunk,
x, baseY + 0.18, z
);
const crown = box(
0.43, 0.43, 0.43, materials.tree,
x, baseY + 0.55, z
);
group.add(trunk, crown);
}
function addEntranceAndWindows(group, width, depth, height, side, sign, materials) {
const doorHeight = Math.min(0.29, height * 0.45);
const doorY = doorHeight / 2 + 0.015;
if (side === "x") {
const door = box(
0.055, doorHeight, 0.16, materials.entrance,
sign * (width / 2 + 0.028), doorY, 0
);
group.add(door);
const step = box(
0.13, 0.045, 0.22, materials.stone,
sign * (width / 2 + 0.055), 0.025, 0
);
group.add(step);
const windowY = Math.min(height - 0.12, Math.max(0.34, height * 0.57));
for (const offset of [-depth * 0.20, depth * 0.20]) {
group.add(box(
0.035, 0.13, 0.14, materials.window,
sign * (width / 2 + 0.020), windowY, offset
));
}
} else {
const door = box(
0.16, doorHeight, 0.055, materials.entrance,
0, doorY, sign * (depth / 2 + 0.028)
);
group.add(door);
const step = box(
0.22, 0.045, 0.13, materials.stone,
0, 0.025, sign * (depth / 2 + 0.055)
);
group.add(step);
const windowY = Math.min(height - 0.12, Math.max(0.34, height * 0.57));
for (const offset of [-width * 0.20, width * 0.20]) {
group.add(box(
0.14, 0.13, 0.035, materials.window,
offset, windowY, sign * (depth / 2 + 0.020)
));
}
}
}
function createBuildings(modelData, group, materials) {
const baseY = 0.83;
const cells = [];
for (let row = 0; row < 3; row++) {
for (let col = 0; col < 3; col++) {
const ids = {
a: row * 4 + col,
b: row * 4 + col + 1,
c: (row + 1) * 4 + col + 1,
d: (row + 1) * 4 + col
};
const A = modelData.nodes[ids.a];
const B = modelData.nodes[ids.b];
const C = modelData.nodes[ids.c];
const D = modelData.nodes[ids.d];
const center = [
(A[0] + B[0] + C[0] + D[0]) / 4,
(A[1] + B[1] + C[1] + D[1]) / 4
];
const u = [
((B[0] - A[0]) + (C[0] - D[0])) / 2,
((B[1] - A[1]) + (C[1] - D[1])) / 2
];
const v = [
((D[0] - A[0]) + (C[0] - B[0])) / 2,
((D[1] - A[1]) + (C[1] - B[1])) / 2
];
const uLen = Math.hypot(u[0], u[1]);
const vLen = Math.hypot(v[0], v[1]);
const uN = [u[0] / uLen, u[1] / uLen];
const vN = [v[0] / vLen, v[1] / vLen];
cells.push({ row, col, ids, center, u, v, uLen, vLen, uN, vN });
}
}
for (const cell of cells) {
// The central block is a civic space in both models.
if (cell.row === 1 && cell.col === 1) continue;
const edgeCandidates = [
{ a: cell.ids.a, b: cell.ids.b, p: modelData.nodes[cell.ids.a], q: modelData.nodes[cell.ids.b] },
{ a: cell.ids.b, b: cell.ids.c, p: modelData.nodes[cell.ids.b], q: modelData.nodes[cell.ids.c] },
{ a: cell.ids.d, b: cell.ids.c, p: modelData.nodes[cell.ids.d], q: modelData.nodes[cell.ids.c] },
{ a: cell.ids.a, b: cell.ids.d, p: modelData.nodes[cell.ids.a], q: modelData.nodes[cell.ids.d] }
].filter(candidate =>
modelData.edges.some(edge =>
(edge.a === candidate.a && edge.b === candidate.b) ||
(edge.a === candidate.b && edge.b === candidate.a)
)
);
for (let sx = -1; sx <= 1; sx += 2) {
for (let sz = -1; sz <= 1; sz += 2) {
const lotIndex = (sx + 1) * 2 + (sz + 1);
const x = cell.center[0] + cell.uN[0] * sx * cell.uLen * 0.22 +
cell.vN[0] * sz * cell.vLen * 0.22;
const z = cell.center[1] + cell.uN[1] * sx * cell.uLen * 0.22 +
cell.vN[1] * sz * cell.vLen * 0.22;
const width = cell.uLen * 0.28;
const depth = cell.vLen * 0.28;
const height = 0.67 + hash01(cell.row, cell.col, lotIndex) * 0.72;
const building = new THREE.Group();
building.position.set(x, baseY, z);
building.rotation.y = Math.atan2(-cell.u[1], cell.u[0]);
const materialIndex = Math.floor(hash01(cell.row + 5, cell.col + 7, lotIndex) * materials.buildings.length);
const mass = box(width, height, depth, materials.buildings[materialIndex], 0, height / 2, 0);
building.add(mass);
building.add(box(
width + 0.045, 0.055, depth + 0.045, materials.roofs[materialIndex],
0, height + 0.028, 0
));
let closest = null;
for (const candidate of edgeCandidates) {
const result = pointToSegmentDistance([x, z], candidate.p, candidate.q);
if (!closest || result.distance < closest.result.distance) {
closest = { candidate, result };
}
}
if (closest) {
const outward = [
closest.result.closest[0] - x,
closest.result.closest[1] - z
];
const length = Math.hypot(outward[0], outward[1]) || 1;
outward[0] /= length;
outward[1] /= length;
const angle = building.rotation.y;
const localX = [Math.cos(angle), -Math.sin(angle)];
const localZ = [Math.sin(angle), Math.cos(angle)];
const dotX = outward[0] * localX[0] + outward[1] * localX[1];
const dotZ = outward[0] * localZ[0] + outward[1] * localZ[1];
if (Math.abs(dotX) >= Math.abs(dotZ)) {
addEntranceAndWindows(
building, width, depth, height,
"x", Math.sign(dotX) || 1, materials
);
} else {
addEntranceAndWindows(
building, width, depth, height,
"z", Math.sign(dotZ) || 1, materials
);
}
}
group.add(building);
}
}
}
}
function createModel(config) {
const group = new THREE.Group();
group.position.x = config.x;
scene.add(group);
const materials = {
table: new THREE.MeshStandardMaterial({ color: 0x8e7558, roughness: 0.86 }),
tableEdge: new THREE.MeshStandardMaterial({ color: 0x765f47, roughness: 0.9 }),
base: new THREE.MeshStandardMaterial({ color: 0xb7aa93, roughness: 0.95 }),
curb: new THREE.MeshStandardMaterial({ color: 0xcbbd9f, roughness: 0.95 }),
road: new THREE.MeshStandardMaterial({ color: 0x454b4c, roughness: 0.94 }),
plaza: new THREE.MeshStandardMaterial({ color: 0x929e82, roughness: 1 }),
plazaEdge: new THREE.MeshStandardMaterial({ color: 0x7f8b72, roughness: 1 }),
entrance: new THREE.MeshStandardMaterial({
color: 0xd3a43e,
emissive: 0x7a5314,
emissiveIntensity: 0.22,
roughness: 0.62
}),
trunk: new THREE.MeshStandardMaterial({ color: 0x746044, roughness: 1 }),
tree: new THREE.MeshStandardMaterial({ color: 0x66765c, roughness: 1 }),
stone: new THREE.MeshStandardMaterial({ color: 0xc3b69b, roughness: 0.95 }),
window: new THREE.MeshStandardMaterial({ color: 0x4e5553, roughness: 0.72 }),
node: new THREE.MeshStandardMaterial({
color: 0xf1e9d9,
emissive: 0x6e685b,
emissiveIntensity: 0.13,
roughness: 0.7
}),
buildings: [
new THREE.MeshStandardMaterial({ color: 0xc2b194, roughness: 0.95 }),
new THREE.MeshStandardMaterial({ color: 0xb7a68b, roughness: 0.95 }),
new THREE.MeshStandardMaterial({ color: 0xcdbb9d, roughness: 0.95 }),
new THREE.MeshStandardMaterial({ color: 0xaa9b84, roughness: 0.95 }),
new THREE.MeshStandardMaterial({ color: 0xc7b9a3, roughness: 0.95 })
],
roofs: [
new THREE.MeshStandardMaterial({ color: 0x8f7762, roughness: 0.95 }),
new THREE.MeshStandardMaterial({ color: 0x806c5a, roughness: 0.95 }),
new THREE.MeshStandardMaterial({ color: 0x977d67, roughness: 0.95 }),
new THREE.MeshStandardMaterial({ color: 0x766456, roughness: 0.95 }),
new THREE.MeshStandardMaterial({ color: 0x8b7461, roughness: 0.95 })
]
};
// Table and legs.
group.add(box(12.2, 0.32, 10.2, materials.table, 0, 0.49, 0));
group.add(box(12.35, 0.12, 10.35, materials.tableEdge, 0, 0.28, 0));
for (const x of [-5.1, 5.1]) {
for (const z of [-4.1, 4.1]) {
group.add(box(0.38, 0.67, 0.38, materials.tableEdge, x, 0.335, z));
}
}
// Model base and a frame that indicates the active model.
group.add(box(11.1, 0.13, 9.45, materials.base, 0, 0.715, 0));
const outlineMaterial = new THREE.MeshStandardMaterial({
color: 0xc49338,
emissive: 0x8a5d1b,
emissiveIntensity: 0.15,
roughness: 0.7
});
group.add(box(11.18, 0.06, 0.07, outlineMaterial, 0, 0.79, -4.73));
group.add(box(11.18, 0.06, 0.07, outlineMaterial, 0, 0.79, 4.73));
group.add(box(0.07, 0.06, 9.46, outlineMaterial, -5.59, 0.79, 0));
group.add(box(0.07, 0.06, 9.46, outlineMaterial, 5.59, 0.79, 0));
// Roads.
for (const edge of config.data.edges) {
const a = config.data.nodes[edge.a];
const b = config.data.nodes[edge.b];
const visualWidth = edge.width / 14;
const curb = box(1, 0.07, visualWidth + 0.20, materials.curb, 0, 0.79, 0);
orientSegment(curb, a, b);
group.add(curb);
const road = box(1, 0.045, visualWidth, materials.road, 0, 0.845, 0);
orientSegment(road, a, b);
road.userData = {
kind: "street",
modelKey: config.key,
edge
};
group.add(road);
pickables.push(road);
edge.visualWidth = visualWidth;
}
// Numbered junctions.
for (let id = 0; id < config.data.nodes.length; id++) {
const [x, z] = config.data.nodes[id];
const node = new THREE.Mesh(
new THREE.SphereGeometry(0.135, 12, 8),
materials.node
);
node.position.set(x, 0.99, z);
node.castShadow = true;
node.userData = {
kind: "node",
modelKey: config.key,
id
};
group.add(node);
pickables.push(node);
const label = makeNumberSprite(id);
label.position.set(x, 1.30, z);
group.add(label);
}
createBuildings(config.data, group, materials);
// Civic space: a square in the reference model and a stepped equivalent
// in the hypothetical model, using the same visual language.
const centerBlock = config.data.nodes.slice(5, 9);
const center = [
centerBlock.reduce((sum, p) => sum + p[0], 0) / 4,
centerBlock.reduce((sum, p) => sum + p[1], 0) / 4
];
const angle = config.key === "reference" ? 0 : -0.035;
if (config.key === "reference") {
const plaza = box(2.10, 0.065, 1.88, materials.plaza, center[0], 0.845, center[1]);
plaza.rotation.y = angle;
group.add(plaza);
const border = box(2.18, 0.035, 1.96, materials.plazaEdge, center[0], 0.819, center[1]);
border.rotation.y = angle;
group.add(border);
addTree(group, center[0] - 0.58, center[1] - 0.48, materials);
addTree(group, center[0] + 0.58, center[1] - 0.48, materials);
addTree(group, center[0] - 0.58, center[1] + 0.48, materials);
addTree(group, center[0] + 0.58, center[1] + 0.48, materials);
} else {
const horizontal = box(2.02, 0.065, 1.20, materials.plaza, center[0], 0.845, center[1] - 0.27);
const vertical = box(1.20, 0.066, 1.92, materials.plaza, center[0] - 0.37, 0.848, center[1] + 0.18);
horizontal.rotation.y = angle;
vertical.rotation.y = angle;
group.add(horizontal, vertical);
addTree(group, center[0] - 0.38, center[1] - 0.54, materials);
addTree(group, center[0] + 0.42, center[1] - 0.52, materials);
addTree(group, center[0] - 0.48, center[1] + 0.46, materials);
addTree(group, center[0] + 0.48, center[1] + 0.55, materials);
}
const title = config.key === "reference"
? "REFERENCE-BASED SCHEMATIC"
: "HYPOTHETICAL ALTERNATIVE";
const subtitle = config.key === "reference"
? "Themes from 1758 rebuilding plans · not a district reconstruction"
: "Counterfactual only · not a documented plan or outcome";
const plaque = makeTextSprite(title, {
background: config.key === "reference" ? "#343a38" : "#704b37",
accent: config.key === "reference" ? "#a8b29a" : "#d0a253",
foreground: "#f5eddd",
subtitle
});
plaque.position.set(0, 1.72, 4.88);
plaque.scale.set(7.25, 1.12);
group.add(plaque);
const routeGroup = new THREE.Group();
const markerGroup = new THREE.Group();
const measureGroup = new THREE.Group();
group.add(routeGroup, markerGroup, measureGroup);
const routeMaterial = new THREE.MeshStandardMaterial({
color: config.key === "reference" ? 0x2e8b83 : 0xd18a37,
emissive: config.key === "reference" ? 0x174f4b : 0x7b4214,
emissiveIntensity: 0.34,
roughness: 0.45,
transparent: true,
opacity: 0.94
});
return {
...config,
group,
outlineMaterial,
routeGroup,
markerGroup,
measureGroup,
routeMaterial,
adjacency: makeAdjacency(config.data.edges)
};
}
models.reference = createModel({
key: "reference",
x: -6.65,
data: {
nodes: referenceNodes,
edges: referenceEdges
}
});
models.alternative = createModel({
key: "alternative",
x: 6.65,
data: {
nodes: alternativeNodes,
edges: alternativeEdges
}
});
let activeModel = "reference";
let pickMode = "source";
let sourceId = 0;
let targetId = 15;
let waypoints = [];
const sourceLabel = document.getElementById("source-label");
const targetLabel = document.getElementById("target-label");
const waypointsElement = document.getElementById("waypoints");
const referenceCountElement = document.getElementById("reference-route-count");
const alternativeCountElement = document.getElementById("alternative-route-count");
const referenceShortestElement = document.getElementById("reference-shortest");
const alternativeShortestElement = document.getElementById("alternative-shortest");
const widthInspector = document.getElementById("width-inspector");
const traceStatus = document.getElementById("trace-status");
function countSimpleRoutes(adjacency, source, target) {
if (source === target) return 1;
let count = 0;
const visited = new Set();
function visit(node) {
if (node === target) {
count++;
return;
}
visited.add(node);
for (const connection of adjacency[node]) {
if (!visited.has(connection.to)) visit(connection.to);
}
visited.delete(node);
}
visit(source);
return count;
}
function shortestPath(adjacency, source, target) {
const distances = new Array(adjacency.length).fill(Infinity);
const previous = new Array(adjacency.length).fill(null);
const unvisited = new Set(adjacency.map((_, i) => i));
distances[source] = 0;
while (unvisited.size) {
let current = null;
let best = Infinity;
for (const node of unvisited) {
if (distances[node] < best) {
best = distances[node];
current = node;
}
}
if (current === null) break;
if (current === target) break;
unvisited.delete(current);
for (const connection of adjacency[current]) {
if (!unvisited.has(connection.to)) continue;
const candidate = distances[current] + connection.edge.width;
if (candidate < distances[connection.to]) {
distances[connection.to] = candidate;
previous[connection.to] = current;
}
}
}
if (!Number.isFinite(distances[target])) return null;
const path = [target];
let cursor = target;
while (cursor !== source) {
cursor = previous[cursor];
if (cursor === null) return null;
path.push(cursor);
}
path.reverse();
return path;
}
function pathThroughWaypoints(adjacency, source, target, points) {
const sequence = [source, ...points, target];
const completePath = [];
for (let i = 0; i < sequence.length - 1; i++) {
const part = shortestPath(adjacency, sequence[i], sequence[i + 1]);
if (!part) return null;
for (let j = 0; j < part.length; j++) {
if (j === 0 && completePath.length) continue;
completePath.push(part[j]);
}
}
return completePath;
}
function routeSegmentCount(path) {
return path ? Math.max(0, path.length - 1) : null;
}
function updateRouteMetrics() {
sourceLabel.textContent = pointName(sourceId);
targetLabel.textContent = pointName(targetId);
waypointsElement.replaceChildren();
if (!waypoints.length) {
waypointsElement.textContent = "Waypoints: none";
} else {
const label = document.createElement("span");
label.textContent = "Waypoints:";
waypointsElement.append(label);
for (const id of waypoints) {
const chip = document.createElement("span");
chip.textContent = pointName(id);
waypointsElement.append(chip);
}
}
for (const key of ["reference", "alternative"]) {
const model = models[key];
const count = countSimpleRoutes(model.adjacency, sourceId, targetId);
const shortest = shortestPath(model.adjacency, sourceId, targetId);
const countElement = key === "reference"
? referenceCountElement
: alternativeCountElement;
const shortestElement = key === "reference"
? referenceShortestElement
: alternativeShortestElement;
countElement.textContent = count.toLocaleString();
shortestElement.textContent = shortest
? `${routeSegmentCount(shortest)} seg.`
: "No route";
}
}
function setActiveModel(key) {
activeModel = key;
document.getElementById("active-reference").classList.toggle("active", key === "reference");
document.getElementById("active-alternative").classList.toggle("active", key === "alternative");
document.getElementById("reference-note").classList.toggle("active", key === "reference");
document.getElementById("alternative-note").classList.toggle("active", key === "alternative");
for (const modelKey of ["reference", "alternative"]) {
const active = modelKey === key;
models[modelKey].outlineMaterial.color.set(active ? 0xc49338 : 0x8b877c);
models[modelKey].outlineMaterial.emissive.set(active ? 0x8a5d1b : 0x000000);
}
}
function setPickMode(mode) {
pickMode = mode;
document.getElementById("pick-source").classList.toggle("active", mode === "source");
document.getElementById("pick-target").classList.toggle("active", mode === "target");
document.getElementById("pick-waypoint").classList.toggle("active", mode === "waypoint");
}
function makeEndpointMarker(color, letter) {
const group = new THREE.Group();
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.36,
roughness: 0.45
});
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.30, 0.052, 8, 28),
material
);
ring.rotation.x = Math.PI / 2;
group.add(ring);
const label = makeTextSprite(letter, {
width: 128,
height: 96,
background: color === 0xc49338 ? "#c49338" : "#397572",
foreground: "#fffaf0",
fontSize: 48
});
label.scale.set(0.52, 0.39);
label.position.y = 0.62;
group.add(label);
return group;
}
const sourceMarker = makeEndpointMarker(0xc49338, "S");
const targetMarker = makeEndpointMarker(0x397572, "T");
function updateEndpointMarkers() {
for (const model of Object.values(models)) {
clearGroup(model.markerGroup);
const source = model.data.nodes[sourceId];
const target = model.data.nodes[targetId];
sourceMarker.position.set(source[0], 0.965, source[1]);
targetMarker.position.set(target[0], 0.985, target[1]);
model.markerGroup.add(sourceMarker.clone());
model.markerGroup.add(targetMarker.clone());
}
}
function clearRoute(model) {
clearGroup(model.routeGroup);
}
function addRouteSegment(model, aId, bId) {
const a = model.data.nodes[aId];
const b = model.data.nodes[bId];
const start = new THREE.Vector3(a[0], 0.925, a[1]);
const end = new THREE.Vector3(b[0], 0.925, b[1]);
const direction = end.clone().sub(start);
const length = direction.length();
const geometry = new THREE.CylinderGeometry(0.075, 0.075, length, 8);
const mesh = new THREE.Mesh(geometry, model.routeMaterial);
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.clone().normalize()
);
model.routeGroup.add(mesh);
}
function tracePaths() {
const statuses = [];
for (const key of ["reference", "alternative"]) {
const model = models[key];
clearRoute(model);
const path = pathThroughWaypoints(
model.adjacency,
sourceId,
targetId,
waypoints
);
if (!path) {
statuses.push(`${key === "reference" ? "Reference" : "Hypothetical"}: no connected path`);
continue;
}
for (let i = 0; i < path.length - 1; i++) {
addRouteSegment(model, path[i], path[i + 1]);
}
statuses.push(
`${key === "reference" ? "Reference" : "Hypothetical"}: ${path.length - 1} segments`
);
}
traceStatus.textContent = `Traced in both models — ${statuses.join(" · ")}.`;
}
function showMeasurement(modelKey, edge) {
const model = models[modelKey];
clearGroup(model.measureGroup);
const a = model.data.nodes[edge.a];
const b = model.data.nodes[edge.b];
const dx = b[0] - a[0];
const dz = b[1] - a[1];
const length = Math.hypot(dx, dz) || 1;
const normal = [-dz / length, dx / length];
const offset = edge.visualWidth / 2 + 0.28;
const p1 = [
a[0] + normal[0] * offset,
0.91,
a[1] + normal[1] * offset
];
const p2 = [
b[0] + normal[0] * offset,
0.91,
b[1] + normal[1] * offset
];
const material = new THREE.LineBasicMaterial({
color: 0x2f7773,
transparent: true,
opacity: 0.95
});
const line = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(p1[0], p1[1], p1[2]),
new THREE.Vector3(p2[0], p2[1], p2[2])
]),
material
);
model.measureGroup.add(line);
for (const point of [p1, p2]) {
const tick = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(
point[0] - normal[0] * 0.16,
point[1],
point[2] - normal[1] * 0.16
),
new THREE.Vector3(
point[0] + normal[0] * 0.16,
point[1],
point[2] + normal[1] * 0.16
)
]),
material
);
model.measureGroup.add(tick);
}
}
function clearMeasurement(modelKey) {
clearGroup(models[modelKey].measureGroup);
}
function updateWidthInspector(modelKey, edge) {
const modelName = modelKey === "reference"
? "Reference-based network"
: "Hypothetical alternative";
widthInspector.replaceChildren();
const label = document.createElement("div");
label.className = "small";
label.textContent = modelName;
const width = document.createElement("div");
width.className = "big";
width.textContent = `${edge.width} m`;
const description = document.createElement("div");
description.className = "small";
description.textContent = `${edge.class} · schematic width · ${edge.id}`;
widthInspector.append(label, width, description);
}
document.getElementById("active-reference").addEventListener("click", () => setActiveModel("reference"));
document.getElementById("active-alternative").addEventListener("click", () => setActiveModel("alternative"));
document.getElementById("pick-source").addEventListener("click", () => setPickMode("source"));
document.getElementById("pick-target").addEventListener("click", () => setPickMode("target"));
document.getElementById("pick-waypoint").addEventListener("click", () => setPickMode("waypoint"));
document.getElementById("trace-button").addEventListener("click", tracePaths);
document.getElementById("clear-waypoints").addEventListener("click", () => {
waypoints = [];
updateRouteMetrics();
traceStatus.textContent = "Waypoints cleared. Trace the direct shortest route.";
for (const model of Object.values(models)) clearRoute(model);
});
// Custom orbit/pan/zoom controls implemented directly, without addons.
const pointer = new THREE.Vector2();
const raycaster = new THREE.Raycaster();
let pointerDown = false;
let pointerButton = 0;
let pointerStartX = 0;
let pointerStartY = 0;
let lastX = 0;
let lastY = 0;
let dragged = false;
function updateCamera() {
const offset = new THREE.Vector3().setFromSpherical(spherical);
camera.position.copy(cameraTarget).add(offset);
camera.lookAt(cameraTarget);
}
function resize() {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / Math.max(1, height);
camera.updateProjectionMatrix();
if (!viewInitialized) {
const visibleWidth = 29.5;
const fitRadius = visibleWidth /
(2 * Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)) * camera.aspect);
spherical.radius = THREE.MathUtils.clamp(fitRadius, 27, 52);
viewInitialized = true;
}
updateCamera();
}
new ResizeObserver(resize).observe(viewport);
resize();
function setPointerFromEvent(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function pick(event) {
setPointerFromEvent(event);
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(pickables, false);
if (!intersections.length) return null;
return intersections[0].object.userData;
}
renderer.domElement.addEventListener("contextmenu", event => event.preventDefault());
renderer.domElement.addEventListener("pointerdown", event => {
pointerDown = true;
pointerButton = event.button;
pointerStartX = event.clientX;
pointerStartY = event.clientY;
lastX = event.clientX;
lastY = event.clientY;
dragged = false;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (pointerDown) {
const dx = event.clientX - lastX;
const dy = event.clientY - lastY;
if (Math.hypot(event.clientX - pointerStartX, event.clientY - pointerStartY) > 5) {
dragged = true;
}
if (pointerButton === 0) {
spherical.theta -= dx * 0.006;
spherical.phi = THREE.MathUtils.clamp(spherical.phi - dy * 0.005, 0.42, 1.38);
} else if (pointerButton === 2 || pointerButton === 1) {
const scale = spherical.radius * 0.0014;
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0);
const up = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 1);
cameraTarget.addScaledVector(right, -dx * scale);
cameraTarget.addScaledVector(up, dy * scale);
}
lastX = event.clientX;
lastY = event.clientY;
updateCamera();
tooltip.style.display = "none";
return;
}
const hit = pick(event);
if (!hit) {
tooltip.style.display = "none";
clearMeasurement("reference");
clearMeasurement("alternative");
return;
}
if (hit.kind === "node") {
tooltip.textContent = `${pointName(hit.id)} — click to assign it to the selected action.`;
} else {
const name = hit.modelKey === "reference"
? "Reference-based"
: "Hypothetical";
tooltip.textContent = `${name} street · ${hit.edge.width} m schematic · ${hit.edge.class}`;
updateWidthInspector(hit.modelKey, hit.edge);
showMeasurement(hit.modelKey, hit.edge);
clearMeasurement(hit.modelKey === "reference" ? "alternative" : "reference");
}
tooltip.style.display = "block";
const tooltipWidth = tooltip.offsetWidth;
const tooltipHeight = tooltip.offsetHeight;
tooltip.style.left = `${Math.min(window.innerWidth - tooltipWidth - 8, event.clientX + 13)}px`;
tooltip.style.top = `${Math.min(window.innerHeight - tooltipHeight - 8, event.clientY + 13)}px`;
});
renderer.domElement.addEventListener("pointerup", event => {
const wasDragged = dragged;
pointerDown = false;
dragged = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
if (pointerButton !== 0 || wasDragged) return;
const hit = pick(event);
if (!hit) return;
setActiveModel(hit.modelKey);
if (hit.kind === "node") {
if (pickMode === "source") {
sourceId = hit.id;
} else if (pickMode === "target") {
targetId = hit.id;
} else {
if (!waypoints.includes(hit.id)) waypoints.push(hit.id);
}
updateRouteMetrics();
updateEndpointMarkers();
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = false;
dragged = false;
});
renderer.domElement.addEventListener("pointerleave", () => {
if (!pointerDown) {
tooltip.style.display = "none";
clearMeasurement("reference");
clearMeasurement("alternative");
}
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
spherical.radius = THREE.MathUtils.clamp(
spherical.radius * Math.exp(event.deltaY * 0.001),
17,
58
);
updateCamera();
}, { passive: false });
updateRouteMetrics();
updateEndpointMarkers();
setActiveModel("reference");
setPickMode("source");
const clock = new THREE.Clock();
function animate() {
const elapsed = clock.getElapsedTime();
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
for (const model of Object.values(models)) {
model.routeMaterial.opacity = reducedMotion
? 0.94
: 0.84 + Math.sin(elapsed * 2.2) * 0.10;
}
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
animate();
requestAnimationFrame(() => {
document.getElementById("loading").style.display = "none";
});
</script>
</body>
</html>
```