Prompt specification
Build or customize the Three.js 3D scene "School Trip Planning Under Delays" 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: School Trip Planning Under Delays
Category: Art & Culture · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/school-trip-planning-under-delays-x3224
Scene Description Prompt:
Build a low-poly school-trip planning game with seeded delays and fallback activities. Three.js from cdnjs, one self-contained HTML file.
Working Three.js Starter (school-trip-planning-under-delays-x3224):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tripwise — School Trip Planner</title>
<style>
:root {
--ink: #183153;
--muted: #6d7e91;
--paper: #fffdf7;
--paper-2: #f7f2e8;
--line: #e5dfd2;
--orange: #f47b48;
--orange-dark: #d75e2e;
--teal: #2c9d91;
--blue: #4d83c5;
--red: #d95d5d;
--shadow: 0 16px 42px rgba(29, 48, 69, 0.16);
--radius: 18px;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #b9d9d7;
color: var(--ink);
font-family: "Trebuchet MS", "Segoe UI", sans-serif;
}
button, input, select {
font: inherit;
}
button {
cursor: pointer;
}
button:disabled {
cursor: not-allowed;
opacity: 0.48;
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
#labels {
position: fixed;
inset: 0;
pointer-events: none;
overflow: hidden;
}
.map-label {
position: absolute;
transform: translate(-50%, -100%);
pointer-events: auto;
border: 1px solid rgba(24, 49, 83, 0.12);
border-radius: 999px;
padding: 6px 10px 6px 7px;
background: rgba(255, 253, 247, 0.94);
color: var(--ink);
box-shadow: 0 5px 16px rgba(24, 49, 83, 0.15);
white-space: nowrap;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.01em;
transition: transform 160ms ease, background 160ms ease;
}
.map-label:hover {
transform: translate(-50%, -100%) scale(1.05);
background: white;
}
.map-label.selected {
background: var(--ink);
color: white;
border-color: var(--ink);
}
.map-label .label-dot {
display: inline-block;
width: 9px;
height: 9px;
margin-right: 6px;
border-radius: 50%;
background: var(--orange);
vertical-align: -1px;
}
.map-label.school-label {
pointer-events: none;
opacity: 0.9;
}
.topbar {
position: fixed;
z-index: 20;
top: 14px;
left: 16px;
right: 16px;
height: 62px;
display: flex;
align-items: center;
gap: 16px;
padding: 0 16px;
background: rgba(255, 253, 247, 0.94);
border: 1px solid rgba(255, 255, 255, 0.65);
border-radius: 17px;
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
}
.brand {
display: flex;
align-items: center;
gap: 11px;
min-width: 225px;
}
.brand-mark {
display: grid;
place-items: center;
width: 38px;
height: 38px;
border-radius: 12px;
background: var(--orange);
color: white;
font-size: 21px;
box-shadow: inset 0 -4px 0 rgba(0, 0, 0, 0.08);
}
.brand-title {
font-size: 17px;
font-weight: 900;
letter-spacing: 0.08em;
line-height: 1;
}
.brand-subtitle {
margin-top: 5px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.top-spacer { flex: 1; }
.top-chip {
display: flex;
align-items: center;
gap: 8px;
min-height: 34px;
padding: 0 11px;
border: 1px solid var(--line);
border-radius: 999px;
background: white;
font-size: 11px;
font-weight: 800;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--teal);
box-shadow: 0 0 0 4px rgba(44, 157, 145, 0.13);
}
.status-dot.running {
background: var(--orange);
box-shadow: 0 0 0 4px rgba(244, 123, 72, 0.16);
animation: pulse 1.2s infinite;
}
.status-dot.complete {
background: var(--blue);
box-shadow: 0 0 0 4px rgba(77, 131, 197, 0.15);
}
@keyframes pulse {
50% { opacity: 0.45; }
}
.small-button {
min-height: 34px;
padding: 0 12px;
border: 1px solid var(--line);
border-radius: 10px;
background: white;
color: var(--ink);
font-size: 11px;
font-weight: 800;
}
.small-button:hover {
border-color: #c9bfae;
background: #fffaf0;
}
.panel {
position: fixed;
z-index: 15;
top: 88px;
bottom: 16px;
width: 342px;
overflow: auto;
scrollbar-width: thin;
scrollbar-color: #cfc7b9 transparent;
background: rgba(255, 253, 247, 0.95);
border: 1px solid rgba(255, 255, 255, 0.75);
border-radius: var(--radius);
box-shadow: var(--shadow);
backdrop-filter: blur(13px);
}
.planner {
left: 16px;
}
.dispatch {
right: 16px;
width: 294px;
}
.panel-inner {
padding: 19px;
}
.eyebrow {
color: var(--orange-dark);
font-size: 10px;
font-weight: 900;
letter-spacing: 0.13em;
text-transform: uppercase;
}
h1, h2, h3, p { margin-top: 0; }
h1 {
margin: 7px 0 9px;
max-width: 280px;
font-size: 25px;
line-height: 1.04;
letter-spacing: -0.04em;
}
.intro {
margin-bottom: 17px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.form-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.field {
min-width: 0;
}
.field-label {
display: block;
margin: 0 0 6px;
color: var(--muted);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.input-wrap {
position: relative;
}
input, select {
width: 100%;
height: 39px;
border: 1px solid var(--line);
border-radius: 10px;
outline: none;
background: white;
color: var(--ink);
font-size: 12px;
font-weight: 700;
}
input {
padding: 0 38px 0 10px;
}
select {
padding: 0 28px 0 9px;
}
input:focus, select:focus {
border-color: var(--orange);
box-shadow: 0 0 0 3px rgba(244, 123, 72, 0.12);
}
.roll-button {
position: absolute;
top: 5px;
right: 5px;
width: 29px;
height: 29px;
padding: 0;
border: 0;
border-radius: 8px;
background: var(--paper-2);
color: var(--ink);
font-size: 15px;
}
.forecast-card {
margin: 15px 0 17px;
padding: 13px;
border: 1px solid #eadfcd;
border-radius: 14px;
background: linear-gradient(145deg, #fff8e9, #fffdf7);
}
.forecast-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
}
.forecast-head strong {
font-size: 11px;
letter-spacing: 0.04em;
}
.forecast-badge {
padding: 4px 7px;
border-radius: 999px;
background: rgba(44, 157, 145, 0.12);
color: #247b72;
font-size: 9px;
font-weight: 900;
}
.forecast-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 8px;
}
.metric {
min-width: 0;
text-align: center;
}
.metric-value {
display: block;
font-size: 17px;
font-weight: 900;
line-height: 1;
}
.metric-label {
display: block;
margin-top: 5px;
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.section-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 9px;
}
.section-title {
margin: 0;
font-size: 13px;
font-weight: 900;
}
.count-badge {
display: inline-grid;
place-items: center;
min-width: 23px;
height: 23px;
margin-left: 5px;
border-radius: 8px;
background: var(--ink);
color: white;
font-size: 10px;
vertical-align: 1px;
}
.text-button {
padding: 0;
border: 0;
background: none;
color: var(--orange-dark);
font-size: 10px;
font-weight: 900;
}
.text-button:hover { text-decoration: underline; }
.route-list {
display: grid;
gap: 9px;
}
.route-card {
position: relative;
padding: 12px;
border: 1px solid var(--line);
border-radius: 14px;
background: white;
box-shadow: 0 4px 13px rgba(24, 49, 83, 0.05);
}
.route-card.active {
border-color: #f4b394;
box-shadow: 0 6px 16px rgba(244, 123, 72, 0.10);
}
.route-top {
display: flex;
align-items: flex-start;
gap: 9px;
}
.route-number {
display: grid;
flex: 0 0 28px;
place-items: center;
width: 28px;
height: 28px;
border-radius: 9px;
background: var(--ink);
color: white;
font-size: 11px;
font-weight: 900;
}
.route-title-wrap {
flex: 1;
min-width: 0;
}
.route-name {
display: block;
overflow: hidden;
font-size: 12px;
font-weight: 900;
text-overflow: ellipsis;
white-space: nowrap;
}
.route-site {
display: block;
margin-top: 2px;
overflow: hidden;
color: var(--muted);
font-size: 9px;
text-overflow: ellipsis;
white-space: nowrap;
}
.route-controls {
display: flex;
gap: 3px;
}
.icon-button {
display: grid;
place-items: center;
width: 25px;
height: 25px;
padding: 0;
border: 1px solid var(--line);
border-radius: 7px;
background: white;
color: var(--ink);
font-size: 11px;
font-weight: 900;
}
.icon-button:hover {
border-color: var(--orange);
color: var(--orange-dark);
}
.route-forecast {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin: 10px 0;
padding: 7px 8px;
border-radius: 9px;
background: var(--paper-2);
color: var(--muted);
font-size: 9px;
font-weight: 800;
}
.route-forecast strong {
color: var(--ink);
font-size: 10px;
}
.forecast-status {
padding: 3px 6px;
border-radius: 999px;
background: rgba(44, 157, 145, 0.13);
color: #247b72;
}
.forecast-status.fallback {
background: rgba(217, 93, 93, 0.12);
color: #ad4444;
}
.route-options {
display: grid;
grid-template-columns: 1fr 82px;
gap: 7px;
}
.route-options .mini-label {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 8px;
font-weight: 900;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.route-options select {
height: 34px;
font-size: 9px;
}
.planning-note {
margin: 12px 0;
padding: 10px;
border-left: 3px solid var(--teal);
border-radius: 0 8px 8px 0;
background: rgba(44, 157, 145, 0.08);
color: #4e6e6c;
font-size: 10px;
line-height: 1.45;
}
.primary-button {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
width: 100%;
min-height: 46px;
padding: 0 16px;
border: 0;
border-radius: 12px;
background: var(--orange);
color: white;
box-shadow: inset 0 -4px 0 rgba(0, 0, 0, 0.09), 0 8px 18px rgba(244, 123, 72, 0.22);
font-size: 12px;
font-weight: 900;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.primary-button:hover:not(:disabled) {
background: var(--orange-dark);
}
.dispatch-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 14px;
}
.dispatch-title h2 {
margin: 0;
font-size: 15px;
}
.live-badge {
padding: 4px 7px;
border-radius: 999px;
background: rgba(244, 123, 72, 0.12);
color: var(--orange-dark);
font-size: 8px;
font-weight: 900;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.clock-card {
padding: 15px;
border-radius: 14px;
background: var(--ink);
color: white;
box-shadow: 0 8px 20px rgba(24, 49, 83, 0.18);
}
.clock-label {
color: #aebed2;
font-size: 8px;
font-weight: 900;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.clock-value {
margin: 4px 0 11px;
font-size: 30px;
font-weight: 900;
letter-spacing: -0.04em;
}
.energy-head {
display: flex;
align-items: center;
justify-content: space-between;
color: #dbe5ef;
font-size: 9px;
font-weight: 800;
}
.energy-track {
height: 7px;
margin-top: 7px;
overflow: hidden;
border-radius: 999px;
background: rgba(255, 255, 255, 0.13);
}
.energy-fill {
width: 100%;
height: 100%;
border-radius: inherit;
background: #65d2b6;
transition: width 350ms ease, background 350ms ease;
}
.progress-wrap {
margin: 17px 0;
}
.progress-title {
margin-bottom: 9px;
color: var(--muted);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.progress-steps {
display: grid;
gap: 7px;
}
.progress-step {
display: flex;
align-items: center;
gap: 9px;
color: #8996a5;
font-size: 10px;
font-weight: 800;
}
.progress-dot {
display: grid;
flex: 0 0 21px;
place-items: center;
width: 21px;
height: 21px;
border: 1px solid #d7dde3;
border-radius: 50%;
background: white;
color: #8b98a7;
font-size: 8px;
}
.progress-step.done {
color: #47736d;
}
.progress-step.done .progress-dot {
border-color: var(--teal);
background: var(--teal);
color: white;
}
.progress-step.current {
color: var(--ink);
}
.progress-step.current .progress-dot {
border-color: var(--orange);
background: var(--orange);
color: white;
box-shadow: 0 0 0 4px rgba(244, 123, 72, 0.12);
}
.log-title {
margin-bottom: 9px;
color: var(--muted);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.log-list {
display: grid;
gap: 7px;
max-height: 270px;
overflow: auto;
scrollbar-width: thin;
}
.log-item {
position: relative;
padding: 8px 8px 8px 12px;
border-radius: 9px;
background: #f7f5ef;
color: #5f7082;
font-size: 9px;
line-height: 1.45;
}
.log-item::before {
position: absolute;
top: 9px;
bottom: 9px;
left: 4px;
width: 3px;
border-radius: 3px;
background: #aab5c1;
content: "";
}
.log-item.good::before { background: var(--teal); }
.log-item.warn::before { background: var(--orange); }
.log-item.bad::before { background: var(--red); }
.log-time {
display: block;
margin-bottom: 2px;
color: var(--ink);
font-size: 8px;
font-weight: 900;
}
.map-tools {
position: fixed;
z-index: 12;
left: 50%;
bottom: 19px;
display: flex;
gap: 7px;
transform: translateX(-50%);
}
.map-tool {
display: grid;
place-items: center;
width: 39px;
height: 39px;
border: 1px solid rgba(255, 255, 255, 0.8);
border-radius: 11px;
background: rgba(255, 253, 247, 0.94);
color: var(--ink);
box-shadow: 0 7px 20px rgba(24, 49, 83, 0.16);
font-size: 16px;
}
.map-tool:hover {
background: white;
transform: translateY(-1px);
}
.map-hint {
position: fixed;
z-index: 10;
left: 50%;
bottom: 67px;
transform: translateX(-50%);
padding: 6px 11px;
border-radius: 999px;
background: rgba(24, 49, 83, 0.76);
color: white;
font-size: 9px;
font-weight: 800;
white-space: nowrap;
pointer-events: none;
}
.toast {
position: fixed;
z-index: 50;
left: 50%;
top: 91px;
max-width: min(430px, calc(100vw - 30px));
padding: 10px 15px;
border-radius: 11px;
background: var(--ink);
color: white;
box-shadow: var(--shadow);
font-size: 11px;
font-weight: 800;
text-align: center;
transform: translate(-50%, -15px);
opacity: 0;
pointer-events: none;
transition: 180ms ease;
}
.toast.show {
transform: translate(-50%, 0);
opacity: 1;
}
.modal-overlay {
position: fixed;
z-index: 60;
inset: 0;
display: grid;
place-items: center;
padding: 20px;
background: rgba(18, 35, 55, 0.55);
backdrop-filter: blur(7px);
}
.modal-overlay[hidden] { display: none; }
.result-card {
width: min(510px, 100%);
max-height: calc(100vh - 40px);
overflow: auto;
padding: 25px;
border: 1px solid rgba(255, 255, 255, 0.7);
border-radius: 22px;
background: var(--paper);
box-shadow: 0 25px 70px rgba(10, 25, 40, 0.3);
}
.result-head {
display: flex;
align-items: center;
gap: 17px;
margin-bottom: 19px;
}
.grade {
display: grid;
flex: 0 0 72px;
place-items: center;
width: 72px;
height: 72px;
border-radius: 21px;
background: var(--ink);
color: white;
font-size: 38px;
font-weight: 900;
box-shadow: inset 0 -6px 0 rgba(0, 0, 0, 0.1);
}
.result-head h2 {
margin: 5px 0 4px;
font-size: 25px;
letter-spacing: -0.04em;
}
.result-head p {
margin: 0;
color: var(--muted);
font-size: 11px;
}
.result-stats {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 8px;
margin-bottom: 16px;
}
.result-stat {
padding: 11px 6px;
border: 1px solid var(--line);
border-radius: 12px;
text-align: center;
background: white;
}
.result-stat strong {
display: block;
font-size: 19px;
}
.result-stat span {
color: var(--muted);
font-size: 8px;
font-weight: 800;
text-transform: uppercase;
}
.breakdown {
display: grid;
gap: 7px;
margin: 10px 0 18px;
}
.breakdown-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 10px;
border-radius: 10px;
background: var(--paper-2);
font-size: 10px;
}
.breakdown-row strong {
display: block;
margin-bottom: 2px;
}
.breakdown-row small {
color: var(--muted);
font-size: 8px;
}
.result-points {
color: var(--teal);
font-size: 11px;
font-weight: 900;
white-space: nowrap;
}
.result-actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.secondary-button {
min-height: 44px;
border: 1px solid var(--line);
border-radius: 12px;
background: white;
color: var(--ink);
font-size: 11px;
font-weight: 900;
}
dialog {
width: min(480px, calc(100vw - 30px));
padding: 0;
border: 0;
border-radius: 20px;
background: var(--paper);
color: var(--ink);
box-shadow: 0 25px 70px rgba(10, 25, 40, 0.3);
}
dialog::backdrop {
background: rgba(18, 35, 55, 0.55);
backdrop-filter: blur(5px);
}
.help-body {
padding: 24px;
}
.help-body h2 {
margin: 7px 0 8px;
font-size: 24px;
}
.help-body p,
.help-body li {
color: var(--muted);
font-size: 11px;
line-height: 1.6;
}
.help-body ol {
padding-left: 18px;
}
.help-body .primary-button {
margin-top: 7px;
}
@media (max-width: 1050px) {
.dispatch {
width: 250px;
}
.brand {
min-width: 185px;
}
.trip-chip {
display: none;
}
}
@media (max-width: 800px) {
.topbar {
top: 8px;
left: 8px;
right: 8px;
height: 54px;
padding: 0 10px;
}
.brand {
min-width: 0;
}
.brand-subtitle,
.seed-top-chip {
display: none;
}
.panel {
top: auto;
bottom: 8px;
max-height: 47vh;
}
.planner {
left: 8px;
width: min(360px, calc(100vw - 16px));
}
.dispatch {
display: none;
}
.map-tools {
bottom: calc(47vh + 20px);
}
.map-hint {
display: none;
}
.panel-inner {
padding: 15px;
}
h1 {
font-size: 21px;
}
}
</style>
</head>
<body>
<div id="viewport"></div>
<div id="labels"></div>
<header class="topbar">
<div class="brand">
<div class="brand-mark">▰</div>
<div>
<div class="brand-title">TRIPWISE</div>
<div class="brand-subtitle">Oakwood Elementary · Grade 6</div>
</div>
</div>
<div class="top-spacer"></div>
<div class="top-chip trip-chip">
<span>☀</span>
<span>Clear skies · 18°C</span>
</div>
<div class="top-chip seed-top-chip">
<span>Seed</span>
<strong id="topSeed">OWL-4821</strong>
</div>
<div class="top-chip">
<span class="status-dot" id="statusDot"></span>
<span id="statusText">Planning</span>
</div>
<button class="small-button" id="helpButton">How to play</button>
</header>
<aside class="panel planner">
<div class="panel-inner">
<div class="eyebrow">Route board</div>
<h1>Make every minute count.</h1>
<p class="intro">
Pick three stops, protect their schedules, and prepare a fallback for
the inevitable Monday delay.
</p>
<div class="form-grid">
<div class="field">
<label class="field-label" for="seedInput">Delay seed</label>
<div class="input-wrap">
<input id="seedInput" value="OWL-4821" maxlength="18" spellcheck="false">
<button class="roll-button" id="rollSeed" title="Choose a new seed" aria-label="Choose a new seed">↻</button>
</div>
</div>
<div class="field">
<label class="field-label" for="departureInput">Departure</label>
<input id="departureInput" type="time" value="08:30">
</div>
</div>
<div class="forecast-card">
<div class="forecast-head">
<strong>SEEDED FORECAST</strong>
<span class="forecast-badge" id="forecastBadge">ON TRACK</span>
</div>
<div class="forecast-grid">
<div class="metric">
<span class="metric-value" id="forecastTravel">0m</span>
<span class="metric-label">Travel</span>
</div>
<div class="metric">
<span class="metric-value" id="forecastDelay">0m</span>
<span class="metric-label">Delay</span>
</div>
<div class="metric">
<span class="metric-value" id="forecastPoints">0</span>
<span class="metric-label">Points</span>
</div>
<div class="metric">
<span class="metric-value" id="forecastEnergy">100</span>
<span class="metric-label">Energy</span>
</div>
</div>
</div>
<div class="section-row">
<h2 class="section-title">Your route <span class="count-badge" id="routeCount">3/3</span></h2>
<button class="text-button" id="autoArrange">✦ Best order</button>
</div>
<div class="route-list" id="routeList"></div>
<div class="planning-note">
Click a map marker to add a stop. Each stop needs a fallback activity
and enough schedule buffer to absorb a seeded delay.
</div>
<button class="primary-button" id="runTrip">
<span>▶</span>
<span id="runLabel">Run the trip</span>
</button>
</div>
</aside>
<aside class="panel dispatch">
<div class="panel-inner">
<div class="dispatch-title">
<h2>Trip radio</h2>
<span class="live-badge" id="radioBadge">Standby</span>
</div>
<div class="clock-card">
<div class="clock-label">Current trip time</div>
<div class="clock-value" id="simClock">08:30</div>
<div class="energy-head">
<span>Chaperone energy</span>
<span id="energyValue">100%</span>
</div>
<div class="energy-track">
<div class="energy-fill" id="energyFill"></div>
</div>
</div>
<div class="progress-wrap">
<div class="progress-title">Route progress</div>
<div class="progress-steps" id="progressSteps"></div>
</div>
<div class="log-title">Dispatch log</div>
<div class="log-list" id="logList"></div>
</div>
</aside>
<div class="map-hint">Drag to orbit · Scroll to zoom · Click a marker to add it</div>
<div class="map-tools">
<button class="map-tool" id="resetCamera" title="Reset camera" aria-label="Reset camera">⌂</button>
<button class="map-tool" id="focusRoute" title="Focus route" aria-label="Focus route">◎</button>
</div>
<div class="toast" id="toast"></div>
<div class="modal-overlay" id="resultModal" hidden>
<div class="result-card">
<div class="result-head">
<div class="grade" id="resultGrade">A</div>
<div>
<div class="eyebrow">Trip report</div>
<h2 id="resultTitle">A brilliant day out!</h2>
<p id="resultSubtitle">The class got the most out of every stop.</p>
</div>
</div>
<div class="result-stats">
<div class="result-stat">
<strong id="resultPoints">0</strong>
<span>Points</span>
</div>
<div class="result-stat">
<strong id="resultPrimary">0/3</strong>
<span>Primary</span>
</div>
<div class="result-stat">
<strong id="resultDelay">0m</strong>
<span>Delay</span>
</div>
<div class="result-stat">
<strong id="resultEnergy">100%</strong>
<span>Energy</span>
</div>
</div>
<div class="breakdown" id="resultBreakdown"></div>
<div class="result-actions">
<button class="secondary-button" id="replanButton">Replan this seed</button>
<button class="primary-button" id="newSeedButton">Try a new seed</button>
</div>
</div>
</div>
<dialog id="helpDialog">
<div class="help-body">
<div class="eyebrow">Field guide</div>
<h2>How to run a smooth trip</h2>
<ol>
<li>Select three stop markers, or remove and add stops from the route board.</li>
<li>Choose a fallback activity and a delay buffer for every stop.</li>
<li>Use <strong>Best order</strong> to compare every possible order for your selected stops.</li>
<li>Run the trip. The same seed always creates the same delays.</li>
</ol>
<p>
A primary activity runs when the bus arrives within its activity window
and the lateness fits inside your chosen buffer. Otherwise, the fallback
activity takes over.
</p>
<button class="primary-button" id="closeHelp">Got it</button>
</div>
</dialog>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Game data
// -------------------------------------------------------------------------
const $ = (id) => document.getElementById(id);
const STOPS = {
dino: {
id: "dino",
name: "Dinosaur Gallery",
site: "Natural History Museum",
icon: "🦕",
node: "museum",
schedule: 9 * 60 + 15,
close: 10 * 60 + 15,
duration: 25,
appeal: 30,
color: 0xe58b58,
offset: [2.2, 1.3],
building: [-5.5, -4],
fallbacks: ["Fossil Dig Courtyard", "Museum Maker Cart"]
},
ocean: {
id: "ocean",
name: "Ocean Touch Pool",
site: "Harbor Aquarium",
icon: "🐠",
node: "aquarium",
schedule: 10 * 60,
close: 11 * 60,
duration: 25,
appeal: 29,
color: 0x48a8c6,
offset: [1.8, -1.8],
building: [0, -5.5],
fallbacks: ["Bubble Lab", "Tide Pool Study"]
},
robot: {
id: "robot",
name: "Robotics Lab",
site: "Innovation Center",
icon: "🤖",
node: "science",
schedule: 10 * 60 + 45,
close: 11 * 60 + 45,
duration: 30,
appeal: 32,
color: 0x776cc4,
offset: [2.2, 1.4],
building: [5.2, -4.5],
fallbacks: ["Snap-Circuit Bench", "Design Thinking Studio"]
},
games: {
id: "games",
name: "Team Skills Games",
site: "Oakwood Sports Center",
icon: "⚽",
node: "stadium",
schedule: 11 * 60 + 30,
close: 12 * 60 + 30,
duration: 25,
appeal: 27,
color: 0x58aa78,
offset: [2.3, 1.5],
building: [5, -3],
fallbacks: ["Court Skills Circuit", "Fitness Trail"]
},
theatre: {
id: "theatre",
name: "Story Stage Show",
site: "Civic Arts Theatre",
icon: "🎭",
node: "theatre",
schedule: 12 * 60 + 15,
close: 13 * 60 + 15,
duration: 30,
appeal: 28,
color: 0xd66c83,
offset: [2.1, 1.5],
building: [-5, 3.5],
fallbacks: ["Improv Games", "Puppet Craft"]
},
stars: {
id: "stars",
name: "Planetarium Show",
site: "Riverside Science Center",
icon: "🪐",
node: "planetarium",
schedule: 13 * 60,
close: 14 * 60,
duration: 25,
appeal: 31,
color: 0x4d75bd,
offset: [2.2, 1.3],
building: [5, -4],
fallbacks: ["Constellation Craft", "Storytime Under Stars"]
}
};
const NODES = {
school: { x: 0, z: 14 },
west: { x: -18, z: 4 },
east: { x: 18, z: 4 },
north: { x: 0, z: -13 },
museum: { x: -26, z: -6 },
aquarium: { x: -8, z: -27 },
science: { x: 13, z: -23 },
stadium: { x: 24, z: 6 },
theatre: { x: -15, z: 22 },
planetarium:{ x: 0, z: 34 }
};
const EDGES = [
["school", "west", 6],
["school", "east", 7],
["school", "theatre", 5],
["school", "planetarium", 8],
["west", "north", 8],
["west", "museum", 7],
["west", "theatre", 6],
["east", "north", 10],
["east", "science", 8],
["east", "stadium", 7],
["north", "aquarium", 7],
["north", "science", 6],
["theatre", "planetarium", 7]
];
const GRAPH = Object.fromEntries(Object.keys(NODES).map((key) => [key, []]));
for (const [a, b, weight] of EDGES) {
GRAPH[a].push({ to: b, weight });
GRAPH[b].push({ to: a, weight });
}
const state = {
seed: "OWL-4821",
departure: 8 * 60 + 30,
route: [
{ id: "dino", buffer: 20, fallback: STOPS.dino.fallbacks[0] },
{ id: "ocean", buffer: 20, fallback: STOPS.ocean.fallbacks[0] },
{ id: "robot", buffer: 20, fallback: STOPS.robot.fallbacks[0] }
],
phase: "planning",
forecast: null,
simulation: null,
energy: 100,
points: 0,
bonus: 0,
activeStop: null
};
// -------------------------------------------------------------------------
// Utilities and deterministic random numbers
// -------------------------------------------------------------------------
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
function hash32(text) {
let hash = 2166136261;
for (let i = 0; i < text.length; i++) {
hash ^= text.charCodeAt(i);
hash = Math.imul(hash, 16777619);
}
return hash >>> 0;
}
function mulberry32(seed) {
return function () {
let value = seed += 0x6D2B79F5;
value = Math.imul(value ^ (value >>> 15), value | 1);
value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
};
}
function formatTime(minutes) {
const normalized = ((Math.round(minutes) % 1440) + 1440) % 1440;
const hours = Math.floor(normalized / 60);
const mins = normalized % 60;
const suffix = hours >= 12 ? "PM" : "AM";
const displayHour = hours % 12 || 12;
return `${displayHour}:${String(mins).padStart(2, "0")} ${suffix}`;
}
function parseTime(value) {
const [hours, minutes] = value.split(":").map(Number);
return hours * 60 + minutes;
}
function shortestPath(start, end) {
const distances = {};
const previous = {};
const remaining = new Set(Object.keys(NODES));
for (const key of remaining) distances[key] = Infinity;
distances[start] = 0;
while (remaining.size) {
let current = null;
let best = Infinity;
for (const key of remaining) {
if (distances[key] < best) {
best = distances[key];
current = key;
}
}
if (current === null || current === end) break;
remaining.delete(current);
for (const edge of GRAPH[current]) {
const candidate = distances[current] + edge.weight;
if (candidate < distances[edge.to]) {
distances[edge.to] = candidate;
previous[edge.to] = current;
}
}
}
const path = [end];
while (path[0] !== start) {
const parent = previous[path[0]];
if (!parent) return [start, end];
path.unshift(parent);
}
return path;
}
function pathWeight(path) {
let total = 0;
for (let i = 1; i < path.length; i++) {
const edge = GRAPH[path[i - 1]].find((item) => item.to === path[i]);
total += edge.weight;
}
return total;
}
function edgeBetween(a, b) {
return GRAPH[a].find((edge) => edge.to === b);
}
function getLegDelay(seed, legIndex, from, to, baseTravel, currentTime) {
const key = `${seed}|leg:${legIndex}|${from}:${to}|bucket:${Math.floor(currentTime / 30)}|${baseTravel}`;
const random = mulberry32(hash32(key));
let rush = 0;
if (currentTime >= 8 * 60 && currentTime < 9 * 60) rush = 4;
else if (currentTime >= 9 * 60 && currentTime < 10 * 60) rush = 2;
else if (currentTime >= 11 * 60 && currentTime < 12 * 60) rush = 3;
let delay = Math.floor(random() * 7) + Math.floor(baseTravel / 10) + rush;
const eventRoll = random();
if (eventRoll > 0.84) {
delay += 8 + Math.floor(random() * 8);
const events = [
"Roadworks on the route",
"A replacement coach arrives",
"A permission slip is missing",
"Traffic backs up at the bridge",
"The coach picks up a flat tyre"
];
return {
minutes: delay,
type: events[Math.floor(random() * events.length)]
};
}
if (eventRoll > 0.62) {
return {
minutes: delay,
type: "A slow queue builds near the entrance"
};
}
return {
minutes: delay,
type: "Light traffic, but the schedule is tight"
};
}
function calculateForecast(route) {
let currentTime = state.departure;
let previousNode = "school";
let totalTravel = 0;
let totalDelay = 0;
let totalWait = 0;
let points = 0;
let bonus = 0;
let primaryCount = 0;
let fallbackCount = 0;
const legs = [];
const stopResults = [];
route.forEach((item, index) => {
const stop = STOPS[item.id];
const path = shortestPath(previousNode, stop.node);
const baseTravel = pathWeight(path);
const delayInfo = getLegDelay(
state.seed,
index,
previousNode,
stop.node,
baseTravel,
currentTime
);
const arrival = currentTime + baseTravel + delayInfo.minutes;
const wait = Math.max(0, stop.schedule - arrival);
const activityStart = arrival + wait;
const late = Math.max(0, activityStart - stop.schedule);
const withinWindow = arrival <= stop.close;
const withinBuffer = late <= item.buffer;
const primary = withinWindow && withinBuffer;
const duration = primary ? stop.duration : 20;
const earnedPoints = primary ? stop.appeal : 12;
const punctualityBonus = primary ? Math.max(0, 8 - Math.floor(late / 3)) : 0;
const departure = activityStart + duration;
let reason = "";
if (!withinWindow) reason = "Outside the activity window";
else if (!withinBuffer) reason = "Delay exceeded the schedule buffer";
legs.push({
index,
from: previousNode,
to: stop.node,
path,
baseTravel,
delay: delayInfo.minutes,
delayType: delayInfo.type,
arrival,
wait,
activityStart,
late,
primary,
reason,
duration,
points: earnedPoints,
bonus: punctualityBonus
});
stopResults.push({
id: stop.id,
stop,
item,
arrival,
wait,
late,
primary,
reason,
duration,
points: earnedPoints,
bonus: punctualityBonus
});
totalTravel += baseTravel;
totalDelay += delayInfo.minutes;
totalWait += wait;
points += earnedPoints;
bonus += punctualityBonus;
if (primary) primaryCount++;
else fallbackCount++;
currentTime = departure;
previousNode = stop.node;
});
const energy = clamp(
Math.round(100 - totalDelay * 1.3 - totalWait * 0.15 + primaryCount * 5 - fallbackCount * 2),
0,
100
);
const score = Math.max(0, Math.round(points + bonus - totalDelay * 0.4));
return {
legs,
stops: stopResults,
totalTravel,
totalDelay,
totalWait,
points,
bonus,
primaryCount,
fallbackCount,
energy,
score
};
}
function permutations(items) {
if (items.length <= 1) return [items];
const output = [];
for (let i = 0; i < items.length; i++) {
const rest = items.slice(0, i).concat(items.slice(i + 1));
for (const permutation of permutations(rest)) {
output.push([items[i], ...permutation]);
}
}
return output;
}
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const viewport = $("viewport");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xb9d9d7);
scene.fog = new THREE.Fog(0xb9d9d7, 62, 110);
const camera = new THREE.PerspectiveCamera(43, innerWidth / innerHeight, 0.1, 180);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
viewport.appendChild(renderer.domElement);
const hemi = new THREE.HemisphereLight(0xf8f4df, 0x557a6b, 2.3);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff1ce, 3.4);
sun.position.set(25, 38, 20);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -55;
sun.shadow.camera.right = 55;
sun.shadow.camera.top = 55;
sun.shadow.camera.bottom = -55;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 100;
sun.shadow.bias = -0.0005;
scene.add(sun);
const terrain = new THREE.Mesh(
new THREE.CylinderGeometry(46, 49, 2.8, 10),
new THREE.MeshStandardMaterial({
color: 0x91b982,
roughness: 1,
flatShading: true
})
);
terrain.position.y = -1.55;
terrain.scale.z = 0.82;
terrain.receiveShadow = true;
scene.add(terrain);
const lowerGround = new THREE.Mesh(
new THREE.CylinderGeometry(49, 51, 2.4, 10),
new THREE.MeshStandardMaterial({
color: 0x729b72,
roughness: 1,
flatShading: true
})
);
lowerGround.position.y = -3.0;
lowerGround.scale.z = 0.82;
scene.add(lowerGround);
const water = new THREE.Mesh(
new THREE.CircleGeometry(5.5, 9),
new THREE.MeshStandardMaterial({
color: 0x64b5c0,
roughness: 0.65,
flatShading: true
})
);
water.rotation.x = -Math.PI / 2;
water.position.set(7, 0.08, -5);
water.scale.set(1.3, 0.8, 1);
scene.add(water);
const routeGroup = new THREE.Group();
scene.add(routeGroup);
const labels = [];
const markerGroups = {};
const markerMeshes = [];
const cloudGroups = [];
const markerMaterial = new THREE.MeshStandardMaterial({
color: 0xf47b48,
emissive: 0x3a1206,
emissiveIntensity: 0.08,
roughness: 0.7
});
function createRoad(aId, bId) {
const a = NODES[aId];
const b = NODES[bId];
const dx = b.x - a.x;
const dz = b.z - a.z;
const length = Math.hypot(dx, dz);
const angle = Math.atan2(dx, dz);
const midpoint = new THREE.Vector3((a.x + b.x) / 2, 0.02, (a.z + b.z) / 2);
const road = new THREE.Mesh(
new THREE.BoxGeometry(3.25, 0.14, length + 0.5),
new THREE.MeshStandardMaterial({
color: 0x6f7f80,
roughness: 1,
flatShading: true
})
);
road.position.copy(midpoint);
road.rotation.y = angle;
road.receiveShadow = true;
scene.add(road);
const dashCount = Math.max(1, Math.floor(length / 4));
const dashMaterial = new THREE.MeshStandardMaterial({
color: 0xf5e3a8,
roughness: 1
});
for (let i = 0; i < dashCount; i++) {
const t = (i + 0.5) / dashCount;
const dash = new THREE.Mesh(
new THREE.BoxGeometry(0.16, 0.025, 1.45),
dashMaterial
);
dash.position.set(
a.x + dx * t,
0.115,
a.z + dz * t
);
dash.rotation.y = angle;
scene.add(dash);
}
}
EDGES.forEach(([a, b]) => createRoad(a, b));
function createBuilding(x, z, width, depth, height, wallColor, roofColor, windows = true) {
const group = new THREE.Group();
group.position.set(x, 0, z);
const body = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
new THREE.MeshStandardMaterial({
color: wallColor,
roughness: 0.92,
flatShading: true
})
);
body.position.y = height / 2;
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const roof = new THREE.Mesh(
new THREE.ConeGeometry(1, 1.15, 4),
new THREE.MeshStandardMaterial({
color: roofColor,
roughness: 0.95,
flatShading: true
})
);
roof.position.y = height + 0.56;
roof.rotation.y = Math.PI / 4;
roof.scale.set(width * 0.76, 1, depth * 0.76);
roof.castShadow = true;
group.add(roof);
if (windows) {
const windowMaterial = new THREE.MeshStandardMaterial({
color: 0xb9e0df,
emissive: 0x153c46,
emissiveIntensity: 0.15,
roughness: 0.3
});
const columns = Math.max(2, Math.floor(width / 2));
for (let i = 0; i < columns; i++) {
const windowMesh = new THREE.Mesh(
new THREE.BoxGeometry(1.0, 0.8, 0.08),
windowMaterial
);
windowMesh.position.set(
-width / 2 + (i + 0.5) * (width / columns),
height * 0.58,
depth / 2 + 0.05
);
group.add(windowMesh);
}
}
scene.add(group);
return group;
}
createBuilding(5, 10, 7, 5, 3.4, 0xf1d9a4, 0xd45d45, true);
const buildingColors = {
dino: [0xd9b58b, 0xa95d45],
ocean: [0x91c8d5, 0x397fa2],
robot: [0xb2acd7, 0x60549e],
games: [0xa8cca1, 0x4e8a63],
theatre: [0xe1a6b4, 0xa64d66],
stars: [0xaebee0, 0x4b619d]
};
for (const stop of Object.values(STOPS)) {
const [offsetX, offsetZ] = stop.building;
const node = NODES[stop.node];
const colors = buildingColors[stop.id];
createBuilding(
node.x + offsetX,
node.z + offsetZ,
stop.id === "games" ? 8 : 6.8,
stop.id === "games" ? 6 : 5.5,
stop.id === "stars" ? 4.2 : 3.4,
colors[0],
colors[1],
true
);
}
function createMarker(stop) {
const node = NODES[stop.node];
const group = new THREE.Group();
group.position.set(node.x + stop.offset[0], 0, node.z + stop.offset[1]);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(1.25, 0.19, 5, 12),
markerMaterial.clone()
);
ring.material.color.set(stop.color);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.22;
group.add(ring);
const pole = new THREE.Mesh(
new THREE.CylinderGeometry(0.10, 0.14, 2.6, 6),
new THREE.MeshStandardMaterial({ color: 0x264563, roughness: 0.7 })
);
pole.position.y = 1.4;
group.add(pole);
const cap = new THREE.Mesh(
new THREE.OctahedronGeometry(0.72, 0),
new THREE.MeshStandardMaterial({
color: stop.color,
roughness: 0.55,
flatShading: true
})
);
cap.position.y = 3.0;
group.add(cap);
const pick = new THREE.Mesh(
new THREE.SphereGeometry(2.1, 8, 6),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false
})
);
pick.position.y = 1.6;
pick.userData.stopId = stop.id;
group.add(pick);
markerMeshes.push(pick);
group.userData.ring = ring;
group.userData.cap = cap;
markerGroups[stop.id] = group;
scene.add(group);
const label = document.createElement("button");
label.className = "map-label";
label.type = "button";
label.innerHTML = `<span class="label-dot" style="background:#${stop.color.toString(16).padStart(6, "0")}"></span>${stop.icon} ${stop.name}`;
label.addEventListener("click", () => handleMapStop(stop.id));
$("labels").appendChild(label);
labels.push({
element: label,
position: new THREE.Vector3(group.position.x, 4.1, group.position.z)
});
}
Object.values(STOPS).forEach(createMarker);
const schoolLabel = document.createElement("div");
schoolLabel.className = "map-label school-label";
schoolLabel.innerHTML = `<span class="label-dot" style="background:#183153"></span>🏫 Oakwood School`;
$("labels").appendChild(schoolLabel);
labels.push({
element: schoolLabel,
position: new THREE.Vector3(5, 5, 10)
});
function distanceToSegment(px, pz, a, b) {
const dx = b.x - a.x;
const dz = b.z - a.z;
const lengthSquared = dx * dx + dz * dz;
const t = clamp(((px - a.x) * dx + (pz - a.z) * dz) / lengthSquared, 0, 1);
const x = a.x + t * dx;
const z = a.z + t * dz;
return Math.hypot(px - x, pz - z);
}
const decorativeRandom = mulberry32(734221);
const treeTrunkMaterial = new THREE.MeshStandardMaterial({ color: 0x78563b, roughness: 1 });
const treeLeafMaterials = [
new THREE.MeshStandardMaterial({ color: 0x3f8a62, roughness: 1, flatShading: true }),
new THREE.MeshStandardMaterial({ color: 0x64a76d, roughness: 1, flatShading: true }),
new THREE.MeshStandardMaterial({ color: 0x2f765a, roughness: 1, flatShading: true })
];
for (let i = 0; i < 85; i++) {
const x = (decorativeRandom() - 0.5) * 76;
const z = (decorativeRandom() - 0.5) * 60;
if (Object.values(NODES).some((node) => Math.hypot(x - node.x, z - node.z) < 6)) continue;
if (EDGES.some(([a, b]) => distanceToSegment(x, z, NODES[a], NODES[b]) < 3.8)) continue;
if (Math.hypot(x - 7, z + 5) < 7) continue;
const scale = 0.75 + decorativeRandom() * 0.65;
const tree = new THREE.Group();
tree.position.set(x, 0, z);
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.16, 0.24, 1.7, 5),
treeTrunkMaterial
);
trunk.position.y = 0.85;
trunk.castShadow = true;
tree.add(trunk);
const crown = new THREE.Mesh(
new THREE.ConeGeometry(1.25, 3.1, 5),
treeLeafMaterials[Math.floor(decorativeRandom() * treeLeafMaterials.length)]
);
crown.position.y = 2.65;
crown.castShadow = true;
tree.add(crown);
tree.scale.setScalar(scale);
scene.add(tree);
}
for (let i = 0; i < 6; i++) {
const cloud = new THREE.Group();
cloud.position.set(-35 + i * 14, 15 + (i % 2) * 3, -30 + (i % 3) * 12);
const material = new THREE.MeshStandardMaterial({
color: 0xfffbef,
roughness: 1,
flatShading: true
});
for (let p = 0; p < 3; p++) {
const puff = new THREE.Mesh(
new THREE.DodecahedronGeometry(1.5 + p * 0.15, 0),
material
);
puff.position.set((p - 1) * 1.6, p === 1 ? 0.5 : 0, 0);
puff.scale.y = 0.65;
cloud.add(puff);
}
cloud.userData.speed = 0.12 + i * 0.025;
cloudGroups.push(cloud);
scene.add(cloud);
}
const sunDisc = new THREE.Mesh(
new THREE.IcosahedronGeometry(4.2, 1),
new THREE.MeshBasicMaterial({ color: 0xffe09a })
);
sunDisc.position.set(-34, 28, -30);
scene.add(sunDisc);
function createBus() {
const bus = new THREE.Group();
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0xf5b63e,
roughness: 0.7,
flatShading: true
});
const trimMaterial = new THREE.MeshStandardMaterial({
color: 0xfff4cf,
roughness: 0.8
});
const windowMaterial = new THREE.MeshStandardMaterial({
color: 0x88c9d6,
roughness: 0.25,
metalness: 0.05
});
const tireMaterial = new THREE.MeshStandardMaterial({
color: 0x29323a,
roughness: 0.9
});
const body = new THREE.Mesh(
new THREE.BoxGeometry(1.55, 1.25, 3.25),
bodyMaterial
);
body.position.y = 1.05;
body.castShadow = true;
bus.add(body);
const roof = new THREE.Mesh(
new THREE.BoxGeometry(1.62, 0.22, 3.2),
trimMaterial
);
roof.position.y = 1.77;
roof.castShadow = true;
bus.add(roof);
for (let side = -1; side <= 1; side += 2) {
for (let i = 0; i < 4; i++) {
const windowMesh = new THREE.Mesh(
new THREE.BoxGeometry(0.06, 0.56, 0.54),
windowMaterial
);
windowMesh.position.set(side * 0.79, 1.35, -1.08 + i * 0.68);
bus.add(windowMesh);
}
}
const frontWindow = new THREE.Mesh(
new THREE.BoxGeometry(1.25, 0.58, 0.07),
windowMaterial
);
frontWindow.position.set(0, 1.35, 1.64);
bus.add(frontWindow);
const bumper = new THREE.Mesh(
new THREE.BoxGeometry(1.65, 0.18, 0.18),
tireMaterial
);
bumper.position.set(0, 0.55, 1.68);
bus.add(bumper);
const wheels = [];
for (const x of [-0.82, 0.82]) {
for (const z of [-1.03, 1.03]) {
const wheel = new THREE.Mesh(
new THREE.CylinderGeometry(0.43, 0.43, 0.26, 8),
tireMaterial
);
wheel.rotation.z = Math.PI / 2;
wheel.position.set(x, 0.52, z);
wheel.castShadow = true;
bus.add(wheel);
wheels.push(wheel);
}
}
bus.userData.wheels = wheels;
bus.position.set(NODES.school.x, 0, NODES.school.z);
scene.add(bus);
return bus;
}
const bus = createBus();
// -------------------------------------------------------------------------
// Camera controls implemented directly, without addons
// -------------------------------------------------------------------------
const cameraRig = {
target: new THREE.Vector3(0, 0, 5),
azimuth: 0.48,
polar: 0.88,
radius: 58
};
function updateCamera() {
const sinPolar = Math.sin(cameraRig.polar);
camera.position.set(
cameraRig.target.x + sinPolar * Math.sin(cameraRig.azimuth) * cameraRig.radius,
cameraRig.target.y + Math.cos(cameraRig.polar) * cameraRig.radius,
cameraRig.target.z + sinPolar * Math.cos(cameraRig.azimuth) * cameraRig.radius
);
camera.lookAt(cameraRig.target);
}
function resetCamera() {
cameraRig.target.set(0, 0, 5);
cameraRig.azimuth = 0.48;
cameraRig.polar = 0.88;
cameraRig.radius = 58;
}
function focusStop(stopId) {
const stop = STOPS[stopId];
const node = NODES[stop.node];
cameraRig.target.set(node.x, 0, node.z);
cameraRig.radius = 25;
}
function focusRoute() {
cameraRig.target.set(0, 0, 4);
cameraRig.radius = 58;
cameraRig.azimuth = 0.48;
cameraRig.polar = 0.88;
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const drag = {
active: false,
button: 0,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0,
moved: false
};
function pickMarker(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;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(markerMeshes, false);
return hits.length ? hits[0].object.userData.stopId : null;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
drag.active = true;
drag.button = event.button;
drag.startX = event.clientX;
drag.startY = event.clientY;
drag.lastX = event.clientX;
drag.lastY = event.clientY;
drag.moved = false;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!drag.active) {
renderer.domElement.style.cursor = pickMarker(event) ? "pointer" : "grab";
return;
}
const dx = event.clientX - drag.lastX;
const dy = event.clientY - drag.lastY;
if (Math.hypot(event.clientX - drag.startX, event.clientY - drag.startY) > 5) {
drag.moved = true;
}
if (drag.button === 2) {
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0);
right.y = 0;
right.normalize();
const forward = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 2);
forward.y = 0;
forward.normalize();
cameraRig.target.addScaledVector(right, -dx * 0.035);
cameraRig.target.addScaledVector(forward, -dy * 0.035);
} else {
cameraRig.azimuth -= dx * 0.006;
cameraRig.polar = clamp(cameraRig.polar + dy * 0.005, 0.35, 1.35);
}
drag.lastX = event.clientX;
drag.lastY = event.clientY;
renderer.domElement.style.cursor = "grabbing";
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (!drag.moved && drag.button === 0) {
const stopId = pickMarker(event);
if (stopId) handleMapStop(stopId);
}
drag.active = false;
renderer.domElement.style.cursor = "grab";
});
renderer.domElement.addEventListener("pointercancel", () => {
drag.active = false;
});
renderer.domElement.addEventListener("wheel", (event) => {
event.preventDefault();
cameraRig.radius = clamp(cameraRig.radius * Math.exp(event.deltaY * 0.001), 16, 86);
}, { passive: false });
renderer.domElement.addEventListener("contextmenu", (event) => event.preventDefault());
// -------------------------------------------------------------------------
// Route UI and map interaction
// -------------------------------------------------------------------------
function toast(message) {
const element = $("toast");
element.textContent = message;
element.classList.add("show");
clearTimeout(toast.timer);
toast.timer = setTimeout(() => element.classList.remove("show"), 2400);
}
function handleMapStop(stopId) {
if (state.phase !== "planning") {
focusStop(stopId);
return;
}
const existing = state.route.find((item) => item.id === stopId);
if (existing) {
focusStop(stopId);
return;
}
if (state.route.length >= 3) {
toast("Remove a route stop before adding another one.");
return;
}
const stop = STOPS[stopId];
state.route.push({
id: stopId,
buffer: 20,
fallback: stop.fallbacks[0]
});
updateForecast();
toast(`${stop.name} added to the route.`);
}
function updateMarkerSelection() {
const selected = new Set(state.route.map((item) => item.id));
for (const stop of Object.values(STOPS)) {
const group = markerGroups[stop.id];
const isSelected = selected.has(stop.id);
group.userData.ring.material.color.set(isSelected ? 0xf47b48 : stop.color);
group.userData.cap.material.color.set(isSelected ? 0xf47b48 : stop.color);
group.scale.setScalar(isSelected ? 1.08 : 1);
}
for (const label of labels) {
const id = Object.keys(markerGroups).find((key) => {
const stop = STOPS[key];
const node = NODES[stop.node];
return Math.abs(label.position.x - (node.x + stop.offset[0])) < 0.1 &&
Math.abs(label.position.z - (node.z + stop.offset[1])) < 0.1;
});
if (id) label.element.classList.toggle("selected", selected.has(id));
}
}
function clearRouteGeometry() {
while (routeGroup.children.length) {
const child = routeGroup.children[0];
routeGroup.remove(child);
child.geometry?.dispose();
}
}
function createRouteSegment(aId, bId) {
const a = NODES[aId];
const b = NODES[bId];
const start = new THREE.Vector3(a.x, 0.28, a.z);
const end = new THREE.Vector3(b.x, 0.28, b.z);
const direction = end.clone().sub(start);
const length = direction.length();
const midpoint = start.clone().add(end).multiplyScalar(0.5);
const material = new THREE.MeshBasicMaterial({
color: 0xf47b48,
transparent: true,
opacity: 0.9
});
const segment = new THREE.Mesh(
new THREE.CylinderGeometry(0.095, 0.095, length, 6),
material
);
segment.position.copy(midpoint);
segment.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.clone().normalize()
);
routeGroup.add(segment);
const dot = new THREE.Mesh(
new THREE.SphereGeometry(0.23, 8, 6),
material
);
dot.position.copy(start);
routeGroup.add(dot);
}
function updateRouteGeometry() {
clearRouteGeometry();
let previous = "school";
for (const item of state.route) {
const stop = STOPS[item.id];
const path = shortestPath(previous, stop.node);
for (let i = 1; i < path.length; i++) {
createRouteSegment(path[i - 1], path[i]);
}
previous = stop.node;
}
}
function renderRouteList() {
const list = $("routeList");
list.innerHTML = "";
state.route.forEach((item, index) => {
const stop = STOPS[item.id];
const forecast = state.forecast.stops[index];
const card = document.createElement("div");
card.className = "route-card";
card.dataset.id = item.id;
const fallbackOptions = stop.fallbacks.map((fallback) =>
`<option value="${fallback}" ${fallback === item.fallback ? "selected" : ""}>${fallback}</option>`
).join("");
card.innerHTML = `
<div class="route-top">
<div class="route-number">${index + 1}</div>
<div class="route-title-wrap">
<span class="route-name">${stop.icon} ${stop.name}</span>
<span class="route-site">${stop.site} · Slot ${formatTime(stop.schedule)}</span>
</div>
<div class="route-controls">
<button class="icon-button" data-action="up" title="Move earlier" ${index === 0 ? "disabled" : ""}>↑</button>
<button class="icon-button" data-action="down" title="Move later" ${index === state.route.length - 1 ? "disabled" : ""}>↓</button>
<button class="icon-button" data-action="remove" title="Remove stop">×</button>
</div>
</div>
<div class="route-forecast">
<span>ETA <strong>${formatTime(forecast.arrival)}</strong></span>
<span>+${state.forecast.legs[index].delay}m travel</span>
<span class="forecast-status ${forecast.primary ? "" : "fallback"}">
${forecast.primary ? "PRIMARY" : "FALLBACK"}
</span>
</div>
<div class="route-options">
<label>
<span class="mini-label">Fallback activity</span>
<select data-field="fallback" aria-label="Fallback activity for ${stop.name}">
${fallbackOptions}
</select>
</label>
<label>
<span class="mini-label">Buffer</span>
<select data-field="buffer" aria-label="Delay buffer for ${stop.name}">
<option value="10" ${item.buffer === 10 ? "selected" : ""}>10 min</option>
<option value="20" ${item.buffer === 20 ? "selected" : ""}>20 min</option>
<option value="30" ${item.buffer === 30 ? "selected" : ""}>30 min</option>
<option value="45" ${item.buffer === 45 ? "selected" : ""}>45 min</option>
</select>
</label>
</div>
`;
list.appendChild(card);
});
}
function updateSummary() {
const forecast = state.forecast;
$("forecastTravel").textContent = `${Math.round(forecast.totalTravel)}m`;
$("forecastDelay").textContent = `${forecast.totalDelay}m`;
$("forecastPoints").textContent = forecast.points + forecast.bonus;
$("forecastEnergy").textContent = forecast.energy;
$("routeCount").textContent = `${state.route.length}/3`;
const badge = $("forecastBadge");
if (forecast.primaryCount === 3) {
badge.textContent = "ALL PRIMARY";
badge.style.background = "rgba(44,157,145,.12)";
badge.style.color = "#247b72";
} else if (forecast.fallbackCount >= 2) {
badge.textContent = "RISKY";
badge.style.background = "rgba(217,93,93,.12)";
badge.style.color = "#ad4444";
} else {
badge.textContent = "MIXED PLAN";
badge.style.background = "rgba(244,123,72,.13)";
badge.style.color = "#b35530";
}
$("runTrip").disabled = state.route.length !== 3 || state.phase === "running";
$("runLabel").textContent =
state.phase === "running" ? "Trip in progress" :
state.phase === "finished" ? "Trip complete" :
"Run the trip";
}
function updateForecast() {
state.forecast = calculateForecast(state.route);
renderRouteList();
updateSummary();
updateMarkerSelection();
updateRouteGeometry();
updateProgress();
updateTopStatus();
}
function updateTopStatus() {
$("topSeed").textContent = state.seed;
const dot = $("statusDot");
dot.className = "status-dot";
if (state.phase === "running") {
dot.classList.add("running");
$("statusText").textContent = "On trip";
$("radioBadge").textContent = "Live";
} else if (state.phase === "finished") {
dot.classList.add("complete");
$("statusText").textContent = "Complete";
$("radioBadge").textContent = "Report ready";
} else {
$("statusText").textContent = "Planning";
$("radioBadge").textContent = "Standby";
}
}
function updateProgress() {
const container = $("progressSteps");
container.innerHTML = "";
let activeIndex = -1;
if (state.phase === "running" && state.simulation) {
activeIndex = state.simulation.legIndex ?? -1;
} else if (state.phase === "finished") {
activeIndex = state.route.length;
}
state.route.forEach((item, index) => {
const stop = STOPS[item.id];
const step = document.createElement("div");
step.className = "progress-step";
if (state.phase === "finished" || index < activeIndex) step.classList.add("done");
if (index === activeIndex && state.phase === "running") step.classList.add("current");
step.innerHTML = `
<span class="progress-dot">${state.phase === "finished" || index < activeIndex ? "✓" : index + 1}</span>
<span>${stop.icon} ${stop.name}</span>
`;
container.appendChild(step);
});
}
$("routeList").addEventListener("click", (event) => {
const button = event.target.closest("button[data-action]");
if (!button || state.phase !== "planning") return;
const card = button.closest(".route-card");
const id = card.dataset.id;
const index = state.route.findIndex((item) => item.id === id);
if (button.dataset.action === "remove") {
state.route.splice(index, 1);
} else if (button.dataset.action === "up" && index > 0) {
[state.route[index - 1], state.route[index]] = [state.route[index], state.route[index - 1]];
} else if (button.dataset.action === "down" && index < state.route.length - 1) {
[state.route[index + 1], state.route[index]] = [state.route[index], state.route[index + 1]];
}
updateForecast();
});
$("routeList").addEventListener("change", (event) => {
if (state.phase !== "planning") return;
const select = event.target.closest("select[data-field]");
if (!select) return;
const card = select.closest(".route-card");
const item = state.route.find((entry) => entry.id === card.dataset.id);
if (!item) return;
if (select.dataset.field === "fallback") item.fallback = select.value;
if (select.dataset.field === "buffer") item.buffer = Number(select.value);
updateForecast();
});
$("autoArrange").addEventListener("click", () => {
if (state.phase !== "planning") return;
if (state.route.length !== 3) {
toast("Choose exactly three stops before finding the best order.");
return;
}
let bestRoute = state.route;
let bestForecast = calculateForecast(state.route);
for (const order of permutations(state.route)) {
const forecast = calculateForecast(order);
if (
forecast.score > bestForecast.score ||
(forecast.score === bestForecast.score && forecast.totalDelay < bestForecast.totalDelay)
) {
bestRoute = order;
bestForecast = forecast;
}
}
state.route = bestRoute;
updateForecast();
toast(`Best order found: ${bestForecast.primaryCount} primary activities.`);
});
$("seedInput").addEventListener("change", () => {
const value = $("seedInput").value.trim() || "OWL-4821";
state.seed = value;
$("seedInput").value = value;
if (state.phase === "planning") updateForecast();
toast(`Seed set to ${value}. The forecast has been refreshed.`);
});
$("rollSeed").addEventListener("click", () => {
if (state.phase !== "planning") return;
const value = Math.floor(1000 + Math.random() * 8999);
state.seed = `OWL-${value}`;
$("seedInput").value = state.seed;
updateForecast();
toast(`New seed: ${state.seed}.`);
});
$("departureInput").addEventListener("change", () => {
if (state.phase !== "planning") return;
state.departure = parseTime($("departureInput").value);
updateForecast();
});
$("resetCamera").addEventListener("click", resetCamera);
$("focusRoute").addEventListener("click", focusRoute);
$("helpButton").addEventListener("click", () => $("helpDialog").showModal());
$("closeHelp").addEventListener("click", () => $("helpDialog").close());
// -------------------------------------------------------------------------
// Dispatch log and simulation
// -------------------------------------------------------------------------
function addLog(time, message, tone = "info") {
const item = document.createElement("div");
item.className = `log-item ${tone}`;
item.innerHTML = `<span class="log-time">${formatTime(time)}</span>${message}`;
$("logList").prepend(item);
while ($("logList").children.length > 18) {
$("logList").lastElementChild.remove();
}
}
function resetLog() {
$("logList").innerHTML = "";
addLog(state.departure, "Bus checked in at Oakwood School.", "good");
addLog(state.departure, "Choose three stops, then run the trip.", "info");
}
function setBusAtNode(nodeId) {
const node = NODES[nodeId];
bus.position.set(node.x, 0, node.z);
}
function placeBusOnEdge(aId, bId, t) {
const a = NODES[aId];
const b = NODES[bId];
bus.position.set(
THREE.MathUtils.lerp(a.x, b.x, t),
0,
THREE.MathUtils.lerp(a.z, b.z, t)
);
bus.rotation.y = Math.atan2(b.x - a.x, b.z - a.z);
}
function beginEdge() {
const sim = state.simulation;
const from = sim.path[sim.edgeIndex];
const to = sim.path[sim.edgeIndex + 1];
const edge = edgeBetween(from, to);
sim.phase = "edge";
sim.from = from;
sim.to = to;
sim.edgeStartTime = sim.currentTime;
sim.edgeEndTime = sim.currentTime + edge.weight;
sim.realStart = performance.now();
sim.realDuration = clamp(edge.weight / 8, 0.65, 1.45);
}
function beginRouteLeg(index) {
const sim = state.simulation;
const leg = state.forecast.legs[index];
sim.legIndex = index;
sim.path = [...leg.path];
sim.edgeIndex = 0;
sim.returning = false;
beginEdge();
updateProgress();
}
function beginDelay() {
const sim = state.simulation;
const leg = state.forecast.legs[sim.legIndex];
sim.phase = "delay";
sim.delayStartTime = sim.currentTime;
sim.delayEndTime = sim.currentTime + leg.delay;
sim.realStart = performance.now();
sim.realDuration = 1.15;
state.energy = clamp(state.energy - leg.delay * 1.3, 0, 100);
addLog(
sim.currentTime,
`${leg.delayType}: the bus loses ${leg.delay} minutes.`,
leg.delay > 15 ? "bad" : "warn"
);
}
function beginActivity() {
const sim = state.simulation;
const leg = state.forecast.legs[sim.legIndex];
const stop = STOPS[state.route[sim.legIndex].id];
state.activeStop = stop.id;
sim.phase = "activity";
sim.realStart = performance.now();
sim.realDuration = clamp(leg.duration / 12, 1.8, 3.2);
sim.activityStartTime = sim.currentTime;
sim.activityEndTime = sim.currentTime + leg.duration;
if (leg.primary) {
state.energy = clamp(state.energy + 5, 0, 100);
addLog(
sim.currentTime,
`${stop.name} begins${leg.late ? ` with ${leg.late} minutes of lateness absorbed by the buffer.` : " right on schedule."}.`,
"good"
);
} else {
state.energy = clamp(state.energy - 2, 0, 100);
addLog(
sim.currentTime,
`${stop.name} is unavailable: ${leg.reason}. ${state.route[sim.legIndex].fallback} takes over.`,
"warn"
);
}
}
function beginWait() {
const sim = state.simulation;
const leg = state.forecast.legs[sim.legIndex];
const stop = STOPS[state.route[sim.legIndex].id];
state.energy = clamp(state.energy - leg.wait * 0.15, 0, 100);
sim.phase = "wait";
sim.waitStartTime = sim.currentTime;
sim.waitEndTime = sim.currentTime + leg.wait;
sim.realStart = performance.now();
sim.realDuration = 0.8;
addLog(
sim.currentTime,
`The bus is ${leg.wait} minutes early for ${stop.name}. The class waits for the activity slot.`,
"info"
);
}
function beginReturn() {
const sim = state.simulation;
const lastNode = STOPS[state.route[state.route.length - 1].id].node;
sim.path = shortestPath(lastNode, "school");
sim.edgeIndex = 0;
sim.returning = true;
beginEdge();
}
function startTrip() {
if (state.phase !== "planning" || state.route.length !== 3) return;
state.forecast = calculateForecast(state.route);
state.phase = "running";
state.energy = 100;
state.points = 0;
state.bonus = 0;
state.activeStop = null;
$("logList").innerHTML = "";
state.simulation = {
phase: "travel",
legIndex: 0,
edgeIndex: 0,
path: [],
currentTime: state.departure,
returning: false,
realStart: performance.now(),
realDuration: 0
};
addLog(state.departure, "The coach leaves Oakwood School with 27 students aboard.", "good");
beginRouteLeg(0);
updateSummary();
updateTopStatus();
updateProgress();
}
function updateSimulation(now) {
if (state.phase !== "running" || !state.simulation) return;
const sim = state.simulation;
const t = clamp((now - sim.realStart) / (sim.realDuration * 1000), 0, 1);
if (sim.phase === "edge") {
placeBusOnEdge(sim.from, sim.to, t);
sim.currentTime = THREE.MathUtils.lerp(sim.edgeStartTime, sim.edgeEndTime, t);
if (t >= 1) {
sim.currentTime = sim.edgeEndTime;
sim.edgeIndex++;
if (sim.edgeIndex < sim.path.length - 1) {
beginEdge();
} else if (sim.returning) {
finishTrip();
} else {
beginDelay();
}
}
} else if (sim.phase === "delay") {
sim.currentTime = THREE.MathUtils.lerp(sim.delayStartTime, sim.delayEndTime, t);
if (t >= 1) {
sim.currentTime = sim.delayEndTime;
const leg = state.forecast.legs[sim.legIndex];
addLog(sim.currentTime, `The coach arrives at ${STOPS[state.route[sim.legIndex].id].name}.`, "info");
if (leg.wait > 0) beginWait();
else beginActivity();
}
} else if (sim.phase === "wait") {
sim.currentTime = THREE.MathUtils.lerp(sim.waitStartTime, sim.waitEndTime, t);
if (t >= 1) {
sim.currentTime = sim.waitEndTime;
beginActivity();
}
} else if (sim.phase === "activity") {
sim.currentTime = THREE.MathUtils.lerp(sim.activityStartTime, sim.activityEndTime, t);
if (t >= 1) {
sim.currentTime = sim.activityEndTime;
const leg = state.forecast.legs[sim.legIndex];
const stop = STOPS[state.route[sim.legIndex].id];
state.points += leg.points;
state.bonus += leg.bonus;
addLog(
sim.currentTime,
`${stop.name} ${leg.primary ? "finishes" : "and its fallback finish"} with +${leg.points + leg.bonus} learning points.`,
"good"
);
state.activeStop = null;
sim.legIndex++;
if (sim.legIndex < state.route.length) {
beginRouteLeg(sim.legIndex);
} else {
beginReturn();
}
}
}
}
function finishTrip() {
state.phase = "finished";
state.activeStop = null;
const score = Math.max(
0,
Math.round(state.points + state.bonus - state.forecast.totalDelay * 0.4)
);
let grade = "C";
let title = "A learning day, with a few bumps.";
let subtitle = "The class made it home safe, and the fallbacks did their job.";
if (score >= 86 && state.energy >= 70) {
grade = "S";
title = "A beautifully organized adventure!";
subtitle = "Every primary activity landed and the schedule stayed under control.";
} else if (score >= 72 && state.energy >= 45) {
grade = "A";
title = "A brilliant day out!";
subtitle = "The class got the most out of every stop.";
} else if (score >= 55) {
grade = "B";
title = "A solid school trip!";
subtitle = "A smart route and dependable fallbacks kept things moving.";
} else if (state.energy <= 0) {
grade = "D";
title = "The timetable got the better of us.";
subtitle = "Try larger buffers, earlier departure times, or a different route order.";
}
addLog(state.simulation.currentTime, "The coach returns safely to Oakwood School.", "good");
$("resultGrade").textContent = grade;
$("resultTitle").textContent = title;
$("resultSubtitle").textContent = subtitle;
$("resultPoints").textContent = score;
$("resultPrimary").textContent = `${state.forecast.primaryCount}/3`;
$("resultDelay").textContent = `${state.forecast.totalDelay}m`;
$("resultEnergy").textContent = `${Math.round(state.energy)}%`;
const breakdown = $("resultBreakdown");
breakdown.innerHTML = "";
state.forecast.stops.forEach((result) => {
const row = document.createElement("div");
row.className = "breakdown-row";
row.innerHTML = `
<div>
<strong>${result.stop.icon} ${result.stop.name}</strong>
<small>${result.primary ? "Primary activity completed" : `Fallback: ${result.item.fallback}`}</small>
</div>
<div class="result-points">+${result.points + result.bonus} pts</div>
`;
breakdown.appendChild(row);
});
$("resultModal").hidden = false;
updateSummary();
updateTopStatus();
updateProgress();
}
function replan() {
$("resultModal").hidden = true;
state.phase = "planning";
state.simulation = null;
state.energy = 100;
state.points = 0;
state.bonus = 0;
state.activeStop = null;
setBusAtNode("school");
bus.rotation.y = 0;
resetLog();
updateForecast();
}
$("runTrip").addEventListener("click", startTrip);
$("replanButton").addEventListener("click", replan);
$("newSeedButton").addEventListener("click", () => {
const value = Math.floor(1000 + Math.random() * 8999);
state.seed = `OWL-${value}`;
$("seedInput").value = state.seed;
replan();
toast(`New seed: ${state.seed}. Plan again for different delays.`);
});
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
function updateLabels() {
for (const label of labels) {
const projected = label.position.clone().project(camera);
const visible = projected.z > -1 && projected.z < 1 &&
projected.x > -1.1 && projected.x < 1.1 &&
projected.y > -1.1 && projected.y < 1.1;
label.element.style.display = visible ? "block" : "none";
if (visible) {
const x = (projected.x * 0.5 + 0.5) * innerWidth;
const y = (-projected.y * 0.5 + 0.5) * innerHeight;
label.element.style.left = `${x}px`;
label.element.style.top = `${y}px`;
}
}
}
function updateDispatch() {
const currentTime = state.phase === "running" && state.simulation
? state.simulation.currentTime
: state.phase === "finished" && state.simulation
? state.simulation.currentTime
: state.departure;
$("simClock").textContent = formatTime(currentTime);
$("energyValue").textContent = `${Math.round(state.energy)}%`;
$("energyFill").style.width = `${state.energy}%`;
$("energyFill").style.background =
state.energy > 55 ? "#65d2b6" : state.energy > 25 ? "#f4bd55" : "#e56b67";
}
function animate(now) {
requestAnimationFrame(animate);
updateSimulation(now);
updateCamera();
updateLabels();
updateDispatch();
const time = now * 0.001;
for (const cloud of cloudGroups) {
cloud.position.x += cloud.userData.speed * 0.008;
if (cloud.position.x > 48) cloud.position.x = -48;
}
for (const stop of Object.values(STOPS)) {
const group = markerGroups[stop.id];
const isActive = state.activeStop === stop.id;
const pulse = isActive ? 1 + Math.sin(time * 4) * 0.1 : 1;
group.userData.ring.scale.setScalar(pulse);
group.userData.cap.rotation.y = time * 0.45;
}
const moving = state.phase === "running" &&
(state.simulation?.phase === "edge" || state.simulation?.phase === "delay");
bus.position.y = moving ? Math.sin(time * 12) * 0.025 : 0;
if (moving) {
for (const wheel of bus.userData.wheels) {
wheel.rotation.x -= 0.14;
}
}
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
updateCamera();
updateForecast();
resetLog();
requestAnimationFrame(animate);
</script>
</body>
</html>
```