Prompt specification
Build or customize the Three.js 3D scene "Chaining and probing collision 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: Chaining and probing collision comparison
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/chaining-and-probing-collision-comparison-x1890
Scene Description Prompt:
Insert identical keys into two stylized hash tables and compare chaining with probing through visible lookup steps. Use Three.js from cdnjs in one HTML.
Working Three.js Starter (chaining-and-probing-collision-comparison-x1890):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Hash Table Lab — Chaining vs. Probing</title>
<style>
:root {
--bg: #07111f;
--panel: rgba(10, 23, 41, 0.82);
--panel-border: rgba(166, 205, 239, 0.16);
--text: #edf7ff;
--muted: #91a9bd;
--chain: #57e5d0;
--probe: #ffb45f;
--found: #fff09a;
--shadow: 0 18px 55px rgba(0, 0, 0, 0.32);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
select {
font: inherit;
}
button {
color: var(--text);
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
}
.topbar {
position: fixed;
z-index: 10;
top: 22px;
left: 26px;
right: 26px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 24px;
pointer-events: none;
}
.brand {
width: min(440px, 42vw);
pointer-events: auto;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 8px;
color: #a9c0d3;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
width: 24px;
height: 2px;
content: "";
border-radius: 2px;
background: linear-gradient(90deg, var(--chain), var(--probe));
}
h1 {
margin: 0;
font-size: clamp(26px, 3vw, 43px);
font-weight: 780;
line-height: 1.03;
letter-spacing: -0.045em;
}
.subtitle {
max-width: 430px;
margin: 10px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.controls {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 8px;
flex-wrap: wrap;
max-width: 720px;
pointer-events: auto;
}
.control-panel {
display: flex;
align-items: center;
gap: 8px;
padding: 9px;
border: 1px solid var(--panel-border);
border-radius: 15px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(18px);
}
.control-label {
padding: 0 4px 0 7px;
color: var(--muted);
font-size: 11px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
select {
min-width: 84px;
padding: 9px 30px 9px 11px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 9px;
outline: none;
background: #102238;
color: var(--text);
font-weight: 750;
}
.btn {
min-height: 38px;
padding: 0 13px;
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 9px;
background: rgba(255, 255, 255, 0.065);
cursor: pointer;
font-size: 12px;
font-weight: 750;
transition:
transform 120ms ease,
border-color 120ms ease,
background 120ms ease;
}
.btn:hover {
transform: translateY(-1px);
border-color: rgba(255, 255, 255, 0.28);
background: rgba(255, 255, 255, 0.11);
}
.btn:active {
transform: translateY(0);
}
.btn.primary {
border-color: rgba(87, 229, 208, 0.35);
background: rgba(87, 229, 208, 0.14);
color: #b8fff5;
}
.btn.playing {
border-color: rgba(255, 180, 95, 0.45);
background: rgba(255, 180, 95, 0.14);
color: #ffd29c;
}
.key-strip {
display: flex;
align-items: center;
gap: 7px;
flex-wrap: wrap;
margin-top: 15px;
pointer-events: auto;
}
.key-strip-label {
margin-right: 3px;
color: #7890a5;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.key-chip {
display: grid;
width: 32px;
height: 30px;
place-items: center;
padding: 0;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 8px;
background: rgba(11, 27, 46, 0.8);
color: #c9d9e6;
cursor: pointer;
font-size: 12px;
font-weight: 800;
transition: 140ms ease;
}
.key-chip:hover {
border-color: var(--chain);
color: white;
transform: translateY(-2px);
}
.key-chip.selected {
border-color: var(--found);
background: rgba(255, 240, 154, 0.14);
color: var(--found);
box-shadow: 0 0 20px rgba(255, 240, 154, 0.12);
}
.method-card {
position: fixed;
z-index: 10;
bottom: 24px;
width: min(470px, calc(50vw - 42px));
padding: 16px 17px 15px;
overflow: hidden;
border: 1px solid var(--panel-border);
border-radius: 17px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(20px);
pointer-events: none;
}
.method-card::before {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 2px;
content: "";
background: var(--accent);
box-shadow: 0 0 18px var(--accent);
}
#chain-card {
--accent: var(--chain);
left: 24px;
}
#probe-card {
--accent: var(--probe);
right: 24px;
}
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.card-title {
display: flex;
align-items: center;
gap: 9px;
font-size: 14px;
font-weight: 800;
letter-spacing: 0.02em;
}
.dot {
width: 8px;
height: 8px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 12px var(--accent);
}
.step-counter {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metrics {
display: flex;
gap: 7px;
margin: 12px 0 10px;
}
.metric {
flex: 1;
padding: 8px 10px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 9px;
background: rgba(255, 255, 255, 0.035);
}
.metric span {
display: block;
margin-bottom: 2px;
color: #7890a5;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric strong {
font-size: 16px;
font-variant-numeric: tabular-nums;
}
.status {
min-height: 34px;
margin: 0;
color: #c7d8e5;
font-size: 12px;
line-height: 1.45;
}
.status.found {
color: var(--found);
}
.pills {
display: flex;
min-height: 26px;
align-items: center;
gap: 6px;
flex-wrap: wrap;
margin-top: 10px;
}
.pill {
padding: 4px 7px;
border: 1px solid color-mix(in srgb, var(--accent) 35%, transparent);
border-radius: 6px;
background: color-mix(in srgb, var(--accent) 9%, transparent);
color: color-mix(in srgb, var(--accent) 82%, white);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
font-weight: 700;
}
.pill.current {
border-color: var(--found);
background: rgba(255, 240, 154, 0.1);
color: var(--found);
}
.hint {
position: fixed;
z-index: 8;
left: 50%;
bottom: 25px;
transform: translateX(-50%);
padding: 7px 12px;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 999px;
background: rgba(8, 19, 33, 0.72);
color: #7890a5;
font-size: 10px;
font-weight: 650;
letter-spacing: 0.04em;
pointer-events: none;
backdrop-filter: blur(12px);
}
#tooltip {
position: fixed;
z-index: 30;
display: none;
padding: 7px 10px;
border: 1px solid rgba(255, 255, 255, 0.17);
border-radius: 8px;
background: rgba(7, 17, 31, 0.93);
color: white;
font-size: 11px;
font-weight: 750;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.32);
pointer-events: none;
transform: translate(12px, 12px);
}
@media (max-width: 900px) {
.topbar {
top: 15px;
left: 15px;
right: 15px;
flex-direction: column;
gap: 13px;
}
.brand {
width: 100%;
}
h1 {
font-size: 29px;
}
.subtitle {
display: none;
}
.controls {
justify-content: flex-start;
max-width: 100%;
}
.control-panel {
padding: 7px;
}
.btn,
select {
min-height: 34px;
}
.key-strip {
margin-top: 10px;
}
.method-card {
bottom: 14px;
width: calc(50vw - 20px);
padding: 13px;
}
#chain-card {
left: 12px;
}
#probe-card {
right: 12px;
}
.hint {
display: none;
}
}
@media (max-width: 580px) {
.eyebrow {
margin-bottom: 5px;
}
h1 {
font-size: 25px;
}
.control-label {
display: none;
}
.btn {
padding: 0 10px;
font-size: 11px;
}
.key-chip {
width: 28px;
height: 27px;
}
.method-card {
width: calc(50vw - 15px);
padding: 11px;
border-radius: 13px;
}
.card-title {
font-size: 11px;
}
.step-counter {
font-size: 8px;
}
.metrics {
margin: 8px 0;
}
.metric {
padding: 6px 7px;
}
.metric strong {
font-size: 13px;
}
.status {
min-height: 42px;
font-size: 10px;
}
.pills {
margin-top: 6px;
}
}
</style>
</head>
<body>
<div id="scene" aria-label="Interactive 3D hash table comparison"></div>
<header class="topbar">
<div class="brand">
<div class="eyebrow">Hash table lab</div>
<h1>Same keys.<br />Different search paths.</h1>
<p class="subtitle">
Seven identical keys are inserted into two hash tables. Compare how
separate chaining and linear probing locate the same value.
</p>
<div class="key-strip" id="key-strip" aria-label="Choose a key to look up">
<span class="key-strip-label">Keys</span>
</div>
</div>
<div class="controls">
<div class="control-panel">
<label class="control-label" for="key-select">Look up</label>
<select id="key-select" aria-label="Key to look up"></select>
<button class="btn primary" id="lookup-button">Compare lookup</button>
<button class="btn" id="step-button">Next step</button>
<button class="btn" id="play-button">Auto play</button>
<button class="btn" id="insert-button">Replay inserts</button>
</div>
</div>
</header>
<section class="method-card" id="chain-card">
<div class="card-header">
<div class="card-title"><span class="dot"></span>Separate chaining</div>
<div class="step-counter" id="chain-counter">Ready</div>
</div>
<div class="metrics">
<div class="metric">
<span>Buckets checked</span>
<strong id="chain-buckets">—</strong>
</div>
<div class="metric">
<span>Key comparisons</span>
<strong id="chain-comparisons">—</strong>
</div>
</div>
<p class="status" id="chain-status">Waiting for insertion…</p>
<div class="pills" id="chain-pills"></div>
</section>
<section class="method-card" id="probe-card">
<div class="card-header">
<div class="card-title"><span class="dot"></span>Linear probing</div>
<div class="step-counter" id="probe-counter">Ready</div>
</div>
<div class="metrics">
<div class="metric">
<span>Buckets checked</span>
<strong id="probe-buckets">—</strong>
</div>
<div class="metric">
<span>Key comparisons</span>
<strong id="probe-comparisons">—</strong>
</div>
</div>
<p class="status" id="probe-status">Waiting for insertion…</p>
<div class="pills" id="probe-pills"></div>
</section>
<div class="hint">Click a key in the scene or use Next step · Space advances the trace</div>
<div id="tooltip"></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Configuration
// -------------------------------------------------------------------------
const TABLE_SIZE = 11;
const KEYS = [14, 25, 3, 10, 6, 17, 28];
const INITIAL_KEY = 25;
const INSERT_INTERVAL = 430;
const REVEAL_DURATION = 380;
const COLORS = {
chain: 0x57e5d0,
probe: 0xffb45f,
found: 0xfff09a,
background: 0x07111f
};
const sceneHost = document.querySelector("#scene");
const tooltip = document.querySelector("#tooltip");
const keySelect = document.querySelector("#key-select");
const keyStrip = document.querySelector("#key-strip");
const ui = {
lookup: document.querySelector("#lookup-button"),
step: document.querySelector("#step-button"),
play: document.querySelector("#play-button"),
insert: document.querySelector("#insert-button"),
chainCounter: document.querySelector("#chain-counter"),
chainBuckets: document.querySelector("#chain-buckets"),
chainComparisons: document.querySelector("#chain-comparisons"),
chainStatus: document.querySelector("#chain-status"),
chainPills: document.querySelector("#chain-pills"),
probeCounter: document.querySelector("#probe-counter"),
probeBuckets: document.querySelector("#probe-buckets"),
probeComparisons: document.querySelector("#probe-comparisons"),
probeStatus: document.querySelector("#probe-status"),
probePills: document.querySelector("#probe-pills")
};
// -------------------------------------------------------------------------
// Renderer, camera, and lighting
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
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;
sceneHost.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(COLORS.background);
scene.fog = new THREE.FogExp2(COLORS.background, 0.015);
const camera = new THREE.OrthographicCamera(-32, 32, 20, -20, 0.1, 180);
camera.position.set(0, 26, 34);
camera.lookAt(0, 2, 0);
scene.add(new THREE.HemisphereLight(0xb8dcff, 0x07101c, 1.65));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.7);
keyLight.position.set(-8, 24, 18);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -45;
keyLight.shadow.camera.right = 45;
keyLight.shadow.camera.top = 30;
keyLight.shadow.camera.bottom = -30;
keyLight.shadow.bias = -0.0003;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(COLORS.chain, 30, 30, 2);
cyanLight.position.set(-17, 8, 8);
scene.add(cyanLight);
const amberLight = new THREE.PointLight(COLORS.probe, 30, 30, 2);
amberLight.position.set(17, 8, 8);
scene.add(amberLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(140, 140),
new THREE.MeshStandardMaterial({
color: 0x091525,
roughness: 0.92,
metalness: 0.05
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.25;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(120, 60, 0x1b3850, 0x10263a);
grid.position.y = -0.235;
grid.material.transparent = true;
grid.material.opacity = 0.38;
scene.add(grid);
// -------------------------------------------------------------------------
// Utility functions
// -------------------------------------------------------------------------
function hashKey(key) {
return key % TABLE_SIZE;
}
function makeTextSprite(text, options = {}) {
const {
color = "#ffffff",
width = 4,
height = 1,
fontSize = 58,
background = null,
border = null
} = options;
const canvas = document.createElement("canvas");
canvas.width = 768;
canvas.height = 160;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (background) {
ctx.fillStyle = background;
ctx.beginPath();
ctx.roundRect(4, 4, 760, 152, 30);
ctx.fill();
}
if (border) {
ctx.strokeStyle = border;
ctx.lineWidth = 4;
ctx.beginPath();
ctx.roundRect(4, 4, 760, 152, 30);
ctx.stroke();
}
ctx.fillStyle = color;
ctx.font = `800 ${fontSize}px ui-sans-serif, system-ui, sans-serif`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 384, 84);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false,
depthTest: options.depthTest ?? true
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(width, height, 1);
sprite.userData.texture = texture;
return sprite;
}
function disposeObject(object) {
object.traverse(child => {
if (child.geometry) child.geometry.dispose();
if (child.material) {
const materials = Array.isArray(child.material)
? child.material
: [child.material];
for (const material of materials) {
if (material.map) material.map.dispose();
material.dispose();
}
}
});
}
function easeOutBack(value) {
const c1 = 1.70158;
const c3 = c1 + 1;
const x = value - 1;
return 1 + c3 * x * x * x + c1 * x * x;
}
function clamp01(value) {
return Math.max(0, Math.min(1, value));
}
function bucketX(index) {
return (index - (TABLE_SIZE - 1) / 2) * 2.55;
}
// -------------------------------------------------------------------------
// Insertion plan
// -------------------------------------------------------------------------
function createInsertionPlan() {
const chainBuckets = Array.from({ length: TABLE_SIZE }, () => []);
const probeBuckets = Array.from({ length: TABLE_SIZE }, () => null);
KEYS.forEach((key, order) => {
const home = hashKey(key);
chainBuckets[home].push({ key, order, home });
let slot = home;
let attempts = 0;
while (probeBuckets[slot] !== null && attempts < TABLE_SIZE) {
slot = (slot + 1) % TABLE_SIZE;
attempts++;
}
probeBuckets[slot] = { key, order, home, slot };
});
return { chainBuckets, probeBuckets };
}
// -------------------------------------------------------------------------
// Table construction
// -------------------------------------------------------------------------
const pickables = [];
let tables = null;
let inserting = false;
let insertionStart = 0;
let lookup = null;
let selectedKey = INITIAL_KEY;
let lastAutoAdvance = 0;
function createBucket(group, index, accent) {
const x = bucketX(index);
const base = new THREE.Mesh(
new THREE.BoxGeometry(2.22, 0.34, 2.0),
new THREE.MeshStandardMaterial({
color: index % 2 === 0 ? 0x142b40 : 0x102438,
roughness: 0.58,
metalness: 0.26
})
);
base.position.set(x, 0.32, 0);
base.castShadow = true;
base.receiveShadow = true;
group.add(base);
const inset = new THREE.Mesh(
new THREE.BoxGeometry(1.76, 0.055, 1.48),
new THREE.MeshStandardMaterial({
color: 0x071523,
roughness: 0.8,
metalness: 0.08
})
);
inset.position.set(x, 0.515, 0);
inset.receiveShadow = true;
group.add(inset);
const front = new THREE.Mesh(
new THREE.BoxGeometry(2.22, 0.12, 0.11),
new THREE.MeshStandardMaterial({
color: accent,
emissive: accent,
emissiveIntensity: 0.08,
roughness: 0.45,
metalness: 0.25
})
);
front.position.set(x, 0.29, 1.01);
group.add(front);
const number = makeTextSprite(String(index), {
color: "#819bb0",
width: 0.72,
height: 0.42,
fontSize: 68,
depthTest: false
});
number.position.set(x, 0.64, 1.25);
group.add(number);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.78, 0.055, 8, 32),
new THREE.MeshBasicMaterial({
color: accent,
transparent: true,
opacity: 0.9,
depthWrite: false
})
);
ring.rotation.x = Math.PI / 2;
ring.position.set(x, 0.57, 0);
ring.visible = false;
group.add(ring);
return { base, inset, number, ring, index };
}
function createKeyNode(group, entry, position, accent, type) {
const nodeGroup = new THREE.Group();
nodeGroup.position.copy(position);
nodeGroup.scale.setScalar(0.001);
nodeGroup.visible = false;
const baseColor = new THREE.Color(accent).lerp(
new THREE.Color(0xffffff),
0.05 + (entry.order % 3) * 0.035
);
const material = new THREE.MeshStandardMaterial({
color: baseColor,
emissive: accent,
emissiveIntensity: 0.13,
roughness: 0.28,
metalness: 0.22,
transparent: true,
opacity: 1
});
const tile = new THREE.Mesh(
new THREE.BoxGeometry(1.58, 0.64, 0.86),
material
);
tile.castShadow = true;
tile.receiveShadow = true;
tile.userData.key = entry.key;
tile.userData.type = type;
nodeGroup.add(tile);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(tile.geometry),
new THREE.LineBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.28
})
);
nodeGroup.add(edges);
const label = makeTextSprite(String(entry.key), {
color: "#071725",
width: 1.15,
height: 0.52,
fontSize: 72,
depthTest: false
});
label.position.set(0, 0, 0.48);
nodeGroup.add(label);
const notch = new THREE.Mesh(
new THREE.CylinderGeometry(0.12, 0.12, 0.1, 16),
new THREE.MeshStandardMaterial({
color: 0xf4fbff,
emissive: 0xbdefff,
emissiveIntensity: 0.35,
roughness: 0.25
})
);
notch.position.set(0, 0.39, 0);
nodeGroup.add(notch);
group.add(nodeGroup);
pickables.push(tile);
return {
key: entry.key,
order: entry.order,
group: nodeGroup,
tile,
material,
label,
baseColor,
revealAt: entry.order * INSERT_INTERVAL
};
}
function createTable(type, plan) {
const isChain = type === "chain";
const accent = isChain ? COLORS.chain : COLORS.probe;
const group = new THREE.Group();
const platform = new THREE.Mesh(
new THREE.BoxGeometry(29.2, 0.22, 4.15),
new THREE.MeshStandardMaterial({
color: 0x0c1b2b,
roughness: 0.72,
metalness: 0.18
})
);
platform.position.y = 0;
platform.receiveShadow = true;
group.add(platform);
const platformEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(platform.geometry),
new THREE.LineBasicMaterial({
color: accent,
transparent: true,
opacity: 0.22
})
);
group.add(platformEdges);
const pool = new THREE.Mesh(
new THREE.CircleGeometry(14.6, 64),
new THREE.MeshBasicMaterial({
color: accent,
transparent: true,
opacity: 0.025,
depthWrite: false
})
);
pool.rotation.x = -Math.PI / 2;
pool.scale.y = 0.31;
pool.position.y = -0.18;
group.add(pool);
const buckets = [];
for (let i = 0; i < TABLE_SIZE; i++) {
buckets.push(createBucket(group, i, accent));
}
const title = makeTextSprite(
isChain ? "SEPARATE CHAINING" : "LINEAR PROBING",
{
color: "#f1fbff",
width: 8.8,
height: 1.35,
fontSize: 48,
background: "rgba(9, 22, 37, 0.84)",
border: isChain
? "rgba(87, 229, 208, 0.45)"
: "rgba(255, 180, 95, 0.45)",
depthTest: false
}
);
title.position.set(0, 6.25, 0);
group.add(title);
const subtitle = makeTextSprite(
isChain ? "ONE LIST PER BUCKET" : "ONE KEY PER SLOT",
{
color: isChain ? "#83e9dc" : "#e6b77d",
width: 5.8,
height: 0.75,
fontSize: 44,
depthTest: false
}
);
subtitle.position.set(0, 5.25, 0);
group.add(subtitle);
const nodes = [];
const links = [];
if (isChain) {
plan.chainBuckets.forEach((entries, bucketIndex) => {
let previousY = 0.63;
entries.forEach((entry, chainIndex) => {
const nodeY = 1.26 + chainIndex * 1.15;
const node = createKeyNode(
group,
entry,
new THREE.Vector3(bucketX(bucketIndex), nodeY, -0.25),
accent,
type
);
node.bucket = bucketIndex;
node.chainIndex = chainIndex;
nodes.push(node);
const length = nodeY - previousY;
const linkMaterial = new THREE.MeshStandardMaterial({
color: accent,
emissive: accent,
emissiveIntensity: 0.32,
roughness: 0.25,
metalness: 0.15,
transparent: true,
opacity: 0.55
});
const link = new THREE.Mesh(
new THREE.CylinderGeometry(0.048, 0.048, length, 8),
linkMaterial
);
link.position.set(
bucketX(bucketIndex),
previousY + length / 2,
-0.25
);
link.visible = false;
group.add(link);
links.push({
mesh: link,
material: linkMaterial,
bucket: bucketIndex,
chainIndex,
order: entry.order
});
previousY = nodeY;
});
});
} else {
plan.probeBuckets.forEach((entry, slotIndex) => {
if (!entry) return;
const node = createKeyNode(
group,
entry,
new THREE.Vector3(bucketX(slotIndex), 1.22, 0),
accent,
type
);
node.bucket = slotIndex;
nodes.push(node);
});
}
const traceGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(0.01, 0, 0)
]);
const traceMaterial = new THREE.LineBasicMaterial({
color: accent,
transparent: true,
opacity: 0.78,
depthWrite: false
});
const traceLine = new THREE.Line(traceGeometry, traceMaterial);
traceLine.position.set(0, 0.61, 1.43);
traceLine.visible = false;
group.add(traceLine);
scene.add(group);
return {
type,
group,
accent,
buckets,
nodes,
links,
traceLine,
traceGeometry,
traceMaterial
};
}
function removeTables() {
pickables.length = 0;
if (!tables) return;
for (const table of Object.values(tables)) {
scene.remove(table.group);
disposeObject(table.group);
}
}
function buildTables() {
removeTables();
const plan = createInsertionPlan();
tables = {
chain: createTable("chain", plan),
probe: createTable("probe", plan)
};
positionTables();
}
// -------------------------------------------------------------------------
// Responsive scene layout
// -------------------------------------------------------------------------
function positionTables() {
if (!tables) return;
const mobile = window.innerWidth < 760;
if (mobile) {
tables.chain.group.position.set(0, 0, -8);
tables.probe.group.position.set(0, 0, 8);
} else {
tables.chain.group.position.set(-16.3, 0, 0);
tables.probe.group.position.set(16.3, 0, 0);
}
const aspect = window.innerWidth / window.innerHeight;
const desiredWidth = mobile ? 32 : 64;
const halfHeight = Math.max(mobile ? 29 : 13, desiredWidth / (2 * aspect));
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.updateProjectionMatrix();
}
function resize() {
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
positionTables();
}
window.addEventListener("resize", resize);
// -------------------------------------------------------------------------
// Insertion animation
// -------------------------------------------------------------------------
function replayInsertion() {
lookup = null;
ui.play.classList.remove("playing");
ui.play.textContent = "Auto play";
buildTables();
inserting = true;
insertionStart = performance.now();
ui.chainStatus.textContent = "Inserting keys…";
ui.probeStatus.textContent = "Inserting keys…";
ui.chainStatus.classList.remove("found");
ui.probeStatus.classList.remove("found");
ui.chainCounter.textContent = "Inserting";
ui.probeCounter.textContent = "Inserting";
ui.chainBuckets.textContent = "—";
ui.probeBuckets.textContent = "—";
ui.chainComparisons.textContent = "—";
ui.probeComparisons.textContent = "—";
ui.chainPills.innerHTML = "";
ui.probePills.innerHTML = "";
}
function completeInsertion() {
if (!tables) return;
inserting = false;
for (const table of Object.values(tables)) {
for (const node of table.nodes) {
node.group.visible = true;
node.group.scale.setScalar(1);
node.material.opacity = 1;
node.label.material.opacity = 1;
node.material.color.copy(node.baseColor);
node.material.emissive.set(table.accent);
node.material.emissiveIntensity = 0.13;
}
for (const link of table.links) {
link.mesh.visible = true;
link.material.opacity = 0.55;
link.material.emissiveIntensity = 0.32;
}
for (const bucket of table.buckets) {
bucket.ring.visible = false;
}
}
ui.chainCounter.textContent = "Ready";
ui.probeCounter.textContent = "Ready";
ui.chainStatus.textContent = "7 keys inserted. Choose a key to begin comparing lookups.";
ui.probeStatus.textContent = "7 keys inserted. Choose a key to begin comparing lookups.";
ui.chainBuckets.textContent = "0";
ui.probeBuckets.textContent = "0";
ui.chainComparisons.textContent = "0";
ui.probeComparisons.textContent = "0";
}
function updateInsertion(now) {
const elapsed = now - insertionStart;
const activeOrder = Math.min(
KEYS.length - 1,
Math.max(0, Math.floor(elapsed / INSERT_INTERVAL))
);
for (const table of Object.values(tables)) {
for (const node of table.nodes) {
const progress = clamp01(
(elapsed - node.revealAt) / REVEAL_DURATION
);
if (progress > 0) {
node.group.visible = true;
node.group.scale.setScalar(Math.max(0.001, easeOutBack(progress)));
node.material.opacity = Math.min(1, progress * 2);
node.label.material.opacity = Math.min(1, progress * 2);
}
}
for (const link of table.links) {
const progress = clamp01(
(elapsed - link.order * INSERT_INTERVAL) / 260
);
link.mesh.visible = progress > 0;
link.material.opacity = 0.55 * Math.min(1, progress * 2);
}
for (const bucket of table.buckets) {
bucket.ring.visible = false;
}
const activeEntry = KEYS[activeOrder];
const activeBucket =
table.type === "chain"
? hashKey(activeEntry)
: table.nodes.find(node => node.key === activeEntry)?.bucket;
if (activeBucket !== undefined) {
const ring = table.buckets[activeBucket].ring;
ring.visible = true;
ring.material.opacity = 0.5 + 0.4 * Math.sin(now * 0.008);
}
}
const activeKey = KEYS[activeOrder];
ui.chainStatus.textContent = `Inserting key ${activeKey} → bucket ${hashKey(activeKey)}`;
ui.probeStatus.textContent = `Inserting key ${activeKey} → probing from bucket ${hashKey(activeKey)}`;
if (elapsed >= KEYS.length * INSERT_INTERVAL + REVEAL_DURATION + 100) {
completeInsertion();
}
}
// -------------------------------------------------------------------------
// Lookup traces
// -------------------------------------------------------------------------
function buildChainSteps(key) {
const home = hashKey(key);
const candidates = tables.chain.nodes
.filter(node => node.bucket === home)
.sort((a, b) => a.chainIndex - b.chainIndex);
const steps = [
{
bucket: home,
key: null,
kind: "hash",
text: `Hash ${key} % ${TABLE_SIZE} = ${home}. Enter bucket ${home}.`
}
];
for (const candidate of candidates) {
const found = candidate.key === key;
steps.push({
bucket: home,
key: candidate.key,
kind: "compare",
found,
text: found
? `Compare ${key} with ${candidate.key}: match found.`
: `Compare ${key} with ${candidate.key}: no match, follow the chain.`
});
if (found) break;
}
return steps;
}
function buildProbeSteps(key) {
const home = hashKey(key);
const steps = [
{
bucket: home,
key: null,
kind: "hash",
text: `Hash ${key} % ${TABLE_SIZE} = ${home}. Start probing at bucket ${home}.`
}
];
let slot = home;
let attempts = 0;
while (attempts < TABLE_SIZE) {
const node = tables.probe.nodes.find(item => item.bucket === slot);
if (!node) {
steps.push({
bucket: slot,
key: null,
kind: "empty",
found: false,
text: `Bucket ${slot} is empty: the key was not found.`
});
break;
}
const found = node.key === key;
steps.push({
bucket: slot,
key: node.key,
kind: "compare",
found,
text: found
? `Bucket ${slot} contains ${node.key}: match found.`
: `Bucket ${slot} contains ${node.key}: collision, probe the next slot.`
});
if (found) break;
slot = (slot + 1) % TABLE_SIZE;
attempts++;
}
return steps;
}
function setSelectedKey(key) {
selectedKey = Number(key);
keySelect.value = String(selectedKey);
document.querySelectorAll(".key-chip").forEach(chip => {
chip.classList.toggle(
"selected",
Number(chip.dataset.key) === selectedKey
);
});
}
function startLookup(key = selectedKey) {
if (inserting) completeInsertion();
setSelectedKey(key);
lookup = {
key: selectedKey,
chainSteps: buildChainSteps(selectedKey),
probeSteps: buildProbeSteps(selectedKey),
chainIndex: 0,
probeIndex: 0,
playing: false
};
ui.play.classList.remove("playing");
ui.play.textContent = "Auto play";
applyLookupHighlights();
updateCards();
}
function advanceLookup() {
if (!lookup) {
startLookup();
return;
}
lookup.playing = false;
ui.play.classList.remove("playing");
ui.play.textContent = "Auto play";
if (lookup.chainIndex < lookup.chainSteps.length - 1) {
lookup.chainIndex++;
}
if (lookup.probeIndex < lookup.probeSteps.length - 1) {
lookup.probeIndex++;
}
applyLookupHighlights();
updateCards();
}
function toggleAutoPlay() {
if (!lookup) {
startLookup();
lookup.playing = true;
} else {
const chainDone = lookup.chainIndex >= lookup.chainSteps.length - 1;
const probeDone = lookup.probeIndex >= lookup.probeSteps.length - 1;
if (chainDone && probeDone) {
lookup.chainIndex = 0;
lookup.probeIndex = 0;
lookup.playing = true;
} else {
lookup.playing = !lookup.playing;
}
}
lastAutoAdvance = performance.now();
ui.play.classList.toggle("playing", lookup.playing);
ui.play.textContent = lookup.playing ? "Pause" : "Auto play";
applyLookupHighlights();
updateCards();
}
// -------------------------------------------------------------------------
// Lookup highlighting
// -------------------------------------------------------------------------
function applyLookupHighlights() {
if (!tables || !lookup) return;
for (const table of Object.values(tables)) {
for (const node of table.nodes) {
node.group.scale.setScalar(1);
node.material.color.copy(node.baseColor);
node.material.emissive.set(table.accent);
node.material.emissiveIntensity = 0.13;
}
for (const link of table.links) {
link.material.opacity = 0.48;
link.material.emissiveIntensity = 0.28;
}
for (const bucket of table.buckets) {
bucket.ring.visible = false;
bucket.ring.material.opacity = 0.25;
}
table.traceLine.visible = false;
}
const chainTable = tables.chain;
const probeTable = tables.probe;
const chainSteps = lookup.chainSteps.slice(0, lookup.chainIndex + 1);
const probeSteps = lookup.probeSteps.slice(0, lookup.probeIndex + 1);
const chainCurrent = chainSteps[chainSteps.length - 1];
const probeCurrent = probeSteps[probeSteps.length - 1];
const chainVisitedBuckets = new Set(chainSteps.map(step => step.bucket));
const probeVisitedBuckets = new Set(probeSteps.map(step => step.bucket));
for (const bucketIndex of chainVisitedBuckets) {
const bucket = chainTable.buckets[bucketIndex];
bucket.ring.visible = true;
bucket.ring.material.opacity =
bucketIndex === chainCurrent.bucket ? 0.95 : 0.22;
}
for (const bucketIndex of probeVisitedBuckets) {
const bucket = probeTable.buckets[bucketIndex];
bucket.ring.visible = true;
bucket.ring.material.opacity =
bucketIndex === probeCurrent.bucket ? 0.95 : 0.22;
}
for (const step of chainSteps) {
if (step.kind !== "compare") continue;
const node = chainTable.nodes.find(item => item.key === step.key);
if (!node) continue;
node.material.emissiveIntensity = step.found ? 1.45 : 0.68;
if (step.found) {
node.material.color.lerp(new THREE.Color(COLORS.found), 0.72);
}
}
for (const step of probeSteps) {
if (step.kind !== "compare") continue;
const node = probeTable.nodes.find(item => item.key === step.key);
if (!node) continue;
node.material.emissiveIntensity = step.found ? 1.45 : 0.68;
if (step.found) {
node.material.color.lerp(new THREE.Color(COLORS.found), 0.72);
}
}
const chainComparisons = chainSteps.filter(step => step.kind === "compare");
for (const link of chainTable.links) {
const traversed = chainComparisons.some(
step =>
step.bucket === link.bucket &&
chainTable.nodes.find(node => node.key === step.key)?.chainIndex >=
link.chainIndex
);
if (traversed) {
link.material.opacity = 0.95;
link.material.emissiveIntensity = 0.85;
}
}
const probePoints = probeSteps
.filter(step => step.kind === "compare")
.map(step => new THREE.Vector3(bucketX(step.bucket), 0, 0));
if (probePoints.length > 1) {
probeTable.traceGeometry.setFromPoints(probePoints);
probeTable.traceGeometry.attributes.position.needsUpdate = true;
probeTable.traceLine.visible = true;
}
}
// -------------------------------------------------------------------------
// Cards and status updates
// -------------------------------------------------------------------------
function sideState(side) {
if (!lookup) return null;
const steps =
side === "chain" ? lookup.chainSteps : lookup.probeSteps;
const index =
side === "chain" ? lookup.chainIndex : lookup.probeIndex;
return {
steps,
index,
current: steps[index],
comparisons: steps
.slice(0, index + 1)
.filter(step => step.kind === "compare")
};
}
function updateCards() {
if (inserting) return;
for (const side of ["chain", "probe"]) {
const state = sideState(side);
const prefix = side;
if (!state) {
ui[`${prefix}Counter`].textContent = "Ready";
ui[`${prefix}Buckets`].textContent = "0";
ui[`${prefix}Comparisons`].textContent = "0";
ui[`${prefix}Status`].textContent =
"Choose a key to trace both lookup strategies.";
ui[`${prefix}Status`].classList.remove("found");
ui[`${prefix}Pills`].innerHTML = "";
continue;
}
const finished = state.index === state.steps.length - 1;
const found = state.current.found;
const bucketChecks =
side === "chain"
? state.comparisons.length > 0 || state.current.kind === "hash"
? 1
: 0
: state.comparisons.length;
ui[`${prefix}Counter`].textContent = `Step ${state.index + 1} / ${state.steps.length}`;
ui[`${prefix}Buckets`].textContent = String(bucketChecks);
ui[`${prefix}Comparisons`].textContent = String(state.comparisons.length);
ui[`${prefix}Status`].textContent = state.current.text;
ui[`${prefix}Status`].classList.toggle("found", Boolean(found));
if (finished && found) {
ui[`${prefix}Status`].textContent =
`Found ${lookup.key} after ${state.comparisons.length} key ` +
`comparison${state.comparisons.length === 1 ? "" : "s"} ` +
`and ${bucketChecks} bucket check${bucketChecks === 1 ? "" : "s"}.`;
ui[`${prefix}Status`].classList.add("found");
}
const pills = state.steps.map((step, index) => {
let text;
if (step.kind === "hash") {
text = `h = ${step.bucket}`;
} else if (step.kind === "empty") {
text = `bucket ${step.bucket} empty`;
} else if (step.found) {
text = `${step.key} = ${lookup.key}`;
} else {
text = `${step.key} ≠ ${lookup.key}`;
}
const currentClass = index === state.index ? " current" : "";
return `<span class="pill${currentClass}">${text}</span>`;
});
ui[`${prefix}Pills`].innerHTML = pills.join("");
}
}
// -------------------------------------------------------------------------
// Key selection and controls
// -------------------------------------------------------------------------
for (const key of KEYS) {
const option = document.createElement("option");
option.value = String(key);
option.textContent = String(key);
keySelect.appendChild(option);
const chip = document.createElement("button");
chip.className = "key-chip";
chip.dataset.key = String(key);
chip.textContent = String(key);
chip.title = `Look up key ${key}`;
chip.addEventListener("click", () => startLookup(key));
keyStrip.appendChild(chip);
}
keySelect.value = String(INITIAL_KEY);
setSelectedKey(INITIAL_KEY);
keySelect.addEventListener("change", () => {
setSelectedKey(keySelect.value);
});
ui.lookup.addEventListener("click", () => startLookup());
ui.step.addEventListener("click", advanceLookup);
ui.play.addEventListener("click", toggleAutoPlay);
ui.insert.addEventListener("click", replayInsertion);
window.addEventListener("keydown", event => {
if (event.code === "Space" && event.target === document.body) {
event.preventDefault();
advanceLookup();
}
});
// -------------------------------------------------------------------------
// Raycasting: select keys directly in the 3D scene
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function updatePointer(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function pickKey(event) {
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(pickables, false);
return hits.length ? hits[0].object.userData : null;
}
renderer.domElement.addEventListener("pointermove", event => {
const hit = pickKey(event);
if (hit) {
tooltip.style.display = "block";
tooltip.style.left = `${event.clientX}px`;
tooltip.style.top = `${event.clientY}px`;
tooltip.textContent = `Key ${hit.key} · hash ${hashKey(hit.key)}`;
renderer.domElement.style.cursor = "pointer";
} else {
tooltip.style.display = "none";
renderer.domElement.style.cursor = "default";
}
});
renderer.domElement.addEventListener("pointerleave", () => {
tooltip.style.display = "none";
});
renderer.domElement.addEventListener("pointerdown", event => {
const hit = pickKey(event);
if (hit) startLookup(hit.key);
});
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
function animate(now) {
if (inserting) {
updateInsertion(now);
}
if (lookup?.playing && now - lastAutoAdvance > 850) {
const chainDone =
lookup.chainIndex >= lookup.chainSteps.length - 1;
const probeDone =
lookup.probeIndex >= lookup.probeSteps.length - 1;
if (chainDone && probeDone) {
lookup.playing = false;
ui.play.classList.remove("playing");
ui.play.textContent = "Auto play";
} else {
if (!chainDone) lookup.chainIndex++;
if (!probeDone) lookup.probeIndex++;
applyLookupHighlights();
updateCards();
}
lastAutoAdvance = now;
}
if (lookup && tables) {
const pulse = 0.72 + Math.sin(now * 0.009) * 0.24;
for (const side of ["chain", "probe"]) {
const table = tables[side];
const state = sideState(side);
if (!state) continue;
const currentBucket = state.current.bucket;
const ring = table.buckets[currentBucket]?.ring;
if (ring?.visible) {
ring.material.opacity = pulse;
}
}
}
renderer.render(scene, camera);
}
// -------------------------------------------------------------------------
// Start
// -------------------------------------------------------------------------
replayInsertion();
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```