Prompt specification
Build or customize the Three.js 3D scene "Shortest-path edge-cost explorer" 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: Shortest-path edge-cost explorer
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/shortest-path-edge-cost-explorer-x1920
Scene Description Prompt:
Make a low-poly Three.js scene in a self-contained HTML file using cdnjs: shortest-path edge-cost explorer. Allow changing nonnegative costs on a small graph and recompute the route; expose predecessor updates and unreachable destinations, and reject unsupported negative-weight inputs.
Working Three.js Starter (shortest-path-edge-cost-explorer-x1920):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Shortest-Path Edge-Cost Explorer</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: #0b1727;
--panel-2: #101e31;
--line: #203149;
--text: #eaf2ff;
--muted: #8fa3bc;
--teal: #37e0b2;
--gold: #ffd166;
--pink: #ff6f91;
--red: #ff6b78;
--blue: #63a9ff;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
width: 100%;
height: 100%;
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,
select {
font: inherit;
}
button,
select,
input[type="number"] {
color: var(--text);
}
button {
cursor: pointer;
}
.app {
display: grid;
grid-template-columns: 380px minmax(0, 1fr);
grid-template-rows: 72px minmax(0, 1fr);
height: 100vh;
height: 100dvh;
}
header {
grid-column: 1 / -1;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 0 24px;
border-bottom: 1px solid var(--line);
background: rgba(8, 19, 33, 0.96);
z-index: 10;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
width: 39px;
height: 39px;
display: grid;
place-items: center;
flex: 0 0 auto;
border: 1px solid #2b5260;
border-radius: 12px;
background:
linear-gradient(145deg, rgba(55, 224, 178, 0.18), rgba(99, 169, 255, 0.05));
box-shadow: inset 0 0 18px rgba(55, 224, 178, 0.08);
}
.brand-mark svg {
width: 25px;
height: 25px;
}
h1 {
margin: 0;
font-size: 18px;
line-height: 1.2;
letter-spacing: -0.02em;
white-space: nowrap;
}
.subtitle {
margin-top: 4px;
color: var(--muted);
font-size: 12px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.header-meta {
display: flex;
align-items: center;
gap: 10px;
flex: 0 0 auto;
}
.badge {
padding: 7px 10px;
border: 1px solid #29445a;
border-radius: 999px;
color: #b9cbe0;
background: #0e2032;
font-size: 11px;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.badge strong {
color: var(--teal);
font-weight: 700;
}
aside {
grid-column: 1;
grid-row: 2;
min-height: 0;
overflow-y: auto;
padding: 18px;
border-right: 1px solid var(--line);
background: linear-gradient(180deg, #0b1727, #091421);
scrollbar-width: thin;
scrollbar-color: #2a405a transparent;
z-index: 5;
}
section {
padding: 0 0 20px;
margin-bottom: 20px;
border-bottom: 1px solid var(--line);
}
section:last-child {
margin-bottom: 0;
border-bottom: 0;
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}
h2 {
margin: 0;
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.12em;
color: #a9bbd0;
}
.count {
color: var(--muted);
font-size: 11px;
}
.field-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin-bottom: 12px;
}
label.field {
display: block;
color: var(--muted);
font-size: 11px;
}
label.field span {
display: block;
margin-bottom: 6px;
}
select,
input[type="number"] {
width: 100%;
height: 38px;
border: 1px solid #29415c;
border-radius: 8px;
outline: none;
background: #0d1d30;
padding: 0 10px;
transition: border-color 0.15s, box-shadow 0.15s;
}
select:focus,
input[type="number"]:focus {
border-color: var(--blue);
box-shadow: 0 0 0 3px rgba(99, 169, 255, 0.12);
}
input[type="number"].invalid {
border-color: var(--red);
box-shadow: 0 0 0 3px rgba(255, 107, 120, 0.1);
}
.primary {
width: 100%;
height: 43px;
border: 0;
border-radius: 9px;
color: #062018;
background: linear-gradient(135deg, #50e8bd, #2fc7e7);
font-weight: 800;
box-shadow: 0 7px 22px rgba(47, 199, 231, 0.16);
transition: transform 0.15s, filter 0.15s;
}
.primary:hover {
filter: brightness(1.06);
transform: translateY(-1px);
}
.primary:active {
transform: translateY(0);
}
.help {
margin: 9px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.validation {
margin: 0 0 12px;
padding: 10px 11px;
border: 1px solid rgba(255, 107, 120, 0.45);
border-radius: 8px;
color: #ffc2c8;
background: rgba(255, 107, 120, 0.08);
font-size: 12px;
line-height: 1.45;
}
.validation[hidden] {
display: none;
}
.edge-list {
display: grid;
gap: 7px;
}
.edge-row {
display: grid;
grid-template-columns: 1fr 78px 48px;
align-items: center;
gap: 8px;
min-height: 44px;
padding: 7px 8px;
border: 1px solid #1d3047;
border-radius: 8px;
background: rgba(16, 30, 49, 0.72);
}
.edge-name {
min-width: 0;
font-size: 12px;
font-weight: 700;
}
.edge-name small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 10px;
font-weight: 500;
}
.edge-row input[type="number"] {
height: 32px;
padding: 0 7px;
font-size: 12px;
}
.toggle {
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
}
.toggle input {
position: absolute;
opacity: 0;
pointer-events: none;
}
.toggle span {
width: 34px;
height: 20px;
display: block;
border: 1px solid #344860;
border-radius: 999px;
background: #17263a;
transition: 0.18s;
}
.toggle span::after {
content: "";
position: absolute;
width: 14px;
height: 14px;
top: 3px;
left: 3px;
border-radius: 50%;
background: #71849b;
transition: 0.18s;
}
.toggle input:checked + span {
border-color: #287c70;
background: rgba(55, 224, 178, 0.2);
}
.toggle input:checked + span::after {
transform: translateX(14px);
background: var(--teal);
}
.toggle input:focus-visible + span {
box-shadow: 0 0 0 3px rgba(99, 169, 255, 0.15);
}
.predecessor-table {
width: 100%;
border-collapse: collapse;
font-size: 11px;
}
.predecessor-table th {
padding: 0 4px 8px;
color: #71869f;
font-size: 9px;
font-weight: 700;
text-align: left;
text-transform: uppercase;
letter-spacing: 0.09em;
}
.predecessor-table td {
padding: 7px 4px;
border-top: 1px solid #1b2b40;
color: #b9c8d9;
}
.predecessor-table td:first-child {
width: 27px;
color: var(--text);
font-weight: 800;
}
.predecessor-table td:nth-child(2) {
width: 58px;
font-variant-numeric: tabular-nums;
}
.predecessor-table tr.settled td:first-child::before {
content: "";
display: inline-block;
width: 6px;
height: 6px;
margin-right: 7px;
border-radius: 50%;
background: var(--teal);
box-shadow: 0 0 8px rgba(55, 224, 178, 0.7);
}
.settled-order {
display: flex;
flex-wrap: wrap;
gap: 5px;
min-height: 25px;
margin: 10px 0 13px;
}
.settled-chip {
padding: 4px 7px;
border: 1px solid #28584f;
border-radius: 6px;
color: #83ebce;
background: rgba(55, 224, 178, 0.08);
font-size: 10px;
font-weight: 800;
}
.secondary {
height: 34px;
padding: 0 11px;
border: 1px solid #2b435e;
border-radius: 7px;
color: #bcd0e5;
background: #102035;
font-size: 11px;
}
.secondary:hover {
border-color: #466784;
background: #15283f;
}
.algorithm-status {
min-height: 36px;
margin: 11px 0 0;
color: #9db1c8;
font-size: 11px;
line-height: 1.45;
}
#viewport {
grid-column: 2;
grid-row: 2;
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #07111f;
}
#canvasHost,
#labels {
position: absolute;
inset: 0;
}
#canvasHost canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#canvasHost canvas:active {
cursor: grabbing;
}
#labels {
pointer-events: none;
overflow: hidden;
}
.node-label,
.edge-label {
position: absolute;
left: 0;
top: 0;
white-space: nowrap;
will-change: transform;
user-select: none;
}
.node-label {
min-width: 25px;
padding: 4px 7px;
border: 1px solid rgba(160, 187, 214, 0.45);
border-radius: 7px;
color: #eaf4ff;
background: rgba(8, 19, 33, 0.86);
box-shadow: 0 5px 12px rgba(0, 0, 0, 0.24);
text-align: center;
font-size: 11px;
font-weight: 900;
}
.node-label.source {
border-color: var(--teal);
color: #8af4d9;
}
.node-label.destination {
border-color: var(--pink);
color: #ffafc1;
}
.node-label.route {
border-color: var(--gold);
color: #ffe3a0;
}
.edge-label {
padding: 2px 5px;
border: 1px solid rgba(89, 109, 137, 0.35);
border-radius: 5px;
color: #aebed0;
background: rgba(7, 17, 31, 0.8);
font-size: 10px;
font-weight: 700;
font-variant-numeric: tabular-nums;
}
.edge-label.disabled {
color: #68788c;
text-decoration: line-through;
}
.edge-label.route {
border-color: rgba(255, 209, 102, 0.7);
color: #ffe3a0;
background: rgba(55, 43, 16, 0.88);
}
.scene-top {
position: absolute;
top: 17px;
left: 18px;
right: 18px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
pointer-events: none;
z-index: 3;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 8px;
max-width: 430px;
padding: 9px 11px;
border: 1px solid rgba(44, 67, 94, 0.75);
border-radius: 9px;
background: rgba(8, 19, 33, 0.78);
backdrop-filter: blur(8px);
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
color: #a9bad0;
font-size: 10px;
}
.legend-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #8ba0b8;
}
.legend-dot.source {
background: var(--teal);
}
.legend-dot.destination {
background: var(--pink);
}
.legend-dot.route {
background: var(--gold);
}
.camera-controls {
display: flex;
gap: 5px;
pointer-events: auto;
}
.camera-controls button {
width: 34px;
height: 34px;
padding: 0;
border: 1px solid rgba(48, 72, 99, 0.85);
border-radius: 8px;
color: #c7d8e9;
background: rgba(8, 19, 33, 0.82);
backdrop-filter: blur(8px);
}
.camera-controls button:hover {
border-color: #527392;
background: #12253b;
}
.route-card {
position: absolute;
left: 20px;
bottom: 50px;
width: min(430px, calc(100% - 40px));
padding: 16px 17px;
border: 1px solid rgba(54, 78, 105, 0.9);
border-radius: 12px;
background: rgba(8, 19, 33, 0.88);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(12px);
pointer-events: none;
z-index: 3;
}
.route-card.found {
border-color: rgba(255, 209, 102, 0.45);
}
.route-card.unreachable {
border-color: rgba(255, 107, 120, 0.5);
}
.route-kicker {
color: #8ea3bb;
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.12em;
}
.route-title {
margin-top: 5px;
font-size: 22px;
font-weight: 850;
letter-spacing: -0.03em;
}
.route-path {
margin-top: 7px;
color: #b7c7d9;
font-size: 12px;
line-height: 1.5;
}
.route-cost {
display: flex;
align-items: baseline;
gap: 7px;
margin-top: 10px;
}
.route-cost strong {
color: var(--gold);
font-size: 25px;
line-height: 1;
}
.route-cost span {
color: var(--muted);
font-size: 11px;
}
.scene-hint {
position: absolute;
left: 20px;
bottom: 17px;
color: #6f839c;
font-size: 10px;
pointer-events: none;
z-index: 3;
}
#toast {
position: absolute;
top: 70px;
left: 50%;
padding: 9px 13px;
border: 1px solid #31536c;
border-radius: 8px;
color: #d9e9f7;
background: rgba(12, 31, 48, 0.94);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
font-size: 12px;
opacity: 0;
transform: translate(-50%, -8px);
transition: 0.2s;
pointer-events: none;
z-index: 20;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 900px) {
html,
body {
overflow: auto;
}
.app {
grid-template-columns: 1fr;
grid-template-rows: 64px 52vh auto;
height: auto;
min-height: 100dvh;
}
header {
padding: 0 14px;
}
.subtitle,
.header-meta .badge:last-child {
display: none;
}
aside {
grid-column: 1;
grid-row: 3;
overflow: visible;
border-right: 0;
border-top: 1px solid var(--line);
}
#viewport {
grid-column: 1;
grid-row: 2;
}
.scene-top {
top: 10px;
left: 10px;
right: 10px;
}
.legend {
gap: 6px;
}
.route-card {
left: 10px;
bottom: 42px;
width: calc(100% - 20px);
}
.scene-hint {
left: 10px;
bottom: 12px;
}
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<svg viewBox="0 0 32 32" fill="none">
<path d="M7 24 14 8l11 15M11 18h10" stroke="#54e7c1" stroke-width="2.4"
stroke-linecap="round" stroke-linejoin="round"/>
<circle cx="7" cy="24" r="3" fill="#63a9ff"/>
<circle cx="14" cy="8" r="3" fill="#ffd166"/>
<circle cx="25" cy="23" r="3" fill="#ff6f91"/>
</svg>
</div>
<div>
<h1>Shortest-Path Edge-Cost Explorer</h1>
<div class="subtitle">Edit nonnegative edge costs and inspect Dijkstra’s predecessor state.</div>
</div>
</div>
<div class="header-meta">
<span class="badge">8 vertices · 11 edges</span>
<span class="badge"><strong>Dijkstra</strong> · O(V²)</span>
</div>
</header>
<aside>
<section>
<div class="section-heading">
<h2>Route endpoints</h2>
<span class="count">Directed exploration</span>
</div>
<div class="field-grid">
<label class="field">
<span>Source</span>
<select id="sourceSelect"></select>
</label>
<label class="field">
<span>Destination</span>
<select id="destinationSelect"></select>
</label>
</div>
<button id="runRoute" class="primary" type="button">Recompute shortest route</button>
<p class="help">Click a node to set the destination. Shift-click a node to set the source.</p>
</section>
<section>
<div class="section-heading">
<h2>Edge costs</h2>
<span class="count">0 = valid · off = blocked</span>
</div>
<div id="validation" class="validation" role="alert" hidden></div>
<div id="edgeList" class="edge-list"></div>
<p class="help">
Costs must be finite and nonnegative. Negative-weight inputs are rejected.
Disable an edge to test unreachable destinations.
</p>
</section>
<section>
<div class="section-heading">
<h2>Dijkstra state</h2>
<button id="copyState" class="secondary" type="button" disabled>Copy JSON</button>
</div>
<table class="predecessor-table">
<thead>
<tr>
<th>Node</th>
<th>Distance</th>
<th>Predecessor</th>
</tr>
</thead>
<tbody id="predecessorRows"></tbody>
</table>
<div id="settledOrder" class="settled-order" aria-label="Settled vertex order"></div>
<div id="algorithmStatus" class="algorithm-status" aria-live="polite"></div>
</section>
</aside>
<main id="viewport" aria-label="Interactive three-dimensional graph">
<div id="canvasHost"></div>
<div id="labels" aria-hidden="true"></div>
<div class="scene-top">
<div class="legend">
<span class="legend-item"><i class="legend-dot source"></i>Source</span>
<span class="legend-item"><i class="legend-dot destination"></i>Destination</span>
<span class="legend-item"><i class="legend-dot route"></i>Shortest path</span>
</div>
<div class="camera-controls">
<button id="zoomIn" type="button" title="Zoom in" aria-label="Zoom in">+</button>
<button id="zoomOut" type="button" title="Zoom out" aria-label="Zoom out">−</button>
<button id="resetCamera" type="button" title="Reset camera" aria-label="Reset camera">↺</button>
</div>
</div>
<div id="routeCard" class="route-card">
<div class="route-kicker">Current result</div>
<div id="routeTitle" class="route-title">Ready to explore</div>
<div id="routePath" class="route-path">Choose endpoints and recompute the route.</div>
<div class="route-cost">
<strong id="routeCost">—</strong>
<span id="routeUnits">total edge cost</span>
</div>
</div>
<div class="scene-hint">Drag to orbit · Wheel/pinch controls zoom · Click nodes to choose endpoints</div>
<div id="toast" role="status"></div>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const viewport = document.querySelector("#viewport");
const canvasHost = document.querySelector("#canvasHost");
const labelsHost = document.querySelector("#labels");
const sourceSelect = document.querySelector("#sourceSelect");
const destinationSelect = document.querySelector("#destinationSelect");
const runButton = document.querySelector("#runRoute");
const edgeList = document.querySelector("#edgeList");
const validationBox = document.querySelector("#validation");
const predecessorRows = document.querySelector("#predecessorRows");
const settledOrder = document.querySelector("#settledOrder");
const algorithmStatus = document.querySelector("#algorithmStatus");
const copyStateButton = document.querySelector("#copyState");
const routeCard = document.querySelector("#routeCard");
const routeTitle = document.querySelector("#routeTitle");
const routePath = document.querySelector("#routePath");
const routeCost = document.querySelector("#routeCost");
const routeUnits = document.querySelector("#routeUnits");
const toast = document.querySelector("#toast");
const nodeDefinitions = [
{ id: "A", name: "Alpha", x: -5.2, z: -2.4 },
{ id: "B", name: "Bravo", x: -2.2, z: -4.2 },
{ id: "C", name: "Charlie", x: 1.4, z: -3.4 },
{ id: "D", name: "Delta", x: -3.4, z: 1.2 },
{ id: "E", name: "Echo", x: 1.0, z: -0.5 },
{ id: "F", name: "Foxtrot", x: -0.2, z: 3.4 },
{ id: "G", name: "Golf", x: 4.2, z: 1.6 },
{ id: "H", name: "Hotel", x: 5.0, z: -2.4 }
];
const edgeDefinitions = [
{ id: "AB", a: "A", b: "B", cost: 2 },
{ id: "AC", a: "A", b: "C", cost: 4 },
{ id: "AD", a: "A", b: "D", cost: 7 },
{ id: "BC", a: "B", b: "C", cost: 1 },
{ id: "BD", a: "B", b: "D", cost: 5 },
{ id: "CE", a: "C", b: "E", cost: 2 },
{ id: "DE", a: "D", b: "E", cost: 3 },
{ id: "DF", a: "D", b: "F", cost: 6 },
{ id: "EF", a: "E", b: "F", cost: 2 },
{ id: "EG", a: "E", b: "G", cost: 4 },
{ id: "FG", a: "F", b: "G", cost: 3 },
{ id: "FH", a: "F", b: "H", cost: 5 },
{ id: "GH", a: "G", b: "H", cost: 1 }
];
const nodes = Object.fromEntries(
nodeDefinitions.map(node => [
node.id,
{
...node,
position: new THREE.Vector3(node.x, 0, node.z)
}
])
);
const edges = Object.fromEntries(
edgeDefinitions.map(edge => [
edge.id,
{
...edge,
enabled: true
}
])
);
const nodeVisuals = {};
const edgeVisuals = {};
const nodeHitMeshes = [];
const edgeInputs = {};
const edgeToggles = {};
let latestState = null;
let dirty = true;
let runToken = 0;
// ----- Three.js scene -----------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 27, 55);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.18;
canvasHost.appendChild(renderer.domElement);
const cameraState = {
radius: 21,
theta: 0.70,
phi: 0.98,
target: new THREE.Vector3(0, 0.15, 0)
};
function updateCamera() {
const { radius, theta, phi, target } = cameraState;
const horizontal = radius * Math.sin(phi);
camera.position.set(
target.x + horizontal * Math.sin(theta),
target.y + radius * Math.cos(phi),
target.z + horizontal * Math.cos(theta)
);
camera.lookAt(target);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xa9d8ff, 0x142032, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffe7bd, 3.1);
sun.position.set(-7, 14, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.camera.left = -14;
sun.shadow.camera.right = 14;
sun.shadow.camera.top = 14;
sun.shadow.camera.bottom = -14;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 40;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x4a91ff, 1.35);
rimLight.position.set(8, 7, -10);
scene.add(rimLight);
const water = new THREE.Mesh(
new THREE.CircleGeometry(60, 48),
new THREE.MeshStandardMaterial({
color: 0x0b2940,
roughness: 0.76,
metalness: 0.05
})
);
water.rotation.x = -Math.PI / 2;
water.position.y = -0.82;
water.receiveShadow = true;
scene.add(water);
const sand = new THREE.Mesh(
new THREE.CylinderGeometry(10.25, 10.7, 0.65, 12, 1, false),
new THREE.MeshStandardMaterial({
color: 0xb69768,
roughness: 1,
flatShading: true
})
);
sand.position.y = -0.43;
sand.receiveShadow = true;
sand.castShadow = true;
scene.add(sand);
const grass = new THREE.Mesh(
new THREE.CylinderGeometry(9.82, 10.15, 0.28, 12, 1, false),
new THREE.MeshStandardMaterial({
color: 0x416d4f,
roughness: 1,
flatShading: true
})
);
grass.position.y = -0.04;
grass.receiveShadow = true;
scene.add(grass);
// A subtle low-poly inset around the graph.
const inset = new THREE.Mesh(
new THREE.CylinderGeometry(7.8, 8.0, 0.035, 12),
new THREE.MeshStandardMaterial({
color: 0x527b5a,
roughness: 1,
flatShading: true
})
);
inset.position.y = 0.115;
inset.receiveShadow = true;
scene.add(inset);
let seed = 93841;
function random() {
seed = (seed * 1664525 + 1013904223) >>> 0;
return seed / 4294967296;
}
function addTree(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0.1, z);
group.scale.setScalar(scale);
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.08, 0.13, 0.85, 5),
new THREE.MeshStandardMaterial({ color: 0x654a34, flatShading: true })
);
trunk.position.y = 0.42;
trunk.castShadow = true;
const crown = new THREE.Mesh(
new THREE.ConeGeometry(0.52, 1.25, 6),
new THREE.MeshStandardMaterial({
color: random() > 0.5 ? 0x285c47 : 0x326b4c,
flatShading: true
})
);
crown.position.y = 1.12;
crown.castShadow = true;
group.add(trunk, crown);
scene.add(group);
}
[
[-7.5, 2.7, 1.0],
[-6.9, -5.5, 0.85],
[-1.0, -7.0, 0.9],
[4.5, -5.8, 1.1],
[7.4, 3.5, 0.9],
[5.8, 5.4, 1.05],
[-5.3, 5.8, 1.1],
[0.8, 6.6, 0.85]
].forEach(args => addTree(...args));
for (let i = 0; i < 12; i++) {
const angle = random() * Math.PI * 2;
const radius = 7.5 + random() * 1.7;
const rock = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.18 + random() * 0.25, 0),
new THREE.MeshStandardMaterial({
color: i % 2 ? 0x76818a : 0x65746f,
roughness: 1,
flatShading: true
})
);
rock.position.set(Math.cos(angle) * radius, 0.25, Math.sin(angle) * radius);
rock.scale.y = 0.65 + random() * 0.6;
rock.rotation.set(random(), random(), random());
rock.castShadow = true;
rock.receiveShadow = true;
scene.add(rock);
}
const nodeBodyGeometry = new THREE.CylinderGeometry(0.44, 0.55, 0.62, 6);
const nodeCapGeometry = new THREE.OctahedronGeometry(0.34, 0);
const nodeBaseGeometry = new THREE.TorusGeometry(0.49, 0.055, 5, 12);
const edgeGeometry = new THREE.CylinderGeometry(1, 1, 1, 8);
for (const node of Object.values(nodes)) {
const group = new THREE.Group();
group.position.copy(node.position);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0x73869c,
roughness: 0.72,
metalness: 0.08,
flatShading: true
});
const capMaterial = new THREE.MeshStandardMaterial({
color: 0xdce8f4,
emissive: 0x10283d,
emissiveIntensity: 0.45,
roughness: 0.48,
metalness: 0.12,
flatShading: true
});
const body = new THREE.Mesh(nodeBodyGeometry, bodyMaterial);
body.position.y = 0.40;
body.castShadow = true;
body.receiveShadow = true;
body.userData.nodeId = node.id;
const cap = new THREE.Mesh(nodeCapGeometry, capMaterial);
cap.position.y = 0.98;
cap.scale.y = 1.18;
cap.castShadow = true;
cap.userData.nodeId = node.id;
const base = new THREE.Mesh(
nodeBaseGeometry,
new THREE.MeshStandardMaterial({
color: 0x273c51,
roughness: 0.8,
flatShading: true
})
);
base.position.y = 0.15;
base.rotation.x = Math.PI / 2;
group.add(body, cap, base);
scene.add(group);
const label = document.createElement("div");
label.className = "node-label";
label.textContent = node.id;
labelsHost.appendChild(label);
nodeVisuals[node.id] = {
group,
body,
cap,
bodyMaterial,
capMaterial,
label
};
nodeHitMeshes.push(body, cap);
}
function edgeKey(a, b) {
return [a, b].sort().join("");
}
const edgeLookup = Object.fromEntries(
edgeDefinitions.map(edge => [edgeKey(edge.a, edge.b), edge.id])
);
for (const edge of Object.values(edges)) {
const start = nodes[edge.a].position.clone();
const end = nodes[edge.b].position.clone();
start.y = end.y = 0.33;
const direction = end.clone().sub(start);
const length = direction.length();
const midpoint = start.clone().add(end).multiplyScalar(0.5);
const material = new THREE.MeshStandardMaterial({
color: 0x667b95,
emissive: 0x000000,
emissiveIntensity: 0,
roughness: 0.82,
transparent: true,
opacity: 0.72,
flatShading: true
});
const mesh = new THREE.Mesh(edgeGeometry, material);
mesh.position.copy(midpoint);
mesh.scale.set(0.065, length, 0.065);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.clone().normalize()
);
mesh.userData.edgeId = edge.id;
mesh.castShadow = true;
scene.add(mesh);
const labelPosition = midpoint.clone();
labelPosition.y = 0.64;
const label = document.createElement("div");
label.className = "edge-label";
label.textContent = edge.cost;
labelsHost.appendChild(label);
edgeVisuals[edge.id] = {
mesh,
material,
label,
labelPosition,
length
};
}
const routePulse = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.13, 0),
new THREE.MeshBasicMaterial({ color: 0xffe08a })
);
routePulse.visible = false;
scene.add(routePulse);
let routePoints = [];
let routeLength = 0;
// ----- Camera controls ----------------------------------------------------
let dragging = false;
let dragMoved = 0;
let lastPointerX = 0;
let lastPointerY = 0;
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button !== 0 && event.button !== 2) return;
dragging = true;
dragMoved = 0;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
dragMoved += Math.abs(dx) + Math.abs(dy);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.34,
1.43
);
updateCamera();
});
renderer.domElement.addEventListener("pointerup", event => {
if (!dragging) return;
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
if (dragMoved < 6) {
pickNode(event);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener("contextmenu", event => {
event.preventDefault();
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.012,
11,
34
);
updateCamera();
}, { passive: false });
function pickNode(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 hit = raycaster.intersectObjects(nodeHitMeshes, false)[0];
if (!hit) return;
const id = hit.object.userData.nodeId;
if (event.shiftKey) {
sourceSelect.value = id;
} else {
destinationSelect.value = id;
}
computeRoute();
}
document.querySelector("#zoomIn").addEventListener("click", () => {
cameraState.radius = Math.max(11, cameraState.radius - 2);
updateCamera();
});
document.querySelector("#zoomOut").addEventListener("click", () => {
cameraState.radius = Math.min(34, cameraState.radius + 2);
updateCamera();
});
document.querySelector("#resetCamera").addEventListener("click", () => {
cameraState.radius = 21;
cameraState.theta = 0.70;
cameraState.phi = 0.98;
cameraState.target.set(0, 0.15, 0);
updateCamera();
});
// ----- UI creation --------------------------------------------------------
const nodeOptions = nodeDefinitions
.map(node => `<option value="${node.id}">${node.id} · ${node.name}</option>`)
.join("");
sourceSelect.innerHTML = nodeOptions;
destinationSelect.innerHTML = nodeOptions;
sourceSelect.value = "A";
destinationSelect.value = "H";
for (const edge of edgeDefinitions) {
const row = document.createElement("div");
row.className = "edge-row";
row.innerHTML = `
<div class="edge-name">
${edge.a} → ${edge.b}
<small>${nodes[edge.a].name} to ${nodes[edge.b].name}</small>
</div>
<input
type="number"
min="0"
step="0.1"
value="${edge.cost}"
aria-label="Cost from ${edge.a} to ${edge.b}"
>
<label class="toggle" title="Enable or disable this edge">
<input type="checkbox" checked aria-label="Enable edge ${edge.a} to ${edge.b}">
<span></span>
</label>
`;
edgeList.appendChild(row);
const input = row.querySelector("input[type='number']");
const toggle = row.querySelector("input[type='checkbox']");
edgeInputs[edge.id] = input;
edgeToggles[edge.id] = toggle;
input.addEventListener("input", () => {
const raw = input.value.trim();
const value = Number(raw);
const valid = raw !== "" && Number.isFinite(value) && value >= 0;
if (valid) {
edges[edge.id].cost = value;
}
validateCosts();
updateEdgeLabel(edge.id);
markDirty(valid ? "Inputs changed — recompute the route." : "Invalid input rejected — the route was not recomputed.");
});
toggle.addEventListener("change", () => {
edges[edge.id].enabled = toggle.checked;
updateEdgeLabel(edge.id);
markDirty("Inputs changed — recompute the route.");
});
}
predecessorRows.innerHTML = nodeDefinitions
.map(node => `
<tr data-node="${node.id}">
<td>${node.id}</td>
<td class="distance">∞</td>
<td class="predecessor">—</td>
</tr>
`)
.join("");
// ----- Validation and visual state ---------------------------------------
function validateCosts() {
const errors = [];
for (const edge of edgeDefinitions) {
const input = edgeInputs[edge.id];
const raw = input.value.trim();
const value = Number(raw);
const valid = raw !== "" && Number.isFinite(value) && value >= 0;
input.classList.toggle("invalid", !valid);
input.setAttribute("aria-invalid", String(!valid));
input.setCustomValidity(
valid ? "" : "Cost must be a finite nonnegative number."
);
if (!valid) {
const reason = raw !== "" && Number.isFinite(value) && value < 0
? "negative weights are unsupported"
: "use a finite number greater than or equal to zero";
errors.push(`${edge.a} → ${edge.b}: ${reason}`);
}
}
validationBox.hidden = errors.length === 0;
validationBox.textContent = errors.length
? `Rejected edge cost: ${errors.join("; ")}.`
: "";
return errors;
}
function updateEdgeLabel(id) {
const edge = edges[id];
const visual = edgeVisuals[id];
visual.label.textContent = edge.enabled ? formatCost(edge.cost) : "off";
visual.label.classList.toggle("disabled", !edge.enabled);
}
function formatCost(value) {
return Number.isInteger(value) ? String(value) : value.toFixed(2).replace(/0+$/, "").replace(/\.$/, "");
}
function resetEdgeVisuals() {
for (const edge of edgeDefinitions) {
const visual = edgeVisuals[edge.id];
const enabled = edges[edge.id].enabled;
visual.material.color.set(enabled ? 0x667b95 : 0x394456);
visual.material.emissive.set(0x000000);
visual.material.emissiveIntensity = 0;
visual.material.opacity = enabled ? 0.72 : 0.18;
visual.mesh.scale.x = visual.mesh.scale.z = enabled ? 0.065 : 0.045;
visual.label.classList.remove("route");
}
}
function updateNodeVisuals(pathSet = new Set()) {
const source = sourceSelect.value;
const destination = destinationSelect.value;
for (const node of nodeDefinitions) {
const visual = nodeVisuals[node.id];
const onRoute = pathSet.has(node.id);
let bodyColor = 0x73869c;
let capColor = 0xdce8f4;
let emissive = 0x10283d;
if (onRoute) {
bodyColor = 0x66501f;
capColor = 0xffd166;
emissive = 0x6d4b05;
}
if (node.id === source) {
bodyColor = 0x185448;
capColor = 0x37e0b2;
emissive = 0x0d6b52;
}
if (node.id === destination) {
bodyColor = 0x632b3c;
capColor = 0xff6f91;
emissive = 0x781d3b;
}
visual.bodyMaterial.color.set(bodyColor);
visual.capMaterial.color.set(capColor);
visual.capMaterial.emissive.set(emissive);
visual.capMaterial.emissiveIntensity = onRoute || node.id === source || node.id === destination ? 0.75 : 0.35;
visual.label.classList.toggle("source", node.id === source);
visual.label.classList.toggle("destination", node.id === destination);
visual.label.classList.toggle("route", onRoute);
}
}
function clearRoute() {
resetEdgeVisuals();
updateNodeVisuals();
routePoints = [];
routeLength = 0;
routePulse.visible = false;
}
function markDirty(message) {
dirty = true;
clearRoute();
routeCard.className = "route-card";
routeTitle.textContent = "Route needs recomputing";
routePath.textContent = message;
routeCost.textContent = "—";
routeUnits.textContent = "total edge cost";
algorithmStatus.textContent = message;
}
// ----- Dijkstra ------------------------------------------------------------
function buildAdjacency() {
const adjacency = Object.fromEntries(nodeDefinitions.map(node => [node.id, []]));
for (const edge of edgeDefinitions) {
if (!edges[edge.id].enabled) continue;
adjacency[edge.a].push({ node: edge.b, cost: edges[edge.id].cost, edgeId: edge.id });
adjacency[edge.b].push({ node: edge.a, cost: edges[edge.id].cost, edgeId: edge.id });
}
return adjacency;
}
function dijkstra(source) {
const adjacency = buildAdjacency();
const distances = {};
const predecessors = {};
const settled = [];
const remaining = new Set(nodeDefinitions.map(node => node.id));
for (const node of nodeDefinitions) {
distances[node.id] = Infinity;
predecessors[node.id] = null;
}
distances[source] = 0;
while (remaining.size > 0) {
let current = null;
let bestDistance = Infinity;
for (const id of remaining) {
if (distances[id] < bestDistance) {
bestDistance = distances[id];
current = id;
}
}
if (current === null) break;
remaining.delete(current);
settled.push(current);
for (const neighbor of adjacency[current]) {
if (!remaining.has(neighbor.node)) continue;
const candidate = distances[current] + neighbor.cost;
if (candidate < distances[neighbor.node]) {
distances[neighbor.node] = candidate;
predecessors[neighbor.node] = current;
}
}
}
return { distances, predecessors, settled };
}
function reconstructPath(predecessors, source, destination, distance) {
if (!Number.isFinite(distance)) return [];
const path = [];
let current = destination;
while (current !== null) {
path.unshift(current);
if (current === source) break;
current = predecessors[current];
}
return path[0] === source ? path : [];
}
function resetPredecessorTable() {
settledOrder.innerHTML = "";
for (const row of predecessorRows.querySelectorAll("tr")) {
row.classList.remove("settled");
row.querySelector(".distance").textContent = "∞";
row.querySelector(".predecessor").textContent = "—";
}
}
function updatePredecessorCell(id, distance, predecessor, isSettled) {
const row = predecessorRows.querySelector(`tr[data-node="${id}"]`);
row.classList.toggle("settled", isSettled);
row.querySelector(".distance").textContent =
Number.isFinite(distance) ? formatCost(distance) : "∞";
row.querySelector(".predecessor").textContent =
predecessor ? `via ${predecessor}` : "—";
}
function applyRouteVisuals(path) {
resetEdgeVisuals();
updateNodeVisuals(new Set(path));
const pathSet = new Set(path);
for (let i = 1; i < path.length; i++) {
const id = edgeLookup[edgeKey(path[i - 1], path[i])];
const visual = edgeVisuals[id];
visual.material.color.set(0xffd166);
visual.material.emissive.set(0x6f4b00);
visual.material.emissiveIntensity = 0.5;
visual.material.opacity = 1;
visual.mesh.scale.x = visual.mesh.scale.z = 0.105;
visual.label.classList.add("route");
}
routePoints = path.map(id => {
const point = nodes[id].position.clone();
point.y = 0.90;
return point;
});
routeLength = 0;
for (let i = 1; i < routePoints.length; i++) {
routeLength += routePoints[i].distanceTo(routePoints[i - 1]);
}
routePulse.visible = routePoints.length > 1;
}
async function computeRoute() {
const token = ++runToken;
const errors = validateCosts();
if (errors.length > 0) {
dirty = true;
clearRoute();
routeCard.className = "route-card unreachable";
routeTitle.textContent = "Invalid edge cost";
routePath.textContent = "Negative or non-finite costs are unsupported. The route was not recomputed.";
routeCost.textContent = "—";
routeUnits.textContent = "total edge cost";
algorithmStatus.textContent = "Computation rejected: all edge costs must be finite and nonnegative.";
return;
}
dirty = false;
clearRoute();
resetPredecessorTable();
const source = sourceSelect.value;
const destination = destinationSelect.value;
const result = dijkstra(source);
algorithmStatus.textContent = `Starting at ${source}…`;
for (const id of result.settled) {
if (token !== runToken) return;
updatePredecessorCell(
id,
result.distances[id],
result.predecessors[id],
true
);
const chip = document.createElement("span");
chip.className = "settled-chip";
chip.textContent = id;
settledOrder.appendChild(chip);
const via = result.predecessors[id]
? ` via ${result.predecessors[id]}`
: " as source";
algorithmStatus.textContent = `Settled ${id}${via}. Distance: ${formatCost(result.distances[id])}.`;
await new Promise(resolve => setTimeout(resolve, 185));
}
if (token !== runToken) return;
for (const node of nodeDefinitions) {
updatePredecessorCell(
node.id,
result.distances[node.id],
result.predecessors[node.id],
result.settled.includes(node.id)
);
}
const reachable = Number.isFinite(result.distances[destination]);
const path = reachable
? reconstructPath(result.predecessors, source, destination, result.distances[destination])
: [];
applyRouteVisuals(path);
if (reachable) {
routeCard.className = "route-card found";
routeTitle.textContent = `${source} → ${destination}`;
routePath.textContent = path.join(" → ");
routeCost.textContent = formatCost(result.distances[destination]);
routeUnits.textContent = path.length === 1
? "total edge cost · source equals destination"
: `total edge cost · ${path.length - 1} edges`;
algorithmStatus.textContent =
`Settled ${result.settled.length} reachable vertices. ` +
`Destination found with total cost ${formatCost(result.distances[destination])}.`;
} else {
routeCard.className = "route-card unreachable";
routeTitle.textContent = `${destination} is unreachable`;
routePath.textContent =
`No valid route exists from ${source}. Enable one or more blocked edges or edit their costs.`;
routeCost.textContent = "∞";
routeUnits.textContent = "no finite route";
algorithmStatus.textContent =
`Settled ${result.settled.length} reachable vertices. ` +
`${destination} was never reached.`;
}
latestState = {
source,
destination,
reachable,
totalCost: reachable ? result.distances[destination] : null,
path,
settledOrder: result.settled,
distances: Object.fromEntries(
nodeDefinitions.map(node => [
node.id,
Number.isFinite(result.distances[node.id])
? result.distances[node.id]
: null
])
),
predecessors: result.predecessors,
edges: Object.fromEntries(
edgeDefinitions.map(edge => [
edge.id,
{
cost: edges[edge.id].cost,
enabled: edges[edge.id].enabled
}
])
)
};
copyStateButton.disabled = false;
}
sourceSelect.addEventListener("change", () => {
markDirty("Source changed — recompute the route.");
});
destinationSelect.addEventListener("change", () => {
markDirty("Destination changed — recompute the route.");
});
runButton.addEventListener("click", computeRoute);
copyStateButton.addEventListener("click", async () => {
if (!latestState) return;
const text = JSON.stringify(latestState, null, 2);
try {
await navigator.clipboard.writeText(text);
} catch {
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.style.position = "fixed";
textarea.style.opacity = "0";
document.body.appendChild(textarea);
textarea.select();
document.execCommand("copy");
textarea.remove();
}
showToast("Dijkstra state copied as JSON");
});
let toastTimer;
function showToast(message) {
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 1900);
}
// ----- Projection, resizing, and render loop ------------------------------
function projectLabel(element, worldPosition) {
const projected = worldPosition.clone().project(camera);
if (
projected.z < -1 ||
projected.z > 1 ||
projected.x < -1.15 ||
projected.x > 1.15 ||
projected.y < -1.15 ||
projected.y > 1.15
) {
element.style.display = "none";
return;
}
const x = (projected.x * 0.5 + 0.5) * viewport.clientWidth;
const y = (-projected.y * 0.5 + 0.5) * viewport.clientHeight;
element.style.display = "";
element.style.transform =
`translate(${x}px, ${y}px) translate(-50%, -50%)`;
}
function resize() {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
if (!width || !height) return;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
new ResizeObserver(resize).observe(viewport);
resize();
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
for (const node of nodeDefinitions) {
const world = nodes[node.id].position.clone();
world.y = 1.53;
projectLabel(nodeVisuals[node.id].label, world);
}
for (const edge of edgeDefinitions) {
projectLabel(
edgeVisuals[edge.id].label,
edgeVisuals[edge.id].labelPosition
);
}
if (routePulse.visible && routePoints.length > 1 && routeLength > 0) {
const travel = (elapsed * 1.65) % routeLength;
let remaining = travel;
for (let i = 1; i < routePoints.length; i++) {
const segmentLength = routePoints[i].distanceTo(routePoints[i - 1]);
if (remaining <= segmentLength || i === routePoints.length - 1) {
const t = segmentLength === 0 ? 0 : remaining / segmentLength;
routePulse.position.lerpVectors(
routePoints[i - 1],
routePoints[i],
THREE.MathUtils.clamp(t, 0, 1)
);
break;
}
remaining -= segmentLength;
}
}
renderer.render(scene, camera);
}
validateCosts();
animate();
computeRoute();
</script>
</body>
</html>
```