Prompt specification
Build or customize the Three.js 3D scene "Add One Link for Resilience" 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: Add One Link for Resilience
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/add-one-link-for-resilience-x2116
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring a low-poly transport-network puzzle. Arrange a depot, three residential clusters, a clinic marker, and two bridges on a small terrain board. Show the current road links and announce which bridge will close before the player makes a choice. The player may add exactly one connection from a small set of candidate routes, then test the closure. Recompute which destinations remain reachable and compare their shortest route lengths using a stated distance rule. Keep the initial map and closure identical across attempts, allowing several useful solutions when their tradeoffs differ rather than forcing one visually preferred road. Draw unused candidate links as dashed routes, distinguish new construction from existing roads, and show a simple before-and-after route for one selected destination.
Working Three.js Starter (add-one-link-for-resilience-x2116):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bridge & Borough — Transport Network Puzzle</title>
<style>
:root {
--ink: #173042;
--muted: #5c7180;
--paper: rgba(250, 253, 250, 0.94);
--line: rgba(30, 65, 75, 0.14);
--green: #15b88a;
--green-dark: #08785f;
--gold: #e6a91d;
--purple: #b36ce3;
--blue: #168bd2;
--red: #d94a3d;
--shadow: 0 16px 48px rgba(25, 48, 55, 0.16);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
color: var(--ink);
background: #dce9e3;
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
select {
font: inherit;
}
button {
cursor: pointer;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas:active {
cursor: grabbing;
}
#labels {
position: fixed;
inset: 0;
z-index: 3;
overflow: hidden;
pointer-events: none;
}
.map-label {
position: absolute;
z-index: 3;
transform: translate(-50%, -100%);
white-space: nowrap;
border: 1px solid rgba(26, 61, 71, 0.15);
border-radius: 10px;
padding: 6px 9px;
color: #173042;
background: rgba(250, 253, 250, 0.91);
box-shadow: 0 5px 16px rgba(26, 51, 56, 0.14);
backdrop-filter: blur(8px);
font-size: 12px;
font-weight: 760;
letter-spacing: 0.01em;
}
.map-label small {
display: block;
margin-top: 2px;
color: #607582;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.node-label {
pointer-events: auto;
cursor: pointer;
}
.node-label.selected {
border-color: rgba(22, 139, 210, 0.8);
box-shadow:
0 0 0 3px rgba(22, 139, 210, 0.15),
0 6px 18px rgba(26, 51, 56, 0.15);
}
.candidate-label {
pointer-events: auto;
cursor: pointer;
color: #73510a;
border: 1px dashed #c58a0b;
background: rgba(255, 247, 210, 0.94);
}
.candidate-label.selected {
color: #4e3600;
border-style: solid;
background: #fff0a8;
box-shadow:
0 0 0 4px rgba(230, 169, 29, 0.16),
0 8px 20px rgba(95, 70, 12, 0.15);
}
.bridge-label {
color: #704619;
border-color: rgba(176, 111, 45, 0.45);
background: rgba(255, 244, 219, 0.94);
font-size: 10px;
letter-spacing: 0.08em;
}
.bridge-label.warning {
color: #8b241c;
border-color: rgba(217, 74, 61, 0.62);
background: rgba(255, 234, 229, 0.96);
}
#header {
position: fixed;
z-index: 5;
top: 18px;
left: 20px;
max-width: min(520px, calc(100vw - 430px));
pointer-events: none;
}
#header .eyebrow {
display: inline-flex;
align-items: center;
gap: 7px;
margin-bottom: 7px;
padding: 6px 9px;
border: 1px solid rgba(23, 48, 66, 0.12);
border-radius: 999px;
color: #285747;
background: rgba(250, 253, 250, 0.84);
box-shadow: 0 5px 16px rgba(24, 53, 60, 0.08);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.11em;
text-transform: uppercase;
}
#header .eyebrow::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--green);
content: "";
box-shadow: 0 0 0 4px rgba(21, 184, 138, 0.13);
}
#header h1 {
margin: 0;
font-size: clamp(23px, 3vw, 38px);
line-height: 0.98;
letter-spacing: -0.045em;
}
#header p {
max-width: 460px;
margin: 8px 0 0;
color: #49616e;
font-size: 13px;
line-height: 1.45;
}
#closure-banner {
position: fixed;
z-index: 5;
top: 130px;
left: 20px;
display: flex;
align-items: center;
gap: 10px;
max-width: min(490px, calc(100vw - 430px));
padding: 10px 13px;
border: 1px solid rgba(176, 55, 42, 0.28);
border-radius: 12px;
color: #7e281f;
background: rgba(255, 239, 232, 0.94);
box-shadow: 0 8px 24px rgba(112, 46, 38, 0.12);
font-size: 12px;
font-weight: 760;
line-height: 1.35;
pointer-events: none;
}
#closure-banner .alert-icon {
display: grid;
flex: 0 0 auto;
width: 25px;
height: 25px;
place-items: center;
border-radius: 8px;
color: white;
background: var(--red);
font-size: 14px;
font-weight: 900;
}
#closure-banner.active {
color: #7e281f;
background: rgba(255, 226, 218, 0.97);
}
#panel {
position: fixed;
z-index: 6;
top: 16px;
right: 16px;
bottom: 16px;
width: 374px;
overflow: auto;
padding: 17px;
border: 1px solid rgba(28, 64, 72, 0.13);
border-radius: 20px;
background: var(--paper);
box-shadow: var(--shadow);
backdrop-filter: blur(15px);
scrollbar-width: thin;
scrollbar-color: #a8bbb4 transparent;
}
#panel h2 {
margin: 0 0 7px;
font-size: 17px;
letter-spacing: -0.02em;
}
#panel h3 {
margin: 0 0 8px;
font-size: 12px;
letter-spacing: 0.065em;
text-transform: uppercase;
}
.section {
padding-top: 14px;
margin-top: 14px;
border-top: 1px solid var(--line);
}
.small-copy {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.48;
}
.rule-box {
padding: 10px 11px;
border: 1px solid rgba(28, 97, 81, 0.13);
border-radius: 11px;
color: #34584f;
background: rgba(218, 242, 232, 0.63);
font-size: 11px;
line-height: 1.48;
}
.rule-box strong {
color: #155f4c;
}
.stage-box {
display: flex;
align-items: flex-start;
gap: 9px;
margin-top: 11px;
padding: 10px 11px;
border-radius: 11px;
color: #435d67;
background: #edf3f0;
font-size: 12px;
line-height: 1.42;
}
.stage-dot {
flex: 0 0 auto;
width: 9px;
height: 9px;
margin-top: 4px;
border-radius: 50%;
background: var(--gold);
box-shadow: 0 0 0 4px rgba(230, 169, 29, 0.13);
}
details {
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.52);
}
summary {
padding: 9px 11px;
cursor: pointer;
color: #38535f;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.link-list {
padding: 0 11px 10px;
margin: 0;
list-style: none;
font-size: 11px;
line-height: 1.7;
}
.link-list li {
display: flex;
align-items: center;
gap: 7px;
}
.link-list li::before {
width: 7px;
height: 7px;
flex: 0 0 auto;
border-radius: 2px;
background: #405563;
content: "";
}
.link-list li.bridge::before {
background: #b77b43;
}
.link-list li.new::before {
background: var(--green);
}
.link-list li.closed {
color: #a2493f;
text-decoration: line-through;
}
.link-list li.closed::before {
background: var(--red);
}
.destination-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 9px;
}
select {
min-width: 168px;
padding: 7px 27px 7px 9px;
border: 1px solid rgba(28, 64, 72, 0.18);
border-radius: 9px;
color: var(--ink);
background: white;
font-size: 11px;
font-weight: 700;
}
.reach-summary {
margin: 0 0 7px;
color: #46634f;
font-size: 11px;
font-weight: 750;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 10.5px;
}
th {
padding: 5px 3px;
color: #74868e;
font-size: 9px;
letter-spacing: 0.05em;
text-align: right;
text-transform: uppercase;
}
th:first-child,
td:first-child {
text-align: left;
}
td {
padding: 7px 3px;
border-top: 1px solid rgba(30, 65, 75, 0.08);
text-align: right;
vertical-align: middle;
}
tbody tr {
cursor: pointer;
}
tbody tr.selected td {
background: rgba(22, 139, 210, 0.07);
}
td:first-child {
font-weight: 760;
}
.delta.shorter {
color: #08785f;
font-weight: 800;
}
.delta.longer {
color: #a04e3f;
font-weight: 760;
}
.reach-pill {
display: inline-block;
padding: 3px 5px;
border-radius: 999px;
color: #08785f;
background: #dff4ec;
font-size: 8.5px;
font-weight: 850;
letter-spacing: 0.03em;
text-transform: uppercase;
}
.reach-pill.no {
color: #9b392e;
background: #fde4df;
}
.reach-pill.pending {
color: #7a6a43;
background: #f3ecd8;
}
.route-summary {
margin-top: 9px;
padding: 9px 10px;
border-radius: 10px;
color: #526974;
background: #f0f5f3;
font-size: 10.5px;
line-height: 1.55;
}
.route-line {
display: flex;
gap: 7px;
margin: 3px 0;
}
.route-swatch {
flex: 0 0 auto;
width: 18px;
height: 4px;
margin-top: 6px;
border-radius: 4px;
background: var(--purple);
}
.route-swatch.final {
height: 5px;
background: var(--blue);
}
.candidate-list {
display: grid;
gap: 8px;
}
.candidate-card {
width: 100%;
padding: 10px 11px;
border: 1px dashed #c99527;
border-radius: 11px;
color: var(--ink);
background: rgba(255, 249, 225, 0.72);
text-align: left;
transition:
transform 120ms ease,
border-color 120ms ease,
background 120ms ease;
}
.candidate-card:hover:not(:disabled) {
transform: translateY(-1px);
border-color: #b47b06;
background: #fff8d9;
}
.candidate-card.selected {
border-style: solid;
border-color: #d59b0a;
background: #fff1aa;
box-shadow: 0 0 0 3px rgba(230, 169, 29, 0.12);
}
.candidate-card:disabled {
cursor: default;
opacity: 0.55;
}
.candidate-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
font-size: 12px;
font-weight: 830;
}
.candidate-title span {
color: #8a6515;
font-size: 9px;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.candidate-copy {
display: block;
margin-top: 4px;
color: #6c725d;
font-size: 10px;
line-height: 1.42;
}
.actions {
display: grid;
grid-template-columns: 1fr;
gap: 8px;
margin-top: 11px;
}
.primary,
.secondary {
width: 100%;
padding: 10px 12px;
border-radius: 10px;
font-size: 11px;
font-weight: 850;
letter-spacing: 0.025em;
}
.primary {
border: 0;
color: white;
background: var(--green-dark);
box-shadow: 0 5px 14px rgba(8, 120, 95, 0.2);
}
.primary:hover:not(:disabled) {
background: #066b55;
}
.primary:disabled {
cursor: not-allowed;
opacity: 0.42;
box-shadow: none;
}
.secondary {
border: 1px solid rgba(28, 64, 72, 0.17);
color: #425d69;
background: white;
}
.secondary:hover {
background: #f2f7f5;
}
#result-box {
display: none;
margin-top: 10px;
padding: 11px;
border: 1px solid rgba(21, 184, 138, 0.28);
border-radius: 11px;
color: #2b5e4e;
background: rgba(222, 246, 237, 0.76);
font-size: 11px;
line-height: 1.48;
}
#result-box.visible {
display: block;
}
#result-box strong {
display: block;
margin-bottom: 4px;
color: #086b54;
font-size: 12px;
}
.legend {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px 10px;
color: #5c717b;
font-size: 9.5px;
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
}
.legend-line {
width: 21px;
height: 5px;
flex: 0 0 auto;
border-radius: 5px;
background: #405563;
}
.legend-line.bridge {
background: #b77b43;
}
.legend-line.candidate {
height: 3px;
background: repeating-linear-gradient(
90deg,
#e0a51d 0,
#e0a51d 6px,
transparent 6px,
transparent 10px
);
}
.legend-line.new {
background: var(--green);
}
.legend-line.base {
height: 3px;
background: repeating-linear-gradient(
90deg,
var(--purple) 0,
var(--purple) 6px,
transparent 6px,
transparent 10px
);
}
.legend-line.final {
background: var(--blue);
}
.history {
padding-left: 17px;
margin: 0;
color: #5c717b;
font-size: 10px;
line-height: 1.7;
}
#hint {
position: fixed;
z-index: 4;
left: 20px;
bottom: 16px;
padding: 7px 10px;
border-radius: 9px;
color: rgba(40, 66, 76, 0.8);
background: rgba(250, 253, 250, 0.76);
box-shadow: 0 4px 14px rgba(25, 48, 55, 0.08);
font-size: 10px;
pointer-events: none;
}
@media (max-width: 820px) {
#header {
top: 10px;
left: 12px;
max-width: calc(100vw - 24px);
}
#header p {
display: none;
}
#closure-banner {
top: 82px;
left: 12px;
max-width: calc(100vw - 24px);
}
#panel {
top: auto;
right: 8px;
bottom: 8px;
left: 8px;
width: auto;
max-height: 51vh;
padding: 14px;
border-radius: 16px;
}
#hint {
display: none;
}
.candidate-label {
display: none !important;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div id="labels"></div>
<header id="header">
<div class="eyebrow">Low-poly transport puzzle</div>
<h1>Bridge & Borough</h1>
<p>
Plan one new connection, then test the announced bridge closure.
The goal is to keep every destination reachable—not merely to find one
shortest-looking road.
</p>
</header>
<div id="closure-banner" aria-live="polite">
<span class="alert-icon">!</span>
<span id="closure-text">
CLOSURE ANNOUNCED — The North Bridge will close during the test.
This closure is fixed for every attempt.
</span>
</div>
<aside id="panel">
<h2>Network brief</h2>
<p class="small-copy">
The depot is on the west bank. Build exactly one dashed candidate link,
test the North Bridge closure, and inspect the resulting shortest routes.
All three candidates are valid designs, but they have different length
and redundancy trade-offs.
</p>
<div class="rule-box">
<strong>Distance rule</strong><br />
Every edge costs its straight-line map distance in board units.
One board unit equals 100 m. A route is the sum of its edge costs;
the shortest route is the least-cost simple path. All links have the
same travel cost per unit.
</div>
<div class="stage-box">
<span class="stage-dot"></span>
<span id="stage-text">Choose one dashed candidate connection.</span>
</div>
<section class="section">
<details open>
<summary>Current road links</summary>
<ul class="link-list" id="link-list"></ul>
</details>
</section>
<section class="section">
<h3>Reachability & shortest lengths</h3>
<p class="reach-summary" id="reach-summary">Closure not tested yet.</p>
<div class="destination-row">
<span class="small-copy">Route display</span>
<select id="destination-select" aria-label="Destination for route display">
<option value="R1">Pine Row</option>
<option value="R2" selected>Harbor Homes</option>
<option value="R3">Cedar Commons</option>
<option value="K">Clinic</option>
</select>
</div>
<table aria-label="Shortest route lengths">
<thead>
<tr>
<th>Destination</th>
<th>Baseline</th>
<th>Final</th>
<th>Δ</th>
<th>Reach</th>
</tr>
</thead>
<tbody id="route-table"></tbody>
</table>
<div class="route-summary" id="route-summary"></div>
<div class="legend" style="margin-top: 10px">
<div class="legend-item">
<span class="legend-line"></span> Existing road
</div>
<div class="legend-item">
<span class="legend-line bridge"></span> Bridge
</div>
<div class="legend-item">
<span class="legend-line candidate"></span> Unused candidate
</div>
<div class="legend-item">
<span class="legend-line new"></span> New construction
</div>
<div class="legend-item">
<span class="legend-line base"></span> Baseline route
</div>
<div class="legend-item">
<span class="legend-line final"></span> Final route
</div>
</div>
</section>
<section class="section">
<h3>One candidate connection</h3>
<div class="candidate-list" id="candidate-list"></div>
<div class="actions">
<button class="primary" id="action-button" disabled>
Build selected connection
</button>
<button class="secondary" id="reset-button">
Reset attempt · same map & closure
</button>
</div>
<div id="result-box" aria-live="polite"></div>
</section>
<section class="section">
<h3>Attempt comparison</h3>
<ol class="history" id="history-list">
<li>No completed attempts yet.</li>
</ol>
</section>
</aside>
<div id="hint">
Drag to orbit · right-drag to pan · wheel to zoom · click a dashed link or stop
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const COLORS = {
existing: 0x405563,
existingStripe: 0xcbd7d8,
bridge: 0xb77b43,
bridgeRail: 0x704722,
candidate: 0xe0a51d,
candidateSelected: 0xffd44d,
newRoad: 0x16c995,
baseline: 0xb36ce3,
final: 0x168bd2,
red: 0xd94a3d,
gold: 0xf0a51b,
grass: 0x91b98b,
grassDark: 0x78a975,
sand: 0xd6c18c,
water: 0x5baec3
};
const nodes = {
D: {
name: "Depot",
kind: "Depot",
color: 0xf08a36,
pos: new THREE.Vector3(-4.2, 0, 0.1)
},
R1: {
name: "Pine Row",
kind: "Residential",
color: 0x4cb69b,
pos: new THREE.Vector3(-2.8, 0, -2.9)
},
R2: {
name: "Harbor Homes",
kind: "Residential",
color: 0x4d91d0,
pos: new THREE.Vector3(3.5, 0, -2.5)
},
R3: {
name: "Cedar Commons",
kind: "Residential",
color: 0x7b9dca,
pos: new THREE.Vector3(-2.6, 0, 3.0)
},
K: {
name: "Clinic",
kind: "Clinic",
color: 0xf4f1e8,
pos: new THREE.Vector3(3.2, 0, 0.7)
}
};
const destinations = ["R1", "R2", "R3", "K"];
const existingEdges = [
{ id: "D-R1", a: "D", b: "R1", type: "road" },
{ id: "D-R3", a: "D", b: "R3", type: "road" },
{ id: "NBRIDGE", a: "R1", b: "R2", type: "bridge" },
{ id: "SBRIDGE", a: "R3", b: "K", type: "bridge" }
];
const candidateDefs = [
{
id: "tunnel",
name: "Depot Tunnel",
a: "D",
b: "R2",
tagline: "Direct",
description:
"Depot → Harbor Homes. A direct tunnel gives the quickest recovery for Harbor Homes, but spends more construction cost."
},
{
id: "causeway",
name: "South Causeway",
a: "R3",
b: "R2",
tagline: "Independent",
description:
"Cedar Commons → Harbor Homes. It avoids reliance on the South Bridge and reconnects the upper-east branch from the west bank."
},
{
id: "clinic",
name: "Clinic Link",
a: "K",
b: "R2",
tagline: "East bank",
description:
"Clinic → Harbor Homes. The short physical segment creates a long depot detour and couples the two east-bank destinations."
}
];
const state = {
phase: "build",
selectedCandidate: null,
builtCandidate: null,
destination: "R2",
finalEdges: [],
attemptHistory: []
};
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce9e3);
scene.fog = new THREE.Fog(0xdce9e3, 25, 43);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
$("scene").appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xf7fff8, 0x708272, 2.25);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff3d4, 3.1);
sun.position.set(-8, 15, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -12;
sun.shadow.camera.right = 12;
sun.shadow.camera.top = 12;
sun.shadow.camera.bottom = -12;
sun.shadow.normalBias = 0.025;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xa8d9ed, 0.8);
fill.position.set(10, 7, -10);
scene.add(fill);
const terrain = new THREE.Group();
const infrastructure = new THREE.Group();
const candidateLayer = new THREE.Group();
const routeLayer = new THREE.Group();
scene.add(terrain, infrastructure, candidateLayer, routeLayer);
const labels = [];
const nodePickObjects = [];
const candidatePickObjects = [];
const candidateGroups = new Map();
const candidateMaterials = new Map();
let newRoadVisual = null;
let finalRoutePath = [];
let warningBeacon = null;
let northBridgeClosure = null;
let northBridgeLabel = null;
let bus = null;
const cameraControl = {
target: new THREE.Vector3(-0.65, 0, 0),
radius: 18.4,
theta: 0.71,
phi: 0.78
};
const xAxis = new THREE.Vector3(1, 0, 0);
function applyCamera() {
const { target, radius, theta, phi } = cameraControl;
const sinPhi = Math.sin(phi);
camera.position.set(
target.x + radius * sinPhi * Math.sin(theta),
target.y + radius * Math.cos(phi),
target.z + radius * sinPhi * Math.cos(theta)
);
camera.lookAt(target);
}
applyCamera();
function box(width, height, depth, color, parent = scene) {
const material =
typeof color === "number"
? new THREE.MeshStandardMaterial({
color,
roughness: 0.84,
metalness: 0.02,
flatShading: true
})
: color;
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeBoard() {
const board = box(
13,
0.72,
9,
new THREE.MeshStandardMaterial({
color: COLORS.grass,
roughness: 0.95,
flatShading: true
}),
terrain
);
board.position.y = -0.36;
const sideMaterial = new THREE.MeshStandardMaterial({
color: 0x6d8067,
roughness: 1,
flatShading: true
});
const underlay = new THREE.Mesh(
new THREE.BoxGeometry(13.16, 0.16, 9.16),
sideMaterial
);
underlay.position.y = -0.76;
underlay.receiveShadow = true;
terrain.add(underlay);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(board.geometry),
new THREE.LineBasicMaterial({
color: 0x59705e,
transparent: true,
opacity: 0.45
})
);
edges.position.copy(board.position);
terrain.add(edges);
}
function riverCenter(z) {
return (
0.18 +
0.42 * Math.sin(z * 0.82) +
0.14 * Math.sin(z * 1.85 + 0.6)
);
}
function makeRiverStrip(width, y, color) {
const positions = [];
const indices = [];
const segments = 48;
for (let i = 0; i <= segments; i++) {
const z = -4.72 + (9.44 * i) / segments;
const center = riverCenter(z);
positions.push(center - width / 2, y, z);
positions.push(center + width / 2, y, z);
if (i < segments) {
const a = i * 2;
indices.push(a, a + 2, a + 1);
indices.push(a + 1, a + 2, a + 3);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
const material = new THREE.MeshStandardMaterial({
color,
roughness: 0.38,
metalness: 0.03,
side: THREE.DoubleSide,
flatShading: true
});
const mesh = new THREE.Mesh(geometry, material);
mesh.receiveShadow = true;
terrain.add(mesh);
return mesh;
}
function mulberry32(seed) {
return function () {
let t = (seed += 0x6d2b79f5);
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function distanceToSegment(px, pz, ax, az, bx, bz) {
const dx = bx - ax;
const dz = bz - az;
const lengthSquared = dx * dx + dz * dz;
if (lengthSquared === 0) {
return Math.hypot(px - ax, pz - az);
}
const t = Math.max(
0,
Math.min(
1,
((px - ax) * dx + (pz - az) * dz) / lengthSquared
)
);
const x = ax + t * dx;
const z = az + t * dz;
return Math.hypot(px - x, pz - z);
}
function makeTree(x, z, scale, color) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.scale.setScalar(scale);
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.075, 0.09, 0.42, 5),
new THREE.MeshStandardMaterial({
color: 0x7e5a3b,
roughness: 1,
flatShading: true
})
);
trunk.position.y = 0.21;
trunk.castShadow = true;
group.add(trunk);
const crown = new THREE.Mesh(
new THREE.ConeGeometry(0.31, 0.72, 6),
new THREE.MeshStandardMaterial({
color,
roughness: 0.95,
flatShading: true
})
);
crown.position.y = 0.72;
crown.castShadow = true;
group.add(crown);
terrain.add(group);
}
function makeVegetation() {
const random = mulberry32(74291);
const treeColors = [0x3e8055, 0x4c9560, 0x5a9e67, 0x357553];
let placed = 0;
let attempts = 0;
while (placed < 34 && attempts < 800) {
attempts++;
const x = -6.1 + random() * 12.2;
const z = -4.1 + random() * 8.2;
if (Math.abs(x - riverCenter(z)) < 0.9) continue;
let nearNode = false;
for (const node of Object.values(nodes)) {
if (
Math.hypot(
x - node.pos.x,
z - node.pos.z
) < 1.05
) {
nearNode = true;
break;
}
}
if (nearNode) continue;
let nearRoad = false;
for (const edge of existingEdges) {
const a = nodes[edge.a].pos;
const b = nodes[edge.b].pos;
if (
distanceToSegment(
x,
z,
a.x,
a.z,
b.x,
b.z
) < 0.53
) {
nearRoad = true;
break;
}
}
if (nearRoad) continue;
makeTree(
x,
z,
0.72 + random() * 0.46,
treeColors[Math.floor(random() * treeColors.length)]
);
placed++;
}
const hillMaterial = new THREE.MeshStandardMaterial({
color: 0x789476,
roughness: 1,
flatShading: true
});
const hillData = [
[-5.7, -3.8, 0.9, 0.85],
[5.5, 3.65, 1.15, 0.72],
[-5.5, 3.7, 0.76, 0.95]
];
for (const [x, z, radius, height] of hillData) {
const hill = new THREE.Mesh(
new THREE.ConeGeometry(radius, height, 5),
hillMaterial
);
hill.position.set(x, height / 2 - 0.02, z);
hill.rotation.y = 0.3;
hill.castShadow = true;
hill.receiveShadow = true;
terrain.add(hill);
}
}
function makeHouse(x, z, color, rotation = 0, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.rotation.y = rotation;
group.scale.setScalar(scale);
const body = box(
0.38,
0.28,
0.34,
new THREE.MeshStandardMaterial({
color,
roughness: 0.92,
flatShading: true
}),
group
);
body.position.y = 0.17;
const roof = new THREE.Mesh(
new THREE.ConeGeometry(0.31, 0.27, 4),
new THREE.MeshStandardMaterial({
color: 0x9e5b48,
roughness: 0.95,
flatShading: true
})
);
roof.position.y = 0.43;
roof.rotation.y = Math.PI / 4;
roof.castShadow = true;
group.add(roof);
const windowMaterial = new THREE.MeshBasicMaterial({
color: 0xffecae
});
const windowMesh = box(0.11, 0.1, 0.012, windowMaterial, group);
windowMesh.position.set(0, 0.2, 0.176);
terrain.add(group);
}
function makeStop(nodeId) {
const node = nodes[nodeId];
const group = new THREE.Group();
group.position.copy(node.pos);
const markerMaterial = new THREE.MeshStandardMaterial({
color: node.color,
roughness: 0.62,
flatShading: true
});
const marker = new THREE.Mesh(
new THREE.CylinderGeometry(0.42, 0.48, 0.15, 6),
markerMaterial
);
marker.position.y = 0.12;
marker.castShadow = true;
marker.receiveShadow = true;
marker.userData.node = nodeId;
group.add(marker);
nodePickObjects.push(marker);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.43, 0.045, 5, 18),
new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.85
})
);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.205;
group.add(ring);
if (nodeId === "D") {
const warehouse = box(
0.9,
0.48,
0.58,
new THREE.MeshStandardMaterial({
color: 0xd98243,
roughness: 0.86,
flatShading: true
}),
group
);
warehouse.position.set(0.05, 0.26, -0.72);
const roof = box(
1.02,
0.08,
0.67,
new THREE.MeshStandardMaterial({
color: 0x6b7780,
roughness: 0.9,
flatShading: true
}),
group
);
roof.position.set(0.05, 0.54, -0.72);
for (let i = 0; i < 3; i++) {
const crate = box(
0.18,
0.18,
0.18,
new THREE.MeshStandardMaterial({
color: 0xc7904e,
roughness: 1,
flatShading: true
}),
group
);
crate.position.set(-0.67 + i * 0.21, 0.12, 0.35);
}
} else if (nodeId === "K") {
const clinic = box(
0.64,
0.48,
0.55,
new THREE.MeshStandardMaterial({
color: 0xf6f3e9,
roughness: 0.78,
flatShading: true
}),
group
);
clinic.position.set(-0.38, 0.26, -0.63);
const red = new THREE.MeshBasicMaterial({ color: 0xd94a3d });
const crossA = box(0.34, 0.025, 0.09, red, group);
const crossB = box(0.09, 0.025, 0.34, red, group);
crossA.position.set(-0.38, 0.515, -0.63);
crossB.position.set(-0.38, 0.515, -0.63);
} else {
const houseColors = [0xe7c98d, 0xdca58d, 0xaecda7, 0xbac7dd];
const offsets = [
[-0.65, -0.55, 0.55],
[0.63, -0.48, -0.45],
[-0.58, 0.65, -0.7]
];
offsets.forEach((offset, index) => {
makeHouse(
node.pos.x + offset[0],
node.pos.z + offset[1],
houseColors[(index + nodeId.length) % houseColors.length],
offset[2],
0.78
);
});
}
infrastructure.add(group);
}
function segmentQuaternion(a, b) {
const direction = new THREE.Vector3().subVectors(b, a).normalize();
return new THREE.Quaternion().setFromUnitVectors(xAxis, direction);
}
function makeRoadSegment(aId, bId, color = COLORS.existing) {
const a = nodes[aId].pos;
const b = nodes[bId].pos;
const midpoint = new THREE.Vector3().addVectors(a, b).multiplyScalar(0.5);
const length = a.distanceTo(b);
const quaternion = segmentQuaternion(a, b);
const group = new THREE.Group();
group.position.copy(midpoint);
group.position.y = 0.075;
group.quaternion.copy(quaternion);
const road = box(
length,
0.075,
0.34,
new THREE.MeshStandardMaterial({
color,
roughness: 0.83,
flatShading: true
}),
group
);
road.position.y = 0;
const stripeMaterial = new THREE.MeshBasicMaterial({
color: COLORS.existingStripe,
transparent: true,
opacity: 0.72
});
const stripeCount = Math.max(2, Math.floor(length / 0.62));
const stripeLength = 0.23;
for (let i = 0; i < stripeCount; i++) {
const stripe = box(
stripeLength,
0.012,
0.055,
stripeMaterial,
group
);
stripe.position.set(
-length / 2 +
((i + 0.5) * length) / stripeCount,
0.045,
0
);
}
infrastructure.add(group);
return group;
}
function makeBridge(aId, bId) {
const a = nodes[aId].pos;
const b = nodes[bId].pos;
const midpoint = new THREE.Vector3().addVectors(a, b).multiplyScalar(0.5);
const length = a.distanceTo(b);
const group = new THREE.Group();
group.position.copy(midpoint);
group.position.y = 0.13;
group.quaternion.copy(segmentQuaternion(a, b));
const deck = box(
length,
0.13,
0.55,
new THREE.MeshStandardMaterial({
color: COLORS.bridge,
roughness: 0.92,
flatShading: true
}),
group
);
deck.position.y = 0;
const railMaterial = new THREE.MeshStandardMaterial({
color: COLORS.bridgeRail,
roughness: 0.95,
flatShading: true
});
for (const side of [-1, 1]) {
const rail = box(length, 0.075, 0.065, railMaterial, group);
rail.position.set(0, 0.19, side * 0.285);
const postCount = Math.max(3, Math.floor(length / 0.9));
for (let i = 0; i <= postCount; i++) {
const post = box(
0.07,
0.24,
0.07,
railMaterial,
group
);
post.position.set(
-length / 2 + (i * length) / postCount,
0.16,
side * 0.285
);
}
}
infrastructure.add(group);
return group;
}
function makeWorldDashes(aId, bId, color, y, dashLength, gap, width) {
const a = nodes[aId].pos;
const b = nodes[bId].pos;
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
const quaternion = segmentQuaternion(a, b);
const group = new THREE.Group();
const step = dashLength + gap;
const count = Math.max(1, Math.floor((length + gap) / step));
for (let i = 0; i < count; i++) {
const t = (i * step + dashLength / 2) / length;
const position = new THREE.Vector3().lerpVectors(a, b, t);
position.y = y;
const dash = box(dashLength, 0.065, width, color, group);
dash.position.copy(position);
dash.quaternion.copy(quaternion);
}
return group;
}
function makeCandidateVisual(def) {
const group = new THREE.Group();
const material = new THREE.MeshStandardMaterial({
color: COLORS.candidate,
emissive: 0x4a2800,
emissiveIntensity: 0.22,
roughness: 0.72,
flatShading: true
});
const a = nodes[def.a].pos;
const b = nodes[def.b].pos;
const length = a.distanceTo(b);
const step = 0.54;
const count = Math.max(1, Math.floor(length / step));
const quaternion = segmentQuaternion(a, b);
for (let i = 0; i < count; i++) {
const t = (i + 0.5) / count;
const position = new THREE.Vector3().lerpVectors(a, b, t);
position.y = 0.17;
const dash = box(0.31, 0.07, 0.115, material, group);
dash.position.copy(position);
dash.quaternion.copy(quaternion);
dash.userData.candidate = def.id;
candidatePickObjects.push(dash);
}
for (const nodeId of [def.a, def.b]) {
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.26, 0.045, 5, 18),
material
);
ring.rotation.x = Math.PI / 2;
ring.position.copy(nodes[nodeId].pos);
ring.position.y = 0.18;
group.add(ring);
}
const pick = new THREE.Mesh(
new THREE.BoxGeometry(length, 0.34, 0.34),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
colorWrite: false
})
);
pick.position.copy(a).add(b).multiplyScalar(0.5);
pick.position.y = 0.2;
pick.quaternion.copy(quaternion);
pick.userData.candidate = def.id;
group.add(pick);
candidatePickObjects.push(pick);
candidateLayer.add(group);
candidateGroups.set(def.id, group);
candidateMaterials.set(def.id, material);
}
function addLabel({
html,
className,
position,
onClick,
visible = true
}) {
const element = document.createElement("div");
element.className = `map-label ${className}`;
element.innerHTML = html;
if (onClick) {
element.addEventListener("click", (event) => {
event.stopPropagation();
onClick();
});
}
$("labels").appendChild(element);
const label = {
element,
position: position.clone(),
visible
};
labels.push(label);
return label;
}
function buildScene() {
makeBoard();
makeRiverStrip(1.42, 0.012, COLORS.sand);
makeRiverStrip(0.92, 0.019, COLORS.water);
makeVegetation();
for (const nodeId of Object.keys(nodes)) {
makeStop(nodeId);
const node = nodes[nodeId];
addLabel({
html: `<b>${node.name}</b><small>${node.kind}</small>`,
className: `node-label ${nodeId === state.destination ? "selected" : ""}`,
position: new THREE.Vector3(node.pos.x, 0.95, node.pos.z),
onClick: () => setDestination(nodeId)
});
}
makeRoadSegment("D", "R1");
makeRoadSegment("D", "R3");
makeBridge("R1", "R2");
makeBridge("R3", "K");
const northMid = new THREE.Vector3()
.addVectors(nodes.R1.pos, nodes.R2.pos)
.multiplyScalar(0.5);
const southMid = new THREE.Vector3()
.addVectors(nodes.R3.pos, nodes.K.pos)
.multiplyScalar(0.5);
northBridgeLabel = addLabel({
html: "NORTH BRIDGE · WILL CLOSE",
className: "bridge-label warning",
position: new THREE.Vector3(northMid.x, 0.95, northMid.z)
});
addLabel({
html: "SOUTH BRIDGE",
className: "bridge-label",
position: new THREE.Vector3(southMid.x, 0.85, southMid.z)
});
warningBeacon = new THREE.Group();
warningBeacon.position.set(northMid.x, 0.64, northMid.z);
const beaconMaterial = new THREE.MeshBasicMaterial({
color: COLORS.gold,
transparent: true,
opacity: 0.95
});
const beacon = new THREE.Mesh(
new THREE.OctahedronGeometry(0.18),
beaconMaterial
);
warningBeacon.add(beacon);
const beaconRing = new THREE.Mesh(
new THREE.TorusGeometry(0.29, 0.035, 5, 20),
beaconMaterial
);
beaconRing.rotation.x = Math.PI / 2;
warningBeacon.add(beaconRing);
infrastructure.add(warningBeacon);
northBridgeClosure = new THREE.Group();
northBridgeClosure.position.set(northMid.x, 0.29, northMid.z);
const closureMaterial = new THREE.MeshBasicMaterial({
color: COLORS.red
});
const barA = box(1.0, 0.08, 0.11, closureMaterial, northBridgeClosure);
const barB = box(1.0, 0.08, 0.11, closureMaterial, northBridgeClosure);
barA.rotation.y = Math.PI / 4;
barB.rotation.y = -Math.PI / 4;
northBridgeClosure.visible = false;
infrastructure.add(northBridgeClosure);
for (const def of candidateDefs) {
makeCandidateVisual(def);
const midpoint = new THREE.Vector3()
.addVectors(nodes[def.a].pos, nodes[def.b].pos)
.multiplyScalar(0.5);
const label = addLabel({
html: def.name,
className: "candidate-label",
position: new THREE.Vector3(midpoint.x, 0.62, midpoint.z),
onClick: () => selectCandidate(def.id)
});
candidateGroups.get(def.id).userData.label = label;
}
bus = new THREE.Mesh(
new THREE.SphereGeometry(0.13, 10, 8),
new THREE.MeshBasicMaterial({ color: 0xffffff })
);
bus.visible = false;
routeLayer.add(bus);
}
function edgeWeight(aId, bId) {
const a = nodes[aId].pos;
const b = nodes[bId].pos;
return Math.hypot(b.x - a.x, b.z - a.z);
}
function shortestPath(edges, destination) {
const adjacency = new Map();
for (const nodeId of Object.keys(nodes)) {
adjacency.set(nodeId, []);
}
for (const edge of edges) {
const weight = edgeWeight(edge.a, edge.b);
adjacency.get(edge.a).push({ to: edge.b, weight });
adjacency.get(edge.b).push({ to: edge.a, weight });
}
const distances = new Map();
const previous = new Map();
const unvisited = new Set(Object.keys(nodes));
for (const nodeId of unvisited) {
distances.set(nodeId, Infinity);
}
distances.set("D", 0);
while (unvisited.size > 0) {
let current = null;
let currentDistance = Infinity;
for (const nodeId of unvisited) {
const d = distances.get(nodeId);
if (d < currentDistance) {
current = nodeId;
currentDistance = d;
}
}
if (current === null || currentDistance === Infinity) break;
unvisited.delete(current);
for (const neighbor of adjacency.get(current)) {
const nextDistance = currentDistance + neighbor.weight;
if (nextDistance < distances.get(neighbor.to)) {
distances.set(neighbor.to, nextDistance);
previous.set(neighbor.to, current);
}
}
}
const distance = distances.get(destination);
if (!Number.isFinite(distance)) {
return { distance: Infinity, path: null };
}
const path = [destination];
let cursor = destination;
while (cursor !== "D") {
cursor = previous.get(cursor);
if (!cursor) break;
path.unshift(cursor);
}
return { distance, path };
}
function routeName(path) {
return path ? path.map((id) => nodes[id].name).join(" → ") : "Unreachable";
}
function formatDistance(distance) {
return `${distance.toFixed(2)} u`;
}
function clearGroup(group) {
while (group.children.length) {
const child = group.children[0];
group.remove(child);
child.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const materials = Array.isArray(object.material)
? object.material
: [object.material];
for (const material of materials) material.dispose();
}
});
}
}
function addRouteSegment(group, aId, bId, color, dashed, y) {
const a = nodes[aId].pos;
const b = nodes[bId].pos;
if (dashed) {
const dashes = makeWorldDashes(
aId,
bId,
new THREE.MeshBasicMaterial({ color }),
y,
0.28,
0.16,
0.09
);
group.add(dashes);
} else {
const length = a.distanceTo(b);
const midpoint = new THREE.Vector3().addVectors(a, b).multiplyScalar(0.5);
midpoint.y = y;
const segment = box(
length,
0.065,
0.12,
new THREE.MeshBasicMaterial({ color }),
group
);
segment.position.copy(midpoint);
segment.quaternion.copy(segmentQuaternion(a, b));
}
}
function updateRoutes() {
clearGroup(routeLayer);
const baseline = shortestPath(existingEdges, state.destination);
if (baseline.path) {
for (let i = 0; i < baseline.path.length - 1; i++) {
addRouteSegment(
routeLayer,
baseline.path[i],
baseline.path[i + 1],
COLORS.baseline,
true,
0.255
);
}
}
finalRoutePath = [];
let final = null;
if (state.phase === "result") {
final = shortestPath(state.finalEdges, state.destination);
finalRoutePath = final.path || [];
if (final.path) {
for (let i = 0; i < final.path.length - 1; i++) {
addRouteSegment(
routeLayer,
final.path[i],
final.path[i + 1],
COLORS.final,
false,
0.29
);
}
for (const nodeId of final.path) {
const point = box(
0.17,
0.17,
0.17,
new THREE.MeshBasicMaterial({ color: COLORS.final }),
routeLayer
);
point.position.copy(nodes[nodeId].pos);
point.position.y = 0.32;
}
}
}
if (bus) {
bus.visible = Boolean(finalRoutePath && finalRoutePath.length > 1);
}
let summary = `
<div class="route-line">
<span class="route-swatch"></span>
<span><strong>Baseline:</strong> ${routeName(baseline.path)}
· ${formatDistance(baseline.distance)}</span>
</div>
`;
if (final) {
summary += `
<div class="route-line">
<span class="route-swatch final"></span>
<span><strong>Final:</strong> ${routeName(final.path)}
· ${formatDistance(final.distance)}</span>
</div>
`;
} else {
summary += `
<div class="route-line">
<span class="route-swatch final"></span>
<span><strong>Final:</strong> Build one link and test the closure.</span>
</div>
`;
}
$("route-summary").innerHTML = summary;
}
function updateTable() {
const baselineResults = new Map();
const finalResults = new Map();
for (const destination of destinations) {
baselineResults.set(
destination,
shortestPath(existingEdges, destination)
);
if (state.phase === "result") {
finalResults.set(
destination,
shortestPath(state.finalEdges, destination)
);
}
}
let reachableCount = 0;
$("route-table").innerHTML = destinations
.map((destination) => {
const baseline = baselineResults.get(destination);
const final = finalResults.get(destination);
const reachable = final && Number.isFinite(final.distance);
if (reachable) reachableCount++;
let delta = "—";
let deltaClass = "";
if (final && Number.isFinite(final.distance)) {
const difference = final.distance - baseline.distance;
delta = `${difference >= 0 ? "+" : ""}${difference.toFixed(2)}`;
deltaClass =
difference < -0.001
? "shorter"
: difference > 0.001
? "longer"
: "";
}
const finalText = final
? Number.isFinite(final.distance)
? formatDistance(final.distance)
: "—"
: "—";
const reach = !final
? '<span class="reach-pill pending">Pending</span>'
: reachable
? '<span class="reach-pill">Reachable</span>'
: '<span class="reach-pill no">No route</span>';
const baselineTitle = routeName(baseline.path);
const finalTitle = final ? routeName(final.path) : "Not tested";
return `
<tr data-destination="${destination}"
class="${state.destination === destination ? "selected" : ""}">
<td>${nodes[destination].name}</td>
<td title="${baselineTitle}">${formatDistance(baseline.distance)}</td>
<td title="${finalTitle}">${finalText}</td>
<td class="delta ${deltaClass}">${delta}</td>
<td>${reach}</td>
</tr>
`;
})
.join("");
$("route-table")
.querySelectorAll("tr")
.forEach((row) => {
row.addEventListener("click", () => {
setDestination(row.dataset.destination);
});
});
if (state.phase === "result") {
$("reach-summary").textContent =
`${reachableCount} of ${destinations.length} destinations remain reachable.`;
} else {
$("reach-summary").textContent =
"Baseline: all four destinations are reachable. Final reachability is pending.";
}
}
function updateCurrentLinks() {
const items = existingEdges.map((edge) => {
const isNorth = edge.id === "NBRIDGE";
const closed = isNorth && state.phase === "result";
const bridgeName =
edge.id === "NBRIDGE"
? "North Bridge"
: edge.id === "SBRIDGE"
? "South Bridge"
: "";
const label = `${nodes[edge.a].name} ↔ ${nodes[edge.b].name}${
bridgeName ? ` · ${bridgeName}` : ""
}`;
return `<li class="${edge.type} ${closed ? "closed" : ""}">${label}${
closed ? " · CLOSED" : ""
}</li>`;
});
if (state.builtCandidate) {
const def = candidateDefs.find(
(candidate) => candidate.id === state.builtCandidate
);
items.push(
`<li class="new">${nodes[def.a].name} ↔ ${nodes[def.b].name} · NEW</li>`
);
}
$("link-list").innerHTML = items.join("");
}
function renderCandidateCards() {
$("candidate-list").innerHTML = candidateDefs
.map(
(def) => `
<button class="candidate-card"
data-candidate="${def.id}"
type="button">
<span class="candidate-title">
${def.name}
<span>${def.tagline}</span>
</span>
<span class="candidate-copy">${def.description}</span>
</button>
`
)
.join("");
$("candidate-list")
.querySelectorAll(".candidate-card")
.forEach((button) => {
button.addEventListener("click", () => {
selectCandidate(button.dataset.candidate);
});
});
}
function updateCandidateAppearance() {
for (const def of candidateDefs) {
const material = candidateMaterials.get(def.id);
const selected = state.selectedCandidate === def.id;
material.color.setHex(
selected ? COLORS.candidateSelected : COLORS.candidate
);
material.emissiveIntensity = selected ? 0.48 : 0.22;
const group = candidateGroups.get(def.id);
group.userData.label.element.classList.toggle("selected", selected);
}
document
.querySelectorAll(".candidate-card")
.forEach((button) => {
const selected = button.dataset.candidate === state.selectedCandidate;
button.classList.toggle("selected", selected);
button.disabled = state.phase !== "build";
});
}
function updateStage() {
let text = "";
let buttonText = "";
let disabled = true;
if (state.phase === "build") {
if (state.selectedCandidate) {
const def = candidateDefs.find(
(candidate) => candidate.id === state.selectedCandidate
);
text = `Choice selected: ${def.name}. Build it before testing the closure.`;
buttonText = "Build selected connection";
disabled = false;
} else {
text =
"The closure is already announced. Choose exactly one dashed candidate connection.";
buttonText = "Build selected connection";
}
} else if (state.phase === "test") {
text =
"The new connection is built. The North Bridge is still open; test the closure to calculate final reachability and route lengths.";
buttonText = "Test North Bridge closure";
disabled = false;
} else {
text =
"The North Bridge is closed. Inspect the final network, select another destination, or reset to compare a different valid design.";
buttonText = "Closure tested";
}
$("stage-text").textContent = text;
$("action-button").textContent = buttonText;
$("action-button").disabled = disabled;
const stageDot = document.querySelector(".stage-dot");
stageDot.style.background =
state.phase === "result" ? "var(--green)" : "var(--gold)";
}
function selectCandidate(id) {
if (state.phase !== "build") return;
state.selectedCandidate = id;
updateCandidateAppearance();
updateStage();
}
function removeNewRoad() {
if (!newRoadVisual) return;
infrastructure.remove(newRoadVisual);
newRoadVisual.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const materials = Array.isArray(object.material)
? object.material
: [object.material];
for (const material of materials) material.dispose();
}
});
newRoadVisual = null;
}
function buildSelectedConnection() {
if (
state.phase !== "build" ||
!state.selectedCandidate
) {
return;
}
const def = candidateDefs.find(
(candidate) => candidate.id === state.selectedCandidate
);
state.builtCandidate = def.id;
state.phase = "test";
for (const group of candidateGroups.values()) {
group.visible = false;
}
newRoadVisual = makeRoadSegment(def.a, def.b, COLORS.newRoad);
const beaconMaterial = new THREE.MeshBasicMaterial({
color: COLORS.newRoad
});
for (const nodeId of [def.a, def.b]) {
const beacon = new THREE.Mesh(
new THREE.TorusGeometry(0.31, 0.055, 6, 20),
beaconMaterial
);
beacon.rotation.x = Math.PI / 2;
beacon.position.copy(nodes[nodeId].pos);
beacon.position.y = 0.2;
newRoadVisual.add(beacon);
}
$("closure-text").textContent =
"CLOSURE ANNOUNCED — The North Bridge will close when you test. Your chosen connection is now built.";
updateCandidateAppearance();
updateCurrentLinks();
updateStage();
updateRoutes();
}
function testClosure() {
if (state.phase !== "test") return;
const candidate = candidateDefs.find(
(def) => def.id === state.builtCandidate
);
state.finalEdges = existingEdges
.filter((edge) => edge.id !== "NBRIDGE")
.concat([
{
id: `NEW-${candidate.id}`,
a: candidate.a,
b: candidate.b,
type: "new"
}
]);
state.phase = "result";
northBridgeClosure.visible = true;
warningBeacon.children.forEach((child) => {
child.material.color.setHex(COLORS.red);
});
northBridgeLabel.element.classList.add("warning");
northBridgeLabel.element.innerHTML = "NORTH BRIDGE · CLOSED";
$("closure-banner").classList.add("active");
$("closure-text").textContent =
"CLOSURE ACTIVE — The North Bridge is closed. Final routes use your new connection.";
const harbor = shortestPath(state.finalEdges, "R2");
const baselineHarbor = shortestPath(existingEdges, "R2");
const reachableCount = destinations.filter((destination) => {
const result = shortestPath(state.finalEdges, destination);
return Number.isFinite(result.distance);
}).length;
const difference = harbor.distance - baselineHarbor.distance;
const comparison =
Math.abs(difference) < 0.001
? "The shortest Harbor Homes route has the same length as the baseline."
: difference < 0
? `The shortest Harbor Homes route is ${Math.abs(difference).toFixed(
2
)} u shorter than the baseline.`
: `The shortest Harbor Homes route is ${difference.toFixed(
2
)} u longer than the baseline.`;
$("result-box").classList.add("visible");
$("result-box").innerHTML = `
<strong>VALID NETWORK · ${reachableCount}/4 reachable</strong>
Your ${candidate.name} restores Harbor Homes and keeps every destination
reachable after the North Bridge closes.<br><br>
<b>Harbor Homes final length:</b> ${formatDistance(harbor.distance)}
(${Math.round(harbor.distance * 100)} m). ${comparison}<br><br>
This is a valid design, not the only valid design. Reset to try a
candidate with a different length or redundancy trade-off.
`;
state.attemptHistory.push({
candidate: candidate.name,
distance: harbor.distance,
reachable: reachableCount
});
renderHistory();
updateCandidateAppearance();
updateCurrentLinks();
updateStage();
updateTable();
updateRoutes();
}
function renderHistory() {
if (!state.attemptHistory.length) {
$("history-list").innerHTML =
"<li>No completed attempts yet.</li>";
return;
}
$("history-list").innerHTML = state.attemptHistory
.map(
(attempt, index) => `
<li>
Attempt ${index + 1}: <b>${attempt.candidate}</b> —
${formatDistance(attempt.distance)} to Harbor Homes,
${attempt.reachable}/4 reachable.
</li>
`
)
.join("");
}
function resetAttempt() {
removeNewRoad();
state.phase = "build";
state.selectedCandidate = null;
state.builtCandidate = null;
state.finalEdges = [];
for (const group of candidateGroups.values()) {
group.visible = true;
}
northBridgeClosure.visible = false;
warningBeacon.children.forEach((child) => {
child.material.color.setHex(COLORS.gold);
});
northBridgeLabel.element.classList.remove("warning");
northBridgeLabel.element.innerHTML = "NORTH BRIDGE · WILL CLOSE";
$("closure-banner").classList.remove("active");
$("closure-text").textContent =
"CLOSURE ANNOUNCED — The North Bridge will close during the test. This closure is fixed for every attempt.";
$("result-box").classList.remove("visible");
$("result-box").innerHTML = "";
updateCandidateAppearance();
updateCurrentLinks();
updateStage();
updateTable();
updateRoutes();
}
function setDestination(destination) {
state.destination = destination;
$("destination-select").value = destination;
labels.forEach((label) => {
if (label.element.classList.contains("node-label")) {
const nodeId = Object.keys(nodes).find((id) => {
return label.element.innerHTML.includes(nodes[id].name);
});
label.element.classList.toggle(
"selected",
nodeId === state.destination
);
}
});
updateTable();
updateRoutes();
}
function actionButtonClicked() {
if (state.phase === "build") {
buildSelectedConnection();
} else if (state.phase === "test") {
testClosure();
}
}
$("action-button").addEventListener("click", actionButtonClicked);
$("reset-button").addEventListener("click", resetAttempt);
$("destination-select").addEventListener("change", (event) => {
setDestination(event.target.value);
});
renderCandidateCards();
buildScene();
updateCandidateAppearance();
updateCurrentLinks();
updateStage();
updateTable();
updateRoutes();
// -------------------------------------------------------------------------
// Camera controls: implemented directly, without Three.js addons.
// -------------------------------------------------------------------------
const pointer = new THREE.Vector2();
const raycaster = new THREE.Raycaster();
const drag = {
active: false,
button: 0,
moved: false,
startX: 0,
startY: 0,
previousX: 0,
previousY: 0
};
function updatePointer(event) {
pointer.x = (event.clientX / window.innerWidth) * 2 - 1;
pointer.y = -(event.clientY / window.innerHeight) * 2 + 1;
}
function pickScene(event) {
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
if (state.phase === "build") {
const candidateHits = raycaster.intersectObjects(
candidatePickObjects,
false
);
if (candidateHits.length) {
const id = candidateHits[0].object.userData.candidate;
if (id) {
selectCandidate(id);
return;
}
}
}
const nodeHits = raycaster.intersectObjects(nodePickObjects, false);
if (nodeHits.length) {
const id = nodeHits[0].object.userData.node;
if (id) setDestination(id);
}
}
renderer.domElement.addEventListener("pointerdown", (event) => {
drag.active = true;
drag.button = event.button;
drag.moved = false;
drag.startX = event.clientX;
drag.startY = event.clientY;
drag.previousX = event.clientX;
drag.previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!drag.active) return;
const dx = event.clientX - drag.previousX;
const dy = event.clientY - drag.previousY;
if (
Math.hypot(
event.clientX - drag.startX,
event.clientY - drag.startY
) > 4
) {
drag.moved = true;
}
if (drag.button === 0) {
cameraControl.theta -= dx * 0.005;
cameraControl.phi = THREE.MathUtils.clamp(
cameraControl.phi + dy * 0.004,
0.38,
1.25
);
} else {
const right = new THREE.Vector3();
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
right.crossVectors(forward, camera.up).normalize();
const panScale = cameraControl.radius * 0.0015;
cameraControl.target.addScaledVector(right, -dx * panScale);
cameraControl.target.addScaledVector(forward, -dy * panScale);
cameraControl.target.x = THREE.MathUtils.clamp(
cameraControl.target.x,
-4,
4
);
cameraControl.target.z = THREE.MathUtils.clamp(
cameraControl.target.z,
-3,
3
);
}
drag.previousX = event.clientX;
drag.previousY = event.clientY;
applyCamera();
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (!drag.active) return;
if (!drag.moved && drag.button === 0) {
pickScene(event);
}
drag.active = false;
renderer.domElement.releasePointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointercancel", () => {
drag.active = false;
});
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraControl.radius = THREE.MathUtils.clamp(
cameraControl.radius + event.deltaY * 0.012,
10,
28
);
applyCamera();
},
{ passive: false }
);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
function pointAlongPath(path, t) {
if (!path || path.length < 2) return null;
const lengths = [];
let total = 0;
for (let i = 0; i < path.length - 1; i++) {
const length = nodes[path[i]].pos.distanceTo(
nodes[path[i + 1]].pos
);
lengths.push(length);
total += length;
}
let distance = t * total;
for (let i = 0; i < lengths.length; i++) {
if (distance <= lengths[i] || i === lengths.length - 1) {
const local = lengths[i] === 0 ? 0 : distance / lengths[i];
const point = new THREE.Vector3().lerpVectors(
nodes[path[i]].pos,
nodes[path[i + 1]].pos,
local
);
point.y = 0.47;
return point;
}
distance -= lengths[i];
}
return null;
}
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
if (warningBeacon) {
const pulse = 1 + Math.sin(elapsed * 3.8) * 0.15;
warningBeacon.scale.setScalar(pulse);
warningBeacon.rotation.y = elapsed * 0.9;
}
if (bus && bus.visible && finalRoutePath.length > 1) {
const point = pointAlongPath(
finalRoutePath,
(elapsed * 0.085) % 1
);
if (point) bus.position.copy(point);
}
for (const label of labels) {
const projected = label.position.clone().project(camera);
const onScreen =
projected.z > -1 &&
projected.z < 1 &&
projected.x > -1.15 &&
projected.x < 1.15 &&
projected.y > -1.15 &&
projected.y < 1.15;
if (!label.visible || !onScreen) {
label.element.style.display = "none";
continue;
}
label.element.style.display = "block";
label.element.style.left =
`${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
label.element.style.top =
`${(-projected.y * 0.5 + 0.5) * window.innerHeight}px`;
}
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```