Prompt specification
Build or customize the Three.js 3D scene "Prerequisite Graph Repair Puzzle" 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: Prerequisite Graph Repair Puzzle
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/prerequisite-graph-repair-puzzle-x3584
Scene Description Prompt:
Make a low-poly Three.js scene in a self-contained HTML file using cdnjs: prerequisite graph repair puzzle. Create a strategy board containing an intentionally circular dependency. Let players inspect the deadlock and revise one rule to produce a valid progression path.
Working Three.js Starter (prerequisite-graph-repair-puzzle-x3584):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#090d16" />
<title>Deadlock — Foundry Protocol</title>
<style>
:root {
color-scheme: dark;
--bg: #090d16;
--panel: rgba(14, 20, 34, 0.88);
--panel-strong: rgba(18, 26, 43, 0.96);
--line: rgba(156, 184, 224, 0.17);
--text: #eef5ff;
--muted: #8d9bb4;
--cyan: #69e7ff;
--mint: #6af0c2;
--gold: #ffd166;
--danger: #ff5878;
--warning: #ffb45e;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button,
select {
font: inherit;
}
button {
color: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
outline: none;
touch-action: none;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 50% 42%, transparent 30%, rgba(2, 5, 11, 0.35) 100%),
linear-gradient(180deg, rgba(8, 12, 21, 0.1), rgba(8, 12, 21, 0.34));
z-index: 2;
}
.topbar {
position: fixed;
z-index: 10;
top: 0;
left: 0;
right: 0;
height: 82px;
padding: 18px 24px;
display: flex;
align-items: center;
justify-content: space-between;
pointer-events: none;
background: linear-gradient(180deg, rgba(6, 10, 18, 0.86), transparent);
}
.brand {
display: flex;
align-items: center;
gap: 13px;
}
.brand-mark {
width: 42px;
height: 42px;
display: grid;
place-items: center;
position: relative;
border: 1px solid rgba(105, 231, 255, 0.42);
background: rgba(105, 231, 255, 0.08);
clip-path: polygon(25% 6%, 75% 6%, 100% 50%, 75% 94%, 25% 94%, 0 50%);
box-shadow: inset 0 0 20px rgba(105, 231, 255, 0.1);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
width: 14px;
height: 2px;
background: var(--cyan);
box-shadow: 0 0 10px var(--cyan);
}
.brand-mark::before {
transform: rotate(45deg);
}
.brand-mark::after {
transform: rotate(-45deg);
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
h1 {
margin: 2px 0 0;
font-size: clamp(18px, 2vw, 25px);
line-height: 1;
letter-spacing: 0.045em;
font-weight: 850;
}
.top-actions {
display: flex;
align-items: center;
gap: 9px;
pointer-events: auto;
}
.status-pill,
.ghost-button {
min-height: 38px;
padding: 0 14px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(11, 17, 29, 0.76);
backdrop-filter: blur(14px);
font-size: 11px;
font-weight: 750;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.status-pill {
display: flex;
align-items: center;
gap: 8px;
}
.status-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--danger);
box-shadow: 0 0 12px var(--danger);
}
.status-pill.good .status-dot {
background: var(--mint);
box-shadow: 0 0 12px var(--mint);
}
.ghost-button {
cursor: pointer;
transition: border-color 160ms ease, background 160ms ease, transform 160ms ease;
}
.ghost-button:hover {
border-color: rgba(105, 231, 255, 0.5);
background: rgba(105, 231, 255, 0.09);
transform: translateY(-1px);
}
.panel {
position: fixed;
z-index: 8;
border: 1px solid var(--line);
background:
linear-gradient(135deg, rgba(255, 255, 255, 0.025), transparent 40%),
var(--panel);
box-shadow:
0 20px 60px rgba(0, 0, 0, 0.32),
inset 0 1px rgba(255, 255, 255, 0.035);
backdrop-filter: blur(18px) saturate(125%);
overflow: hidden;
}
.panel::before {
content: "";
position: absolute;
top: 0;
left: 20px;
width: 76px;
height: 1px;
background: linear-gradient(90deg, var(--cyan), transparent);
}
.brief {
left: 24px;
top: 102px;
width: 310px;
padding: 20px;
border-radius: 18px;
}
.panel-title {
margin: 0 0 7px;
font-size: 19px;
letter-spacing: -0.02em;
}
.copy {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.6;
}
.divider {
height: 1px;
margin: 17px 0;
background: var(--line);
}
.metric-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.metric {
min-height: 64px;
padding: 11px 12px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.018);
}
.metric-label {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.metric-value {
display: block;
margin-top: 7px;
font-size: 16px;
font-weight: 800;
}
.metric-value.danger {
color: var(--danger);
}
.metric-value.mint {
color: var(--mint);
}
.section-label {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
color: var(--muted);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.deadlock-strip {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 7px;
}
.node-chip {
padding: 7px 9px;
border: 1px solid rgba(255, 88, 120, 0.25);
border-radius: 8px;
background: rgba(255, 88, 120, 0.08);
color: #ff91a5;
cursor: pointer;
font-size: 10px;
font-weight: 750;
transition: background 150ms ease, border-color 150ms ease;
}
.node-chip:hover {
border-color: rgba(255, 88, 120, 0.65);
background: rgba(255, 88, 120, 0.15);
}
.cycle-arrow {
color: var(--danger);
font-size: 12px;
font-weight: 900;
}
.path-list {
display: flex;
flex-direction: column;
gap: 6px;
}
.path-step {
position: relative;
padding: 8px 10px 8px 30px;
border-left: 1px solid rgba(106, 240, 194, 0.4);
color: #cbd8e7;
font-size: 11px;
}
.path-step::before {
content: "";
position: absolute;
top: 13px;
left: -4px;
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--mint);
box-shadow: 0 0 9px rgba(106, 240, 194, 0.75);
}
.empty-state {
padding: 12px;
border: 1px dashed rgba(255, 88, 120, 0.25);
border-radius: 10px;
color: #a98a96;
background: rgba(255, 88, 120, 0.035);
font-size: 11px;
line-height: 1.5;
}
.inspector {
right: 24px;
top: 102px;
width: 344px;
padding: 20px;
border-radius: 18px;
}
.inspector-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 15px;
}
.inspector h2 {
margin: 4px 0 0;
font-size: 24px;
letter-spacing: -0.025em;
}
.node-state {
flex: 0 0 auto;
padding: 6px 8px;
border-radius: 7px;
background: rgba(255, 88, 120, 0.1);
color: #ff8ca2;
font-size: 9px;
font-weight: 850;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.node-state.ready {
background: rgba(106, 240, 194, 0.1);
color: var(--mint);
}
.rule-card {
margin-top: 18px;
padding: 14px;
border: 1px solid rgba(105, 231, 255, 0.17);
border-radius: 12px;
background: rgba(105, 231, 255, 0.035);
}
.rule-card.revised {
border-color: rgba(106, 240, 194, 0.25);
background: rgba(106, 240, 194, 0.045);
}
.rule-kicker {
color: var(--cyan);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.rule-text {
margin-top: 7px;
font-size: 13px;
font-weight: 750;
line-height: 1.45;
}
.rule-text .accent {
color: var(--gold);
}
.field-label {
display: block;
margin: 15px 0 7px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
select {
width: 100%;
height: 42px;
padding: 0 34px 0 11px;
border: 1px solid var(--line);
border-radius: 9px;
outline: none;
background: #111a2a;
color: var(--text);
font-size: 12px;
cursor: pointer;
}
select:focus {
border-color: rgba(105, 231, 255, 0.55);
}
.primary-button {
width: 100%;
height: 43px;
margin-top: 10px;
border: 0;
border-radius: 9px;
background: linear-gradient(135deg, #5ee3ff, #78f1ca);
color: #071018;
cursor: pointer;
font-size: 11px;
font-weight: 900;
letter-spacing: 0.09em;
text-transform: uppercase;
box-shadow: 0 8px 25px rgba(105, 231, 255, 0.13);
transition: filter 150ms ease, transform 150ms ease, opacity 150ms ease;
}
.primary-button:hover:not(:disabled) {
filter: brightness(1.08);
transform: translateY(-1px);
}
.primary-button:disabled {
opacity: 0.35;
cursor: not-allowed;
}
.relation-list {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.relation {
padding: 6px 8px;
border: 1px solid var(--line);
border-radius: 7px;
background: rgba(255, 255, 255, 0.025);
color: #bdc9d9;
font-size: 10px;
}
button.relation {
cursor: pointer;
}
button.relation:hover {
border-color: rgba(105, 231, 255, 0.45);
color: white;
}
.budget-note {
display: flex;
align-items: flex-start;
gap: 8px;
margin-top: 13px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.budget-note strong {
color: var(--gold);
}
.controls-hint {
position: fixed;
z-index: 6;
left: 50%;
bottom: 18px;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 13px;
padding: 10px 15px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(9, 14, 24, 0.76);
backdrop-filter: blur(14px);
color: var(--muted);
font-size: 10px;
white-space: nowrap;
}
.key {
display: inline-grid;
min-width: 22px;
height: 22px;
place-items: center;
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 5px;
color: #dce7f4;
background: rgba(255, 255, 255, 0.035);
font-size: 9px;
font-weight: 800;
}
.toast {
position: fixed;
z-index: 20;
left: 50%;
top: 88px;
max-width: min(520px, calc(100vw - 30px));
padding: 12px 16px;
border: 1px solid rgba(255, 88, 120, 0.38);
border-radius: 10px;
background: rgba(34, 15, 25, 0.94);
color: #ffd3dc;
box-shadow: 0 15px 50px rgba(0, 0, 0, 0.35);
font-size: 11px;
font-weight: 700;
text-align: center;
pointer-events: none;
opacity: 0;
transform: translate(-50%, -12px);
transition: opacity 180ms ease, transform 180ms ease;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
.toast.success {
border-color: rgba(106, 240, 194, 0.45);
background: rgba(12, 38, 33, 0.95);
color: #c8ffeb;
}
.legend {
display: flex;
gap: 12px;
margin-top: 12px;
color: var(--muted);
font-size: 9px;
}
.legend-item {
display: flex;
align-items: center;
gap: 5px;
}
.legend-dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--mint);
}
.legend-dot.locked {
background: #657087;
}
.legend-dot.cycle {
background: var(--danger);
}
@media (max-width: 950px) {
.brief {
left: 14px;
width: 275px;
}
.inspector {
right: 14px;
width: 310px;
}
}
@media (max-width: 700px) {
.topbar {
height: 74px;
padding: 14px;
}
.brand-mark {
width: 36px;
height: 36px;
}
.top-actions .status-pill {
display: none;
}
.brief {
top: 82px;
left: 10px;
right: 10px;
width: auto;
padding: 14px;
}
.brief .protocol-copy,
.brief .metric-row,
.brief .legend,
.brief .divider:first-of-type {
display: none;
}
.brief .divider {
margin: 10px 0;
}
.inspector {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 43vh;
padding: 16px;
overflow-y: auto;
}
.controls-hint {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive low-poly prerequisite strategy board"></canvas>
<div class="vignette"></div>
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<div class="eyebrow">Prerequisite repair puzzle</div>
<h1>DEADLOCK // FOUNDRY</h1>
</div>
</div>
<div class="top-actions">
<div id="topStatus" class="status-pill">
<span class="status-dot"></span>
<span id="topStatusText">Deadlock detected</span>
</div>
<button id="resetProtocol" class="ghost-button" type="button">
Reset protocol
</button>
</div>
</header>
<section class="panel brief" aria-label="Mission brief">
<div class="eyebrow">Mission 01</div>
<h2 class="panel-title">Restore the progression path</h2>
<p class="protocol-copy copy">
Three production nodes depend on one another. Inspect the deadlock,
then revise exactly one prerequisite rule to reach the Observatory.
</p>
<div class="divider"></div>
<div class="metric-row">
<div class="metric">
<span class="metric-label">Rule budget</span>
<span id="budgetValue" class="metric-value">1 / 1</span>
</div>
<div class="metric">
<span class="metric-label">Target</span>
<span class="metric-value">Observatory</span>
</div>
</div>
<div class="divider"></div>
<div class="section-label">
<span>Deadlock trace</span>
<span id="cycleCount">3 nodes</span>
</div>
<div id="cycleStrip" class="deadlock-strip"></div>
<div class="divider"></div>
<div class="section-label">
<span>Valid progression</span>
<span id="pathCount">0 / 8</span>
</div>
<div id="pathList" class="path-list"></div>
<div class="legend">
<span class="legend-item"><i class="legend-dot"></i>Available</span>
<span class="legend-item"><i class="legend-dot locked"></i>Locked</span>
<span class="legend-item"><i class="legend-dot cycle"></i>Deadlocked</span>
</div>
</section>
<aside id="inspector" class="panel inspector" aria-label="Node inspector"></aside>
<div class="controls-hint">
<span><span class="key">Drag</span> orbit</span>
<span><span class="key">Wheel</span> zoom</span>
<span><span class="key">Click</span> inspect node</span>
<button id="resetView" class="ghost-button" type="button">Reset view</button>
</div>
<div id="toast" class="toast" role="status" aria-live="polite"></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const canvas = document.querySelector("#scene");
const inspector = document.querySelector("#inspector");
const cycleStrip = document.querySelector("#cycleStrip");
const pathList = document.querySelector("#pathList");
const budgetValue = document.querySelector("#budgetValue");
const cycleCount = document.querySelector("#cycleCount");
const pathCount = document.querySelector("#pathCount");
const topStatus = document.querySelector("#topStatus");
const topStatusText = document.querySelector("#topStatusText");
const toast = document.querySelector("#toast");
const nodeDefinitions = [
{
id: "campfire",
name: "Campfire",
role: "First light",
description: "The first usable technology. Every valid campaign begins here.",
color: 0xff955b,
position: [-5.5, 0, 2.6]
},
{
id: "pickaxe",
name: "Pickaxe",
role: "Extraction tool",
description: "A basic extraction tool used to open the quarry.",
color: 0x9eb8cf,
position: [-5.5, 0, -1.1]
},
{
id: "quarry",
name: "Quarry",
role: "Ore site",
description: "The quarry exposes the raw iron vein used by later processes.",
color: 0xa38bd8,
position: [-2.7, 0, -4.35]
},
{
id: "iron",
name: "Iron Vein",
role: "Raw material",
description: "Raw iron can support processes that do not require the broken foundry chain.",
color: 0x62d9ec,
position: [1.0, 0, -4.35]
},
{
id: "alloy",
name: "Alloy",
role: "Structural recipe",
description: "A reinforced recipe required by the foundry.",
color: 0xffce69,
position: [4.15, 0, -2.35]
},
{
id: "foundry",
name: "Foundry",
role: "Production plant",
description: "The foundry converts alloy into the smelter required by the Observatory.",
color: 0xff825d,
position: [5.05, 0, 0.75]
},
{
id: "smelter",
name: "Smelter",
role: "Final processor",
description: "The last missing process before the Observatory can be constructed.",
color: 0xf45c77,
position: [2.65, 0, 4.0]
},
{
id: "observatory",
name: "Observatory",
role: "Mission target",
description: "The final campaign objective. It must be reachable from the Campfire.",
color: 0xb887ff,
position: [-1.25, 0, 4.45]
}
];
const nodeById = Object.fromEntries(
nodeDefinitions.map(node => [node.id, node])
);
// Dependency semantics:
// graph[target] contains the prerequisites that must be completed first.
const initialGraph = {
campfire: [],
pickaxe: ["campfire"],
quarry: ["pickaxe"],
iron: ["quarry"],
smelter: ["foundry"],
alloy: ["smelter"],
foundry: ["alloy"],
observatory: ["smelter"]
};
let graph = cloneGraph(initialGraph);
let revisionUsed = false;
let revisionRecord = null;
let selectedNode = "alloy";
let toastTimer = null;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x090d16);
scene.fog = new THREE.Fog(0x090d16, 16, 34);
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraState = {
radius: 18,
desiredRadius: 18,
theta: 0.72,
phi: 0.92,
target: new THREE.Vector3(0, 0.35, 0),
desiredTarget: new THREE.Vector3(0, 0.35, 0)
};
function updateCamera(dt) {
const smoothing = 1 - Math.pow(0.001, dt);
cameraState.radius +=
(cameraState.desiredRadius - cameraState.radius) * smoothing;
cameraState.target.lerp(cameraState.desiredTarget, smoothing);
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z +
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
updateCamera(1);
const hemisphere = new THREE.HemisphereLight(0x9bdfff, 0x241727, 2.1);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffd7ad, 3.2);
keyLight.position.set(-7, 12, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -12;
keyLight.shadow.camera.right = 12;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -12;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.0006;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x6d8fff, 1.6);
rimLight.position.set(9, 7, -10);
scene.add(rimLight);
const centerLight = new THREE.PointLight(0xa15eff, 13, 15, 2);
centerLight.position.set(0, 3.3, 0);
scene.add(centerLight);
const boardGroup = new THREE.Group();
const edgeGroup = new THREE.Group();
const pulseGroup = new THREE.Group();
const confettiGroup = new THREE.Group();
scene.add(boardGroup, edgeGroup, pulseGroup, confettiGroup);
const clickableMeshes = [];
const nodes = new Map();
const edges = [];
const pulseMeshes = [];
function standardMaterial(color, emissive = 0x000000, emissiveIntensity = 0) {
return new THREE.MeshStandardMaterial({
color,
emissive,
emissiveIntensity,
roughness: 0.76,
metalness: 0.08,
flatShading: true
});
}
function addMesh(group, geometry, material, position = [0, 0, 0]) {
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(...position);
mesh.castShadow = true;
mesh.receiveShadow = true;
group.add(mesh);
return mesh;
}
function makeRoundedRect(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + width, y, x + width, y + height, r);
ctx.arcTo(x + width, y + height, x, y + height, r);
ctx.arcTo(x, y + height, x, y, r);
ctx.arcTo(x, y, x + width, y, r);
ctx.closePath();
}
function createLabel(node) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 128;
const context = labelCanvas.getContext("2d");
context.clearRect(0, 0, 512, 128);
context.fillStyle = "rgba(7, 12, 23, 0.88)";
makeRoundedRect(context, 8, 17, 496, 94, 24);
context.fill();
context.strokeStyle = "rgba(177, 205, 235, 0.24)";
context.lineWidth = 3;
context.stroke();
context.fillStyle = "#f0f6ff";
context.font = "800 42px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(node.name.toUpperCase(), 256, 65);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(
8,
renderer.capabilities.getMaxAnisotropy()
);
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.position.set(0, 1.72, 0);
sprite.scale.set(2.35, 0.59, 1);
sprite.renderOrder = 20;
return sprite;
}
function tagNodeMeshes(group, id) {
group.traverse(object => {
if (object.isMesh) {
object.userData.nodeId = id;
clickableMeshes.push(object);
}
});
}
function createNode(node) {
const group = new THREE.Group();
group.position.set(...node.position);
group.userData.nodeId = node.id;
const baseMaterial = standardMaterial(0x273247);
const base = addMesh(
group,
new THREE.CylinderGeometry(0.73, 0.82, 0.22, 6),
baseMaterial,
[0, 0.11, 0]
);
baseMaterial.userData.baseColor = baseMaterial.color.clone();
const ringMaterial = standardMaterial(0xff5878, 0xff5878, 0.8);
const ring = addMesh(
group,
new THREE.TorusGeometry(0.83, 0.055, 4, 28),
ringMaterial,
[0, 0.27, 0]
);
ring.rotation.x = Math.PI / 2;
ring.castShadow = false;
const icon = new THREE.Group();
icon.position.y = 0.25;
group.add(icon);
const bodyMaterial = standardMaterial(node.color, node.color, 0.045);
const darkMaterial = standardMaterial(0x263047);
const glowMaterial = standardMaterial(node.color, node.color, 1.5);
const materials = [];
if (node.id === "campfire") {
const logMaterial = standardMaterial(0x704536);
const logA = addMesh(
icon,
new THREE.CylinderGeometry(0.085, 0.11, 0.95, 6),
logMaterial,
[0, 0.25, 0]
);
logA.rotation.z = Math.PI / 2;
const logB = addMesh(
icon,
new THREE.CylinderGeometry(0.085, 0.11, 0.95, 6),
logMaterial,
[0, 0.25, 0]
);
logB.rotation.x = Math.PI / 2;
const flame = addMesh(
icon,
new THREE.ConeGeometry(0.28, 0.75, 5),
glowMaterial,
[0, 0.72, 0]
);
flame.rotation.y = Math.PI / 5;
materials.push(bodyMaterial, glowMaterial, logMaterial);
}
if (node.id === "pickaxe") {
const handle = addMesh(
icon,
new THREE.CylinderGeometry(0.07, 0.085, 1.18, 6),
darkMaterial,
[0, 0.53, 0]
);
handle.rotation.z = 0.27;
const head = addMesh(
icon,
new THREE.BoxGeometry(0.82, 0.19, 0.24),
bodyMaterial,
[0.05, 1.08, 0]
);
head.rotation.z = 0.27;
materials.push(bodyMaterial, darkMaterial);
}
if (node.id === "quarry") {
addMesh(
icon,
new THREE.DodecahedronGeometry(0.43, 0),
bodyMaterial,
[-0.28, 0.36, 0.08]
);
addMesh(
icon,
new THREE.DodecahedronGeometry(0.34, 0),
darkMaterial,
[0.34, 0.3, -0.05]
);
addMesh(
icon,
new THREE.DodecahedronGeometry(0.29, 0),
bodyMaterial,
[0.05, 0.58, 0.13]
);
materials.push(bodyMaterial, darkMaterial);
}
if (node.id === "iron") {
const crystalA = addMesh(
icon,
new THREE.OctahedronGeometry(0.42, 0),
bodyMaterial,
[-0.19, 0.55, 0]
);
crystalA.scale.set(0.72, 1.35, 0.72);
const crystalB = addMesh(
icon,
new THREE.OctahedronGeometry(0.32, 0),
glowMaterial,
[0.25, 0.38, 0.05]
);
crystalB.scale.set(0.7, 1.2, 0.7);
crystalB.rotation.z = -0.16;
materials.push(bodyMaterial, glowMaterial);
}
if (node.id === "alloy") {
addMesh(
icon,
new THREE.CylinderGeometry(0.4, 0.55, 0.74, 6),
bodyMaterial,
[0, 0.43, 0]
);
const band = addMesh(
icon,
new THREE.TorusGeometry(0.39, 0.065, 4, 12),
glowMaterial,
[0, 0.48, 0]
);
band.rotation.x = Math.PI / 2;
materials.push(bodyMaterial, glowMaterial);
}
if (node.id === "foundry") {
addMesh(
icon,
new THREE.BoxGeometry(0.95, 0.7, 0.82),
bodyMaterial,
[0, 0.43, 0]
);
addMesh(
icon,
new THREE.BoxGeometry(0.55, 0.27, 0.08),
glowMaterial,
[0, 0.43, 0.45]
);
addMesh(
icon,
new THREE.CylinderGeometry(0.17, 0.2, 0.76, 6),
darkMaterial,
[0.28, 1.03, -0.12]
);
materials.push(bodyMaterial, glowMaterial, darkMaterial);
}
if (node.id === "smelter") {
addMesh(
icon,
new THREE.CylinderGeometry(0.42, 0.56, 0.75, 6),
bodyMaterial,
[0, 0.43, 0]
);
const mouth = addMesh(
icon,
new THREE.CylinderGeometry(0.23, 0.23, 0.08, 6),
glowMaterial,
[0, 0.84, 0]
);
const chimney = addMesh(
icon,
new THREE.CylinderGeometry(0.13, 0.17, 0.55, 6),
darkMaterial,
[0.25, 1.02, 0]
);
materials.push(bodyMaterial, glowMaterial, darkMaterial);
}
if (node.id === "observatory") {
addMesh(
icon,
new THREE.CylinderGeometry(0.57, 0.67, 0.2, 8),
darkMaterial,
[0, 0.2, 0]
);
const dome = addMesh(
icon,
new THREE.SphereGeometry(
0.52,
8,
4,
0,
Math.PI * 2,
0,
Math.PI / 2
),
bodyMaterial,
[0, 0.31, 0]
);
dome.scale.y = 0.86;
addMesh(
icon,
new THREE.CylinderGeometry(0.035, 0.035, 0.65, 5),
darkMaterial,
[0, 1.02, 0]
);
const beacon = addMesh(
icon,
new THREE.OctahedronGeometry(0.13, 0),
glowMaterial,
[0, 1.38, 0]
);
materials.push(bodyMaterial, glowMaterial, darkMaterial);
}
for (const material of materials) {
material.userData.baseColor = material.color.clone();
}
group.add(createLabel(node));
tagNodeMeshes(group, node.id);
boardGroup.add(group);
nodes.set(node.id, {
group,
icon,
ring,
ringMaterial,
baseMaterial,
materials: [...new Set(materials)],
phase: Math.random() * Math.PI * 2
});
}
function createBoard() {
const boardMaterial = standardMaterial(0x161e2e);
const board = addMesh(
boardGroup,
new THREE.CylinderGeometry(7.35, 7.65, 0.48, 12),
boardMaterial,
[0, -0.26, 0]
);
board.castShadow = false;
const topMaterial = standardMaterial(0x1d293b);
const top = addMesh(
boardGroup,
new THREE.CylinderGeometry(7.08, 7.18, 0.13, 12),
topMaterial,
[0, 0.025, 0]
);
top.castShadow = false;
for (const radius of [2.05, 4.45, 6.65]) {
const points = [];
for (let i = 0; i < 64; i++) {
const angle = (i / 64) * Math.PI * 2;
points.push(
new THREE.Vector3(
Math.cos(angle) * radius,
0.105,
Math.sin(angle) * radius
)
);
}
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({
color: radius === 4.45 ? 0x334864 : 0x26364d,
transparent: true,
opacity: radius === 4.45 ? 0.65 : 0.45
});
const line = new THREE.LineLoop(geometry, material);
boardGroup.add(line);
}
const emblemMaterial = new THREE.MeshBasicMaterial({
color: 0x6be7ff,
transparent: true,
opacity: 0.1,
side: THREE.DoubleSide
});
const emblem = addMesh(
boardGroup,
new THREE.RingGeometry(0.72, 1.12, 6),
emblemMaterial,
[0, 0.115, 0]
);
emblem.rotation.x = -Math.PI / 2;
emblem.castShadow = false;
const crystalColors = [
0x34576c,
0x4e3d6f,
0x295b61,
0x6a473f
];
for (let i = 0; i < 18; i++) {
const angle = (i / 18) * Math.PI * 2 + 0.11;
const radius = 6.65 + Math.sin(i * 2.4) * 0.16;
const height = 0.18 + (i % 4) * 0.08;
const crystal = addMesh(
boardGroup,
new THREE.ConeGeometry(0.12, height, 5),
standardMaterial(crystalColors[i % crystalColors.length]),
[
Math.cos(angle) * radius,
0.15 + height / 2,
Math.sin(angle) * radius
]
);
crystal.rotation.z = Math.sin(i) * 0.15;
crystal.castShadow = false;
}
}
function createAmbientMotes() {
const positions = new Float32Array(180 * 3);
for (let i = 0; i < 180; i++) {
const angle = Math.random() * Math.PI * 2;
const radius = Math.sqrt(Math.random()) * 9.5;
positions[i * 3] = Math.cos(angle) * radius;
positions[i * 3 + 1] = 0.7 + Math.random() * 5.5;
positions[i * 3 + 2] = Math.sin(angle) * radius;
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.BufferAttribute(positions, 3)
);
const material = new THREE.PointsMaterial({
color: 0x8beaff,
size: 0.035,
transparent: true,
opacity: 0.52,
depthWrite: false,
sizeAttenuation: true
});
const points = new THREE.Points(geometry, material);
scene.add(points);
}
function cloneGraph(source) {
return Object.fromEntries(
Object.entries(source).map(([id, prerequisites]) => [
id,
[...prerequisites]
])
);
}
function buildAdjacency(candidateGraph) {
const adjacency = Object.fromEntries(
Object.keys(candidateGraph).map(id => [id, []])
);
for (const [target, prerequisites] of Object.entries(candidateGraph)) {
for (const prerequisite of prerequisites) {
if (adjacency[prerequisite]) {
adjacency[prerequisite].push(target);
}
}
}
return adjacency;
}
function findCycle(candidateGraph) {
const adjacency = buildAdjacency(candidateGraph);
const visited = new Set();
const active = new Set();
const stack = [];
function visit(id) {
visited.add(id);
active.add(id);
stack.push(id);
for (const next of adjacency[id]) {
if (active.has(next)) {
const index = stack.indexOf(next);
return stack.slice(index);
}
if (!visited.has(next)) {
const cycle = visit(next);
if (cycle) return cycle;
}
}
stack.pop();
active.delete(id);
return null;
}
for (const id of Object.keys(candidateGraph)) {
if (!visited.has(id)) {
const cycle = visit(id);
if (cycle) return cycle;
}
}
return [];
}
function getReachable(candidateGraph) {
const adjacency = buildAdjacency(candidateGraph);
const reachable = new Set(["campfire"]);
const queue = ["campfire"];
while (queue.length) {
const current = queue.shift();
for (const next of adjacency[current]) {
if (!reachable.has(next)) {
reachable.add(next);
queue.push(next);
}
}
}
return reachable;
}
function findProgressionPath(candidateGraph, reachable) {
function backtrack(id, visiting) {
if (id === "campfire") return ["campfire"];
if (visiting.has(id)) return null;
visiting.add(id);
for (const prerequisite of candidateGraph[id]) {
if (!reachable.has(prerequisite)) continue;
const path = backtrack(prerequisite, visiting);
if (path) return [...path, id];
}
visiting.delete(id);
return null;
}
return backtrack("observatory", new Set());
}
function cycleEdgePairs(cycle) {
const pairs = new Set();
for (let i = 0; i < cycle.length; i++) {
pairs.add(`${cycle[i]}->${cycle[(i + 1) % cycle.length]}`);
}
return pairs;
}
function clearGroup(group) {
while (group.children.length) {
const child = group.children.pop();
child.traverse(object => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const materials = Array.isArray(object.material)
? object.material
: [object.material];
for (const material of materials) {
material.dispose();
}
}
});
}
}
function rebuildEdges() {
clearGroup(edgeGroup);
clearGroup(pulseGroup);
edges.length = 0;
pulseMeshes.length = 0;
const cycle = findCycle(graph);
const deadEdges = cycleEdgePairs(cycle);
const solved = cycle.length === 0;
for (const target of nodeDefinitions) {
for (const prerequisite of graph[target.id]) {
const sourcePosition = nodeById[prerequisite].position;
const targetPosition = target.position;
const source = new THREE.Vector3(
sourcePosition[0],
0.56,
sourcePosition[2]
);
const end = new THREE.Vector3(
targetPosition[0],
0.56,
targetPosition[2]
);
const middle = source.clone().lerp(end, 0.5);
middle.y += 0.8 + source.distanceTo(end) * 0.025;
const curve = new THREE.CatmullRomCurve3([
source,
middle,
end
]);
const isDead = deadEdges.has(`${prerequisite}->${target.id}`);
const edgeColor = isDead
? 0xff5878
: solved
? 0x6af0c2
: 0x62cfe8;
const material = standardMaterial(
edgeColor,
edgeColor,
isDead ? 0.85 : 0.55
);
material.transparent = true;
material.opacity = isDead ? 0.95 : 0.72;
const tube = new THREE.Mesh(
new THREE.TubeGeometry(curve, 18, 0.047, 5, false),
material
);
tube.castShadow = false;
edgeGroup.add(tube);
const arrowMaterial = standardMaterial(
edgeColor,
edgeColor,
isDead ? 1.15 : 0.75
);
const arrow = new THREE.Mesh(
new THREE.ConeGeometry(0.13, 0.31, 5),
arrowMaterial
);
arrow.position.copy(curve.getPoint(0.64));
arrow.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
curve.getTangent(0.64).normalize()
);
edgeGroup.add(arrow);
edges.push({
from: prerequisite,
to: target.id,
curve,
material,
arrowMaterial,
dead: isDead
});
}
}
}
function updateNodeStates() {
const reachable = getReachable(graph);
const cycle = findCycle(graph);
for (const definition of nodeDefinitions) {
const node = nodes.get(definition.id);
const isReachable = reachable.has(definition.id);
const isDeadlocked = cycle.includes(definition.id);
let ringColor = 0x667087;
if (isReachable) ringColor = 0x6af0c2;
if (isDeadlocked) ringColor = 0xff5878;
node.ringMaterial.color.setHex(ringColor);
node.ringMaterial.emissive.setHex(ringColor);
node.ringMaterial.emissiveIntensity = isDeadlocked ? 1.15 : 0.72;
node.ringMaterial.opacity = isReachable || isDeadlocked ? 1 : 0.45;
node.ringMaterial.transparent = true;
node.baseMaterial.color
.copy(node.baseMaterial.userData.baseColor)
.multiplyScalar(isReachable || isDeadlocked ? 1 : 0.65);
for (const material of node.materials) {
const base = material.userData.baseColor;
if (isDeadlocked) {
material.color.setHex(0xff5e7b);
material.emissive.setHex(0xff4167);
material.emissiveIntensity = 0.13;
} else if (isReachable) {
material.color.copy(base);
material.emissive.copy(base);
material.emissiveIntensity = 0.035;
} else {
material.color.copy(base).multiplyScalar(0.43);
material.emissive.setHex(0x000000);
material.emissiveIntensity = 0;
}
}
node.ring.scale.setScalar(
definition.id === selectedNode ? 1.13 : 1
);
}
}
function nodeStateLabel(id) {
const reachable = getReachable(graph);
const cycle = findCycle(graph);
if (cycle.includes(id)) return "Deadlocked";
if (reachable.has(id)) return "Available";
return "Locked";
}
function renderCycle() {
const cycle = findCycle(graph);
if (cycle.length) {
cycleCount.textContent = `${cycle.length} nodes`;
cycleStrip.innerHTML = cycle
.map((id, index) => {
const separator =
index < cycle.length - 1
? '<span class="cycle-arrow">→</span>'
: '<span class="cycle-arrow">↺</span>';
return `
<button class="node-chip" data-node="${id}" type="button">
${nodeById[id].name}
</button>
${separator}
`;
})
.join("");
cycleStrip.querySelectorAll("[data-node]").forEach(button => {
button.addEventListener("click", () => {
selectNode(button.dataset.node, true);
});
});
} else {
cycleCount.textContent = "Cleared";
cycleStrip.innerHTML = `
<span class="node-chip" style="color:var(--mint);border-color:rgba(106,240,194,.3);background:rgba(106,240,194,.07)">
No circular dependency
</span>
`;
}
}
function renderPath() {
const reachable = getReachable(graph);
const cycle = findCycle(graph);
const path = cycle.length
? []
: findProgressionPath(graph, reachable);
if (path.length) {
pathCount.textContent = `${path.length} / ${nodeDefinitions.length}`;
pathList.innerHTML = path
.map(id => `<div class="path-step">${nodeById[id].name}</div>`)
.join("");
} else {
pathCount.textContent = "0 / 8";
pathList.innerHTML = `
<div class="empty-state">
No progression path can leave the Campfire while the circular
dependency remains unresolved.
</div>
`;
}
return path;
}
function renderInspector() {
if (!selectedNode || !nodeById[selectedNode]) {
inspector.innerHTML = `
<div class="eyebrow">Node inspector</div>
<h2>Select a node</h2>
<p class="copy">Click any technology on the board to inspect its rule.</p>
`;
return;
}
const definition = nodeById[selectedNode];
const prerequisites = graph[selectedNode];
const state = nodeStateLabel(selectedNode);
const outgoing = nodeDefinitions.filter(node =>
graph[node.id].includes(selectedNode)
);
const ruleText = prerequisites.length
? `${definition.name} requires <span class="accent">${
prerequisites.map(id => nodeById[id].name).join(" + ")
}</span>`
: `${definition.name} requires <span class="accent">nothing</span>`;
const editable =
prerequisites.length === 1 &&
!revisionUsed &&
definition.id !== "campfire";
const options = nodeDefinitions
.filter(node => node.id !== selectedNode)
.map(node => {
const current = node.id === prerequisites[0];
return `
<option value="${node.id}" ${current ? "selected disabled" : ""}>
${node.name}${current ? " — current" : ""}
</option>
`;
})
.join("");
inspector.innerHTML = `
<div class="inspector-head">
<div>
<div class="eyebrow">${definition.role}</div>
<h2>${definition.name}</h2>
</div>
<span class="node-state ${state === "Available" ? "ready" : ""}">
${state}
</span>
</div>
<p class="copy" style="margin-top:12px">
${definition.description}
</p>
<div class="rule-card ${revisionUsed ? "revised" : ""}">
<div class="rule-kicker">
${revisionUsed ? "Revised rule" : "Current prerequisite rule"}
</div>
<div class="rule-text">${ruleText}</div>
${
editable
? `
<label class="field-label" for="ruleSelect">
Replace prerequisite
</label>
<select id="ruleSelect">
${options}
<option value="none">No prerequisite</option>
</select>
<button id="applyRule" class="primary-button" type="button" disabled>
Commit revision
</button>
`
: revisionUsed
? `
<div class="budget-note">
<span>✓</span>
<span>The single permitted rule revision has been committed.</span>
</div>
`
: `
<div class="budget-note">
<span>—</span>
<span>This node has no editable prerequisite rule.</span>
</div>
`
}
</div>
<div class="divider"></div>
<div class="section-label">
<span>Direct relations</span>
<span>${prerequisites.length + outgoing.length}</span>
</div>
<div class="relation-list">
${
prerequisites.length
? prerequisites
.map(
id =>
`<button class="relation" data-select-node="${id}" type="button">
Requires ${nodeById[id].name}
</button>`
)
.join("")
: `<span class="relation">Starting technology</span>`
}
${
outgoing.length
? outgoing
.map(
node =>
`<button class="relation" data-select-node="${node.id}" type="button">
Unlocks ${node.name}
</button>`
)
.join("")
: `<span class="relation">No downstream rules</span>`
}
</div>
<div class="budget-note">
<span>◆</span>
<span>
Rule budget:
<strong>${revisionUsed ? "0 remaining" : "1 remaining"}</strong>.
Choose a replacement that removes the cycle and keeps the
Observatory reachable.
</span>
</div>
`;
inspector.querySelectorAll("[data-select-node]").forEach(button => {
button.addEventListener("click", () => {
selectNode(button.dataset.selectNode, true);
});
});
const select = inspector.querySelector("#ruleSelect");
const applyButton = inspector.querySelector("#applyRule");
if (select && applyButton) {
const updateApplyState = () => {
applyButton.disabled = select.value === prerequisites[0];
};
select.addEventListener("change", updateApplyState);
applyButton.addEventListener("click", () => {
applyRevision(selectedNode, select.value);
});
updateApplyState();
}
}
function showToast(message, type = "error") {
clearTimeout(toastTimer);
toast.textContent = message;
toast.className = `toast show${type === "success" ? " success" : ""}`;
toastTimer = setTimeout(() => {
toast.classList.remove("show");
}, 3200);
}
function applyRevision(nodeId, candidate) {
if (revisionUsed) {
showToast("The one-rule revision budget has already been used.");
return;
}
const testGraph = cloneGraph(graph);
testGraph[nodeId] = candidate === "none" ? [] : [candidate];
const testCycle = findCycle(testGraph);
if (testCycle.length) {
showToast(
"Rejected: that replacement recreates a circular dependency."
);
return;
}
const testReachable = getReachable(testGraph);
if (!testReachable.has("observatory")) {
showToast(
"Rejected: the Observatory would remain unreachable from the Campfire."
);
return;
}
graph = testGraph;
revisionUsed = true;
revisionRecord = {
node: nodeId,
candidate
};
rebuildEdges();
updateNodeStates();
renderAll();
createSuccessPulse();
createConfetti();
showToast(
"Protocol restored — a valid progression path now reaches the Observatory.",
"success"
);
}
function selectNode(id, focus = false) {
if (!nodeById[id]) return;
selectedNode = id;
updateNodeStates();
renderInspector();
if (focus) {
const position = nodes.get(id).group.position;
cameraState.desiredTarget.set(position.x, 0.5, position.z);
cameraState.desiredRadius = Math.min(
cameraState.desiredRadius,
12.5
);
}
}
function renderAll() {
const cycle = findCycle(graph);
const reachable = getReachable(graph);
const path = cycle.length
? []
: findProgressionPath(graph, reachable);
budgetValue.textContent = revisionUsed ? "0 / 1" : "1 / 1";
budgetValue.className = `metric-value ${revisionUsed ? "mint" : ""}`;
if (path.length) {
topStatus.classList.add("good");
topStatusText.textContent = "Protocol restored";
} else {
topStatus.classList.remove("good");
topStatusText.textContent = "Deadlock detected";
}
renderCycle();
renderPath();
renderInspector();
updateNodeStates();
}
function createSuccessPulse() {
clearGroup(pulseGroup);
pulseMeshes.length = 0;
const material = new THREE.MeshBasicMaterial({
color: 0xbaffdf,
transparent: true,
opacity: 0.9
});
for (const edge of edges) {
const pulse = new THREE.Mesh(
new THREE.SphereGeometry(0.075, 6, 4),
material
);
pulseGroup.add(pulse);
pulseMeshes.push({ mesh: pulse, edge, offset: Math.random() });
}
}
function createConfetti() {
clearGroup(confettiGroup);
const colors = [0x69e7ff, 0x6af0c2, 0xffd166, 0xb887ff];
const materials = colors.map(color =>
new THREE.MeshBasicMaterial({ color })
);
for (let i = 0; i < 52; i++) {
const mesh = new THREE.Mesh(
new THREE.TetrahedronGeometry(0.065 + Math.random() * 0.055),
materials[i % materials.length]
);
mesh.position.set(
(Math.random() - 0.5) * 1.5,
2.4 + Math.random() * 1.4,
(Math.random() - 0.5) * 1.5
);
confettiGroup.add(mesh);
mesh.userData.velocity = new THREE.Vector3(
(Math.random() - 0.5) * 4.5,
2.8 + Math.random() * 3.5,
(Math.random() - 0.5) * 4.5
);
mesh.userData.spin = new THREE.Vector3(
Math.random() * 5,
Math.random() * 5,
Math.random() * 5
);
}
}
function resetProtocol() {
graph = cloneGraph(initialGraph);
revisionUsed = false;
revisionRecord = null;
selectedNode = "alloy";
clearGroup(confettiGroup);
rebuildEdges();
updateNodeStates();
renderAll();
showToast("Protocol reset. The original deadlock has been restored.");
}
function resetView() {
cameraState.desiredTarget.set(0, 0.35, 0);
cameraState.desiredRadius = 18;
cameraState.theta = 0.72;
cameraState.phi = 0.92;
}
document.querySelector("#resetProtocol").addEventListener("click", resetProtocol);
document.querySelector("#resetView").addEventListener("click", resetView);
// Raycasting and manual camera controls.
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const pointerState = {
active: false,
moved: 0,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0,
button: 0
};
function setPointerFromEvent(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function pickNode(event) {
setPointerFromEvent(event);
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(clickableMeshes, false);
if (!intersections.length) return null;
let object = intersections[0].object;
while (object && !object.userData.nodeId) {
object = object.parent;
}
return object ? object.userData.nodeId : null;
}
canvas.addEventListener("pointerdown", event => {
if (event.button !== 0 && event.button !== 2) return;
pointerState.active = true;
pointerState.moved = 0;
pointerState.startX = event.clientX;
pointerState.startY = event.clientY;
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
pointerState.button = event.button;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
if (!pointerState.active) {
const hovered = pickNode(event);
canvas.style.cursor = hovered ? "pointer" : "grab";
return;
}
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
pointerState.moved += Math.abs(dx) + Math.abs(dy);
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
if (event.shiftKey || pointerState.button === 2) {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
const right = new THREE.Vector3()
.crossVectors(forward, camera.up)
.normalize();
const up = new THREE.Vector3()
.crossVectors(right, forward)
.normalize();
cameraState.desiredTarget.addScaledVector(
right,
-dx * cameraState.radius * 0.0016
);
cameraState.desiredTarget.addScaledVector(
up,
dy * cameraState.radius * 0.0016
);
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.006,
0.3,
1.38
);
}
canvas.style.cursor = "grabbing";
});
canvas.addEventListener("pointerup", event => {
if (!pointerState.active) return;
const wasClick =
pointerState.moved < 7 &&
pointerState.button === 0 &&
event.button === 0;
pointerState.active = false;
canvas.style.cursor = "grab";
if (wasClick) {
const id = pickNode(event);
if (id) selectNode(id);
}
});
canvas.addEventListener("pointercancel", () => {
pointerState.active = false;
canvas.style.cursor = "grab";
});
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener(
"wheel",
event => {
event.preventDefault();
cameraState.desiredRadius = THREE.MathUtils.clamp(
cameraState.desiredRadius + event.deltaY * 0.012,
8.5,
26
);
},
{ passive: false }
);
window.addEventListener("keydown", event => {
if (event.key === "Escape") resetView();
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
createBoard();
nodeDefinitions.forEach(createNode);
createAmbientMotes();
rebuildEdges();
renderAll();
const clock = new THREE.Clock();
const confettiStart = { value: 0 };
renderer.setAnimationLoop(() => {
const dt = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
updateCamera(dt);
for (const definition of nodeDefinitions) {
const node = nodes.get(definition.id);
node.icon.position.y =
0.25 + Math.sin(elapsed * 1.25 + node.phase) * 0.025;
}
for (const edge of edges) {
const intensity = edge.dead
? 0.85 + Math.sin(elapsed * 4) * 0.32
: 0.55;
edge.material.emissiveIntensity = intensity;
edge.arrowMaterial.emissiveIntensity = intensity + 0.15;
}
if (pulseMeshes.length) {
for (let i = 0; i < pulseMeshes.length; i++) {
const pulse = pulseMeshes[i];
const t = (elapsed * 0.2 + pulse.offset) % 1;
pulse.mesh.position.copy(pulse.edge.curve.getPoint(t));
pulse.mesh.scale.setScalar(0.8 + Math.sin(t * Math.PI) * 0.55);
}
}
if (confettiGroup.children.length) {
if (confettiStart.value === 0) {
confettiStart.value = elapsed;
}
for (const piece of confettiGroup.children) {
piece.userData.velocity.y -= dt * 3.2;
piece.position.addScaledVector(piece.userData.velocity, dt);
piece.rotation.x += piece.userData.spin.x * dt;
piece.rotation.y += piece.userData.spin.y * dt;
piece.rotation.z += piece.userData.spin.z * dt;
}
if (elapsed - confettiStart.value > 4.2) {
clearGroup(confettiGroup);
confettiStart.value = 0;
}
}
renderer.render(scene, camera);
});
</script>
</body>
</html>
```