Prompt specification
Build or customize the Three.js 3D scene "Weighted route graph table" 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: Weighted route graph table
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/weighted-route-graph-table-x1917
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring shortest paths in a weighted graph. Build a small connected graph with nonnegative edge costs and separate geometric lengths; show a least-cost path and its summed cost explicitly. Low-poly.
Working Three.js Starter (weighted-route-graph-table-x1917):
```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 — Shortest Cost Path</title>
<style>
:root {
color-scheme: dark;
--bg: #07131f;
--panel: rgba(8, 20, 33, 0.84);
--panel-strong: rgba(7, 17, 29, 0.94);
--line: rgba(154, 190, 214, 0.18);
--text: #e8f3fa;
--muted: #91a8b9;
--cyan: #52e2cd;
--gold: #ffd166;
--green: #8bf1a7;
--orange: #ffad5c;
}
* {
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;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
cursor: grab;
}
#scene canvas:active {
cursor: grabbing;
}
#label-layer {
position: fixed;
inset: 0;
z-index: 3;
overflow: hidden;
pointer-events: none;
}
.world-label {
position: absolute;
transform: translate(-50%, -50%);
white-space: nowrap;
user-select: none;
}
.node-label {
display: flex;
align-items: center;
gap: 6px;
padding: 4px 8px 4px 5px;
color: var(--text);
background: rgba(4, 13, 23, 0.84);
border: 1px solid rgba(170, 205, 225, 0.24);
border-radius: 999px;
box-shadow: 0 7px 22px rgba(0, 0, 0, 0.22);
backdrop-filter: blur(7px);
}
.node-letter {
display: grid;
place-items: center;
width: 22px;
height: 22px;
border-radius: 50%;
color: #06121c;
background: #8ba5b8;
font-size: 12px;
font-weight: 900;
}
.node-label.source .node-letter {
color: #291405;
background: var(--orange);
}
.node-label.target .node-letter {
color: #062313;
background: var(--green);
}
.node-label.on-path .node-letter {
color: #05231e;
background: var(--cyan);
}
.node-role {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.edge-label {
padding: 3px 7px;
color: #c1d0dc;
background: rgba(5, 15, 25, 0.8);
border: 1px solid rgba(152, 183, 203, 0.17);
border-radius: 999px;
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.2);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.015em;
backdrop-filter: blur(5px);
}
.edge-label.on-path {
color: #ffe29a;
border-color: rgba(255, 209, 102, 0.45);
background: rgba(55, 42, 12, 0.82);
}
.panel {
position: fixed;
z-index: 10;
overflow: hidden;
background: var(--panel);
border: 1px solid var(--line);
border-radius: 16px;
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(16px);
}
.title-panel {
top: 16px;
left: 16px;
width: 330px;
padding: 18px 19px 16px;
}
.eyebrow {
margin-bottom: 7px;
color: var(--cyan);
font-size: 10px;
font-weight: 900;
letter-spacing: 0.19em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 20px;
line-height: 1.15;
letter-spacing: -0.025em;
}
.intro {
margin: 9px 0 13px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.chip-row {
display: flex;
flex-wrap: wrap;
gap: 7px;
}
.chip {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 5px 8px;
border: 1px solid var(--line);
border-radius: 999px;
color: #c4d4df;
background: rgba(255, 255, 255, 0.025);
font-size: 10px;
font-weight: 800;
}
.chip::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
content: "";
}
.chip.source::before {
background: var(--orange);
}
.chip.target::before {
background: var(--green);
}
.result-panel {
top: 16px;
right: 16px;
width: 360px;
padding: 18px;
}
.result-panel .eyebrow {
color: var(--gold);
}
.route {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 7px;
margin: 11px 0 15px;
font-size: 18px;
font-weight: 850;
}
.route-node {
display: grid;
place-items: center;
min-width: 30px;
height: 30px;
padding: 0 7px;
color: #05231e;
background: var(--cyan);
border-radius: 9px;
}
.route-node:first-child {
color: #291405;
background: var(--orange);
}
.route-node:last-child {
color: #062313;
background: var(--green);
}
.route-arrow {
color: #61798a;
font-size: 14px;
}
.equation {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 15px;
padding: 12px 13px;
border: 1px solid rgba(255, 209, 102, 0.23);
border-radius: 12px;
background: rgba(255, 209, 102, 0.065);
}
.equation span {
color: var(--muted);
font-size: 10px;
font-weight: 900;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.equation strong {
color: var(--gold);
font-size: 18px;
white-space: nowrap;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-top: 10px;
}
.metric {
padding: 10px 11px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.025);
}
.metric small {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric b {
font-size: 13px;
}
.legend {
margin: 12px 1px 0;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.legend strong {
color: #c7d8e4;
}
.edge-panel {
bottom: 16px;
left: 16px;
width: 360px;
max-height: 310px;
padding: 0;
overflow-y: auto;
}
.edge-panel summary {
padding: 13px 16px;
color: #d8e7f0;
font-size: 11px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
cursor: pointer;
list-style: none;
}
.edge-panel summary::-webkit-details-marker {
display: none;
}
.edge-panel summary::after {
float: right;
color: var(--muted);
content: "+";
font-size: 16px;
line-height: 0.8;
}
.edge-panel[open] summary::after {
content: "−";
}
.table-wrap {
padding: 0 10px 10px;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 11px;
}
th,
td {
padding: 7px 8px;
border-bottom: 1px solid rgba(154, 190, 214, 0.1);
text-align: left;
}
th {
color: var(--muted);
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
td:nth-child(2) {
color: var(--gold);
font-weight: 850;
}
td:nth-child(3) {
color: #b8cad7;
font-variant-numeric: tabular-nums;
}
tr.route-row td {
color: #fff1c9;
background: rgba(82, 226, 205, 0.07);
}
tr.route-row td:first-child {
border-left: 2px solid var(--cyan);
}
.table-note {
padding: 9px 16px 13px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.controls-panel {
right: 16px;
bottom: 16px;
width: 280px;
padding: 12px;
}
.control-row {
display: flex;
align-items: center;
gap: 7px;
margin-bottom: 9px;
}
button {
padding: 7px 10px;
color: #dceaf3;
background: rgba(255, 255, 255, 0.045);
border: 1px solid var(--line);
border-radius: 8px;
font: inherit;
font-size: 11px;
font-weight: 750;
cursor: pointer;
}
button:hover {
color: var(--cyan);
border-color: rgba(82, 226, 205, 0.42);
background: rgba(82, 226, 205, 0.08);
}
.control-copy {
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.fallback {
position: fixed;
inset: 0;
z-index: 100;
display: grid;
place-items: center;
padding: 30px;
color: white;
background: #07131f;
text-align: center;
}
@media (max-width: 800px) {
.title-panel {
top: 10px;
left: 10px;
width: calc(100% - 20px);
padding: 14px 15px;
}
h1 {
font-size: 18px;
}
.intro {
margin-bottom: 10px;
}
.result-panel {
top: 139px;
right: 10px;
left: 10px;
width: auto;
padding: 14px;
}
.route {
margin: 8px 0 10px;
}
.edge-panel {
bottom: 10px;
left: 10px;
width: calc(100% - 20px);
max-height: 190px;
}
.controls-panel {
display: none;
}
.node-role {
display: none;
}
.edge-label {
padding: 2px 5px;
font-size: 9px;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div id="label-layer"></div>
<header class="panel title-panel">
<div class="eyebrow">Weighted Graph / Dijkstra</div>
<h1>Shortest cost, not shortest distance</h1>
<p class="intro">
Edge costs are independent weights. Geometric length is the measured
distance between endpoints. The route is computed at runtime.
</p>
<div class="chip-row">
<span class="chip source">Source A</span>
<span class="chip target">Target G</span>
<span class="chip">7 nodes · 10 links</span>
</div>
</header>
<section class="panel result-panel" aria-live="polite">
<div class="eyebrow">Least-Cost Path</div>
<div id="route" class="route"></div>
<div class="equation">
<span>Summed edge cost</span>
<strong id="cost-equation"></strong>
</div>
<div class="metric-grid">
<div class="metric">
<small>Path geometric length</small>
<b id="path-length"></b>
</div>
<div class="metric">
<small>Algorithm</small>
<b>Dijkstra</b>
</div>
</div>
<p class="legend">
<strong>Visual encoding:</strong> edge length is geometric distance;
edge thickness and labels represent cost. All listed costs are nonnegative.
</p>
</section>
<details class="panel edge-panel" open>
<summary>Edge costs and geometric lengths</summary>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Edge</th>
<th>Cost</th>
<th>Geometric length</th>
</tr>
</thead>
<tbody id="edge-table"></tbody>
</table>
</div>
<div class="table-note">
Lengths are Euclidean distances between edge endpoints in scene units.
Highlighted rows belong to the least-cost path.
</div>
</details>
<aside class="panel controls-panel">
<div class="control-row">
<button id="zoom-in" type="button">Zoom +</button>
<button id="zoom-out" type="button">Zoom −</button>
<button id="reset-view" type="button">Reset</button>
</div>
<div class="control-copy">
Left drag: orbit · Right drag: pan · Wheel: zoom<br>
Touch: drag to orbit · Pinch to zoom · Double-click: reset
</div>
</aside>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Graph data. Costs are deliberately independent of geometric lengths.
// -------------------------------------------------------------------------
const nodes = [
{ id: "A", x: -5.0, z: 2.8, role: "source" },
{ id: "B", x: -2.3, z: 5.0, role: "node" },
{ id: "C", x: 1.2, z: 4.2, role: "node" },
{ id: "D", x: 4.4, z: 2.2, role: "node" },
{ id: "E", x: 1.0, z: -0.5, role: "node" },
{ id: "F", x: -3.1, z: -1.9, role: "node" },
{ id: "G", x: -0.5, z: -5.1, role: "target" }
];
const edgeDefinitions = [
{ id: "AB", a: "A", b: "B", cost: 2, offset: [ 0.00, 0.12] },
{ id: "BC", a: "B", b: "C", cost: 5, offset: [ 0.10, 0.16] },
{ id: "CD", a: "C", b: "D", cost: 1, offset: [ 0.13, 0.08] },
{ id: "DE", a: "D", b: "E", cost: 2, offset: [ 0.12, 0.00] },
{ id: "EF", a: "E", b: "F", cost: 2, offset: [-0.12, 0.02] },
{ id: "FA", a: "F", b: "A", cost: 6, offset: [-0.16, 0.05] },
{ id: "BE", a: "B", b: "E", cost: 1, offset: [-0.13, -0.06] },
{ id: "CE", a: "C", b: "E", cost: 1, offset: [ 0.24, -0.04] },
{ id: "CG", a: "C", b: "G", cost: 3, offset: [ 0.18, 0.02] },
{ id: "FG", a: "F", b: "G", cost: 1, offset: [ 0.08, -0.12] }
];
const SOURCE = "A";
const TARGET = "G";
const NODE_Y = 0.90;
const EDGE_Y = 0.38;
const nodeById = new Map(nodes.map(node => [node.id, node]));
const edges = edgeDefinitions.map(edge => {
const a = nodeById.get(edge.a);
const b = nodeById.get(edge.b);
const pointA = new THREE.Vector3(a.x, EDGE_Y, a.z);
const pointB = new THREE.Vector3(b.x, EDGE_Y, b.z);
return {
...edge,
pointA,
pointB,
midpoint: pointA.clone().add(pointB).multiplyScalar(0.5),
length: pointA.distanceTo(pointB)
};
});
// -------------------------------------------------------------------------
// Dijkstra shortest-path calculation.
// -------------------------------------------------------------------------
function dijkstra(source, target) {
const adjacency = new Map(nodes.map(node => [node.id, []]));
for (const edge of edges) {
adjacency.get(edge.a).push({ to: edge.b, cost: edge.cost, edge });
adjacency.get(edge.b).push({ to: edge.a, cost: edge.cost, edge });
}
const distance = Object.fromEntries(nodes.map(node => [node.id, Infinity]));
const previous = {};
const visited = new Set();
distance[source] = 0;
while (visited.size < nodes.length) {
let current = null;
let bestDistance = Infinity;
for (const node of nodes) {
if (!visited.has(node.id) && distance[node.id] < bestDistance) {
current = node.id;
bestDistance = distance[node.id];
}
}
if (current === null || current === target) break;
visited.add(current);
for (const connection of adjacency.get(current)) {
const candidate = distance[current] + connection.cost;
if (candidate < distance[connection.to]) {
distance[connection.to] = candidate;
previous[connection.to] = {
node: current,
edge: connection.edge.id
};
}
}
}
if (!Number.isFinite(distance[target])) return null;
const pathNodes = [target];
const pathEdges = [];
let cursor = target;
while (cursor !== source) {
const step = previous[cursor];
if (!step) return null;
pathEdges.unshift(step.edge);
cursor = step.node;
pathNodes.unshift(cursor);
}
return {
distance: distance[target],
pathNodes,
pathEdges
};
}
const shortest = dijkstra(SOURCE, TARGET);
const pathNodeIds = new Set(shortest.pathNodes);
const pathEdgeIds = new Set(shortest.pathEdges);
// -------------------------------------------------------------------------
// UI values.
// -------------------------------------------------------------------------
const routeElement = document.querySelector("#route");
const costEquationElement = document.querySelector("#cost-equation");
const pathLengthElement = document.querySelector("#path-length");
const edgeTableElement = document.querySelector("#edge-table");
routeElement.innerHTML = shortest.pathNodes.map((id, index) => {
const arrow = index < shortest.pathNodes.length - 1
? '<span class="route-arrow">→</span>'
: "";
return `<span class="route-node">${id}</span>${arrow}`;
}).join("");
const pathEdgeObjects = shortest.pathEdges.map(id =>
edges.find(edge => edge.id === id)
);
const costTerms = pathEdgeObjects.map(edge => edge.cost).join(" + ");
const geometricPathLength = pathEdgeObjects.reduce(
(sum, edge) => sum + edge.length,
0
);
costEquationElement.textContent = `${costTerms} = ${shortest.distance}`;
pathLengthElement.textContent = `${geometricPathLength.toFixed(2)} units`;
edgeTableElement.innerHTML = edges.map(edge => {
const onPath = pathEdgeIds.has(edge.id);
return `
<tr class="${onPath ? "route-row" : ""}">
<td>${edge.a} — ${edge.b}</td>
<td>${edge.cost}</td>
<td>${edge.length.toFixed(2)}</td>
</tr>
`;
}).join("");
// -------------------------------------------------------------------------
// Three.js renderer and scene.
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07131f);
scene.fog = new THREE.Fog(0x07131f, 19, 38);
let renderer;
try {
renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
} catch (error) {
document.body.innerHTML = `
<div class="fallback">
<div>
<h2>WebGL could not be initialized</h2>
<p>Please open this scene in a browser with WebGL enabled.</p>
</div>
</div>
`;
throw error;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
const canvas = renderer.domElement;
canvas.tabIndex = 0;
canvas.setAttribute(
"aria-label",
"Interactive 3D weighted graph. Drag to orbit, wheel to zoom, right-drag to pan."
);
document.querySelector("#scene").appendChild(canvas);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const hemisphereLight = new THREE.HemisphereLight(
0xb8ddff,
0x18212a,
1.75
);
scene.add(hemisphereLight);
const keyLight = new THREE.DirectionalLight(0xffe7c7, 3.2);
keyLight.position.set(-7, 13, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -13;
keyLight.shadow.camera.right = 13;
keyLight.shadow.camera.top = 13;
keyLight.shadow.camera.bottom = -13;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x43d9e8, 1.15);
rimLight.position.set(9, 7, -10);
scene.add(rimLight);
// -------------------------------------------------------------------------
// Low-poly faceted terrain.
// -------------------------------------------------------------------------
function terrainHeight(x, z) {
return -0.28
+ 0.065 * Math.sin(x * 0.72)
+ 0.055 * Math.cos(z * 0.61)
+ 0.025 * Math.sin((x + z) * 1.35);
}
const terrainSource = new THREE.PlaneGeometry(24, 22, 10, 10);
terrainSource.rotateX(-Math.PI / 2);
const terrainPositions = terrainSource.attributes.position;
for (let i = 0; i < terrainPositions.count; i++) {
const x = terrainPositions.getX(i);
const z = terrainPositions.getZ(i);
terrainPositions.setY(i, terrainHeight(x, z));
}
terrainSource.computeVertexNormals();
const terrainGeometry = terrainSource.toNonIndexed();
terrainGeometry.computeVertexNormals();
const terrainPalette = [
new THREE.Color(0x102b38),
new THREE.Color(0x123340),
new THREE.Color(0x153744),
new THREE.Color(0x183b46),
new THREE.Color(0x1c404a)
];
const terrainColors = new Float32Array(
terrainGeometry.attributes.position.count * 3
);
for (let i = 0; i < terrainGeometry.attributes.position.count; i += 3) {
const x =
(terrainGeometry.attributes.position.getX(i) +
terrainGeometry.attributes.position.getX(i + 1) +
terrainGeometry.attributes.position.getX(i + 2)) / 3;
const z =
(terrainGeometry.attributes.position.getZ(i) +
terrainGeometry.attributes.position.getZ(i + 1) +
terrainGeometry.attributes.position.getZ(i + 2)) / 3;
const colorIndex = Math.floor(
Math.abs(Math.sin(x * 1.37 + z * 1.91)) * terrainPalette.length
) % terrainPalette.length;
const color = terrainPalette[colorIndex];
for (let vertex = 0; vertex < 3; vertex++) {
const offset = (i + vertex) * 3;
terrainColors[offset] = color.r;
terrainColors[offset + 1] = color.g;
terrainColors[offset + 2] = color.b;
}
}
terrainGeometry.setAttribute(
"color",
new THREE.BufferAttribute(terrainColors, 3)
);
const terrain = new THREE.Mesh(
terrainGeometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
flatShading: true,
roughness: 1,
metalness: 0
})
);
terrain.receiveShadow = true;
scene.add(terrain);
// Subtle terrain grid following the faceted ground.
const gridVertices = [];
for (let x = -10.5; x <= 10.5; x += 1.5) {
for (let z = -9.75; z < 9.75; z += 0.75) {
const z2 = z + 0.75;
gridVertices.push(
x, terrainHeight(x, z) + 0.018, z,
x, terrainHeight(x, z2) + 0.018, z2
);
}
}
for (let z = -9; z <= 9; z += 1.5) {
for (let x = -10.5; x < 10.5; x += 0.75) {
const x2 = x + 0.75;
gridVertices.push(
x, terrainHeight(x, z) + 0.018, z,
x2, terrainHeight(x2, z) + 0.018, z
);
}
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridVertices, 3)
);
scene.add(new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x83c9d8,
transparent: true,
opacity: 0.085
})
));
// Deterministic low-poly boulders around the graph.
function seededRandom(seed) {
return function () {
seed |= 0;
seed = seed + 0x6D2B79F5 | 0;
let value = Math.imul(seed ^ seed >>> 15, 1 | seed);
value = value + Math.imul(value ^ value >>> 7, 61 | value) ^ value;
return ((value ^ value >>> 14) >>> 0) / 4294967296;
};
}
const random = seededRandom(1937);
const boulderGeometry = new THREE.DodecahedronGeometry(0.35, 0);
const boulderMaterials = [
new THREE.MeshStandardMaterial({
color: 0x173640,
roughness: 0.94,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: 0x1b414b,
roughness: 0.94,
flatShading: true
})
];
let boulderCount = 0;
let attempts = 0;
while (boulderCount < 25 && attempts++ < 300) {
const x = random() * 21 - 10.5;
const z = random() * 18 - 9;
const nearestNode = Math.min(...nodes.map(node =>
Math.hypot(x - node.x, z - node.z)
));
if (nearestNode < 5.4) continue;
const scaleX = 0.55 + random() * 1.1;
const scaleY = 0.45 + random() * 1.1;
const scaleZ = 0.55 + random() * 1.1;
const boulder = new THREE.Mesh(
boulderGeometry,
boulderMaterials[boulderCount % boulderMaterials.length]
);
boulder.position.set(
x,
terrainHeight(x, z) + 0.24 * scaleY,
z
);
boulder.scale.set(scaleX, scaleY, scaleZ);
boulder.rotation.set(random() * 0.5, random() * Math.PI, random() * 0.4);
boulder.castShadow = true;
boulder.receiveShadow = true;
scene.add(boulder);
boulderCount++;
}
// -------------------------------------------------------------------------
// Graph edges.
// -------------------------------------------------------------------------
const labelLayer = document.querySelector("#label-layer");
const edgeLabels = [];
const nodeLabels = [];
const pathEdgeMaterials = [];
const nodeMeshes = [];
const targetRings = [];
const upVector = new THREE.Vector3(0, 1, 0);
for (const edge of edges) {
const onPath = pathEdgeIds.has(edge.id);
const direction = edge.pointB.clone().sub(edge.pointA);
const radius = 0.035 + edge.cost * 0.009 + (onPath ? 0.025 : 0);
const geometry = new THREE.CylinderGeometry(
radius,
radius,
edge.length,
6,
1,
false
);
const material = new THREE.MeshStandardMaterial({
color: onPath ? 0x43d8c5 : 0x526a7d,
emissive: onPath ? 0x0b6259 : 0x000000,
emissiveIntensity: onPath ? 0.42 : 0,
roughness: 0.48,
metalness: 0.18,
flatShading: true
});
if (onPath) pathEdgeMaterials.push(material);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(edge.midpoint);
mesh.quaternion.setFromUnitVectors(
upVector,
direction.clone().normalize()
);
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
// A small faceted weight marker at each edge midpoint.
const marker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.105 + edge.cost * 0.012, 0),
new THREE.MeshStandardMaterial({
color: onPath ? 0xffd166 : 0x71899b,
emissive: onPath ? 0x5d4107 : 0x000000,
emissiveIntensity: onPath ? 0.35 : 0,
roughness: 0.4,
metalness: 0.25,
flatShading: true
})
);
marker.position.copy(edge.midpoint);
marker.position.y += 0.04;
marker.castShadow = true;
scene.add(marker);
const label = document.createElement("div");
label.className = `world-label edge-label${onPath ? " on-path" : ""}`;
label.textContent = `w ${edge.cost} · ℓ ${edge.length.toFixed(2)}`;
labelLayer.appendChild(label);
edgeLabels.push({
element: label,
position: edge.midpoint.clone().add(
new THREE.Vector3(edge.offset[0], 0.28, edge.offset[1])
)
});
}
// -------------------------------------------------------------------------
// Graph nodes.
// -------------------------------------------------------------------------
const nodeGeometry = new THREE.OctahedronGeometry(0.58, 0);
const nodeOutlineGeometry = new THREE.EdgesGeometry(nodeGeometry);
for (const node of nodes) {
const isSource = node.role === "source";
const isTarget = node.role === "target";
const onPath = pathNodeIds.has(node.id);
let color = 0x6f88a4;
let emissive = 0x000000;
let emissiveIntensity = 0;
if (isSource) {
color = 0xffad5c;
emissive = 0x6b2f05;
emissiveIntensity = 0.18;
} else if (isTarget) {
color = 0x8bf1a7;
emissive = 0x145c2c;
emissiveIntensity = 0.18;
} else if (onPath) {
color = 0x52e2cd;
emissive = 0x0b5f56;
emissiveIntensity = 0.18;
}
const material = new THREE.MeshStandardMaterial({
color,
emissive,
emissiveIntensity,
roughness: 0.48,
metalness: 0.22,
flatShading: true
});
const mesh = new THREE.Mesh(nodeGeometry, material);
mesh.position.set(node.x, NODE_Y, node.z);
mesh.rotation.set(0.18, 0.45, 0.08);
mesh.castShadow = true;
mesh.receiveShadow = true;
const baseScale = isSource || isTarget ? 1.15 : onPath ? 1.08 : 1;
mesh.scale.setScalar(baseScale);
mesh.userData.baseScale = baseScale;
mesh.userData.phase = nodes.indexOf(node) * 0.65;
const outline = new THREE.LineSegments(
nodeOutlineGeometry,
new THREE.LineBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.24
})
);
mesh.add(outline);
scene.add(mesh);
nodeMeshes.push(mesh);
if (isSource || isTarget) {
const ring = new THREE.Mesh(
new THREE.RingGeometry(0.76, 0.88, 24),
new THREE.MeshBasicMaterial({
color: isSource ? 0xffad5c : 0x8bf1a7,
transparent: true,
opacity: 0.65,
side: THREE.DoubleSide,
depthWrite: false
})
);
ring.rotation.x = -Math.PI / 2;
ring.position.set(
node.x,
terrainHeight(node.x, node.z) + 0.04,
node.z
);
scene.add(ring);
targetRings.push(ring);
}
const label = document.createElement("div");
label.className = [
"world-label",
"node-label",
isSource ? "source" : "",
isTarget ? "target" : "",
onPath ? "on-path" : ""
].filter(Boolean).join(" ");
const roleText = isSource
? "source"
: isTarget
? "target"
: onPath
? "route"
: "";
label.innerHTML = `
<span class="node-letter">${node.id}</span>
<span class="node-role">${roleText}</span>
`;
labelLayer.appendChild(label);
nodeLabels.push({
element: label,
position: new THREE.Vector3(node.x, NODE_Y + 1.16, node.z)
});
}
// -------------------------------------------------------------------------
// Animated marker traveling along the selected path.
// -------------------------------------------------------------------------
const routePoints = shortest.pathNodes.map(id => {
const node = nodeById.get(id);
return new THREE.Vector3(node.x, EDGE_Y + 0.18, node.z);
});
const routeSegments = [];
for (let i = 0; i < routePoints.length - 1; i++) {
routeSegments.push({
start: routePoints[i],
end: routePoints[i + 1],
length: routePoints[i].distanceTo(routePoints[i + 1])
});
}
const routeLength = routeSegments.reduce(
(sum, segment) => sum + segment.length,
0
);
const routeMarker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.17, 0),
new THREE.MeshStandardMaterial({
color: 0xffd166,
emissive: 0x8f5a00,
emissiveIntensity: 1.2,
roughness: 0.3,
metalness: 0.2,
flatShading: true
})
);
routeMarker.castShadow = true;
scene.add(routeMarker);
// -------------------------------------------------------------------------
// Camera controls implemented directly, without Three.js addons.
// -------------------------------------------------------------------------
const controls = {
target: new THREE.Vector3(-0.2, 0.25, 0),
radius: 17,
theta: 0.58,
phi: 0.94
};
const defaultCamera = {
target: controls.target.clone(),
radius: controls.radius,
theta: controls.theta,
phi: controls.phi
};
function updateCamera() {
const sinPhi = Math.sin(controls.phi);
camera.position.set(
controls.target.x + controls.radius * sinPhi * Math.sin(controls.theta),
controls.target.y + controls.radius * Math.cos(controls.phi),
controls.target.z + controls.radius * sinPhi * Math.cos(controls.theta)
);
camera.lookAt(controls.target);
camera.updateMatrixWorld();
}
function resetCamera() {
controls.target.copy(defaultCamera.target);
controls.radius = defaultCamera.radius;
controls.theta = defaultCamera.theta;
controls.phi = defaultCamera.phi;
updateCamera();
}
function zoomBy(factor) {
controls.radius = THREE.MathUtils.clamp(
controls.radius * factor,
8,
31
);
updateCamera();
}
function panCamera(deltaX, deltaY) {
camera.updateMatrixWorld();
const right = new THREE.Vector3()
.setFromMatrixColumn(camera.matrix, 0);
right.y = 0;
right.normalize();
const forward = new THREE.Vector3()
.subVectors(controls.target, camera.position);
forward.y = 0;
forward.normalize();
const scale = controls.radius / window.innerHeight * 1.25;
controls.target
.addScaledVector(right, -deltaX * scale)
.addScaledVector(forward, -deltaY * scale);
controls.target.x = THREE.MathUtils.clamp(controls.target.x, -6, 6);
controls.target.z = THREE.MathUtils.clamp(controls.target.z, -6, 6);
updateCamera();
}
const pointers = new Map();
let lastPinchDistance = 0;
let lastPinchCenter = null;
function pointerDistance() {
const values = [...pointers.values()];
if (values.length < 2) return 0;
return Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
function pointerCenter() {
const values = [...pointers.values()];
if (values.length < 2) return null;
return {
x: (values[0].x + values[1].x) * 0.5,
y: (values[0].y + values[1].y) * 0.5
};
}
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("pointerdown", event => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 2) {
lastPinchDistance = pointerDistance();
lastPinchCenter = pointerCenter();
}
});
canvas.addEventListener("pointermove", event => {
const previous = pointers.get(event.pointerId);
if (!previous) return;
const current = {
x: event.clientX,
y: event.clientY
};
pointers.set(event.pointerId, current);
if (pointers.size >= 2) {
const distance = pointerDistance();
const center = pointerCenter();
if (lastPinchDistance > 0 && distance > 0) {
zoomBy(lastPinchDistance / distance);
}
if (lastPinchCenter && center) {
panCamera(
center.x - lastPinchCenter.x,
center.y - lastPinchCenter.y
);
}
lastPinchDistance = distance;
lastPinchCenter = center;
return;
}
const deltaX = current.x - previous.x;
const deltaY = current.y - previous.y;
if (event.pointerType === "mouse" && (event.buttons & 2)) {
panCamera(deltaX, deltaY);
} else {
controls.theta -= deltaX * 0.006;
controls.phi = THREE.MathUtils.clamp(
controls.phi - deltaY * 0.006,
0.28,
1.43
);
updateCamera();
}
});
function endPointer(event) {
pointers.delete(event.pointerId);
if (pointers.size < 2) {
lastPinchDistance = 0;
lastPinchCenter = null;
}
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener("wheel", event => {
event.preventDefault();
zoomBy(Math.exp(event.deltaY * 0.001));
}, { passive: false });
canvas.addEventListener("dblclick", resetCamera);
window.addEventListener("keydown", event => {
if (event.target instanceof HTMLInputElement) return;
if (event.key === "+" || event.key === "=") zoomBy(0.9);
if (event.key === "-" || event.key === "_") zoomBy(1.1);
if (event.key.toLowerCase() === "r") resetCamera();
});
document.querySelector("#zoom-in").addEventListener("click", () => zoomBy(0.86));
document.querySelector("#zoom-out").addEventListener("click", () => zoomBy(1.16));
document.querySelector("#reset-view").addEventListener("click", resetCamera);
// -------------------------------------------------------------------------
// Label projection and render loop.
// -------------------------------------------------------------------------
const projected = new THREE.Vector3();
function projectLabel(label) {
projected.copy(label.position).project(camera);
const visible = projected.z > -1 && projected.z < 1;
label.element.style.display = visible ? "flex" : "none";
if (!visible) return;
label.element.style.left =
`${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
label.element.style.top =
`${(-projected.y * 0.5 + 0.5) * window.innerHeight}px`;
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
const reducedMotion = window.matchMedia(
"(prefers-reduced-motion: reduce)"
).matches;
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const elapsed = reducedMotion ? 0 : clock.getElapsedTime();
for (const node of nodeMeshes) {
if (pathNodeIds.has(
node.position.x === undefined ? "" : ""
)) {
// Kept separate from the pulse below for clarity.
}
const pulse = 1 + Math.sin(elapsed * 2.2 + node.userData.phase) * 0.025;
node.scale.setScalar(node.userData.baseScale * pulse);
}
for (const ring of targetRings) {
const scale = 1 + Math.sin(elapsed * 2) * 0.06;
ring.scale.setScalar(scale);
}
for (const material of pathEdgeMaterials) {
material.emissiveIntensity =
0.40 + Math.sin(elapsed * 2.4) * 0.10;
}
if (routeLength > 0) {
let distance = (elapsed * 1.65) % routeLength;
for (const segment of routeSegments) {
if (distance <= segment.length) {
const amount = segment.length === 0
? 0
: distance / segment.length;
routeMarker.position.lerpVectors(
segment.start,
segment.end,
amount
);
break;
}
distance -= segment.length;
}
routeMarker.rotation.x += 0.025;
routeMarker.rotation.y += 0.035;
}
for (const label of nodeLabels) projectLabel(label);
for (const label of edgeLabels) projectLabel(label);
renderer.render(scene, camera);
}
updateCamera();
animate();
</script>
</body>
</html>
```