Prompt specification
Build or customize the Three.js 3D scene "Changing Daylight Alters the Route" 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: Changing Daylight Alters the Route
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/changing-daylight-alters-the-route-x3540
Scene Description Prompt:
Make a voxel Three.js scene in a self-contained HTML file using cdnjs: changing daylight alters the route. Create a bounded rover strategy puzzle with a declared daylight schedule. Compare feasible routes when one charger becomes unavailable, keeping movement and energy accounting deterministic.
Working Three.js Starter (changing-daylight-alters-the-route-x3540):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Lumen Transit — Voxel Rover Strategy</title>
<style>
:root {
--bg: #07111f;
--panel: rgba(10, 22, 35, 0.91);
--panel-border: rgba(151, 203, 224, 0.19);
--text: #eaf6ff;
--muted: #91aabd;
--green: #72efb3;
--amber: #ffbd59;
--cyan: #64d8ff;
--phase: #ffd166;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#stage {
position: fixed;
inset: 0;
overflow: hidden;
background: var(--bg);
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#stage canvas:active {
cursor: grabbing;
}
#world-labels {
position: absolute;
inset: 0;
overflow: hidden;
pointer-events: none;
}
.world-label {
position: absolute;
left: 0;
top: 0;
min-width: 30px;
padding: 4px 7px;
border: 1px solid rgba(255, 255, 255, 0.25);
border-radius: 5px;
background: rgba(5, 13, 23, 0.84);
color: white;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-align: center;
box-shadow: 0 5px 18px rgba(0, 0, 0, 0.32);
transform: translate(-50%, -50%);
white-space: nowrap;
}
.world-label.charger-a {
border-color: rgba(114, 239, 179, 0.8);
color: var(--green);
}
.world-label.charger-b {
border-color: rgba(255, 189, 89, 0.8);
color: var(--amber);
}
.world-label.goal {
border-color: rgba(100, 216, 255, 0.8);
color: var(--cyan);
}
.panel {
position: fixed;
z-index: 10;
border: 1px solid var(--panel-border);
border-radius: 12px;
background:
linear-gradient(145deg, rgba(255, 255, 255, 0.035), transparent 45%),
var(--panel);
box-shadow:
0 18px 50px rgba(0, 0, 0, 0.35),
inset 0 1px 0 rgba(255, 255, 255, 0.04);
backdrop-filter: blur(15px);
}
header {
top: 16px;
left: 18px;
right: 18px;
display: flex;
align-items: center;
justify-content: space-between;
min-height: 62px;
padding: 12px 16px;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
}
.brand-mark {
display: grid;
width: 38px;
height: 38px;
place-items: center;
border: 1px solid color-mix(in srgb, var(--phase) 65%, transparent);
border-radius: 8px;
background: color-mix(in srgb, var(--phase) 12%, transparent);
color: var(--phase);
font-weight: 900;
box-shadow: 0 0 24px color-mix(in srgb, var(--phase) 15%, transparent);
}
.eyebrow {
margin-bottom: 3px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1,
h2,
p {
margin: 0;
}
h1 {
font-size: 19px;
letter-spacing: 0.08em;
}
h2 {
font-size: 13px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.header-right {
display: flex;
align-items: center;
gap: 10px;
}
.phase-badge {
padding: 7px 11px;
border: 1px solid color-mix(in srgb, var(--phase) 55%, transparent);
border-radius: 999px;
background: color-mix(in srgb, var(--phase) 10%, transparent);
color: var(--phase);
font-size: 10px;
font-weight: 900;
letter-spacing: 0.15em;
}
#controls {
top: 92px;
left: 18px;
width: 322px;
max-height: calc(100vh - 255px);
padding: 15px;
overflow: auto;
scrollbar-width: thin;
scrollbar-color: #365064 transparent;
}
#comparison {
top: 92px;
right: 18px;
width: 388px;
padding: 15px;
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 10px;
}
.section-heading small {
color: var(--muted);
font-size: 10px;
letter-spacing: 0.08em;
}
.clock-row {
display: flex;
align-items: baseline;
justify-content: space-between;
margin: 2px 0 8px;
}
#time-output {
font-variant-numeric: tabular-nums;
font-size: 31px;
font-weight: 800;
letter-spacing: -0.04em;
}
#phase-description {
max-width: 185px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
text-align: right;
}
input[type="range"] {
width: 100%;
margin: 4px 0 10px;
accent-color: var(--phase);
cursor: pointer;
}
.schedule {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 5px;
margin-bottom: 9px;
}
.schedule button {
padding: 7px 2px;
border: 1px solid rgba(150, 190, 210, 0.15);
border-radius: 6px;
background: rgba(255, 255, 255, 0.035);
color: var(--muted);
cursor: pointer;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.07em;
}
.schedule button.active {
border-color: color-mix(in srgb, var(--phase) 60%, transparent);
background: color-mix(in srgb, var(--phase) 11%, transparent);
color: var(--phase);
}
.cost-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-bottom: 13px;
}
.cost-card {
padding: 9px;
border: 1px solid rgba(150, 190, 210, 0.12);
border-radius: 7px;
background: rgba(255, 255, 255, 0.025);
}
.cost-card span {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.cost-card strong {
font-size: 12px;
}
.divider {
height: 1px;
margin: 12px 0;
background: var(--panel-border);
}
.segmented {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin-top: 8px;
}
.segmented button,
.action-button {
min-height: 36px;
border: 1px solid rgba(150, 190, 210, 0.17);
border-radius: 7px;
background: rgba(255, 255, 255, 0.035);
color: var(--muted);
cursor: pointer;
font-size: 10px;
font-weight: 800;
transition: 140ms ease;
}
.segmented button:hover,
.action-button:hover {
border-color: rgba(180, 225, 245, 0.42);
color: white;
transform: translateY(-1px);
}
.segmented button.active {
border-color: color-mix(in srgb, var(--phase) 65%, transparent);
background: color-mix(in srgb, var(--phase) 11%, transparent);
color: var(--phase);
}
details {
margin-top: 12px;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
summary {
cursor: pointer;
color: #c8dce8;
font-weight: 700;
}
details ul {
margin: 8px 0 0;
padding-left: 17px;
}
.route-table {
width: 100%;
border-collapse: collapse;
font-size: 11px;
}
.route-table th {
padding: 0 5px 8px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-align: left;
text-transform: uppercase;
}
.route-table th:last-child,
.route-table td:last-child {
text-align: right;
}
.route-table td {
padding: 10px 5px;
border-top: 1px solid rgba(150, 190, 210, 0.11);
vertical-align: middle;
}
.route-table tbody tr {
cursor: pointer;
transition: background 120ms ease;
}
.route-table tbody tr:hover {
background: rgba(255, 255, 255, 0.025);
}
.route-table tbody tr.active {
background: rgba(114, 239, 179, 0.075);
}
.scenario-name {
display: flex;
align-items: center;
gap: 7px;
font-weight: 750;
}
.route-dot {
width: 8px;
height: 8px;
flex: 0 0 auto;
border-radius: 50%;
box-shadow: 0 0 10px currentColor;
}
.route-dot.none {
color: var(--green);
background: var(--green);
}
.route-dot.A {
color: var(--amber);
background: var(--amber);
}
.route-dot.B {
color: var(--cyan);
background: var(--cyan);
}
.good {
color: var(--green);
font-weight: 800;
}
.bad {
color: #ff7f8d;
font-weight: 800;
}
.muted {
color: var(--muted);
}
#comparison-note {
min-height: 48px;
margin-top: 11px;
padding: 10px;
border-left: 2px solid var(--phase);
background: rgba(255, 255, 255, 0.025);
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
#trace-panel {
left: 50%;
bottom: 18px;
width: 480px;
padding: 12px 14px;
transform: translateX(-50%);
}
.trace-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 9px;
}
#trace-name {
font-size: 11px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#trace-position {
color: var(--muted);
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.trace-grid {
display: grid;
grid-template-columns: 1.45fr 1fr 1fr 1fr;
gap: 9px;
align-items: end;
}
.trace-metric span {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.trace-metric strong {
font-size: 13px;
font-variant-numeric: tabular-nums;
}
.battery-track {
height: 7px;
margin-top: 6px;
overflow: hidden;
border-radius: 999px;
background: rgba(255, 255, 255, 0.09);
}
#battery-fill {
width: 75%;
height: 100%;
border-radius: inherit;
background: var(--green);
box-shadow: 0 0 12px rgba(114, 239, 179, 0.5);
transition: width 140ms linear, background 140ms linear;
}
.trace-actions {
display: flex;
gap: 6px;
margin-top: 10px;
}
.trace-actions button {
min-width: 38px;
min-height: 30px;
border: 1px solid rgba(150, 190, 210, 0.17);
border-radius: 6px;
background: rgba(255, 255, 255, 0.035);
color: #c7dbe8;
cursor: pointer;
font-size: 10px;
font-weight: 800;
}
.trace-actions #play-button {
min-width: 78px;
color: var(--phase);
}
.camera-tools {
position: fixed;
right: 18px;
bottom: 18px;
z-index: 11;
display: flex;
gap: 6px;
}
.camera-tools button {
width: 36px;
height: 36px;
border: 1px solid var(--panel-border);
border-radius: 8px;
background: var(--panel);
color: var(--text);
cursor: pointer;
font-size: 17px;
backdrop-filter: blur(12px);
}
.camera-help {
position: fixed;
left: 18px;
bottom: 18px;
z-index: 9;
color: rgba(211, 231, 241, 0.65);
font-size: 10px;
letter-spacing: 0.04em;
pointer-events: none;
}
@media (max-width: 1050px) {
#controls {
width: 288px;
}
#comparison {
width: 342px;
}
#trace-panel {
width: 430px;
}
.camera-help {
display: none;
}
}
@media (max-width: 760px) {
header {
right: 10px;
left: 10px;
top: 10px;
}
h1 {
font-size: 15px;
}
.brand-mark {
display: none;
}
#controls {
top: 80px;
left: 10px;
width: calc(50% - 15px);
max-height: 47vh;
padding: 11px;
}
#comparison {
top: 80px;
right: 10px;
width: calc(50% - 15px);
padding: 11px;
}
.route-table th:nth-child(3),
.route-table td:nth-child(3) {
display: none;
}
#trace-panel {
bottom: 10px;
width: calc(100% - 70px);
}
.trace-grid {
grid-template-columns: 1.3fr 1fr 1fr;
}
.trace-grid .trace-metric:nth-child(4) {
display: none;
}
.camera-tools {
right: 10px;
bottom: 10px;
flex-direction: column;
}
}
</style>
</head>
<body>
<div id="stage">
<div id="world-labels">
<div id="label-a" class="world-label charger-a">CHARGER A</div>
<div id="label-b" class="world-label charger-b">CHARGER B</div>
<div id="label-start" class="world-label">START</div>
<div id="label-goal" class="world-label goal">GOAL</div>
</div>
</div>
<header class="panel">
<div class="brand">
<div class="brand-mark">L</div>
<div>
<div class="eyebrow">Bounded rover strategy / grid 10 × 8</div>
<h1>LUMEN TRANSIT</h1>
</div>
</div>
<div class="header-right">
<span class="muted" style="font-size:10px;letter-spacing:.08em">
DETERMINISTIC ENERGY ROUTING
</span>
<span id="phase-badge" class="phase-badge">DAY</span>
</div>
</header>
<section id="controls" class="panel">
<div class="section-heading">
<h2>Declared daylight schedule</h2>
<small>UTC</small>
</div>
<div class="clock-row">
<div id="time-output">12:00</div>
<div id="phase-description"></div>
</div>
<input
id="time-slider"
type="range"
min="0"
max="23.75"
step="0.25"
value="12"
aria-label="Time of day"
>
<div class="schedule" id="schedule-buttons">
<button type="button" data-time="1">NIGHT</button>
<button type="button" data-time="6">DAWN</button>
<button type="button" data-time="12">DAY</button>
<button type="button" data-time="17">DUSK</button>
</div>
<div class="cost-grid">
<div class="cost-card">
<span>Sun tile / step</span>
<strong id="solar-cost" style="color:#ffd166">2 energy</strong>
</div>
<div class="cost-card">
<span>Shade tile / step</span>
<strong id="shade-cost" style="color:#a99cff">5 energy</strong>
</div>
</div>
<div class="divider"></div>
<div class="section-heading">
<h2>Charger availability</h2>
<small>One outage at a time</small>
</div>
<div class="segmented" id="scenario-buttons">
<button type="button" data-scenario="none" class="active">All online</button>
<button type="button" data-scenario="A">A offline</button>
<button type="button" data-scenario="B">B offline</button>
</div>
<details>
<summary>Fixed rules and tie-breaks</summary>
<ul>
<li>Battery capacity: 40. Initial charge: 30.</li>
<li>Orthogonal movement only; each cell has a fixed integer cost.</li>
<li>Normal terrain costs 4 energy per step.</li>
<li>Entering an available charger immediately fills the battery to 40.</li>
<li>Objective: minimum drive energy, then fewer steps, then lexicographically smallest coordinate path.</li>
<li>No randomness is used in routing, charging, or energy accounting.</li>
</ul>
</details>
</section>
<section id="comparison" class="panel">
<div class="section-heading">
<h2>Feasible route comparison</h2>
<small>Current daylight</small>
</div>
<table class="route-table">
<thead>
<tr>
<th>Scenario</th>
<th>Status</th>
<th>Charger plan</th>
<th>Drive</th>
<th>Min.</th>
</tr>
</thead>
<tbody id="comparison-body"></tbody>
</table>
<div id="comparison-note"></div>
</section>
<section id="trace-panel" class="panel">
<div class="trace-top">
<div id="trace-name">ACTIVE TRACE</div>
<div id="trace-position">x1 · y6</div>
</div>
<div class="trace-grid">
<div class="trace-metric">
<span>Battery</span>
<strong id="battery-text">30 / 40</strong>
<div class="battery-track"><div id="battery-fill"></div></div>
</div>
<div class="trace-metric">
<span>Drive energy</span>
<strong id="drive-text">0</strong>
</div>
<div class="trace-metric">
<span>Charger draw</span>
<strong id="charged-text">0</strong>
</div>
<div class="trace-metric">
<span>Action</span>
<strong id="action-text">0 / 0</strong>
</div>
</div>
<div class="trace-actions">
<button id="reset-button" type="button" title="Reset trace">↺</button>
<button id="step-button" type="button" title="Advance one deterministic action">STEP</button>
<button id="play-button" type="button">PLAY</button>
<button id="pause-button" type="button" title="Pause animation">Ⅱ</button>
</div>
</section>
<div class="camera-help">Drag: orbit · Shift-drag: pan · Wheel: zoom · Double-click: reset camera</div>
<div class="camera-tools">
<button id="zoom-in" type="button" title="Zoom in">+</button>
<button id="zoom-out" type="button" title="Zoom out">−</button>
<button id="camera-reset" type="button" title="Reset camera">⌂</button>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Deterministic puzzle definition
// -------------------------------------------------------------------------
const WIDTH = 10;
const HEIGHT = 8;
const CAPACITY = 40;
const INITIAL_BATTERY = 30;
const NORMAL_COST = 4;
const MAP = [
"##..ss..##",
"#..ssss.G#",
"#.C......#",
"#..xx..sx#",
"#..xx..sx#",
"#.....C..#",
"#........#",
"##......##"
];
const START = { x: 1, y: 6 };
const GOAL = { x: 8, y: 1 };
const CHARGERS = {
A: { x: 2, y: 2 },
B: { x: 7, y: 5 }
};
const PHASES = {
night: {
name: "NIGHT",
start: 18,
end: 6,
solar: 6,
shade: 2,
description: "Solar cells are weak. Shade tiles provide the cheap corridor.",
background: 0x07111f,
light: 0x83adff,
intensity: 0.85,
ambient: 0.72,
accent: "#78aaff"
},
dawn: {
name: "DAWN",
start: 6,
end: 8,
solar: 5,
shade: 3,
description: "Low light. Neither surface is at full efficiency.",
background: 0x172338,
light: 0xffc58c,
intensity: 1.35,
ambient: 0.9,
accent: "#ffbc7a"
},
day: {
name: "DAY",
start: 8,
end: 16,
solar: 2,
shade: 5,
description: "Strong sunlight makes the northern solar causeway efficient.",
background: 0x12283a,
light: 0xfff0c4,
intensity: 2.05,
ambient: 1.22,
accent: "#ffd166"
},
dusk: {
name: "DUSK",
start: 16,
end: 18,
solar: 4,
shade: 3,
description: "The light is fading. Shade begins to outperform sun tiles.",
background: 0x241d32,
light: 0xffa46b,
intensity: 1.45,
ambient: 0.92,
accent: "#ff9b68"
}
};
const SCENARIOS = {
none: {
key: "none",
label: "All online",
unavailable: new Set(),
color: 0x72efb3,
css: "#72efb3"
},
A: {
key: "A",
label: "A offline",
unavailable: new Set(["A"]),
color: 0xffbd59,
css: "#ffbd59"
},
B: {
key: "B",
label: "B offline",
unavailable: new Set(["B"]),
color: 0x64d8ff,
css: "#64d8ff"
}
};
const DIRECTIONS = [
{ x: 1, y: 0 },
{ x: 0, y: -1 },
{ x: -1, y: 0 },
{ x: 0, y: 1 }
];
const cellId = (x, y) => y * WIDTH + x;
const idToCell = id => ({ x: id % WIDTH, y: Math.floor(id / WIDTH) });
const terrainAt = (x, y) => MAP[y][x];
function phaseAt(hour) {
if (hour < 6 || hour >= 18) return PHASES.night;
if (hour < 8) return PHASES.dawn;
if (hour < 16) return PHASES.day;
return PHASES.dusk;
}
function terrainCost(character, phase) {
if (character === "s") return phase.solar;
if (character === "x") return phase.shade;
return NORMAL_COST;
}
function terrainLabel(character) {
if (character === "s") return "SUN";
if (character === "x") return "SHADE";
if (character === "C") return "CHARGER";
if (character === "G") return "GOAL";
if (character === "#") return "WALL";
return "BASALT";
}
// -------------------------------------------------------------------------
// Deterministic Dijkstra route solver
// -------------------------------------------------------------------------
function comparePaths(a, b) {
const length = Math.min(a.length, b.length);
for (let i = 0; i < length; i++) {
if (a[i] !== b[i]) return a[i] - b[i];
}
return a.length - b.length;
}
function compareStates(a, b) {
return (
a.g - b.g ||
a.steps - b.steps ||
comparePaths(a.path, b.path)
);
}
class MinHeap {
constructor() {
this.items = [];
}
get size() {
return this.items.length;
}
push(value) {
const item = { value, priority: compareStates(value, value) };
this.items.push(item);
let index = this.items.length - 1;
while (index > 0) {
const parent = Math.floor((index - 1) / 2);
if (compareStates(this.items[index].value, this.items[parent].value) >= 0) {
break;
}
[this.items[index], this.items[parent]] = [
this.items[parent],
this.items[index]
];
index = parent;
}
}
pop() {
if (!this.items.length) return null;
const root = this.items[0];
const last = this.items.pop();
if (this.items.length) {
this.items[0] = last;
let index = 0;
while (true) {
const left = index * 2 + 1;
const right = left + 1;
let smallest = index;
if (
left < this.items.length &&
compareStates(this.items[left].value, this.items[smallest].value) < 0
) {
smallest = left;
}
if (
right < this.items.length &&
compareStates(this.items[right].value, this.items[smallest].value) < 0
) {
smallest = right;
}
if (smallest === index) break;
[this.items[index], this.items[smallest]] = [
this.items[smallest],
this.items[index]
];
index = smallest;
}
}
return root.value;
}
}
function solveScenario(scenarioKey, phase) {
const scenario = SCENARIOS[scenarioKey];
const startId = cellId(START.x, START.y);
const startState = {
x: START.x,
y: START.y,
b: INITIAL_BATTERY,
g: 0,
steps: 0,
path: [startId],
chain: []
};
const open = new MinHeap();
const best = new Map();
const stateKey = state => `${state.x},${state.y},${state.b}`;
best.set(stateKey(startState), startState);
open.push(startState);
while (open.size) {
const current = open.pop();
const currentKey = stateKey(current);
if (best.get(currentKey) !== current) continue;
if (current.x === GOAL.x && current.y === GOAL.y) {
return materializeResult(current, scenario);
}
for (const direction of DIRECTIONS) {
const nx = current.x + direction.x;
const ny = current.y + direction.y;
if (nx < 0 || nx >= WIDTH || ny < 0 || ny >= HEIGHT) continue;
const character = terrainAt(nx, ny);
if (character === "#") continue;
const cost = terrainCost(character, phase);
if (current.b < cost) continue;
const fromId = cellId(current.x, current.y);
const toId = cellId(nx, ny);
let nextBattery = current.b - cost;
const chain = current.chain.concat({
type: "move",
from: fromId,
to: toId,
cost,
terrain: terrainLabel(character)
});
const chargerName = Object.keys(CHARGERS).find(
name => CHARGERS[name].x === nx && CHARGERS[name].y === ny
);
if (
chargerName &&
!scenario.unavailable.has(chargerName) &&
nextBattery < CAPACITY
) {
const amount = CAPACITY - nextBattery;
chain.push({
type: "charge",
at: toId,
charger: chargerName,
amount
});
nextBattery = CAPACITY;
}
const candidate = {
x: nx,
y: ny,
b: nextBattery,
g: current.g + cost,
steps: current.steps + 1,
path: current.path.concat(toId),
chain
};
const candidateKey = stateKey(candidate);
const previous = best.get(candidateKey);
if (!previous || compareStates(candidate, previous) < 0) {
best.set(candidateKey, candidate);
open.push(candidate);
}
}
}
return {
feasible: false,
scenario: scenarioKey,
path: [],
actions: [],
drive: 0,
charged: 0,
minimum: INITIAL_BATTERY,
finalBattery: INITIAL_BATTERY,
chargeStops: [],
plan: "NO ROUTE"
};
}
function materializeResult(state, scenario) {
let battery = INITIAL_BATTERY;
let minimum = INITIAL_BATTERY;
let charged = 0;
const chargeStops = [];
for (const action of state.chain) {
if (action.type === "move") {
battery -= action.cost;
minimum = Math.min(minimum, battery);
} else {
battery = Math.min(CAPACITY, battery + action.amount);
charged += action.amount;
chargeStops.push(action.charger);
}
}
return {
feasible: true,
scenario: scenario.key,
path: state.path.slice(),
actions: state.chain.slice(),
drive: state.g,
charged,
minimum,
finalBattery: battery,
chargeStops,
plan: chargeStops.length
? `${chargeStops.join(" → ")} → G`
: "DIRECT → G"
};
}
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const stage = document.getElementById("stage");
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(PHASES.day.background, 17, 34);
const camera = new THREE.PerspectiveCamera(
43,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
stage.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xbfe9ff, 0x081018, 1.2);
scene.add(hemisphere);
const sunLight = new THREE.DirectionalLight(0xfff0c4, 2);
sunLight.position.set(6, 11, 5);
sunLight.castShadow = true;
sunLight.shadow.mapSize.set(1024, 1024);
sunLight.shadow.camera.left = -9;
sunLight.shadow.camera.right = 9;
sunLight.shadow.camera.top = 9;
sunLight.shadow.camera.bottom = -9;
sunLight.shadow.camera.near = 1;
sunLight.shadow.camera.far = 30;
sunLight.shadow.bias = -0.0004;
scene.add(sunLight);
const world = new THREE.Group();
scene.add(world);
const tileMaterials = {
normal: new THREE.MeshStandardMaterial({
color: 0x36515a,
roughness: 0.9,
metalness: 0.06,
flatShading: true
}),
solar: new THREE.MeshStandardMaterial({
color: 0xb98225,
emissive: 0xff9f22,
emissiveIntensity: 1.1,
roughness: 0.65,
metalness: 0.12,
flatShading: true
}),
shade: new THREE.MeshStandardMaterial({
color: 0x504684,
emissive: 0x7662d7,
emissiveIntensity: 0.9,
roughness: 0.75,
metalness: 0.08,
flatShading: true
}),
wall: new THREE.MeshStandardMaterial({
color: 0x111b27,
roughness: 1,
flatShading: true
}),
charger: new THREE.MeshStandardMaterial({
color: 0x48636a,
roughness: 0.72,
metalness: 0.22,
flatShading: true
}),
start: new THREE.MeshStandardMaterial({
color: 0x55dba1,
emissive: 0x1e8d62,
emissiveIntensity: 0.55,
roughness: 0.7,
flatShading: true
}),
goal: new THREE.MeshStandardMaterial({
color: 0x3ca9c7,
emissive: 0x1683a3,
emissiveIntensity: 0.8,
roughness: 0.6,
flatShading: true
})
};
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x0a141d,
transparent: true,
opacity: 0.58
});
const base = new THREE.Mesh(
new THREE.BoxGeometry(WIDTH + 0.8, 0.3, HEIGHT + 0.8),
new THREE.MeshStandardMaterial({
color: 0x0c1822,
roughness: 0.95,
metalness: 0.1
})
);
base.position.y = -0.52;
base.receiveShadow = true;
world.add(base);
const chargerLights = {
A: new THREE.PointLight(0x72efb3, 1.2, 4.2),
B: new THREE.PointLight(0xffbd59, 1.2, 4.2)
};
function worldPosition(x, y, height = 0) {
return new THREE.Vector3(
x - (WIDTH - 1) / 2,
height,
y - (HEIGHT - 1) / 2
);
}
function addVoxel(parent, geometry, material, x, y, z, 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;
}
function buildGrid() {
for (let y = 0; y < HEIGHT; y++) {
for (let x = 0; x < WIDTH; x++) {
const character = MAP[y][x];
const position = worldPosition(x, y);
let height = 0.35;
let material = tileMaterials.normal;
if (character === "#") {
height = 0.86;
material = tileMaterials.wall;
} else if (character === "s") {
height = 0.42;
material = tileMaterials.solar;
} else if (character === "x") {
height = 0.48;
material = tileMaterials.shade;
} else if (character === "C") {
height = 0.36;
material = tileMaterials.charger;
} else if (character === "G") {
height = 0.39;
material = tileMaterials.goal;
}
const body = new THREE.Mesh(
new THREE.BoxGeometry(0.94, height, 0.94),
material
);
body.position.set(position.x, -0.35 + height / 2, position.z);
body.castShadow = true;
body.receiveShadow = true;
world.add(body);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(body.geometry),
edgeMaterial
);
edges.position.copy(body.position);
world.add(edges);
if (character === "s") {
const panel = addVoxel(
world,
new THREE.BoxGeometry(0.62, 0.075, 0.62),
tileMaterials.solar,
position.x,
-0.35 + height + 0.035,
position.z
);
panel.castShadow = false;
}
if (character === "x") {
const inset = addVoxel(
world,
new THREE.BoxGeometry(0.62, 0.07, 0.62),
tileMaterials.shade,
position.x,
-0.35 + height + 0.032,
position.z
);
inset.castShadow = false;
}
if (character === "C") {
const chargerName =
x === CHARGERS.A.x && y === CHARGERS.A.y ? "A" : "B";
addVoxel(
world,
new THREE.BoxGeometry(0.46, 0.08, 0.46),
chargerName === "A" ? tileMaterials.start : tileMaterials.goal,
position.x,
0.035,
position.z
);
addVoxel(
world,
new THREE.BoxGeometry(0.18, 0.43, 0.18),
tileMaterials.charger,
position.x,
0.25,
position.z - 0.28
);
const beacon = addVoxel(
world,
new THREE.BoxGeometry(0.22, 0.12, 0.22),
chargerName === "A" ? tileMaterials.start : tileMaterials.goal,
position.x,
0.51,
position.z - 0.28
);
beacon.castShadow = false;
chargerLights[chargerName].position.set(position.x, 0.65, position.z);
world.add(chargerLights[chargerName]);
}
if (x === START.x && y === START.y) {
addVoxel(
world,
new THREE.BoxGeometry(0.16, 0.28, 0.16),
tileMaterials.start,
position.x,
0.08,
position.z - 0.28
);
addVoxel(
world,
new THREE.BoxGeometry(0.34, 0.12, 0.12),
tileMaterials.start,
position.x + 0.09,
0.26,
position.z - 0.28
);
}
if (character === "G") {
addVoxel(
world,
new THREE.BoxGeometry(0.13, 0.64, 0.13),
tileMaterials.goal,
position.x - 0.29,
0.28,
position.z
);
addVoxel(
world,
new THREE.BoxGeometry(0.13, 0.64, 0.13),
tileMaterials.goal,
position.x + 0.29,
0.28,
position.z
);
addVoxel(
world,
new THREE.BoxGeometry(0.72, 0.12, 0.16),
tileMaterials.goal,
position.x,
0.64,
position.z
);
}
}
}
const railMaterial = new THREE.MeshStandardMaterial({
color: 0x27404b,
roughness: 0.75,
metalness: 0.25
});
const longRailX = new THREE.BoxGeometry(WIDTH + 0.55, 0.16, 0.13);
const longRailZ = new THREE.BoxGeometry(0.13, 0.16, HEIGHT + 0.55);
for (const z of [-HEIGHT / 2 - 0.25, HEIGHT / 2 + 0.25]) {
addVoxel(world, longRailX, railMaterial, 0, -0.3, z, false);
}
for (const x of [-WIDTH / 2 - 0.25, WIDTH / 2 + 0.25]) {
addVoxel(world, longRailZ, railMaterial, x, -0.3, 0, false);
}
}
buildGrid();
// Rover: a compact voxel assembly.
const rover = new THREE.Group();
const roverBodyMaterial = new THREE.MeshStandardMaterial({
color: 0xd9e8ec,
roughness: 0.6,
metalness: 0.18,
flatShading: true
});
const roverDarkMaterial = new THREE.MeshStandardMaterial({
color: 0x15232c,
roughness: 0.82,
metalness: 0.15,
flatShading: true
});
const roverAccentMaterial = new THREE.MeshStandardMaterial({
color: 0x64d8ff,
emissive: 0x186d86,
emissiveIntensity: 0.9,
roughness: 0.45,
flatShading: true
});
addVoxel(rover, new THREE.BoxGeometry(0.42, 0.2, 0.5), roverBodyMaterial, 0, 0.13, 0);
addVoxel(rover, new THREE.BoxGeometry(0.28, 0.17, 0.27), roverAccentMaterial, 0, 0.31, 0.02);
for (const x of [-0.25, 0.25]) {
for (const z of [-0.18, 0.18]) {
addVoxel(
rover,
new THREE.BoxGeometry(0.13, 0.18, 0.18),
roverDarkMaterial,
x,
0.01,
z
);
}
}
addVoxel(
rover,
new THREE.BoxGeometry(0.34, 0.055, 0.32),
roverAccentMaterial,
0,
0.43,
0.02
);
world.add(rover);
// -------------------------------------------------------------------------
// Route visualization
// -------------------------------------------------------------------------
const routeRoot = new THREE.Group();
world.add(routeRoot);
const routeVisuals = new Map();
function clearRouteVisual(visual) {
const geometries = new Set();
const materials = new Set();
visual.group.traverse(object => {
if (object.geometry) geometries.add(object.geometry);
if (object.material) {
if (Array.isArray(object.material)) {
object.material.forEach(material => materials.add(material));
} else {
materials.add(object.material);
}
}
});
geometries.forEach(geometry => geometry.dispose());
materials.forEach(material => material.dispose());
routeRoot.remove(visual.group);
}
function renderRoutes(results) {
for (const visual of routeVisuals.values()) clearRouteVisual(visual);
routeVisuals.clear();
for (const scenarioKey of Object.keys(SCENARIOS)) {
const scenario = SCENARIOS[scenarioKey];
const result = results[scenarioKey];
const group = new THREE.Group();
routeRoot.add(group);
if (!result.feasible) {
routeVisuals.set(scenarioKey, { group, materials: [] });
continue;
}
const markerMaterial = new THREE.MeshBasicMaterial({
color: scenario.color,
transparent: true,
opacity: 0.88,
depthTest: false,
depthWrite: false
});
const connectorMaterial = new THREE.MeshBasicMaterial({
color: scenario.color,
transparent: true,
opacity: 0.72,
depthTest: false,
depthWrite: false
});
const markerGeometry = new THREE.BoxGeometry(0.21, 0.07, 0.21);
const connectorGeometry = new THREE.BoxGeometry(1, 0.055, 0.1);
for (const id of result.path) {
const cell = idToCell(id);
const position = worldPosition(cell.x, cell.y, 0.25);
const marker = new THREE.Mesh(markerGeometry, markerMaterial);
marker.position.copy(position);
marker.renderOrder = 5;
group.add(marker);
}
for (let i = 1; i < result.path.length; i++) {
const a = idToCell(result.path[i - 1]);
const b = idToCell(result.path[i]);
const pa = worldPosition(a.x, a.y, 0.25);
const pb = worldPosition(b.x, b.y, 0.25);
const midpoint = pa.clone().add(pb).multiplyScalar(0.5);
const connector = new THREE.Mesh(connectorGeometry, connectorMaterial);
connector.position.copy(midpoint);
connector.scale.x = Math.max(0.1, Math.abs(pb.x - pa.x) + 0.11);
connector.scale.z = Math.max(0.1, Math.abs(pb.z - pa.z) + 0.11);
connector.renderOrder = 4;
group.add(connector);
}
const points = result.path.map(id => {
const cell = idToCell(id);
return worldPosition(cell.x, cell.y, 0.33);
});
const lineMaterial = new THREE.LineBasicMaterial({
color: scenario.color,
transparent: true,
opacity: 0.95,
depthTest: false,
depthWrite: false
});
const line = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(points),
lineMaterial
);
line.renderOrder = 6;
group.add(line);
routeVisuals.set(scenarioKey, {
group,
materials: [markerMaterial, connectorMaterial, lineMaterial]
});
}
updateRouteVisualState();
}
function updateRouteVisualState() {
for (const [key, visual] of routeVisuals) {
const active = key === activeScenario;
visual.materials.forEach((material, index) => {
material.opacity = active
? [0.9, 0.78, 1][index] ?? 0.8
: [0.22, 0.17, 0.28][index] ?? 0.2;
});
}
}
// -------------------------------------------------------------------------
// UI and route state
// -------------------------------------------------------------------------
const timeSlider = document.getElementById("time-slider");
const timeOutput = document.getElementById("time-output");
const phaseBadge = document.getElementById("phase-badge");
const phaseDescription = document.getElementById("phase-description");
const solarCostElement = document.getElementById("solar-cost");
const shadeCostElement = document.getElementById("shade-cost");
const comparisonBody = document.getElementById("comparison-body");
const comparisonNote = document.getElementById("comparison-note");
let activeScenario = "none";
let currentPhase = phaseAt(Number(timeSlider.value));
let results = {};
let refreshQueued = false;
function formatTime(hour) {
const totalMinutes = Math.round(hour * 60);
const hours = Math.floor(totalMinutes / 60) % 24;
const minutes = totalMinutes % 60;
return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}`;
}
function updatePhaseUI() {
const hour = Number(timeSlider.value);
currentPhase = phaseAt(hour);
timeOutput.textContent = formatTime(hour);
phaseBadge.textContent = currentPhase.name;
phaseDescription.textContent = currentPhase.description;
solarCostElement.textContent = `${currentPhase.solar} energy`;
shadeCostElement.textContent = `${currentPhase.shade} energy`;
document.documentElement.style.setProperty("--phase", currentPhase.accent);
document.querySelectorAll("#schedule-buttons button").forEach(button => {
button.classList.toggle(
"active",
phaseAt(Number(button.dataset.time)).name === currentPhase.name
);
});
renderer.setClearColor(currentPhase.background);
scene.fog.color.set(currentPhase.background);
sunLight.color.set(currentPhase.light);
sunLight.intensity = currentPhase.intensity;
hemisphere.intensity = currentPhase.ambient;
const solarEfficiency = 1 - currentPhase.solar / 7;
const shadeEfficiency = 1 - currentPhase.shade / 7;
tileMaterials.solar.emissiveIntensity = 0.3 + solarEfficiency * 1.9;
tileMaterials.shade.emissiveIntensity = 0.25 + shadeEfficiency * 1.5;
const chargerIntensity = currentPhase.name === "NIGHT" ? 2.1 : 1.25;
chargerLights.A.intensity = chargerIntensity;
chargerLights.B.intensity = chargerIntensity;
}
function renderComparison() {
comparisonBody.innerHTML = "";
for (const key of Object.keys(SCENARIOS)) {
const scenario = SCENARIOS[key];
const result = results[key];
const row = document.createElement("tr");
row.dataset.scenario = key;
row.classList.toggle("active", key === activeScenario);
row.innerHTML = `
<td>
<div class="scenario-name">
<span class="route-dot ${key}"></span>
${scenario.label}
</div>
</td>
<td class="${result.feasible ? "good" : "bad"}">
${result.feasible ? "FEASIBLE" : "NO ROUTE"}
</td>
<td class="muted">${result.feasible ? result.plan : "—"}</td>
<td>${result.feasible ? `${result.drive} E` : "—"}</td>
<td>${result.feasible ? `${result.minimum} E` : "—"}</td>
`;
row.addEventListener("click", () => {
setActiveScenario(key);
});
comparisonBody.appendChild(row);
}
const selected = results[activeScenario];
const baseline = results.none;
if (activeScenario === "none") {
comparisonNote.textContent =
`${currentPhase.name}: ${baseline.plan} is the minimum-energy plan with ` +
`both chargers online. The route may change when daylight changes.`;
} else if (selected.feasible && baseline.feasible) {
const difference = selected.drive - baseline.drive;
comparisonNote.textContent =
`${SCENARIOS[activeScenario].label}: ${selected.plan}, costing ` +
`${selected.drive} drive energy. ` +
(difference === 0
? "It ties the all-online route."
: `${difference > 0 ? "+" : ""}${difference} energy versus the all-online route.`);
} else {
comparisonNote.textContent =
`${SCENARIOS[activeScenario].label}: no feasible route under ${currentPhase.name}.`;
}
}
function setActiveScenario(key) {
activeScenario = key;
document.querySelectorAll("#scenario-buttons button").forEach(button => {
button.classList.toggle("active", button.dataset.scenario === key);
});
renderComparison();
updateRouteVisualState();
resetTrace();
}
function refreshRoutes() {
updatePhaseUI();
results = {};
for (const key of Object.keys(SCENARIOS)) {
results[key] = solveScenario(key, currentPhase);
}
renderComparison();
renderRoutes(results);
resetTrace();
}
timeSlider.addEventListener("input", () => {
updatePhaseUI();
if (!refreshQueued) {
refreshQueued = true;
requestAnimationFrame(() => {
refreshQueued = false;
refreshRoutes();
});
}
});
document.querySelectorAll("#schedule-buttons button").forEach(button => {
button.addEventListener("click", () => {
timeSlider.value = button.dataset.time;
refreshRoutes();
});
});
document.querySelectorAll("#scenario-buttons button").forEach(button => {
button.addEventListener("click", () => {
setActiveScenario(button.dataset.scenario);
});
});
// -------------------------------------------------------------------------
// Deterministic route trace and cosmetic playback
// -------------------------------------------------------------------------
const traceName = document.getElementById("trace-name");
const tracePosition = document.getElementById("trace-position");
const batteryText = document.getElementById("battery-text");
const batteryFill = document.getElementById("battery-fill");
const driveText = document.getElementById("drive-text");
const chargedText = document.getElementById("charged-text");
const actionText = document.getElementById("action-text");
const playButton = document.getElementById("play-button");
const ROVER_Y = 0.39;
let trace = null;
let playing = false;
function resetTrace() {
playing = false;
const result = results[activeScenario];
trace = {
actions: result?.feasible ? result.actions : [],
path: result?.feasible ? result.path : [],
index: 0,
pathIndex: 0,
battery: INITIAL_BATTERY,
drive: 0,
charged: 0,
minimum: INITIAL_BATTERY,
move: null,
chargeElapsed: 0
};
const startPosition = worldPosition(START.x, START.y, ROVER_Y);
rover.position.copy(startPosition);
rover.rotation.y = 0;
updateTraceHUD();
}
function updateTraceHUD() {
if (!trace) return;
const result = results[activeScenario];
const currentCell = trace.path.length
? idToCell(trace.path[trace.pathIndex])
: START;
traceName.textContent =
`${SCENARIOS[activeScenario].label} / ${currentPhase.name}`;
tracePosition.textContent =
`x${currentCell.x} · y${currentCell.y} · ` +
`${terrainLabel(terrainAt(currentCell.x, currentCell.y))}`;
batteryText.textContent = `${trace.battery} / ${CAPACITY}`;
batteryFill.style.width = `${(trace.battery / CAPACITY) * 100}%`;
batteryFill.style.background =
trace.battery <= 8 ? "#ffbd59" : "#72efb3";
driveText.textContent = `${trace.drive} E`;
chargedText.textContent = `${trace.charged} E`;
actionText.textContent = `${trace.index} / ${trace.actions.length}`;
playButton.textContent = playing ? "PLAYING" : "PLAY";
if (result && !result.feasible) {
traceName.textContent = `${SCENARIOS[activeScenario].label} / NO ROUTE`;
}
}
function applyMove(action) {
trace.battery -= action.cost;
trace.drive += action.cost;
trace.minimum = Math.min(trace.minimum, trace.battery);
trace.pathIndex += 1;
}
function applyCharge(action) {
trace.battery = Math.min(CAPACITY, trace.battery + action.amount);
trace.charged += action.amount;
}
function setRoverDirection(action) {
const from = idToCell(action.from);
const to = idToCell(action.to);
const dx = to.x - from.x;
const dz = to.y - from.y;
rover.rotation.y = Math.atan2(dx, dz);
}
function advanceOne() {
if (!trace || trace.index >= trace.actions.length) return;
const action = trace.actions[trace.index];
if (action.type === "move") {
setRoverDirection(action);
applyMove(action);
const destination = idToCell(action.to);
rover.position.copy(worldPosition(destination.x, destination.y, ROVER_Y));
} else {
applyCharge(action);
}
trace.index += 1;
trace.move = null;
updateTraceHUD();
}
function updateTraceAnimation(delta) {
if (!playing || !trace || trace.index >= trace.actions.length) return;
const action = trace.actions[trace.index];
if (action.type === "charge") {
trace.chargeElapsed += delta;
const pulse = Math.sin((trace.chargeElapsed / 0.38) * Math.PI);
rover.position.y = ROVER_Y + pulse * 0.07;
if (trace.chargeElapsed >= 0.38) {
applyCharge(action);
trace.index += 1;
trace.chargeElapsed = 0;
rover.position.y = ROVER_Y;
updateTraceHUD();
}
} else {
if (!trace.move) {
setRoverDirection(action);
const from = idToCell(action.from);
const to = idToCell(action.to);
trace.move = {
from: worldPosition(from.x, from.y, ROVER_Y),
to: worldPosition(to.x, to.y, ROVER_Y),
elapsed: 0,
duration: 0.48
};
}
trace.move.elapsed += delta;
const raw = Math.min(1, trace.move.elapsed / trace.move.duration);
const eased = raw * raw * (3 - 2 * raw);
rover.position.lerpVectors(trace.move.from, trace.move.to, eased);
rover.position.y = ROVER_Y + Math.sin(raw * Math.PI) * 0.16;
if (raw >= 1) {
applyMove(action);
trace.index += 1;
trace.move = null;
rover.position.y = ROVER_Y;
updateTraceHUD();
}
}
if (trace.index >= trace.actions.length) {
playing = false;
updateTraceHUD();
}
}
document.getElementById("reset-button").addEventListener("click", resetTrace);
document.getElementById("step-button").addEventListener("click", () => {
playing = false;
advanceOne();
});
playButton.addEventListener("click", () => {
if (!trace || trace.index >= trace.actions.length) resetTrace();
playing = !playing;
updateTraceHUD();
});
document.getElementById("pause-button").addEventListener("click", () => {
playing = false;
updateTraceHUD();
});
// -------------------------------------------------------------------------
// Direct camera controls; no examples or addons are imported
// -------------------------------------------------------------------------
const cameraState = {
yaw: -0.66,
pitch: 0.82,
distance: 16.5,
target: new THREE.Vector3(0, 0.05, 0)
};
function resetCamera() {
cameraState.yaw = -0.66;
cameraState.pitch = 0.82;
cameraState.distance = 16.5;
cameraState.target.set(0, 0.05, 0);
}
function updateCamera() {
const horizontal =
cameraState.distance * Math.cos(cameraState.pitch);
camera.position.set(
cameraState.target.x +
horizontal * Math.sin(cameraState.yaw),
cameraState.target.y +
cameraState.distance * Math.sin(cameraState.pitch),
cameraState.target.z +
horizontal * Math.cos(cameraState.yaw)
);
camera.lookAt(cameraState.target);
camera.updateMatrixWorld();
}
let dragging = false;
let dragX = 0;
let dragY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
dragX = event.clientX;
dragY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - dragX;
const dy = event.clientY - dragY;
dragX = event.clientX;
dragY = event.clientY;
if (event.shiftKey) {
const scale = cameraState.distance * 0.0013;
cameraState.target.x -= dx * scale;
cameraState.target.z -= dy * scale;
cameraState.target.x = THREE.MathUtils.clamp(
cameraState.target.x,
-4,
4
);
cameraState.target.z = THREE.MathUtils.clamp(
cameraState.target.z,
-4,
4
);
} else {
cameraState.yaw -= dx * 0.007;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
0.38,
1.35
);
}
});
renderer.domElement.addEventListener("pointerup", event => {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance + event.deltaY * 0.012,
9,
27
);
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
document.getElementById("zoom-in").addEventListener("click", () => {
cameraState.distance = Math.max(9, cameraState.distance - 1.5);
});
document.getElementById("zoom-out").addEventListener("click", () => {
cameraState.distance = Math.min(27, cameraState.distance + 1.5);
});
document.getElementById("camera-reset").addEventListener("click", resetCamera);
// -------------------------------------------------------------------------
// World-space HTML labels
// -------------------------------------------------------------------------
const labels = [
{
element: document.getElementById("label-a"),
position: worldPosition(CHARGERS.A.x, CHARGERS.A.y, 1.0)
},
{
element: document.getElementById("label-b"),
position: worldPosition(CHARGERS.B.x, CHARGERS.B.y, 1.0)
},
{
element: document.getElementById("label-start"),
position: worldPosition(START.x, START.y, 0.9)
},
{
element: document.getElementById("label-goal"),
position: worldPosition(GOAL.x, GOAL.y, 1.15)
}
];
function updateLabels() {
for (const label of labels) {
const projected = label.position.clone().project(camera);
const visible = projected.z >= -1 && projected.z <= 1;
label.element.style.left = `${(projected.x * 0.5 + 0.5) * innerWidth}px`;
label.element.style.top = `${(-projected.y * 0.5 + 0.5) * innerHeight}px`;
label.element.style.opacity = visible ? "1" : "0";
}
}
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
function resize() {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
}
addEventListener("resize", resize);
refreshRoutes();
resetCamera();
let previousTime = performance.now();
function animate(now) {
requestAnimationFrame(animate);
const delta = Math.min(0.05, (now - previousTime) / 1000);
previousTime = now;
updateTraceAnimation(delta);
updateCamera();
updateLabels();
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```