Prompt specification
Build or customize the Three.js 3D scene "Neighborhood Resilience Planning Table" 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: Neighborhood Resilience Planning Table
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/neighborhood-resilience-planning-table-x3963
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing service networks, reserves, and disruption recovery. Build an original bounded neighborhood with water, power, and access networks represented separately. Compare single failures using explicit synthetic demands and clearly labeled service dependencies. Voxel style.
Working Three.js Starter (neighborhood-resilience-planning-table-x3963):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Resilience District</title>
<style>
:root {
color-scheme: dark;
--bg: #08111d;
--panel: rgba(15, 27, 42, 0.96);
--panel-2: #111f31;
--panel-3: #17283c;
--line: #263a50;
--text: #e8f0f7;
--muted: #91a4b8;
--water: #39bdf2;
--power: #ffc857;
--access: #55d98a;
--failure: #ff4f87;
--danger: #ff7777;
--good: #61e6a4;
}
* {
box-sizing: border-box;
}
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, select, input {
font: inherit;
}
header {
height: 64px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
padding: 0 18px;
border-bottom: 1px solid var(--line);
background: #0c1725;
z-index: 20;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-icon {
width: 32px;
height: 32px;
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 3px;
transform: rotate(-8deg);
}
.brand-icon i {
display: block;
background: var(--water);
border-radius: 2px;
}
.brand-icon i:nth-child(2),
.brand-icon i:nth-child(3) {
background: var(--power);
}
.brand-icon i:nth-child(5) {
background: var(--access);
}
h1 {
margin: 0;
font-size: 17px;
line-height: 1.15;
letter-spacing: 0.01em;
}
.subtitle {
margin-top: 4px;
color: var(--muted);
font-size: 11px;
}
.header-meta {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
justify-content: flex-end;
}
.pill {
border: 1px solid var(--line);
border-radius: 999px;
padding: 6px 9px;
color: #bdcad8;
background: #101d2d;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
white-space: nowrap;
}
.pill.live {
color: #a7f3d0;
border-color: #246149;
background: #10271f;
}
#app {
display: grid;
grid-template-columns: 300px minmax(440px, 1fr) 430px;
height: calc(100vh - 64px);
}
aside {
min-width: 0;
overflow-y: auto;
background: var(--panel);
scrollbar-width: thin;
scrollbar-color: #35506c transparent;
}
.left-panel {
border-right: 1px solid var(--line);
padding: 15px;
}
.right-panel {
border-left: 1px solid var(--line);
padding: 15px;
}
section.card {
margin-bottom: 12px;
padding: 13px;
border: 1px solid var(--line);
border-radius: 10px;
background: linear-gradient(145deg, #132236, #0e1a2a);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin: 0 0 10px;
color: #dce8f4;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.section-title small {
color: var(--muted);
font-size: 9px;
letter-spacing: 0;
text-transform: none;
font-weight: 600;
}
.tiny {
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.tiny strong {
color: #d9e6f2;
}
label.field-label {
display: block;
margin: 0 0 6px;
color: #b9c8d7;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.04em;
text-transform: uppercase;
}
select {
width: 100%;
height: 39px;
padding: 0 34px 0 10px;
border: 1px solid #35506b;
border-radius: 7px;
color: var(--text);
background: #0b1726;
outline: none;
}
select:focus {
border-color: var(--failure);
box-shadow: 0 0 0 2px rgba(255, 79, 135, 0.13);
}
.failure-box {
margin-top: 10px;
padding: 10px;
border-left: 3px solid var(--failure);
border-radius: 6px;
background: rgba(255, 79, 135, 0.075);
}
.failure-box strong {
display: block;
margin-bottom: 4px;
color: #ffb4ca;
font-size: 12px;
}
.failure-box p {
margin: 4px 0 0;
color: #b8c7d5;
font-size: 11px;
line-height: 1.4;
}
.range-head {
display: flex;
align-items: baseline;
justify-content: space-between;
margin-top: 12px;
}
.range-value {
color: #fff;
font-size: 18px;
font-weight: 800;
}
input[type="range"] {
width: 100%;
margin: 8px 0 2px;
accent-color: var(--failure);
}
.timeline {
position: relative;
height: 42px;
margin-top: 5px;
overflow: hidden;
border-radius: 6px;
background:
repeating-linear-gradient(
90deg,
rgba(255,255,255,.045) 0 1px,
transparent 1px 20%
),
#0a1523;
}
.timeline-track {
position: absolute;
left: 10px;
right: 10px;
top: 19px;
height: 3px;
border-radius: 3px;
background: #31465e;
}
.timeline-fill {
position: absolute;
left: 0;
top: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--failure), var(--power));
}
.timeline-marker {
position: absolute;
top: 12px;
width: 2px;
height: 17px;
background: #fff;
}
.timeline-marker.reserve {
background: var(--access);
}
.timeline-marker.now {
width: 8px;
height: 8px;
top: 16px;
border-radius: 2px;
background: #fff;
box-shadow: 0 0 0 3px rgba(255,255,255,.12);
}
.timeline-label {
position: absolute;
top: 0;
transform: translateX(-50%);
color: #cbd8e5;
font-size: 8px;
white-space: nowrap;
}
.layer-list {
display: grid;
gap: 8px;
}
.layer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
cursor: pointer;
}
.layer-name {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
font-size: 12px;
font-weight: 650;
}
.swatch {
width: 17px;
height: 7px;
border-radius: 2px;
background: var(--c);
box-shadow: 0 0 10px color-mix(in srgb, var(--c), transparent 55%);
}
.switch {
position: relative;
width: 34px;
height: 19px;
flex: 0 0 auto;
}
.switch input {
position: absolute;
opacity: 0;
pointer-events: none;
}
.switch i {
position: absolute;
inset: 0;
border-radius: 999px;
background: #34465a;
transition: .18s ease;
}
.switch i::after {
content: "";
position: absolute;
width: 13px;
height: 13px;
left: 3px;
top: 3px;
border-radius: 3px;
background: #d9e4ef;
transition: .18s ease;
}
.switch input:checked + i {
background: #236e83;
}
.switch input:checked + i::after {
transform: translateX(15px);
background: #fff;
}
.table-wrap {
overflow-x: auto;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 10px;
}
th {
padding: 6px 5px;
border-bottom: 1px solid var(--line);
color: #8297aa;
text-align: left;
font-size: 9px;
letter-spacing: .04em;
text-transform: uppercase;
}
td {
padding: 7px 5px;
border-bottom: 1px solid rgba(38, 58, 80, .7);
color: #c7d3df;
vertical-align: top;
}
td.num, th.num {
text-align: right;
font-variant-numeric: tabular-nums;
}
.ledger-site {
color: #e0e9f2;
font-weight: 700;
}
.ledger-people {
color: #7f94a8;
font-size: 9px;
}
details {
margin-top: 9px;
}
summary {
cursor: pointer;
color: #afc1d2;
font-size: 10px;
font-weight: 700;
}
.reserve-item {
padding: 8px 0;
border-bottom: 1px solid rgba(38, 58, 80, .65);
}
.reserve-item:last-child {
border-bottom: 0;
padding-bottom: 0;
}
.reserve-head {
display: flex;
justify-content: space-between;
gap: 8px;
color: #dce6ef;
font-size: 11px;
font-weight: 700;
}
.reserve-head span:last-child {
color: var(--muted);
font-size: 9px;
font-weight: 600;
white-space: nowrap;
}
#viewport {
position: relative;
min-width: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 30%, #16283b, #08111d 70%);
}
#canvas-host, #label-layer {
position: absolute;
inset: 0;
}
#canvas-host canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
#label-layer {
pointer-events: none;
overflow: hidden;
}
.scene-label {
position: absolute;
left: 0;
top: 0;
min-width: 92px;
padding: 6px 7px;
border: 1px solid rgba(130, 158, 184, .36);
border-radius: 6px;
background: rgba(8, 17, 29, .88);
box-shadow: 0 5px 16px rgba(0,0,0,.24);
transform: translate(-50%, -100%);
white-space: nowrap;
backdrop-filter: blur(5px);
}
.scene-label b {
display: block;
color: #eef5fb;
font-size: 10px;
line-height: 1.1;
}
.scene-label > span {
display: block;
margin-top: 2px;
color: #8fa5b9;
font-size: 8px;
}
.scene-label .chips {
display: flex;
gap: 3px;
margin-top: 4px;
}
.mini-chip {
display: inline-block;
padding: 2px 4px;
border-radius: 3px;
font-size: 8px;
font-weight: 800;
line-height: 1;
}
.mini-chip.water {
color: #a9e8ff;
background: rgba(57, 189, 242, .18);
}
.mini-chip.power {
color: #ffe29d;
background: rgba(255, 200, 87, .17);
}
.mini-chip.access {
color: #a8f2c2;
background: rgba(85, 217, 138, .17);
}
.mini-chip.off {
color: #728092;
background: #202b38;
text-decoration: line-through;
}
.scene-label.failed {
border-color: rgba(255, 79, 135, .8);
background: rgba(55, 12, 31, .92);
box-shadow: 0 0 20px rgba(255, 79, 135, .25);
}
.scene-label.failed > span {
color: #ff8eb0;
font-weight: 800;
letter-spacing: .07em;
}
.scene-label.reserve-label {
border-color: rgba(85, 217, 138, .48);
}
.view-tools {
position: absolute;
top: 12px;
right: 12px;
display: flex;
gap: 6px;
z-index: 5;
}
.tool-button {
height: 31px;
padding: 0 10px;
border: 1px solid #344b63;
border-radius: 6px;
color: #c9d7e4;
background: rgba(11, 24, 38, .9);
cursor: pointer;
font-size: 10px;
font-weight: 700;
}
.tool-button:hover {
border-color: #6e8ba7;
background: #172a40;
}
.view-hint {
position: absolute;
left: 12px;
bottom: 12px;
padding: 7px 9px;
border: 1px solid rgba(65, 87, 108, .55);
border-radius: 6px;
color: #8ea3b7;
background: rgba(8, 17, 29, .78);
font-size: 9px;
pointer-events: none;
}
.compass {
position: absolute;
right: 15px;
bottom: 14px;
width: 36px;
height: 36px;
display: grid;
place-items: center;
border: 1px solid #365069;
border-radius: 50%;
color: #d8e6f2;
background: rgba(10, 22, 35, .82);
font-size: 10px;
font-weight: 800;
pointer-events: none;
}
.compass::before {
content: "";
position: absolute;
top: 4px;
border-left: 4px solid transparent;
border-right: 4px solid transparent;
border-bottom: 7px solid var(--failure);
}
.compass span {
margin-top: 8px;
}
#hover-tip {
position: fixed;
display: none;
z-index: 50;
padding: 6px 8px;
border: 1px solid #4a647d;
border-radius: 5px;
color: #edf5fb;
background: #0c1928;
box-shadow: 0 5px 20px rgba(0,0,0,.35);
font-size: 10px;
pointer-events: none;
}
.summary-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 8px;
margin-bottom: 10px;
}
.metric {
padding: 10px;
border: 1px solid var(--line);
border-radius: 8px;
background: #101d2d;
}
.metric-title {
color: #879caf;
font-size: 9px;
font-weight: 750;
letter-spacing: .04em;
text-transform: uppercase;
}
.metric-value {
margin-top: 5px;
color: #f4f8fc;
font-size: 22px;
font-weight: 850;
font-variant-numeric: tabular-nums;
}
.metric-sub {
margin-top: 3px;
color: #8499ad;
font-size: 9px;
line-height: 1.35;
}
.metric.bad .metric-value {
color: #ff9292;
}
.metric.good .metric-value {
color: var(--good);
}
.service-metrics {
display: grid;
gap: 7px;
margin-bottom: 10px;
}
.service-metric {
display: grid;
grid-template-columns: 80px 1fr 52px;
align-items: center;
gap: 8px;
padding: 8px 9px;
border: 1px solid var(--line);
border-radius: 7px;
background: #101d2d;
}
.service-metric .name {
color: var(--c);
font-size: 10px;
font-weight: 800;
}
.bar {
position: relative;
height: 6px;
overflow: hidden;
border-radius: 4px;
background: #263548;
}
.bar span {
position: absolute;
inset: 0 auto 0 0;
width: var(--w);
border-radius: inherit;
background: var(--c);
}
.service-metric .numbers {
color: #cbd7e3;
text-align: right;
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.impact-summary {
margin: 0 0 10px;
padding: 9px 10px;
border: 1px solid #2d445a;
border-radius: 7px;
color: #9eb2c4;
background: #0d1928;
font-size: 10px;
line-height: 1.45;
}
.impact-summary strong {
color: #edf4fa;
}
.compare-table {
table-layout: fixed;
}
.compare-table th,
.compare-table td {
padding: 8px 4px;
}
.compare-table th:first-child,
.compare-table td:first-child {
width: 37%;
}
.compare-table .site-name {
color: #e5edf5;
font-size: 10px;
font-weight: 800;
}
.compare-table .people {
margin-top: 2px;
color: #7890a5;
font-size: 8px;
}
.dep-chips {
display: flex;
flex-wrap: wrap;
gap: 3px;
margin-top: 5px;
}
.dep {
display: inline-flex;
align-items: center;
gap: 3px;
padding: 2px 4px;
border-radius: 3px;
font-size: 7px;
font-weight: 800;
line-height: 1;
}
.dep small {
opacity: .65;
font-size: 6px;
font-weight: 700;
}
.dep.water {
color: #a9e8ff;
background: rgba(57, 189, 242, .14);
}
.dep.power {
color: #ffe29d;
background: rgba(255, 200, 87, .14);
}
.dep.access {
color: #a8f2c2;
background: rgba(85, 217, 138, .14);
}
.dep.off {
color: #677585;
background: #202a35;
text-decoration: line-through;
}
.score {
color: #e3ecf4;
font-size: 10px;
font-weight: 800;
font-variant-numeric: tabular-nums;
}
.score.bad {
color: #ff9191;
}
.score.good {
color: #6ce7aa;
}
.gain {
display: block;
margin-top: 2px;
color: #7e94a8;
font-size: 7px;
font-weight: 600;
}
.gain.positive {
color: #6ce7aa;
}
.model-note {
margin-top: 10px;
padding: 9px 10px;
border-left: 3px solid #41617d;
color: #8ea2b5;
background: #0c1827;
font-size: 9px;
line-height: 1.5;
}
@media (max-width: 1120px) {
html, body {
overflow: auto;
}
#app {
height: auto;
min-height: calc(100vh - 64px);
grid-template-columns: 280px minmax(420px, 1fr);
grid-template-rows: 680px auto;
}
.right-panel {
grid-column: 1 / -1;
border-top: 1px solid var(--line);
border-left: 0;
}
}
@media (max-width: 720px) {
header {
height: auto;
min-height: 64px;
padding: 10px 12px;
}
.header-meta {
display: none;
}
#app {
display: flex;
flex-direction: column;
}
#viewport {
order: 1;
height: 620px;
}
.left-panel {
order: 2;
border-right: 0;
}
.right-panel {
order: 3;
}
}
</style>
</head>
<body>
<header>
<div class="brand">
<div class="brand-icon" aria-hidden="true">
<i></i><i></i><i></i>
<i></i><i></i><i></i>
<i></i><i></i><i></i>
</div>
<div>
<h1>Voxel Resilience District</h1>
<div class="subtitle">Single-failure comparison · synthetic weekday demand · emergency reserves</div>
</div>
</div>
<div class="header-meta">
<span class="pill live">486 residents</span>
<span class="pill">3 separate networks</span>
<span class="pill">1 failed asset at a time</span>
</div>
</header>
<main id="app">
<aside class="left-panel">
<section class="card">
<div class="section-title">
Failure scenario
<small>single asset</small>
</div>
<label class="field-label" for="failure-select">Failed infrastructure</label>
<select id="failure-select" aria-label="Select one failed asset"></select>
<div id="failure-detail" class="failure-box"></div>
</section>
<section class="card">
<div class="section-title">
Recovery horizon
<small>minutes after failure</small>
</div>
<div class="range-head">
<span class="tiny">Selected time</span>
<span id="time-value" class="range-value">15 min</span>
</div>
<input id="recovery-time" type="range" min="0" max="60" step="5" value="15">
<div id="timeline" class="timeline">
<div class="timeline-track">
<div id="timeline-fill" class="timeline-fill"></div>
</div>
<div id="repair-marker" class="timeline-marker"></div>
<div id="reserve-marker" class="timeline-marker reserve"></div>
<div id="now-marker" class="timeline-marker now"></div>
<div id="repair-label" class="timeline-label"></div>
<div id="reserve-label" class="timeline-label"></div>
</div>
<p class="tiny" style="margin-bottom:0">
Repair completion restores normal topology. Before repair,
finite reserves supply disconnected sites in the listed priority order.
</p>
</section>
<section class="card">
<div class="section-title">
Visible layers
<small>click amber cubes to fail</small>
</div>
<div class="layer-list">
<label class="layer">
<span class="layer-name">
<i class="swatch" style="--c:var(--water)"></i>
Water network
</span>
<span class="switch">
<input id="layer-water" type="checkbox" checked><i></i>
</span>
</label>
<label class="layer">
<span class="layer-name">
<i class="swatch" style="--c:var(--power)"></i>
Power network
</span>
<span class="switch">
<input id="layer-power" type="checkbox" checked><i></i>
</span>
</label>
<label class="layer">
<span class="layer-name">
<i class="swatch" style="--c:var(--access)"></i>
Access network
</span>
<span class="switch">
<input id="layer-access" type="checkbox" checked><i></i>
</span>
</label>
<label class="layer">
<span class="layer-name">
<i class="swatch" style="--c:var(--good)"></i>
Emergency reserves
</span>
<span class="switch">
<input id="layer-reserves" type="checkbox" checked><i></i>
</span>
</label>
</div>
<label class="layer" style="margin-top:11px">
<span class="layer-name">Dim unaffected demand sites</span>
<span class="switch">
<input id="isolate-impact" type="checkbox"><i></i>
</span>
</label>
</section>
<section class="card">
<div class="section-title">
Synthetic demand ledger
<small>dependency units / person</small>
</div>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Site</th>
<th class="num">People</th>
<th class="num">W</th>
<th class="num">P</th>
<th class="num">A</th>
</tr>
</thead>
<tbody id="demand-ledger"></tbody>
</table>
</div>
<p class="tiny" style="margin-bottom:0">
W, P, and A are synthetic service-demand coefficients.
People scale each site's service load; they are not forecasts.
</p>
</section>
<section class="card">
<div class="section-title">
Emergency reserves
<small>finite shared capacity</small>
</div>
<div id="reserve-ledger"></div>
</section>
<section class="card">
<details open>
<summary>Model assumptions</summary>
<p class="tiny">
Each service is a separate connectivity graph. A failed node removes
itself and its incident edges; a failed edge removes that edge.
Normal coverage is binary, with no alternate paths, transfer capacity,
repair logistics, or cross-network coupling.
</p>
<p class="tiny">
Site coverage =
(Σ people × dependency coefficient × service availability) /
(Σ people × dependency coefficient).
Reserve coverage is prorated when reserve capacity runs out.
</p>
</details>
</section>
</aside>
<section id="viewport" aria-label="Interactive 3D resilience district">
<div id="canvas-host"></div>
<div id="label-layer"></div>
<div class="view-tools">
<button id="reset-view" class="tool-button" type="button">Reset view</button>
<button id="top-view" class="tool-button" type="button">Top view</button>
</div>
<div class="view-hint">
Drag: orbit · Shift/right drag: pan · Wheel: zoom · Hover amber asset cubes
</div>
<div class="compass"><span>N</span></div>
</section>
<aside class="right-panel">
<section class="card">
<div class="section-title">
Coverage comparison
<small id="scenario-badge" class="pill">active failure</small>
</div>
<div id="summary-grid" class="summary-grid"></div>
<div id="service-metrics" class="service-metrics"></div>
<div id="impact-summary" class="impact-summary"></div>
</section>
<section class="card">
<div class="section-title">
Demand-by-demand result
<small>site service coverage</small>
</div>
<table class="compare-table">
<thead>
<tr>
<th>Site & dependencies</th>
<th class="num">Base</th>
<th class="num">0 min</th>
<th class="num" id="no-res-header">No reserve</th>
<th class="num">+ reserve</th>
</tr>
</thead>
<tbody id="compare-body"></tbody>
</table>
<div class="model-note">
Dependency chips show service, synthetic coefficient, and network
endpoint. Red rows are degraded at the selected horizon. The
“+ reserve” column is always compared with the same failure without reserves.
</div>
</section>
</aside>
</main>
<div id="hover-tip"></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 = {
water: 0x39bdf2,
power: 0xffc857,
access: 0x55d98a,
failure: 0xff4f87,
stranded: 0xff7777,
reserve: 0x61e6a4
};
const SERVICE_NAMES = {
water: "Water",
power: "Power",
access: "Access"
};
const SERVICE_CSS = {
water: "var(--water)",
power: "var(--power)",
access: "var(--access)"
};
/*
Explicit synthetic topology.
Node coordinates are district plan coordinates in the X/Z plane.
Demand endpoints and coefficients are defined below.
*/
const NETWORKS = {
water: {
name: "Water",
source: "w0",
y: 1.35,
thickness: 0.28,
color: COLORS.water,
nodes: {
w0: [-38, -23],
w1: [-24, -22],
w2: [-8, -13],
w3: [5, -3],
w4: [5, 16],
w5: [30, 16],
w6: [30, -17],
w7: [7, -20],
w8: [-8, -7],
w9: [7, 15],
w10: [24, 9],
w11: [30, -16],
w12: [-25, -14]
},
edges: [
["w0", "w1"],
["w1", "w2"],
["w2", "w3"],
["w3", "w4"],
["w4", "w5"],
["w5", "w6"],
["w5", "w10"],
["w4", "w9"],
["w3", "w7"],
["w2", "w8"],
["w1", "w12"]
]
},
power: {
name: "Power",
source: "p0",
y: 6.25,
thickness: 0.17,
color: COLORS.power,
nodes: {
p0: [-38, 18],
p1: [-22, 17],
p2: [-8, -7],
p3: [-8, -20],
p4: [5, 0],
p5: [5, 16],
p6: [30, 16],
p7: [24, 9],
p8: [30, -16],
p9: [7, 15],
p10: [-25, -14],
p11: [7, -20]
},
edges: [
["p0", "p1"],
["p1", "p2"],
["p2", "p3"],
["p3", "p4"],
["p4", "p5"],
["p5", "p6"],
["p6", "p7"],
["p6", "p8"],
["p5", "p9"],
["p1", "p10"],
["p4", "p11"]
]
},
access: {
name: "Access",
source: "a0",
y: 0.28,
thickness: 1.35,
color: COLORS.access,
nodes: {
a0: [-38, 0],
a1: [-20, 0],
a2: [-20, -18],
a3: [0, 0],
a4: [0, 16],
a5: [6, -18],
a6: [15, -18],
a7: [28, -18],
a8: [15, 16],
a9: [28, 16],
a10: [24, 9],
a11: [30, -16],
a12: [5, -20]
},
edges: [
["a0", "a1"],
["a1", "a2"],
["a1", "a3"],
["a3", "a4"],
["a3", "a5"],
["a4", "a8"],
["a8", "a9"],
["a9", "a10"],
["a5", "a6"],
["a6", "a7"],
["a7", "a11"],
["a2", "a12"]
]
}
};
/*
Dependency coefficient is synthetic service units per person.
endpoint identifies the service node required by that demand site.
*/
const DEMANDS = [
{
id: "homes",
name: "Row Houses",
short: "Homes",
people: 120,
position: [-25, -14],
color: 0xa7b7ca,
dependencies: {
water: { endpoint: "w12", coefficient: 0.45 },
power: { endpoint: "p10", coefficient: 0.65 },
access: { endpoint: "a1", coefficient: 0.30 }
}
},
{
id: "clinic",
name: "Health Clinic",
short: "Clinic",
people: 24,
position: [-8, -7],
color: 0xc6d2de,
dependencies: {
water: { endpoint: "w8", coefficient: 0.40 },
power: { endpoint: "p2", coefficient: 0.85 },
access: { endpoint: "a3", coefficient: 0.55 }
}
},
{
id: "school",
name: "Primary School",
short: "School",
people: 180,
position: [7, 15],
color: 0xaebfd1,
dependencies: {
water: { endpoint: "w9", coefficient: 0.55 },
power: { endpoint: "p9", coefficient: 0.60 },
access: { endpoint: "a4", coefficient: 0.45 }
}
},
{
id: "market",
name: "Food Market",
short: "Market",
people: 80,
position: [24, 9],
color: 0xb4c1d0,
dependencies: {
water: { endpoint: "w10", coefficient: 0.65 },
power: { endpoint: "p7", coefficient: 0.50 },
access: { endpoint: "a10", coefficient: 0.70 }
}
},
{
id: "care",
name: "Care Home",
short: "Care Home",
people: 32,
position: [30, -16],
color: 0xc2cedb,
dependencies: {
water: { endpoint: "w11", coefficient: 0.60 },
power: { endpoint: "p8", coefficient: 0.80 },
access: { endpoint: "a11", coefficient: 0.40 }
}
},
{
id: "workshop",
name: "Repair Workshop",
short: "Workshop",
people: 50,
position: [7, -20],
color: 0xaab9ca,
dependencies: {
water: { endpoint: "w7", coefficient: 0.35 },
power: { endpoint: "p11", coefficient: 0.75 },
access: { endpoint: "a12", coefficient: 0.65 }
}
}
];
const ASSETS = [
{
id: "W-01",
network: "water",
label: "Treatment intake",
target: { type: "node", id: "w0" },
repairTime: 45,
description: "Removes the district's only raw-water source. All water demand depends on this node."
},
{
id: "W-02",
network: "water",
label: "West transfer pump",
target: { type: "node", id: "w2" },
repairTime: 30,
description: "Removes the western transfer pump and all downstream water branches."
},
{
id: "W-03",
network: "water",
label: "Central valve",
target: { type: "node", id: "w3" },
repairTime: 25,
description: "Removes the central water junction, stranding the eastern and southern branches."
},
{
id: "P-01",
network: "power",
label: "Grid substation",
target: { type: "node", id: "p0" },
repairTime: 50,
description: "Removes the sole grid intake. All power demand depends on this substation."
},
{
id: "P-02",
network: "power",
label: "Clinic feeder",
target: { type: "node", id: "p2" },
repairTime: 35,
description: "Removes the clinic feeder and the downstream southern and eastern network."
},
{
id: "P-03",
network: "power",
label: "East feeder",
target: { type: "node", id: "p6" },
repairTime: 30,
description: "Removes the eastern feeder, isolating the market and care-home power endpoints."
},
{
id: "A-01",
network: "access",
label: "Municipal depot",
target: { type: "node", id: "a0" },
repairTime: 40,
description: "Removes the access depot and its only road connection into the neighborhood."
},
{
id: "A-02",
network: "access",
label: "West checkpoint",
target: { type: "node", id: "a1" },
repairTime: 30,
description: "Removes the west checkpoint, cutting central, southern, and eastern access branches."
},
{
id: "A-03",
network: "access",
label: "North river bridge",
target: { type: "edge", id: "a4", id2: "a8" },
repairTime: 45,
description: "Removes the northern bridge edge, disconnecting the school and market access paths."
},
{
id: "A-04",
network: "access",
label: "South river bridge",
target: { type: "edge", id: "a5", id2: "a6" },
repairTime: 45,
description: "Removes the southern bridge edge, disconnecting the care-home access path."
}
];
const RESERVES = {
water: {
id: "R-W",
label: "Mobile water tank",
capacity: 180,
duration: 35,
location: [-30, 8],
priority: ["clinic", "care", "homes", "workshop", "market", "school"]
},
power: {
id: "R-P",
label: "Mobile generator",
capacity: 160,
duration: 45,
location: [-38, 8],
priority: ["clinic", "care", "workshop", "market", "homes", "school"]
},
access: {
id: "R-A",
label: "Shuttle + pontoon unit",
capacity: 120,
duration: 30,
location: [15, -27],
priority: ["clinic", "care", "workshop", "market", "homes", "school"]
}
};
let selectedAssetId = "W-02";
let currentTime = 15;
let isolateImpact = false;
// -------------------------------------------------------------------------
// Scene and renderer
// -------------------------------------------------------------------------
const host = $("canvas-host");
const labelLayer = $("label-layer");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x08111d);
scene.fog = new THREE.Fog(0x08111d, 105, 185);
const camera = new THREE.PerspectiveCamera(43, 1, 0.1, 300);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
host.appendChild(renderer.domElement);
const hemi = new THREE.HemisphereLight(0xb9ddff, 0x17202a, 2.0);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff0d4, 3.1);
sun.position.set(-25, 70, 28);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -65;
sun.shadow.camera.right = 65;
sun.shadow.camera.top = 50;
sun.shadow.camera.bottom = -50;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 150;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x6fc8ff, 0.9);
fill.position.set(50, 25, -40);
scene.add(fill);
const cameraState = {
target: new THREE.Vector3(0, 0, 0),
radius: 108,
theta: 0.68,
phi: 0.86
};
function updateCamera() {
const { target, radius, theta, phi } = cameraState;
camera.position.set(
target.x + radius * Math.sin(phi) * Math.sin(theta),
target.y + radius * Math.cos(phi),
target.z + radius * Math.sin(phi) * Math.cos(theta)
);
camera.lookAt(target);
}
function resetCamera() {
cameraState.target.set(0, 0, 0);
cameraState.radius = 108;
cameraState.theta = 0.68;
cameraState.phi = 0.86;
updateCamera();
}
function topCamera() {
cameraState.target.set(0, 0, 0);
cameraState.radius = 105;
cameraState.theta = 0;
cameraState.phi = 0.10;
updateCamera();
}
updateCamera();
// -------------------------------------------------------------------------
// Voxel construction helpers
// -------------------------------------------------------------------------
function addBox(parent, size, position, color, options = {}) {
const geometry = new THREE.BoxGeometry(...size);
const material = options.material || new THREE.MeshStandardMaterial({
color,
roughness: options.roughness ?? 0.78,
metalness: options.metalness ?? 0.05,
emissive: options.emissive ?? 0x000000,
emissiveIntensity: options.emissiveIntensity ?? 0
});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(...position);
mesh.castShadow = options.castShadow ?? true;
mesh.receiveShadow = options.receiveShadow ?? true;
parent.add(mesh);
return mesh;
}
function addAxisSegment(parent, a, b, y, thickness, height, material) {
const dx = b[0] - a[0];
const dz = b[1] - a[1];
if (Math.abs(dx) > 0.001) {
const mesh = addBox(
parent,
[Math.abs(dx) + thickness, height, thickness],
[(a[0] + b[0]) / 2, y, a[1]],
0xffffff,
{ material }
);
return mesh;
}
if (Math.abs(dz) > 0.001) {
const mesh = addBox(
parent,
[thickness, height, Math.abs(dz) + thickness],
[a[0], y, (a[1] + b[1]) / 2],
0xffffff,
{ material }
);
return mesh;
}
return null;
}
function addOrthogonalEdge(parent, a, b, y, thickness, height, material) {
const meshes = [];
const corner = [b[0], a[1]];
if (Math.abs(b[0] - a[0]) > 0.001) {
meshes.push(addAxisSegment(
parent, a, corner, y, thickness, height, material
));
}
if (Math.abs(b[1] - a[1]) > 0.001) {
meshes.push(addAxisSegment(
parent, corner, b, y, thickness, height, material
));
}
return meshes.filter(Boolean);
}
function edgeKey(a, b) {
return [a, b].sort().join("|");
}
function createDistrictBase() {
addBox(scene, [100, 1.5, 70], [0, -0.9, 0], 0x162537);
addBox(scene, [101, 1.2, 2], [0, -0.4, -35], 0x26384a);
addBox(scene, [101, 1.2, 2], [0, -0.4, 35], 0x26384a);
addBox(scene, [2, 1.2, 68], [-50, -0.4, 0], 0x26384a);
addBox(scene, [2, 1.2, 68], [50, -0.4, 0], 0x26384a);
const tiles = [
[-31, -15, 30, 30],
[-6, -8, 31, 34],
[30, -13, 30, 32],
[30, 14, 29, 25],
[-30, 14, 30, 25]
];
for (const [x, z, w, d] of tiles) {
addBox(scene, [w, 0.16, d], [x, -0.03, z], 0x1d3042);
}
// River and stepped banks.
addBox(scene, [6.3, 0.32, 66], [15, 0.04, 0], 0x147ca5);
addBox(scene, [1.2, 0.48, 66], [11.4, 0.08, 0], 0x476675);
addBox(scene, [1.2, 0.48, 66], [18.6, 0.08, 0], 0x476675);
for (let i = 0; i < 18; i++) {
const z = -30 + i * 3.5;
addBox(
scene,
[2.2 + (i % 3) * 0.5, 0.06, 0.65],
[15 + ((i % 2) - 0.5) * 1.2, 0.24, z],
0x3bbde6,
{ castShadow: false }
);
}
// Small deterministic park and plaza blocks.
addBox(scene, [10, 0.2, 8], [-31, 0.12, 13], 0x254b42);
addBox(scene, [8, 0.2, 7], [31, 0.12, -2], 0x31445a);
}
createDistrictBase();
// Trees are deliberately blocky rather than billboarded.
const treePositions = [
[-42, 10], [-40, 12], [-32, 12], [-23, 12], [-14, 11],
[-42, -7], [-42, -4], [-31, -26], [-19, -26], [-12, -27],
[27, 4], [36, 3], [37, -8], [39, 4], [-36, 27],
[-28, 27], [-20, 27], [23, 27], [31, 26], [39, 26]
];
for (const [x, z] of treePositions) {
addBox(scene, [0.45, 1.6, 0.45], [x, 0.8, z], 0x74523b);
addBox(scene, [1.7, 1.7, 1.7], [x, 2.0, z], 0x2d7550);
addBox(scene, [1.1, 0.8, 1.1], [x + 0.2, 2.9, z - 0.1], 0x398b5c);
}
// -------------------------------------------------------------------------
// Network visuals
// -------------------------------------------------------------------------
const networkVisuals = {};
function buildNetwork(key) {
const network = NETWORKS[key];
const group = new THREE.Group();
group.name = `${key} network`;
scene.add(group);
const edgeVisuals = new Map();
const nodeMaterials = new Map();
for (const [id, position] of Object.entries(network.nodes)) {
const markerMaterial = new THREE.MeshStandardMaterial({
color: network.color,
roughness: 0.45,
metalness: 0.08,
emissive: network.color,
emissiveIntensity: key === "power" ? 0.48 : 0.24
});
const size = key === "access" ? 0.62 : 0.72;
const marker = addBox(
group,
[size, size, size],
[position[0], network.y, position[1]],
network.color,
{ material: markerMaterial }
);
marker.userData.network = key;
nodeMaterials.set(id, markerMaterial);
if (key === "power") {
addBox(group, [0.18, 6.0, 0.18], [position[0], 3.0, position[1]], 0x6b7884);
addBox(group, [1.6, 0.16, 0.16], [position[0], 5.65, position[1]], 0x8a96a1);
addBox(group, [1.05, 0.14, 0.14], [position[0], 5.2, position[1]], 0x778590);
} else if (key === "water") {
addBox(group, [0.18, 1.05, 0.18], [position[0], 0.52, position[1]], 0x5d7889);
}
}
for (const [a, b] of network.edges) {
const material = new THREE.MeshStandardMaterial({
color: network.color,
roughness: key === "access" ? 0.95 : 0.48,
metalness: key === "access" ? 0 : 0.12,
emissive: network.color,
emissiveIntensity: key === "access" ? 0.04 : 0.25,
transparent: true,
opacity: 0.96
});
const meshes = addOrthogonalEdge(
group,
network.nodes[a],
network.nodes[b],
network.y,
network.thickness,
key === "access" ? 0.22 : 0.18,
material
);
edgeVisuals.set(edgeKey(a, b), { material, meshes, a, b });
}
networkVisuals[key] = { group, edgeVisuals, nodeMaterials };
}
Object.keys(NETWORKS).forEach(buildNetwork);
// -------------------------------------------------------------------------
// Demand building visuals and labels
// -------------------------------------------------------------------------
const demandVisuals = new Map();
const BUILDING_SPECS = {
homes: { w: 7.5, d: 5.0, h: 4.0 },
clinic: { w: 6.0, d: 5.0, h: 5.0 },
school: { w: 9.0, d: 5.0, h: 4.0 },
market: { w: 7.0, d: 5.0, h: 3.5 },
care: { w: 7.0, d: 5.0, h: 5.2 },
workshop: { w: 8.0, d: 5.0, h: 3.2 }
};
function createSceneLabel(className = "") {
const element = document.createElement("div");
element.className = `scene-label ${className}`;
labelLayer.appendChild(element);
return element;
}
function buildDemandVisual(demand) {
const spec = BUILDING_SPECS[demand.id];
const group = new THREE.Group();
group.position.set(demand.position[0], 0, demand.position[1]);
scene.add(group);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: demand.color,
roughness: 0.84,
metalness: 0.04,
emissive: 0x152131,
emissiveIntensity: 0.18
});
const roofMaterial = new THREE.MeshStandardMaterial({
color: 0x52687f,
roughness: 0.8,
emissive: 0x101a28,
emissiveIntensity: 0.12
});
const bodyMeshes = [];
if (demand.id === "homes") {
for (let i = -1; i <= 1; i++) {
const houseMaterial = bodyMaterial.clone();
bodyMeshes.push(addBox(
group,
[2.1, 3.4 + (i === 0 ? 0.7 : 0), 3.8],
[i * 2.35, (3.4 + (i === 0 ? 0.7 : 0)) / 2, 0],
demand.color,
{ material: houseMaterial }
));
addBox(
group,
[2.4, 0.35, 4.1],
[i * 2.35, 3.55 + (i === 0 ? 0.35 : 0), 0],
0x52687f,
{ material: roofMaterial }
);
}
} else {
bodyMeshes.push(addBox(
group,
[spec.w, spec.h, spec.d],
[0, spec.h / 2, 0],
demand.color,
{ material: bodyMaterial }
));
addBox(
group,
[spec.w + 0.45, 0.48, spec.d + 0.45],
[0, spec.h + 0.18, 0],
0x52687f,
{ material: roofMaterial }
);
if (demand.id === "clinic" || demand.id === "care") {
addBox(group, [2.0, 0.8, 2.0], [0, spec.h + 0.7, 0], 0xdde6ef);
addBox(group, [0.32, 1.1, 0.32], [0, spec.h + 1.55, 0], 0xff6f91);
}
if (demand.id === "school") {
addBox(group, [2.5, 0.65, 2.5], [-2.2, spec.h + 0.72, 0], 0xcbd8e4);
addBox(group, [2.5, 0.65, 2.5], [2.2, spec.h + 0.72, 0], 0xcbd8e4);
}
}
// Small emissive windows.
const windowMaterial = new THREE.MeshStandardMaterial({
color: 0x8ed8ff,
emissive: 0x5fc9ff,
emissiveIntensity: 0.75,
roughness: 0.4
});
const windowCount = demand.id === "school" ? 5 : 3;
for (let i = 0; i < windowCount; i++) {
const x = (i - (windowCount - 1) / 2) * 1.25;
addBox(
group,
[0.62, 0.48, 0.10],
[x, Math.max(1.8, spec.h * 0.55), spec.d / 2 + 0.06],
0x8ed8ff,
{ material: windowMaterial, castShadow: false }
);
}
// Three roof-level service status blocks.
const signals = {};
const services = ["water", "power", "access"];
services.forEach((service, index) => {
const material = new THREE.MeshStandardMaterial({
color: COLORS[service],
emissive: COLORS[service],
emissiveIntensity: 0.9,
roughness: 0.35
});
const signal = addBox(
group,
[0.34, 0.85, 0.34],
[(index - 1) * 0.85, spec.h + 1.15, 0],
COLORS[service],
{ material, castShadow: false }
);
signals[service] = { mesh: signal, material };
});
const label = createSceneLabel();
const worldAnchor = new THREE.Vector3(
demand.position[0],
spec.h + 2.8,
demand.position[1]
);
demandVisuals.set(demand.id, {
group,
bodyMaterial,
bodyMeshes,
roofMaterial,
signals,
label,
worldAnchor
});
}
DEMANDS.forEach(buildDemandVisual);
// -------------------------------------------------------------------------
// Selectable failed-asset markers
// -------------------------------------------------------------------------
const assetVisuals = new Map();
const assetPickMeshes = [];
function assetWorldPosition(asset) {
const network = NETWORKS[asset.network];
if (asset.target.type === "node") {
const p = network.nodes[asset.target.id];
return new THREE.Vector3(p[0], network.y, p[1]);
}
const a = network.nodes[asset.target.id];
const b = network.nodes[asset.target.id2];
return new THREE.Vector3(
(a[0] + b[0]) / 2,
network.y,
(a[1] + b[1]) / 2
);
}
function buildAssetMarker(asset) {
const group = new THREE.Group();
const position = assetWorldPosition(asset);
group.position.copy(position);
networkVisuals[asset.network].group.add(group);
const material = new THREE.MeshStandardMaterial({
color: 0xffb342,
emissive: 0xff8a1f,
emissiveIntensity: 0.55,
roughness: 0.36,
metalness: 0.2
});
const pickMesh = addBox(
group,
[0.85, 0.85, 0.85],
[0, 0.55, 0],
0xffb342,
{ material }
);
pickMesh.userData.assetId = asset.id;
assetPickMeshes.push(pickMesh);
addBox(
group,
[0.24, 0.24, 0.24],
[0, 1.15, 0],
0xffe0a6,
{ material }
);
const beacon = new THREE.Group();
group.add(beacon);
const beaconMaterial = new THREE.MeshBasicMaterial({
color: COLORS.failure,
transparent: true,
opacity: 0.82,
depthWrite: false
});
addBox(beacon, [2.1, 0.08, 0.08], [0, 0.8, -0.65], 0xff4f87, {
material: beaconMaterial, castShadow: false
});
addBox(beacon, [2.1, 0.08, 0.08], [0, 0.8, 0.65], 0xff4f87, {
material: beaconMaterial, castShadow: false
});
addBox(beacon, [0.08, 0.08, 1.3], [-1.05, 0.8, 0], 0xff4f87, {
material: beaconMaterial, castShadow: false
});
addBox(beacon, [0.08, 0.08, 1.3], [1.05, 0.8, 0], 0xff4f87, {
material: beaconMaterial, castShadow: false
});
const beamMaterial = new THREE.MeshBasicMaterial({
color: COLORS.failure,
transparent: true,
opacity: 0.22,
depthWrite: false
});
addBox(beacon, [0.16, 4.2, 0.16], [0, 2.5, 0], 0xff4f87, {
material: beamMaterial,
castShadow: false,
receiveShadow: false
});
beacon.visible = false;
const label = createSceneLabel("failed");
label.style.display = "none";
assetVisuals.set(asset.id, {
group,
beacon,
beaconMaterial,
beamMaterial,
label,
worldAnchor: position.clone().add(new THREE.Vector3(0, 1.6, 0))
});
}
ASSETS.forEach(buildAssetMarker);
// -------------------------------------------------------------------------
// Emergency reserve assets
// -------------------------------------------------------------------------
const reserveGroup = new THREE.Group();
scene.add(reserveGroup);
const reserveVisuals = new Map();
function buildReserveVisual(key) {
const reserve = RESERVES[key];
const group = new THREE.Group();
group.position.set(reserve.location[0], 0, reserve.location[1]);
reserveGroup.add(group);
const color = COLORS[key];
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.38,
roughness: 0.45,
metalness: 0.12
});
if (key === "water") {
addBox(group, [3.8, 0.6, 2.0], [0, 0.45, 0], 0x405569, {
material
});
addBox(group, [1.25, 2.1, 1.25], [-0.8, 1.75, 0], color, {
material
});
addBox(group, [1.25, 2.1, 1.25], [0.8, 1.75, 0], color, {
material
});
addBox(group, [0.8, 0.8, 0.8], [0, 3.05, 0], 0xd5f5ff, {
material
});
} else if (key === "power") {
addBox(group, [3.8, 2.2, 2.2], [0, 1.25, 0], 0x7c613a, {
material
});
addBox(group, [1.2, 0.8, 1.2], [1.4, 2.6, 0], color, {
material
});
addBox(group, [0.35, 1.4, 0.35], [-1.2, 3.1, 0], 0x394a5c);
} else {
addBox(group, [3.8, 0.8, 1.7], [0, 0.55, 0], 0x3d6350, {
material
});
addBox(group, [4.8, 0.35, 1.35], [0.8, 1.25, 0], color, {
material
});
addBox(group, [1.6, 1.0, 1.4], [-1.4, 1.6, 0], 0xd5e8dd, {
material
});
}
const pips = [];
for (let i = 0; i < 5; i++) {
const pipMaterial = new THREE.MeshStandardMaterial({
color: COLORS.reserve,
emissive: COLORS.reserve,
emissiveIntensity: 0.85,
roughness: 0.4
});
const pip = addBox(
group,
[0.38, 0.38, 0.38],
[-1.2 + i * 0.6, 0.25, 1.7],
COLORS.reserve,
{ material: pipMaterial, castShadow: false }
);
pips.push(pipMaterial);
}
const label = createSceneLabel("reserve-label");
label.innerHTML = `
<b>${reserve.id} · ${reserve.label}</b>
<span>${reserve.capacity} units · ${reserve.duration} min</span>
`;
reserveVisuals.set(key, {
group,
pips,
label,
worldAnchor: new THREE.Vector3(
reserve.location[0],
key === "power" ? 4.2 : 3.9,
reserve.location[1]
)
});
}
Object.keys(RESERVES).forEach(buildReserveVisual);
// -------------------------------------------------------------------------
// Connectivity and recovery calculations
// -------------------------------------------------------------------------
function getReach(networkKey, failure) {
const network = NETWORKS[networkKey];
const active = failure && failure.network === networkKey;
const blockedNode = active && failure.target.type === "node"
? failure.target.id
: null;
const blockedEdge = active && failure.target.type === "edge"
? edgeKey(failure.target.id, failure.target.id2)
: null;
if (blockedNode === network.source) {
return new Set();
}
const adjacency = new Map(
Object.keys(network.nodes).map(id => [id, []])
);
for (const [a, b] of network.edges) {
if (blockedNode === a || blockedNode === b) continue;
if (blockedEdge === edgeKey(a, b)) continue;
adjacency.get(a).push(b);
adjacency.get(b).push(a);
}
const reached = new Set([network.source]);
const queue = [network.source];
while (queue.length) {
const current = queue.shift();
for (const next of adjacency.get(current) || []) {
if (!reached.has(next)) {
reached.add(next);
queue.push(next);
}
}
}
return reached;
}
function evaluateAt(failure, minutes, useReserves) {
const reach = {};
for (const key of Object.keys(NETWORKS)) {
reach[key] = getReach(key, failure);
}
const availability = {};
for (const demand of DEMANDS) {
availability[demand.id] = {};
for (const service of ["water", "power", "access"]) {
const endpoint = demand.dependencies[service].endpoint;
const repaired = failure && minutes >= failure.repairTime;
availability[demand.id][service] =
!failure || repaired || reach[service].has(endpoint) ? 1 : 0;
}
}
const reserveUsed = { water: 0, power: 0, access: 0 };
if (failure && useReserves && minutes < failure.repairTime) {
for (const service of ["water", "power", "access"]) {
const reserve = RESERVES[service];
if (minutes >= reserve.duration) continue;
let remaining = reserve.capacity;
for (const demandId of reserve.priority) {
const demand = DEMANDS.find(d => d.id === demandId);
if (availability[demandId][service] >= 1) continue;
const load =
demand.people *
demand.dependencies[service].coefficient;
const allocated = Math.min(remaining, load);
availability[demandId][service] = allocated / load;
reserveUsed[service] += allocated;
remaining -= allocated;
if (remaining <= 0.0001) break;
}
}
}
const networkStats = {};
for (const service of ["water", "power", "access"]) {
let total = 0;
let served = 0;
for (const demand of DEMANDS) {
const load =
demand.people *
demand.dependencies[service].coefficient;
total += load;
served += load * availability[demand.id][service];
}
networkStats[service] = {
total,
served,
coverage: total ? served / total : 1
};
}
const sites = {};
const disconnectedByService = {
water: [],
power: [],
access: []
};
let overallTotal = 0;
let overallServed = 0;
let degradedSites = 0;
let degradedPeople = 0;
for (const demand of DEMANDS) {
let siteTotal = 0;
let siteServed = 0;
for (const service of ["water", "power", "access"]) {
const load =
demand.people *
demand.dependencies[service].coefficient;
const available = availability[demand.id][service];
siteTotal += load;
siteServed += load * available;
if (available === 0) {
disconnectedByService[service].push(demand.short);
}
}
const coverage = siteTotal ? siteServed / siteTotal : 1;
sites[demand.id] = coverage;
overallTotal += siteTotal;
overallServed += siteServed;
if (coverage < 0.9999) {
degradedSites++;
degradedPeople += demand.people;
}
}
return {
availability,
sites,
networkStats,
disconnectedByService,
reserveUsed,
overall: overallTotal ? overallServed / overallTotal : 1,
degradedSites,
degradedPeople
};
}
function evaluateScenario() {
const failure = ASSETS.find(a => a.id === selectedAssetId) || null;
return {
failure,
baseline: evaluateAt(null, 0, false),
immediate: evaluateAt(failure, 0, false),
noReserves: evaluateAt(failure, currentTime, false),
withReserves: evaluateAt(failure, currentTime, true)
};
}
// -------------------------------------------------------------------------
// UI construction and rendering
// -------------------------------------------------------------------------
function percent(value) {
return `${Math.round(value * 100)}%`;
}
function signedPoints(value) {
if (Math.abs(value) < 0.0005) return "0 pp";
return `${value > 0 ? "+" : "−"}${Math.round(Math.abs(value) * 100)} pp`;
}
function buildSelect() {
const select = $("failure-select");
select.innerHTML = `<option value="">Baseline — no failure</option>`;
for (const key of ["water", "power", "access"]) {
const group = document.createElement("optgroup");
group.label = `${SERVICE_NAMES[key]} assets`;
for (const asset of ASSETS.filter(a => a.network === key)) {
const option = document.createElement("option");
option.value = asset.id;
option.textContent = `${asset.id} — ${asset.label}`;
group.appendChild(option);
}
select.appendChild(group);
}
select.value = selectedAssetId;
}
function buildLedgers() {
$("demand-ledger").innerHTML = DEMANDS.map(d => `
<tr>
<td>
<div class="ledger-site">${d.short}</div>
<div class="ledger-people">${d.dependencies.water.coefficient.toFixed(2)} W / person</div>
</td>
<td class="num">${d.people}</td>
<td class="num">${d.dependencies.water.coefficient.toFixed(2)}</td>
<td class="num">${d.dependencies.power.coefficient.toFixed(2)}</td>
<td class="num">${d.dependencies.access.coefficient.toFixed(2)}</td>
</tr>
`).join("");
$("reserve-ledger").innerHTML = Object.entries(RESERVES).map(([key, reserve]) => {
const names = reserve.priority
.map(id => DEMANDS.find(d => d.id === id).short)
.join(" → ");
return `
<div class="reserve-item">
<div class="reserve-head">
<span style="color:${SERVICE_CSS[key]}">${reserve.id} · ${reserve.label}</span>
<span>${reserve.capacity}u / ${reserve.duration}m</span>
</div>
<div class="tiny" style="margin-top:4px">
Priority: ${names}
</div>
</div>
`;
}).join("");
}
function renderSummary(results) {
const { baseline, immediate, noReserves, withReserves, failure } = results;
const metrics = [
{
title: "Normal baseline",
value: percent(baseline.overall),
sub: "All six sites connected",
className: "good"
},
{
title: "Failure at 0 min",
value: percent(immediate.overall),
sub: "No reserve intervention",
className: "bad"
},
{
title: `No reserve @ ${currentTime}m`,
value: percent(noReserves.overall),
sub: failure ? "Topology only" : "No active failure",
className: noReserves.overall < 0.9999 ? "bad" : "good"
},
{
title: `+ reserve @ ${currentTime}m`,
value: percent(withReserves.overall),
sub: failure ? "Finite emergency support" : "No active failure",
className: "good"
}
];
$("summary-grid").innerHTML = metrics.map(metric => `
<div class="metric ${metric.className}">
<div class="metric-title">${metric.title}</div>
<div class="metric-value">${metric.value}</div>
<div class="metric-sub">${metric.sub}</div>
</div>
`).join("");
$("service-metrics").innerHTML = ["water", "power", "access"].map(service => {
const base = baseline.networkStats[service].coverage;
const no = noReserves.networkStats[service].coverage;
const yes = withReserves.networkStats[service].coverage;
return `
<div class="service-metric" style="--c:${SERVICE_CSS[service]}">
<div class="name">${SERVICE_NAMES[service]}</div>
<div class="bar"><span style="--w:${yes * 100}%"></span></div>
<div class="numbers">${percent(no)} → ${percent(yes)}</div>
</div>
`;
}).join("");
const gain = withReserves.overall - noReserves.overall;
const affectedNo = noReserves.degradedSites;
const affectedYes = withReserves.degradedSites;
$("impact-summary").innerHTML = `
<strong>${failure ? `${failure.id} active` : "Baseline topology"}</strong> ·
Immediate overall loss: ${signedPoints(immediate.overall - baseline.overall)}.<br>
At ${currentTime} min without reserves,
<strong>${affectedNo}/6 sites</strong> are degraded
(${noReserves.degradedPeople} people).<br>
Reserves reduce this to <strong>${affectedYes}/6 sites</strong>
(${withReserves.degradedPeople} people) and improve overall coverage by
<strong>${signedPoints(gain)}</strong>.
`;
$("scenario-badge").textContent = failure
? `${failure.id} active`
: "baseline";
$("no-res-header").textContent = `No res. @ ${currentTime}m`;
}
function renderComparison(results) {
$("compare-body").innerHTML = DEMANDS.map(demand => {
const base = results.baseline.sites[demand.id];
const immediate = results.immediate.sites[demand.id];
const no = results.noReserves.sites[demand.id];
const yes = results.withReserves.sites[demand.id];
const gain = yes - no;
const degraded = no < 0.9999;
const chips = ["water", "power", "access"].map(service => {
const dependency = demand.dependencies[service];
const available = results.noReserves.availability[demand.id][service] >= 1;
return `
<span
class="dep ${service} ${available ? "" : "off"}"
title="${SERVICE_NAMES[service]}: ${dependency.coefficient.toFixed(2)} units/person via ${dependency.endpoint}"
>
${service[0].toUpperCase()} ${dependency.coefficient.toFixed(2)}
<small>${dependency.endpoint}</small>
</span>
`;
}).join("");
return `
<tr style="${degraded ? "background:rgba(255,79,135,.045)" : ""}">
<td>
<div class="site-name">${demand.short}</div>
<div class="people">${demand.people} people</div>
<div class="dep-chips">${chips}</div>
</td>
<td class="num">
<span class="score">${percent(base)}</span>
</td>
<td class="num">
<span class="score ${immediate < .9999 ? "bad" : "good"}">${percent(immediate)}</span>
</td>
<td class="num">
<span class="score ${no < .9999 ? "bad" : "good"}">${percent(no)}</span>
</td>
<td class="num">
<span class="score ${yes < .9999 ? "bad" : "good"}">${percent(yes)}</span>
<span class="gain ${gain > 0 ? "positive" : ""}">${signedPoints(gain)}</span>
</td>
</tr>
`;
}).join("");
}
function renderFailureDetail(results) {
const box = $("failure-detail");
if (!results.failure) {
box.innerHTML = `
<strong>Baseline comparison</strong>
<p>
No infrastructure is failed. The normal table still provides the
baseline against which any single asset can be selected.
</p>
`;
return;
}
const asset = results.failure;
const state = currentTime >= asset.repairTime
? "repair complete; normal service restored"
: `repair pending; estimated completion at ${asset.repairTime} min`;
const disconnected = results.noReserves.disconnectedByService[asset.network];
const disconnectedText = disconnected.length
? disconnected.join(", ")
: "none";
const reserve = RESERVES[asset.network];
const used = results.withReserves.reserveUsed[asset.network];
const reserveState = currentTime < asset.repairTime
? currentTime < reserve.duration
? `${Math.round(used)}/${reserve.capacity} units deployed`
: "reserve expired"
: "reserve no longer required";
box.innerHTML = `
<strong>${asset.id} · ${asset.label} failed</strong>
<p>${asset.description}</p>
<p><b>At ${currentTime} min:</b> ${state}.</p>
<p><b>Disconnected ${SERVICE_NAMES[asset.network]} sites:</b> ${disconnectedText}.</p>
<p><b>${reserve.id} reserve:</b> ${reserveState}.</p>
`;
}
function renderTimeline(results) {
$("time-value").textContent = `${currentTime} min`;
const nowPercent = currentTime / 60 * 100;
$("now-marker").style.left = `calc(10px + (100% - 20px) * ${nowPercent / 100})`;
$("timeline-fill").style.width = `${nowPercent}%`;
if (!results.failure) {
$("repair-marker").style.display = "none";
$("reserve-marker").style.display = "none";
$("repair-label").style.display = "none";
$("reserve-label").style.display = "none";
return;
}
const repairPercent = results.failure.repairTime / 60 * 100;
const reserve = RESERVES[results.failure.network];
const reservePercent = reserve.duration / 60 * 100;
$("repair-marker").style.display = "block";
$("reserve-marker").style.display = "block";
$("repair-label").style.display = "block";
$("reserve-label").style.display = "block";
$("repair-marker").style.left = `calc(10px + (100% - 20px) * ${repairPercent / 100})`;
$("reserve-marker").style.left = `calc(10px + (100% - 20px) * ${reservePercent / 100})`;
$("repair-label").style.left = `calc(10px + (100% - 20px) * ${repairPercent / 100})`;
$("reserve-label").style.left = `calc(10px + (100% - 20px) * ${reservePercent / 100})`;
$("repair-label").textContent = `repair ${results.failure.repairTime}m`;
$("reserve-label").textContent = `reserve ends ${reserve.duration}m`;
}
// -------------------------------------------------------------------------
// Scene state visualization
// -------------------------------------------------------------------------
function updateNetworkVisuals(results) {
const failure = results.failure;
for (const key of Object.keys(NETWORKS)) {
const network = NETWORKS[key];
const visual = networkVisuals[key];
const reach = getReach(key, failure);
for (const [edgeId, edge] of visual.edgeVisuals) {
let color = network.color;
let emissiveIntensity = key === "access" ? 0.04 : 0.25;
if (failure && failure.network === key) {
const directlyFailed =
failure.target.type === "edge" &&
edgeId === edgeKey(failure.target.id, failure.target.id2);
const touchesFailedNode =
failure.target.type === "node" &&
(edge.a === failure.target.id || edge.b === failure.target.id);
if (directlyFailed || touchesFailedNode) {
color = COLORS.failure;
emissiveIntensity = 0.65;
} else if (!reach.has(edge.a) || !reach.has(edge.b)) {
color = COLORS.stranded;
emissiveIntensity = 0.38;
}
}
edge.material.color.setHex(color);
edge.material.emissive.setHex(color);
edge.material.emissiveIntensity = emissiveIntensity;
edge.material.opacity = color === network.color ? 0.96 : 0.88;
}
for (const [id, material] of visual.nodeMaterials) {
let color = network.color;
let intensity = key === "power" ? 0.48 : 0.24;
if (failure && failure.network === key) {
if (failure.target.type === "node" && id === failure.target.id) {
color = COLORS.failure;
intensity = 0.85;
} else if (!reach.has(id)) {
color = COLORS.stranded;
intensity = 0.38;
}
}
material.color.setHex(color);
material.emissive.setHex(color);
material.emissiveIntensity = intensity;
}
}
}
function updateDemandVisuals(results) {
for (const demand of DEMANDS) {
const visual = demandVisuals.get(demand.id);
const noCoverage = results.noReserves.sites[demand.id];
const affected = noCoverage < 0.9999;
let bodyColor = 0x93a5b8;
let emissive = 0x152131;
let intensity = 0.18;
if (affected) {
bodyColor = 0xe98782;
emissive = 0x6d1729;
intensity = 0.38;
} else if (isolateImpact && results.failure) {
bodyColor = 0x3b4b5e;
emissive = 0x111923;
intensity = 0.08;
}
visual.bodyMaterial.color.setHex(bodyColor);
visual.bodyMaterial.emissive.setHex(emissive);
visual.bodyMaterial.emissiveIntensity = intensity;
for (const mesh of visual.bodyMeshes) {
if (mesh.material !== visual.bodyMaterial) {
mesh.material.color.setHex(bodyColor);
mesh.material.emissive.setHex(emissive);
mesh.material.emissiveIntensity = intensity;
}
}
const chips = ["water", "power", "access"].map(service => {
const available =
results.noReserves.availability[demand.id][service] >= 1;
return `
<span class="mini-chip ${service} ${available ? "" : "off"}">
${service[0].toUpperCase()}${demand.dependencies[service].coefficient.toFixed(2)}
</span>
`;
}).join("");
visual.label.innerHTML = `
<b>${demand.short}</b>
<span>${demand.people} people</span>
<div class="chips">${chips}</div>
`;
for (const service of ["water", "power", "access"]) {
const available =
results.noReserves.availability[demand.id][service] >= 1;
const signal = visual.signals[service];
signal.material.color.setHex(available ? COLORS[service] : 0x3b2530);
signal.material.emissive.setHex(available ? COLORS[service] : 0x2a111a);
signal.material.emissiveIntensity = available ? 0.9 : 0.08;
}
}
}
function updateAssetVisuals(results) {
for (const asset of ASSETS) {
const visual = assetVisuals.get(asset.id);
const selected = results.failure && results.failure.id === asset.id;
visual.beacon.visible = !!selected;
if (selected) {
visual.label.style.display = "block";
visual.label.innerHTML = `
<b>${asset.id} · ${asset.label}</b>
<span>FAILED · repair ${asset.repairTime} min</span>
`;
} else {
visual.label.style.display = "none";
}
}
}
function updateReserveVisuals(results) {
const failure = results.failure;
for (const [key, visual] of reserveVisuals) {
let used = 0;
let exhausted = false;
if (failure && failure.network === key) {
used = results.withReserves.reserveUsed[key];
if (
currentTime < failure.repairTime &&
currentTime >= RESERVES[key].duration
) {
exhausted = true;
}
}
const fraction = exhausted ? 1 : used / RESERVES[key].capacity;
const litPips = Math.max(0, visual.pips.length - Math.ceil(fraction * visual.pips.length));
visual.pips.forEach((material, index) => {
const lit = index < litPips;
material.color.setHex(lit ? COLORS.reserve : 0x354552);
material.emissive.setHex(lit ? COLORS.reserve : 0x172128);
material.emissiveIntensity = lit ? 0.85 : 0.08;
});
}
}
function updateAll() {
const results = evaluateScenario();
renderSummary(results);
renderComparison(results);
renderFailureDetail(results);
renderTimeline(results);
updateNetworkVisuals(results);
updateDemandVisuals(results);
updateAssetVisuals(results);
updateReserveVisuals(results);
return results;
}
// -------------------------------------------------------------------------
// Label projection
// -------------------------------------------------------------------------
function projectLabel(element, worldPosition, visible = true) {
if (!visible) {
element.style.display = "none";
return;
}
const projected = worldPosition.clone().project(camera);
if (
projected.z < -1 ||
projected.z > 1 ||
projected.x < -1.2 ||
projected.x > 1.2 ||
projected.y < -1.2 ||
projected.y > 1.2
) {
element.style.display = "none";
return;
}
const width = host.clientWidth;
const height = host.clientHeight;
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
element.style.display = "block";
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}
function updateLabels() {
for (const demand of DEMANDS) {
const visual = demandVisuals.get(demand.id);
projectLabel(visual.label, visual.worldAnchor, true);
}
for (const asset of ASSETS) {
const visual = assetVisuals.get(asset.id);
const layerVisible = networkVisuals[asset.network].group.visible;
projectLabel(visual.label, visual.worldAnchor, visual.beacon.visible && layerVisible);
}
for (const [key, visual] of reserveVisuals) {
projectLabel(visual.label, visual.worldAnchor, reserveGroup.visible);
}
}
// -------------------------------------------------------------------------
// Direct camera controls and asset picking
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const hoverTip = $("hover-tip");
let pointerDown = false;
let pointerButton = 0;
let pointerStart = { x: 0, y: 0 };
let previousPointer = { x: 0, y: 0 };
let pointerMoved = false;
function updatePointer(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 pickAsset(event) {
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(assetPickMeshes, false);
for (const intersection of intersections) {
const id = intersection.object.userData.assetId;
const asset = ASSETS.find(a => a.id === id);
const layerVisible = networkVisuals[asset.network].group.visible;
if (layerVisible) return asset;
}
return null;
}
renderer.domElement.addEventListener("pointerdown", event => {
pointerDown = true;
pointerButton = event.button;
pointerMoved = false;
pointerStart = { x: event.clientX, y: event.clientY };
previousPointer = { ...pointerStart };
renderer.domElement.setPointerCapture(event.pointerId);
hoverTip.style.display = "none";
});
renderer.domElement.addEventListener("pointermove", event => {
if (!pointerDown) {
const asset = pickAsset(event);
renderer.domElement.style.cursor = asset ? "pointer" : "grab";
if (asset) {
hoverTip.style.display = "block";
hoverTip.style.left = `${event.clientX + 12}px`;
hoverTip.style.top = `${event.clientY + 12}px`;
hoverTip.textContent = `${asset.id} · ${asset.label} — click to fail`;
} else {
hoverTip.style.display = "none";
}
return;
}
const dx = event.clientX - previousPointer.x;
const dy = event.clientY - previousPointer.y;
const totalDistance = Math.hypot(
event.clientX - pointerStart.x,
event.clientY - pointerStart.y
);
if (totalDistance > 4) pointerMoved = true;
if (pointerButton === 2 || event.shiftKey) {
const right = new THREE.Vector3();
const forward = new THREE.Vector3();
camera.matrixWorld.extractBasis(right, new THREE.Vector3(), forward);
const panScale = cameraState.radius * 0.0014;
cameraState.target.addScaledVector(right, -dx * panScale);
cameraState.target.addScaledVector(forward, -dy * panScale);
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.08,
1.43
);
}
previousPointer = { x: event.clientX, y: event.clientY };
updateCamera();
});
renderer.domElement.addEventListener("pointerup", event => {
pointerDown = false;
if (!pointerMoved && event.button === 0) {
const asset = pickAsset(event);
if (asset) {
selectedAssetId = asset.id;
$("failure-select").value = asset.id;
updateAll();
}
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = false;
});
renderer.domElement.addEventListener("contextmenu", event => {
event.preventDefault();
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
52,
170
);
updateCamera();
}, { passive: false });
// -------------------------------------------------------------------------
// Controls and initialization
// -------------------------------------------------------------------------
buildSelect();
buildLedgers();
$("failure-select").addEventListener("change", event => {
selectedAssetId = event.target.value;
updateAll();
});
$("recovery-time").addEventListener("input", event => {
currentTime = Number(event.target.value);
updateAll();
});
$("isolate-impact").addEventListener("change", event => {
isolateImpact = event.target.checked;
updateAll();
});
for (const key of ["water", "power", "access"]) {
$(`layer-${key}`).addEventListener("change", event => {
networkVisuals[key].group.visible = event.target.checked;
});
}
$("layer-reserves").addEventListener("change", event => {
reserveGroup.visible = event.target.checked;
});
$("reset-view").addEventListener("click", resetCamera);
$("top-view").addEventListener("click", topCamera);
const resizeObserver = new ResizeObserver(() => {
const width = host.clientWidth;
const height = host.clientHeight;
if (!width || !height) return;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
});
resizeObserver.observe(host);
updateAll();
const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
const time = clock.getElapsedTime();
for (const visual of assetVisuals.values()) {
if (visual.beacon.visible) {
const pulse = 1 + Math.sin(time * 5.5) * 0.12;
visual.beacon.scale.set(pulse, 1, pulse);
visual.beaconMaterial.opacity = 0.65 + Math.sin(time * 5.5) * 0.18;
visual.beamMaterial.opacity = 0.18 + Math.sin(time * 3.0) * 0.05;
}
}
updateLabels();
renderer.render(scene, camera);
});
</script>
</body>
</html>
```