Prompt specification
Build or customize the Three.js 3D scene "Single and double error comparison" 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: Single and double error comparison
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/single-and-double-error-comparison-x1866
Scene Description Prompt:
Create a standalone stylized scene in one HTML file using Three.js from cdnjs. Transmit the same message with one and two bit flips; demonstrate that simple parity detects the first but can miss the second rather than promising universal protection.
Working Three.js Starter (single-and-double-error-comparison-x1866):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Parity Lab — One Bit vs. Two Bits</title>
<style>
:root {
color-scheme: dark;
--bg: #07101d;
--panel: rgba(10, 23, 38, 0.78);
--panel-border: rgba(148, 210, 235, 0.16);
--text: #e9f8ff;
--muted: #8ba7b9;
--cyan: #55dcff;
--gold: #ffd166;
--red: #ff627c;
--amber: #ffba58;
--green: #72e6a8;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 40%, #102940 0%, #091523 42%, #050b13 100%);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--text);
}
#stage {
position: fixed;
inset: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#stage canvas:active {
cursor: grabbing;
}
#ui {
position: fixed;
inset: 0;
z-index: 5;
pointer-events: none;
}
.header {
position: absolute;
top: 22px;
left: 50%;
width: min(680px, calc(100vw - 36px));
transform: translateX(-50%);
text-align: center;
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 9px;
margin-bottom: 9px;
color: #8cdcf2;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.2em;
text-transform: uppercase;
}
.eyebrow::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 16px var(--cyan);
content: "";
}
h1 {
margin: 0;
font-size: clamp(30px, 4vw, 52px);
line-height: 0.98;
letter-spacing: -0.045em;
text-shadow: 0 8px 35px rgba(0, 0, 0, 0.55);
}
h1 span {
color: var(--cyan);
}
.intro {
max-width: 610px;
margin: 12px auto 0;
color: #a8bfce;
font-size: 13px;
line-height: 1.55;
}
.toolbar {
display: flex;
justify-content: center;
flex-wrap: wrap;
gap: 8px;
margin-top: 17px;
pointer-events: auto;
}
button {
appearance: none;
border: 1px solid rgba(158, 219, 242, 0.2);
border-radius: 999px;
padding: 10px 15px;
background: rgba(12, 28, 44, 0.84);
color: #bdd3df;
font: inherit;
font-size: 12px;
font-weight: 750;
cursor: pointer;
backdrop-filter: blur(12px);
transition:
border-color 160ms ease,
background 160ms ease,
color 160ms ease,
transform 160ms ease;
}
button:hover {
transform: translateY(-1px);
border-color: rgba(85, 220, 255, 0.65);
color: white;
}
button:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 3px;
}
button.active {
border-color: rgba(85, 220, 255, 0.8);
background: rgba(27, 100, 132, 0.45);
color: white;
box-shadow: inset 0 0 20px rgba(85, 220, 255, 0.08);
}
button.primary {
border-color: rgba(255, 209, 102, 0.55);
background: rgba(112, 81, 20, 0.34);
color: #ffe5a8;
}
.card {
position: absolute;
bottom: 20px;
border: 1px solid var(--panel-border);
border-radius: 18px;
background: var(--panel);
box-shadow:
0 20px 60px rgba(0, 0, 0, 0.32),
inset 0 1px rgba(255, 255, 255, 0.035);
backdrop-filter: blur(18px);
}
.readout {
left: 20px;
width: min(375px, calc(100vw - 40px));
padding: 16px;
}
.lesson {
right: 20px;
width: min(350px, calc(100vw - 40px));
padding: 16px;
}
.card-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
color: #8faabd;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.always {
color: #5f7e91;
font-size: 9px;
letter-spacing: 0.08em;
}
.bit-row {
display: grid;
grid-template-columns: repeat(9, 1fr);
gap: 4px;
margin-top: 10px;
}
.bit {
display: grid;
height: 29px;
place-items: center;
border: 1px solid rgba(125, 204, 234, 0.18);
border-radius: 6px;
background: rgba(39, 87, 112, 0.26);
color: #bff5ff;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
font-weight: 800;
}
.bit.zero {
background: rgba(23, 43, 60, 0.5);
color: #728fa1;
}
.bit.parity {
border-color: rgba(255, 209, 102, 0.55);
background: rgba(124, 89, 20, 0.28);
color: var(--gold);
}
.bit.corrupt {
border-color: rgba(255, 98, 124, 0.85);
background: rgba(142, 34, 54, 0.42);
color: #ffd6dd;
box-shadow: 0 0 14px rgba(255, 98, 124, 0.15);
}
.bit.empty {
color: #486274;
}
.meta {
margin-top: 7px;
color: #708c9e;
font-size: 10px;
line-height: 1.45;
}
.scenario-line {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 14px;
padding-top: 13px;
border-top: 1px solid rgba(141, 201, 225, 0.12);
}
#scenarioName {
color: #d8edf7;
font-size: 12px;
font-weight: 800;
}
#scenarioDetail {
margin-top: 3px;
color: #718ea0;
font-size: 10px;
}
.badge {
flex: 0 0 auto;
border: 1px solid rgba(139, 167, 185, 0.25);
border-radius: 999px;
padding: 6px 9px;
color: #90a8b7;
background: rgba(125, 151, 167, 0.08);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.1em;
}
.badge.flight {
border-color: rgba(85, 220, 255, 0.45);
color: var(--cyan);
}
.badge.bad {
border-color: rgba(255, 98, 124, 0.55);
background: rgba(125, 32, 49, 0.25);
color: #ff9aaa;
}
.badge.warn {
border-color: rgba(255, 186, 88, 0.55);
background: rgba(122, 78, 18, 0.24);
color: #ffd086;
}
.lesson h2 {
margin: 12px 0 7px;
color: #e7f8ff;
font-size: 18px;
letter-spacing: -0.02em;
}
.lesson p {
margin: 0;
color: #8da8b9;
font-size: 11px;
line-height: 1.55;
}
.scope {
margin-top: 13px;
padding-top: 12px;
border-top: 1px solid rgba(141, 201, 225, 0.12);
color: #647f90;
font-size: 9px;
line-height: 1.55;
}
.scope strong {
color: #9bb5c5;
}
.hint {
position: absolute;
bottom: 24px;
left: 50%;
transform: translateX(-50%);
color: rgba(153, 188, 205, 0.55);
font-size: 10px;
letter-spacing: 0.08em;
white-space: nowrap;
}
@media (max-width: 920px) {
.lesson {
display: none;
}
.header {
top: 14px;
}
.intro {
max-width: 520px;
font-size: 11px;
}
.readout {
left: 12px;
bottom: 12px;
width: min(360px, calc(100vw - 24px));
}
.hint {
display: none;
}
}
@media (max-width: 560px) {
.header {
width: calc(100vw - 20px);
}
h1 {
font-size: 31px;
}
.intro {
display: none;
}
.toolbar {
margin-top: 13px;
}
button {
padding: 9px 11px;
font-size: 10px;
}
.readout {
padding: 12px;
}
.lesson {
display: none;
}
}
@media (max-height: 650px) {
.intro,
.scope {
display: none;
}
.header {
top: 10px;
}
.readout {
bottom: 10px;
padding: 11px;
}
}
</style>
</head>
<body>
<main id="stage" aria-label="Interactive three-dimensional parity demonstration"></main>
<div id="ui">
<header class="header">
<div class="eyebrow">Transmission Playground</div>
<h1>
One flip is caught.<br />
<span>Two flips can hide.</span>
</h1>
<p class="intro">
The same 8-bit message is transmitted twice. Even parity checks the
number of 1s—not the truth of every individual bit.
</p>
<nav class="toolbar" aria-label="Transmission controls">
<button id="oneButton" data-mode="one" aria-pressed="false">
1-bit flip
</button>
<button id="twoButton" data-mode="two" aria-pressed="false">
2-bit flips
</button>
<button id="bothButton" class="primary">
Play comparison
</button>
</nav>
</header>
<section class="card readout" aria-live="polite">
<div class="card-heading">
<span>Sent codeword</span>
<span class="always">Every run</span>
</div>
<div id="sentBits" class="bit-row"></div>
<div class="meta">
8 data bits followed by 1 even-parity bit. Colored received bits show
the injected damage, not a diagnosis made by parity.
</div>
<div class="scenario-line">
<div>
<div id="scenarioName">Ready</div>
<div id="scenarioDetail">Choose a transmission scenario</div>
</div>
<span id="resultBadge" class="badge">WAITING</span>
</div>
<div id="receivedBits" class="bit-row"></div>
<div id="receivedMeta" class="meta">No frame received yet.</div>
</section>
<section class="card lesson">
<div class="card-heading">
<span>Even parity check</span>
</div>
<h2 id="lessonTitle">A limited error-detection tool</h2>
<p id="lessonBody">
Start a scenario to compare a single changed bit with two changed bits.
</p>
<div class="scope">
<strong>Scope, not a promise:</strong> even parity detects odd-numbered
flips in the protected word, but it can miss even-numbered flips.
Parity detects an error; it does not correct one.
</div>
</section>
<div class="hint">Drag to orbit · Scroll or pinch to zoom</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Data and scenarios
// -------------------------------------------------------------------------
const DATA_BITS = [1, 0, 1, 1, 0, 1, 0, 0];
const SENT_PARITY = 0; // DATA_BITS contains four ones, so even parity is 0.
const SCENARIOS = {
one: {
name: "One-bit flip",
detail: "Bit 4 changes from 1 → 0",
flips: [3],
received: [1, 0, 1, 0, 0, 1, 0, 0],
lessonTitle: "Odd parity exposes the error",
lessonBody:
"The received codeword contains three 1s. Even parity expects an " +
"even count, so the stored parity bit disagrees and the receiver " +
"flags an error. Parity still does not locate or repair the bad bit."
},
two: {
name: "Two-bit flips",
detail: "Bit 4 changes 1 → 0 and bit 5 changes 0 → 1",
flips: [3, 4],
received: [1, 0, 1, 0, 1, 1, 0, 0],
lessonTitle: "Even parity can conceal it",
lessonBody:
"The received codeword still contains four 1s. The parity check " +
"therefore agrees even though two bits changed. Parity alone cannot " +
"distinguish this damaged word from the original."
}
};
const COLORS = {
one: 0x55dcff,
zero: 0x172b3e,
parity: 0xffd166,
damaged: 0xff627c,
waiting: 0x23394b,
cyan: 0x55dcff,
amber: 0xffba58
};
const stage = document.querySelector("#stage");
const ui = {
oneButton: document.querySelector("#oneButton"),
twoButton: document.querySelector("#twoButton"),
bothButton: document.querySelector("#bothButton"),
sentBits: document.querySelector("#sentBits"),
receivedBits: document.querySelector("#receivedBits"),
receivedMeta: document.querySelector("#receivedMeta"),
scenarioName: document.querySelector("#scenarioName"),
scenarioDetail: document.querySelector("#scenarioDetail"),
resultBadge: document.querySelector("#resultBadge"),
lessonTitle: document.querySelector("#lessonTitle"),
lessonBody: document.querySelector("#lessonBody")
};
// -------------------------------------------------------------------------
// Renderer, scene, camera, and lighting
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07101d);
scene.fog = new THREE.Fog(0x07101d, 14, 35);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraState = {
yaw: 0,
pitch: 0.08,
radius: 16,
targetY: -0.25,
hasZoomed: false
};
const hemi = new THREE.HemisphereLight(0x9adfff, 0x101522, 1.8);
scene.add(hemi);
const keyLight = new THREE.DirectionalLight(0xd9f4ff, 3.1);
keyLight.position.set(-5, 9, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -12;
keyLight.shadow.camera.right = 12;
keyLight.shadow.camera.top = 9;
keyLight.shadow.camera.bottom = -8;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x39cfff, 24, 13, 2);
cyanLight.position.set(0, 2.2, 4.5);
scene.add(cyanLight);
const pinkLight = new THREE.PointLight(0xff557c, 18, 11, 2);
pinkLight.position.set(6, 0.2, 2.8);
scene.add(pinkLight);
// -------------------------------------------------------------------------
// Ground, grid, path, and atmospheric particles
// -------------------------------------------------------------------------
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(40, 40),
new THREE.MeshStandardMaterial({
color: 0x07111d,
roughness: 0.92,
metalness: 0.08
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -2.08;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(
34,
34,
0x1d6885,
0x143247
);
grid.position.y = -2.065;
grid.material.transparent = true;
grid.material.opacity = 0.3;
scene.add(grid);
const pathCurve = new THREE.CatmullRomCurve3([
new THREE.Vector3(-4.45, 0.68, 0),
new THREE.Vector3(-2.55, 1.24, 0),
new THREE.Vector3(0, 0.55, 0),
new THREE.Vector3(2.55, 1.24, 0),
new THREE.Vector3(4.45, 0.68, 0)
]);
const path = new THREE.Mesh(
new THREE.TubeGeometry(pathCurve, 120, 0.026, 8, false),
new THREE.MeshBasicMaterial({
color: COLORS.cyan,
transparent: true,
opacity: 0.42
})
);
scene.add(path);
const haloRing = new THREE.Mesh(
new THREE.TorusGeometry(3.75, 0.018, 8, 120),
new THREE.MeshBasicMaterial({
color: 0x3aa7cb,
transparent: true,
opacity: 0.19
})
);
haloRing.position.set(0, 0.1, -1.35);
haloRing.scale.y = 0.43;
scene.add(haloRing);
const haloRing2 = new THREE.Mesh(
new THREE.TorusGeometry(5.1, 0.012, 8, 120),
new THREE.MeshBasicMaterial({
color: 0x7c5cff,
transparent: true,
opacity: 0.12
})
);
haloRing2.position.set(0, 0.1, -1.8);
haloRing2.scale.y = 0.5;
scene.add(haloRing2);
function seededRandom(seed) {
return function () {
seed |= 0;
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const random = seededRandom(42);
const starPositions = new Float32Array(240 * 3);
for (let i = 0; i < 240; i++) {
starPositions[i * 3] = (random() - 0.5) * 30;
starPositions[i * 3 + 1] = random() * 11 - 2;
starPositions[i * 3 + 2] = -3 - random() * 10;
}
const starGeometry = new THREE.BufferGeometry();
starGeometry.setAttribute(
"position",
new THREE.BufferAttribute(starPositions, 3)
);
const stars = new THREE.Points(
starGeometry,
new THREE.PointsMaterial({
color: 0x8bdfff,
size: 0.028,
transparent: true,
opacity: 0.58,
depthWrite: false
})
);
scene.add(stars);
const pathDots = [];
const pathDotGeometry = new THREE.SphereGeometry(0.035, 8, 8);
const pathDotMaterial = new THREE.MeshBasicMaterial({
color: 0x70e6ff,
transparent: true,
opacity: 0.7
});
for (let i = 0; i < 11; i++) {
const dot = new THREE.Mesh(pathDotGeometry, pathDotMaterial);
scene.add(dot);
pathDots.push(dot);
}
// -------------------------------------------------------------------------
// Label sprites made locally with CanvasTexture
// -------------------------------------------------------------------------
function makeLabel(text, color = "#dff8ff", width = 2, height = 0.5) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
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(width, height, 1);
sprite.renderOrder = 20;
sprite.userData.canvas = canvas;
sprite.userData.context = context;
sprite.userData.texture = texture;
paintLabel(sprite, text, color);
return sprite;
}
function paintLabel(sprite, text, color = "#dff8ff") {
const canvas = sprite.userData.canvas;
const context = sprite.userData.context;
context.clearRect(0, 0, canvas.width, canvas.height);
context.font = "800 56px Inter, system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = color;
context.fillText(text, canvas.width / 2, canvas.height / 2 + 2);
sprite.userData.texture.needsUpdate = true;
}
// -------------------------------------------------------------------------
// Reusable bit cells and transmitter/receiver panels
// -------------------------------------------------------------------------
function createCell(role = "data", small = false) {
const group = new THREE.Group();
const backing = new THREE.Mesh(
new THREE.BoxGeometry(
small ? 0.36 : 0.5,
small ? 0.36 : 0.5,
0.08
),
new THREE.MeshStandardMaterial({
color: 0x102538,
roughness: 0.75,
metalness: 0.3
})
);
backing.position.z = -0.04;
group.add(backing);
const cubeSize = small ? 0.245 : 0.38;
const cube = new THREE.Mesh(
new THREE.BoxGeometry(cubeSize, cubeSize, small ? 0.14 : 0.18),
new THREE.MeshStandardMaterial({
color: COLORS.waiting,
emissive: COLORS.waiting,
emissiveIntensity: 0.35,
roughness: 0.34,
metalness: 0.28
})
);
cube.position.z = 0.08;
cube.castShadow = true;
group.add(cube);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(cube.geometry),
new THREE.LineBasicMaterial({
color: 0x8adfff,
transparent: true,
opacity: 0.18
})
);
edges.position.copy(cube.position);
group.add(edges);
const label = makeLabel(
"?",
"#718b9d",
small ? 0.52 : 0.7,
small ? 0.13 : 0.175
);
label.position.z = 0.22;
group.add(label);
return { group, cube, edges, label, role };
}
function setCellVisual(cell, value, options = {}) {
const role = options.role ?? cell.role;
const waiting = options.waiting ?? false;
const damaged = options.damaged ?? false;
let color = COLORS.zero;
let emissive = COLORS.zero;
let labelColor = "#7691a2";
let text = "?";
if (!waiting) {
if (damaged) {
color = COLORS.damaged;
emissive = COLORS.damaged;
labelColor = "#ffd7dd";
} else if (role === "parity") {
color = COLORS.parity;
emissive = COLORS.parity;
labelColor = "#ffe7aa";
} else if (value === 1) {
color = COLORS.one;
emissive = COLORS.one;
labelColor = "#c9f8ff";
}
text = role === "parity" ? `P${value}` : String(value);
}
cell.cube.material.color.setHex(color);
cell.cube.material.emissive.setHex(emissive);
cell.cube.material.emissiveIntensity = damaged ? 0.7 : 0.38;
cell.edges.material.color.setHex(
damaged ? COLORS.damaged : role === "parity" ? COLORS.parity : 0x77cce7
);
cell.edges.material.opacity = damaged ? 0.72 : 0.18;
paintLabel(cell.label, text, labelColor);
}
function createPedestal(x, accentColor) {
const group = new THREE.Group();
group.position.x = x;
const base = new THREE.Mesh(
new THREE.CylinderGeometry(1.05, 1.18, 0.18, 48),
new THREE.MeshStandardMaterial({
color: 0x102437,
roughness: 0.46,
metalness: 0.62
})
);
base.position.y = -1.82;
base.castShadow = true;
base.receiveShadow = true;
group.add(base);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.91, 0.025, 8, 64),
new THREE.MeshBasicMaterial({
color: accentColor,
transparent: true,
opacity: 0.7
})
);
ring.rotation.x = Math.PI / 2;
ring.position.y = -1.715;
group.add(ring);
const support = new THREE.Mesh(
new THREE.BoxGeometry(0.32, 0.55, 0.32),
new THREE.MeshStandardMaterial({
color: 0x152a3c,
metalness: 0.72,
roughness: 0.4
})
);
support.position.y = -1.48;
support.castShadow = true;
group.add(support);
scene.add(group);
return group;
}
function createBoard(x, receiver = false) {
const group = new THREE.Group();
group.position.set(x, -0.15, 0);
const panel = new THREE.Mesh(
new THREE.BoxGeometry(2.35, 2.35, 0.18),
new THREE.MeshStandardMaterial({
color: 0x0b1b2b,
roughness: 0.46,
metalness: 0.58
})
);
panel.castShadow = true;
panel.receiveShadow = true;
group.add(panel);
const panelEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(panel.geometry),
new THREE.LineBasicMaterial({
color: receiver ? 0xff627c : 0x55dcff,
transparent: true,
opacity: 0.38
})
);
group.add(panelEdges);
const accent = new THREE.Mesh(
new THREE.BoxGeometry(2.05, 0.045, 0.055),
new THREE.MeshBasicMaterial({
color: receiver ? COLORS.damaged : COLORS.cyan
})
);
accent.position.set(0, 1.08, 0.13);
group.add(accent);
const title = makeLabel(
receiver ? "RECEIVER" : "SENT 10110100",
receiver ? "#ffafbd" : "#d8f8ff",
receiver ? 2.2 : 2.45,
0.55
);
title.position.set(0, 1.4, 0.15);
group.add(title);
const subtitle = makeLabel(
receiver ? "RECEIVED FRAME" : "8 DATA + 1 PARITY",
"#64869a",
1.8,
0.45
);
subtitle.position.set(0, -1.34, 0.14);
group.add(subtitle);
const positions = [
[-0.65, 0.5],
[0, 0.5],
[0.65, 0.5],
[-0.65, 0],
[0, 0],
[0.65, 0],
[-0.65, -0.5],
[0, -0.5],
[0.65, -0.5]
];
const cells = positions.map(([cellX, cellY], index) => {
const cell = createCell(index === 8 ? "parity" : "data");
cell.group.position.set(cellX, cellY, 0.11);
group.add(cell.group);
return cell;
});
let statusLight = null;
let statusLabel = null;
if (receiver) {
statusLight = new THREE.Mesh(
new THREE.SphereGeometry(0.15, 20, 20),
new THREE.MeshStandardMaterial({
color: COLORS.waiting,
emissive: COLORS.waiting,
emissiveIntensity: 0.55,
roughness: 0.3
})
);
statusLight.position.set(1.27, -0.82, 0.38);
group.add(statusLight);
statusLabel = makeLabel(
"WAITING FOR FRAME",
"#718b9d",
3.65,
0.91
);
statusLabel.position.set(0, -1.73, 0.3);
group.add(statusLabel);
}
scene.add(group);
createPedestal(x, receiver ? COLORS.damaged : COLORS.cyan);
return { group, cells, statusLight, statusLabel };
}
const sourceBoard = createBoard(-6.1, false);
const receiverBoard = createBoard(6.1, true);
sourceBoard.cells.forEach((cell, index) => {
const value = index < 8 ? DATA_BITS[index] : SENT_PARITY;
setCellVisual(cell, value, { role: index === 8 ? "parity" : "data" });
});
// -------------------------------------------------------------------------
// Moving data frame
// -------------------------------------------------------------------------
const packet = new THREE.Group();
packet.scale.setScalar(0.9);
const packetBack = new THREE.Mesh(
new THREE.BoxGeometry(2.95, 0.59, 0.08),
new THREE.MeshStandardMaterial({
color: 0x0b2134,
transparent: true,
opacity: 0.9,
roughness: 0.4,
metalness: 0.48
})
);
packetBack.position.z = -0.11;
packet.add(packetBack);
const packetEdge = new THREE.LineSegments(
new THREE.EdgesGeometry(packetBack.geometry),
new THREE.LineBasicMaterial({
color: COLORS.cyan,
transparent: true,
opacity: 0.42
})
);
packetEdge.position.copy(packetBack.position);
packet.add(packetEdge);
const packetCells = [];
for (let i = 0; i < 9; i++) {
const cell = createCell(i === 8 ? "parity" : "data", true);
cell.group.position.set(
i === 8 ? 1.45 : (i - 3.5) * 0.29,
0,
0.06
);
packet.add(cell.group);
packetCells.push(cell);
}
const packetLabel = makeLabel(
"TRANSMISSION",
"#9beaff",
2.05,
0.51
);
packetLabel.position.set(0, 0.61, 0.05);
packet.add(packetLabel);
const packetLight = new THREE.PointLight(0x55dcff, 5, 4, 2);
packetLight.position.set(0, 0.1, 1);
packet.add(packetLight);
scene.add(packet);
function resetPacket() {
packet.visible = true;
packet.position.copy(pathCurve.getPointAt(0));
packet.rotation.set(0, 0, 0);
packetCells.forEach((cell, index) => {
cell.cube.rotation.set(0, 0, 0);
cell.cube.scale.set(1, 1, 1);
cell.flipped = false;
const value = index < 8 ? DATA_BITS[index] : SENT_PARITY;
setCellVisual(cell, value, {
role: index === 8 ? "parity" : "data"
});
});
}
function resetReceiver() {
receiverBoard.cells.forEach((cell) => {
setCellVisual(cell, 0, {
role: cell.role,
waiting: true
});
});
receiverBoard.statusLight.material.color.setHex(COLORS.waiting);
receiverBoard.statusLight.material.emissive.setHex(COLORS.waiting);
receiverBoard.statusLight.material.emissiveIntensity = 0.4;
paintLabel(receiverBoard.statusLabel, "WAITING FOR FRAME", "#718b9d");
}
// -------------------------------------------------------------------------
// DOM bit rows and UI state
// -------------------------------------------------------------------------
function renderBitRow(element, bits, damagedIndices = []) {
element.replaceChildren();
for (let i = 0; i < 9; i++) {
const chip = document.createElement("span");
chip.className = "bit";
if (i === 8) chip.classList.add("parity");
if (!bits) {
chip.textContent = "·";
chip.classList.add("empty");
} else {
chip.textContent = String(bits[i]);
if (bits[i] === 0 && i !== 8) chip.classList.add("zero");
if (damagedIndices.includes(i)) chip.classList.add("corrupt");
}
element.appendChild(chip);
}
}
renderBitRow(ui.sentBits, [...DATA_BITS, SENT_PARITY]);
renderBitRow(ui.receivedBits, null);
const state = {
mode: null,
scenario: null,
phase: "idle",
flightElapsed: 0,
revealElapsed: 0,
doneElapsed: 0,
queue: []
};
const reducedMotion = window.matchMedia(
"(prefers-reduced-motion: reduce)"
).matches;
const flightDuration = reducedMotion ? 1.8 : 4.3;
function updateActiveButtons() {
ui.oneButton.classList.toggle("active", state.mode === "one");
ui.twoButton.classList.toggle("active", state.mode === "two");
ui.oneButton.setAttribute(
"aria-pressed",
String(state.mode === "one")
);
ui.twoButton.setAttribute(
"aria-pressed",
String(state.mode === "two")
);
}
function updateUI(phase) {
const scenario = state.scenario;
if (!scenario) return;
ui.scenarioName.textContent = scenario.name;
ui.scenarioDetail.textContent = scenario.detail;
ui.lessonTitle.textContent = scenario.lessonTitle;
ui.lessonBody.textContent = scenario.lessonBody;
updateActiveButtons();
ui.resultBadge.className = "badge";
if (phase === "flight") {
ui.resultBadge.textContent = "IN FLIGHT";
ui.resultBadge.classList.add("flight");
renderBitRow(ui.receivedBits, null);
ui.receivedMeta.textContent =
"The frame is moving from the transmitter to the receiver.";
} else if (phase === "reveal") {
ui.resultBadge.textContent = "CHECKING";
ui.resultBadge.classList.add("flight");
} else {
const isOne = state.mode === "one";
const receivedCodeword = [...scenario.received, SENT_PARITY];
const ones = receivedCodeword.reduce((sum, bit) => sum + bit, 0);
ui.resultBadge.textContent = isOne ? "DETECTED" : "MISSED";
ui.resultBadge.classList.add(isOne ? "bad" : "warn");
renderBitRow(
ui.receivedBits,
receivedCodeword,
scenario.flips
);
ui.receivedMeta.textContent = isOne
? `Received ${receivedCodeword.join("")} • ${ones} ones → odd parity → mismatch.`
: `Received ${receivedCodeword.join("")} • ${ones} ones → even parity → parity agrees, but damage remains.`;
}
}
function startScenario(mode, queue = []) {
state.mode = mode;
state.scenario = SCENARIOS[mode];
state.phase = "flight";
state.flightElapsed = 0;
state.revealElapsed = 0;
state.doneElapsed = 0;
state.queue = [...queue];
resetPacket();
resetReceiver();
updateUI("flight");
}
ui.oneButton.addEventListener("click", () => {
userInteracted = true;
startScenario("one");
});
ui.twoButton.addEventListener("click", () => {
userInteracted = true;
startScenario("two");
});
ui.bothButton.addEventListener("click", () => {
userInteracted = true;
startScenario("one", ["two"]);
});
// -------------------------------------------------------------------------
// Transmission state machine
// -------------------------------------------------------------------------
function updateFlight(delta) {
state.flightElapsed += delta;
const progress = Math.min(
1,
state.flightElapsed / flightDuration
);
const point = pathCurve.getPointAt(progress);
packet.position.copy(point);
packet.position.z = Math.sin(progress * Math.PI) * 0.42;
packet.rotation.z = Math.sin(progress * Math.PI * 2) * -0.055;
packet.rotation.y = Math.sin(progress * Math.PI) * 0.08;
const pulse = 1 + Math.sin(progress * Math.PI) * 0.045;
packet.scale.setScalar(0.9 * pulse);
state.scenario.flips.forEach((bitIndex, flipIndex) => {
const threshold = 0.47 + flipIndex * 0.12;
const cell = packetCells[bitIndex];
if (progress >= threshold && !cell.flipped) {
cell.flipped = true;
const newValue = state.scenario.received[bitIndex];
setCellVisual(cell, newValue, {
role: "data",
damaged: true
});
}
if (cell.flipped) {
const age = Math.max(
0,
state.flightElapsed - threshold * flightDuration
);
const rotation = Math.min(Math.PI, age * 5.5);
cell.cube.rotation.z = rotation;
cell.cube.scale.y =
1 - Math.sin(Math.min(1, age * 4) * Math.PI) * 0.28;
}
});
if (progress >= 1) {
packet.visible = false;
state.phase = "reveal";
state.revealElapsed = 0;
updateUI("reveal");
}
}
function updateReveal(delta) {
state.revealElapsed += delta;
const fullReceived = [
...state.scenario.received,
SENT_PARITY
];
receiverBoard.cells.forEach((cell, index) => {
const revealTime = 0.1 + index * 0.12;
if (state.revealElapsed >= revealTime) {
setCellVisual(cell, fullReceived[index], {
role: index === 8 ? "parity" : "data",
damaged: state.scenario.flips.includes(index)
});
}
});
if (state.revealElapsed >= 1.35) {
const totalOnes = fullReceived.reduce(
(sum, bit) => sum + bit,
0
);
const parityAgreement = totalOnes % 2 === 0;
const statusColor = parityAgreement
? COLORS.amber
: COLORS.damaged;
const statusText = parityAgreement
? "PARITY AGREES • ERROR MISSED"
: "PARITY MISMATCH • ERROR FLAGGED";
const statusLabelColor = parityAgreement
? "#ffd18a"
: "#ff9bad";
receiverBoard.statusLight.material.color.setHex(statusColor);
receiverBoard.statusLight.material.emissive.setHex(statusColor);
receiverBoard.statusLight.material.emissiveIntensity = 0.85;
paintLabel(
receiverBoard.statusLabel,
statusText,
statusLabelColor
);
state.phase = "done";
state.doneElapsed = 0;
updateUI("done");
}
}
function updateDone(delta) {
state.doneElapsed += delta;
if (state.doneElapsed > 1.65 && state.queue.length > 0) {
const next = state.queue.shift();
startScenario(next, state.queue);
}
}
// -------------------------------------------------------------------------
// Direct camera controls — no addons or OrbitControls
// -------------------------------------------------------------------------
let dragging = false;
let previousX = 0;
let previousY = 0;
let activePointers = new Map();
let pinchDistance = 0;
const canvas = renderer.domElement;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
activePointers.set(event.pointerId, event);
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!activePointers.has(event.pointerId)) return;
activePointers.set(event.pointerId, event);
if (activePointers.size === 1 && dragging) {
const deltaX = event.clientX - previousX;
const deltaY = event.clientY - previousY;
cameraState.yaw -= deltaX * 0.005;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + deltaY * 0.0035,
-0.42,
0.62
);
previousX = event.clientX;
previousY = event.clientY;
} else if (activePointers.size === 2) {
const points = [...activePointers.values()];
const distance = Math.hypot(
points[0].clientX - points[1].clientX,
points[0].clientY - points[1].clientY
);
if (pinchDistance > 0) {
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + (pinchDistance - distance) * 0.018,
9,
30
);
cameraState.hasZoomed = true;
}
pinchDistance = distance;
}
});
function endPointer(event) {
activePointers.delete(event.pointerId);
if (activePointers.size < 2) pinchDistance = 0;
if (activePointers.size === 0) dragging = false;
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener("lostpointercapture", endPointer);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.012,
9,
30
);
cameraState.hasZoomed = true;
},
{ passive: false }
);
function updateCamera() {
const horizontalRadius =
Math.cos(cameraState.pitch) * cameraState.radius;
camera.position.set(
Math.sin(cameraState.yaw) * horizontalRadius,
cameraState.targetY +
Math.sin(cameraState.pitch) * cameraState.radius,
Math.cos(cameraState.yaw) * horizontalRadius
);
camera.lookAt(0, cameraState.targetY, 0);
}
function handleResize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
camera.aspect = width / height;
camera.updateProjectionMatrix();
if (!cameraState.hasZoomed) {
cameraState.radius = camera.aspect < 1 ? 24 : 16;
}
}
window.addEventListener("resize", handleResize);
handleResize();
// -------------------------------------------------------------------------
// Main loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
let elapsed = 0;
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
elapsed += delta;
if (state.phase === "flight") {
updateFlight(delta);
} else if (state.phase === "reveal") {
updateReveal(delta);
} else if (state.phase === "done") {
updateDone(delta);
}
pathDots.forEach((dot, index) => {
const progress = (elapsed * 0.075 + index / pathDots.length) % 1;
dot.position.copy(pathCurve.getPointAt(progress));
dot.position.z += Math.sin(progress * Math.PI) * 0.42;
});
haloRing.rotation.z = elapsed * 0.035;
haloRing2.rotation.z = -elapsed * 0.022;
stars.rotation.y = Math.sin(elapsed * 0.025) * 0.03;
updateCamera();
renderer.render(scene, camera);
}
resetPacket();
resetReceiver();
updateCamera();
animate();
// Automatically demonstrate both scenarios unless the user interacts first.
let userInteracted = false;
window.setTimeout(() => {
if (!userInteracted) {
startScenario("one", ["two"]);
}
}, reducedMotion ? 400 : 1000);
</script>
</body>
</html>
```