Prompt specification
Build or customize the Three.js 3D scene "Fewest edges versus lowest cost comparison" 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: Fewest edges versus lowest cost comparison
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/fewest-edges-versus-lowest-cost-comparison-x1918
Scene Description Prompt:
A stylized weighted graph compares fewest hops with minimum nonnegative path cost, using correct searches. Make one HTML scene with Three.js from cdnjs.
Working Three.js Starter (fewest-edges-versus-lowest-cost-comparison-x1918):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Weighted Graph — Hops vs. Cost</title>
<style>
:root {
color-scheme: dark;
--bg: #07101d;
--panel: rgba(10, 20, 35, 0.84);
--panel-border: rgba(164, 196, 222, 0.16);
--text: #eaf4ff;
--muted: #8da5bb;
--cyan: #55e6ff;
--amber: #ffb84d;
--green: #7cffb2;
--red: #ff6f91;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
color: var(--text);
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 2;
}
.topbar {
position: absolute;
top: 22px;
left: 24px;
right: 24px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 24px;
}
.brand {
max-width: 470px;
padding: 17px 19px;
border: 1px solid var(--panel-border);
border-radius: 18px;
background:
linear-gradient(135deg, rgba(19, 37, 57, 0.91), rgba(7, 15, 27, 0.79));
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.22);
backdrop-filter: blur(16px);
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
color: #8cb5cf;
font: 700 10px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
width: 18px;
height: 2px;
content: "";
border-radius: 999px;
background: linear-gradient(90deg, var(--cyan), var(--amber));
}
h1 {
margin: 0;
font-size: clamp(23px, 2.5vw, 36px);
line-height: 1.02;
letter-spacing: -0.045em;
}
.subtitle {
margin: 9px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.comparison {
min-height: 21px;
margin-top: 12px;
padding-top: 11px;
border-top: 1px solid rgba(164, 196, 222, 0.12);
color: #c3d5e4;
font-size: 12px;
line-height: 1.45;
}
.controls {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
align-items: flex-end;
gap: 9px;
pointer-events: auto;
}
.control-panel {
display: flex;
align-items: flex-end;
gap: 9px;
padding: 12px;
border: 1px solid var(--panel-border);
border-radius: 16px;
background: var(--panel);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(16px);
}
.field {
display: grid;
gap: 6px;
}
.field span {
color: var(--muted);
font: 700 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.14em;
text-transform: uppercase;
}
select,
button {
height: 37px;
border: 1px solid rgba(164, 196, 222, 0.2);
border-radius: 9px;
outline: none;
font: 700 12px/1 ui-sans-serif, system-ui, sans-serif;
}
select {
min-width: 62px;
padding: 0 28px 0 10px;
color: var(--text);
background: #101e30;
cursor: pointer;
}
button {
padding: 0 14px;
color: #041018;
background: linear-gradient(135deg, #8af2ff, #55e6ff);
cursor: pointer;
transition:
transform 160ms ease,
filter 160ms ease;
}
button:hover {
transform: translateY(-1px);
filter: brightness(1.08);
}
button.secondary {
color: #c9d9e7;
background: #142338;
}
.status {
align-self: center;
display: inline-flex;
align-items: center;
gap: 8px;
min-height: 37px;
padding: 0 13px;
border: 1px solid var(--panel-border);
border-radius: 999px;
color: #b9cbda;
background: var(--panel);
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.07em;
text-transform: uppercase;
backdrop-filter: blur(12px);
}
.status i {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 12px var(--green);
}
.metrics {
position: absolute;
right: 24px;
bottom: 22px;
left: 24px;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 14px;
pointer-events: none;
}
.card {
position: relative;
min-width: 0;
overflow: hidden;
padding: 17px 18px 15px;
border: 1px solid var(--panel-border);
border-radius: 17px;
background:
linear-gradient(135deg, rgba(15, 29, 47, 0.94), rgba(7, 16, 29, 0.91));
box-shadow: 0 20px 55px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(18px);
pointer-events: auto;
}
.card::before {
position: absolute;
top: 0;
right: 0;
left: 0;
height: 3px;
content: "";
background: var(--accent);
box-shadow: 0 0 20px color-mix(in srgb, var(--accent) 65%, transparent);
}
.card.bfs {
--accent: var(--cyan);
}
.card.dijkstra {
--accent: var(--amber);
}
.card-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
}
.card-title {
display: flex;
align-items: center;
gap: 9px;
font-size: 13px;
font-weight: 800;
}
.dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 14px var(--accent);
}
.algorithm {
color: var(--muted);
font: 700 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.metric-row {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 14px;
}
.primary {
display: flex;
align-items: baseline;
gap: 8px;
}
.primary strong {
font-size: clamp(35px, 4.5vw, 58px);
line-height: 0.92;
letter-spacing: -0.06em;
color: var(--accent);
}
.primary span {
color: var(--muted);
font-size: 12px;
font-weight: 700;
text-transform: uppercase;
}
.secondary-stat {
padding-bottom: 3px;
text-align: right;
}
.secondary-stat span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.secondary-stat strong {
display: block;
margin-top: 3px;
font: 800 18px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.path {
margin-top: 13px;
padding: 9px 10px;
border: 1px solid rgba(164, 196, 222, 0.1);
border-radius: 9px;
color: #d8e8f5;
background: rgba(2, 9, 18, 0.36);
font: 600 11px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace;
overflow-wrap: anywhere;
}
.card-foot {
display: flex;
justify-content: space-between;
gap: 12px;
margin-top: 9px;
color: #8299ae;
font-size: 10px;
line-height: 1.35;
}
.hint {
position: absolute;
bottom: 252px;
left: 50%;
padding: 7px 11px;
border: 1px solid rgba(164, 196, 222, 0.1);
border-radius: 999px;
color: rgba(190, 211, 228, 0.68);
background: rgba(7, 16, 29, 0.56);
font: 600 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.04em;
transform: translateX(-50%);
backdrop-filter: blur(8px);
}
@media (max-width: 820px) {
.topbar {
top: 12px;
right: 12px;
left: 12px;
gap: 10px;
}
.brand {
max-width: 360px;
padding: 13px 14px;
}
.subtitle {
display: none;
}
.comparison {
margin-top: 8px;
padding-top: 8px;
font-size: 10px;
}
.control-panel {
padding: 9px;
}
.status {
display: none;
}
.metrics {
right: 12px;
bottom: 12px;
left: 12px;
gap: 9px;
}
.card {
padding: 14px;
}
.algorithm {
display: none;
}
.path {
font-size: 9px;
}
.hint {
bottom: 235px;
}
}
@media (max-width: 620px) {
.topbar {
flex-direction: column;
}
.brand,
.control-panel {
width: 100%;
}
.controls {
width: 100%;
}
.control-panel {
justify-content: space-between;
}
.field {
flex: 1;
}
select {
width: 100%;
}
.primary strong {
font-size: 35px;
}
.card-head {
margin-bottom: 7px;
}
.card-title {
font-size: 11px;
}
.secondary-stat strong {
font-size: 15px;
}
.card-foot {
display: block;
font-size: 9px;
}
.card-foot span:last-child {
display: none;
}
.path {
margin-top: 9px;
padding: 7px;
}
.hint {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<div class="hud">
<header class="topbar">
<section class="brand">
<div class="eyebrow">Undirected · Nonnegative weights</div>
<h1>Two truths, one graph.</h1>
<p class="subtitle">
Compare a route with the fewest edges against one with the smallest
total edge weight.
</p>
<div id="comparison" class="comparison" aria-live="polite">
Solving both optimal routes…
</div>
</section>
<div class="controls">
<div class="control-panel">
<label class="field">
<span>Start</span>
<select id="source" aria-label="Start node"></select>
</label>
<label class="field">
<span>Goal</span>
<select id="target" aria-label="Goal node"></select>
</label>
<button id="run" type="button">Run both</button>
<button id="reset" class="secondary" type="button">Reset view</button>
</div>
<div class="status">
<i></i>
<span id="statusText">Ready</span>
</div>
</div>
</header>
<div class="hint">
Drag to orbit · Shift/right-drag to pan · Scroll to zoom · Click a node to move the start
</div>
<main class="metrics">
<article class="card bfs">
<div class="card-head">
<div class="card-title">
<span class="dot"></span>
Fewest hops
</div>
<span class="algorithm">Breadth-first search</span>
</div>
<div class="metric-row">
<div class="primary">
<strong id="bfsHops">—</strong>
<span>hops</span>
</div>
<div class="secondary-stat">
<span>Path weight</span>
<strong id="bfsCost">—</strong>
</div>
</div>
<div id="bfsPath" class="path">—</div>
<div class="card-foot">
<span id="bfsExplored">—</span>
<span>Ignores weights; expands in edge-count layers.</span>
</div>
</article>
<article class="card dijkstra">
<div class="card-head">
<div class="card-title">
<span class="dot"></span>
Minimum cost
</div>
<span class="algorithm">Dijkstra's algorithm</span>
</div>
<div class="metric-row">
<div class="primary">
<strong id="dijkstraCost">—</strong>
<span>cost</span>
</div>
<div class="secondary-stat">
<span>Route length</span>
<strong id="dijkstraHops">—</strong>
</div>
</div>
<div id="dijkstraPath" class="path">—</div>
<div class="card-foot">
<span id="dijkstraExplored">—</span>
<span>Correct for all edge weights ≥ 0.</span>
</div>
</article>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------
// Graph data
// ---------------------------------------------------------------------
const nodePositions = {
A: new THREE.Vector3(-7.0, 2.5, 0),
B: new THREE.Vector3(-4.5, 3.2, 0),
C: new THREE.Vector3(-2.0, 1.7, 0),
D: new THREE.Vector3( 0.0, 3.0, 0),
E: new THREE.Vector3( 1.5, 0.0, 0),
F: new THREE.Vector3( 4.0, 1.0, 0),
G: new THREE.Vector3( 6.0, -0.7, 0),
H: new THREE.Vector3( 4.7, -3.1, 0),
I: new THREE.Vector3( 2.1, -4.0, 0),
J: new THREE.Vector3(-0.6, -3.2, 0)
};
const nodeIds = Object.keys(nodePositions);
const edges = [
{ a: "A", b: "B", w: 0 },
{ a: "A", b: "C", w: 5 },
{ a: "A", b: "D", w: 8 },
{ a: "B", b: "C", w: 1 },
{ a: "B", b: "D", w: 4 },
{ a: "C", b: "D", w: 1 },
{ a: "C", b: "E", w: 7 },
{ a: "D", b: "E", w: 3 },
{ a: "D", b: "F", w: 6 },
{ a: "E", b: "F", w: 2 },
{ a: "E", b: "G", w: 8 },
{ a: "F", b: "G", w: 3 },
{ a: "F", b: "H", w: 9 },
{ a: "G", b: "H", w: 4 },
{ a: "G", b: "I", w: 7 },
{ a: "H", b: "I", w: 2 },
{ a: "H", b: "J", w: 6 },
{ a: "I", b: "J", w: 1 }
];
const adjacency = new Map(nodeIds.map((id) => [id, []]));
const edgeLookup = new Map();
function edgeKey(a, b) {
return a < b ? `${a}|${b}` : `${b}|${a}`;
}
for (const edge of edges) {
adjacency.get(edge.a).push({ to: edge.b, weight: edge.w });
adjacency.get(edge.b).push({ to: edge.a, weight: edge.w });
edgeLookup.set(edgeKey(edge.a, edge.b), edge);
}
// ---------------------------------------------------------------------
// Correct searches
// ---------------------------------------------------------------------
function pathWeight(path) {
let total = 0;
for (let i = 1; i < path.length; i++) {
total += edgeLookup.get(edgeKey(path[i - 1], path[i])).w;
}
return total;
}
function reconstructPath(parent, source, target) {
if (!parent.has(target) && source !== target) return [];
const path = [target];
let current = target;
while (current !== source) {
current = parent.get(current);
if (current === undefined) return [];
path.unshift(current);
}
return path;
}
// BFS minimizes the number of edges. Edge weights are intentionally ignored.
function breadthFirstSearch(source, target) {
const distance = new Map([[source, 0]]);
const parent = new Map();
const queue = [source];
const visited = [];
for (let head = 0; head < queue.length; head++) {
const current = queue[head];
visited.push(current);
if (current === target) break;
for (const neighbor of adjacency.get(current)) {
if (distance.has(neighbor.to)) continue;
distance.set(neighbor.to, distance.get(current) + 1);
parent.set(neighbor.to, current);
queue.push(neighbor.to);
}
}
const path = reconstructPath(parent, source, target);
return {
path,
hops: distance.get(target) ?? Infinity,
cost: pathWeight(path),
visited
};
}
// Binary min-heap used by Dijkstra's algorithm.
class MinHeap {
constructor() {
this.items = [];
}
push(node, cost) {
const item = { node, cost };
this.items.push(item);
let index = this.items.length - 1;
while (index > 0) {
const parent = Math.floor((index - 1) / 2);
if (this.items[parent].cost <= this.items[index].cost) break;
[this.items[parent], this.items[index]] =
[this.items[index], this.items[parent]];
index = parent;
}
}
pop() {
if (this.items.length === 0) return null;
const root = this.items[0];
const last = this.items.pop();
if (this.items.length > 0) {
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 &&
this.items[left].cost < this.items[smallest].cost
) {
smallest = left;
}
if (
right < this.items.length &&
this.items[right].cost < this.items[smallest].cost
) {
smallest = right;
}
if (smallest === index) break;
[this.items[smallest], this.items[index]] =
[this.items[index], this.items[smallest]];
index = smallest;
}
}
return root;
}
get size() {
return this.items.length;
}
}
// Dijkstra minimizes cumulative weight. This is valid because all
// weights in the graph are nonnegative.
function dijkstraSearch(source, target) {
const distance = new Map([[source, 0]]);
const parent = new Map();
const settled = new Set();
const settledOrder = [];
const heap = new MinHeap();
heap.push(source, 0);
while (heap.size > 0) {
const current = heap.pop();
// Ignore stale heap entries.
if (current.cost !== distance.get(current.node)) continue;
if (settled.has(current.node)) continue;
settled.add(current.node);
settledOrder.push(current.node);
if (current.node === target) break;
for (const neighbor of adjacency.get(current.node)) {
const candidate = current.cost + neighbor.weight;
if (candidate < (distance.get(neighbor.to) ?? Infinity)) {
distance.set(neighbor.to, candidate);
parent.set(neighbor.to, current.node);
heap.push(neighbor.to, candidate);
}
}
}
const path = reconstructPath(parent, source, target);
return {
path,
cost: distance.get(target) ?? Infinity,
hops: Math.max(0, path.length - 1),
visited: settledOrder
};
}
// ---------------------------------------------------------------------
// Three.js scene
// ---------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x07101d, 1);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
const scene = new THREE.Scene();
scene.fog = new THREE.FogExp2(0x07101d, 0.022);
const camera = new THREE.PerspectiveCamera(
44,
window.innerWidth / window.innerHeight,
0.1,
100
);
const graphRoot = new THREE.Group();
graphRoot.position.y = 0.72;
scene.add(graphRoot);
scene.add(new THREE.AmbientLight(0x9dc8e8, 1.2));
const keyLight = new THREE.DirectionalLight(0xc8ecff, 2.3);
keyLight.position.set(-4, 8, 12);
scene.add(keyLight);
const warmLight = new THREE.PointLight(0xffb15d, 28, 24, 2);
warmLight.position.set(7, -3, 5);
scene.add(warmLight);
const coolLight = new THREE.PointLight(0x43dfff, 25, 24, 2);
coolLight.position.set(-7, 4, 4);
scene.add(coolLight);
// Background grid.
const grid = new THREE.GridHelper(30, 30, 0x31546c, 0x1c3347);
grid.rotation.x = Math.PI / 2;
grid.position.set(0, -0.35, -0.8);
grid.material.transparent = true;
grid.material.opacity = 0.16;
scene.add(grid);
// Subtle concentric backdrop rings.
for (let i = 0; i < 4; i++) {
const ring = new THREE.Mesh(
new THREE.RingGeometry(3.2 + i * 2.25, 3.225 + i * 2.25, 128),
new THREE.MeshBasicMaterial({
color: 0x31516a,
transparent: true,
opacity: 0.085,
side: THREE.DoubleSide,
depthWrite: false
})
);
ring.position.z = -0.72;
scene.add(ring);
}
// Deterministic background particles.
let randomSeed = 8731;
function seededRandom() {
randomSeed = (randomSeed * 16807) % 2147483647;
return (randomSeed - 1) / 2147483646;
}
const dustGeometry = new THREE.BufferGeometry();
const dustPositions = new Float32Array(360 * 3);
for (let i = 0; i < 360; i++) {
dustPositions[i * 3] = (seededRandom() - 0.5) * 30;
dustPositions[i * 3 + 1] = (seededRandom() - 0.5) * 20;
dustPositions[i * 3 + 2] = -1.5 - seededRandom() * 5;
}
dustGeometry.setAttribute(
"position",
new THREE.BufferAttribute(dustPositions, 3)
);
const dust = new THREE.Points(
dustGeometry,
new THREE.PointsMaterial({
color: 0x83b8d7,
size: 0.025,
transparent: true,
opacity: 0.42,
depthWrite: false
})
);
scene.add(dust);
// ---------------------------------------------------------------------
// Text sprites
// ---------------------------------------------------------------------
function roundedRectangle(context, x, y, width, height, radius) {
context.beginPath();
context.moveTo(x + radius, y);
context.lineTo(x + width - radius, y);
context.quadraticCurveTo(x + width, y, x + width, y + radius);
context.lineTo(x + width, y + height - radius);
context.quadraticCurveTo(
x + width,
y + height,
x + width - radius,
y + height
);
context.lineTo(x + radius, y + height);
context.quadraticCurveTo(x, y + height, x, y + height - radius);
context.lineTo(x, y + radius);
context.quadraticCurveTo(x, y, x + radius, y);
context.closePath();
}
function makeTextTexture(text, type = "weight") {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 256;
labelCanvas.height = 128;
const context = labelCanvas.getContext("2d");
context.clearRect(0, 0, 256, 128);
if (type === "weight") {
roundedRectangle(context, 48, 27, 160, 74, 24);
context.fillStyle = "rgba(7, 17, 30, 0.91)";
context.fill();
context.strokeStyle = "rgba(141, 184, 214, 0.30)";
context.lineWidth = 3;
context.stroke();
context.fillStyle = "#d8e9f7";
context.font = "700 40px ui-monospace, SFMono-Regular, Menlo, monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(String(text), 128, 65);
} else {
context.fillStyle = "#f0f8ff";
context.font = "800 72px Inter, system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.shadowColor = "rgba(0,0,0,0.8)";
context.shadowBlur = 10;
context.fillText(String(text), 128, 66);
}
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
return texture;
}
function createTextSprite(text, type, scaleX, scaleY) {
const material = new THREE.SpriteMaterial({
map: makeTextTexture(text, type),
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(scaleX, scaleY, 1);
sprite.renderOrder = 20;
return sprite;
}
// ---------------------------------------------------------------------
// Graph geometry
// ---------------------------------------------------------------------
const upAxis = new THREE.Vector3(0, 1, 0);
function makeRod(start, end, radius, material) {
const direction = new THREE.Vector3().subVectors(end, start);
const length = direction.length();
const geometry = new THREE.CylinderGeometry(
radius,
radius,
length,
12,
1,
false
);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
upAxis,
direction.normalize()
);
return mesh;
}
for (const edge of edges) {
const start = nodePositions[edge.a].clone();
const end = nodePositions[edge.b].clone();
const material = new THREE.MeshStandardMaterial({
color: 0x7893aa,
emissive: 0x152b3c,
emissiveIntensity: 0.35,
roughness: 0.5,
metalness: 0.25,
transparent: true,
opacity: 0.28
});
const rod = makeRod(start, end, 0.028, material);
graphRoot.add(rod);
const label = createTextSprite(edge.w, "weight", 0.62, 0.31);
label.position.copy(start).add(end).multiplyScalar(0.5);
label.position.z = 0.34;
graphRoot.add(label);
}
const nodeMeshes = [];
const nodeMaterials = new Map();
const nodeRings = new Map();
for (const id of nodeIds) {
const position = nodePositions[id];
const material = new THREE.MeshStandardMaterial({
color: 0x8ba8bf,
emissive: 0x18364d,
emissiveIntensity: 0.5,
roughness: 0.26,
metalness: 0.45
});
const sphere = new THREE.Mesh(
new THREE.SphereGeometry(0.27, 28, 20),
material
);
sphere.position.copy(position);
sphere.userData.nodeId = id;
graphRoot.add(sphere);
nodeMeshes.push(sphere);
nodeMaterials.set(id, material);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.37, 0.025, 8, 48),
new THREE.MeshBasicMaterial({
color: 0x7893aa,
transparent: true,
opacity: 0.26,
depthWrite: false
})
);
ring.position.copy(position);
graphRoot.add(ring);
nodeRings.set(id, ring);
const label = createTextSprite(id, "node", 0.48, 0.48);
label.position.copy(position);
label.position.z = 0.42;
graphRoot.add(label);
}
function updateNodeStyles(source, target) {
for (const id of nodeIds) {
const material = nodeMaterials.get(id);
const ring = nodeRings.get(id);
if (id === source) {
material.color.set(0x7cffb2);
material.emissive.set(0x1b8f52);
material.emissiveIntensity = 0.95;
ring.material.color.set(0x7cffb2);
ring.material.opacity = 0.8;
} else if (id === target) {
material.color.set(0xff6f91);
material.emissive.set(0x9e294b);
material.emissiveIntensity = 0.95;
ring.material.color.set(0xff6f91);
ring.material.opacity = 0.8;
} else {
material.color.set(0x8ba8bf);
material.emissive.set(0x18364d);
material.emissiveIntensity = 0.5;
ring.material.color.set(0x7893aa);
ring.material.opacity = 0.26;
}
}
}
// ---------------------------------------------------------------------
// Animated route visuals
// ---------------------------------------------------------------------
const routeVisuals = [];
const BFS_COLOR = new THREE.Color(0x55e6ff);
const DIJKSTRA_COLOR = new THREE.Color(0xffb84d);
function disposeObject(object) {
object.traverse((child) => {
if (child.geometry) child.geometry.dispose();
if (child.material) {
if (Array.isArray(child.material)) {
child.material.forEach((material) => material.dispose());
} else {
child.material.dispose();
}
}
});
}
function clearRoutes() {
while (routeVisuals.length) {
const visual = routeVisuals.pop();
graphRoot.remove(visual.group);
disposeObject(visual.group);
}
}
function createRouteVisual(path, color, zOffset, delay) {
const group = new THREE.Group();
graphRoot.add(group);
const segmentMeshes = [];
const halos = [];
const points = path.map((id) => nodePositions[id].clone());
const cumulative = [0];
let totalLength = 0;
for (let i = 1; i < points.length; i++) {
totalLength += points[i].distanceTo(points[i - 1]);
cumulative.push(totalLength);
const start = points[i - 1].clone();
const end = points[i].clone();
start.z = zOffset;
end.z = zOffset;
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.9,
roughness: 0.28,
metalness: 0.35,
transparent: true,
opacity: 0,
depthWrite: false
});
const rod = makeRod(start, end, 0.066, material);
rod.renderOrder = 5;
rod.userData.segmentIndex = i - 1;
group.add(rod);
segmentMeshes.push(rod);
}
for (let i = 0; i < path.length; i++) {
const halo = new THREE.Mesh(
new THREE.TorusGeometry(0.43, 0.028, 8, 48),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0,
depthWrite: false
})
);
halo.position.copy(points[i]);
halo.position.z = zOffset;
halo.userData.arrival = i * 0.24;
group.add(halo);
halos.push(halo);
}
const particle = new THREE.Mesh(
new THREE.SphereGeometry(0.105, 18, 12),
new THREE.MeshStandardMaterial({
color: 0xffffff,
emissive: color,
emissiveIntensity: 1.5,
roughness: 0.2,
transparent: true,
opacity: 0.95
})
);
particle.visible = path.length > 1;
group.add(particle);
const visual = {
group,
path,
color,
zOffset,
delay,
segmentMeshes,
halos,
particle,
points,
cumulative,
totalLength,
duration: Math.max(1.25, (path.length - 1) * 0.34)
};
routeVisuals.push(visual);
return visual;
}
function sampleRoute(visual, t) {
if (visual.points.length === 1) {
return visual.points[0].clone();
}
const distance = THREE.MathUtils.clamp(t, 0, 1) * visual.totalLength;
for (let i = 1; i < visual.cumulative.length; i++) {
if (distance <= visual.cumulative[i]) {
const previousDistance = visual.cumulative[i - 1];
const segmentDistance = visual.cumulative[i] - previousDistance;
const localT =
segmentDistance === 0
? 0
: (distance - previousDistance) / segmentDistance;
const point = new THREE.Vector3().lerpVectors(
visual.points[i - 1],
visual.points[i],
localT
);
point.z = visual.zOffset;
return point;
}
}
const point = visual.points.at(-1).clone();
point.z = visual.zOffset;
return point;
}
// ---------------------------------------------------------------------
// UI and search execution
// ---------------------------------------------------------------------
const sourceSelect = document.querySelector("#source");
const targetSelect = document.querySelector("#target");
const runButton = document.querySelector("#run");
const resetButton = document.querySelector("#reset");
for (const id of nodeIds) {
for (const select of [sourceSelect, targetSelect]) {
const option = document.createElement("option");
option.value = id;
option.textContent = id;
select.appendChild(option);
}
}
sourceSelect.value = "A";
targetSelect.value = "J";
let routeStartTime = performance.now() / 1000;
let routeAnimationEnd = 0;
function formatPath(path) {
return path.length ? path.join(" → ") : "No route";
}
function updateComparison(bfs, dijkstra) {
const comparison = document.querySelector("#comparison");
if (!bfs.path.length || !dijkstra.path.length) {
comparison.textContent = "No connected route exists for this selection.";
return;
}
if (bfs.hops === dijkstra.hops && bfs.cost === dijkstra.cost) {
comparison.textContent =
"Both objectives select the same optimal route.";
return;
}
const extraCost = bfs.cost - dijkstra.cost;
const extraHops = dijkstra.hops - bfs.hops;
const costPhrase =
extraCost === 0
? "The cheapest route also ties on edge count."
: `The fewest-hop route costs ${extraCost} more weight.`;
const hopPhrase =
extraHops === 0
? "It also ties on hop count."
: `The minimum-cost route uses ${extraHops} more hops.`;
comparison.textContent = `${costPhrase} ${hopPhrase}`;
}
function runSearches() {
const source = sourceSelect.value;
const target = targetSelect.value;
updateNodeStyles(source, target);
const bfs = breadthFirstSearch(source, target);
const dijkstra = dijkstraSearch(source, target);
document.querySelector("#bfsHops").textContent = bfs.hops;
document.querySelector("#bfsCost").textContent = bfs.cost;
document.querySelector("#bfsPath").textContent = formatPath(bfs.path);
document.querySelector("#bfsExplored").textContent =
`${bfs.visited.length} nodes reached in BFS order`;
document.querySelector("#dijkstraCost").textContent = dijkstra.cost;
document.querySelector("#dijkstraHops").textContent =
`${dijkstra.hops} hops`;
document.querySelector("#dijkstraPath").textContent =
formatPath(dijkstra.path);
document.querySelector("#dijkstraExplored").textContent =
`${dijkstra.visited.length} nodes settled by cost`;
updateComparison(bfs, dijkstra);
clearRoutes();
routeStartTime = performance.now() / 1000;
createRouteVisual(bfs.path, BFS_COLOR, 0.19, 0);
createRouteVisual(dijkstra.path, DIJKSTRA_COLOR, -0.19, 0.18);
routeAnimationEnd =
routeStartTime +
Math.max(
bfs.path.length * 0.24,
dijkstra.path.length * 0.24 + 0.18
) +
1.1;
document.querySelector("#statusText").textContent = "Revealing optima";
}
sourceSelect.addEventListener("change", runSearches);
targetSelect.addEventListener("change", runSearches);
runButton.addEventListener("click", runSearches);
// ---------------------------------------------------------------------
// Custom orbit, pan, pinch, and zoom controls
// ---------------------------------------------------------------------
const controls = {
target: new THREE.Vector3(0, 0.25, 0),
radius: 18,
theta: 0.1,
phi: Math.PI / 2 - 0.06
};
function updateCamera() {
const sinPhi = Math.sin(controls.phi);
const cosPhi = Math.cos(controls.phi);
camera.position.set(
controls.target.x + controls.radius * sinPhi * Math.sin(controls.theta),
controls.target.y + controls.radius * cosPhi,
controls.target.z + controls.radius * sinPhi * Math.cos(controls.theta)
);
camera.lookAt(controls.target);
}
function resetView() {
controls.target.set(0, 0.25, 0);
controls.radius = window.innerWidth < 620 ? 30 : 18;
controls.theta = 0.1;
controls.phi = Math.PI / 2 - 0.06;
updateCamera();
}
resetButton.addEventListener("click", resetView);
canvas.addEventListener("dblclick", resetView);
const pointers = new Map();
let movedDistance = 0;
let pinchDistance = 0;
canvas.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
canvas.addEventListener("pointerdown", (event) => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
movedDistance = 0;
if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
pinchDistance = Math.hypot(a.x - b.x, a.y - b.y);
}
});
canvas.addEventListener("pointermove", (event) => {
const previous = pointers.get(event.pointerId);
if (!previous) return;
const dx = event.clientX - previous.x;
const dy = event.clientY - previous.y;
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
movedDistance += Math.hypot(dx, dy);
if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
const nextDistance = Math.hypot(a.x - b.x, a.y - b.y);
if (pinchDistance > 0 && nextDistance > 0) {
controls.radius = THREE.MathUtils.clamp(
controls.radius * (pinchDistance / nextDistance),
9,
42
);
}
pinchDistance = nextDistance;
updateCamera();
return;
}
const wantsPan =
event.shiftKey ||
(event.buttons & 2) !== 0;
if (wantsPan) {
const forward = camera.getWorldDirection(new THREE.Vector3());
const right = new THREE.Vector3()
.crossVectors(forward, camera.up)
.normalize();
const up = new THREE.Vector3()
.crossVectors(right, forward)
.normalize();
const panScale = controls.radius / 650;
controls.target
.addScaledVector(right, -dx * panScale)
.addScaledVector(up, dy * panScale);
} else {
controls.theta -= dx * 0.006;
controls.phi = THREE.MathUtils.clamp(
controls.phi - dy * 0.006,
0.28,
Math.PI - 0.28
);
}
updateCamera();
});
canvas.addEventListener("pointerup", (event) => {
const wasClick =
movedDistance < 6 &&
event.button === 0 &&
pointers.size === 1;
pointers.delete(event.pointerId);
pinchDistance = 0;
if (wasClick) {
const rect = canvas.getBoundingClientRect();
const pointer = new THREE.Vector2(
((event.clientX - rect.left) / rect.width) * 2 - 1,
-((event.clientY - rect.top) / rect.height) * 2 + 1
);
const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(pointer, camera);
const hit = raycaster.intersectObjects(nodeMeshes, false)[0];
if (hit) {
const id = hit.object.userData.nodeId;
if (event.shiftKey) {
targetSelect.value = id;
} else {
sourceSelect.value = id;
}
runSearches();
}
}
});
canvas.addEventListener("pointercancel", (event) => {
pointers.delete(event.pointerId);
pinchDistance = 0;
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
controls.radius = THREE.MathUtils.clamp(
controls.radius * Math.exp(event.deltaY * 0.001),
9,
42
);
updateCamera();
},
{ passive: false }
);
// ---------------------------------------------------------------------
// Resize and render loop
// ---------------------------------------------------------------------
function onResize() {
const width = window.innerWidth;
const height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", onResize);
function animate(nowMilliseconds) {
requestAnimationFrame(animate);
const now = nowMilliseconds / 1000;
const elapsed = now - routeStartTime;
const pulse = (Math.sin(now * 2.2) + 1) * 0.5;
for (const visual of routeVisuals) {
const localTime = elapsed - visual.delay;
for (const mesh of visual.segmentMeshes) {
const reveal = THREE.MathUtils.clamp(
(localTime - mesh.userData.segmentIndex * 0.24) / 0.24,
0,
1
);
mesh.material.opacity = reveal * 0.96;
}
for (const halo of visual.halos) {
const reveal = THREE.MathUtils.clamp(
(localTime - halo.userData.arrival) / 0.24,
0,
1
);
halo.material.opacity = reveal * 0.72;
const haloScale = 1 + Math.sin(now * 3 + halo.userData.arrival) * 0.055;
halo.scale.setScalar(haloScale);
}
if (visual.path.length > 1) {
const progress = THREE.MathUtils.clamp(
localTime / visual.duration,
0,
1
);
visual.particle.visible = progress < 1;
visual.particle.position.copy(sampleRoute(visual, progress));
} else {
visual.particle.visible = false;
}
}
for (const id of nodeIds) {
const sphere = nodeMeshes.find((mesh) => mesh.userData.nodeId === id);
const base = 1 + pulse * 0.035;
sphere.scale.setScalar(base);
}
dust.rotation.z = now * 0.006;
if (now > routeAnimationEnd) {
const status = document.querySelector("#statusText");
if (status.textContent !== "Both searches complete") {
status.textContent = "Both searches complete";
}
}
renderer.render(scene, camera);
}
updateCamera();
runSearches();
requestAnimationFrame(animate);
</script>
</body>
</html>
```