Prompt specification
Build or customize the Three.js 3D scene "Cooperative Route Plan With a Closed Dock" 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: Cooperative Route Plan With a Closed Dock
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/cooperative-route-plan-with-a-closed-dock-x3564
Scene Description Prompt:
Please use Three.js from cdnjs for a low-poly scene based on this idea: cooperative route plan with a closed dock. Create a bounded rescue puzzle where one docking point becomes unavailable. Replan trips, preserve passenger counts, and expose impossible schedules rather than forcing a successful outcome. Return one self-contained HTML file.
Working Three.js Starter (cooperative-route-plan-with-a-closed-dock-x3564):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Last Light Rescue — Cooperative Route Planner</title>
<style>
:root {
--ink: #102a36;
--muted: #617681;
--paper: #f5f1e8;
--panel: #fffaf0;
--line: #d8ddd7;
--teal: #0b7c7a;
--teal-dark: #075e62;
--orange: #ed7d45;
--orange-dark: #b9552a;
--red: #bd3c43;
--red-soft: #fde8e5;
--green: #31825d;
--green-soft: #e3f2e8;
--amber: #b4771b;
--amber-soft: #fff0cf;
--blue: #297b99;
--shadow: 0 16px 45px rgba(20, 49, 59, .14);
}
* { box-sizing: border-box; }
html, body {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
background: var(--paper);
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button, select, input { font: inherit; }
button {
cursor: pointer;
border: 0;
}
#app {
display: grid;
grid-template-columns: 326px minmax(420px, 1fr) 350px;
width: 100%;
height: 100%;
}
.panel {
position: relative;
z-index: 3;
background: var(--panel);
overflow-y: auto;
scrollbar-width: thin;
scrollbar-color: #aebbb8 transparent;
}
.left-panel {
border-right: 1px solid var(--line);
box-shadow: 8px 0 30px rgba(29, 54, 60, .08);
}
.right-panel {
border-left: 1px solid var(--line);
box-shadow: -8px 0 30px rgba(29, 54, 60, .08);
}
.panel-inner {
padding: 24px 22px 30px;
}
.eyebrow {
color: var(--teal);
font-size: 11px;
font-weight: 850;
letter-spacing: .14em;
text-transform: uppercase;
}
h1 {
margin: 8px 0 8px;
font-size: 31px;
line-height: 1.02;
letter-spacing: -.045em;
}
h2 {
margin: 0;
font-size: 16px;
letter-spacing: -.02em;
}
h3 {
margin: 0 0 10px;
font-size: 12px;
font-weight: 850;
letter-spacing: .09em;
text-transform: uppercase;
color: var(--muted);
}
p {
margin: 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.story {
margin-top: 14px;
}
.closure-card {
position: relative;
margin: 18px 0;
padding: 14px 15px 14px 46px;
border: 1px solid #edb9b1;
border-radius: 13px;
background: var(--red-soft);
color: #783439;
font-size: 12px;
line-height: 1.45;
}
.closure-card::before {
content: "!";
position: absolute;
left: 14px;
top: 13px;
width: 22px;
height: 22px;
border-radius: 50%;
display: grid;
place-items: center;
color: white;
background: var(--red);
font-weight: 900;
}
.closure-card strong {
display: block;
margin-bottom: 3px;
color: #6b292f;
font-size: 13px;
}
.objective {
padding: 13px 14px;
margin: 15px 0 20px;
border: 1px solid var(--line);
border-radius: 13px;
background: #fffdf8;
}
.objective-row {
display: flex;
justify-content: space-between;
gap: 12px;
padding: 5px 0;
color: var(--muted);
font-size: 12px;
}
.objective-row strong {
color: var(--ink);
text-align: right;
}
.section {
padding-top: 18px;
margin-top: 18px;
border-top: 1px solid var(--line);
}
.boat-tabs {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-bottom: 12px;
}
.boat-tab {
padding: 10px 8px;
border: 1px solid var(--line);
border-radius: 11px;
background: #f7f4ec;
color: var(--muted);
font-size: 12px;
font-weight: 800;
}
.boat-tab span {
display: inline-grid;
place-items: center;
width: 21px;
height: 21px;
margin-right: 5px;
border-radius: 6px;
color: white;
background: var(--orange);
font-size: 10px;
}
.boat-tab[data-boat="B"] span { background: var(--teal); }
.boat-tab.active {
border-color: var(--orange);
background: #fff2e9;
color: var(--orange-dark);
box-shadow: inset 0 0 0 1px rgba(237,125,69,.12);
}
.boat-tab[data-boat="B"].active {
border-color: var(--teal);
background: #e8f4f1;
color: var(--teal-dark);
box-shadow: inset 0 0 0 1px rgba(11,124,122,.12);
}
.mode-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin: 10px 0;
}
.mode-row > span {
color: var(--muted);
font-size: 11px;
font-weight: 700;
}
.segmented {
display: inline-flex;
padding: 3px;
border: 1px solid var(--line);
border-radius: 9px;
background: #eeeae0;
}
.segmented button {
padding: 6px 9px;
border-radius: 6px;
background: transparent;
color: var(--muted);
font-size: 10px;
font-weight: 850;
}
.segmented button.active {
background: white;
color: var(--ink);
box-shadow: 0 1px 4px rgba(30, 50, 55, .12);
}
.route-box {
min-height: 118px;
padding: 10px;
border: 1px dashed #b9c4c1;
border-radius: 12px;
background:
linear-gradient(90deg, rgba(11,124,122,.035) 1px, transparent 1px),
linear-gradient(rgba(11,124,122,.035) 1px, transparent 1px),
#fbfaf5;
background-size: 16px 16px;
}
.route-line {
display: flex;
align-items: center;
gap: 7px;
margin-bottom: 8px;
}
.route-line:last-child { margin-bottom: 0; }
.route-node {
min-width: 0;
display: flex;
align-items: center;
gap: 7px;
flex: 1;
padding: 8px 8px;
border: 1px solid var(--line);
border-radius: 9px;
background: white;
}
.route-node.closed {
border-color: #e2aaa5;
background: #fff3f0;
}
.stop-number {
width: 18px;
height: 18px;
flex: 0 0 auto;
display: grid;
place-items: center;
border-radius: 5px;
background: #e7ece9;
color: var(--muted);
font-size: 9px;
font-weight: 900;
}
.stop-name {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 11px;
font-weight: 750;
}
.stop-type {
padding: 4px 5px;
border-radius: 5px;
background: #e9f4ed;
color: var(--green);
font-size: 8px;
font-weight: 900;
letter-spacing: .05em;
}
.stop-type.waypoint {
background: #e8eef1;
color: var(--blue);
}
.remove-stop {
width: 23px;
height: 23px;
border-radius: 6px;
background: transparent;
color: #93a09f;
font-size: 16px;
}
.remove-stop:hover { background: #f5e6e2; color: var(--red); }
.hq-chip {
display: inline-flex;
align-items: center;
gap: 5px;
margin-bottom: 8px;
padding: 5px 8px;
border-radius: 7px;
background: #e8eeee;
color: var(--teal-dark);
font-size: 10px;
font-weight: 850;
}
.hq-chip::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--teal);
}
.dock-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-top: 10px;
}
.add-stop {
padding: 9px 8px;
border: 1px solid var(--line);
border-radius: 9px;
background: #fffdf8;
color: var(--ink);
text-align: left;
font-size: 10px;
font-weight: 750;
}
.add-stop small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
font-weight: 550;
}
.add-stop:hover:not(:disabled) {
border-color: var(--teal);
color: var(--teal-dark);
}
.add-stop:disabled {
opacity: .38;
cursor: default;
}
.add-stop.closed {
border-color: #e7b7b0;
color: var(--red);
}
.delay-row {
display: grid;
grid-template-columns: 1fr 72px;
align-items: center;
gap: 10px;
margin-top: 12px;
}
.delay-row label {
color: var(--muted);
font-size: 11px;
font-weight: 750;
}
input[type="range"] {
width: 100%;
accent-color: var(--orange);
}
input[type="number"], select {
width: 100%;
border: 1px solid var(--line);
border-radius: 8px;
padding: 8px 9px;
background: #fffdf8;
color: var(--ink);
outline: none;
}
input[type="number"]:focus, select:focus {
border-color: var(--teal);
box-shadow: 0 0 0 3px rgba(11,124,122,.1);
}
.transfer-grid {
display: grid;
grid-template-columns: 1fr 88px;
gap: 9px;
}
.field-label {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: .05em;
text-transform: uppercase;
}
.transfer-note {
margin-top: 8px;
padding: 9px 10px;
border-radius: 9px;
background: #edf3f2;
color: #4b686d;
font-size: 10px;
line-height: 1.45;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 17px;
}
.secondary-btn, .primary-btn {
min-height: 43px;
padding: 10px 12px;
border-radius: 11px;
font-size: 11px;
font-weight: 900;
letter-spacing: .02em;
}
.secondary-btn {
border: 1px solid var(--line);
background: #fffdf8;
color: var(--ink);
}
.secondary-btn:hover { background: #f4f0e7; }
.primary-btn {
background: var(--teal);
color: white;
box-shadow: 0 8px 20px rgba(11,124,122,.22);
}
.primary-btn:hover { background: var(--teal-dark); }
.primary-btn.running {
background: var(--orange);
box-shadow: 0 8px 20px rgba(237,125,69,.22);
}
details {
margin-top: 15px;
padding: 11px 12px;
border: 1px solid var(--line);
border-radius: 10px;
background: #fffdf8;
}
summary {
cursor: pointer;
color: var(--teal-dark);
font-size: 11px;
font-weight: 850;
}
details p {
margin-top: 9px;
font-size: 11px;
}
#viewport {
position: relative;
min-width: 0;
overflow: hidden;
background: #8cc5c5;
}
#scene {
position: absolute;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.map-top {
position: absolute;
z-index: 2;
top: 18px;
left: 18px;
right: 18px;
display: flex;
justify-content: space-between;
align-items: flex-start;
pointer-events: none;
}
.map-label {
padding: 10px 12px;
border: 1px solid rgba(255,255,255,.55);
border-radius: 12px;
background: rgba(18, 51, 61, .78);
color: white;
backdrop-filter: blur(8px);
box-shadow: var(--shadow);
}
.map-label strong {
display: block;
font-size: 11px;
letter-spacing: .08em;
text-transform: uppercase;
}
.map-label span {
display: block;
margin-top: 3px;
color: #cbe1df;
font-size: 9px;
}
.camera-btn {
pointer-events: auto;
padding: 9px 11px;
border: 1px solid rgba(255,255,255,.5);
border-radius: 10px;
background: rgba(18,51,61,.78);
color: white;
font-size: 10px;
font-weight: 800;
backdrop-filter: blur(8px);
}
.map-bottom {
position: absolute;
z-index: 2;
left: 18px;
right: 18px;
bottom: 17px;
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 12px;
pointer-events: none;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 7px;
max-width: 430px;
padding: 9px 10px;
border: 1px solid rgba(255,255,255,.5);
border-radius: 11px;
background: rgba(18,51,61,.74);
color: white;
backdrop-filter: blur(8px);
font-size: 9px;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 5px;
}
.legend i {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 3px;
}
.clock-card {
min-width: 114px;
padding: 10px 12px;
border: 1px solid rgba(255,255,255,.5);
border-radius: 11px;
background: rgba(18,51,61,.78);
color: white;
text-align: right;
backdrop-filter: blur(8px);
}
.clock-card small {
display: block;
color: #bcd6d4;
font-size: 8px;
font-weight: 800;
letter-spacing: .1em;
text-transform: uppercase;
}
.clock-card strong {
display: block;
margin-top: 1px;
font-size: 19px;
font-variant-numeric: tabular-nums;
}
.toast {
position: absolute;
z-index: 6;
left: 50%;
top: 82px;
max-width: min(460px, calc(100% - 40px));
padding: 10px 14px;
border-radius: 10px;
background: rgba(17,42,54,.92);
color: white;
box-shadow: var(--shadow);
font-size: 11px;
font-weight: 700;
opacity: 0;
pointer-events: none;
transform: translate(-50%, -8px);
transition: opacity .2s, transform .2s;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
.status-pill {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 8px;
border-radius: 999px;
background: var(--amber-soft);
color: var(--amber);
font-size: 9px;
font-weight: 900;
letter-spacing: .06em;
text-transform: uppercase;
}
.status-pill::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
}
.status-pill.good {
background: var(--green-soft);
color: var(--green);
}
.status-pill.bad {
background: var(--red-soft);
color: var(--red);
}
.right-panel .panel-inner { padding-top: 20px; }
.validation-card {
padding: 13px;
border: 1px solid var(--line);
border-radius: 12px;
background: #fffdf8;
}
.validation-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 10px;
}
.validation-list {
margin: 0;
padding: 0;
list-style: none;
}
.validation-list li {
position: relative;
margin: 7px 0;
padding-left: 17px;
color: #7a3d38;
font-size: 11px;
line-height: 1.42;
}
.validation-list li::before {
content: "×";
position: absolute;
left: 0;
top: -1px;
color: var(--red);
font-size: 15px;
font-weight: 900;
}
.validation-list.good li {
color: #416d55;
}
.validation-list.good li::before {
content: "✓";
color: var(--green);
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin: 14px 0;
}
.metric {
padding: 11px;
border: 1px solid var(--line);
border-radius: 11px;
background: #fffdf8;
}
.metric small {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: .07em;
text-transform: uppercase;
}
.metric strong {
display: block;
margin-top: 3px;
font-size: 23px;
font-variant-numeric: tabular-nums;
}
.boat-status {
margin: 8px 0;
padding: 11px;
border: 1px solid var(--line);
border-radius: 11px;
background: #fffdf8;
}
.boat-status-head {
display: flex;
justify-content: space-between;
gap: 8px;
font-size: 11px;
font-weight: 850;
}
.boat-status-head span {
color: var(--muted);
font-variant-numeric: tabular-nums;
}
.load-track {
height: 6px;
margin-top: 8px;
overflow: hidden;
border-radius: 99px;
background: #e7ebe7;
}
.load-fill {
width: 0;
height: 100%;
border-radius: inherit;
background: var(--orange);
transition: width .25s;
}
.boat-status.b .load-fill { background: var(--teal); }
.schedule-list {
margin: 0;
padding: 0;
list-style: none;
}
.schedule-item {
display: grid;
grid-template-columns: 43px 22px 1fr;
gap: 8px;
align-items: start;
padding: 9px 0;
border-bottom: 1px solid #ece9e0;
font-size: 10px;
line-height: 1.4;
}
.schedule-item:last-child { border-bottom: 0; }
.schedule-time {
color: var(--muted);
font-weight: 850;
font-variant-numeric: tabular-nums;
}
.schedule-dot {
width: 18px;
height: 18px;
display: grid;
place-items: center;
border-radius: 6px;
color: white;
background: var(--orange);
font-size: 9px;
font-weight: 900;
}
.schedule-dot.b { background: var(--teal); }
.schedule-dot.transfer { background: #695e9b; }
.schedule-dot.delivery { background: var(--green); }
.schedule-text strong {
display: block;
color: var(--ink);
font-size: 10px;
}
.schedule-text span {
display: block;
margin-top: 2px;
color: var(--muted);
}
.ledger {
padding: 11px;
border: 1px solid #bdd7cf;
border-radius: 11px;
background: #edf6f2;
}
.ledger-line {
display: flex;
justify-content: space-between;
gap: 10px;
padding: 3px 0;
color: #527069;
font-size: 10px;
}
.ledger-line.total {
margin-top: 5px;
padding-top: 8px;
border-top: 1px solid #c8ded6;
color: var(--ink);
font-weight: 900;
}
.outcome {
margin-top: 14px;
padding: 13px;
border: 1px solid var(--line);
border-radius: 12px;
background: #fffdf8;
}
.outcome h3 {
margin-bottom: 6px;
}
.outcome p { font-size: 11px; }
.outcome.impossible {
border-color: #e5b3ad;
background: var(--red-soft);
}
.outcome.impossible h3 { color: var(--red); }
.outcome.viable {
border-color: #b7d6c6;
background: var(--green-soft);
}
.outcome.viable h3 { color: var(--green); }
.outcome ul {
margin: 8px 0 0;
padding-left: 16px;
color: #79423d;
font-size: 10px;
line-height: 1.5;
}
@media (max-width: 1100px) {
#app { grid-template-columns: 300px minmax(350px, 1fr) 310px; }
.panel-inner { padding-left: 17px; padding-right: 17px; }
h1 { font-size: 27px; }
}
@media (max-width: 900px) {
html, body { overflow: auto; }
#app {
display: flex;
flex-direction: column;
height: auto;
min-height: 100%;
}
#viewport {
order: -1;
height: 58vh;
min-height: 430px;
}
.panel {
overflow: visible;
border: 0;
box-shadow: none;
}
.left-panel { border-top: 1px solid var(--line); }
.right-panel { border-top: 1px solid var(--line); }
.panel-inner { max-width: 680px; margin: 0 auto; }
}
@media (max-width: 520px) {
.panel-inner { padding: 21px 16px 28px; }
.dock-grid { grid-template-columns: 1fr; }
.map-top { top: 12px; left: 12px; right: 12px; }
.map-bottom { left: 12px; right: 12px; bottom: 12px; }
.legend { display: none; }
}
</style>
</head>
<body>
<div id="app">
<aside class="panel left-panel">
<div class="panel-inner">
<div class="eyebrow">Puzzle 04 · bounded rescue dispatch</div>
<h1>Last Light<br>Rescue</h1>
<p class="story">A squall has damaged the outer harbor. Twelve passengers are waiting, two skiffs are available, and the only transfer point in the original plan is no longer usable.</p>
<div class="closure-card">
<strong>Gull Dock closed at 00:00</strong>
Harbor authority has blocked the dock after structural damage. No route may use it as a stop or transfer point.
</div>
<div class="objective">
<h3>Mission constraints</h3>
<div class="objective-row"><span>Passengers to rescue</span><strong>12</strong></div>
<div class="objective-row"><span>Available skiffs</span><strong>2</strong></div>
<div class="objective-row"><span>Return-to-HQ deadline</span><strong>00:45</strong></div>
<div class="objective-row"><span>Passenger transfers</span><strong>Exact count only</strong></div>
</div>
<section class="section">
<h3>Trip planner</h3>
<div class="boat-tabs">
<button class="boat-tab active" data-boat="A"><span>A</span>Kestrel · cap 7</button>
<button class="boat-tab" data-boat="B"><span>B</span>Finch · cap 6</button>
</div>
<div class="mode-row">
<span>New stop type</span>
<div class="segmented" id="modeButtons">
<button class="active" data-mode="pickup">PICKUP</button>
<button data-mode="waypoint">WAYPOINT</button>
</div>
</div>
<div class="route-box" id="routeBox"></div>
<div class="dock-grid" id="dockButtons"></div>
<div class="delay-row">
<label for="delayInput">Departure delay · minutes</label>
<input id="delayInput" type="number" min="0" max="20" step="1" value="4">
</div>
</section>
<section class="section">
<h3>Cooperative transfer</h3>
<div class="transfer-grid">
<label>
<span class="field-label">Meeting dock</span>
<select id="transferDock"></select>
</label>
<label>
<span class="field-label">A → B</span>
<input id="transferAmount" type="number" min="1" max="5" step="1" value="1">
</label>
</div>
<div class="transfer-note">Both skiffs must reach the meeting dock at the same minute. The transfer occurs before either vessel continues.</div>
</section>
<details>
<summary>Planning hint</summary>
<p>North Jetty holds 5, East Quay 4, and West Steps 3. Kestrel can carry 7 and Finch 6. Try meeting at North Jetty, transfer one passenger from Kestrel to Finch, and have Kestrel collect West Steps afterward.</p>
</details>
<div class="button-row">
<button class="secondary-btn" id="resetBtn">Reset puzzle</button>
<button class="secondary-btn" id="hintBtn">Show hint</button>
</div>
</div>
</aside>
<main id="viewport">
<div id="scene"></div>
<div class="map-top">
<div class="map-label">
<strong>Brindle Bay</strong>
<span>Click a dock to add the selected stop</span>
</div>
<button class="camera-btn" id="cameraBtn">Reset camera</button>
</div>
<div class="map-bottom">
<div class="legend">
<span><i style="background:#ed7d45"></i>Kestrel</span>
<span><i style="background:#0b7c7a"></i>Finch</span>
<span><i style="background:#bd3c43"></i>Closed dock</span>
<span><i style="background:#ffffff"></i>Open dock</span>
</div>
<div class="clock-card">
<small>Dispatch clock</small>
<strong id="clockText">00:00</strong>
</div>
</div>
<div class="toast" id="toast"></div>
</main>
<aside class="panel right-panel">
<div class="panel-inner">
<div class="eyebrow">Live feasibility check</div>
<div class="validation-card" style="margin-top:10px">
<div class="validation-head">
<h2>Schedule status</h2>
<span class="status-pill bad" id="validationPill">Blocked</span>
</div>
<ul class="validation-list" id="validationList"></ul>
</div>
<div class="metric-grid">
<div class="metric"><small>Waiting</small><strong id="waitingMetric">12</strong></div>
<div class="metric"><small>Aboard boats</small><strong id="aboardMetric">0</strong></div>
<div class="metric"><small>Delivered</small><strong id="deliveredMetric">0</strong></div>
<div class="metric"><small>Total tracked</small><strong id="trackedMetric">12</strong></div>
</div>
<button class="primary-btn" id="dispatchBtn" style="width:100%">Run dispatch check</button>
<section class="section">
<h3>Boat status</h3>
<div class="boat-status">
<div class="boat-status-head"><strong>A · Kestrel</strong><span id="boatAStatus">0 / 7 aboard</span></div>
<div class="load-track"><div class="load-fill" id="boatAFill"></div></div>
</div>
<div class="boat-status b">
<div class="boat-status-head"><strong>B · Finch</strong><span id="boatBStatus">0 / 6 aboard</span></div>
<div class="load-track"><div class="load-fill" id="boatBFill"></div></div>
</div>
</section>
<section class="section">
<h3>Proposed schedule</h3>
<ul class="schedule-list" id="scheduleList"></ul>
</section>
<section class="section">
<div class="ledger">
<h3>Passenger ledger</h3>
<div class="ledger-line"><span>Waiting ashore</span><strong id="ledgerWaiting">12</strong></div>
<div class="ledger-line"><span>On Kestrel</span><strong id="ledgerA">0</strong></div>
<div class="ledger-line"><span>On Finch</span><strong id="ledgerB">0</strong></div>
<div class="ledger-line"><span>Delivered</span><strong id="ledgerDelivered">0</strong></div>
<div class="ledger-line total"><span>Conserved total</span><strong id="ledgerTotal">12 / 12</strong></div>
</div>
</section>
<div class="outcome" id="outcomeBox">
<h3>Awaiting dispatch</h3>
<p>The plan is checked against dock availability, arrival timing, capacity, deadline, and passenger conservation.</p>
</div>
</div>
</aside>
</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 stations = {
HQ: { id: "HQ", name: "Harbor HQ", short: "HQ", x: 0, z: 0, waiting: 0 },
North: { id: "North", name: "North Jetty", short: "North Jetty", x: -8, z: 6, waiting: 5 },
East: { id: "East", name: "East Quay", short: "East Quay", x: 8, z: 4, waiting: 4 },
West: { id: "West", name: "West Steps", short: "West Steps", x: -6, z: -7, waiting: 3 },
Gull: { id: "Gull", name: "Gull Dock", short: "Gull Dock", x: 2, z: 9, waiting: 0 }
};
const closedDock = "Gull";
const capacities = { A: 7, B: 6 };
const boatNames = { A: "Kestrel", B: "Finch" };
const totalPassengers = 12;
const deadline = 45;
const travelTimes = {
"HQ-North": 12, "HQ-East": 14, "HQ-West": 10, "HQ-Gull": 10,
"North-East": 7, "North-West": 9, "North-Gull": 5,
"East-West": 13, "East-Gull": 7, "West-Gull": 12
};
function travel(a, b) {
if (a === b) return 0;
return travelTimes[`${a}-${b}`] ?? travelTimes[`${b}-${a}`] ?? 0;
}
const initialState = {
activeBoat: "A",
addMode: "pickup",
delays: { A: 4, B: 0 },
routes: {
A: [
{ id: "North", type: "pickup" },
{ id: "Gull", type: "waypoint" }
],
B: [
{ id: "East", type: "pickup" },
{ id: "Gull", type: "waypoint" }
]
},
transfer: { dock: "Gull", amount: 1 }
};
let state = structuredClone(initialState);
let lastPlan = null;
let animation = null;
let toastTimer = null;
let pulseUntil = 0;
const live = {
waiting: totalPassengers,
aboard: { A: 0, B: 0 },
delivered: 0
};
/* -------------------------- Three.js scene -------------------------- */
const sceneHost = $("scene");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x86bec0);
scene.fog = new THREE.Fog(0x86bec0, 30, 78);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 160);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
sceneHost.appendChild(renderer.domElement);
const hemi = new THREE.HemisphereLight(0xd8f3ee, 0x41636a, 2.0);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff2d6, 3.0);
sun.position.set(-12, 24, 15);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -30;
sun.shadow.camera.right = 30;
sun.shadow.camera.top = 30;
sun.shadow.camera.bottom = -30;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 70;
sun.shadow.bias = -0.0006;
scene.add(sun);
const waterMaterial = new THREE.MeshStandardMaterial({
color: 0x3f9fa4,
roughness: 0.76,
metalness: 0.04
});
const water = new THREE.Mesh(new THREE.PlaneGeometry(120, 120), waterMaterial);
water.rotation.x = -Math.PI / 2;
water.position.y = -0.2;
water.receiveShadow = true;
scene.add(water);
const waveMeshes = [];
const waveMaterial = new THREE.MeshBasicMaterial({
color: 0xbfe9e4,
transparent: true,
opacity: 0.17,
depthWrite: false,
side: THREE.DoubleSide
});
for (let i = 0; i < 34; i++) {
const geo = new THREE.CircleGeometry(0.35 + Math.random() * 0.65, 3);
const mesh = new THREE.Mesh(geo, waveMaterial.clone());
mesh.rotation.x = -Math.PI / 2;
mesh.rotation.z = Math.random() * Math.PI;
mesh.position.set((Math.random() - .5) * 42, -0.13 + Math.random() * .015, (Math.random() - .5) * 42);
mesh.userData.phase = Math.random() * Math.PI * 2;
mesh.userData.baseOpacity = .08 + Math.random() * .14;
scene.add(mesh);
waveMeshes.push(mesh);
}
const stationObjects = {};
const pickMeshes = [];
const routeLines = { A: null, B: null };
function addMesh(geometry, material, parent, x = 0, y = 0, z = 0, castShadow = true) {
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(x, y, z);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
const mat = {
sand: new THREE.MeshStandardMaterial({ color: 0xd7bd83, roughness: .9, flatShading: true }),
grass: new THREE.MeshStandardMaterial({ color: 0x7eaa72, roughness: .9, flatShading: true }),
darkGrass: new THREE.MeshStandardMaterial({ color: 0x527f5d, roughness: .9, flatShading: true }),
dock: new THREE.MeshStandardMaterial({ color: 0x896b4b, roughness: .88, flatShading: true }),
dockEdge: new THREE.MeshStandardMaterial({ color: 0x5e4936, roughness: .9, flatShading: true }),
white: new THREE.MeshStandardMaterial({ color: 0xf5eee0, roughness: .82, flatShading: true }),
teal: new THREE.MeshStandardMaterial({ color: 0x0b7c7a, roughness: .72, flatShading: true }),
orange: new THREE.MeshStandardMaterial({ color: 0xed7d45, roughness: .72, flatShading: true }),
red: new THREE.MeshStandardMaterial({ color: 0xbd3c43, roughness: .72, flatShading: true }),
dark: new THREE.MeshStandardMaterial({ color: 0x243a42, roughness: .8, flatShading: true }),
roof: new THREE.MeshStandardMaterial({ color: 0x355a65, roughness: .85, flatShading: true }),
glass: new THREE.MeshStandardMaterial({ color: 0x83c9d2, roughness: .25, metalness: .08, flatShading: true })
};
function makeStationLabel(station) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 150;
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({ map: texture, depthTest: false, depthWrite: false });
const sprite = new THREE.Sprite(material);
sprite.position.set(station.x, 5.4, station.z);
sprite.scale.set(5.3, 1.55, 1);
sprite.renderOrder = 20;
scene.add(sprite);
function update(waiting) {
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
const closed = station.id === closedDock;
ctx.fillStyle = "rgba(13, 42, 53, 0.91)";
ctx.beginPath();
ctx.roundRect(8, 8, 496, 134, 26);
ctx.fill();
ctx.fillStyle = closed ? "#bd3c43" : "#0b7c7a";
ctx.fillRect(8, 8, 14, 134);
ctx.textAlign = "center";
ctx.fillStyle = "#ffffff";
ctx.font = "800 38px system-ui";
ctx.fillText(station.name, 260, 62);
ctx.font = "700 26px system-ui";
ctx.fillStyle = closed ? "#ffd6d0" : (station.id === "HQ" ? "#cde6e2" : "#ffe0a9");
const subtitle = closed ? "CLOSED · DO NOT DOCK" :
station.id === "HQ" ? "BASE · RETURN HERE" : `${waiting} WAITING`;
ctx.fillText(subtitle, 260, 108);
texture.needsUpdate = true;
}
update(station.waiting);
return { sprite, update };
}
function createDock(station) {
const group = new THREE.Group();
scene.add(group);
const dx = station.x;
const dz = station.z;
const length = Math.hypot(dx, dz) || 1;
const ux = dx / length;
const uz = dz / length;
const islandX = station.id === "HQ" ? 0 : dx + ux * 2.5;
const islandZ = station.id === "HQ" ? 0 : dz + uz * 2.5;
const island = addMesh(
new THREE.CylinderGeometry(station.id === "HQ" ? 3.4 : 2.25, station.id === "HQ" ? 3.8 : 2.65, .65, 7),
mat.sand, group, islandX, .12, islandZ
);
island.userData.stationId = station.id;
pickMeshes.push(island);
const top = addMesh(
new THREE.CylinderGeometry(station.id === "HQ" ? 3.0 : 1.9, station.id === "HQ" ? 3.15 : 2.05, .18, 7),
station.id === "Gull" ? mat.darkGrass : mat.grass, group, islandX, .52, islandZ
);
top.userData.stationId = station.id;
pickMeshes.push(top);
const deck = addMesh(
new THREE.BoxGeometry(station.id === "HQ" ? 4.0 : 3.0, .28, 1.15),
mat.dock, group, dx * .78, .58, dz * .78
);
deck.rotation.y = -Math.atan2(uz, ux);
deck.userData.stationId = station.id;
pickMeshes.push(deck);
for (let i = -2; i <= 2; i++) {
const plank = addMesh(
new THREE.BoxGeometry(.08, .06, 1.18),
mat.dockEdge, group, 0, .75, 0, false
);
const angle = -Math.atan2(uz, ux);
plank.position.set(
dx * .78 + Math.cos(angle) * i * .55,
.75,
dz * .78 - Math.sin(angle) * i * .55
);
plank.rotation.y = angle;
}
const marker = addMesh(
new THREE.CylinderGeometry(.23, .28, 1.25, 8),
station.id === closedDock ? mat.red : mat.white,
group, dx, 1.15, dz
);
marker.userData.stationId = station.id;
pickMeshes.push(marker);
const cap = addMesh(
new THREE.ConeGeometry(.34, .5, 8),
station.id === closedDock ? mat.red : mat.teal,
group, dx, 1.98, dz
);
cap.userData.stationId = station.id;
pickMeshes.push(cap);
if (station.id === "HQ") {
addMesh(new THREE.BoxGeometry(2.0, 1.2, 1.5), mat.white, group, islandX, 1.15, islandZ);
addMesh(new THREE.ConeGeometry(1.45, .75, 4), mat.roof, group, islandX, 2.1, islandZ).rotation.y = Math.PI / 4;
} else if (station.id === "North") {
addMesh(new THREE.CylinderGeometry(.5, .7, 2.6, 8), mat.white, group, islandX, 1.8, islandZ);
addMesh(new THREE.CylinderGeometry(.58, .58, .45, 8), mat.orange, group, islandX, 2.9, islandZ);
addMesh(new THREE.ConeGeometry(.7, .7, 8), mat.roof, group, islandX, 3.5, islandZ);
} else if (station.id === "East") {
addMesh(new THREE.BoxGeometry(1.9, 1.1, 1.45), mat.white, group, islandX, 1.1, islandZ);
addMesh(new THREE.BoxGeometry(2.2, .25, 1.7), mat.orange, group, islandX, 1.78, islandZ);
} else if (station.id === "West") {
addMesh(new THREE.BoxGeometry(1.7, .8, 1.2), mat.white, group, islandX, 1.05, islandZ);
addMesh(new THREE.ConeGeometry(1.25, .75, 4), mat.teal, group, islandX, 1.85, islandZ).rotation.y = Math.PI / 4;
} else {
addMesh(new THREE.BoxGeometry(1.8, 1.2, 1.2), mat.dark, group, islandX, 1.2, islandZ);
addMesh(new THREE.BoxGeometry(2.0, .22, 1.4), mat.red, group, islandX, 1.9, islandZ);
}
if (station.id === closedDock) {
const bar = addMesh(new THREE.BoxGeometry(2.9, .18, .18), mat.red, group, dx, 1.18, dz);
bar.rotation.y = -.4;
const bar2 = addMesh(new THREE.BoxGeometry(2.9, .18, .18), mat.red, group, dx, 1.18, dz);
bar2.rotation.y = .4;
}
const label = makeStationLabel(station);
stationObjects[station.id] = { group, label, marker, cap };
}
Object.values(stations).forEach(createDock);
for (let i = 0; i < 18; i++) {
const a = i / 18 * Math.PI * 2;
const x = Math.cos(a) * 18.5;
const z = Math.sin(a) * 16.0;
const buoy = new THREE.Group();
buoy.position.set(x, 0, z);
scene.add(buoy);
addMesh(new THREE.CylinderGeometry(.22, .34, .65, 6), i % 3 === 0 ? mat.orange : mat.white, buoy, 0, .2, 0);
addMesh(new THREE.ConeGeometry(.27, .5, 6), i % 3 === 0 ? mat.orange : mat.teal, buoy, 0, .75, 0);
}
function createBoat(color, accent) {
const group = new THREE.Group();
scene.add(group);
const hull = addMesh(new THREE.BoxGeometry(1.35, .42, 2.35), color, group, 0, .22, .15);
hull.rotation.y = Math.PI / 4;
const bow = addMesh(new THREE.ConeGeometry(.78, 1.4, 4), color, group, 0, .22, -1.35);
bow.rotation.x = -Math.PI / 2;
bow.rotation.y = Math.PI / 4;
addMesh(new THREE.BoxGeometry(1.06, .12, 1.85), mat.white, group, 0, .48, .12);
addMesh(new THREE.BoxGeometry(.85, .65, .78), accent, group, 0, .83, .28);
addMesh(new THREE.BoxGeometry(.66, .32, .04), mat.glass, group, 0, .9, -.13);
addMesh(new THREE.CylinderGeometry(.05, .05, .75, 6), mat.dark, group, .32, 1.15, .38);
addMesh(new THREE.SphereGeometry(.1, 8, 6), mat.orange, group, .32, 1.56, .38);
addMesh(new THREE.BoxGeometry(.9, .12, .45), mat.dark, group, 0, .61, 1.15);
group.userData.bobPhase = Math.random() * Math.PI * 2;
return group;
}
const boats = {
A: createBoat(mat.orange, mat.white),
B: createBoat(mat.teal, mat.white)
};
function updateRouteLines() {
for (const boat of ["A", "B"]) {
if (routeLines[boat]) {
scene.remove(routeLines[boat]);
routeLines[boat].geometry.dispose();
routeLines[boat].material.dispose();
}
const ids = ["HQ", ...state.routes[boat].map(s => s.id), "HQ"];
const points = ids.map(id => new THREE.Vector3(stations[id].x, .02, stations[id].z));
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineDashedMaterial({
color: boat === "A" ? 0xed7d45 : 0x0b7c7a,
dashSize: .75,
gapSize: .35,
transparent: true,
opacity: .9,
depthWrite: false
});
const line = new THREE.Line(geometry, material);
line.computeLineDistances();
scene.add(line);
routeLines[boat] = line;
}
}
/* ----------------------- Custom orbit camera ----------------------- */
const orbit = {
target: new THREE.Vector3(0, .2, 0),
radius: 35,
theta: .72,
phi: 1.02
};
function updateCamera() {
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + orbit.radius * sinPhi * Math.sin(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + orbit.radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(orbit.target);
}
function resetCamera() {
orbit.target.set(0, .2, 0);
orbit.radius = 35;
orbit.theta = .72;
orbit.phi = 1.02;
updateCamera();
}
const pointer = { active: false, button: 0, x: 0, y: 0, moved: 0 };
const raycaster = new THREE.Raycaster();
const pointerNDC = new THREE.Vector2();
renderer.domElement.addEventListener("contextmenu", e => e.preventDefault());
renderer.domElement.addEventListener("pointerdown", e => {
pointer.active = true;
pointer.button = e.button;
pointer.x = e.clientX;
pointer.y = e.clientY;
pointer.moved = 0;
renderer.domElement.setPointerCapture(e.pointerId);
});
renderer.domElement.addEventListener("pointermove", e => {
if (!pointer.active) return;
const dx = e.clientX - pointer.x;
const dy = e.clientY - pointer.y;
pointer.x = e.clientX;
pointer.y = e.clientY;
pointer.moved += Math.abs(dx) + Math.abs(dy);
if (pointer.button === 2 || e.shiftKey) {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = forward.clone().cross(new THREE.Vector3(0, 1, 0)).normalize();
orbit.target.addScaledVector(right, -dx * orbit.radius * .0016);
orbit.target.addScaledVector(forward, dy * orbit.radius * .0016);
} else {
orbit.theta -= dx * .006;
orbit.phi = THREE.MathUtils.clamp(orbit.phi - dy * .006, .35, 1.42);
}
updateCamera();
});
renderer.domElement.addEventListener("pointerup", e => {
pointer.active = false;
if (pointer.moved < 7 && e.button === 0) {
const rect = renderer.domElement.getBoundingClientRect();
pointerNDC.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;
pointerNDC.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointerNDC, camera);
const hits = raycaster.intersectObjects(pickMeshes, false);
if (hits.length) {
const id = hits[0].object.userData.stationId;
if (id && id !== "HQ") addStop(id);
}
}
});
renderer.domElement.addEventListener("pointercancel", () => pointer.active = false);
renderer.domElement.addEventListener("wheel", e => {
e.preventDefault();
orbit.radius = THREE.MathUtils.clamp(orbit.radius + e.deltaY * .025, 18, 58);
updateCamera();
}, { passive: false });
const resizeObserver = new ResizeObserver(() => {
const w = sceneHost.clientWidth;
const h = sceneHost.clientHeight;
if (!w || !h) return;
camera.aspect = w / h;
camera.updateProjectionMatrix();
renderer.setSize(w, h, false);
});
resizeObserver.observe(sceneHost);
/* ----------------------------- Analysis ----------------------------- */
function fmtTime(t) {
const seconds = Math.max(0, Math.round(t));
return `${String(Math.floor(seconds / 60)).padStart(2, "0")}:${String(seconds % 60).padStart(2, "0")}`;
}
function unique(items) {
return [...new Set(items)];
}
function analyze() {
const blockers = [];
const warnings = [];
const visits = { A: [], B: [] };
const paths = { A: [], B: [] };
for (const boat of ["A", "B"]) {
let time = Number(state.delays[boat]) || 0;
let previous = "HQ";
for (let index = 0; index < state.routes[boat].length; index++) {
const stop = state.routes[boat][index];
if (stop.id === closedDock) {
blockers.push(`${boatNames[boat]} cannot use ${stations[stop.id].name}; the dock is closed.`);
}
const arrival = time + travel(previous, stop.id);
const service = stop.type === "pickup" ? 1 : 0;
visits[boat].push({
stop: stop.id,
type: stop.type,
arrival,
departure: arrival + service,
index
});
time = arrival + service;
previous = stop.id;
}
const returnTime = time + travel(previous, "HQ");
paths[boat].returnTime = returnTime;
let from = "HQ";
let cursorTime = time - (state.routes[boat].length ? visits[boat][visits[boat].length - 1].departure : time) + (visits[boat].length ? visits[boat][visits[boat].length - 1].departure : 0);
cursorTime = Number(state.delays[boat]) || 0;
for (const visit of visits[boat]) {
paths[boat].push({
from,
to: visit.stop,
start: cursorTime,
end: visit.arrival
});
cursorTime = visit.departure;
from = visit.stop;
}
paths[boat].push({ from, to: "HQ", start: cursorTime, end: returnTime });
}
const transferDock = state.transfer.dock;
const transferAmount = Number(state.transfer.amount) || 0;
if (transferDock === closedDock) {
blockers.push(`${stations[transferDock].name} cannot be used as a transfer point because it is closed.`);
}
if (!Number.isInteger(transferAmount) || transferAmount < 1 || transferAmount > 5) {
blockers.push("Transfer count must be a whole number from 1 to 5.");
}
const aVisit = visits.A.find(v => v.stop === transferDock);
const bVisit = visits.B.find(v => v.stop === transferDock);
let transferTime = null;
if (!aVisit) blockers.push(`${boatNames.A} does not visit ${stations[transferDock].name}, so the transfer cannot occur.`);
if (!bVisit) blockers.push(`${boatNames.B} does not visit ${stations[transferDock].name}, so the transfer cannot occur.`);
if (aVisit && bVisit) {
if (Math.abs(aVisit.arrival - bVisit.arrival) > .001) {
blockers.push(`Transfer timing fails: Kestrel arrives at ${fmtTime(aVisit.arrival)}, Finch at ${fmtTime(bVisit.arrival)}.`);
} else {
transferTime = aVisit.arrival;
}
}
const pickupCounts = { North: 0, East: 0, West: 0, Gull: 0 };
for (const boat of ["A", "B"]) {
for (const visit of visits[boat]) {
if (visit.type === "pickup") pickupCounts[visit.stop]++;
}
}
for (const [stop, count] of Object.entries(pickupCounts)) {
if (count > 1) blockers.push(`${stations[stop].name} is assigned as a pickup to both boats. Assign one pickup route and use a waypoint for the other.`);
}
const events = [];
for (const boat of ["A", "B"]) {
for (const visit of visits[boat]) {
if (visit.type === "pickup") {
events.push({
time: visit.arrival,
priority: 0,
kind: "pickup",
boat,
station: visit.stop,
amount: 0
});
}
}
}
if (transferTime !== null) {
events.push({
time: transferTime,
priority: 2,
kind: "transfer",
amount: transferAmount
});
}
for (const boat of ["A", "B"]) {
events.push({
time: paths[boat].returnTime,
priority: 3,
kind: "delivery",
boat,
amount: 0
});
}
events.sort((a, b) => a.time - b.time || a.priority - b.priority);
const waiting = { North: 5, East: 4, West: 3, Gull: 0 };
const aboard = { A: 0, B: 0 };
let delivered = 0;
for (const event of events) {
if (event.kind === "pickup") {
event.amount = waiting[event.station];
waiting[event.station] -= event.amount;
aboard[event.boat] += event.amount;
if (aboard[event.boat] > capacities[event.boat]) {
blockers.push(`${boatNames[event.boat]} exceeds capacity at ${stations[event.station].name}: ${aboard[event.boat]} aboard, limit ${capacities[event.boat]}.`);
}
} else if (event.kind === "transfer") {
if (aboard.A < event.amount) {
blockers.push(`Kestrel cannot transfer ${event.amount} passenger${event.amount === 1 ? "" : "s"}; only ${aboard.A} aboard.`);
} else if (aboard.B + event.amount > capacities.B) {
blockers.push(`Finch would exceed capacity after receiving ${event.amount}: ${aboard.B + event.amount}/${capacities.B}.`);
} else {
aboard.A -= event.amount;
aboard.B += event.amount;
}
} else if (event.kind === "delivery") {
event.amount = aboard[event.boat];
delivered += event.amount;
aboard[event.boat] = 0;
if (event.time > deadline) {
blockers.push(`${boatNames[event.boat]} returns at ${fmtTime(event.time)}, after the ${fmtTime(deadline)} deadline.`);
}
}
}
const leftWaiting = Object.values(waiting).reduce((a, b) => a + b, 0);
if (leftWaiting > 0) {
const details = Object.entries(waiting)
.filter(([, count]) => count > 0)
.map(([id, count]) => `${count} at ${stations[id].name}`)
.join(", ");
blockers.push(`${leftWaiting} passenger${leftWaiting === 1 ? "" : "s"} would remain ashore: ${details}.`);
}
const conserved = leftWaiting + aboard.A + aboard.B + delivered;
if (conserved !== totalPassengers) {
blockers.push(`Passenger conservation failed: ${conserved} tracked instead of ${totalPassengers}.`);
}
const deliveryTimes = events.filter(e => e.kind === "delivery").map(e => e.time);
const maxDelivery = deliveryTimes.length ? Math.max(...deliveryTimes) : Infinity;
if (!blockers.length && maxDelivery > deadline - 5) {
warnings.push(`Only ${Math.max(0, Math.floor(deadline - maxDelivery))} minutes of schedule slack remain.`);
}
return {
valid: blockers.length === 0,
blockers: unique(blockers),
warnings,
visits,
paths,
events,
maxDelivery
};
}
/* ------------------------------- UI --------------------------------- */
function renderDockButtons() {
$("dockButtons").innerHTML = ["North", "East", "West", "Gull"].map(id => {
const station = stations[id];
const already = state.routes[state.activeBoat].some(s => s.id === id);
const closed = id === closedDock;
return `
<button class="add-stop ${closed ? "closed" : ""}" data-add="${id}" ${already ? "disabled" : ""}>
${station.name}
<small>${closed ? "closed" : `${station.waiting} waiting · ${state.addMode}`}</small>
</button>`;
}).join("");
}
function renderRoute() {
const boat = state.activeBoat;
const route = state.routes[boat];
let html = `<div class="hq-chip">HARBOR HQ · START & RETURN</div>`;
route.forEach((stop, index) => {
const closed = stop.id === closedDock;
html += `
<div class="route-line">
<div class="route-node ${closed ? "closed" : ""}">
<span class="stop-number">${index + 1}</span>
<span class="stop-name">${stations[stop.id].name}</span>
<button class="stop-type ${stop.type === "waypoint" ? "waypoint" : ""}" data-type-index="${index}" title="Toggle pickup / waypoint">
${stop.type === "pickup" ? "PICK" : "WAY"}
</button>
<button class="remove-stop" data-remove-index="${index}" title="Remove stop">×</button>
</div>
</div>`;
});
if (!route.length) {
html += `<div class="route-line"><div class="route-node"><span class="stop-name">No outer stops yet</span></div></div>`;
}
$("routeBox").innerHTML = html;
$("delayInput").value = state.delays[boat];
renderDockButtons();
}
function renderTransfer() {
$("transferDock").innerHTML = ["North", "East", "West", "Gull"].map(id =>
`<option value="${id}" ${state.transfer.dock === id ? "selected" : ""}>${stations[id].name}${id === closedDock ? " · CLOSED" : ""}</option>`
).join("");
$("transferAmount").value = state.transfer.amount;
}
function eventDescription(event) {
if (event.kind === "pickup") {
return {
title: `${event.boat} · ${stations[event.station].name}`,
detail: `Pick up ${event.amount} passenger${event.amount === 1 ? "" : "s"}`
};
}
if (event.kind === "transfer") {
return {
title: "Transfer · Kestrel → Finch",
detail: `Move exactly ${event.amount} passenger${event.amount === 1 ? "" : "s"}`
};
}
return {
title: `${event.boat} · Harbor HQ`,
detail: `Deliver ${event.amount} passenger${event.amount === 1 ? "" : "s"}`
};
}
function renderSchedule(plan) {
const events = plan.events.filter(e => e.kind !== "visit");
$("scheduleList").innerHTML = events.map(event => {
const desc = eventDescription(event);
const cls = event.kind === "transfer" ? "transfer" : event.kind === "delivery" ? "delivery" : event.boat.toLowerCase();
const dot = event.kind === "transfer" ? "↔" : event.kind === "delivery" ? "✓" : event.boat;
return `
<li class="schedule-item">
<span class="schedule-time">${fmtTime(event.time)}</span>
<span class="schedule-dot ${cls}">${dot}</span>
<span class="schedule-text"><strong>${desc.title}</strong><span>${desc.detail}</span></span>
</li>`;
}).join("");
}
function renderValidation(plan) {
const pill = $("validationPill");
const list = $("validationList");
if (plan.valid) {
pill.className = "status-pill good";
pill.textContent = "Viable";
list.className = "validation-list good";
list.innerHTML = `
<li>All stops are open and reachable.</li>
<li>Boat capacities remain within limits.</li>
<li>The transfer timing and exact count are valid.</li>
<li>All ${totalPassengers} passengers can be delivered by ${fmtTime(deadline)}.</li>`;
} else {
pill.className = "status-pill bad";
pill.textContent = `${plan.blockers.length} blocker${plan.blockers.length === 1 ? "" : "s"}`;
list.className = "validation-list";
list.innerHTML = plan.blockers.map(b => `<li>${b}</li>`).join("");
}
}
function renderMetrics() {
const aboardTotal = live.aboard.A + live.aboard.B;
const tracked = live.waiting + aboardTotal + live.delivered;
$("waitingMetric").textContent = live.waiting;
$("aboardMetric").textContent = aboardTotal;
$("deliveredMetric").textContent = live.delivered;
$("trackedMetric").textContent = tracked;
$("boatAStatus").textContent = `${live.aboard.A} / ${capacities.A} aboard`;
$("boatBStatus").textContent = `${live.aboard.B} / ${capacities.B} aboard`;
$("boatAFill").style.width = `${live.aboard.A / capacities.A * 100}%`;
$("boatBFill").style.width = `${live.aboard.B / capacities.B * 100}%`;
$("ledgerWaiting").textContent = live.waiting;
$("ledgerA").textContent = live.aboard.A;
$("ledgerB").textContent = live.aboard.B;
$("ledgerDelivered").textContent = live.delivered;
$("ledgerTotal").textContent = `${tracked} / ${totalPassengers}`;
}
function refreshPlan() {
lastPlan = analyze();
renderValidation(lastPlan);
renderSchedule(lastPlan);
renderMetrics();
return lastPlan;
}
function addStop(id) {
const route = state.routes[state.activeBoat];
if (route.some(s => s.id === id)) {
showToast(`${stations[id].name} is already in this route.`);
return;
}
route.push({ id, type: state.addMode });
renderRoute();
refreshPlan();
showToast(`${stations[id].name} added to ${boatNames[state.activeBoat]} as ${state.addMode}.`);
}
function showToast(message) {
clearTimeout(toastTimer);
$("toast").textContent = message;
$("toast").classList.add("show");
toastTimer = setTimeout(() => $("toast").classList.remove("show"), 2200);
}
function setOutcome(kind, title, body, items = []) {
const box = $("outcomeBox");
box.className = `outcome ${kind}`;
box.innerHTML = `
<h3>${title}</h3>
<p>${body}</p>
${items.length ? `<ul>${items.map(item => `<li>${item}</li>`).join("")}</ul>` : ""}`;
}
function resetLive() {
live.waiting = totalPassengers;
live.aboard.A = 0;
live.aboard.B = 0;
live.delivered = 0;
Object.values(stations).forEach(station => stationObjects[station.id].label.update(station.waiting));
}
function resetPuzzle() {
state = structuredClone(initialState);
animation = null;
resetLive();
$("clockText").textContent = "00:00";
$("dispatchBtn").textContent = "Run dispatch check";
$("dispatchBtn").classList.remove("running");
document.querySelectorAll(".boat-tab").forEach(b => b.classList.toggle("active", b.dataset.boat === state.activeBoat));
document.querySelectorAll("#modeButtons button").forEach(b => b.classList.toggle("active", b.dataset.mode === state.addMode));
renderRoute();
renderTransfer();
updateRouteLines();
refreshPlan();
setOutcome("", "Awaiting dispatch", "The plan is checked against dock availability, arrival timing, capacity, deadline, and passenger conservation.");
placeBoatStatic();
}
document.querySelectorAll(".boat-tab").forEach(button => {
button.addEventListener("click", () => {
state.activeBoat = button.dataset.boat;
document.querySelectorAll(".boat-tab").forEach(b => b.classList.toggle("active", b === button));
renderRoute();
});
});
document.querySelectorAll("#modeButtons button").forEach(button => {
button.addEventListener("click", () => {
state.addMode = button.dataset.mode;
document.querySelectorAll("#modeButtons button").forEach(b => b.classList.toggle("active", b === button));
renderDockButtons();
});
});
$("dockButtons").addEventListener("click", e => {
const button = e.target.closest("[data-add]");
if (button) addStop(button.dataset.add);
});
$("routeBox").addEventListener("click", e => {
const route = state.routes[state.activeBoat];
const typeButton = e.target.closest("[data-type-index]");
const removeButton = e.target.closest("[data-remove-index]");
if (typeButton) {
const index = Number(typeButton.dataset.typeIndex);
route[index].type = route[index].type === "pickup" ? "waypoint" : "pickup";
renderRoute();
refreshPlan();
}
if (removeButton) {
route.splice(Number(removeButton.dataset.removeIndex), 1);
renderRoute();
refreshPlan();
}
});
$("delayInput").addEventListener("input", e => {
state.delays[state.activeBoat] = Math.max(0, Math.min(20, Number(e.target.value) || 0));
refreshPlan();
});
$("transferDock").addEventListener("change", e => {
state.transfer.dock = e.target.value;
refreshPlan();
});
$("transferAmount").addEventListener("input", e => {
state.transfer.amount = Math.max(1, Math.min(5, Number(e.target.value) || 1));
refreshPlan();
});
$("resetBtn").addEventListener("click", () => {
resetPuzzle();
showToast("Puzzle reset to the original blocked plan.");
});
$("hintBtn").addEventListener("click", () => {
showToast("Meet at North Jetty. Transfer 1 from A to B; A collects West afterward.");
});
$("cameraBtn").addEventListener("click", resetCamera);
/* ------------------------- Dispatch animation ------------------------ */
function positionOnPath(boat, time) {
const path = lastPlan?.paths[boat];
if (!path) return { x: stations.HQ.x, z: stations.HQ.z, yaw: 0 };
if (time <= Number(state.delays[boat])) {
return { x: stations.HQ.x, z: stations.HQ.z, yaw: 0 };
}
for (const segment of path) {
if (time <= segment.end + .0001) {
const from = stations[segment.from];
const to = stations[segment.to];
const duration = Math.max(.001, segment.end - segment.start);
const t = THREE.MathUtils.clamp((time - segment.start) / duration, 0, 1);
const x = THREE.MathUtils.lerp(from.x, to.x, t);
const z = THREE.MathUtils.lerp(from.z, to.z, t);
const dx = to.x - from.x;
const dz = to.z - from.z;
const yaw = dx || dz ? Math.atan2(-dx, -dz) : 0;
return { x, z, yaw };
}
}
return { x: stations.HQ.x, z: stations.HQ.z, yaw: 0 };
}
function placeBoatStatic() {
for (const [index, boat] of ["A", "B"].entries()) {
const group = boats[boat];
const side = boat === "A" ? .42 : -.42;
group.position.set(stations.HQ.x + side, .04, stations.HQ.z + (boat === "A" ? -.7 : .7));
group.rotation.y = Math.PI;
}
}
function applyLiveEvent(event) {
if (event.kind === "pickup") {
live.waiting -= event.amount;
live.aboard[event.boat] += event.amount;
const station = stations[event.station];
station.waiting = Math.max(0, station.waiting - event.amount);
stationObjects[event.station].label.update(station.waiting);
} else if (event.kind === "transfer") {
live.aboard.A -= event.amount;
live.aboard.B += event.amount;
} else if (event.kind === "delivery") {
live.delivered += event.amount;
live.aboard[event.boat] -= event.amount;
}
renderMetrics();
}
function dispatch() {
const plan = refreshPlan();
if (!plan.valid) {
animation = null;
$("dispatchBtn").textContent = "Run dispatch check";
$("dispatchBtn").classList.remove("running");
$("clockText").textContent = "00:00";
pulseUntil = performance.now() + 2600;
resetLive();
placeBoatStatic();
setOutcome(
"impossible",
"Impossible schedule",
"No boats were launched. The current plan has hard blockers that must be resolved.",
plan.blockers
);
showToast("Dispatch rejected: the schedule is impossible.");
return;
}
resetLive();
animation = {
plan,
start: performance.now(),
eventIndex: 0,
finished: false
};
$("dispatchBtn").textContent = "Dispatching…";
$("dispatchBtn").classList.add("running");
setOutcome(
"viable",
"Dispatch in progress",
`Both skiffs are following the approved plan. The transfer is scheduled for ${fmtTime(plan.events.find(e => e.kind === "transfer")?.time || 0)}.`
);
}
$("dispatchBtn").addEventListener("click", dispatch);
function animateBoats(timeMs) {
if (animation && !animation.finished) {
const elapsed = (timeMs - animation.start) / 1000;
const simTime = elapsed * 7;
$("clockText").textContent = fmtTime(Math.min(simTime, deadline + 3));
while (
animation.eventIndex < animation.plan.events.length &&
animation.plan.events[animation.eventIndex].time <= simTime
) {
const event = animation.plan.events[animation.eventIndex++];
applyLiveEvent(event);
}
for (const boat of ["A", "B"]) {
const p = positionOnPath(boat, simTime);
const side = boat === "A" ? .36 : -.36;
const perpX = Math.cos(p.yaw) * side;
const perpZ = -Math.sin(p.yaw) * side;
const group = boats[boat];
group.position.x = p.x + perpX;
group.position.z = p.z + perpZ;
group.rotation.y = p.yaw;
}
if (simTime >= animation.plan.maxDelivery && animation.eventIndex >= animation.plan.events.length) {
animation.finished = true;
$("dispatchBtn").textContent = "Run dispatch check";
$("dispatchBtn").classList.remove("running");
setOutcome(
"viable",
"Rescue complete",
`All ${totalPassengers} passengers were delivered by ${fmtTime(animation.plan.maxDelivery)}. The ledger remains balanced.`
);
}
} else {
for (const [index, boat] of ["A", "B"].entries()) {
const group = boats[boat];
group.position.x = stations.HQ.x + (boat === "A" ? .42 : -.42);
group.position.z = stations.HQ.z + (boat === "A" ? -.7 : .7);
group.rotation.y = Math.PI;
}
}
}
function frame(timeMs) {
requestAnimationFrame(frame);
for (const wave of waveMeshes) {
wave.position.y = -.13 + Math.sin(timeMs * .0007 + wave.userData.phase) * .025;
wave.material.opacity = wave.userData.baseOpacity * (.72 + Math.sin(timeMs * .001 + wave.userData.phase) * .22);
}
for (const boat of ["A", "B"]) {
const group = boats[boat];
group.position.y = .04 + Math.sin(timeMs * .003 + group.userData.bobPhase) * .045;
group.rotation.z = Math.sin(timeMs * .002 + group.userData.bobPhase) * .018;
}
const pulse = performance.now() < pulseUntil;
stationObjects[closedDock].marker.material.emissive.setHex(pulse ? 0x7d1118 : 0x000000);
stationObjects[closedDock].marker.material.emissiveIntensity = pulse ? 1.2 : 0;
animateBoats(timeMs);
updateCamera();
renderer.render(scene, camera);
}
/* ------------------------------ Startup ------------------------------ */
renderRoute();
renderTransfer();
updateRouteLines();
placeBoatStatic();
refreshPlan();
resetCamera();
requestAnimationFrame(frame);
</script>
</body>
</html>
```