Prompt specification
Build or customize the Three.js 3D scene "Library shelf ordering diorama" 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: Library shelf ordering diorama
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/library-shelf-ordering-diorama-x1907
Scene Description Prompt:
Create a standalone voxel scene in one HTML file using Three.js from cdnjs. Compose books with synthetic catalog keys moving through a sorting workspace; show stable ordering for equal keys when the selected algorithm promises stability.
Working Three.js Starter (library-shelf-ordering-diorama-x1907):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Voxel Catalog Sorter</title>
<style>
:root {
color-scheme: dark;
--bg: #07101c;
--panel: rgba(9, 20, 34, 0.88);
--panel-strong: rgba(10, 24, 41, 0.96);
--line: rgba(158, 202, 230, 0.18);
--muted: #8ca3b8;
--text: #eef8ff;
--cyan: #5eead4;
--amber: #fbbf24;
--red: #fb7185;
--green: #86efac;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 35%, #15324b 0, #091827 45%, #050b14 100%);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.hud {
position: fixed;
z-index: 10;
pointer-events: none;
}
.panel {
pointer-events: auto;
background: var(--panel);
border: 1px solid var(--line);
box-shadow:
0 20px 60px rgba(0, 0, 0, 0.34),
inset 0 1px rgba(255, 255, 255, 0.035);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
header {
top: 0;
left: 0;
right: 0;
padding: 18px 22px 30px;
background: linear-gradient(rgba(4, 10, 18, 0.78), transparent);
}
.brand {
display: flex;
align-items: center;
gap: 13px;
}
.brand-mark {
width: 36px;
height: 36px;
position: relative;
border: 2px solid var(--cyan);
box-shadow: 5px 5px 0 rgba(94, 234, 212, 0.18);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
background: var(--cyan);
}
.brand-mark::before {
width: 14px;
height: 4px;
left: 9px;
top: 8px;
box-shadow: 0 9px 0 var(--cyan), 0 18px 0 var(--cyan);
}
.brand-mark::after {
width: 4px;
height: 14px;
left: 8px;
top: 14px;
box-shadow: 9px 0 0 var(--cyan);
}
h1 {
margin: 0;
font-size: 17px;
line-height: 1;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.subtitle {
margin-top: 6px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
letter-spacing: 0.04em;
}
#controlsPanel {
top: 88px;
left: 18px;
width: 294px;
border-radius: 14px;
padding: 16px;
}
#tiePanel {
top: 88px;
right: 18px;
width: 336px;
border-radius: 14px;
padding: 16px;
}
.eyebrow {
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
.pill {
display: inline-flex;
align-items: center;
min-height: 22px;
padding: 4px 8px;
border: 1px solid rgba(94, 234, 212, 0.34);
border-radius: 999px;
background: rgba(94, 234, 212, 0.09);
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.pill.warning {
color: var(--amber);
border-color: rgba(251, 191, 36, 0.35);
background: rgba(251, 191, 36, 0.09);
}
.algorithm-list {
display: grid;
gap: 7px;
}
.algo-button {
width: 100%;
display: grid;
grid-template-columns: 1fr auto;
gap: 3px 9px;
text-align: left;
padding: 10px 11px;
color: var(--text);
background: rgba(255, 255, 255, 0.025);
border: 1px solid var(--line);
border-radius: 9px;
cursor: pointer;
transition:
border-color 140ms ease,
background 140ms ease,
transform 140ms ease;
}
.algo-button:hover {
background: rgba(255, 255, 255, 0.05);
border-color: rgba(158, 202, 230, 0.36);
}
.algo-button:active {
transform: translateY(1px);
}
.algo-button.active {
border-color: rgba(94, 234, 212, 0.7);
background: rgba(94, 234, 212, 0.085);
box-shadow: inset 3px 0 0 var(--cyan);
}
.algo-name {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.025em;
}
.algo-kind {
align-self: center;
color: var(--cyan);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.algo-kind.unstable {
color: var(--amber);
}
.algo-description {
grid-column: 1 / -1;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.divider {
height: 1px;
margin: 14px 0;
background: var(--line);
}
.speed-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 12px;
color: var(--muted);
font-size: 11px;
}
input[type="range"] {
width: 145px;
accent-color: var(--cyan);
}
.button-row {
display: grid;
grid-template-columns: 1.4fr 0.8fr 0.8fr;
gap: 7px;
margin-top: 12px;
}
.control-button {
min-height: 36px;
padding: 8px 9px;
border-radius: 8px;
border: 1px solid var(--line);
color: var(--text);
background: rgba(255, 255, 255, 0.035);
cursor: pointer;
font-size: 11px;
font-weight: 750;
transition: background 120ms ease, border-color 120ms ease;
}
.control-button:hover {
border-color: rgba(158, 202, 230, 0.38);
background: rgba(255, 255, 255, 0.065);
}
.control-button.primary {
color: #03211d;
border-color: var(--cyan);
background: var(--cyan);
}
.control-button.primary:hover {
background: #8af5e3;
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-top: 13px;
}
.stat {
padding: 9px 8px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255, 255, 255, 0.025);
}
.stat-label {
color: var(--muted);
font-size: 8px;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.stat-value {
margin-top: 4px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 14px;
font-weight: 800;
}
.book-detail {
margin-top: 12px;
min-height: 48px;
padding: 10px;
border: 1px dashed rgba(158, 202, 230, 0.22);
border-radius: 8px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.5;
}
.book-detail strong {
color: var(--text);
}
#tieRows {
display: grid;
gap: 8px;
}
.tie-row {
display: grid;
grid-template-columns: 46px 1fr auto;
align-items: center;
gap: 9px;
min-height: 45px;
padding: 8px 9px;
border: 1px solid var(--line);
border-left: 3px solid var(--key-color);
border-radius: 8px;
background: rgba(255, 255, 255, 0.025);
}
.tie-key {
color: var(--key-color);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 14px;
font-weight: 900;
}
.tie-order {
color: #c8d8e7;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.5;
}
.tie-state {
padding: 4px 6px;
border-radius: 5px;
color: var(--muted);
background: rgba(255, 255, 255, 0.045);
font-size: 8px;
font-weight: 900;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.tie-state.kept {
color: var(--green);
background: rgba(134, 239, 172, 0.09);
}
.tie-state.crossed {
color: var(--red);
background: rgba(251, 113, 133, 0.1);
}
.tie-summary {
margin: 11px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
#statusBar {
left: 50%;
bottom: 18px;
transform: translateX(-50%);
width: min(620px, calc(100% - 40px));
min-height: 48px;
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
gap: 11px;
padding: 10px 13px;
border-radius: 11px;
background: rgba(5, 13, 23, 0.9);
border: 1px solid var(--line);
box-shadow: 0 14px 40px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(12px);
}
.status-dot {
width: 9px;
height: 9px;
border-radius: 2px;
background: var(--cyan);
box-shadow: 0 0 12px rgba(94, 234, 212, 0.7);
animation: pulse 1.4s ease-in-out infinite;
}
@keyframes pulse {
50% {
opacity: 0.38;
transform: scale(0.72);
}
}
#statusMessage {
overflow: hidden;
color: #d9e8f5;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
text-overflow: ellipsis;
white-space: nowrap;
}
#progressText {
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
white-space: nowrap;
}
#cameraHint {
left: 18px;
bottom: 18px;
padding: 8px 10px;
color: rgba(210, 229, 243, 0.67);
background: rgba(5, 13, 23, 0.62);
border: 1px solid rgba(158, 202, 230, 0.12);
border-radius: 8px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
}
kbd {
color: var(--cyan);
font: inherit;
}
@media (max-width: 900px) {
#controlsPanel {
width: 270px;
}
#tiePanel {
width: 300px;
}
#cameraHint {
display: none;
}
}
@media (max-width: 680px) {
header {
padding: 12px;
}
h1 {
font-size: 13px;
}
.subtitle {
font-size: 9px;
}
#controlsPanel {
top: 76px;
left: 10px;
width: calc(100% - 20px);
max-height: 43vh;
overflow: auto;
}
#tiePanel {
top: auto;
right: 10px;
bottom: 66px;
width: calc(100% - 20px);
max-height: 31vh;
overflow: auto;
}
#statusBar {
bottom: 10px;
width: calc(100% - 20px);
}
}
</style>
</head>
<body>
<div id="scene"></div>
<header class="hud">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>Order Deck / Voxel Catalog Sorter</h1>
<div class="subtitle">SYNTHETIC KEYS · EQUAL-KEY STABILITY AUDIT · THREE.JS CORE</div>
</div>
</div>
</header>
<section id="controlsPanel" class="hud panel" aria-label="Sorting controls">
<div class="panel-title">
<span class="eyebrow">Algorithm</span>
<span id="stabilityPill" class="pill">Stable</span>
</div>
<div class="algorithm-list">
<button class="algo-button" data-algorithm="insertion">
<span class="algo-name">INSERTION SORT</span>
<span class="algo-kind">Stable</span>
<span class="algo-description">Shifts records right and inserts after equal keys.</span>
</button>
<button class="algo-button active" data-algorithm="merge">
<span class="algo-name">MERGE SORT</span>
<span class="algo-kind">Stable</span>
<span class="algo-description">Merges runs using a left-first rule for ties.</span>
</button>
<button class="algo-button" data-algorithm="selection">
<span class="algo-name">SELECTION SORT</span>
<span class="algo-kind unstable">Not stable</span>
<span class="algo-description">May swap equal-key records across one another.</span>
</button>
</div>
<div class="divider"></div>
<div class="speed-row">
<label for="speed">Playback speed</label>
<span id="speedValue">1.20×</span>
</div>
<input id="speed" type="range" min="0.55" max="2.4" value="1.2" step="0.05" />
<div class="button-row">
<button id="playBtn" class="control-button primary">Run sort</button>
<button id="stepBtn" class="control-button">Step</button>
<button id="resetBtn" class="control-button">Reset</button>
</div>
<div class="stats">
<div class="stat">
<div class="stat-label">Step</div>
<div id="stepStat" class="stat-value">0/4</div>
</div>
<div class="stat">
<div class="stat-label">Compares</div>
<div id="compareStat" class="stat-value">0</div>
</div>
<div class="stat">
<div class="stat-label">Writes</div>
<div id="moveStat" class="stat-value">0</div>
</div>
</div>
<div id="bookDetail" class="book-detail">
Click a voxel book to inspect its catalog record.
</div>
</section>
<aside id="tiePanel" class="hud panel" aria-label="Equal-key ordering audit">
<div class="panel-title">
<span class="eyebrow">Equal-key ledger</span>
<span id="tieCount" class="pill">5 key groups</span>
</div>
<div id="tieRows"></div>
<p id="tieSummary" class="tie-summary"></p>
</aside>
<div id="statusBar" class="hud">
<span class="status-dot"></span>
<span id="statusMessage">10 synthetic records waiting at infeed.</span>
<span id="progressText">READY</span>
</div>
<div id="cameraHint" class="hud">
DRAG orbit · WHEEL zoom · SHIFT+DRAG pan · <kbd>SPACE</kbd> play/pause ·
<kbd>→</kbd> step · <kbd>R</kbd> reset
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Data: fixed synthetic catalog records with several deliberately equal keys.
// -------------------------------------------------------------------------
const KEY_COLORS = {
8: 0x5eead4,
17: 0xfbbf24,
31: 0xa78bfa,
42: 0xfb7185,
63: 0x60a5fa
};
const BOOKS = [
{ id: "CAT-101", key: 42 },
{ id: "CAT-204", key: 17 },
{ id: "CAT-318", key: 42 },
{ id: "CAT-407", key: 8 },
{ id: "CAT-522", key: 31 },
{ id: "CAT-619", key: 17 },
{ id: "CAT-731", key: 63 },
{ id: "CAT-846", key: 31 },
{ id: "CAT-913", key: 42 },
{ id: "CAT-A24", key: 8 }
];
const bookById = new Map(BOOKS.map((book) => [book.id, book]));
const initialOrder = BOOKS.map((book) => book.id);
const keyOf = (id) => bookById.get(id).key;
const shortId = (id) => id.replace("CAT-", "");
const ALGORITHMS = {
insertion: {
stable: true,
description: "Stable insertion sort"
},
merge: {
stable: true,
description: "Stable merge sort"
},
selection: {
stable: false,
description: "Unstable selection sort"
}
};
let selectedAlgorithm = "merge";
let events = [];
let currentOrder = [...initialOrder];
let eventIndex = 0;
let runState = "idle"; // idle, feeding, sorting, dispatching, done
let paused = false;
let playbackSpeed = 1.2;
let simTime = 0;
let feedReadyAt = 0;
let eventReadyAt = 0;
let dispatchReadyAt = 0;
let dispatchManual = false;
let dispatchCompletionCount = 0;
let selectedBookId = null;
// -------------------------------------------------------------------------
// Renderer, scene, camera, and custom camera controls.
// -------------------------------------------------------------------------
const container = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
container.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111e);
scene.fog = new THREE.Fog(0x07111e, 23, 43);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0, 1.05, 0);
let cameraYaw = 0.54;
let cameraPitch = 0.98;
let cameraRadius = 20.5;
function updateCamera() {
const horizontal = Math.sin(cameraPitch) * cameraRadius;
camera.position.set(
cameraTarget.x + horizontal * Math.sin(cameraYaw),
cameraTarget.y + Math.cos(cameraPitch) * cameraRadius,
cameraTarget.z + horizontal * Math.cos(cameraYaw)
);
camera.lookAt(cameraTarget);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xbfe9ff, 0x172033, 2.15);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xe8f7ff, 3.2);
keyLight.position.set(-8, 14, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -15;
keyLight.shadow.camera.right = 15;
keyLight.shadow.camera.top = 13;
keyLight.shadow.camera.bottom = -13;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 40;
keyLight.shadow.bias = -0.00025;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x5eead4, 1.8);
rimLight.position.set(9, 7, -8);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xfbbf24, 18, 12, 2);
warmLight.position.set(5.5, 4.5, 3);
scene.add(warmLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(48, 48),
new THREE.MeshStandardMaterial({
color: 0x0b1724,
roughness: 0.92,
metalness: 0.05
})
);
floor.rotation.x = -Math.PI / 2;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(40, 40, 0x244156, 0x132638);
grid.position.y = 0.012;
grid.material.transparent = true;
grid.material.opacity = 0.52;
scene.add(grid);
// -------------------------------------------------------------------------
// Voxel workspace: infeed, sorting deck, and dispatch deck.
// -------------------------------------------------------------------------
const INPUT_Z = -3.1;
const WORK_Z = 0;
const OUTPUT_Z = 3.1;
const DECK_Y = 0.88;
const SLOT_X = Array.from({ length: BOOKS.length }, (_, index) =>
-5.4 + index * 1.2
);
function boxMesh(width, height, depth, color, position, parent = scene) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
new THREE.MeshStandardMaterial({
color,
roughness: 0.74,
metalness: 0.16
})
);
mesh.position.copy(position);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function buildDeck(z, accent, isMain = false) {
const group = new THREE.Group();
scene.add(group);
boxMesh(
13.8,
0.28,
1.92,
0x17283a,
new THREE.Vector3(0, 0.62, z),
group
);
boxMesh(
13.95,
0.12,
0.13,
accent,
new THREE.Vector3(0, 0.79, z - 0.88),
group
);
boxMesh(
13.95,
0.12,
0.13,
accent,
new THREE.Vector3(0, 0.79, z + 0.88),
group
);
for (let index = 0; index < 24; index += 1) {
const slat = boxMesh(
0.35,
0.09,
1.58,
index % 2 === 0 ? 0x263c50 : 0x203448,
new THREE.Vector3(-6.45 + index * 0.56, 0.79, z),
group
);
slat.castShadow = false;
}
for (const x of [-5.8, 5.8]) {
for (const side of [-0.68, 0.68]) {
boxMesh(
0.28,
0.62,
0.28,
0x20364b,
new THREE.Vector3(x, 0.31, z + side),
group
);
}
}
if (isMain) {
for (const x of [-6.45, 6.45]) {
boxMesh(
0.26,
3.15,
0.3,
0x2c4960,
new THREE.Vector3(x, 1.9, z),
group
);
boxMesh(
0.52,
0.22,
0.52,
accent,
new THREE.Vector3(x, 0.92, z),
group
);
}
boxMesh(
13.15,
0.24,
0.3,
0x2c4960,
new THREE.Vector3(0, 3.42, z),
group
);
boxMesh(
4.8,
0.05,
0.34,
accent,
new THREE.Vector3(0, 3.27, z),
group
);
}
return group;
}
buildDeck(INPUT_Z, 0x3d7087);
buildDeck(WORK_Z, 0x5eead4, true);
buildDeck(OUTPUT_Z, 0x5eead4);
function makeTextPlane(text, width, height, accent = "#5eead4") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
context.fillStyle = "rgba(5, 13, 23, 0.92)";
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = accent;
context.fillRect(0, 0, 10, canvas.height);
context.font = "800 48px monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2 + 4, canvas.height / 2 + 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.MeshBasicMaterial({
map: texture,
transparent: true,
depthWrite: false
});
return new THREE.Mesh(new THREE.PlaneGeometry(width, height), material);
}
const infeedSign = makeTextPlane("01 INFEED", 2.55, 0.62, "#73c8e6");
infeedSign.position.set(-5.25, 2.45, INPUT_Z);
scene.add(infeedSign);
const workSign = makeTextPlane("02 SORT DECK", 2.85, 0.62, "#5eead4");
workSign.position.set(-4.85, 2.75, WORK_Z);
scene.add(workSign);
const outputSign = makeTextPlane("03 DISPATCH", 2.85, 0.62, "#86efac");
outputSign.position.set(-4.85, 2.45, OUTPUT_Z);
scene.add(outputSign);
// Work-deck slot pads.
for (let index = 0; index < BOOKS.length; index += 1) {
const pad = boxMesh(
1.02,
0.035,
1.38,
index % 2 === 0 ? 0x21394d : 0x1d3448,
new THREE.Vector3(SLOT_X[index], 0.81, WORK_Z)
);
pad.castShadow = false;
}
// Small voxel data packets moving along the back rail.
const packets = [];
for (let index = 0; index < 15; index += 1) {
const packet = boxMesh(
0.12,
0.12,
0.12,
index % 3 === 0 ? 0x5eead4 : 0xfbbf24,
new THREE.Vector3(-6 + index * 0.8, 0.95, WORK_Z - 1.06)
);
packet.castShadow = false;
packets.push(packet);
}
// Voxel crates and machine blocks.
function buildCrate(x, z, color) {
const group = new THREE.Group();
group.position.set(x, 0, z);
scene.add(group);
boxMesh(1.15, 0.92, 1.15, color, new THREE.Vector3(0, 0.46, 0), group);
boxMesh(1.22, 0.1, 1.22, 0x2c4052, new THREE.Vector3(0, 0.95, 0), group);
for (const side of [-1, 1]) {
boxMesh(
0.08,
0.68,
1.2,
0x304b60,
new THREE.Vector3(side * 0.37, 0.45, 0),
group
);
}
}
buildCrate(-8.1, -1.7, 0x29465d);
buildCrate(8.0, -2.8, 0x29465d);
buildCrate(8.2, 2.0, 0x244052);
// -------------------------------------------------------------------------
// Voxel books.
// -------------------------------------------------------------------------
const clickTargets = [];
const bookObjects = new Map();
function createBookLabel(book) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 512;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(5, 13, 23, 0.82)";
context.fillRect(15, 24, 226, 464);
context.fillStyle = "#ffffff";
context.font = "900 74px monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(String(book.key).padStart(2, "0"), 128, 125);
context.fillStyle = "rgba(255,255,255,0.45)";
context.fillRect(42, 190, 172, 4);
context.fillStyle = "#ffffff";
context.font = "700 25px monospace";
context.fillText(book.id, 128, 255);
context.fillStyle = "rgba(255,255,255,0.52)";
context.font = "600 18px monospace";
context.fillText("KEY", 128, 340);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
return new THREE.Mesh(
new THREE.PlaneGeometry(0.61, 0.88),
new THREE.MeshBasicMaterial({
map: texture,
transparent: true,
depthWrite: false
})
);
}
function createBook(book) {
const group = new THREE.Group();
const color = KEY_COLORS[book.key];
const coverMaterial = new THREE.MeshStandardMaterial({
color,
roughness: 0.62,
metalness: 0.08,
emissive: color,
emissiveIntensity: 0.035
});
const pageMaterial = new THREE.MeshStandardMaterial({
color: 0xe7ddc3,
roughness: 0.92
});
const page = new THREE.Mesh(
new THREE.BoxGeometry(0.7, 1.3, 0.49),
pageMaterial
);
page.position.y = 0.67;
page.castShadow = true;
page.receiveShadow = true;
group.add(page);
const frontCover = new THREE.Mesh(
new THREE.BoxGeometry(0.87, 1.4, 0.075),
coverMaterial
);
frontCover.position.set(0, 0.69, 0.287);
frontCover.castShadow = true;
group.add(frontCover);
const backCover = frontCover.clone();
backCover.position.z = -0.287;
group.add(backCover);
const spine = new THREE.Mesh(
new THREE.BoxGeometry(0.13, 1.4, 0.64),
coverMaterial
);
spine.position.set(-0.405, 0.69, 0);
spine.castShadow = true;
group.add(spine);
const topLip = new THREE.Mesh(
new THREE.BoxGeometry(0.73, 0.045, 0.54),
coverMaterial
);
topLip.position.y = 1.345;
group.add(topLip);
const label = createBookLabel(book);
label.position.set(0.03, 0.77, 0.329);
group.add(label);
const bookmark = new THREE.Mesh(
new THREE.BoxGeometry(0.09, 0.3, 0.025),
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.8
})
);
bookmark.position.set(0.25, 1.52, 0.31);
group.add(bookmark);
group.traverse((child) => {
if (child.isMesh) {
child.userData.bookId = book.id;
clickTargets.push(child);
}
});
group.userData.bookId = book.id;
scene.add(group);
const object = {
id: book.id,
group,
coverMaterial
};
bookObjects.set(book.id, object);
return object;
}
BOOKS.forEach(createBook);
const selectionMarker = new THREE.Mesh(
new THREE.BoxGeometry(1.04, 1.66, 0.75),
new THREE.MeshBasicMaterial({
color: 0xffffff,
wireframe: true,
transparent: true,
opacity: 0.85
})
);
selectionMarker.visible = false;
scene.add(selectionMarker);
// -------------------------------------------------------------------------
// Scanner head and beam.
// -------------------------------------------------------------------------
const scanner = new THREE.Group();
scanner.position.set(0, 3.12, WORK_Z);
scene.add(scanner);
const scannerHead = new THREE.Mesh(
new THREE.BoxGeometry(0.58, 0.36, 0.68),
new THREE.MeshStandardMaterial({
color: 0x183e4a,
emissive: 0x5eead4,
emissiveIntensity: 0.42,
roughness: 0.4
})
);
scannerHead.castShadow = true;
scanner.add(scannerHead);
const scannerBeam = new THREE.Mesh(
new THREE.BoxGeometry(0.12, 2.05, 0.9),
new THREE.MeshBasicMaterial({
color: 0x5eead4,
transparent: true,
opacity: 0.12,
depthWrite: false
})
);
scannerBeam.position.y = -1.08;
scanner.add(scannerBeam);
const scannerLight = new THREE.PointLight(0x5eead4, 5, 3.5, 2);
scanner.add(scannerLight);
let scannerTargetX = 0;
// -------------------------------------------------------------------------
// Sorting event generation.
//
// Every event stores the complete visible order after a meaningful action.
// Equal-key behavior is implemented explicitly:
// insertion: shifts only while left key > item key
// merge: takes the left record when keys are equal
// selection: has no equal-key preservation guarantee
// -------------------------------------------------------------------------
function buildEvents(algorithm) {
const result = [];
let comparisons = 0;
let writes = 0;
if (algorithm === "insertion") {
const order = [...initialOrder];
for (let index = 1; index < order.length; index += 1) {
const itemId = order[index];
const itemKey = keyOf(itemId);
let left = index - 1;
let shifted = 0;
while (left >= 0) {
comparisons += 1;
// Strict comparison preserves equal-key records.
if (keyOf(order[left]) <= itemKey) {
break;
}
order[left + 1] = order[left];
writes += 1;
shifted += 1;
left -= 1;
}
order[left + 1] = itemId;
writes += 1;
result.push({
order: [...order],
focus: left + 1,
comparisons,
writes,
message:
shifted > 0
? `Insert ${itemId}: shifted ${shifted} record${shifted === 1 ? "" : "s"}; equal keys stay ahead.`
: `Insert ${itemId}: already in order relative to equal keys.`
});
}
return result;
}
if (algorithm === "merge") {
const order = [...initialOrder];
const temporary = new Array(order.length);
let width = 1;
while (width < order.length) {
for (let left = 0; left < order.length; left += width * 2) {
const middle = Math.min(left + width, order.length);
const right = Math.min(left + width * 2, order.length);
let leftIndex = left;
let rightIndex = middle;
let writeIndex = left;
while (leftIndex < middle || rightIndex < right) {
comparisons += 1;
if (
rightIndex >= right ||
(leftIndex < middle && keyOf(order[leftIndex]) <= keyOf(order[rightIndex]))
) {
// <= is the stable merge choice for equal keys.
temporary[writeIndex] = order[leftIndex];
leftIndex += 1;
} else {
temporary[writeIndex] = order[rightIndex];
rightIndex += 1;
}
writeIndex += 1;
writes += 1;
}
for (let index = left; index < right; index += 1) {
order[index] = temporary[index];
}
}
result.push({
order: [...order],
focus: Math.min(width - 1, order.length - 1),
comparisons,
writes,
message: `Merge pass ${Math.log2(width * 2) | 0}: left-first rule preserves equal-key order.`
});
width *= 2;
}
return result;
}
// Selection sort is intentionally not stable.
const order = [...initialOrder];
for (let index = 0; index < order.length - 1; index += 1) {
let minimum = index;
for (let scan = index + 1; scan < order.length; scan += 1) {
comparisons += 1;
// A strict comparison does not protect equal-key relative order.
if (keyOf(order[scan]) < keyOf(order[minimum])) {
minimum = scan;
}
}
if (minimum !== index) {
const temporary = order[index];
order[index] = order[minimum];
order[minimum] = temporary;
writes += 2;
result.push({
order: [...order],
focus: minimum,
comparisons,
writes,
message: `Swap ${order[index]} with ${order[minimum]}: equal keys may cross in this algorithm.`
});
}
}
return result;
}
// -------------------------------------------------------------------------
// Animation system. Pausing freezes normal tweens; a manual Step creates
// independently animated tweens so the user can inspect one event at a time.
// -------------------------------------------------------------------------
const tweens = [];
function cancelBookTweens(bookId) {
for (let index = tweens.length - 1; index >= 0; index -= 1) {
if (tweens[index].book.id === bookId) {
tweens.splice(index, 1);
}
}
}
function tweenBook(book, target, duration, delay, arc, manual, onComplete) {
cancelBookTweens(book.id);
tweens.push({
book,
from: book.group.position.clone(),
to: target.clone(),
elapsed: -delay,
duration,
arc,
manual,
onComplete
});
}
function animateOrder(order, z, duration, arc = 0.45, manual = false, onComplete) {
order.forEach((id, index) => {
const book = bookObjects.get(id);
const target = new THREE.Vector3(SLOT_X[index], DECK_Y, z);
const dx = Math.abs(target.x - book.group.position.x);
const delay = Math.min(110, dx * 10);
tweenBook(book, target, duration, delay, arc, manual, onComplete);
});
}
function updateTweens(delta) {
for (let index = tweens.length - 1; index >= 0; index -= 1) {
const tween = tweens[index];
if (paused && !tween.manual) {
continue;
}
tween.elapsed += delta;
if (tween.elapsed < 0) {
continue;
}
const progress = Math.min(1, tween.elapsed / tween.duration);
const eased =
progress < 0.5
? 4 * progress * progress * progress
: 1 - Math.pow(-2 * progress + 2, 3) / 2;
tween.book.group.position.lerpVectors(tween.from, tween.to, eased);
tween.book.group.position.y += Math.sin(Math.PI * progress) * tween.arc;
tween.book.group.rotation.z =
Math.sin(Math.PI * progress) *
Math.sign(tween.to.x - tween.from.x || 1) *
0.07;
if (progress >= 1) {
tween.book.group.position.copy(tween.to);
tween.book.group.rotation.z = 0;
if (tween.onComplete) {
tween.onComplete();
}
tweens.splice(index, 1);
}
}
}
// -------------------------------------------------------------------------
// UI and tie audit.
// -------------------------------------------------------------------------
const playButton = document.querySelector("#playBtn");
const stepButton = document.querySelector("#stepBtn");
const resetButton = document.querySelector("#resetBtn");
const speedInput = document.querySelector("#speed");
const speedValue = document.querySelector("#speedValue");
const stepStat = document.querySelector("#stepStat");
const compareStat = document.querySelector("#compareStat");
const moveStat = document.querySelector("#moveStat");
const statusMessage = document.querySelector("#statusMessage");
const progressText = document.querySelector("#progressText");
const stabilityPill = document.querySelector("#stabilityPill");
const tieRows = document.querySelector("#tieRows");
const tieSummary = document.querySelector("#tieSummary");
const bookDetail = document.querySelector("#bookDetail");
function setStatus(message, progress = "") {
statusMessage.textContent = message;
progressText.textContent = progress;
}
function updateStats(comparisons = 0, writes = 0) {
stepStat.textContent = `${eventIndex}/${events.length}`;
compareStat.textContent = comparisons;
moveStat.textContent = writes;
}
function updatePlayButton() {
if (runState === "done") {
playButton.textContent = "Run again";
} else if (paused) {
playButton.textContent = "Resume";
} else if (runState === "idle") {
playButton.textContent = "Run sort";
} else {
playButton.textContent = "Pause";
}
}
function updateBookDetail() {
if (!selectedBookId) {
bookDetail.innerHTML = "Click a voxel book to inspect its catalog record.";
return;
}
const book = bookById.get(selectedBookId);
const slot = currentOrder.indexOf(selectedBookId) + 1;
const stableNote = ALGORITHMS[selectedAlgorithm].stable
? "Equal-key order is protected by this algorithm."
: "This algorithm does not protect equal-key order.";
bookDetail.innerHTML = `
<strong>${book.id}</strong><br>
SYNTHETIC KEY: <strong>${String(book.key).padStart(2, "0")}</strong>
· CURRENT SLOT: <strong>${slot}</strong><br>
${stableNote}
`;
}
function getTieGroups() {
const groups = new Map();
for (const key of Object.keys(KEY_COLORS).map(Number)) {
groups.set(key, []);
}
for (const id of initialOrder) {
groups.get(keyOf(id)).push(id);
}
return [...groups.entries()];
}
function renderTieAudit(final = false) {
tieRows.replaceChildren();
for (const [key, baseline] of getTieGroups()) {
const actual = final
? currentOrder.filter((id) => keyOf(id) === key)
: [...baseline];
const preserved =
actual.length === baseline.length &&
actual.every((id, index) => id === baseline[index]);
const row = document.createElement("div");
row.className = "tie-row";
row.style.setProperty(
"--key-color",
`#${KEY_COLORS[key].toString(16).padStart(6, "0")}`
);
const keyElement = document.createElement("div");
keyElement.className = "tie-key";
keyElement.textContent = String(key).padStart(2, "0");
const orderElement = document.createElement("div");
orderElement.className = "tie-order";
orderElement.textContent = actual.map(shortId).join(" → ");
const stateElement = document.createElement("div");
stateElement.className = "tie-state";
stateElement.textContent = final ? (preserved ? "Kept" : "Crossed") : "Infeed";
if (final && preserved) {
stateElement.classList.add("kept");
} else if (final) {
stateElement.classList.add("crossed");
}
row.append(keyElement, orderElement, stateElement);
tieRows.appendChild(row);
}
if (!final) {
tieSummary.textContent =
"Baseline captured at infeed. Run the sorter to audit whether each equal-key group kept that order.";
} else if (ALGORITHMS[selectedAlgorithm].stable) {
tieSummary.textContent =
"Stable result: every equal-key group retained its original infeed order.";
} else {
tieSummary.textContent =
"Unstable result: a red CROSSED marker means equal-key records changed their relative infeed order.";
}
}
function selectAlgorithm(algorithm) {
selectedAlgorithm = algorithm;
const algorithmInfo = ALGORITHMS[algorithm];
document.querySelectorAll(".algo-button").forEach((button) => {
button.classList.toggle("active", button.dataset.algorithm === algorithm);
});
stabilityPill.textContent = algorithmInfo.stable ? "Stable" : "Not stable";
stabilityPill.classList.toggle("warning", !algorithmInfo.stable);
events = buildEvents(algorithm);
resetScene();
updateBookDetail();
}
// -------------------------------------------------------------------------
// Run state transitions.
// -------------------------------------------------------------------------
function resetScene() {
tweens.length = 0;
currentOrder = [...initialOrder];
eventIndex = 0;
runState = "idle";
paused = false;
dispatchManual = false;
dispatchCompletionCount = 0;
initialOrder.forEach((id, index) => {
const book = bookObjects.get(id);
book.group.position.set(SLOT_X[index], DECK_Y, INPUT_Z);
book.group.rotation.set(0, 0, 0);
});
scannerTargetX = 0;
scannerHead.material.color.setHex(0x183e4a);
scannerHead.material.emissive.setHex(0x5eead4);
scannerLight.color.setHex(0x5eead4);
updateStats(0, 0);
updatePlayButton();
renderTieAudit(false);
setStatus("10 synthetic records waiting at infeed.", "READY");
}
function startRun() {
if (runState === "done") {
resetScene();
}
runState = "feeding";
paused = false;
eventIndex = 0;
currentOrder = [...initialOrder];
updateStats(0, 0);
const duration = 950 / playbackSpeed;
animateOrder(currentOrder, WORK_Z, duration, 0.8);
feedReadyAt = simTime + duration + 120;
setStatus("Feeding catalog records into the sorting deck…", "FEED");
updatePlayButton();
}
function applyEvent(index, manual = false) {
const event = events[index];
currentOrder = [...event.order];
scannerTargetX = SLOT_X[event.focus];
const duration = 690 / playbackSpeed;
animateOrder(currentOrder, WORK_Z, duration, 0.48, manual);
eventIndex = index + 1;
eventReadyAt = simTime + duration + 110;
updateStats(event.comparisons, event.writes);
setStatus(event.message, `${eventIndex}/${events.length}`);
updateBookDetail();
}
function beginDispatch(manual = false) {
runState = "dispatching";
dispatchManual = manual;
dispatchCompletionCount = 0;
const duration = 980 / playbackSpeed;
const required = currentOrder.length;
animateOrder(
currentOrder,
OUTPUT_Z,
duration,
0.72,
manual,
() => {
dispatchCompletionCount += 1;
if (manual && dispatchCompletionCount === required) {
finishRun();
}
}
);
dispatchReadyAt = simTime + duration + 130;
scannerHead.material.emissive.setHex(0x86efac);
scannerLight.color.setHex(0x86efac);
setStatus("Sorted run dispatched to the output deck.", "OUTPUT");
updatePlayButton();
}
function finishRun() {
runState = "done";
paused = false;
renderTieAudit(true);
updateBookDetail();
updatePlayButton();
const stable = ALGORITHMS[selectedAlgorithm].stable;
setStatus(
stable
? "Sort complete — all equal-key groups preserved infeed order."
: "Sort complete — inspect the crossed equal-key group in the ledger.",
"DONE"
);
}
function stepOnce() {
paused = true;
if (runState === "idle" || runState === "done") {
resetScene();
runState = "sorting";
currentOrder = [...initialOrder];
initialOrder.forEach((id, index) => {
bookObjects.get(id).group.position.set(SLOT_X[index], DECK_Y, WORK_Z);
});
applyEvent(0, true);
} else if (runState === "feeding") {
currentOrder = [...initialOrder];
initialOrder.forEach((id, index) => {
bookObjects.get(id).group.position.set(SLOT_X[index], DECK_Y, WORK_Z);
});
runState = "sorting";
applyEvent(0, true);
} else if (runState === "sorting") {
if (eventIndex < events.length) {
applyEvent(eventIndex, true);
} else {
beginDispatch(true);
}
}
updatePlayButton();
}
playButton.addEventListener("click", () => {
if (runState === "idle" || runState === "done") {
startRun();
} else {
paused = !paused;
if (!paused) {
eventReadyAt = Math.max(eventReadyAt, simTime + 200);
}
updatePlayButton();
}
});
stepButton.addEventListener("click", stepOnce);
resetButton.addEventListener("click", resetScene);
speedInput.addEventListener("input", () => {
playbackSpeed = Number(speedInput.value);
speedValue.textContent = `${playbackSpeed.toFixed(2)}×`;
});
document.querySelectorAll(".algo-button").forEach((button) => {
button.addEventListener("click", () => {
selectAlgorithm(button.dataset.algorithm);
});
});
window.addEventListener("keydown", (event) => {
const tag = event.target?.tagName;
if (tag === "INPUT" || tag === "TEXTAREA" || tag === "BUTTON") {
return;
}
if (event.code === "Space") {
event.preventDefault();
playButton.click();
} else if (event.code === "ArrowRight") {
event.preventDefault();
stepOnce();
} else if (event.code === "KeyR") {
resetScene();
}
});
// -------------------------------------------------------------------------
// Custom camera interaction, implemented without OrbitControls.
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let pointerActive = false;
let pointerButton = 0;
let pointerMoved = 0;
let lastPointerX = 0;
let lastPointerY = 0;
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
pointerActive = true;
pointerButton = event.button;
pointerMoved = 0;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointerActive) {
return;
}
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
pointerMoved += Math.abs(dx) + Math.abs(dy);
const panMode = event.shiftKey || pointerButton === 2;
if (panMode) {
const right = new THREE.Vector3(
Math.cos(cameraYaw),
0,
-Math.sin(cameraYaw)
);
cameraTarget.addScaledVector(right, -dx * 0.012 * (cameraRadius / 18));
cameraTarget.y += dy * 0.009;
cameraTarget.x = THREE.MathUtils.clamp(cameraTarget.x, -5, 5);
cameraTarget.y = THREE.MathUtils.clamp(cameraTarget.y, 0.4, 3.2);
} else {
cameraYaw -= dx * 0.006;
cameraPitch = THREE.MathUtils.clamp(cameraPitch - dy * 0.005, 0.35, 1.38);
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
pointerActive = false;
renderer.domElement.releasePointerCapture(event.pointerId);
if (pointerMoved < 6 && pointerButton === 0) {
const bounds = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - bounds.left) / bounds.width) * 2 - 1;
pointer.y = -((event.clientY - bounds.top) / bounds.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(clickTargets, false);
if (intersections.length > 0) {
selectedBookId = intersections[0].object.userData.bookId;
selectionMarker.visible = true;
updateBookDetail();
}
}
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius + event.deltaY * 0.012,
11.5,
29
);
},
{ passive: false }
);
// -------------------------------------------------------------------------
// Main loop.
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (!paused) {
simTime += delta * 1000;
}
updateTweens(delta * 1000);
if (runState === "feeding" && simTime >= feedReadyAt) {
runState = "sorting";
eventIndex = 0;
applyEvent(0);
} else if (runState === "sorting" && simTime >= eventReadyAt) {
if (eventIndex < events.length) {
applyEvent(eventIndex);
} else {
beginDispatch();
}
} else if (runState === "dispatching" && !dispatchManual && simTime >= dispatchReadyAt) {
finishRun();
}
renderAnimation(simTime / 1000, delta);
}
function renderAnimation(simTime, delta) {
// Idle scanning motion.
if (runState === "idle") {
scannerTargetX = Math.sin(simTime * 0.65) * 5.2;
}
scanner.position.x +=
(scannerTargetX - scanner.position.x) * Math.min(1, delta * 8);
scannerBeam.material.opacity =
runState === "sorting" ? 0.13 + Math.sin(simTime * 8) * 0.045 : 0.07;
scannerHead.position.y = Math.sin(simTime * 4.2) * 0.055;
packets.forEach((packet, index) => {
const travel = (index * 0.83 + simTime * 1.35) % 13.2;
packet.position.x = -6.6 + travel;
packet.position.y = 0.96 + Math.sin(simTime * 3 + index) * 0.035;
});
if (selectedBookId) {
const selectedBook = bookObjects.get(selectedBookId);
selectionMarker.position.copy(selectedBook.group.position);
selectionMarker.position.y += 0.72;
selectionMarker.rotation.y =
Math.sin(clock.elapsedTime * 2.2) * 0.035;
}
updateCamera();
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
events = buildEvents(selectedAlgorithm);
resetScene();
animate();
</script>
</body>
</html>
```