Prompt specification
Build or customize the Three.js 3D scene "Perceptron update exploration board" 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: Perceptron update exploration board
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/perceptron-update-exploration-board-x1896
Scene Description Prompt:
I'd like to see this as a voxel Three.js scene: perceptron update exploration board. Let users step through a small linearly separable dataset with a stated update rule, then try an XOR dataset; show the linear model's limitation honestly. Use cdnjs and return one self-contained HTML file.
Working Three.js Starter (perceptron-update-exploration-board-x1896):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Perceptron — Voxel Exploration Board</title>
<style>
:root {
color-scheme: dark;
--bg: #080b16;
--panel: #101526;
--panel-2: #151b2e;
--line: rgba(170, 190, 225, 0.14);
--text: #edf3ff;
--muted: #929eb8;
--cyan: #55f2d0;
--coral: #ff7082;
--amber: #ffd166;
--blue: #76a9ff;
--shadow: 0 20px 60px rgba(0, 0, 0, 0.32);
--mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
--sans: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: var(--sans);
}
button, input { font: inherit; }
button {
color: inherit;
cursor: pointer;
}
.app {
height: 100%;
display: grid;
grid-template-rows: 70px minmax(0, 1fr);
background:
radial-gradient(circle at 82% 8%, rgba(67, 90, 173, 0.14), transparent 32%),
var(--bg);
}
header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 24px;
border-bottom: 1px solid var(--line);
background: rgba(8, 11, 22, 0.84);
backdrop-filter: blur(18px);
z-index: 10;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
position: relative;
width: 31px;
height: 31px;
flex: 0 0 auto;
}
.brand-mark i {
position: absolute;
width: 14px;
height: 14px;
border-radius: 3px;
background: var(--cyan);
box-shadow: 0 0 22px rgba(85, 242, 208, 0.3);
}
.brand-mark i:nth-child(1) { left: 1px; top: 1px; }
.brand-mark i:nth-child(2) { right: 1px; top: 1px; opacity: 0.62; }
.brand-mark i:nth-child(3) { left: 1px; bottom: 1px; opacity: 0.34; }
.brand h1 {
margin: 0;
font-size: 15px;
line-height: 1.1;
letter-spacing: 0.12em;
text-transform: uppercase;
white-space: nowrap;
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font: 11px/1.2 var(--mono);
letter-spacing: 0.04em;
white-space: nowrap;
}
.header-chip {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 8px 11px;
border: 1px solid var(--line);
border-radius: 999px;
color: #b8c4de;
background: rgba(255,255,255,0.025);
font: 11px var(--mono);
white-space: nowrap;
}
.header-chip::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px var(--cyan);
}
.workspace {
min-height: 0;
display: grid;
grid-template-columns: 354px minmax(0, 1fr);
}
aside {
min-height: 0;
overflow-y: auto;
padding: 18px;
border-right: 1px solid var(--line);
background: rgba(12, 16, 29, 0.88);
scrollbar-width: thin;
scrollbar-color: #2b3551 transparent;
}
.section {
padding-bottom: 17px;
margin-bottom: 17px;
border-bottom: 1px solid var(--line);
}
.section:last-child {
border-bottom: 0;
margin-bottom: 0;
padding-bottom: 4px;
}
.eyebrow {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
color: var(--muted);
font: 10px var(--mono);
letter-spacing: 0.14em;
text-transform: uppercase;
}
.segmented {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 5px;
padding: 5px;
border: 1px solid var(--line);
border-radius: 12px;
background: #0b0f1d;
}
.segmented button {
border: 0;
border-radius: 8px;
padding: 10px 8px;
color: var(--muted);
background: transparent;
font-weight: 700;
transition: 160ms ease;
}
.segmented button:hover { color: var(--text); }
.segmented button.active {
color: #07110f;
background: var(--cyan);
box-shadow: 0 7px 24px rgba(85, 242, 208, 0.14);
}
.dataset-copy {
min-height: 48px;
margin: 11px 2px 0;
color: #aab5ce;
font-size: 12px;
line-height: 1.5;
}
.rule-card {
padding: 13px;
border: 1px solid rgba(118, 169, 255, 0.18);
border-radius: 12px;
background:
linear-gradient(135deg, rgba(118, 169, 255, 0.07), transparent 65%),
#0c1222;
}
.formula {
padding-bottom: 11px;
margin-bottom: 10px;
border-bottom: 1px solid var(--line);
color: #dce7ff;
font: 13px/1.6 var(--mono);
}
.formula b { color: var(--cyan); }
.update-lines {
display: grid;
gap: 6px;
color: #b8c5df;
font: 11px/1.5 var(--mono);
}
.update-lines code {
color: #dce7ff;
font: inherit;
}
.rule-note {
margin: 10px 0 0;
color: #7f8da9;
font-size: 10.5px;
line-height: 1.45;
}
.control-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.control-grid .wide { grid-column: 1 / -1; }
.control {
min-height: 42px;
border: 1px solid var(--line);
border-radius: 10px;
padding: 10px 12px;
background: #171d31;
font-weight: 750;
font-size: 12px;
transition: 150ms ease;
}
.control:hover:not(:disabled) {
transform: translateY(-1px);
border-color: rgba(85, 242, 208, 0.38);
background: #1b243a;
}
.control:active:not(:disabled) { transform: translateY(0); }
.control.primary {
color: #07110f;
border-color: transparent;
background: var(--cyan);
}
.control.primary:hover:not(:disabled) { background: #78f7dc; }
.control.running {
color: #11131b;
background: var(--amber);
border-color: transparent;
}
.control:disabled {
opacity: 0.42;
cursor: not-allowed;
}
.slider-row {
display: grid;
grid-template-columns: 56px 1fr 42px;
align-items: center;
gap: 9px;
margin-top: 12px;
color: var(--muted);
font: 10px var(--mono);
}
.slider-row output {
text-align: right;
color: #dce7ff;
}
input[type="range"] {
width: 100%;
accent-color: var(--cyan);
cursor: pointer;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
min-height: 70px;
padding: 11px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255,255,255,0.025);
}
.metric span {
display: block;
margin-bottom: 7px;
color: var(--muted);
font: 9px var(--mono);
letter-spacing: 0.09em;
text-transform: uppercase;
}
.metric strong {
display: block;
color: var(--text);
font: 18px var(--mono);
font-variant-numeric: tabular-nums;
}
.metric small {
display: block;
margin-top: 5px;
color: #74819c;
font: 9px var(--mono);
}
.weights {
margin-top: 9px;
padding: 10px 11px;
border: 1px solid var(--line);
border-radius: 10px;
color: #aebbd5;
background: #0b1020;
font: 10px/1.55 var(--mono);
}
.weights span { color: var(--muted); }
.status {
margin-bottom: 10px;
padding: 11px 12px;
border-left: 3px solid var(--blue);
border-radius: 4px 10px 10px 4px;
color: #c7d2e9;
background: rgba(118, 169, 255, 0.07);
font-size: 11.5px;
line-height: 1.45;
}
.status.good {
border-color: var(--cyan);
background: rgba(85, 242, 208, 0.07);
}
.status.warn {
border-color: var(--amber);
background: rgba(255, 209, 102, 0.07);
}
.status.limit {
border-color: var(--coral);
background: rgba(255, 112, 130, 0.07);
}
.insight {
padding: 12px;
border: 1px solid var(--line);
border-radius: 11px;
background: #0d1221;
}
.insight h3 {
margin: 0 0 7px;
color: #dce5f8;
font-size: 12px;
}
.insight p {
margin: 0;
color: #8996b1;
font-size: 11px;
line-height: 1.55;
}
.stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
isolation: isolate;
}
#viewport {
position: absolute;
inset: 0;
cursor: grab;
}
#viewport:active { cursor: grabbing; }
#viewport canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
}
.stage-top {
position: absolute;
top: 18px;
left: 20px;
right: 20px;
z-index: 4;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
pointer-events: none;
}
.stage-title {
padding: 11px 13px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(9, 13, 25, 0.72);
backdrop-filter: blur(12px);
}
.stage-title strong {
display: block;
font: 11px var(--mono);
letter-spacing: 0.08em;
text-transform: uppercase;
}
.stage-title span {
display: block;
margin-top: 5px;
color: var(--muted);
font-size: 10px;
}
.legend {
display: flex;
gap: 7px;
flex-wrap: wrap;
justify-content: flex-end;
padding: 9px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(9, 13, 25, 0.72);
backdrop-filter: blur(12px);
pointer-events: none;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
color: #aeb9d0;
font: 9px var(--mono);
}
.swatch {
width: 9px;
height: 9px;
border-radius: 2px;
background: var(--cyan);
box-shadow: 0 0 10px rgba(85, 242, 208, 0.35);
}
.swatch.negative { background: var(--coral); box-shadow: 0 0 10px rgba(255, 112, 130, 0.3); }
.swatch.boundary { background: var(--amber); box-shadow: 0 0 10px rgba(255, 209, 102, 0.3); }
.sequence-panel {
position: absolute;
left: 20px;
right: 20px;
bottom: 18px;
z-index: 4;
padding: 12px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(9, 13, 25, 0.83);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
pointer-events: none;
}
.sequence-head {
display: flex;
justify-content: space-between;
margin-bottom: 9px;
color: var(--muted);
font: 9px var(--mono);
letter-spacing: 0.1em;
text-transform: uppercase;
}
#sequence {
display: flex;
gap: 7px;
overflow-x: auto;
scrollbar-width: none;
}
#sequence::-webkit-scrollbar { display: none; }
.sample-chip {
min-width: 95px;
display: grid;
grid-template-columns: auto 1fr;
gap: 2px 8px;
padding: 8px 10px;
border: 1px solid var(--line);
border-radius: 8px;
color: #9aa7c0;
background: rgba(255,255,255,0.025);
font: 9px var(--mono);
}
.sample-chip b {
grid-row: 1 / 3;
align-self: center;
color: var(--cyan);
font-size: 12px;
}
.sample-chip.negative b { color: var(--coral); }
.sample-chip small {
color: #697690;
font: inherit;
}
.sample-chip.visited {
border-color: rgba(118, 169, 255, 0.28);
background: rgba(118, 169, 255, 0.055);
}
.sample-chip.current {
border-color: var(--amber);
background: rgba(255, 209, 102, 0.09);
box-shadow: inset 0 -2px 0 var(--amber);
}
.camera-hint {
position: absolute;
right: 20px;
bottom: 135px;
z-index: 3;
color: rgba(174, 185, 208, 0.62);
font: 9px var(--mono);
text-align: right;
pointer-events: none;
}
#loading {
position: absolute;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
color: var(--muted);
background: var(--bg);
font: 12px var(--mono);
}
@media (max-width: 900px) {
html, body { height: auto; overflow: auto; }
.app { height: auto; min-height: 100vh; grid-template-rows: 64px auto; }
.workspace { display: flex; flex-direction: column; }
.stage { order: 0; height: 68vh; min-height: 520px; }
aside { order: 1; overflow: visible; border-right: 0; border-top: 1px solid var(--line); }
.header-chip { display: none; }
.brand p { white-space: normal; }
.sequence-panel { left: 12px; right: 12px; bottom: 12px; }
.stage-top { left: 12px; right: 12px; top: 12px; }
.camera-hint { display: none; }
}
@media (max-width: 560px) {
header { padding: 0 15px; }
.brand h1 { font-size: 13px; }
.stage-title span { display: none; }
.legend { gap: 5px; }
.legend-item { font-size: 8px; }
.sample-chip { min-width: 83px; }
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true"><i></i><i></i><i></i></div>
<div>
<h1>Perceptron / Voxel Lab</h1>
<p>Sequential learning · explicit geometry · honest failure</p>
</div>
</div>
<div class="header-chip">THREE.JS CORE / 0.160.0</div>
</header>
<div class="workspace">
<aside>
<section class="section">
<div class="eyebrow"><span>01 / Dataset</span><span id="datasetSize"></span></div>
<div class="segmented" role="group" aria-label="Choose dataset">
<button id="linearBtn" class="active" aria-pressed="true">Linear</button>
<button id="xorBtn" aria-pressed="false">XOR</button>
</div>
<p id="datasetCopy" class="dataset-copy"></p>
</section>
<section class="section">
<div class="eyebrow"><span>02 / Update rule</span><span>binary perceptron</span></div>
<div class="rule-card">
<div class="formula">
ŷ = <b>sign</b>(w₁x₁ + w₂x₂ + b)<br>
x = [x₁, x₂]ᵀ
</div>
<div class="update-lines">
<div><code>w ← w + η(y − ŷ)x</code></div>
<div><code>b ← b + η(y − ŷ)</code></div>
</div>
<p class="rule-note">
One sample is updated at a time. Labels are −1/+1, sign(0) = +1,
and the fixed visit order repeats after every complete pass.
</p>
</div>
<div class="slider-row">
<label for="eta">η rate</label>
<input id="eta" type="range" min="0.10" max="0.80" step="0.05" value="0.35">
<output id="etaValue">0.35</output>
</div>
</section>
<section class="section">
<div class="eyebrow"><span>03 / Exploration</span><span>manual + automatic</span></div>
<div class="control-grid">
<button id="stepBtn" class="control primary wide">Step one sample</button>
<button id="passBtn" class="control">Run one pass</button>
<button id="autoBtn" class="control">Auto</button>
<button id="resetBtn" class="control wide">Reset weights</button>
</div>
<div class="slider-row">
<label for="speed">speed</label>
<input id="speed" type="range" min="220" max="1500" step="20" value="720">
<output id="speedValue">720ms</output>
</div>
</section>
<section class="section">
<div class="eyebrow"><span>04 / Telemetry</span><span id="lastPassLabel">no full pass yet</span></div>
<div class="metrics">
<div class="metric">
<span>Current pass</span>
<strong id="passMetric">1</strong>
<small id="stepMetric">next: sample 01</small>
</div>
<div class="metric">
<span>Accuracy now</span>
<strong id="accuracyMetric">—</strong>
<small>current decision line</small>
</div>
<div class="metric">
<span>Presentations</span>
<strong id="presentationMetric">0</strong>
<small id="updateMetric">0 weight updates</small>
</div>
<div class="metric">
<span>Last prediction</span>
<strong id="predictionMetric">—</strong>
<small id="predictionDetail">waiting for a sample</small>
</div>
</div>
<div class="weights">
<span>weights</span> w₁ = <b id="w1Metric">0.00</b>,
w₂ = <b id="w2Metric">0.00</b>,
b = <b id="bMetric">0.00</b>
</div>
</section>
<section class="section">
<div class="eyebrow"><span>05 / Interpretation</span><span>live</span></div>
<div id="status" class="status" aria-live="polite">Ready for the first update.</div>
<div class="insight">
<h3 id="insightTitle"></h3>
<p id="insightText"></p>
</div>
</section>
</aside>
<main class="stage">
<div id="viewport" aria-label="Interactive 3D perceptron visualization"></div>
<div class="stage-top">
<div class="stage-title">
<strong id="stageTitle">LINEAR DATASET</strong>
<span>Decision geometry in the x₁–x₂ input plane</span>
</div>
<div class="legend">
<div class="legend-item"><span class="swatch"></span> class +1</div>
<div class="legend-item"><span class="swatch negative"></span> class −1</div>
<div class="legend-item"><span class="swatch boundary"></span> boundary</div>
</div>
</div>
<div class="camera-hint">drag to orbit · wheel to zoom · double-click to reset view</div>
<div class="sequence-panel">
<div class="sequence-head">
<span>Fixed sample stream</span>
<span id="streamInfo">gold ring = next sample</span>
</div>
<div id="sequence"></div>
</div>
<div id="loading">building voxel board…</div>
</main>
</div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const DATASETS = {
linear: {
id: "linear",
title: "LINEAR DATASET",
size: "8 samples",
copy: "Two compact groups. A single line can separate every +1 point from every −1 point.",
insightTitle: "Why it works",
insightText: "This data is linearly separable. With a positive learning rate and repeated presentation of every sample, the perceptron theorem guarantees eventual separation.",
samples: [
{ x: -3, z: -3, y: -1 },
{ x: 3, z: 3, y: 1 },
{ x: -3, z: -1, y: -1 },
{ x: 3, z: 1, y: 1 },
{ x: -1, z: -3, y: -1 },
{ x: 1, z: 3, y: 1 },
{ x: -2, z: -2, y: -1 },
{ x: 2, z: 2, y: 1 }
]
},
xor: {
id: "xor",
title: "XOR DATASET",
size: "4 samples",
copy: "Opposite corners share a label. No one straight line can classify all four correctly.",
insightTitle: "The representational limit",
insightText: "XOR is not linearly separable. The perceptron may change its line, fit three samples, or enter a cycle, but no value of w and b can correctly label all four corners.",
samples: [
{ x: -2, z: -2, y: -1 },
{ x: 2, z: -2, y: 1 },
{ x: -2, z: 2, y: 1 },
{ x: 2, z: 2, y: -1 }
]
}
};
const $ = id => document.getElementById(id);
const viewport = $("viewport");
const state = {
datasetId: "linear",
w1: 0,
w2: 0,
b: 0,
eta: 0.35,
speed: 720,
index: 0,
pass: 1,
presentations: 0,
updateCount: 0,
seen: [],
last: null,
lastPassAccuracy: null,
converged: false
};
let autoRunning = false;
let autoTimer = null;
let passRunning = false;
let passTimer = null;
let operationToken = 0;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x080b16);
scene.fog = new THREE.Fog(0x080b16, 17, 31);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 80);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
viewport.appendChild(renderer.domElement);
renderer.domElement.setAttribute("aria-label", "Voxel scene showing samples and the perceptron decision boundary");
const hemisphere = new THREE.HemisphereLight(0xa9c8ff, 0x171326, 1.55);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.6);
keyLight.position.set(7, 13, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -9;
keyLight.shadow.camera.right = 9;
keyLight.shadow.camera.top = 9;
keyLight.shadow.camera.bottom = -9;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
keyLight.shadow.normalBias = 0.025;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x5577ff, 28, 18, 2);
rimLight.position.set(-7, 5, -4);
scene.add(rimLight);
const cyanLight = new THREE.PointLight(0x55f2d0, 18, 13, 2);
cyanLight.position.set(4, 3, 3);
scene.add(cyanLight);
const board = new THREE.Group();
const pointGroup = new THREE.Group();
const boundaryGroup = new THREE.Group();
const vectorGroup = new THREE.Group();
scene.add(board, pointGroup, boundaryGroup, vectorGroup);
const tileGeometry = new THREE.BoxGeometry(0.86, 0.12, 0.86);
const tileMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.9,
metalness: 0.03
});
const tileCount = 9;
const tiles = new THREE.InstancedMesh(tileGeometry, tileMaterial, tileCount * tileCount);
tiles.receiveShadow = true;
board.add(tiles);
const tileMatrix = new THREE.Matrix4();
const tileCoordinates = [];
for (let x = -4; x <= 4; x++) {
for (let z = -4; z <= 4; z++) {
const i = tileCoordinates.length;
tileCoordinates.push({ x, z });
tileMatrix.makeTranslation(x, 0, z);
tiles.setMatrixAt(i, tileMatrix);
tiles.setColorAt(i, new THREE.Color(0x18213a));
}
}
tiles.instanceMatrix.needsUpdate = true;
const platform = new THREE.Mesh(
new THREE.BoxGeometry(9.7, 0.34, 9.7),
new THREE.MeshStandardMaterial({ color: 0x11182a, roughness: 0.72, metalness: 0.18 })
);
platform.position.y = -0.23;
platform.receiveShadow = true;
board.add(platform);
const underGlow = new THREE.Mesh(
new THREE.BoxGeometry(10.2, 0.12, 10.2),
new THREE.MeshBasicMaterial({ color: 0x182544 })
);
underGlow.position.y = -0.43;
board.add(underGlow);
const wall = new THREE.Group();
const wallMaterials = [
new THREE.MeshStandardMaterial({ color: 0x17223c, roughness: 0.9 }),
new THREE.MeshStandardMaterial({ color: 0x1b2947, roughness: 0.9 }),
new THREE.MeshStandardMaterial({ color: 0x223356, roughness: 0.9 })
];
for (let x = -4; x <= 4; x++) {
for (let y = 0; y < 3; y++) {
const heightNoise = (x + 4 + y * 3) % 4;
const cube = new THREE.Mesh(
new THREE.BoxGeometry(0.78, 0.78, 0.48),
wallMaterials[heightNoise % wallMaterials.length]
);
cube.position.set(x, 0.18 + y * 0.78, -4.85);
cube.receiveShadow = true;
wall.add(cube);
}
}
scene.add(wall);
const rail = new THREE.Mesh(
new THREE.BoxGeometry(8.2, 0.08, 0.12),
new THREE.MeshBasicMaterial({ color: 0x2d4a82 })
);
rail.position.set(0, 2.62, -4.58);
wall.add(rail);
const positiveMaterial = new THREE.MeshStandardMaterial({
color: 0x55f2d0,
emissive: 0x0e5c4c,
emissiveIntensity: 0.55,
roughness: 0.42,
metalness: 0.12
});
const negativeMaterial = new THREE.MeshStandardMaterial({
color: 0xff7082,
emissive: 0x661a2b,
emissiveIntensity: 0.52,
roughness: 0.42,
metalness: 0.12
});
const highlightMaterial = new THREE.MeshStandardMaterial({
color: 0xffd166,
emissive: 0x8a5a00,
emissiveIntensity: 0.9,
roughness: 0.35
});
const boundaryMaterial = new THREE.MeshStandardMaterial({
color: 0xffd166,
emissive: 0x7b4e00,
emissiveIntensity: 0.72,
roughness: 0.34
});
let pointVisuals = [];
function createTextSprite(text, color = "#eaf0ff", worldWidth = 1.15) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 96;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.font = "700 46px ui-monospace, monospace";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = color;
ctx.shadowColor = color;
ctx.shadowBlur = 12;
ctx.fillText(text, 128, 48);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(worldWidth, worldWidth * 0.375, 1);
sprite.renderOrder = 20;
return sprite;
}
const x1Label = createTextSprite("x₁", "#8fa5ca", 1.0);
x1Label.position.set(4.65, 0.15, 0);
scene.add(x1Label);
const x2Label = createTextSprite("x₂", "#8fa5ca", 1.0);
x2Label.position.set(0, 0.15, 4.65);
scene.add(x2Label);
const wallLabel = createTextSprite("INPUT PLANE", "#60779f", 2.4);
wallLabel.position.set(0, 3.05, -4.7);
scene.add(wallLabel);
function clearGroup(group) {
while (group.children.length) {
const child = group.children[0];
group.remove(child);
child.traverse(object => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const materials = Array.isArray(object.material) ? object.material : [object.material];
materials.forEach(material => {
if (material.map) material.map.dispose();
material.dispose();
});
}
});
}
}
function rebuildPoints() {
clearGroup(pointGroup);
pointVisuals = [];
DATASETS[state.datasetId].samples.forEach((sample, index) => {
const root = new THREE.Group();
root.position.set(sample.x, 0, sample.z);
const material = sample.y === 1 ? positiveMaterial : negativeMaterial;
const base = new THREE.Mesh(new THREE.BoxGeometry(0.52, 0.26, 0.52), material);
base.position.y = 0.18;
base.castShadow = true;
base.receiveShadow = true;
const middle = new THREE.Mesh(new THREE.BoxGeometry(0.36, 0.3, 0.36), material);
middle.position.y = 0.45;
middle.castShadow = true;
const top = new THREE.Mesh(new THREE.BoxGeometry(0.22, 0.22, 0.22), material);
top.position.y = 0.71;
top.castShadow = true;
const label = createTextSprite(sample.y === 1 ? "+1" : "−1", sample.y === 1 ? "#75ffe1" : "#ff8b99", 0.85);
label.position.y = 1.35;
const highlight = new THREE.Group();
const cornerPositions = [
[-0.39, -0.39], [0.39, -0.39], [-0.39, 0.39], [0.39, 0.39]
];
cornerPositions.forEach(([x, z]) => {
const corner = new THREE.Mesh(new THREE.BoxGeometry(0.13, 0.13, 0.13), highlightMaterial);
corner.position.set(x, 0.15, z);
highlight.add(corner);
});
root.add(base, middle, top, label, highlight);
pointGroup.add(root);
pointVisuals.push({ root, highlight, index });
});
}
function predictionFor(sample, w1 = state.w1, w2 = state.w2, b = state.b) {
const score = w1 * sample.x + w2 * sample.z + b;
return { score, prediction: score >= 0 ? 1 : -1 };
}
function currentAccuracy() {
const samples = DATASETS[state.datasetId].samples;
const correct = samples.reduce((total, sample) => {
const { prediction } = predictionFor(sample);
return total + (prediction === sample.y ? 1 : 0);
}, 0);
return correct / samples.length;
}
function updateGridColors() {
const positive = new THREE.Color(0x123d3b);
const negative = new THREE.Color(0x3c1d31);
const neutral = new THREE.Color(0x18213a);
const nearBoundary = new THREE.Color(0x55452b);
tileCoordinates.forEach(({ x, z }, index) => {
const score = state.w1 * x + state.w2 * z + state.b;
let color;
if (Math.abs(score) < 0.16 && Math.hypot(state.w1, state.w2) > 0.001) {
color = nearBoundary;
} else {
color = score >= 0 ? positive : negative;
}
tiles.setColorAt(index, color);
});
tiles.instanceColor.needsUpdate = true;
}
function boundaryEndpoints() {
const A = state.w1;
const B = state.w2;
const C = state.b;
const magnitude = Math.hypot(A, B);
if (magnitude < 0.0001) return null;
const min = -4.35;
const max = 4.35;
const baseX = -C * A / (magnitude * magnitude);
const baseZ = -C * B / (magnitude * magnitude);
const dirX = -B / magnitude;
const dirZ = A / magnitude;
const candidates = [];
function addCandidate(t, x, z) {
if (x >= min - 1e-6 && x <= max + 1e-6 && z >= min - 1e-6 && z <= max + 1e-6) {
candidates.push(t);
}
}
if (Math.abs(dirX) > 1e-8) {
const tMin = (min - baseX) / dirX;
addCandidate(tMin, min, baseZ + tMin * dirZ);
const tMax = (max - baseX) / dirX;
addCandidate(tMax, max, baseZ + tMax * dirZ);
}
if (Math.abs(dirZ) > 1e-8) {
const tMin = (min - baseZ) / dirZ;
addCandidate(tMin, baseX + tMin * dirX, min);
const tMax = (max - baseZ) / dirZ;
addCandidate(tMax, baseX + tMax * dirX, max);
}
const unique = [...new Set(candidates.map(t => t.toFixed(6)))].map(Number).sort((a, b) => a - b);
if (unique.length < 2) return null;
return {
x1: baseX + unique[0] * dirX,
z1: baseZ + unique[0] * dirZ,
x2: baseX + unique[unique.length - 1] * dirX,
z2: baseZ + unique[unique.length - 1] * dirZ
};
}
function updateBoundary() {
clearGroup(boundaryGroup);
const endpoints = boundaryEndpoints();
if (!endpoints) return;
const dx = endpoints.x2 - endpoints.x1;
const dz = endpoints.z2 - endpoints.z1;
const length = Math.hypot(dx, dz);
const count = Math.max(2, Math.ceil(length / 0.18));
for (let i = 0; i <= count; i++) {
const t = i / count;
const cube = new THREE.Mesh(new THREE.BoxGeometry(0.17, 0.17, 0.17), boundaryMaterial);
cube.position.set(
THREE.MathUtils.lerp(endpoints.x1, endpoints.x2, t),
0.16,
THREE.MathUtils.lerp(endpoints.z1, endpoints.z2, t)
);
cube.castShadow = true;
boundaryGroup.add(cube);
}
}
function updateWeightVector() {
clearGroup(vectorGroup);
const magnitude = Math.hypot(state.w1, state.w2);
if (magnitude < 0.02) return;
const directionX = state.w1 / magnitude;
const directionZ = state.w2 / magnitude;
const count = 8;
for (let i = 1; i <= count; i++) {
const scale = i / count;
const cube = new THREE.Mesh(
new THREE.BoxGeometry(i === count ? 0.25 : 0.17, i === count ? 0.25 : 0.17, i === count ? 0.25 : 0.17),
highlightMaterial
);
cube.position.set(directionX * scale * 1.65, 0.28, directionZ * scale * 1.65);
cube.castShadow = true;
vectorGroup.add(cube);
}
const label = createTextSprite("w", "#ffd166", 0.72);
label.position.set(directionX * 1.92, 0.72, directionZ * 1.92);
vectorGroup.add(label);
}
function updateScene() {
updateGridColors();
updateBoundary();
updateWeightVector();
pointVisuals.forEach(visual => {
visual.highlight.visible = visual.index === state.index;
});
}
function formatSigned(value, digits = 2) {
const rounded = Math.abs(value) < 0.005 ? 0 : value;
return `${rounded >= 0 ? "+" : "−"}${Math.abs(rounded).toFixed(digits)}`;
}
function formatCoordinate(value) {
return value < 0 ? `−${Math.abs(value)}` : `${value}`;
}
function resetLearningState() {
state.w1 = 0;
state.w2 = 0;
state.b = 0;
state.index = 0;
state.pass = 1;
state.presentations = 0;
state.updateCount = 0;
state.seen = DATASETS[state.datasetId].samples.map(() => 0);
state.last = null;
state.lastPassAccuracy = null;
state.converged = false;
}
function stepSample() {
const dataset = DATASETS[state.datasetId];
const sample = dataset.samples[state.index];
const old = { w1: state.w1, w2: state.w2, b: state.b };
const { score, prediction } = predictionFor(sample);
const error = sample.y - prediction;
state.w1 += state.eta * error * sample.x;
state.w2 += state.eta * error * sample.z;
state.b += state.eta * error;
state.presentations++;
state.seen[state.index]++;
if (error !== 0) state.updateCount++;
state.last = {
sample,
prediction,
score,
corrected: error !== 0,
deltaW1: state.w1 - old.w1,
deltaW2: state.w2 - old.w2,
deltaB: state.b - old.b
};
const wasLast = state.index === dataset.samples.length - 1;
state.index = (state.index + 1) % dataset.samples.length;
if (wasLast) {
state.lastPassAccuracy = currentAccuracy();
state.pass++;
if (state.datasetId === "linear" && state.lastPassAccuracy === 1) {
state.converged = true;
}
}
updateScene();
updateUI();
return wasLast;
}
function stopAuto(message = "") {
autoRunning = false;
clearTimeout(autoTimer);
autoTimer = null;
if (message) state.last = state.last;
updateUI();
}
function scheduleAuto() {
clearTimeout(autoTimer);
if (!autoRunning) return;
if (state.datasetId === "xor" && state.pass > 8) {
stopAuto("Eight complete passes were observed without perfect XOR classification.");
return;
}
if (state.datasetId === "linear" && state.converged) {
stopAuto("A perfect separating line was found.");
return;
}
autoTimer = setTimeout(() => {
if (!autoRunning) return;
stepSample();
scheduleAuto();
}, state.speed);
}
function toggleAuto() {
if (passRunning) return;
if (autoRunning) {
stopAuto();
} else {
autoRunning = true;
updateUI();
scheduleAuto();
}
}
function runOnePass() {
if (passRunning || autoRunning) return;
passRunning = true;
const token = ++operationToken;
const datasetLength = DATASETS[state.datasetId].samples.length;
const tick = () => {
if (token !== operationToken) return;
const wasLast = stepSample();
if (wasLast) {
passRunning = false;
updateUI();
return;
}
passTimer = setTimeout(tick, Math.min(460, Math.max(220, state.speed * 0.55)));
};
updateUI();
tick();
}
function chooseDataset(id) {
if (!DATASETS[id]) return;
operationToken++;
clearTimeout(autoTimer);
clearTimeout(passTimer);
autoRunning = false;
passRunning = false;
state.datasetId = id;
resetLearningState();
rebuildPoints();
updateScene();
updateUI();
}
function statusText() {
const accuracy = currentAccuracy();
const percent = Math.round(accuracy * 100);
if (state.datasetId === "xor") {
if (state.pass > 8) {
return `Eight passes completed; current accuracy is ${percent}%. No perfect XOR solution exists. The changing line is the model searching a space that cannot contain a solution.`;
}
if (state.presentations === 0) {
return "Ready. This is the XOR control case: watch the line move without ever reaching a correct classification of all four corners.";
}
return `XOR limit active — ${percent}% classified correctly. A perceptron cannot make all four corners correct because XOR is not linearly separable.`;
}
if (state.converged) {
return `Separating line found: all samples are classified correctly (${percent}%). Further correct presentations leave the weights unchanged.`;
}
if (state.presentations === 0) {
return "Ready. The first prediction uses w = (0, 0) and b = 0, so it initially predicts +1 everywhere.";
}
const last = state.last;
if (!last) return "Ready for the next sample.";
const outcome = last.corrected ? "The miss caused a weight update." : "The prediction was already correct, so no update was needed.";
return `At (${formatCoordinate(last.sample.x)}, ${formatCoordinate(last.sample.z)}), ŷ = ${last.prediction === 1 ? "+1" : "−1"} while y = ${last.sample.y === 1 ? "+1" : "−1"}. ${outcome}`;
}
function updateSequence() {
const samples = DATASETS[state.datasetId].samples;
$("sequence").innerHTML = samples.map((sample, index) => {
const classes = ["sample-chip"];
if (sample.y === -1) classes.push("negative");
if (state.seen[index] > 0) classes.push("visited");
if (index === state.index) classes.push("current");
const sign = sample.y === 1 ? "+1" : "−1";
return `
<div class="${classes.join(" ")}">
<b>${sign}</b>
<span>${String(index + 1).padStart(2, "0")}</span>
<small>(${formatCoordinate(sample.x)}, ${formatCoordinate(sample.z)})</small>
</div>
`;
}).join("");
}
function updateUI() {
const dataset = DATASETS[state.datasetId];
const samples = dataset.samples;
const accuracy = currentAccuracy();
const percent = Math.round(accuracy * 100);
$("linearBtn").classList.toggle("active", state.datasetId === "linear");
$("linearBtn").setAttribute("aria-pressed", String(state.datasetId === "linear"));
$("xorBtn").classList.toggle("active", state.datasetId === "xor");
$("xorBtn").setAttribute("aria-pressed", String(state.datasetId === "xor"));
$("datasetSize").textContent = dataset.size;
$("datasetCopy").textContent = dataset.copy;
$("stageTitle").textContent = dataset.title;
$("insightTitle").textContent = dataset.insightTitle;
$("insightText").textContent = dataset.insightText;
$("passMetric").textContent = String(state.pass);
$("stepMetric").textContent = `next: sample ${String(state.index + 1).padStart(2, "0")}`;
$("accuracyMetric").textContent = `${percent}%`;
$("presentationMetric").textContent = String(state.presentations);
$("updateMetric").textContent = `${state.updateCount} weight update${state.updateCount === 1 ? "" : "s"}`;
$("lastPassLabel").textContent = state.lastPassAccuracy === null
? "no full pass yet"
: `last full pass: ${Math.round(state.lastPassAccuracy * 100)}%`;
$("w1Metric").textContent = formatSigned(state.w1);
$("w2Metric").textContent = formatSigned(state.w2);
$("bMetric").textContent = formatSigned(state.b);
if (state.last) {
$("predictionMetric").textContent = state.last.prediction === 1 ? "+1" : "−1";
$("predictionMetric").style.color = state.last.prediction === 1 ? "var(--cyan)" : "var(--coral)";
$("predictionDetail").textContent = state.last.corrected
? `miss · Δb ${formatSigned(state.last.deltaB)}`
: "hit · no change";
} else {
$("predictionMetric").textContent = "—";
$("predictionMetric").style.color = "var(--text)";
$("predictionDetail").textContent = "waiting for a sample";
}
const status = $("status");
status.textContent = statusText();
status.className = "status";
if (state.datasetId === "xor") {
status.classList.add("limit");
} else if (state.converged) {
status.classList.add("good");
} else if (state.presentations > 0) {
status.classList.add("warn");
}
$("autoBtn").textContent = autoRunning ? "Stop auto" : "Auto";
$("autoBtn").classList.toggle("running", autoRunning);
$("stepBtn").disabled = passRunning;
$("passBtn").disabled = passRunning || autoRunning;
$("autoBtn").disabled = passRunning;
$("resetBtn").disabled = passRunning;
$("etaValue").textContent = state.eta.toFixed(2);
$("speedValue").textContent = `${state.speed}ms`;
$("streamInfo").textContent = state.datasetId === "xor"
? "gold ring = next sample · fixed order repeats"
: "gold ring = next sample · pass repeats in fixed order";
updateSequence();
}
$("linearBtn").addEventListener("click", () => chooseDataset("linear"));
$("xorBtn").addEventListener("click", () => chooseDataset("xor"));
$("stepBtn").addEventListener("click", () => {
if (passRunning) return;
stopAuto();
stepSample();
});
$("passBtn").addEventListener("click", runOnePass);
$("autoBtn").addEventListener("click", toggleAuto);
$("resetBtn").addEventListener("click", () => {
operationToken++;
clearTimeout(autoTimer);
clearTimeout(passTimer);
autoRunning = false;
passRunning = false;
resetLearningState();
updateScene();
updateUI();
});
$("eta").addEventListener("input", event => {
state.eta = Number(event.target.value);
updateUI();
});
$("speed").addEventListener("input", event => {
state.speed = Number(event.target.value);
if (autoRunning) scheduleAuto();
updateUI();
});
// Direct camera controls: orbit, zoom, and reset. No addons are imported.
const orbit = {
yaw: 0.72,
pitch: 0.72,
radius: 15.7,
target: new THREE.Vector3(0, 0.35, 0)
};
function updateCamera() {
const horizontal = orbit.radius * Math.cos(orbit.pitch);
camera.position.set(
orbit.target.x + horizontal * Math.sin(orbit.yaw),
orbit.target.y + orbit.radius * Math.sin(orbit.pitch),
orbit.target.z + horizontal * Math.cos(orbit.yaw)
);
camera.lookAt(orbit.target);
}
function resetCamera() {
orbit.yaw = 0.72;
orbit.pitch = 0.72;
orbit.radius = 15.7;
updateCamera();
}
let dragging = false;
let dragX = 0;
let dragY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
dragX = event.clientX;
dragY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - dragX;
const dy = event.clientY - dragY;
dragX = event.clientX;
dragY = event.clientY;
orbit.yaw -= dx * 0.006;
orbit.pitch = THREE.MathUtils.clamp(orbit.pitch + dy * 0.005, 0.34, 1.35);
updateCamera();
});
function endDrag(event) {
dragging = false;
if (event.pointerId !== undefined && renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(orbit.radius + event.deltaY * 0.012, 10, 25);
updateCamera();
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
function resize() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(viewport);
resize();
updateCamera();
rebuildPoints();
resetLearningState();
updateScene();
updateUI();
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
pointVisuals.forEach((visual, index) => {
if (visual.index === state.index) {
visual.highlight.rotation.y = elapsed * 0.65;
const pulse = 1 + Math.sin(elapsed * 3.2) * 0.08;
visual.highlight.scale.setScalar(pulse);
} else {
visual.highlight.scale.setScalar(1);
}
});
renderer.render(scene, camera);
}
$("loading").style.display = "none";
animate();
</script>
</body>
</html>
```