Prompt specification
Build or customize the Three.js 3D scene "Logic-rule construction 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: Logic-rule construction puzzle
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/logic-rule-construction-puzzle-x1856
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring Boolean logic gates and compound rules. Let users connect a bounded set of gates to satisfy a displayed truth table; evaluate all combinations and identify counterexamples rather than accepting only the current input. Voxel style.
Working Three.js Starter (logic-rule-construction-puzzle-x1856):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Logic Lab</title>
<style>
:root {
--bg: #07101c;
--panel: #0c1727;
--panel-2: #111f32;
--line: #263a54;
--text: #eaf4ff;
--muted: #8ba2bb;
--cyan: #55e6d0;
--blue: #62a8ff;
--purple: #b37cff;
--yellow: #ffd166;
--red: #ff637c;
--green: #64ef9a;
--shadow: 0 8px 0 rgba(0, 0, 0, .24);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
}
button {
font: inherit;
color: inherit;
cursor: pointer;
}
button:focus-visible,
tr:focus-visible {
outline: 3px solid var(--yellow);
outline-offset: 2px;
}
header {
height: 64px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
padding: 0 18px;
background: #091422;
border-bottom: 3px solid #1c3049;
box-shadow: var(--shadow);
z-index: 10;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-cube {
width: 30px;
height: 30px;
background: var(--cyan);
border: 5px solid #174d50;
box-shadow: 6px 6px 0 #234969;
transform: rotate(-4deg);
}
.brand h1 {
margin: 0;
font-size: 17px;
letter-spacing: .09em;
white-space: nowrap;
}
.brand small {
display: block;
color: var(--muted);
font-size: 10px;
letter-spacing: .12em;
margin-top: 3px;
}
.toolbar {
display: flex;
align-items: center;
gap: 8px;
}
.toolbar button,
.small-button {
border: 2px solid var(--line);
background: var(--panel-2);
padding: 8px 11px;
box-shadow: 3px 3px 0 #050b13;
font-size: 11px;
letter-spacing: .04em;
}
.toolbar button:hover,
.small-button:hover {
border-color: var(--cyan);
color: var(--cyan);
}
.primary {
background: var(--cyan) !important;
color: #06131b !important;
border-color: #9ffff0 !important;
font-weight: 800;
}
main {
height: calc(100% - 64px);
display: grid;
grid-template-columns: 264px minmax(420px, 1fr) 330px;
}
aside {
min-width: 0;
overflow-y: auto;
background: var(--panel);
padding: 15px;
scrollbar-color: #29415e #0c1727;
}
#left-panel {
border-right: 3px solid #1c3049;
}
#right-panel {
border-left: 3px solid #1c3049;
}
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 3px 0 8px;
color: #cfe3f7;
font-size: 12px;
font-weight: 800;
letter-spacing: .12em;
text-transform: uppercase;
}
.micro {
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
.card {
margin-top: 12px;
padding: 12px;
background: #101d2e;
border: 2px solid var(--line);
box-shadow: 4px 4px 0 #050b13;
}
.challenge-name {
color: var(--yellow);
font-size: 14px;
font-weight: 800;
margin-bottom: 8px;
}
#rule-reveal {
display: none;
margin: 9px 0;
padding: 9px;
color: var(--cyan);
background: #071722;
border-left: 4px solid var(--cyan);
font-size: 11px;
line-height: 1.45;
word-break: break-word;
}
#rule-reveal.visible { display: block; }
.button-row {
display: flex;
gap: 7px;
margin-top: 10px;
}
.button-row button {
flex: 1;
border: 2px solid var(--line);
background: #0b1523;
padding: 8px 6px;
font-size: 10px;
}
.button-row button:hover {
color: var(--cyan);
border-color: var(--cyan);
}
.palette {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-top: 10px;
}
.gate-button {
position: relative;
min-height: 74px;
padding: 11px 8px;
text-align: left;
background: #15243a;
border: 2px solid #304863;
box-shadow: 4px 4px 0 #050b13;
}
.gate-button:hover:not(:disabled) {
transform: translateY(-2px);
border-color: var(--cyan);
}
.gate-button:disabled {
opacity: .35;
cursor: not-allowed;
}
.gate-button strong {
display: block;
font-size: 15px;
letter-spacing: .08em;
}
.gate-button .count {
position: absolute;
right: 7px;
bottom: 7px;
color: var(--muted);
font-size: 10px;
}
.gate-button .gate-icon {
display: block;
width: 26px;
height: 26px;
margin-top: 9px;
border: 5px solid currentColor;
border-right-width: 8px;
box-shadow: 5px 5px 0 #07101b;
}
.gate-button[data-type="AND"] { color: var(--blue); }
.gate-button[data-type="OR"] { color: var(--purple); }
.gate-button[data-type="NOT"] { color: var(--red); }
.gate-button[data-type="XOR"] { color: var(--cyan); }
.budget {
display: flex;
justify-content: space-between;
margin: 9px 0 4px;
color: var(--muted);
font-size: 10px;
}
.budget strong { color: var(--cyan); }
.inspector-title {
font-size: 13px;
font-weight: 800;
color: var(--yellow);
margin-bottom: 6px;
}
#delete-gate {
width: 100%;
margin-top: 10px;
border: 2px solid #713244;
background: #321824;
color: #ff9aac;
padding: 8px;
font-size: 10px;
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 30%, #12243b 0%, #091321 62%, #050b13 100%);
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.hud {
position: absolute;
top: 14px;
left: 50%;
transform: translateX(-50%);
z-index: 2;
width: min(620px, calc(100% - 28px));
pointer-events: none;
}
#status-badge {
display: inline-flex;
align-items: center;
gap: 9px;
max-width: 100%;
padding: 9px 13px;
background: #08131fee;
border: 2px solid #344c68;
box-shadow: 4px 4px 0 #03080dcc;
font-size: 11px;
font-weight: 800;
letter-spacing: .05em;
}
#status-dot {
width: 10px;
height: 10px;
flex: 0 0 auto;
background: var(--yellow);
box-shadow: 0 0 12px currentColor;
}
#status-badge.pass {
color: var(--green);
border-color: #327751;
}
#status-badge.pass #status-dot { background: var(--green); }
#status-badge.fail {
color: var(--red);
border-color: #793448;
}
#status-badge.fail #status-dot { background: var(--red); }
#status-badge.invalid {
color: var(--yellow);
border-color: #715d2d;
}
#status-badge.invalid #status-dot { background: var(--yellow); }
#status-detail {
margin-top: 7px;
color: #bdd0e4;
text-align: center;
font-size: 10px;
text-shadow: 0 2px 4px #000;
}
.stage-help {
position: absolute;
left: 13px;
bottom: 13px;
padding: 9px 11px;
background: #07111ddd;
border: 2px solid #203650;
color: var(--muted);
font-size: 9px;
line-height: 1.65;
pointer-events: none;
}
.stage-help b { color: var(--cyan); }
.legend {
display: flex;
flex-wrap: wrap;
gap: 11px;
margin-top: 10px;
color: var(--muted);
font-size: 9px;
}
.legend span::before {
content: "";
display: inline-block;
width: 8px;
height: 8px;
margin-right: 5px;
background: var(--cyan);
}
.legend .input::before { background: var(--yellow); }
.legend .bad::before { background: var(--red); }
.legend .good::before { background: var(--green); }
.table-wrap {
overflow-x: auto;
border: 2px solid var(--line);
background: #08121f;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 10px;
}
th {
padding: 9px 5px;
color: var(--muted);
background: #142237;
border-bottom: 2px solid var(--line);
font-size: 9px;
letter-spacing: .04em;
}
td {
padding: 7px 5px;
text-align: center;
border-bottom: 1px solid #192a40;
}
tr[data-row] { cursor: pointer; }
tr[data-row]:hover { background: #14263b; }
tr.current { outline: 2px solid var(--blue); outline-offset: -2px; }
tr.fail { background: #3a1725aa; }
tr.pass { background: #12352866; }
.bit {
display: inline-block;
min-width: 19px;
padding: 3px;
color: #70869d;
background: #142235;
border: 1px solid #263b55;
}
.bit.on {
color: #07131b;
background: var(--cyan);
border-color: var(--cyan);
font-weight: 800;
}
.target-bit.on {
color: #07131b;
background: var(--yellow);
border-color: var(--yellow);
}
.verdict.pass { color: var(--green); }
.verdict.fail { color: var(--red); }
.verdict.pending { color: #6d8198; }
.summary {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-top: 12px;
}
.summary-box {
min-width: 0;
padding: 9px 5px;
text-align: center;
background: #101d2e;
border: 2px solid var(--line);
}
.summary-box strong {
display: block;
color: var(--cyan);
font-size: 15px;
}
.summary-box span {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 8px;
letter-spacing: .04em;
}
.issue-box {
margin-top: 11px;
padding: 10px;
color: #ffd98b;
background: #302718;
border: 2px solid #69522c;
font-size: 9px;
line-height: 1.55;
}
.issue-box strong {
display: block;
margin-bottom: 4px;
letter-spacing: .08em;
}
.issue-box ul {
margin: 0;
padding-left: 16px;
}
#toast {
position: fixed;
left: 50%;
bottom: 22px;
transform: translate(-50%, 30px);
z-index: 30;
max-width: min(560px, calc(100% - 30px));
padding: 10px 14px;
color: var(--text);
background: #13243aee;
border: 2px solid var(--cyan);
box-shadow: 5px 5px 0 #03080dcc;
font-size: 10px;
opacity: 0;
pointer-events: none;
transition: opacity .15s, transform .15s;
}
#toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.error {
border-color: var(--red);
}
@media (max-width: 1050px) {
main {
grid-template-columns: 230px minmax(380px, 1fr) 290px;
}
aside { padding: 11px; }
.palette { gap: 7px; }
}
@media (max-width: 820px) {
html, body { overflow: auto; }
header {
height: auto;
min-height: 64px;
flex-wrap: wrap;
padding: 10px 12px;
}
.toolbar { width: 100%; }
.toolbar button { flex: 1; }
main {
height: auto;
display: flex;
flex-direction: column;
}
#stage {
order: -1;
height: 62vh;
min-height: 480px;
}
aside {
overflow: visible;
border: 0;
border-top: 3px solid #1c3049;
}
.palette { grid-template-columns: repeat(4, 1fr); }
}
</style>
</head>
<body>
<header>
<div class="brand">
<div class="brand-cube"></div>
<div>
<h1>VOXEL LOGIC LAB</h1>
<small>COMPOUND CIRCUIT CHALLENGE</small>
</div>
</div>
<div class="toolbar">
<button id="evaluate-button">Evaluate all 8</button>
<button id="reset-circuit">Reset circuit</button>
<button id="reset-camera">Reset camera</button>
</div>
</header>
<main>
<aside id="left-panel">
<div class="panel-title">
<span>Gate rack</span>
<span id="total-budget">0 / 12</span>
</div>
<div class="micro">
Click a gate to place it. Drag its cyan output to an amber input.
Click a wire to remove it.
</div>
<div id="palette" class="palette"></div>
<div class="budget">
<span>Bounded circuit inventory</span>
<strong>12 gates maximum</strong>
</div>
<div class="card">
<div class="panel-title">Compound target</div>
<div id="challenge-name" class="challenge-name">—</div>
<div class="micro">
Build a forward circuit that matches every row of the truth table.
The highlighted row only changes the visible input lamps.
</div>
<div id="rule-reveal"></div>
<div class="button-row">
<button id="reveal-rule">Reveal rule</button>
<button id="new-challenge">New target</button>
</div>
</div>
<div class="card">
<div class="panel-title">Selected voxel</div>
<div id="inspector" class="micro">Nothing selected.</div>
<button id="delete-gate" hidden>Delete selected gate</button>
</div>
<div class="card">
<div class="panel-title">Controls</div>
<div class="micro">
Drag empty space: orbit<br>
Shift-drag / right-drag: pan<br>
Wheel: zoom<br>
Drag a gate body: reposition<br>
Delete: remove selected gate<br>
E: evaluate every input row
</div>
</div>
</aside>
<section id="stage">
<canvas id="scene"></canvas>
<div class="hud">
<div id="status-badge">
<span id="status-dot"></span>
<span id="status-text">OPEN CIRCUIT</span>
</div>
<div id="status-detail">Connect the output target to a source.</div>
</div>
<div class="stage-help">
<b>Wiring:</b> cyan cube = output · amber cube = input<br>
<b>Audit rail:</b> every lamp represents one of the eight truth-table rows.
</div>
</section>
<aside id="right-panel">
<div class="panel-title">Truth table</div>
<div class="micro" style="margin-bottom:9px">
Click a row to set A, B, and C. Scoring always evaluates all eight combinations.
</div>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<th>Target</th>
<th>Actual</th>
<th>Result</th>
</tr>
</thead>
<tbody id="truth-body"></tbody>
</table>
</div>
<div class="summary">
<div class="summary-box">
<strong id="audit-tested">8</strong>
<span>COMBINATIONS</span>
</div>
<div class="summary-box">
<strong id="audit-counter">—</strong>
<span>COUNTEREXAMPLES</span>
</div>
<div class="summary-box">
<strong id="audit-current">000</strong>
<span>CURRENT ROW</span>
</div>
</div>
<div id="issue-box" class="issue-box" hidden>
<strong>CIRCUIT DIAGNOSTIC</strong>
<ul id="issue-list"></ul>
</div>
<div class="card">
<div class="panel-title">Legend</div>
<div class="legend">
<span class="input">Input port</span>
<span>Source output</span>
<span class="good">Passing row</span>
<span class="bad">Counterexample</span>
</div>
</div>
<div class="card">
<div class="panel-title">Why “all rows”?</div>
<div class="micro">
A circuit that only handles the currently highlighted assignment can still
fail elsewhere. The audit rail and red truth-table rows expose every
failing input combination.
</div>
</div>
</aside>
</main>
<div id="toast"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = id => document.getElementById(id);
const inventory = {
NOT: { max: 3, color: 0xff637c },
AND: { max: 4, color: 0x62a8ff },
OR: { max: 3, color: 0xb37cff },
XOR: { max: 2, color: 0x55e6d0 }
};
const MAX_GATES = 12;
const MAX_CONNECTIONS = 28;
const challenges = [
{
name: "Hybrid blend",
rule: "A AND (B OR NOT C)",
fn: (a, b, c) => a && (b || !c)
},
{
name: "Odd pair / enable",
rule: "(A XOR B) OR C",
fn: (a, b, c) => (a !== b) || c
},
{
name: "Inverted gate",
rule: "NOT A AND (B OR C)",
fn: (a, b, c) => !a && (b || c)
},
{
name: "Fallback pair",
rule: "A OR (B AND C)",
fn: (a, b, c) => a || (b && c)
},
{
name: "Consensus echo",
rule: "(A AND NOT B) OR (NOT A AND C)",
fn: (a, b, c) => (a && !b) || (!a && c)
}
];
let challengeIndex = 0;
let targetValues = [];
let currentIndex = 0;
let selectedNodeId = null;
let nextGateNumber = 1;
let nextConnectionNumber = 1;
const nodes = new Map();
const connections = new Map();
let lastEval = {
valid: false,
actuals: Array(8).fill(null),
counterexamples: [],
issues: []
};
// ---------- Renderer, scene, camera ----------
const canvas = $("scene");
const stage = $("stage");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x081220);
scene.fog = new THREE.Fog(0x081220, 24, 45);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const cameraState = {
yaw: 0,
pitch: 0.06,
radius: 19,
target: new THREE.Vector3(0, 0.25, 0)
};
function updateCamera() {
const cp = Math.cos(cameraState.pitch);
const sp = Math.sin(cameraState.pitch);
const sy = Math.sin(cameraState.yaw);
const cy = Math.cos(cameraState.yaw);
camera.position.set(
cameraState.target.x + cameraState.radius * sy * cp,
cameraState.target.y + cameraState.radius * sp,
cameraState.target.z + cameraState.radius * cy * cp
);
camera.lookAt(cameraState.target);
camera.updateMatrixWorld();
}
updateCamera();
scene.add(new THREE.HemisphereLight(0xb9dcff, 0x18202d, 2.1));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.6);
keyLight.position.set(-8, 12, 16);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -15;
keyLight.shadow.camera.right = 15;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -12;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x35d7c2, 18, 30);
rimLight.position.set(8, 3, 9);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xffb85c, 12, 24);
warmLight.position.set(-8, -5, 8);
scene.add(warmLight);
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const plateGeometry = new THREE.BoxGeometry(1, 1, 1);
const rivetMaterial = new THREE.MeshStandardMaterial({
color: 0xb5c7d7,
roughness: 0.5,
metalness: 0.5
});
const selectionMaterial = new THREE.MeshBasicMaterial({
color: 0xffd166
});
const outputPortMaterial = new THREE.MeshStandardMaterial({
color: 0x55e6d0,
emissive: 0x0b554c,
emissiveIntensity: 1.3,
roughness: 0.35,
metalness: 0.2
});
const inputPortMaterial = new THREE.MeshStandardMaterial({
color: 0xffd166,
emissive: 0x65460a,
emissiveIntensity: 0.9,
roughness: 0.35,
metalness: 0.2
});
const board = new THREE.Mesh(
new THREE.BoxGeometry(19.2, 10.6, 0.35),
new THREE.MeshStandardMaterial({
color: 0x0b1727,
roughness: 0.92,
metalness: 0.05
})
);
board.position.set(0, 0, -0.82);
board.receiveShadow = true;
scene.add(board);
const grid = new THREE.GridHelper(19, 38, 0x34506e, 0x1b3049);
grid.rotation.x = Math.PI / 2;
grid.position.set(0, 0, -0.62);
grid.material.transparent = true;
grid.material.opacity = 0.28;
scene.add(grid);
let pickables = [];
function registerPick(mesh, pick) {
mesh.userData.pick = pick;
pickables.push(mesh);
}
// ---------- Pixel-style text sprites ----------
function makeTextSprite(lines, options = {}) {
const {
color = "#eaf4ff",
background = "#102035",
border = "#35506e",
width = 2.0
} = options;
const list = Array.isArray(lines) ? lines : [lines];
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = list.length > 1 ? 190 : 120;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (background) {
ctx.fillStyle = background;
ctx.fillRect(7, 7, canvas.width - 14, canvas.height - 14);
ctx.strokeStyle = border;
ctx.lineWidth = 8;
ctx.strokeRect(7, 7, canvas.width - 14, canvas.height - 14);
}
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = color;
if (list.length === 1) {
ctx.font = "bold 60px monospace";
ctx.fillText(list[0], canvas.width / 2, canvas.height / 2 + 2);
} else {
ctx.font = "bold 55px monospace";
ctx.fillText(list[0], canvas.width / 2, 65);
ctx.font = "bold 30px monospace";
ctx.fillText(list[1], canvas.width / 2, 135);
}
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(width, width * canvas.height / canvas.width, 1);
sprite.renderOrder = 20;
return sprite;
}
// ---------- Voxel nodes ----------
function createNode({
id,
kind,
type,
x,
y,
width = 2.4,
height = 1.7,
inputCount = 0,
slotIndex = null
}) {
const group = new THREE.Group();
group.position.set(x, y, 0);
const baseColors = {
A: 0x267f83,
B: 0x267f83,
C: 0x267f83,
OUT: 0xb36e35,
NOT: inventory.NOT.color,
AND: inventory.AND.color,
OR: inventory.OR.color,
XOR: inventory.XOR.color
};
const baseColor = new THREE.Color(baseColors[type] || 0x35506b);
const plateColor = baseColor.clone().lerp(new THREE.Color(0xffffff), 0.16);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: baseColor,
roughness: 0.76,
metalness: 0.12,
flatShading: true
});
const plateMaterial = new THREE.MeshStandardMaterial({
color: plateColor,
roughness: 0.63,
metalness: 0.08,
flatShading: true
});
const body = new THREE.Mesh(unitBox, bodyMaterial);
body.scale.set(width, height, 0.68);
body.castShadow = true;
body.receiveShadow = true;
registerPick(body, { type: "node", id });
group.add(body);
const plate = new THREE.Mesh(plateGeometry, plateMaterial);
plate.scale.set(width - 0.18, height - 0.18, 0.14);
plate.position.z = 0.38;
plate.castShadow = true;
registerPick(plate, { type: "node", id });
group.add(plate);
const rivetPositions = [
[-width / 2 + 0.15, height / 2 - 0.15],
[ width / 2 - 0.15, height / 2 - 0.15],
[-width / 2 + 0.15, -height / 2 + 0.15],
[ width / 2 - 0.15, -height / 2 + 0.15]
];
for (const [rx, ry] of rivetPositions) {
const rivet = new THREE.Mesh(unitBox, rivetMaterial);
rivet.scale.set(0.09, 0.09, 0.08);
rivet.position.set(rx, ry, 0.49);
group.add(rivet);
}
const selection = new THREE.Group();
selection.visible = false;
for (const sx of [-1, 1]) {
for (const sy of [-1, 1]) {
const marker = new THREE.Mesh(unitBox, selectionMaterial);
marker.scale.set(0.2, 0.2, 0.2);
marker.position.set(
sx * (width / 2 + 0.05),
sy * (height / 2 + 0.05),
0.58
);
selection.add(marker);
}
}
group.add(selection);
let labelLines;
if (kind === "input") {
labelLines = [type, "SOURCE"];
} else if (kind === "output") {
labelLines = ["OUT", "TARGET"];
} else {
labelLines = [type, id];
}
const label = makeTextSprite(labelLines, {
color: kind === "output" ? "#fff0c9" : "#eef8ff",
background: kind === "output" ? "#402718" : "#102035",
border: kind === "output" ? "#bd7c38" : "#35506e",
width: kind === "gate" ? 1.9 : 1.45
});
label.position.z = 0.66;
group.add(label);
let led = null;
if (kind === "input" || kind === "output") {
const ledMaterial = new THREE.MeshStandardMaterial({
color: 0x263c4b,
emissive: 0x071018,
emissiveIntensity: 1,
roughness: 0.4
});
led = new THREE.Mesh(unitBox, ledMaterial);
led.scale.set(0.23, 0.23, 0.18);
led.position.set(0, -height / 2 + 0.24, 0.55);
group.add(led);
}
const ports = [];
if (kind === "input" || kind === "gate") {
const port = new THREE.Mesh(unitBox, outputPortMaterial);
const portX = kind === "input" ? width / 2 + 0.12 : width / 2 + 0.14;
port.scale.set(0.28, 0.28, 0.28);
port.position.set(portX, 0, 0.52);
registerPick(port, { type: "port", id, port: "out" });
group.add(port);
ports.push({ id: "out", mesh: port });
}
if (kind === "gate" || kind === "output") {
for (let i = 0; i < inputCount; i++) {
const port = new THREE.Mesh(unitBox, inputPortMaterial);
let portY = 0;
if (kind === "gate" && inputCount === 2) {
portY = i === 0 ? 0.46 : -0.46;
}
port.scale.set(0.28, 0.28, 0.28);
port.position.set(-width / 2 - 0.14, portY, 0.52);
registerPick(port, { type: "port", id, port: `in${i}` });
group.add(port);
ports.push({ id: `in${i}`, mesh: port });
}
}
const node = {
id,
kind,
type,
x,
y,
width,
height,
inputCount,
slotIndex,
group,
body,
plate,
selection,
led,
ports
};
nodes.set(id, node);
scene.add(group);
return node;
}
createNode({
id: "A", kind: "input", type: "A",
x: -7.35, y: 2.5, width: 1.65, height: 1.65
});
createNode({
id: "B", kind: "input", type: "B",
x: -7.35, y: 0, width: 1.65, height: 1.65
});
createNode({
id: "C", kind: "input", type: "C",
x: -7.35, y: -2.5, width: 1.65, height: 1.65
});
createNode({
id: "OUT", kind: "output", type: "OUT",
x: 7.15, y: 0, width: 1.95, height: 2.15, inputCount: 1
});
const outputNode = nodes.get("OUT");
// ---------- Eight-row audit rail ----------
const auditRail = new THREE.Group();
auditRail.position.set(0.65, 4.35, -0.15);
scene.add(auditRail);
const railBase = new THREE.Mesh(
unitBox,
new THREE.MeshStandardMaterial({
color: 0x101f31,
roughness: 0.85,
metalness: 0.08
})
);
railBase.scale.set(7.25, 1.16, 0.24);
railBase.position.z = -0.1;
auditRail.add(railBase);
const railTitle = makeTextSprite("8-ROW AUDIT", {
color: "#bcd7ef",
background: null,
border: null,
width: 1.9
});
railTitle.position.set(0, 0.82, 0.25);
auditRail.add(railTitle);
const auditLamps = [];
for (let i = 0; i < 8; i++) {
const x = (i - 3.5) * 0.78;
const material = new THREE.MeshStandardMaterial({
color: 0x354454,
emissive: 0x101820,
emissiveIntensity: 1,
roughness: 0.4
});
const lamp = new THREE.Mesh(unitBox, material);
lamp.scale.set(0.42, 0.42, 0.42);
lamp.position.set(x, 0.12, 0.14);
lamp.userData.row = i;
auditRail.add(lamp);
auditLamps.push(lamp);
const bits = [
(i >> 2) & 1,
(i >> 1) & 1,
i & 1
].join("");
const label = makeTextSprite(bits, {
color: "#8da4bd",
background: null,
border: null,
width: 0.64
});
label.position.set(x, -0.39, 0.2);
auditRail.add(label);
}
// ---------- Palette ----------
const palette = $("palette");
for (const [type, info] of Object.entries(inventory)) {
const button = document.createElement("button");
button.className = "gate-button";
button.dataset.type = type;
button.innerHTML = `
<strong>${type}</strong>
<span class="gate-icon"></span>
<span class="count">0 / ${info.max}</span>
`;
button.addEventListener("click", () => addGate(type));
palette.appendChild(button);
}
const gateSlots = [
[-3.85, 2.45], [-1.15, 2.45], [1.55, 2.45], [4.25, 2.45],
[-3.85, 0], [-1.15, 0], [1.55, 0], [4.25, 0],
[-3.85, -2.45], [-1.15, -2.45], [1.55, -2.45], [4.25, -2.45]
];
function gateCount() {
let count = 0;
for (const node of nodes.values()) {
if (node.kind === "gate") count++;
}
return count;
}
function typeCount(type) {
let count = 0;
for (const node of nodes.values()) {
if (node.kind === "gate" && node.type === type) count++;
}
return count;
}
function updatePalette() {
const total = gateCount();
$("total-budget").textContent = `${total} / ${MAX_GATES}`;
for (const button of palette.querySelectorAll(".gate-button")) {
const type = button.dataset.type;
const count = typeCount(type);
const max = inventory[type].max;
button.querySelector(".count").textContent = `${count} / ${max}`;
button.disabled = count >= max || total >= MAX_GATES;
}
}
function addGate(type) {
const total = gateCount();
if (total >= MAX_GATES) {
showToast("The circuit is limited to 12 gates.", true);
return;
}
if (typeCount(type) >= inventory[type].max) {
showToast(`No ${type} gates remain in the rack.`, true);
return;
}
const occupied = new Set(
[...nodes.values()]
.filter(node => node.kind === "gate")
.map(node => node.slotIndex)
);
let slotIndex = gateSlots.findIndex((_, index) => !occupied.has(index));
if (slotIndex === -1) {
showToast("No free gate position is available.", true);
return;
}
const [x, y] = gateSlots[slotIndex];
const id = `G${nextGateNumber++}`;
const inputCount = type === "NOT" ? 1 : 2;
createNode({
id,
kind: "gate",
type,
x,
y,
width: 2.4,
height: 1.7,
inputCount,
slotIndex
});
selectNode(id);
updatePalette();
runEvaluation();
showToast(`${type} gate ${id} placed. Drag its cyan output to an amber input.`);
}
// ---------- Selection and inspector ----------
function selectNode(id) {
selectedNodeId = id;
for (const node of nodes.values()) {
node.selection.visible = node.id === id;
}
renderInspector();
}
function renderInspector() {
const inspector = $("inspector");
const deleteButton = $("delete-gate");
if (!selectedNodeId || !nodes.has(selectedNodeId)) {
inspector.textContent = "Click a voxel gate or wire to select it.";
deleteButton.hidden = true;
return;
}
const node = nodes.get(selectedNodeId);
if (node.kind === "gate") {
inspector.innerHTML = `
<div class="inspector-title">${node.id} · ${node.type}</div>
${node.inputCount} input${node.inputCount === 1 ? "" : "s"} · 1 output<br>
Drag the gate body to reposition it.
`;
deleteButton.hidden = false;
} else if (node.kind === "input") {
inspector.innerHTML = `
<div class="inspector-title">Input ${node.type}</div>
Fixed source. Its output can fan out to multiple gates.
`;
deleteButton.hidden = true;
} else {
inspector.innerHTML = `
<div class="inspector-title">Output target</div>
Exactly one source must feed this amber input.
`;
deleteButton.hidden = true;
}
}
function deleteSelectedGate() {
if (!selectedNodeId) return;
const node = nodes.get(selectedNodeId);
if (!node || node.kind !== "gate") {
showToast("Only placed gates can be deleted.", true);
return;
}
removeNode(node.id);
selectNode(null);
updatePalette();
runEvaluation();
showToast(`${node.id} removed.`);
}
function removeNode(id) {
const node = nodes.get(id);
if (!node) return;
for (const [connectionId, connection] of connections) {
if (connection.from === id || connection.to === id) {
connections.delete(connectionId);
}
}
pickables = pickables.filter(mesh => {
const pick = mesh.userData.pick;
return !(pick && pick.type === "node" && pick.id === id);
});
scene.remove(node.group);
nodes.delete(id);
renderConnections();
}
$("delete-gate").addEventListener("click", deleteSelectedGate);
// ---------- Connections ----------
function incomingConnection(nodeId, portId) {
for (const connection of connections.values()) {
if (connection.to === nodeId && connection.toPort === portId) {
return connection;
}
}
return null;
}
function nodeLabel(id) {
const node = nodes.get(id);
if (!node) return id;
if (node.kind === "gate") return `${id} (${node.type})`;
if (node.kind === "output") return "OUT target";
return `input ${node.type}`;
}
function portWorldPosition(nodeId, portId) {
const node = nodes.get(nodeId);
const port = node?.ports.find(p => p.id === portId);
if (!port) return new THREE.Vector3();
const position = new THREE.Vector3();
port.mesh.getWorldPosition(position);
return position;
}
function pathWouldCycle(from, to) {
if (from === to) return true;
const visited = new Set();
const stack = [to];
while (stack.length) {
const current = stack.pop();
if (current === from) return true;
if (visited.has(current)) continue;
visited.add(current);
for (const connection of connections.values()) {
if (connection.from === current) {
stack.push(connection.to);
}
}
}
return false;
}
function connectNodes(from, to, toPort) {
const source = nodes.get(from);
const target = nodes.get(to);
if (!source || !target) return false;
if (target.kind === "gate" && target.type === "NOT" && toPort !== "in0") {
showToast("A NOT gate has only one input.", true);
return false;
}
if (pathWouldCycle(from, to)) {
showToast("That connection would create a feedback cycle.", true);
return false;
}
const existing = incomingConnection(to, toPort);
if (existing) {
connections.delete(existing.id);
} else if (connections.size >= MAX_CONNECTIONS) {
showToast("The circuit has reached its 28-connection limit.", true);
return false;
}
const id = `C${nextConnectionNumber++}`;
connections.set(id, {
id,
from,
fromPort: "out",
to,
toPort
});
renderConnections();
runEvaluation();
showToast(`Connected ${nodeLabel(from)} to ${nodeLabel(to)} ${toPort}.`);
return true;
}
function removeConnection(id) {
if (!connections.has(id)) return;
connections.delete(id);
renderConnections();
runEvaluation();
showToast("Connection removed.");
}
const connectionGroups = new Map();
function createSegment(a, b, material, connectionId) {
const delta = new THREE.Vector3().subVectors(b, a);
const length = delta.length();
if (length < 0.001) return;
const segment = new THREE.Mesh(unitBox, material);
const midpoint = new THREE.Vector3().addVectors(a, b).multiplyScalar(0.5);
segment.position.copy(midpoint);
if (Math.abs(delta.x) >= Math.abs(delta.y)) {
segment.scale.set(length + 0.11, 0.13, 0.13);
} else {
segment.scale.set(0.13, length + 0.11, 0.13);
}
registerPick(segment, { type: "connection", id: connectionId });
return segment;
}
function renderConnections() {
pickables = pickables.filter(mesh =>
mesh.userData.pick?.type !== "connection"
);
for (const group of connectionGroups.values()) {
scene.remove(group);
group.traverse(object => {
if (object.material && !Array.isArray(object.material)) {
object.material.dispose();
}
});
}
connectionGroups.clear();
for (const connection of connections.values()) {
const group = new THREE.Group();
scene.add(group);
const p0 = portWorldPosition(connection.from, connection.fromPort);
const p1 = portWorldPosition(connection.to, connection.toPort);
const middleX = (p0.x + p1.x) * 0.5;
const cornerA = new THREE.Vector3(middleX, p0.y, 0.49);
const cornerB = new THREE.Vector3(middleX, p1.y, 0.49);
const material = new THREE.MeshStandardMaterial({
color: 0x4cdfc9,
emissive: 0x0c4c45,
emissiveIntensity: 0.8,
roughness: 0.5,
metalness: 0.15
});
group.add(createSegment(p0, cornerA, material, connection.id));
group.add(createSegment(cornerA, cornerB, material, connection.id));
group.add(createSegment(cornerB, p1, material, connection.id));
for (const point of [cornerA, cornerB]) {
const joint = new THREE.Mesh(unitBox, material);
joint.scale.set(0.2, 0.2, 0.2);
joint.position.copy(point);
group.add(joint);
}
connectionGroups.set(connection.id, group);
}
}
// ---------- Evaluation across all eight rows ----------
function assignmentForIndex(index) {
return {
A: (index >> 2) & 1,
B: (index >> 1) & 1,
C: index & 1
};
}
function evaluateNode(nodeId, assignment, memo, visiting) {
if (memo.has(nodeId)) return memo.get(nodeId);
if (visiting.has(nodeId)) {
throw new Error(`Cycle at ${nodeId}`);
}
const node = nodes.get(nodeId);
if (!node) return 0;
if (node.kind === "input") {
const value = Number(Boolean(assignment[node.type]));
memo.set(nodeId, value);
return value;
}
visiting.add(nodeId);
const inputValue = slot => {
const connection = incomingConnection(nodeId, `in${slot}`);
if (!connection) return 0;
return evaluateNode(connection.from, assignment, memo, visiting);
};
let value;
if (node.type === "NOT") {
value = inputValue(0) ? 0 : 1;
} else if (node.type === "AND") {
value = inputValue(0) && inputValue(1) ? 1 : 0;
} else if (node.type === "OR") {
value = inputValue(0) || inputValue(1) ? 1 : 0;
} else if (node.type === "XOR") {
value = inputValue(0) !== inputValue(1) ? 1 : 0;
} else {
value = 0;
}
visiting.delete(nodeId);
memo.set(nodeId, value);
return value;
}
function findCycle(reachable) {
const state = new Map();
function visit(id) {
if (state.get(id) === 1) return true;
if (state.get(id) === 2) return false;
state.set(id, 1);
for (const connection of connections.values()) {
if (connection.from === id && reachable.has(connection.to)) {
if (visit(connection.to)) return true;
}
}
state.set(id, 2);
return false;
}
for (const id of reachable) {
if (visit(id)) return true;
}
return false;
}
function runEvaluation(showMessage = false) {
const issues = [];
const reachable = new Set(["OUT"]);
const queue = ["OUT"];
while (queue.length) {
const targetId = queue.shift();
for (const connection of connections.values()) {
if (connection.to === targetId && !reachable.has(connection.from)) {
reachable.add(connection.from);
queue.push(connection.from);
}
}
}
const outputConnection = incomingConnection("OUT", "in0");
if (!outputConnection) {
issues.push("OUT target has no source.");
}
for (const nodeId of reachable) {
const node = nodes.get(nodeId);
if (!node) continue;
if (node.kind === "gate") {
for (let slot = 0; slot < node.inputCount; slot++) {
if (!incomingConnection(nodeId, `in${slot}`)) {
issues.push(`${nodeLabel(nodeId)} input ${slot + 1} is open.`);
}
}
}
}
if (findCycle(reachable)) {
issues.push("A feedback cycle exists in the output's forward path.");
}
const valid = issues.length === 0;
const actuals = Array(8).fill(null);
if (valid) {
for (let row = 0; row < 8; row++) {
const assignment = assignmentForIndex(row);
const memo = new Map();
try {
actuals[row] = evaluateNode(
outputConnection.from,
assignment,
memo,
new Set()
);
} catch (error) {
actuals[row] = null;
issues.push(error.message);
}
}
}
const finalValid = valid && actuals.every(value => value !== null);
const counterexamples = finalValid
? actuals
.map((value, row) => value === targetValues[row] ? -1 : row)
.filter(row => row !== -1)
: [];
lastEval = {
valid: finalValid,
actuals,
counterexamples,
issues
};
updateStatus();
renderTruthTable();
updateCurrentVisuals();
updateAuditRail();
if (showMessage) {
if (finalValid && counterexamples.length === 0) {
showToast("All 8 input combinations satisfy the target.");
} else if (finalValid) {
showToast(`${counterexamples.length} counterexample(s) found across all 8 rows.`, true);
} else {
showToast(`Circuit incomplete: ${issues[0]}`, true);
}
}
}
function updateStatus() {
const badge = $("status-badge");
const text = $("status-text");
const detail = $("status-detail");
const issueBox = $("issue-box");
const issueList = $("issue-list");
badge.classList.remove("pass", "fail", "invalid");
if (!lastEval.valid) {
badge.classList.add("invalid");
text.textContent = "OPEN / INVALID CIRCUIT";
detail.textContent = lastEval.issues[0] || "Complete the forward path before scoring.";
issueBox.hidden = false;
issueList.innerHTML = lastEval.issues
.map(issue => `<li>${issue}</li>`)
.join("");
$("audit-tested").textContent = "8";
$("audit-counter").textContent = "—";
} else if (lastEval.counterexamples.length === 0) {
badge.classList.add("pass");
text.textContent = "SATISFIED · 8 / 8";
detail.textContent = "Every input combination matches the displayed truth table.";
issueBox.hidden = true;
$("audit-tested").textContent = "8 / 8";
$("audit-counter").textContent = "0";
} else {
badge.classList.add("fail");
text.textContent = `COUNTEREXAMPLES · ${lastEval.counterexamples.length}`;
detail.textContent = "The circuit was evaluated on every row; failing rows are highlighted below.";
issueBox.hidden = true;
$("audit-tested").textContent = "8 / 8";
$("audit-counter").textContent = String(lastEval.counterexamples.length);
}
const outputColor = !lastEval.valid
? 0xb36e35
: lastEval.counterexamples.length === 0
? 0x348b58
: 0x9d3f55;
const plateColor = new THREE.Color(outputColor).lerp(
new THREE.Color(0xffffff),
0.16
);
outputNode.body.material.color.setHex(outputColor);
outputNode.plate.material.color.copy(plateColor);
outputNode.led.material.color.setHex(outputColor);
outputNode.led.material.emissive.setHex(outputColor);
outputNode.led.material.emissiveIntensity = 0.8;
}
function updateAuditRail() {
for (let row = 0; row < 8; row++) {
const lamp = auditLamps[row];
let color = 0x354454;
let emissive = 0x101820;
if (lastEval.valid) {
if (lastEval.counterexamples.includes(row)) {
color = 0xff637c;
emissive = 0x70162b;
} else {
color = 0x64ef9a;
emissive = 0x15592f;
}
}
lamp.material.color.setHex(color);
lamp.material.emissive.setHex(emissive);
lamp.material.emissiveIntensity = 1;
}
}
// ---------- Truth table ----------
function renderTruthTable() {
const body = $("truth-body");
body.innerHTML = "";
for (let row = 0; row < 8; row++) {
const assignment = assignmentForIndex(row);
const target = targetValues[row];
const actual = lastEval.valid ? lastEval.actuals[row] : null;
const isPass = lastEval.valid && actual === target;
const isFail = lastEval.valid && actual !== target;
const tr = document.createElement("tr");
tr.dataset.row = row;
tr.tabIndex = 0;
if (row === currentIndex) tr.classList.add("current");
if (isPass) tr.classList.add("pass");
if (isFail) tr.classList.add("fail");
tr.innerHTML = `
<td><span class="bit ${assignment.A ? "on" : ""}">${assignment.A}</span></td>
<td><span class="bit ${assignment.B ? "on" : ""}">${assignment.B}</span></td>
<td><span class="bit ${assignment.C ? "on" : ""}">${assignment.C}</span></td>
<td><span class="bit target-bit ${target ? "on" : ""}">${target}</span></td>
<td><span class="bit ${actual === 1 ? "on" : ""}">${actual === null ? "?" : actual}</span></td>
<td class="verdict ${isPass ? "pass" : isFail ? "fail" : "pending"}">
${isPass ? "✓" : isFail ? "✕" : "·"}
</td>
`;
const chooseRow = () => {
currentIndex = row;
renderTruthTable();
updateCurrentVisuals();
};
tr.addEventListener("click", chooseRow);
tr.addEventListener("keydown", event => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
chooseRow();
}
});
body.appendChild(tr);
}
const bits = assignmentForIndex(currentIndex);
$("audit-current").textContent = `${bits.A}${bits.B}${bits.C}`;
}
function updateCurrentVisuals() {
const assignment = assignmentForIndex(currentIndex);
for (const id of ["A", "B", "C"]) {
const node = nodes.get(id);
const value = assignment[id];
node.led.material.color.setHex(value ? 0x64ef9a : 0x263c4b);
node.led.material.emissive.setHex(value ? 0x15592f : 0x071018);
node.led.material.emissiveIntensity = value ? 1.4 : 0.4;
node.plate.material.emissive.setHex(value ? 0x073c2e : 0x000000);
node.plate.material.emissiveIntensity = value ? 0.75 : 0;
}
}
// ---------- Challenges and reset ----------
function loadTargets() {
const challenge = challenges[challengeIndex];
targetValues = [];
for (let row = 0; row < 8; row++) {
const assignment = assignmentForIndex(row);
targetValues.push(
challenge.fn(assignment.A, assignment.B, assignment.C) ? 1 : 0
);
}
$("challenge-name").textContent =
`${challengeIndex + 1}. ${challenge.name}`;
const reveal = $("rule-reveal");
reveal.textContent = challenge.rule;
reveal.classList.remove("visible");
$("reveal-rule").textContent = "Reveal rule";
}
function clearGates() {
for (const node of [...nodes.values()]) {
if (node.kind === "gate") {
removeNode(node.id);
}
}
connections.clear();
renderConnections();
selectedNodeId = null;
updatePalette();
renderInspector();
}
$("reveal-rule").addEventListener("click", () => {
const reveal = $("rule-reveal");
const visible = reveal.classList.toggle("visible");
$("reveal-rule").textContent = visible ? "Hide rule" : "Reveal rule";
});
$("new-challenge").addEventListener("click", () => {
challengeIndex = (challengeIndex + 1) % challenges.length;
loadTargets();
clearGates();
currentIndex = 0;
runEvaluation();
showToast(`New compound target loaded: ${challenges[challengeIndex].name}`);
});
$("reset-circuit").addEventListener("click", () => {
clearGates();
currentIndex = 0;
runEvaluation();
showToast("Circuit cleared. Fixed inputs and output remain.");
});
$("evaluate-button").addEventListener("click", () => {
runEvaluation(true);
});
$("reset-camera").addEventListener("click", () => {
cameraState.yaw = 0;
cameraState.pitch = 0.06;
cameraState.radius = 19;
cameraState.target.set(0, 0.25, 0);
updateCamera();
});
// ---------- Direct camera and pointer controls ----------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
const previewPlane = new THREE.Plane(new THREE.Vector3(0, 0, 1), -0.52);
let interaction = null;
const previewMaterial = new THREE.LineBasicMaterial({
color: 0xffd166,
transparent: true,
opacity: 0.95
});
const previewGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(),
new THREE.Vector3()
]);
const previewLine = new THREE.Line(previewGeometry, previewMaterial);
previewLine.visible = false;
previewLine.renderOrder = 30;
scene.add(previewLine);
function setPointer(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 getHit(event) {
setPointer(event);
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(pickables, false);
for (const intersection of intersections) {
if (intersection.object.userData.pick) {
return {
...intersection.object.userData.pick,
intersection
};
}
}
return null;
}
function rayPlanePoint(event, plane = dragPlane) {
setPointer(event);
raycaster.setFromCamera(pointer, camera);
const point = new THREE.Vector3();
return raycaster.ray.intersectPlane(plane, point) ? point : null;
}
function resetPortScales() {
for (const node of nodes.values()) {
for (const port of node.ports) {
port.mesh.scale.set(0.28, 0.28, 0.28);
}
}
}
function updatePreview(event) {
if (!interaction || interaction.mode !== "wire") return;
const start = portWorldPosition(interaction.source, "out");
const point = rayPlanePoint(event, previewPlane);
const end = point || start;
const positions = previewGeometry.attributes.position;
positions.setXYZ(0, start.x, start.y, start.z);
positions.setXYZ(1, end.x, end.y, end.z);
positions.needsUpdate = true;
previewGeometry.computeBoundingSphere();
}
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("pointerdown", event => {
if (event.button !== 0 && event.button !== 2) return;
event.preventDefault();
canvas.setPointerCapture(event.pointerId);
const hit = getHit(event);
if (event.button === 0 && hit?.type === "port" && hit.port === "out") {
interaction = {
mode: "wire",
source: hit.id,
startX: event.clientX,
startY: event.clientY
};
previewLine.visible = true;
updatePreview(event);
resetPortScales();
for (const node of nodes.values()) {
for (const port of node.ports) {
if (port.id !== "out") {
port.mesh.scale.set(0.35, 0.35, 0.35);
}
}
}
return;
}
if (event.button === 0 && hit?.type === "connection") {
interaction = {
mode: "deleteWire",
id: hit.id,
startX: event.clientX,
startY: event.clientY
};
return;
}
if (event.button === 0 && hit?.type === "node") {
const node = nodes.get(hit.id);
const point = rayPlanePoint(event);
interaction = {
mode: node?.kind === "gate" ? "gate" : "select",
id: hit.id,
offsetX: point ? node.x - point.x : 0,
offsetY: point ? node.y - point.y : 0,
startX: event.clientX,
startY: event.clientY,
moved: false
};
if (interaction.mode === "gate") {
canvas.style.cursor = "grabbing";
}
return;
}
interaction = {
mode: event.button === 2 || event.shiftKey ? "pan" : "orbit",
startX: event.clientX,
startY: event.clientY
};
});
canvas.addEventListener("pointermove", event => {
if (!interaction) {
const hit = getHit(event);
canvas.style.cursor = hit?.type === "port"
? "crosshair"
: hit?.type === "node"
? "grab"
: hit?.type === "connection"
? "pointer"
: "default";
return;
}
if (interaction.mode === "wire") {
updatePreview(event);
return;
}
if (interaction.mode === "gate") {
const point = rayPlanePoint(event);
const node = nodes.get(interaction.id);
if (point && node) {
node.x = THREE.MathUtils.clamp(
point.x + interaction.offsetX,
-5.3,
5.55
);
node.y = THREE.MathUtils.clamp(
point.y + interaction.offsetY,
-3.55,
3.45
);
node.group.position.set(node.x, node.y, 0);
interaction.moved = true;
renderConnections();
}
return;
}
const dx = event.clientX - interaction.startX;
const dy = event.clientY - interaction.startY;
if (interaction.mode === "orbit") {
cameraState.yaw -= dx * 0.005;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
-0.65,
0.65
);
updateCamera();
} else if (interaction.mode === "pan") {
const scale =
2 * Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)) *
cameraState.radius / stage.clientHeight;
cameraState.target.x -= dx * scale;
cameraState.target.y += dy * scale;
updateCamera();
}
interaction.startX = event.clientX;
interaction.startY = event.clientY;
});
canvas.addEventListener("pointerup", event => {
if (!interaction) return;
const current = interaction;
interaction = null;
if (current.mode === "wire") {
previewLine.visible = false;
resetPortScales();
const hit = getHit(event);
if (hit?.type === "port" && hit.port.startsWith("in")) {
connectNodes(current.source, hit.id, hit.port);
} else {
showToast("Drop the wire on an amber input cube.");
}
} else if (current.mode === "gate") {
selectNode(current.id);
runEvaluation();
} else if (current.mode === "select") {
selectNode(current.id);
} else if (current.mode === "deleteWire") {
const hit = getHit(event);
if (hit?.type === "connection" && hit.id === current.id) {
removeConnection(current.id);
}
}
canvas.style.cursor = "default";
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
});
canvas.addEventListener("pointercancel", () => {
interaction = null;
previewLine.visible = false;
resetPortScales();
});
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
11,
30
);
updateCamera();
}, { passive: false });
window.addEventListener("keydown", event => {
if (event.target instanceof HTMLInputElement ||
event.target instanceof HTMLTextAreaElement) return;
if (event.key === "Delete" || event.key === "Backspace") {
event.preventDefault();
deleteSelectedGate();
} else if (event.key.toLowerCase() === "e") {
runEvaluation(true);
} else if (event.key === "Escape") {
interaction = null;
previewLine.visible = false;
resetPortScales();
}
});
// ---------- Resize and animation ----------
function resize() {
const width = Math.max(1, stage.clientWidth);
const height = Math.max(1, stage.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(stage);
resize();
const clock = new THREE.Clock();
function animate() {
const time = clock.getElapsedTime();
for (let row = 0; row < auditLamps.length; row++) {
const lamp = auditLamps[row];
let scale = 1;
if (lastEval.valid && lastEval.counterexamples.includes(row)) {
scale = 1 + Math.sin(time * 5.5 + row * 0.7) * 0.16;
} else if (row === currentIndex) {
scale = 1.12;
}
lamp.scale.set(0.42 * scale, 0.42 * scale, 0.42 * scale);
}
if (lastEval.valid && lastEval.counterexamples.length) {
const pulse = 1 + Math.sin(time * 5) * 0.12;
outputNode.led.scale.set(0.23 * pulse, 0.23 * pulse, 0.18 * pulse);
} else {
outputNode.led.scale.set(0.23, 0.23, 0.18);
}
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
// ---------- Toast ----------
let toastTimer;
function showToast(message, error = false) {
const toast = $("toast");
toast.textContent = message;
toast.classList.toggle("error", error);
toast.classList.add("visible");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toast.classList.remove("visible");
}, 2800);
}
// ---------- Initialize ----------
loadTargets();
updatePalette();
renderInspector();
renderTruthTable();
updateCurrentVisuals();
updateAuditRail();
renderConnections();
runEvaluation();
animate();
</script>
</body>
</html>
```