Prompt specification
Build or customize the Three.js 3D scene "Gear network completion 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: Gear network completion puzzle
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/gear-network-completion-puzzle-x0340
Scene Description Prompt:
Gear network completion puzzle. Create a pegboard with missing gears and target arrows; users place compatible wheels to connect input and outputs while an animated test checks rotation directions. Please build this with Three.js from cdnjs in one self-contained HTML file, using visible voxel blocks.
Working Three.js Starter (gear-network-completion-puzzle-x0340):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clockwork Bay — Gear Network Puzzle</title>
<style>
:root {
color-scheme: dark;
--bg: #07111d;
--panel: rgba(10, 23, 38, 0.86);
--panel-solid: #0b1929;
--line: rgba(148, 194, 226, 0.16);
--text: #e9f5ff;
--muted: #8fa9bd;
--cyan: #37baff;
--amber: #ffb340;
--green: #58e39c;
--red: #ff657a;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 42%, #14283c 0, #091521 44%, #050b13 100%);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button {
font: inherit;
}
#scene-container {
position: fixed;
inset: 0;
}
#scene-container canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.topbar {
position: fixed;
z-index: 10;
top: 0;
left: 0;
right: 0;
height: 78px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 14px 20px;
background: linear-gradient(
180deg,
rgba(5, 13, 23, 0.96),
rgba(5, 13, 23, 0.66) 72%,
transparent
);
pointer-events: none;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
pointer-events: auto;
}
.brand-mark {
position: relative;
width: 42px;
height: 42px;
border: 1px solid rgba(55, 186, 255, 0.45);
background: rgba(55, 186, 255, 0.07);
box-shadow: inset 0 0 20px rgba(55, 186, 255, 0.06);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
background: var(--cyan);
}
.brand-mark::before {
width: 18px;
height: 18px;
left: 10px;
top: 10px;
box-shadow:
5px 0 0 -4px var(--cyan),
-5px 0 0 -4px var(--cyan),
0 5px 0 -4px var(--cyan),
0 -5px 0 -4px var(--cyan);
}
.brand-mark::after {
width: 8px;
height: 8px;
left: 15px;
top: 15px;
background: #dff6ff;
}
.eyebrow {
margin: 0 0 3px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.2em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 18px;
line-height: 1;
letter-spacing: 0.035em;
}
.top-actions {
display: flex;
align-items: center;
gap: 8px;
pointer-events: auto;
}
.button {
min-height: 38px;
border: 1px solid var(--line);
border-radius: 7px;
padding: 0 14px;
color: var(--text);
background: rgba(17, 37, 57, 0.8);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
cursor: pointer;
transition: 140ms ease;
}
.button:hover {
border-color: rgba(55, 186, 255, 0.48);
background: rgba(26, 57, 83, 0.92);
transform: translateY(-1px);
}
.button.primary {
border-color: rgba(55, 186, 255, 0.55);
color: #eaf9ff;
background: linear-gradient(135deg, #167fb9, #0d547f);
box-shadow: 0 6px 25px rgba(23, 135, 197, 0.2);
}
.button.primary.running {
border-color: rgba(88, 227, 156, 0.58);
background: linear-gradient(135deg, #17815b, #0f5b43);
}
.panel {
position: fixed;
z-index: 8;
border: 1px solid var(--line);
border-radius: 10px;
background: var(--panel);
box-shadow:
0 16px 50px rgba(0, 0, 0, 0.28),
inset 0 1px 0 rgba(255, 255, 255, 0.03);
backdrop-filter: blur(13px);
}
.mission {
top: 96px;
left: 20px;
width: 276px;
padding: 17px;
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 13px;
}
.panel-heading h2 {
margin: 0;
font-size: 11px;
font-weight: 850;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.status-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--muted);
box-shadow: 0 0 12px rgba(143, 169, 189, 0.5);
}
.status-dot.good {
background: var(--green);
box-shadow: 0 0 12px rgba(88, 227, 156, 0.65);
}
.status-dot.bad {
background: var(--red);
box-shadow: 0 0 12px rgba(255, 101, 122, 0.65);
}
.mission-copy {
margin: 0;
color: #adc2d2;
font-size: 12px;
line-height: 1.55;
}
.direction-list {
display: grid;
gap: 7px;
margin: 15px 0;
}
.direction-row {
display: flex;
align-items: center;
justify-content: space-between;
min-height: 34px;
padding: 0 10px;
border: 1px solid rgba(143, 169, 189, 0.12);
border-radius: 6px;
background: rgba(4, 13, 23, 0.38);
color: var(--muted);
font-size: 11px;
font-weight: 700;
}
.direction-row strong {
color: var(--text);
font-size: 12px;
letter-spacing: 0.04em;
}
.direction-row.input strong {
color: var(--cyan);
}
.direction-row.output-a strong {
color: var(--green);
}
.direction-row.output-b strong {
color: var(--amber);
}
.rules {
margin: 13px 0 0;
padding: 12px 0 0;
border-top: 1px solid var(--line);
list-style: none;
}
.rules li {
position: relative;
margin: 7px 0;
padding-left: 16px;
color: #92aabd;
font-size: 11px;
line-height: 1.45;
}
.rules li::before {
content: "";
position: absolute;
left: 1px;
top: 7px;
width: 4px;
height: 4px;
background: var(--cyan);
box-shadow: 0 0 8px rgba(55, 186, 255, 0.6);
}
.palette {
right: 20px;
bottom: 22px;
width: 292px;
padding: 16px;
}
.gear-options {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.gear-card {
position: relative;
min-width: 0;
min-height: 116px;
border: 1px solid var(--line);
border-radius: 8px;
padding: 11px;
color: var(--text);
background: rgba(4, 13, 23, 0.56);
text-align: left;
cursor: pointer;
transition: 150ms ease;
}
.gear-card:hover {
border-color: rgba(145, 200, 235, 0.35);
transform: translateY(-2px);
}
.gear-card.selected {
border-color: var(--wheel-color);
background: color-mix(in srgb, var(--wheel-color) 12%, rgba(4, 13, 23, 0.7));
box-shadow:
0 0 0 1px color-mix(in srgb, var(--wheel-color) 22%, transparent),
0 8px 24px rgba(0, 0, 0, 0.24);
}
.gear-card.cobalt {
--wheel-color: var(--cyan);
}
.gear-card.amber {
--wheel-color: var(--amber);
}
.gear-icon {
position: absolute;
top: 10px;
right: 10px;
width: 34px;
height: 34px;
border: 5px dotted var(--wheel-color);
background:
linear-gradient(90deg, transparent 38%, var(--wheel-color) 38% 62%, transparent 62%),
linear-gradient(transparent 38%, var(--wheel-color) 38% 62%, transparent 62%);
box-shadow: 0 0 17px color-mix(in srgb, var(--wheel-color) 28%, transparent);
transform: rotate(11deg);
}
.gear-card strong {
display: block;
margin-top: 32px;
font-size: 13px;
}
.gear-card small {
display: block;
margin-top: 5px;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.palette-hint {
margin: 12px 0 0;
color: #829cb0;
font-size: 10px;
line-height: 1.45;
}
.progress-block {
margin-top: 14px;
padding-top: 13px;
border-top: 1px solid var(--line);
}
.progress-label {
display: flex;
justify-content: space-between;
margin-bottom: 7px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.04em;
}
.progress-track {
height: 5px;
overflow: hidden;
border-radius: 999px;
background: rgba(143, 169, 189, 0.12);
}
.progress-fill {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--cyan), var(--green));
box-shadow: 0 0 12px rgba(55, 186, 255, 0.4);
transition: width 220ms ease;
}
.toast {
position: fixed;
z-index: 30;
top: 88px;
left: 50%;
max-width: min(460px, calc(100vw - 30px));
padding: 11px 16px;
border: 1px solid rgba(55, 186, 255, 0.32);
border-radius: 7px;
color: #dff6ff;
background: rgba(9, 27, 43, 0.94);
box-shadow: 0 10px 35px rgba(0, 0, 0, 0.34);
font-size: 12px;
font-weight: 650;
text-align: center;
opacity: 0;
pointer-events: none;
transform: translate(-50%, -12px);
transition: 180ms ease;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
.toast.good {
border-color: rgba(88, 227, 156, 0.46);
color: #caffdf;
}
.toast.bad {
border-color: rgba(255, 101, 122, 0.52);
color: #ffd3da;
}
.control-hint {
position: fixed;
z-index: 7;
bottom: 20px;
left: 50%;
padding: 8px 12px;
border: 1px solid rgba(143, 169, 189, 0.11);
border-radius: 6px;
color: rgba(180, 203, 219, 0.58);
background: rgba(5, 14, 24, 0.48);
font-size: 10px;
pointer-events: none;
transform: translateX(-50%);
}
@media (max-width: 950px) {
.mission {
width: 238px;
}
.palette {
width: 258px;
}
.control-hint {
display: none;
}
}
@media (max-width: 680px) {
.topbar {
height: 67px;
padding: 10px 12px;
}
.brand-mark {
width: 36px;
height: 36px;
}
.brand-mark::before {
left: 8px;
top: 8px;
}
.brand-mark::after {
left: 13px;
top: 13px;
}
h1 {
font-size: 14px;
}
.eyebrow {
font-size: 8px;
}
.button {
min-height: 34px;
padding: 0 9px;
font-size: 9px;
}
.mission {
top: 73px;
left: 10px;
width: 205px;
padding: 12px;
}
.mission-copy,
.rules {
display: none;
}
.direction-list {
margin-bottom: 0;
}
.direction-row {
min-height: 29px;
font-size: 9px;
}
.direction-row strong {
font-size: 10px;
}
.palette {
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
padding: 11px;
}
.gear-options {
grid-template-columns: 1fr 1fr;
}
.gear-card {
min-height: 74px;
padding: 9px;
}
.gear-card strong {
margin-top: 23px;
font-size: 11px;
}
.gear-card small {
font-size: 8px;
}
.gear-icon {
width: 26px;
height: 26px;
border-width: 4px;
}
.palette-hint {
display: none;
}
.progress-block {
margin-top: 9px;
padding-top: 8px;
}
.toast {
top: 70px;
}
}
</style>
</head>
<body>
<div id="scene-container"></div>
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<p class="eyebrow">Clockwork Bay / Bay 07</p>
<h1>GEAR NETWORK</h1>
</div>
</div>
<div class="top-actions">
<button class="button" id="clear-button" type="button">Clear</button>
<button class="button" id="reset-button" type="button">Reset</button>
<button class="button primary" id="test-button" type="button">Test Network</button>
</div>
</header>
<aside class="panel mission">
<div class="panel-heading">
<h2>Network Brief</h2>
<span class="status-dot" id="status-dot"></span>
</div>
<p class="mission-copy">
Install a wheel in every outlined socket. The input drives both output
targets, but every mesh reverses the direction of rotation.
</p>
<div class="direction-list">
<div class="direction-row input">
<span>INPUT</span>
<strong>↻ CLOCKWISE</strong>
</div>
<div class="direction-row output-a">
<span>OUTPUT A</span>
<strong>↺ COUNTER-CW</strong>
</div>
<div class="direction-row output-b">
<span>OUTPUT B</span>
<strong>↻ CLOCKWISE</strong>
</div>
</div>
<ul class="rules">
<li>Only opposite profiles mesh. Matching profiles lock.</li>
<li>Click a wheel, then an orange socket.</li>
<li>Click an installed wheel to remove it.</li>
<li>Drag the board to orbit; scroll to zoom.</li>
</ul>
</aside>
<aside class="panel palette">
<div class="panel-heading">
<h2>Wheel Palette</h2>
<span class="status-dot" id="palette-dot"></span>
</div>
<div class="gear-options">
<button
class="gear-card cobalt selected"
data-type="cobalt"
type="button"
aria-pressed="true"
>
<span class="gear-icon" aria-hidden="true"></span>
<strong>COBALT · 12T</strong>
<small>Fast profile<br>1.00× ratio</small>
</button>
<button
class="gear-card amber"
data-type="amber"
type="button"
aria-pressed="false"
>
<span class="gear-icon" aria-hidden="true"></span>
<strong>AMBER · 18T</strong>
<small>Reduction profile<br>1.50× ratio</small>
</button>
</div>
<p class="palette-hint">
Opposite profiles mesh. The same profile cannot drive a neighboring gear.
Press 1 or 2 to switch wheels.
</p>
<div class="progress-block">
<div class="progress-label">
<span>SOCKET INSTALLATION</span>
<span id="progress-text">0 / 8</span>
</div>
<div class="progress-track">
<div class="progress-fill" id="progress-fill"></div>
</div>
</div>
</aside>
<div class="toast" id="toast" role="status" aria-live="polite"></div>
<div class="control-hint">DRAG TO ORBIT · SCROLL TO ZOOM · RIGHT-CLICK A WHEEL TO REMOVE</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Configuration and puzzle state
// ------------------------------------------------------------
const COLS = 7;
const ROWS = 6;
const CELL = 1.08;
const socketDefs = [
{ id: "s1", col: 1, row: 2 },
{ id: "s2", col: 2, row: 2 },
{ id: "s3", col: 3, row: 2 },
{ id: "s4", col: 3, row: 1 },
{ id: "s5", col: 4, row: 1 },
{ id: "s6", col: 5, row: 1 },
{ id: "s7", col: 4, row: 2 },
{ id: "s8", col: 5, row: 2 }
];
const input = {
id: "input",
col: 0,
row: 2,
type: "input",
target: 1
};
const outputs = [
{
id: "output-a",
col: 6,
row: 1,
type: "output",
target: -1,
label: "A · CCW"
},
{
id: "output-b",
col: 6,
row: 2,
type: "output",
target: 1,
label: "B · CW"
}
];
const socketById = new Map(socketDefs.map((socket) => [socket.id, socket]));
const socketByCell = new Map(
socketDefs.map((socket) => [cellKey(socket.col, socket.row), socket])
);
const placements = new Map();
const pickables = [];
const socketMarkers = new Map();
const gearObjects = new Map();
const outputObjects = new Map();
const particles = [];
let selectedType = "cobalt";
let testing = false;
let currentDirections = new Map();
let toastTimer = 0;
let pointerDown = null;
let pointerMoved = false;
const profileNames = {
cobalt: "Cobalt 12T",
amber: "Amber 18T"
};
function cellKey(col, row) {
return `${col},${row}`;
}
function worldX(col) {
return (col - (COLS - 1) / 2) * CELL;
}
function worldZ(row) {
return (row - (ROWS - 1) / 2) * CELL;
}
function neighborsOf(col, row) {
return [
{ col: col + 1, row },
{ col: col - 1, row },
{ col, row: row + 1 },
{ col, row: row - 1 }
];
}
// ------------------------------------------------------------
// Renderer, scene, camera, and custom orbit controls
// ------------------------------------------------------------
const container = document.getElementById("scene-container");
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x07111d, 17, 30);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x07111d, 0);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
container.appendChild(renderer.domElement);
const cameraState = {
yaw: 0.36,
pitch: 0.77,
distance: 12.7,
target: new THREE.Vector3(0, 0.05, 0)
};
function updateCamera() {
const { yaw, pitch, distance, target } = cameraState;
const horizontal = Math.cos(pitch) * distance;
camera.position.set(
target.x + Math.sin(yaw) * horizontal,
target.y + Math.sin(pitch) * distance,
target.z + Math.cos(yaw) * horizontal
);
camera.lookAt(target);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xb9e6ff, 0x142033, 1.55);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xc9edff, 2.4);
keyLight.position.set(4.5, 9, 5.5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -8;
keyLight.shadow.camera.right = 8;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -8;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 24;
keyLight.shadow.bias = -0.0006;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0xffae54, 1.1);
rimLight.position.set(-6, 4, -5);
scene.add(rimLight);
const cyanLight = new THREE.PointLight(0x2fb8ff, 13, 8, 2);
cyanLight.position.set(-3.2, 2.5, 1.2);
scene.add(cyanLight);
const amberLight = new THREE.PointLight(0xffa43d, 10, 7, 2);
amberLight.position.set(3.4, 2.1, -1.7);
scene.add(amberLight);
// ------------------------------------------------------------
// Shared geometry and materials
// ------------------------------------------------------------
const unitBox = new THREE.BoxGeometry(1, 1, 1);
function standardMaterial(color, roughness = 0.42, metalness = 0.52) {
return new THREE.MeshStandardMaterial({
color,
roughness,
metalness,
emissive: new THREE.Color(color).multiplyScalar(0.045)
});
}
const materials = {
cobalt: {
body: standardMaterial(0x268ed9),
tooth: standardMaterial(0x58c7ff, 0.3, 0.6),
hub: standardMaterial(0xc9f3ff, 0.28, 0.55)
},
amber: {
body: standardMaterial(0xe69527),
tooth: standardMaterial(0xffc45c, 0.32, 0.55),
hub: standardMaterial(0xfff0b9, 0.3, 0.45)
},
input: {
body: standardMaterial(0x1678ae),
tooth: standardMaterial(0x42c5ff, 0.25, 0.7),
hub: standardMaterial(0xd7f8ff, 0.22, 0.55)
},
outputA: {
body: standardMaterial(0x2a9c68),
tooth: standardMaterial(0x64efac, 0.25, 0.65),
hub: standardMaterial(0xdcffea, 0.25, 0.5)
},
outputB: {
body: standardMaterial(0xb77920),
tooth: standardMaterial(0xffc85c, 0.27, 0.6),
hub: standardMaterial(0xfff3c4, 0.25, 0.5)
}
};
const tileMaterials = [
standardMaterial(0x152b3e, 0.82, 0.18),
standardMaterial(0x183146, 0.82, 0.18),
standardMaterial(0x13283a, 0.82, 0.18)
];
const tileInsetMaterial = standardMaterial(0x0a1927, 0.95, 0.08);
const frameMaterial = standardMaterial(0x274257, 0.58, 0.42);
const baseMaterial = standardMaterial(0x0c1b29, 0.9, 0.12);
function addBlock(
parent,
x,
y,
z,
sx,
sy,
sz,
material,
rotationY = 0
) {
const mesh = new THREE.Mesh(unitBox, material);
mesh.position.set(x, y, z);
mesh.scale.set(sx, sy, sz);
mesh.rotation.y = rotationY;
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// ------------------------------------------------------------
// Voxel pegboard
// ------------------------------------------------------------
const boardGroup = new THREE.Group();
scene.add(boardGroup);
addBlock(
boardGroup,
0,
-0.38,
0,
COLS * CELL + 0.45,
0.42,
ROWS * CELL + 0.45,
baseMaterial
);
for (let row = 0; row < ROWS; row++) {
for (let col = 0; col < COLS; col++) {
const x = worldX(col);
const z = worldZ(row);
const tileMaterial = tileMaterials[(col + row * 2) % tileMaterials.length];
addBlock(
boardGroup,
x,
-0.085,
z,
0.98,
0.17,
0.98,
tileMaterial
);
addBlock(
boardGroup,
x,
0.006,
z,
0.75,
0.025,
0.75,
tileInsetMaterial
);
}
}
const borderY = -0.08;
for (let col = 0; col < COLS; col++) {
const x = worldX(col);
addBlock(
boardGroup,
x,
borderY,
worldZ(0) - CELL * 0.62,
0.98,
0.22,
0.13,
frameMaterial
);
addBlock(
boardGroup,
x,
borderY,
worldZ(ROWS - 1) + CELL * 0.62,
0.98,
0.22,
0.13,
frameMaterial
);
}
for (let row = 0; row < ROWS; row++) {
const z = worldZ(row);
addBlock(
boardGroup,
worldX(0) - CELL * 0.62,
borderY,
z,
0.13,
0.22,
0.98,
frameMaterial
);
addBlock(
boardGroup,
worldX(COLS - 1) + CELL * 0.62,
borderY,
z,
0.13,
0.22,
0.98,
frameMaterial
);
}
// ------------------------------------------------------------
// Voxel gear construction
// ------------------------------------------------------------
function makeVoxelGear(profile, materialSet, isPickable = false, socketId = null) {
const group = new THREE.Group();
const toothCount = profile === "amber" ? 18 : 12;
const toothRadius = profile === "amber" ? 0.49 : 0.39;
const add = (x, z, sx, sy, sz, material, rotation = 0) => {
const block = addBlock(
group,
x,
0,
z,
sx,
sy,
sz,
material,
rotation
);
if (isPickable) {
block.userData.active = true;
block.userData.kind = "gear";
block.userData.socketId = socketId;
pickables.push(block);
}
return block;
};
if (profile === "cobalt" || profile === "input") {
for (let ix = -1; ix <= 1; ix++) {
for (let iz = -1; iz <= 1; iz++) {
add(ix * 0.185, iz * 0.185, 0.172, 0.145, 0.172, materialSet.body);
}
}
} else {
for (let ix = -2; ix <= 2; ix++) {
for (let iz = -2; iz <= 2; iz++) {
if (Math.abs(ix) === 2 && Math.abs(iz) === 2) continue;
add(ix * 0.145, iz * 0.145, 0.132, 0.14, 0.132, materialSet.body);
}
}
}
for (let i = 0; i < toothCount; i++) {
const angle = (i / toothCount) * Math.PI * 2;
const x = Math.cos(angle) * toothRadius;
const z = Math.sin(angle) * toothRadius;
const toothWidth = profile === "amber" ? 0.082 : 0.112;
const toothLength = profile === "amber" ? 0.09 : 0.125;
add(
x,
z,
toothLength,
0.13,
toothWidth,
materialSet.tooth,
-angle
);
}
add(0, 0, 0.255, 0.205, 0.255, materialSet.hub);
return group;
}
// Fixed input wheel.
const inputGear = makeVoxelGear("input", materials.input);
inputGear.position.set(worldX(input.col), 0.12, worldZ(input.row));
inputGear.rotation.y = 0.08;
boardGroup.add(inputGear);
gearObjects.set(input.id, inputGear);
// Fixed output wheels.
for (const output of outputs) {
const materialSet =
output.id === "output-a" ? materials.outputA : materials.outputB;
const gear = makeVoxelGear(
output.id === "output-a" ? "cobalt" : "amber",
materialSet
);
gear.position.set(worldX(output.col), 0.12, worldZ(output.row));
gear.rotation.y = output.id === "output-a" ? 0.16 : -0.21;
boardGroup.add(gear);
outputObjects.set(output.id, {
gear,
beaconMaterial: standardMaterial(0x344b5e, 0.4, 0.4)
});
addBlock(
boardGroup,
worldX(output.col),
0.65,
worldZ(output.row),
0.14,
0.14,
0.14,
outputObjects.get(output.id).beaconMaterial
);
}
// ------------------------------------------------------------
// Socket frames
// ------------------------------------------------------------
function createSocketMarker(socket) {
const group = new THREE.Group();
group.position.set(worldX(socket.col), 0.07, worldZ(socket.row));
const markerMaterial = new THREE.MeshStandardMaterial({
color: 0xffb340,
roughness: 0.38,
metalness: 0.45,
emissive: 0x5b2d00,
emissiveIntensity: 0.45
});
const corner = 0.37;
const arm = 0.23;
for (const sx of [-1, 1]) {
for (const sz of [-1, 1]) {
const x = sx * corner;
const z = sz * corner;
const horizontal = addBlock(
group,
x - sx * arm * 0.18,
0,
z,
arm,
0.11,
0.075,
markerMaterial
);
const vertical = addBlock(
group,
x,
0,
z - sz * arm * 0.18,
0.075,
0.11,
arm,
markerMaterial
);
for (const block of [horizontal, vertical]) {
block.userData.active = true;
block.userData.kind = "socket";
block.userData.socketId = socket.id;
pickables.push(block);
}
}
}
boardGroup.add(group);
socketMarkers.set(socket.id, { group, material: markerMaterial });
}
socketDefs.forEach(createSocketMarker);
// ------------------------------------------------------------
// Direction sprites drawn with canvas, positioned over the board
// ------------------------------------------------------------
function makeDirectionSprite(text, clockwise, color) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 256;
const context = canvas.getContext("2d");
context.clearRect(0, 0, 256, 256);
context.beginPath();
context.arc(128, 104, 78, 0, Math.PI * 2);
context.fillStyle = "rgba(5, 14, 24, 0.82)";
context.fill();
context.strokeStyle = "rgba(146, 190, 218, 0.25)";
context.lineWidth = 3;
context.stroke();
const arcColor = `#${new THREE.Color(color).getHexString()}`;
const start = clockwise ? -Math.PI * 0.78 : Math.PI * 0.62;
const end = clockwise ? Math.PI * 0.62 : -Math.PI * 0.78;
context.beginPath();
context.arc(128, 101, 49, start, end, !clockwise);
context.strokeStyle = arcColor;
context.lineWidth = 13;
context.lineCap = "square";
context.stroke();
const endAngle = clockwise ? end : end;
const tangentAngle = clockwise ? endAngle + Math.PI / 2 : endAngle - Math.PI / 2;
const tipX = 128 + Math.cos(endAngle) * 49 + Math.cos(tangentAngle) * 22;
const tipY = 101 + Math.sin(endAngle) * 49 + Math.sin(tangentAngle) * 22;
const baseX = 128 + Math.cos(endAngle) * 49 - Math.cos(tangentAngle) * 6;
const baseY = 101 + Math.sin(endAngle) * 49 - Math.sin(tangentAngle) * 6;
const perpendicularX = -Math.sin(tangentAngle) * 15;
const perpendicularY = Math.cos(tangentAngle) * 15;
context.beginPath();
context.moveTo(tipX, tipY);
context.lineTo(baseX + perpendicularX, baseY + perpendicularY);
context.lineTo(baseX - perpendicularX, baseY - perpendicularY);
context.closePath();
context.fillStyle = arcColor;
context.fill();
context.font = "800 24px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = "#eaf7ff";
context.fillText(text, 128, 210);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(1.12, 1.12, 1);
sprite.renderOrder = 20;
return sprite;
}
const inputSprite = makeDirectionSprite("INPUT · CW", true, 0x38bdff);
inputSprite.position.set(worldX(input.col), 1.1, worldZ(input.row));
boardGroup.add(inputSprite);
for (const output of outputs) {
const sprite = makeDirectionSprite(
output.label,
output.target > 0,
output.target > 0 ? 0xffb340 : 0x58e39c
);
sprite.position.set(worldX(output.col), 1.12, worldZ(output.row));
boardGroup.add(sprite);
}
// Small voxel dust in the distance.
const dustMaterial = new THREE.MeshBasicMaterial({
color: 0x6fa2c0,
transparent: true,
opacity: 0.18
});
for (let i = 0; i < 34; i++) {
const dust = new THREE.Mesh(unitBox, dustMaterial);
const angle = (i / 34) * Math.PI * 2;
const radius = 5.2 + (i % 4) * 0.45;
dust.position.set(
Math.cos(angle) * radius,
0.6 + ((i * 7) % 9) * 0.17,
Math.sin(angle) * radius
);
const size = 0.025 + (i % 3) * 0.012;
dust.scale.setScalar(size);
scene.add(dust);
}
// ------------------------------------------------------------
// HUD and notifications
// ------------------------------------------------------------
const toast = document.getElementById("toast");
const testButton = document.getElementById("test-button");
const clearButton = document.getElementById("clear-button");
const resetButton = document.getElementById("reset-button");
const statusDot = document.getElementById("status-dot");
const paletteDot = document.getElementById("palette-dot");
const progressFill = document.getElementById("progress-fill");
const progressText = document.getElementById("progress-text");
const gearCards = [...document.querySelectorAll(".gear-card")];
function showToast(message, tone = "info", duration = 2700) {
clearTimeout(toastTimer);
toast.textContent = message;
toast.className = `toast show ${tone}`;
toastTimer = window.setTimeout(() => {
toast.className = "toast";
}, duration);
}
function updateHUD() {
const count = placements.size;
progressText.textContent = `${count} / ${socketDefs.length}`;
progressFill.style.width = `${(count / socketDefs.length) * 100}%`;
statusDot.className = "status-dot";
paletteDot.className = "status-dot";
if (count === socketDefs.length) {
statusDot.classList.add("good");
paletteDot.classList.add("good");
}
}
function selectType(type) {
selectedType = type;
for (const card of gearCards) {
const selected = card.dataset.type === type;
card.classList.toggle("selected", selected);
card.setAttribute("aria-pressed", String(selected));
}
}
for (const card of gearCards) {
card.addEventListener("click", () => selectType(card.dataset.type));
}
// ------------------------------------------------------------
// Placement, removal, and compatibility checks
// ------------------------------------------------------------
function findProfileConflict(socket, type) {
for (const neighbor of neighborsOf(socket.col, socket.row)) {
const neighborSocket = socketByCell.get(
cellKey(neighbor.col, neighbor.row)
);
if (!neighborSocket) continue;
const placed = placements.get(neighborSocket.id);
if (placed && placed.type === type) {
return neighborSocket;
}
}
return null;
}
function placeGear(socketId) {
const socket = socketById.get(socketId);
if (!socket || placements.has(socketId)) return;
const conflict = findProfileConflict(socket, selectedType);
if (conflict) {
showToast(
`${profileNames[selectedType]} cannot mesh with the adjacent ${profileNames[selectedType]}.`,
"bad"
);
flashSocket(conflict.id);
return;
}
stopTest(false);
const gear = makeVoxelGear(
selectedType,
materials[selectedType],
true,
socket.id
);
gear.position.set(worldX(socket.col), 0.12, worldZ(socket.row));
gear.rotation.y = Math.random() * Math.PI * 2;
gear.scale.setScalar(0.05);
boardGroup.add(gear);
const placement = {
id: socket.id,
type: selectedType,
group: gear,
spawn: 0
};
placements.set(socket.id, placement);
gearObjects.set(socket.id, gear);
const marker = socketMarkers.get(socket.id);
marker.group.visible = false;
for (const block of marker.group.children) {
block.userData.active = false;
}
updateHUD();
showToast(`${profileNames[selectedType]} seated in socket ${socket.id.slice(1)}.`, "good", 1500);
}
function removeGear(socketId) {
const placement = placements.get(socketId);
if (!placement) return;
stopTest(false);
boardGroup.remove(placement.group);
placements.delete(socketId);
gearObjects.delete(socketId);
const marker = socketMarkers.get(socketId);
marker.group.visible = true;
for (const block of marker.group.children) {
block.userData.active = true;
}
updateHUD();
showToast("Wheel removed.", "info", 1300);
}
function clearBoard(showMessage = true) {
stopTest(false);
for (const placement of placements.values()) {
boardGroup.remove(placement.group);
}
placements.clear();
for (const socket of socketDefs) {
const marker = socketMarkers.get(socket.id);
marker.group.visible = true;
marker.material.color.setHex(0xffb340);
marker.material.emissive.setHex(0x5b2d00);
marker.group.scale.setScalar(1);
for (const block of marker.group.children) {
block.userData.active = true;
}
}
for (const output of outputs) {
const object = outputObjects.get(output.id);
object.beaconMaterial.color.setHex(0x344b5e);
object.beaconMaterial.emissive.setHex(0x17232e);
}
updateHUD();
if (showMessage) {
showToast("Network cleared.", "info", 1500);
}
}
function flashSocket(socketId) {
const marker = socketMarkers.get(socketId);
marker.material.color.setHex(0xff657a);
marker.material.emissive.setHex(0x7a1020);
window.setTimeout(() => {
marker.material.color.setHex(0xffb340);
marker.material.emissive.setHex(0x5b2d00);
}, 850);
}
// ------------------------------------------------------------
// Network validation
// ------------------------------------------------------------
function validateNetwork() {
const missing = socketDefs.filter((socket) => !placements.has(socket.id));
const profileConflicts = [];
for (let i = 0; i < socketDefs.length; i++) {
const a = socketDefs[i];
const placedA = placements.get(a.id);
if (!placedA) continue;
for (const neighbor of neighborsOf(a.col, a.row)) {
const b = socketByCell.get(cellKey(neighbor.col, neighbor.row));
if (!b) continue;
const placedB = placements.get(b.id);
if (placedB && placedA.type === placedB.type) {
profileConflicts.push([a.id, b.id]);
}
}
}
const occupancy = new Map();
occupancy.set(cellKey(input.col, input.row), {
kind: "input",
id: input.id
});
for (const placement of placements.values()) {
const socket = socketById.get(placement.id);
occupancy.set(cellKey(socket.col, socket.row), {
kind: "gear",
id: placement.id,
type: placement.type
});
}
for (const output of outputs) {
occupancy.set(cellKey(output.col, output.row), {
kind: "output",
id: output.id,
target: output.target
});
}
const distances = new Map();
const directions = new Map();
const parityConflicts = [];
const queue = [];
const inputKey = cellKey(input.col, input.row);
distances.set(inputKey, 0);
directions.set(inputKey, 1);
queue.push(inputKey);
while (queue.length) {
const currentKey = queue.shift();
const [currentCol, currentRow] = currentKey.split(",").map(Number);
const current = occupancy.get(currentKey);
const currentDirection = directions.get(currentKey);
const currentDistance = distances.get(currentKey);
for (const neighbor of neighborsOf(currentCol, currentRow)) {
const neighborKey = cellKey(neighbor.col, neighbor.row);
const neighborObject = occupancy.get(neighborKey);
if (!neighborObject) continue;
// Outputs are endpoints, not transmission nodes.
if (neighborObject.kind === "output") {
if (!distances.has(neighborKey)) {
distances.set(neighborKey, currentDistance + 1);
directions.set(neighborKey, -currentDirection);
}
continue;
}
if (neighborObject.kind === "gear" && current.kind === "gear") {
if (current.type === neighborObject.type) continue;
}
const candidateDistance = currentDistance + 1;
const candidateDirection = -currentDirection;
if (!distances.has(neighborKey)) {
distances.set(neighborKey, candidateDistance);
directions.set(neighborKey, candidateDirection);
queue.push(neighborKey);
} else if (
distances.get(neighborKey) % 2 !== candidateDistance % 2
) {
parityConflicts.push(neighborObject.id);
}
}
}
const unreachableOutputs = outputs.filter(
(output) => !distances.has(cellKey(output.col, output.row))
);
const directionErrors = outputs.filter((output) => {
const key = cellKey(output.col, output.row);
if (!directions.has(key)) return false;
return directions.get(key) !== output.target;
});
const errors = [];
if (missing.length) {
errors.push(`${missing.length} socket${missing.length === 1 ? "" : "s"} still need a wheel.`);
}
if (profileConflicts.length) {
errors.push("Matching wheel profiles are touching and cannot mesh.");
}
if (parityConflicts.length) {
errors.push("The network contains an inconsistent rotation path.");
}
if (unreachableOutputs.length) {
errors.push(
`${unreachableOutputs.length} output target${unreachableOutputs.length === 1 ? " is" : "s are"} not connected.`
);
}
if (directionErrors.length) {
errors.push(
`${directionErrors.map((output) => output.label.split(" ")[0]).join(" and ")} target direction${directionErrors.length === 1 ? " does" : "s"} not match.`
);
}
return {
ok: errors.length === 0,
errors,
missing,
profileConflicts,
parityConflicts,
unreachableOutputs,
directionErrors,
directions,
distances
};
}
// ------------------------------------------------------------
// Test animation and success particles
// ------------------------------------------------------------
function setBeacon(output, state) {
const object = outputObjects.get(output.id);
if (state === "good") {
object.beaconMaterial.color.setHex(0x58e39c);
object.beaconMaterial.emissive.setHex(0x176d48);
} else if (state === "bad") {
object.beaconMaterial.color.setHex(0xff657a);
object.beaconMaterial.emissive.setHex(0x7a1020);
} else {
object.beaconMaterial.color.setHex(0x344b5e);
object.beaconMaterial.emissive.setHex(0x17232e);
}
}
function stopTest(showMessage = true) {
if (!testing) return;
testing = false;
currentDirections = new Map();
testButton.textContent = "Test Network";
testButton.classList.remove("running");
for (const output of outputs) {
setBeacon(output, "idle");
}
statusDot.className = "status-dot";
if (showMessage) {
showToast("Power isolated.", "info", 1400);
}
}
function runTest() {
if (testing) {
stopTest(true);
return;
}
const result = validateNetwork();
if (!result.ok) {
statusDot.className = "status-dot bad";
showToast(result.errors[0], "bad", 3600);
for (const [a, b] of result.profileConflicts) {
flashSocket(a);
flashSocket(b);
}
for (const socket of result.missing) {
flashSocket(socket.id);
}
for (const output of result.directionErrors) {
setBeacon(output, "bad");
}
return;
}
testing = true;
currentDirections = result.directions;
testButton.textContent = "Stop Test";
testButton.classList.add("running");
statusDot.className = "status-dot good";
for (const output of outputs) {
setBeacon(output, "good");
}
showToast(
"Power flowing. Both output targets are synchronized.",
"good",
3200
);
spawnSuccessParticles();
}
function spawnSuccessParticles() {
const colors = [0x37baff, 0xffb340, 0x58e39c];
for (const output of outputs) {
for (let i = 0; i < 18; i++) {
const material = new THREE.MeshBasicMaterial({
color: colors[i % colors.length],
transparent: true,
opacity: 1
});
const particle = new THREE.Mesh(unitBox, material);
const size = 0.045 + Math.random() * 0.055;
particle.scale.setScalar(size);
particle.position.set(
worldX(output.col) + (Math.random() - 0.5) * 0.25,
0.4 + Math.random() * 0.2,
worldZ(output.row) + (Math.random() - 0.5) * 0.25
);
scene.add(particle);
particles.push({
mesh: particle,
velocity: new THREE.Vector3(
(Math.random() - 0.5) * 2.3,
1.7 + Math.random() * 2.3,
(Math.random() - 0.5) * 2.3
),
life: 1.7
});
}
}
}
testButton.addEventListener("click", runTest);
clearButton.addEventListener("click", () => clearBoard(true));
resetButton.addEventListener("click", () => {
clearBoard(false);
selectType("cobalt");
showToast("Puzzle reset.", "info", 1500);
});
// ------------------------------------------------------------
// Raycasting and direct camera interaction
// ------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function updatePointer(event) {
const bounds = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - bounds.left) / bounds.width) * 2 - 1;
pointer.y = -((event.clientY - bounds.top) / bounds.height) * 2 + 1;
}
function pickAt(event) {
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
const activePickables = pickables.filter(
(object) => object.userData.active !== false
);
const hits = raycaster.intersectObjects(activePickables, false);
return hits.length ? hits[0].object : null;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
pointerDown = {
x: event.clientX,
y: event.clientY,
lastX: event.clientX,
lastY: event.clientY
};
pointerMoved = false;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (pointerDown) {
const dx = event.clientX - pointerDown.lastX;
const dy = event.clientY - pointerDown.lastY;
if (
Math.hypot(
event.clientX - pointerDown.x,
event.clientY - pointerDown.y
) > 5
) {
pointerMoved = true;
}
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.0045,
0.34,
1.3
);
pointerDown.lastX = event.clientX;
pointerDown.lastY = event.clientY;
updateCamera();
return;
}
const hit = pickAt(event);
renderer.domElement.style.cursor = hit ? "pointer" : "grab";
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (!pointerDown) return;
const wasMoved = pointerMoved;
pointerDown = null;
if (wasMoved || event.button !== 0) return;
const hit = pickAt(event);
if (!hit) return;
if (hit.userData.kind === "gear") {
removeGear(hit.userData.socketId);
} else if (hit.userData.kind === "socket") {
placeGear(hit.userData.socketId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = null;
});
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
const hit = pickAt(event);
if (hit?.userData.kind === "gear") {
removeGear(hit.userData.socketId);
}
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance + event.deltaY * 0.008,
8.2,
17.5
);
updateCamera();
},
{ passive: false }
);
window.addEventListener("keydown", (event) => {
if (event.key === "1") selectType("cobalt");
if (event.key === "2") selectType("amber");
if (event.key.toLowerCase() === "r") {
clearBoard(false);
showToast("Puzzle reset.", "info", 1300);
}
if (event.key === "Enter" && document.activeElement?.tagName !== "BUTTON") {
runTest();
}
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
// ------------------------------------------------------------
// Animation loop
// ------------------------------------------------------------
const clock = new THREE.Clock();
function easeOutBack(value) {
const c1 = 1.70158;
const c3 = c1 + 1;
return 1 + c3 * Math.pow(value - 1, 3) + c1 * Math.pow(value - 1, 2);
}
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
for (const placement of placements.values()) {
if (placement.spawn < 1) {
placement.spawn = Math.min(1, placement.spawn + delta * 3.8);
const scale = Math.max(0.05, easeOutBack(placement.spawn));
placement.group.scale.setScalar(scale);
}
if (testing) {
const socket = socketById.get(placement.id);
const direction = currentDirections.get(
cellKey(socket.col, socket.row)
);
if (direction) {
const speed = placement.type === "cobalt" ? 2.0 : 1.45;
placement.group.rotation.y += delta * speed * direction;
}
}
}
if (testing) {
inputGear.rotation.y += delta * 1.75;
for (const output of outputs) {
const object = outputObjects.get(output.id);
const direction = currentDirections.get(
cellKey(output.col, output.row)
);
if (direction) {
object.gear.rotation.y += delta * 1.35 * direction;
}
}
}
const beaconScale = 1 + Math.sin(performance.now() * 0.006) * 0.14;
inputSprite.position.y = 1.1 + Math.sin(performance.now() * 0.0022) * 0.035;
for (const output of outputs) {
const object = outputObjects.get(output.id);
object.beaconMaterial.emissiveIntensity =
testing ? 0.75 + beaconScale * 0.2 : 0.2;
}
for (let i = particles.length - 1; i >= 0; i--) {
const particle = particles[i];
particle.life -= delta;
particle.velocity.y -= 4.2 * delta;
particle.mesh.position.addScaledVector(particle.velocity, delta);
particle.mesh.rotation.x += delta * 3;
particle.mesh.rotation.y += delta * 4;
particle.mesh.material.opacity = Math.max(0, particle.life / 1.7);
if (particle.life <= 0) {
scene.remove(particle.mesh);
particle.mesh.material.dispose();
particles.splice(i, 1);
}
}
renderer.render(scene, camera);
}
updateHUD();
animate();
</script>
</body>
</html>
```