Prompt specification
Build or customize the Three.js 3D scene "Island Clinic Location Strategy" 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: Island Clinic Location Strategy
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/island-clinic-location-strategy-x3579
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts service locations and reachable coverage. Build a fictional planning board with settlements, roads, and limited service sites. Focus on spatial access under simplified rules, without making real healthcare allocation recommendations. Voxel style.
Working Three.js Starter (island-clinic-location-strategy-x3579):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CivicMesh — Fictional Access Planning Board</title>
<style>
:root {
--ink: #193449;
--muted: #687a86;
--paper: #fbfaf4;
--paper-strong: #ffffff;
--line: rgba(25, 52, 73, 0.13);
--teal: #16a895;
--teal-dark: #087d70;
--mint: #72d7bd;
--amber: #e7a83e;
--coral: #df6c57;
--blue: #377fc4;
--shadow: 0 16px 40px rgba(27, 52, 66, 0.14);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dce8e4;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.topbar {
position: fixed;
z-index: 20;
top: 0;
left: 0;
right: 0;
height: 74px;
padding: 12px 20px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
background: rgba(251, 250, 244, 0.91);
border-bottom: 1px solid rgba(25, 52, 73, 0.1);
backdrop-filter: blur(16px);
box-shadow: 0 4px 18px rgba(28, 54, 66, 0.06);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-mark {
width: 42px;
height: 42px;
flex: 0 0 auto;
display: grid;
place-items: center;
border-radius: 12px;
color: white;
background:
linear-gradient(135deg, rgba(255,255,255,0.2), transparent),
var(--teal-dark);
box-shadow:
inset 0 0 0 1px rgba(255,255,255,0.18),
0 7px 18px rgba(8, 125, 112, 0.22);
font-weight: 900;
letter-spacing: -0.06em;
}
.brand-copy {
min-width: 0;
}
.brand-copy strong {
display: block;
font-size: 15px;
line-height: 1.15;
letter-spacing: 0.01em;
}
.brand-copy span {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 11px;
font-weight: 650;
letter-spacing: 0.06em;
text-transform: uppercase;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.top-actions {
display: flex;
align-items: center;
gap: 10px;
}
.scenario-pill,
.synthetic-pill {
display: inline-flex;
align-items: center;
gap: 7px;
min-height: 34px;
padding: 7px 11px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(255,255,255,0.65);
font-size: 11px;
font-weight: 750;
white-space: nowrap;
}
.scenario-pill::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--teal);
box-shadow: 0 0 0 4px rgba(22, 168, 149, 0.12);
}
.synthetic-pill {
color: #78531e;
background: #fff7df;
border-color: rgba(231, 168, 62, 0.28);
}
.panel {
position: fixed;
z-index: 15;
top: 92px;
width: 290px;
max-height: calc(100vh - 176px);
overflow: auto;
padding: 18px;
border: 1px solid rgba(25, 52, 73, 0.11);
border-radius: 18px;
background: rgba(251, 250, 244, 0.93);
backdrop-filter: blur(18px);
box-shadow: var(--shadow);
scrollbar-width: thin;
}
.left-panel {
left: 18px;
}
.info-panel {
right: 18px;
width: 316px;
}
.eyebrow {
margin: 0 0 6px;
color: var(--teal-dark);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.13em;
text-transform: uppercase;
}
h2,
h3,
p {
margin-top: 0;
}
.panel h2 {
margin-bottom: 8px;
font-size: 22px;
line-height: 1.08;
letter-spacing: -0.035em;
}
.panel-intro {
margin-bottom: 18px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.section {
padding-top: 15px;
margin-top: 15px;
border-top: 1px solid var(--line);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 11px;
font-size: 11px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.section-title span:last-child {
color: var(--muted);
font-size: 10px;
letter-spacing: 0.02em;
text-transform: none;
}
.switch-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
font-size: 12px;
font-weight: 700;
}
.switch {
position: relative;
display: inline-flex;
flex: 0 0 auto;
width: 38px;
height: 22px;
}
.switch input {
position: absolute;
opacity: 0;
pointer-events: none;
}
.switch span {
position: absolute;
inset: 0;
border-radius: 999px;
background: #cbd4d2;
transition: background 160ms ease;
cursor: pointer;
}
.switch span::after {
content: "";
position: absolute;
width: 16px;
height: 16px;
top: 3px;
left: 3px;
border-radius: 50%;
background: white;
box-shadow: 0 2px 5px rgba(23, 45, 55, 0.24);
transition: transform 160ms ease;
}
.switch input:checked + span {
background: var(--teal);
}
.switch input:checked + span::after {
transform: translateX(16px);
}
.range-wrap {
margin-top: 14px;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 9px 0 7px;
appearance: none;
border-radius: 99px;
background:
linear-gradient(
to right,
var(--teal) 0%,
var(--teal) var(--range-progress, 45%),
#dce2df var(--range-progress, 45%),
#dce2df 100%
);
accent-color: var(--teal);
}
input[type="range"]::-webkit-slider-thumb {
width: 16px;
height: 16px;
appearance: none;
border: 3px solid white;
border-radius: 50%;
background: var(--teal-dark);
box-shadow: 0 2px 7px rgba(8, 80, 73, 0.28);
cursor: pointer;
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 3px solid white;
border-radius: 50%;
background: var(--teal-dark);
box-shadow: 0 2px 7px rgba(8, 80, 73, 0.28);
cursor: pointer;
}
.range-labels {
display: flex;
justify-content: space-between;
color: var(--muted);
font-size: 10px;
}
.presets {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.preset-button,
.small-button,
.icon-button {
border: 1px solid var(--line);
background: rgba(255,255,255,0.68);
cursor: pointer;
transition:
transform 140ms ease,
border-color 140ms ease,
background 140ms ease;
}
.preset-button:hover,
.small-button:hover,
.icon-button:hover {
transform: translateY(-1px);
border-color: rgba(22, 168, 149, 0.4);
background: white;
}
.preset-button {
min-height: 34px;
padding: 7px 9px;
border-radius: 9px;
font-size: 11px;
font-weight: 750;
}
.preset-button.active {
color: var(--teal-dark);
border-color: rgba(22, 168, 149, 0.35);
background: #e9f8f3;
}
.service-list {
display: grid;
gap: 7px;
}
.service-row {
display: flex;
align-items: center;
gap: 9px;
min-height: 42px;
padding: 6px 8px;
border: 1px solid rgba(25, 52, 73, 0.09);
border-radius: 10px;
background: rgba(255,255,255,0.55);
}
.service-row.selected {
border-color: rgba(22, 168, 149, 0.46);
background: #f0faf6;
}
.service-row .switch {
width: 32px;
height: 19px;
}
.service-row .switch span::after {
width: 13px;
height: 13px;
top: 3px;
}
.service-row .switch input:checked + span::after {
transform: translateX(13px);
}
.service-name {
flex: 1;
min-width: 0;
padding: 0;
border: 0;
background: transparent;
text-align: left;
cursor: pointer;
}
.service-name strong {
display: block;
overflow: hidden;
font-size: 11px;
text-overflow: ellipsis;
white-space: nowrap;
}
.service-name span {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.legend {
display: grid;
gap: 8px;
font-size: 10px;
color: var(--muted);
}
.legend-row {
display: flex;
align-items: center;
gap: 8px;
}
.legend-swatch {
width: 12px;
height: 12px;
border-radius: 3px;
background: var(--mint);
box-shadow: inset 0 0 0 1px rgba(25,52,73,0.1);
}
.legend-swatch.amber {
background: var(--amber);
}
.legend-swatch.gray {
background: #b8c1bf;
}
.legend-swatch.route {
background: transparent;
border-top: 3px dashed #2f9fc0;
border-radius: 0;
height: 3px;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin: 16px 0;
}
.metric {
min-height: 68px;
padding: 11px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255,255,255,0.58);
}
.metric strong {
display: block;
font-size: 19px;
line-height: 1;
letter-spacing: -0.04em;
}
.metric span {
display: block;
margin-top: 7px;
color: var(--muted);
font-size: 9px;
line-height: 1.25;
text-transform: uppercase;
letter-spacing: 0.06em;
}
.status-banner {
margin: 12px 0;
padding: 10px 11px;
border-radius: 10px;
color: #176f64;
background: #e8f7f1;
border: 1px solid rgba(22, 168, 149, 0.18);
font-size: 11px;
line-height: 1.45;
}
.status-banner.outside {
color: #8b5a1c;
background: #fff4dd;
border-color: rgba(231, 168, 62, 0.2);
}
.detail-list {
display: grid;
gap: 4px;
margin-top: 10px;
}
.detail-item {
width: 100%;
display: grid;
grid-template-columns: 9px 1fr auto;
align-items: center;
gap: 8px;
padding: 8px 6px;
border: 0;
border-bottom: 1px solid rgba(25, 52, 73, 0.08);
background: transparent;
text-align: left;
cursor: pointer;
}
.detail-item:hover {
background: rgba(255,255,255,0.65);
border-radius: 7px;
}
.detail-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--mint);
}
.detail-dot.out {
background: var(--amber);
}
.detail-item strong {
font-size: 11px;
}
.detail-item span:last-child {
color: var(--muted);
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.microcopy {
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
.camera-controls {
position: fixed;
z-index: 18;
right: 18px;
bottom: 72px;
display: flex;
gap: 6px;
padding: 6px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(251, 250, 244, 0.91);
backdrop-filter: blur(12px);
box-shadow: var(--shadow);
}
.icon-button {
width: 34px;
height: 34px;
border-radius: 8px;
font-size: 18px;
font-weight: 800;
}
.icon-button.reset {
width: auto;
padding: 0 10px;
font-size: 10px;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.bottom-bar {
position: fixed;
z-index: 20;
left: 0;
right: 0;
bottom: 0;
min-height: 52px;
padding: 10px 18px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
border-top: 1px solid rgba(25, 52, 73, 0.1);
background: rgba(251, 250, 244, 0.94);
backdrop-filter: blur(14px);
font-size: 10px;
}
.disclaimer {
display: flex;
align-items: center;
gap: 9px;
color: #725221;
line-height: 1.35;
}
.disclaimer::before {
content: "!";
width: 20px;
height: 20px;
flex: 0 0 auto;
display: grid;
place-items: center;
border-radius: 50%;
color: white;
background: var(--amber);
font-weight: 900;
}
.interaction-hint {
color: var(--muted);
white-space: nowrap;
}
.tooltip {
position: fixed;
z-index: 50;
display: none;
width: 220px;
padding: 11px 12px;
border: 1px solid rgba(25, 52, 73, 0.12);
border-radius: 11px;
color: var(--ink);
background: rgba(255,255,255,0.96);
box-shadow: 0 12px 32px rgba(20, 43, 56, 0.18);
pointer-events: none;
font-size: 11px;
line-height: 1.45;
}
.tooltip strong {
display: block;
margin-bottom: 3px;
font-size: 12px;
}
.tooltip span {
color: var(--muted);
}
.layer-toggle {
display: none;
border: 1px solid var(--line);
border-radius: 9px;
padding: 8px 10px;
background: rgba(255,255,255,0.75);
font-size: 10px;
font-weight: 800;
cursor: pointer;
}
@media (max-width: 900px) {
.synthetic-pill {
display: none;
}
.panel {
top: 86px;
width: 270px;
max-height: calc(100vh - 155px);
}
.info-panel {
width: 286px;
}
}
@media (max-width: 720px) {
.topbar {
height: 66px;
padding: 10px 12px;
}
.brand-mark {
width: 36px;
height: 36px;
}
.brand-copy span {
display: none;
}
.scenario-pill {
display: none;
}
.layer-toggle {
display: inline-flex;
}
.left-panel {
left: 12px;
top: 78px;
width: min(300px, calc(100vw - 24px));
max-height: calc(100vh - 144px);
transform: translateX(calc(-100% - 20px));
transition: transform 180ms ease;
}
body.layers-open .left-panel {
transform: translateX(0);
}
.info-panel {
left: 12px;
right: 12px;
top: auto;
bottom: 64px;
width: auto;
max-height: 40vh;
}
.camera-controls {
top: 78px;
right: 12px;
bottom: auto;
}
.bottom-bar {
padding: 8px 12px;
}
.interaction-hint {
display: none;
}
}
</style>
</head>
<body>
<div id="viewport"></div>
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true">CM</div>
<div class="brand-copy">
<strong>CivicMesh Planning Board</strong>
<span>Fictional spatial access sandbox</span>
</div>
</div>
<div class="top-actions">
<div class="scenario-pill">Scenario 04 · Road graph</div>
<div class="synthetic-pill">SYNTHETIC DATA</div>
<button id="layerToggle" class="layer-toggle" type="button">Layers</button>
</div>
</header>
<aside class="panel left-panel" aria-label="Scenario controls">
<p class="eyebrow">Access layer</p>
<h2>Road-linked reach</h2>
<p class="panel-intro">
Enable fictional service sites and inspect simulated travel time along
the road network. Coverage follows the shortest available road path.
</p>
<div class="switch-row">
<span>Show reachable coverage</span>
<label class="switch" aria-label="Show reachable coverage">
<input id="coverageToggle" type="checkbox" checked>
<span></span>
</label>
</div>
<div class="range-wrap">
<div class="section-title">
<span>Travel threshold</span>
<span id="thresholdLabel">18 simulated min</span>
</div>
<input
id="thresholdRange"
type="range"
min="10"
max="28"
step="1"
value="18"
aria-label="Travel threshold in simulated minutes"
>
<div class="range-labels">
<span>10 min</span>
<span>28 min</span>
</div>
</div>
<div class="section">
<div class="section-title">
<span>Scenario sites</span>
<span id="siteCount">1 / 3 enabled</span>
</div>
<div id="serviceControls" class="service-list"></div>
</div>
<div class="section">
<div class="section-title">
<span>Quick scenarios</span>
<span>Road graph only</span>
</div>
<div class="presets">
<button class="preset-button" data-preset="all" type="button">All sites</button>
<button class="preset-button" data-preset="west" type="button">West only</button>
<button class="preset-button active" data-preset="junction" type="button">Junction only</button>
<button class="preset-button" data-preset="east" type="button">East only</button>
</div>
</div>
<div class="section">
<div class="section-title">
<span>Legend</span>
<span>Illustrative</span>
</div>
<div class="legend">
<div class="legend-row">
<i class="legend-swatch"></i>
<span>Within selected travel threshold</span>
</div>
<div class="legend-row">
<i class="legend-swatch amber"></i>
<span>Settlement outside selected threshold</span>
</div>
<div class="legend-row">
<i class="legend-swatch gray"></i>
<span>Disabled or inactive service</span>
</div>
<div class="legend-row">
<i class="legend-swatch route"></i>
<span>Shortest road route from selection</span>
</div>
</div>
</div>
</aside>
<aside id="detailsPanel" class="panel info-panel" aria-label="Selection details"></aside>
<div class="camera-controls" aria-label="Camera controls">
<button id="zoomIn" class="icon-button" type="button" aria-label="Zoom in">+</button>
<button id="zoomOut" class="icon-button" type="button" aria-label="Zoom out">−</button>
<button id="resetCamera" class="icon-button reset" type="button">Reset</button>
</div>
<footer class="bottom-bar">
<div class="disclaimer">
<span>
Synthetic geography, population, and travel times. This visual is not a
healthcare needs assessment, capacity model, or allocation recommendation.
</span>
</div>
<div class="interaction-hint">Drag to orbit · Scroll to zoom · Select a settlement or service</div>
</footer>
<div id="tooltip" class="tooltip" role="status"></div>
<noscript>This scene requires JavaScript and WebGL.</noscript>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Fictional data model. Every location, population, distance, and time here
// is invented for an illustrative road-network exercise.
// -------------------------------------------------------------------------
const services = [
{
id: "west",
nodeId: "west",
name: "West Hub",
kind: "Community service hub",
x: -15,
z: 0,
color: 0x2a8fc1,
css: "#2a8fc1"
},
{
id: "junction",
nodeId: "junction",
name: "Junction Post",
kind: "Flexible service desk",
x: 0,
z: 2,
color: 0x16a895,
css: "#16a895"
},
{
id: "east",
nodeId: "east",
name: "East Relay",
kind: "Small relay point",
x: 15,
z: -6,
color: 0xd48a3b,
css: "#d48a3b"
}
];
const settlements = [
{
id: "pinehaven",
nodeId: "pinehaven",
name: "Pinehaven",
population: 620,
x: -9,
z: -9
},
{
id: "north-ridge",
nodeId: "north-ridge",
name: "North Ridge",
population: 310,
x: 6,
z: -10
},
{
id: "easton-mill",
nodeId: "easton-mill",
name: "Easton Mill",
population: 510,
x: 14,
z: 4
},
{
id: "lowbank",
nodeId: "lowbank",
name: "Lowbank",
population: 260,
x: 9,
z: 10
},
{
id: "brookford",
nodeId: "brookford",
name: "Brookford",
population: 430,
x: -7,
z: 8
},
{
id: "cedar-flats",
nodeId: "cedar-flats",
name: "Cedar Flats",
population: 180,
x: -15,
z: 9
}
];
const edgePairs = [
["west", "pinehaven"],
["west", "cedar-flats"],
["west", "junction"],
["pinehaven", "north-ridge"],
["north-ridge", "east"],
["east", "easton-mill"],
["easton-mill", "lowbank"],
["lowbank", "junction"],
["junction", "brookford"],
["brookford", "cedar-flats"],
["pinehaven", "junction"],
["north-ridge", "junction"],
["easton-mill", "junction"]
];
const nodePositions = new Map();
for (const service of services) {
nodePositions.set(service.nodeId, new THREE.Vector3(service.x, 0, service.z));
}
for (const settlement of settlements) {
nodePositions.set(settlement.nodeId, new THREE.Vector3(settlement.x, 0, settlement.z));
}
const edges = edgePairs.map(([a, b]) => {
const pa = nodePositions.get(a);
const pb = nodePositions.get(b);
return {
a,
b,
length: pa.distanceTo(pb),
midpoint: pa.clone().add(pb).multiplyScalar(0.5),
angle: Math.atan2(pb.z - pa.z, pb.x - pa.x)
};
});
const adjacency = new Map();
for (const id of nodePositions.keys()) {
adjacency.set(id, []);
}
for (const edge of edges) {
adjacency.get(edge.a).push({ node: edge.b, edge });
adjacency.get(edge.b).push({ node: edge.a, edge });
}
const WORLD_UNITS_PER_SIMULATED_MINUTE = 1;
const activeServices = new Set(["junction"]);
const entityById = new Map([
...services.map((s) => [s.id, { ...s, type: "service" }]),
...settlements.map((s) => [s.id, { ...s, type: "settlement" }])
]);
let threshold = 18;
let coverageVisible = true;
let selectedEntityId = null;
let accessState = {
perSource: new Map(),
settlementAccess: new Map()
};
// -------------------------------------------------------------------------
// Scene setup
// -------------------------------------------------------------------------
const viewport = document.getElementById("viewport");
const detailsPanel = document.getElementById("detailsPanel");
const tooltip = document.getElementById("tooltip");
const thresholdRange = document.getElementById("thresholdRange");
const thresholdLabel = document.getElementById("thresholdLabel");
const coverageToggle = document.getElementById("coverageToggle");
const serviceControls = document.getElementById("serviceControls");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce8e4);
scene.fog = new THREE.Fog(0xdce8e4, 72, 125);
const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance" });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.domElement.setAttribute("aria-label", "Interactive fictional voxel planning board");
viewport.appendChild(renderer.domElement);
const camera = new THREE.OrthographicCamera(-25, 25, 18, -18, 0.1, 200);
const ambient = new THREE.HemisphereLight(0xf7fff9, 0x7b8c79, 2.0);
scene.add(ambient);
const sun = new THREE.DirectionalLight(0xfff5df, 3.3);
sun.position.set(-20, 38, 16);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -32;
sun.shadow.camera.right = 32;
sun.shadow.camera.top = 30;
sun.shadow.camera.bottom = -30;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 90;
sun.shadow.bias = -0.0005;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0xb9dce3, 1.0);
rimLight.position.set(24, 14, -22);
scene.add(rimLight);
const boxGeometry = new THREE.BoxGeometry(1, 1, 1);
const boardGroup = new THREE.Group();
const roadGroup = new THREE.Group();
const coverageGroup = new THREE.Group();
const routeGroup = new THREE.Group();
const selectionGroup = new THREE.Group();
scene.add(boardGroup, roadGroup, coverageGroup, routeGroup, selectionGroup);
const materials = {
base: new THREE.MeshStandardMaterial({ color: 0x304a52, roughness: 0.88 }),
baseEdge: new THREE.MeshStandardMaterial({ color: 0x22383f, roughness: 0.8 }),
shoulder: new THREE.MeshStandardMaterial({ color: 0xc4b98f, roughness: 1 }),
road: new THREE.MeshStandardMaterial({ color: 0x52616a, roughness: 0.95 }),
dash: new THREE.MeshBasicMaterial({ color: 0xe6d9ac }),
trunk: new THREE.MeshStandardMaterial({ color: 0x775a3c, roughness: 1 }),
leaves: new THREE.MeshStandardMaterial({ color: 0x4f8b66, roughness: 1 }),
leavesLight: new THREE.MeshStandardMaterial({ color: 0x6fa376, roughness: 1 }),
window: new THREE.MeshStandardMaterial({
color: 0x9ad9dd,
emissive: 0x376a70,
emissiveIntensity: 0.25,
roughness: 0.35
}),
route: new THREE.MeshBasicMaterial({
color: 0x2f9fc0,
transparent: true,
opacity: 0.88,
depthWrite: false
}),
routeMuted: new THREE.MeshBasicMaterial({
color: 0xd48a3b,
transparent: true,
opacity: 0.82,
depthWrite: false
}),
selection: new THREE.MeshBasicMaterial({
color: 0xffc857,
transparent: true,
opacity: 0.95,
depthWrite: false
})
};
const pickables = [];
const settlementVisuals = new Map();
const serviceVisuals = new Map();
const coverageMaterialCache = new Map();
function makeBox(width, height, depth, material, x, y, z, rotationY = 0, parent = scene) {
const mesh = new THREE.Mesh(boxGeometry, material);
mesh.scale.set(width, height, depth);
mesh.position.set(x, y, z);
mesh.rotation.y = rotationY;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function randomGenerator(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;
};
}
const random = randomGenerator(4271);
// -------------------------------------------------------------------------
// Voxel terrain board
// -------------------------------------------------------------------------
makeBox(40.7, 0.9, 30.7, materials.base, 0, -0.48, 0);
makeBox(40.9, 0.12, 30.9, materials.baseEdge, 0, -0.05, 0);
const terrainCount = 40 * 30;
const terrain = new THREE.InstancedMesh(
boxGeometry,
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 1,
vertexColors: true
}),
terrainCount
);
const dummy = new THREE.Object3D();
const terrainColor = new THREE.Color();
let terrainIndex = 0;
for (let z = 0; z < 30; z++) {
for (let x = 0; x < 40; x++) {
const wx = x - 19.5;
const wz = z - 14.5;
const isWater = wx < -18.2 && wz > -2 && wz < 5.5;
const hillNoise =
Math.sin(wx * 0.39) * 0.045 +
Math.cos(wz * 0.51) * 0.035 +
(random() - 0.5) * 0.055;
const height = isWater ? 0.045 : Math.max(0.08, 0.17 + hillNoise);
dummy.position.set(wx, height / 2, wz);
dummy.scale.set(0.955, height, 0.955);
dummy.updateMatrix();
terrain.setMatrixAt(terrainIndex, dummy.matrix);
if (isWater) {
terrainColor.set(0x72b8c0);
} else if (wx > 10 && wz < -11) {
terrainColor.set(0x9aaa76);
} else if (wz > 10) {
terrainColor.set(0x9bb77f);
} else {
const tint = random() * 0.06;
terrainColor.setHSL(0.285 + tint, 0.25, 0.57 + random() * 0.055);
}
terrain.setColorAt(terrainIndex, terrainColor);
terrainIndex++;
}
}
terrain.instanceMatrix.needsUpdate = true;
terrain.instanceColor.needsUpdate = true;
terrain.receiveShadow = true;
boardGroup.add(terrain);
// A voxel shoreline detail.
const reedMaterial = new THREE.MeshStandardMaterial({ color: 0x668f64, roughness: 1 });
for (let i = 0; i < 24; i++) {
const z = -1.2 + i * 0.27;
makeBox(
0.10,
0.30 + random() * 0.2,
0.10,
reedMaterial,
-18.45,
0.25,
z
);
}
// -------------------------------------------------------------------------
// Roads and road markings
// -------------------------------------------------------------------------
for (const edge of edges) {
const { a, b, midpoint, length, angle } = edge;
const pa = nodePositions.get(a);
const pb = nodePositions.get(b);
makeBox(
length + 0.18,
0.055,
0.68,
materials.shoulder,
midpoint.x,
0.29,
midpoint.z,
-angle,
roadGroup
);
makeBox(
length + 0.08,
0.07,
0.43,
materials.road,
midpoint.x,
0.35,
midpoint.z,
-angle,
roadGroup
);
const dashCount = Math.max(1, Math.floor(length / 1.35));
for (let i = 0; i < dashCount; i++) {
const t = (i + 0.5) / dashCount;
const x = THREE.MathUtils.lerp(pa.x, pb.x, t);
const z = THREE.MathUtils.lerp(pa.z, pb.z, t);
makeBox(
0.48,
0.025,
0.065,
materials.dash,
x,
0.405,
z,
-angle,
roadGroup
);
}
}
// -------------------------------------------------------------------------
// Trees and small voxel scenery
// -------------------------------------------------------------------------
function pointSegmentDistance(px, pz, ax, az, bx, bz) {
const abx = bx - ax;
const abz = bz - az;
const apx = px - ax;
const apz = pz - az;
const denominator = abx * abx + abz * abz;
const t = denominator
? THREE.MathUtils.clamp((apx * abx + apz * abz) / denominator, 0, 1)
: 0;
const dx = px - (ax + abx * t);
const dz = pz - (az + abz * t);
return Math.hypot(dx, dz);
}
function isClearForTree(x, z) {
for (const position of nodePositions.values()) {
if (Math.hypot(x - position.x, z - position.z) < 2.9) {
return false;
}
}
for (const edge of edges) {
const a = nodePositions.get(edge.a);
const b = nodePositions.get(edge.b);
if (pointSegmentDistance(x, z, a.x, a.z, b.x, b.z) < 1.3) {
return false;
}
}
return true;
}
const treeCount = 68;
const trunks = new THREE.InstancedMesh(boxGeometry, materials.trunk, treeCount);
const crowns = new THREE.InstancedMesh(boxGeometry, materials.leaves, treeCount);
const crownsLight = new THREE.InstancedMesh(boxGeometry, materials.leavesLight, treeCount);
let treesPlaced = 0;
let attempts = 0;
while (treesPlaced < treeCount && attempts < 2000) {
attempts++;
const x = THREE.MathUtils.lerp(-19.4, 19.4, random());
const z = THREE.MathUtils.lerp(-14.4, 14.4, random());
if (!isClearForTree(x, z)) {
continue;
}
const height = 0.48 + random() * 0.34;
const crownSize = 0.55 + random() * 0.30;
dummy.position.set(x, height / 2 + 0.02, z);
dummy.scale.set(0.14, height, 0.14);
dummy.updateMatrix();
trunks.setMatrixAt(treesPlaced, dummy.matrix);
dummy.position.set(x, height + 0.23, z);
dummy.scale.set(crownSize, 0.70, crownSize);
dummy.updateMatrix();
crowns.setMatrixAt(treesPlaced, dummy.matrix);
dummy.position.set(x, height + 0.58, z);
dummy.scale.set(crownSize * 0.66, 0.38, crownSize * 0.66);
dummy.updateMatrix();
crownsLight.setMatrixAt(treesPlaced, dummy.matrix);
treesPlaced++;
}
trunks.count = treesPlaced;
crowns.count = treesPlaced;
crownsLight.count = treesPlaced;
trunks.instanceMatrix.needsUpdate = true;
crowns.instanceMatrix.needsUpdate = true;
crownsLight.instanceMatrix.needsUpdate = true;
trunks.castShadow = true;
crowns.castShadow = true;
crownsLight.castShadow = true;
boardGroup.add(trunks, crowns, crownsLight);
// -------------------------------------------------------------------------
// Labels and place construction
// -------------------------------------------------------------------------
function roundedRect(context, x, y, width, height, radius) {
context.beginPath();
context.moveTo(x + radius, y);
context.lineTo(x + width - radius, y);
context.quadraticCurveTo(x + width, y, x + width, y + radius);
context.lineTo(x + width, y + height - radius);
context.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
context.lineTo(x + radius, y + height);
context.quadraticCurveTo(x, y + height, x, y + height - radius);
context.lineTo(x, y + radius);
context.quadraticCurveTo(x, y, x + radius, y);
context.closePath();
}
function makeLabel(text, subtitle, accent = null) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 160;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(context, 6, 6, 500, 148, 28);
context.fillStyle = accent || "rgba(251,250,244,0.96)";
context.fill();
context.strokeStyle = accent ? "rgba(255,255,255,0.38)" : "rgba(25,52,73,0.13)";
context.lineWidth = 4;
context.stroke();
context.fillStyle = accent ? "#ffffff" : "#193449";
context.font = "800 45px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 256, subtitle ? 62 : 80);
if (subtitle) {
context.globalAlpha = 0.78;
context.font = "650 25px system-ui, sans-serif";
context.fillText(subtitle, 256, 112);
context.globalAlpha = 1;
}
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(4.6, 1.44, 1);
sprite.renderOrder = 20;
return sprite;
}
function makeSquarePad(color, size, parent, y = 0.47) {
const group = new THREE.Group();
const material = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.88,
depthWrite: false
});
const thickness = 0.10;
const length = size;
makeBox(length, 0.06, thickness, material, 0, y, -size / 2, 0, group);
makeBox(length, 0.06, thickness, material, 0, y, size / 2, 0, group);
makeBox(thickness, 0.06, length, material, -size / 2, y, 0, 0, group);
makeBox(thickness, 0.06, length, material, size / 2, y, 0, 0, group);
parent.add(group);
return { group, material };
}
const buildingPalettes = [
[0xe6d8bf, 0xc4a881, 0xd8c3a3],
[0xe8e5d8, 0x9eb5b2, 0xc7d5ce],
[0xe3d3ba, 0xb78c6f, 0xd9b68e]
];
function buildSettlement(settlement, index) {
const group = new THREE.Group();
group.position.set(settlement.x, 0, settlement.z);
group.userData.entityId = settlement.id;
const palette = buildingPalettes[index % buildingPalettes.length];
const offsets = [
[-1.08, -0.90, 0.75, 0.66, 0.92],
[ 1.02, -0.84, 0.70, 0.78, 1.35],
[-1.20, 0.66, 0.78, 0.74, 0.72],
[ 1.03, 0.78, 0.84, 0.65, 1.08],
[ 0.00, 1.15, 0.68, 0.56, 0.76],
[-0.35, -1.25, 0.55, 0.48, 0.62]
];
for (let i = 0; i < offsets.length; i++) {
const [ox, oz, width, depth, height] = offsets[i];
const wallMaterial = new THREE.MeshStandardMaterial({
color: palette[i % palette.length],
roughness: 0.9
});
const wall = makeBox(width, height, depth, wallMaterial, ox, 0.30 + height / 2, oz, 0, group);
wall.castShadow = true;
wall.receiveShadow = true;
wall.userData.entityId = settlement.id;
wall.userData.entityType = "settlement";
pickables.push(wall);
const roofMaterial = new THREE.MeshStandardMaterial({
color: i % 2 ? 0x6c7c77 : 0x8d725e,
roughness: 0.95
});
const roof = makeBox(
width + 0.08,
0.13,
depth + 0.08,
roofMaterial,
ox,
0.30 + height + 0.06,
oz,
0,
group
);
roof.castShadow = true;
roof.userData.entityId = settlement.id;
roof.userData.entityType = "settlement";
pickables.push(roof);
const windowMaterial = materials.window;
const windowMesh = makeBox(
Math.min(0.28, width * 0.34),
0.20,
0.025,
windowMaterial,
ox,
0.30 + height * 0.62,
oz + depth / 2 + 0.02,
0,
group
);
windowMesh.userData.entityId = settlement.id;
windowMesh.userData.entityType = "settlement";
pickables.push(windowMesh);
}
const pad = makeSquarePad(0x72d7bd, 3.05, group);
pad.group.visible = coverageVisible;
const label = makeLabel(settlement.name, `${settlement.population.toLocaleString()} people`);
label.position.set(0, 2.55, 0);
group.add(label);
scene.add(group);
settlementVisuals.set(settlement.id, { group, pad });
}
function buildService(service) {
const group = new THREE.Group();
group.position.set(service.x, 0, service.z);
group.userData.entityId = service.id;
const accentMaterial = new THREE.MeshStandardMaterial({
color: service.color,
roughness: 0.65,
metalness: 0.05
});
const wallMaterial = new THREE.MeshStandardMaterial({
color: 0xf0eee4,
roughness: 0.85
});
const base = makeBox(2.35, 0.22, 2.35, accentMaterial, 0, 0.39, 0, 0, group);
base.castShadow = true;
base.receiveShadow = true;
base.userData.entityId = service.id;
base.userData.entityType = "service";
pickables.push(base);
const main = makeBox(1.45, 1.55, 1.45, wallMaterial, 0, 1.28, 0, 0, group);
main.castShadow = true;
main.receiveShadow = true;
main.userData.entityId = service.id;
main.userData.entityType = "service";
pickables.push(main);
const top = makeBox(1.72, 0.28, 1.72, accentMaterial, 0, 2.18, 0, 0, group);
top.castShadow = true;
top.userData.entityId = service.id;
top.userData.entityType = "service";
pickables.push(top);
const mast = makeBox(0.15, 0.72, 0.15, wallMaterial, 0, 2.66, 0, 0, group);
mast.castShadow = true;
mast.userData.entityId = service.id;
mast.userData.entityType = "service";
pickables.push(mast);
const beaconMaterial = new THREE.MeshBasicMaterial({
color: service.color,
transparent: true,
opacity: 0.9
});
const beacon = makeBox(0.30, 0.30, 0.30, beaconMaterial, 0, 3.12, 0, 0, group);
beacon.userData.entityId = service.id;
beacon.userData.entityType = "service";
pickables.push(beacon);
for (let i = 0; i < 3; i++) {
const windowMesh = makeBox(
0.34,
0.34,
0.025,
materials.window,
(i - 1) * 0.43,
1.30,
0.745,
0,
group
);
windowMesh.userData.entityId = service.id;
windowMesh.userData.entityType = "service";
pickables.push(windowMesh);
}
const pad = makeSquarePad(service.color, 3.25, group);
const label = makeLabel(service.name, service.kind, service.css);
label.position.set(0, 3.85, 0);
label.scale.set(5.0, 1.56, 1);
group.add(label);
scene.add(group);
serviceVisuals.set(service.id, { group, pad, beaconMaterial });
}
settlements.forEach(buildSettlement);
services.forEach(buildService);
// -------------------------------------------------------------------------
// Road graph calculations
// -------------------------------------------------------------------------
function dijkstra(sourceId) {
const distance = new Map();
const previous = new Map();
const unvisited = new Set(nodePositions.keys());
for (const id of unvisited) {
distance.set(id, Infinity);
}
distance.set(sourceId, 0);
while (unvisited.size) {
let current = null;
let currentDistance = Infinity;
for (const id of unvisited) {
const d = distance.get(id);
if (d < currentDistance) {
current = id;
currentDistance = d;
}
}
if (current === null) {
break;
}
unvisited.delete(current);
for (const connection of adjacency.get(current)) {
if (!unvisited.has(connection.node)) {
continue;
}
const weight = connection.edge.length / WORLD_UNITS_PER_SIMULATED_MINUTE;
const nextDistance = currentDistance + weight;
if (nextDistance < distance.get(connection.node)) {
distance.set(connection.node, nextDistance);
previous.set(connection.node, {
node: current,
edge: connection.edge
});
}
}
}
return { distance, previous };
}
function reconstructPath(sourceId, targetId, result) {
const pathEdges = [];
let current = targetId;
const visited = new Set();
while (current !== sourceId) {
if (visited.has(current)) {
return [];
}
visited.add(current);
const step = result.previous.get(current);
if (!step) {
return [];
}
pathEdges.unshift(step.edge);
current = step.node;
}
return pathEdges;
}
function computeAccess() {
const perSource = new Map();
for (const service of services) {
perSource.set(service.id, dijkstra(service.nodeId));
}
const settlementAccess = new Map();
for (const settlement of settlements) {
const candidates = [];
for (const serviceId of activeServices) {
const service = services.find((item) => item.id === serviceId);
const result = perSource.get(serviceId);
candidates.push({
serviceId,
serviceName: service.name,
time: result.distance.get(settlement.nodeId),
result
});
}
candidates.sort((a, b) => a.time - b.time);
settlementAccess.set(settlement.id, candidates);
}
accessState = { perSource, settlementAccess };
}
// -------------------------------------------------------------------------
// Coverage rendering
// -------------------------------------------------------------------------
function getCoverageMaterial(time) {
const ratio = THREE.MathUtils.clamp(time / threshold, 0, 1);
const color = new THREE.Color(0x72d7bd).lerp(new THREE.Color(0xe7a83e), ratio);
const key = color.getHexString();
if (!coverageMaterialCache.has(key)) {
coverageMaterialCache.set(
key,
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.66,
depthWrite: false
})
);
}
return coverageMaterialCache.get(key);
}
function clearGroup(group) {
while (group.children.length) {
group.remove(group.children[group.children.length - 1]);
}
}
function updateCoverage() {
clearGroup(coverageGroup);
coverageGroup.visible = coverageVisible;
if (!coverageVisible || activeServices.size === 0) {
return;
}
for (const edge of edges) {
const pa = nodePositions.get(edge.a);
const pb = nodePositions.get(edge.b);
const segments = Math.max(1, Math.ceil(edge.length / 0.86));
for (let segment = 0; segment < segments; segment++) {
const midpointFraction = (segment + 0.5) / segments;
let bestTime = Infinity;
for (const serviceId of activeServices) {
const result = accessState.perSource.get(serviceId);
const distanceToA = result.distance.get(edge.a);
const distanceToB = result.distance.get(edge.b);
const throughA =
distanceToA + midpointFraction * edge.length / WORLD_UNITS_PER_SIMULATED_MINUTE;
const throughB =
distanceToB + (1 - midpointFraction) * edge.length / WORLD_UNITS_PER_SIMULATED_MINUTE;
bestTime = Math.min(bestTime, throughA, throughB);
}
if (bestTime > threshold) {
continue;
}
const x = THREE.MathUtils.lerp(pa.x, pb.x, midpointFraction);
const z = THREE.MathUtils.lerp(pa.z, pb.z, midpointFraction);
const material = getCoverageMaterial(bestTime);
const tile = makeBox(
0.70,
0.075,
0.60,
material,
x,
0.48,
z,
-edge.angle,
coverageGroup
);
tile.castShadow = false;
tile.receiveShadow = false;
}
}
}
function updatePlaceStatuses() {
for (const settlement of settlements) {
const visual = settlementVisuals.get(settlement.id);
const candidates = accessState.settlementAccess.get(settlement.id);
const covered = candidates.length > 0 && candidates[0].time <= threshold;
visual.pad.group.visible = coverageVisible;
visual.pad.material.color.set(covered ? 0x72d7bd : 0xe7a83e);
visual.pad.material.opacity = covered ? 0.9 : 0.64;
}
for (const service of services) {
const visual = serviceVisuals.get(service.id);
const enabled = activeServices.has(service.id);
visual.pad.material.color.set(enabled ? service.color : 0xaab4b1);
visual.pad.material.opacity = enabled ? 0.92 : 0.45;
}
}
// -------------------------------------------------------------------------
// Selection and route overlays
// -------------------------------------------------------------------------
function updateSelectionMarker() {
clearGroup(selectionGroup);
if (!selectedEntityId) {
return;
}
const entity = entityById.get(selectedEntityId);
const size = entity.type === "service" ? 3.65 : 3.25;
const offset = size / 2;
const arm = 0.72;
const positions = [
[-offset, -offset, 1, 0],
[ offset, -offset, 1, 0],
[-offset, offset, 0, 1],
[ offset, offset, 0, 1]
];
for (const [x, z, horizontal, vertical] of positions) {
const width = horizontal ? arm : 0.12;
const depth = vertical ? arm : 0.12;
makeBox(
width,
0.09,
depth,
materials.selection,
entity.x + x,
0.60,
entity.z + z,
0,
selectionGroup
);
}
}
function drawRoute(edge, material) {
const pa = nodePositions.get(edge.a);
const pb = nodePositions.get(edge.b);
const dashCount = Math.max(2, Math.ceil(edge.length / 0.72));
for (let i = 0; i < dashCount; i++) {
const t = (i + 0.5) / dashCount;
const x = THREE.MathUtils.lerp(pa.x, pb.x, t);
const z = THREE.MathUtils.lerp(pa.z, pb.z, t);
const dash = makeBox(
0.42,
0.055,
0.16,
material,
x,
0.61,
z,
-edge.angle,
routeGroup
);
dash.castShadow = false;
dash.receiveShadow = false;
}
}
function updateRoutes() {
clearGroup(routeGroup);
if (!selectedEntityId) {
return;
}
const entity = entityById.get(selectedEntityId);
if (entity.type === "service") {
const result = accessState.perSource.get(entity.id);
const material = activeServices.has(entity.id) ? materials.route : materials.routeMuted;
for (const settlement of settlements) {
const time = result.distance.get(settlement.nodeId);
if (time > threshold) {
continue;
}
const path = reconstructPath(entity.nodeId, settlement.nodeId, result);
for (const edge of path) {
drawRoute(edge, material);
}
}
}
if (entity.type === "settlement") {
const candidates = accessState.settlementAccess.get(entity.id);
if (candidates.length) {
const nearest = candidates[0];
const path = reconstructPath(
nearest.serviceId,
entity.nodeId,
nearest.result
);
const material =
nearest.time <= threshold ? materials.route : materials.routeMuted;
for (const edge of path) {
drawRoute(edge, material);
}
}
}
}
// -------------------------------------------------------------------------
// UI rendering
// -------------------------------------------------------------------------
function renderServiceControls() {
serviceControls.innerHTML = services.map((service) => `
<div class="service-row ${selectedEntityId === service.id ? "selected" : ""}">
<label class="switch" aria-label="Enable ${service.name}">
<input
type="checkbox"
data-service="${service.id}"
${activeServices.has(service.id) ? "checked" : ""}
>
<span></span>
</label>
<button class="service-name" type="button" data-select-service="${service.id}">
<strong>${service.name}</strong>
<span>${service.kind}</span>
</button>
</div>
`).join("");
document.getElementById("siteCount").textContent =
`${activeServices.size} / ${services.length} enabled`;
}
function metric(value, label) {
return `
<div class="metric">
<strong>${value}</strong>
<span>${label}</span>
</div>
`;
}
function renderDetails() {
if (!selectedEntityId) {
const coveredSettlements = settlements.filter((settlement) => {
const candidates = accessState.settlementAccess.get(settlement.id);
return candidates.length && candidates[0].time <= threshold;
});
const coveredPopulation = coveredSettlements.reduce(
(sum, settlement) => sum + settlement.population,
0
);
const totalPopulation = settlements.reduce(
(sum, settlement) => sum + settlement.population,
0
);
detailsPanel.innerHTML = `
<p class="eyebrow">Scenario snapshot</p>
<h2>Road access</h2>
<p class="panel-intro">
A simplified reachability display over an invented road graph.
Travel time is the shortest path along visible links, not straight-line distance.
</p>
<div class="metric-grid">
${metric(`${coveredSettlements.length}/${settlements.length}`, "Settlements in reach")}
${metric(activeServices.size, "Enabled service sites")}
${metric(`${coveredPopulation.toLocaleString()}`, "Fictional residents covered")}
${metric(`${totalPopulation.toLocaleString()}`, "Fictional population total")}
</div>
<div class="status-banner">
${activeServices.size
? `${coveredSettlements.length} of ${settlements.length} settlements are within ${threshold} simulated minutes of an enabled site.`
: "No service sites are enabled. Select a site to build a scenario."}
</div>
<div class="section-title">
<span>Settlement reach</span>
<span>${threshold} min threshold</span>
</div>
<div class="detail-list">
${settlements.map((settlement) => {
const candidates = accessState.settlementAccess.get(settlement.id);
const nearest = candidates[0];
const inReach = nearest && nearest.time <= threshold;
return `
<button class="detail-item" type="button" data-select-settlement="${settlement.id}">
<i class="detail-dot ${inReach ? "" : "out"}"></i>
<strong>${settlement.name}</strong>
<span>${nearest ? `${nearest.time.toFixed(1)} min` : "—"}</span>
</button>
`;
}).join("")}
</div>
<div class="section">
<p class="microcopy">
The board uses synthetic distances and fixed travel speeds for interaction
and spatial comparison only. It does not infer demand, service capacity,
real travel conditions, or healthcare need.
</p>
</div>
`;
return;
}
const entity = entityById.get(selectedEntityId);
if (entity.type === "settlement") {
const candidates = accessState.settlementAccess.get(entity.id);
const nearest = candidates[0];
const covered = nearest && nearest.time <= threshold;
detailsPanel.innerHTML = `
<p class="eyebrow">Settlement · fictional</p>
<h2>${entity.name}</h2>
<p class="panel-intro">
Fictional population: ${entity.population.toLocaleString()} residents.
Access is calculated from enabled sites over the road graph.
</p>
<div class="metric-grid">
${metric(entity.population.toLocaleString(), "Fictional population")}
${metric(nearest ? `${nearest.time.toFixed(1)} min` : "—", "Nearest enabled path")}
</div>
<div class="status-banner ${covered ? "" : "outside"}">
${!candidates.length
? "No service sites are enabled in this scenario."
: covered
? `Within the selected ${threshold}-minute threshold via ${nearest.serviceName}.`
: `Outside the selected ${threshold}-minute threshold. Nearest enabled path: ${nearest.serviceName}, ${nearest.time.toFixed(1)} simulated minutes.`}
</div>
<div class="section-title">
<span>Enabled-site paths</span>
<span>Road distance</span>
</div>
<div class="detail-list">
${candidates.length
? candidates.map((candidate) => `
<button class="detail-item" type="button" data-select-service="${candidate.serviceId}">
<i class="detail-dot ${candidate.time <= threshold ? "" : "out"}"></i>
<strong>${candidate.serviceName}</strong>
<span>${candidate.time.toFixed(1)} min</span>
</button>
`).join("")
: `<p class="microcopy">Enable at least one service site to calculate a path.</p>`}
</div>
<div class="section">
<p class="microcopy">
The blue route marks the shortest road path from the nearest enabled
site. It is illustrative and does not indicate a service assignment.
</p>
</div>
`;
}
const result = accessState.perSource.get(entity.id);
const serviceIsEnabled = activeServices.has(entity.id);
const reachable = settlements.filter(
(settlement) => result.distance.get(settlement.nodeId) <= threshold
);
detailsPanel.innerHTML = `
<p class="eyebrow">Service site · fictional</p>
<h2>${entity.name}</h2>
<p class="panel-intro">${entity.kind}. Reach below assumes this site were enabled.</p>
<div class="metric-grid">
${metric(`${reachable.length}/${settlements.length}`, "Settlements within threshold")}
${metric(`${threshold} min`, "Selected travel threshold")}
</div>
<div class="status-banner ${serviceIsEnabled ? "" : "outside"}">
${serviceIsEnabled
? "Enabled in the current scenario. Blue dashes show reachable shortest paths."
: "Disabled in the current scenario. Its potential paths are shown in amber."}
</div>
<div class="section-title">
<span>Potential paths</span>
<span>Simulated minutes</span>
</div>
<div class="detail-list">
${settlements.map((settlement) => {
const time = result.distance.get(settlement.nodeId);
return `
<button class="detail-item" type="button" data-select-settlement="${settlement.id}">
<i class="detail-dot ${time <= threshold ? "" : "out"}"></i>
<strong>${settlement.name}</strong>
<span>${time.toFixed(1)} min</span>
</button>
`;
}).join("")}
</div>
<div class="section">
<p class="microcopy">
This site has no modeled capacity, opening schedule, eligibility rule,
demographic weighting, or priority score. Enable or disable it to compare
simple road-network reach.
</p>
</div>
`;
}
function updatePresetButtons() {
document.querySelectorAll(".preset-button").forEach((button) => {
const preset = button.dataset.preset;
let matches = false;
if (preset === "all") {
matches = activeServices.size === services.length;
} else {
matches =
activeServices.size === 1 && activeServices.has(preset);
}
button.classList.toggle("active", matches);
});
}
function updateScenario() {
computeAccess();
updateCoverage();
updatePlaceStatuses();
updateRoutes();
renderServiceControls();
renderDetails();
updatePresetButtons();
}
function selectEntity(entityId) {
selectedEntityId = entityId;
updateSelectionMarker();
updateRoutes();
renderServiceControls();
renderDetails();
}
serviceControls.addEventListener("change", (event) => {
const input = event.target.closest("input[data-service]");
if (!input) {
return;
}
if (input.checked) {
activeServices.add(input.dataset.service);
} else {
activeServices.delete(input.dataset.service);
}
updateScenario();
});
serviceControls.addEventListener("click", (event) => {
const button = event.target.closest("[data-select-service]");
if (button) {
selectEntity(button.dataset.selectService);
}
});
detailsPanel.addEventListener("click", (event) => {
const settlementButton = event.target.closest("[data-select-settlement]");
if (settlementButton) {
selectEntity(settlementButton.dataset.selectSettlement);
return;
}
const serviceButton = event.target.closest("[data-select-service]");
if (serviceButton) {
selectEntity(serviceButton.dataset.selectService);
}
});
document.querySelectorAll(".preset-button").forEach((button) => {
button.addEventListener("click", () => {
activeServices.clear();
if (button.dataset.preset === "all") {
services.forEach((service) => activeServices.add(service.id));
} else {
activeServices.add(button.dataset.preset);
}
updateScenario();
});
});
thresholdRange.addEventListener("input", () => {
threshold = Number(thresholdRange.value);
thresholdLabel.textContent = `${threshold} simulated min`;
const progress =
((threshold - Number(thresholdRange.min)) /
(Number(thresholdRange.max) - Number(thresholdRange.min))) * 100;
thresholdRange.style.setProperty("--range-progress", `${progress}%`);
updateScenario();
});
coverageToggle.addEventListener("change", () => {
coverageVisible = coverageToggle.checked;
updateScenario();
});
document.getElementById("layerToggle").addEventListener("click", () => {
document.body.classList.toggle("layers-open");
});
// -------------------------------------------------------------------------
// Custom camera controls: orbit, zoom, reset, and keyboard support
// -------------------------------------------------------------------------
const cameraState = {
targetTheta: 0.62,
targetPhi: 0.91,
targetZoom: 1.0,
theta: 0.62,
phi: 0.91,
zoom: 1.0,
target: new THREE.Vector3(0, 0, 0)
};
function updateCamera() {
const horizontal = Math.sin(cameraState.phi);
const radius = 70;
camera.position.set(
cameraState.target.x + radius * horizontal * Math.sin(cameraState.theta),
cameraState.target.y + radius * Math.cos(cameraState.phi),
cameraState.target.z + radius * horizontal * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
camera.zoom = cameraState.zoom;
camera.updateProjectionMatrix();
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
const viewHeight = Math.max(30, 42 / aspect);
camera.left = -viewHeight * aspect / 2;
camera.right = viewHeight * aspect / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", resize);
resize();
function resetCamera() {
cameraState.targetTheta = 0.62;
cameraState.targetPhi = 0.91;
cameraState.targetZoom = 1.0;
}
document.getElementById("zoomIn").addEventListener("click", () => {
cameraState.targetZoom = Math.min(2.25, cameraState.targetZoom * 1.12);
});
document.getElementById("zoomOut").addEventListener("click", () => {
cameraState.targetZoom = Math.max(0.62, cameraState.targetZoom / 1.12);
});
document.getElementById("resetCamera").addEventListener("click", resetCamera);
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const pointerState = {
down: false,
moved: false,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0
};
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 pickEntity(event) {
setPointerFromEvent(event);
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(pickables, false);
if (!intersections.length) {
return null;
}
const object = intersections[0].object;
return {
id: object.userData.entityId,
type: object.userData.entityType
};
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) {
return;
}
pointerState.down = true;
pointerState.moved = false;
pointerState.startX = event.clientX;
pointerState.startY = event.clientY;
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
tooltip.style.display = "none";
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (pointerState.down) {
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
if (
Math.hypot(
event.clientX - pointerState.startX,
event.clientY - pointerState.startY
) > 4
) {
pointerState.moved = true;
}
cameraState.targetTheta -= dx * 0.006;
cameraState.targetPhi = THREE.MathUtils.clamp(
cameraState.targetPhi + dy * 0.0045,
0.42,
1.34
);
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
return;
}
const hit = pickEntity(event);
if (!hit) {
renderer.domElement.style.cursor = "grab";
tooltip.style.display = "none";
return;
}
renderer.domElement.style.cursor = "pointer";
const entity = entityById.get(hit.id);
if (entity.type === "service") {
const result = accessState.perSource.get(entity.id);
const reachable = settlements.filter(
(settlement) => result.distance.get(settlement.nodeId) <= threshold
).length;
tooltip.innerHTML = `
<strong>${entity.name}</strong>
<span>${entity.kind}<br>${reachable} settlements within ${threshold} simulated min</span>
`;
} else {
const candidates = accessState.settlementAccess.get(entity.id);
const nearest = candidates[0];
tooltip.innerHTML = `
<strong>${entity.name}</strong>
<span>Fictional population: ${entity.population.toLocaleString()}<br>${
nearest
? `Nearest enabled path: ${nearest.time.toFixed(1)} simulated min`
: "No enabled service site"
}</span>
`;
}
tooltip.style.display = "block";
tooltip.style.left = `${Math.min(window.innerWidth - 235, event.clientX + 14)}px`;
tooltip.style.top = `${Math.min(window.innerHeight - 100, event.clientY + 14)}px`;
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (!pointerState.down) {
return;
}
pointerState.down = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
if (!pointerState.moved) {
const hit = pickEntity(event);
if (hit) {
selectEntity(hit.id);
}
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerState.down = false;
});
renderer.domElement.addEventListener("pointerleave", () => {
if (!pointerState.down) {
tooltip.style.display = "none";
}
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.targetZoom = THREE.MathUtils.clamp(
cameraState.targetZoom * Math.exp(-event.deltaY * 0.001),
0.62,
2.25
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
window.addEventListener("keydown", (event) => {
if (["INPUT", "TEXTAREA", "SELECT"].includes(document.activeElement?.tagName)) {
return;
}
if (event.key === "ArrowLeft") {
cameraState.targetTheta += 0.12;
} else if (event.key === "ArrowRight") {
cameraState.targetTheta -= 0.12;
} else if (event.key === "ArrowUp") {
cameraState.targetPhi = Math.max(0.42, cameraState.targetPhi - 0.08);
} else if (event.key === "ArrowDown") {
cameraState.targetPhi = Math.min(1.34, cameraState.targetPhi + 0.08);
} else if (event.key === "+" || event.key === "=") {
cameraState.targetZoom = Math.min(2.25, cameraState.targetZoom * 1.1);
} else if (event.key === "-") {
cameraState.targetZoom = Math.max(0.62, cameraState.targetZoom / 1.1);
} else if (event.key.toLowerCase() === "r") {
resetCamera();
}
});
// -------------------------------------------------------------------------
// Start the scenario
// -------------------------------------------------------------------------
thresholdRange.dispatchEvent(new Event("input"));
updateScenario();
updateCamera();
renderer.setAnimationLoop(() => {
cameraState.theta += (cameraState.targetTheta - cameraState.theta) * 0.10;
cameraState.phi += (cameraState.targetPhi - cameraState.phi) * 0.10;
cameraState.zoom += (cameraState.targetZoom - cameraState.zoom) * 0.10;
updateCamera();
const pulse = 0.72 + Math.sin(performance.now() * 0.003) * 0.20;
for (const service of services) {
const visual = serviceVisuals.get(service.id);
visual.beaconMaterial.opacity = activeServices.has(service.id) ? pulse : 0.22;
}
renderer.render(scene, camera);
});
</script>
</body>
</html>
```