Prompt specification
Build or customize the Three.js 3D scene "Hash bucket key-placement rack" 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: Hash bucket key-placement rack
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/hash-bucket-key-placement-rack-x1889
Scene Description Prompt:
Build a small bucket array and labeled keys mapped by an explicitly displayed hash rule; show that collisions can occur without keys being equal. Build this with Three.js from cdnjs as a low-poly scene in one self-contained HTML file.
Working Three.js Starter (hash-bucket-key-placement-rack-x1889):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Hash Buckets — Collision Demo</title>
<style>
:root {
--bg: #07111d;
--panel: rgba(9, 24, 39, 0.86);
--panel-border: rgba(113, 218, 220, 0.2);
--text: #edf8ff;
--muted: #91aabd;
--cyan: #65e6dd;
--orange: #ff9d76;
--purple: #c4a7ff;
}
* {
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,
input {
font: inherit;
}
button {
color: inherit;
}
#stage {
position: fixed;
inset: 0;
}
#stage canvas {
display: block;
touch-action: none;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 50% 45%, transparent 38%, rgba(1, 7, 13, 0.43) 100%),
linear-gradient(180deg, rgba(3, 10, 17, 0.14), rgba(3, 10, 17, 0.35));
}
.panel {
position: fixed;
z-index: 10;
border: 1px solid var(--panel-border);
border-radius: 18px;
background: var(--panel);
box-shadow:
0 18px 50px rgba(0, 0, 0, 0.35),
inset 0 1px 0 rgba(255, 255, 255, 0.04);
backdrop-filter: blur(16px);
}
#rule-panel {
top: 18px;
left: 18px;
width: 380px;
max-height: calc(100vh - 36px);
overflow: auto;
padding: 19px;
scrollbar-width: thin;
scrollbar-color: #285069 transparent;
}
.eyebrow {
margin: 0 0 7px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(24px, 3vw, 31px);
line-height: 1.05;
letter-spacing: -0.035em;
}
.intro {
margin: 11px 0 14px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.formula {
padding: 13px 14px;
border: 1px solid rgba(101, 230, 221, 0.2);
border-radius: 12px;
background: rgba(33, 103, 110, 0.13);
color: #d8ffff;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 13px;
line-height: 1.6;
}
.formula strong {
color: var(--cyan);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 18px 0 8px;
color: #c4d8e8;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.section-title span:last-child {
color: var(--muted);
font-weight: 600;
letter-spacing: 0;
text-transform: none;
}
.row-head,
.hash-row {
display: grid;
grid-template-columns: 1fr 64px 48px 68px;
align-items: center;
gap: 5px;
}
.row-head {
padding: 0 9px 7px;
color: #6f8ca2;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.11em;
}
.hash-row {
width: 100%;
min-height: 38px;
margin: 3px 0;
padding: 7px 9px;
border: 1px solid transparent;
border-radius: 9px;
background: rgba(255, 255, 255, 0.025);
cursor: pointer;
text-align: left;
transition:
background 140ms ease,
border-color 140ms ease,
transform 140ms ease;
}
.hash-row:hover {
background: rgba(101, 230, 221, 0.07);
border-color: rgba(101, 230, 221, 0.16);
transform: translateX(2px);
}
.hash-row.selected {
border-color: rgba(101, 230, 221, 0.55);
background: rgba(101, 230, 221, 0.11);
}
.hash-row .key {
overflow: hidden;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 13px;
font-weight: 800;
text-overflow: ellipsis;
}
.hash-row .number {
color: #a9c1d3;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
}
.collision-label {
color: var(--orange);
font-size: 8px;
font-weight: 900;
letter-spacing: 0.08em;
text-align: right;
}
.collision-label.clear {
color: #47677e;
}
.selection {
min-height: 72px;
margin-top: 13px;
padding: 12px;
border-left: 3px solid var(--cyan);
border-radius: 4px 10px 10px 4px;
background: rgba(101, 230, 221, 0.065);
color: #b9cddd;
font-size: 12px;
line-height: 1.55;
white-space: pre-line;
}
.input-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
}
.input-row input {
min-width: 0;
padding: 10px 12px;
border: 1px solid rgba(126, 178, 203, 0.24);
border-radius: 9px;
outline: none;
background: rgba(1, 10, 18, 0.5);
color: var(--text);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 13px;
}
.input-row input:focus {
border-color: rgba(101, 230, 221, 0.65);
box-shadow: 0 0 0 3px rgba(101, 230, 221, 0.08);
}
.button {
padding: 10px 13px;
border: 1px solid rgba(101, 230, 221, 0.35);
border-radius: 9px;
background: rgba(101, 230, 221, 0.12);
color: #d8ffff;
cursor: pointer;
font-size: 11px;
font-weight: 800;
transition: background 140ms ease;
}
.button:hover {
background: rgba(101, 230, 221, 0.21);
}
.button.secondary {
border-color: rgba(125, 157, 181, 0.25);
background: rgba(125, 157, 181, 0.08);
color: var(--muted);
}
.input-note {
margin: 8px 0 0;
color: #6f8ca2;
font-size: 10px;
line-height: 1.45;
}
#stats-panel {
top: 18px;
right: 18px;
width: 205px;
padding: 15px;
}
.stat-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.stat {
padding: 10px;
border: 1px solid rgba(129, 181, 205, 0.12);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.stat-value {
display: block;
color: var(--cyan);
font-size: 23px;
font-weight: 800;
letter-spacing: -0.04em;
}
.stat-label {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#controls-panel {
right: 18px;
bottom: 18px;
padding: 12px 14px;
color: var(--muted);
font-size: 11px;
line-height: 1.7;
}
#controls-panel strong {
color: var(--text);
}
#toast {
position: fixed;
z-index: 20;
left: 50%;
bottom: 25px;
max-width: min(520px, calc(100vw - 30px));
padding: 11px 16px;
border: 1px solid rgba(101, 230, 221, 0.25);
border-radius: 999px;
background: rgba(6, 22, 34, 0.94);
color: #d9faff;
font-size: 12px;
opacity: 0;
pointer-events: none;
transform: translate(-50%, 12px);
transition:
opacity 180ms ease,
transform 180ms ease;
}
#toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 760px) {
#rule-panel {
top: 10px;
left: 10px;
width: min(360px, calc(100vw - 20px));
max-height: 55vh;
padding: 15px;
}
#stats-panel {
display: none;
}
#controls-panel {
right: 10px;
bottom: 10px;
padding: 9px 11px;
font-size: 10px;
}
.intro {
margin-bottom: 10px;
}
.selection {
min-height: 55px;
}
}
</style>
</head>
<body>
<div id="stage" aria-label="Interactive three-dimensional hash bucket array"></div>
<div class="vignette"></div>
<section id="rule-panel" class="panel">
<p class="eyebrow">Hashing / Collision Lab</p>
<h1>Many keys.<br />Seven buckets.</h1>
<p class="intro">
A hash function compresses each key into a number. Different keys can
produce different hash values but still land in the same bucket.
</p>
<div class="formula">
<strong>H(s)</strong> = Σ UTF-16 code units<br />
<strong>bucket(s)</strong> = H(s) mod 7
</div>
<div class="section-title">
<span>Observed mappings</span>
<span>click to inspect</span>
</div>
<div class="row-head" aria-hidden="true">
<span>KEY</span>
<span>HASH</span>
<span>MOD 7</span>
<span style="text-align:right">STATE</span>
</div>
<div id="key-list"></div>
<div id="selection" class="selection" aria-live="polite">
Select a key to trace its mapping through the hash rule.
</div>
<div class="section-title">
<span>Try another key</span>
<span>added to the live array</span>
</div>
<form id="hash-form" class="input-row">
<input
id="key-input"
value="apple"
maxlength="12"
autocomplete="off"
spellcheck="false"
aria-label="Key to hash"
placeholder="type a key"
/>
<button class="button" type="submit">Hash + add</button>
</form>
<p class="input-note">
Case-sensitive. Reset restores the six-key demonstration.
</p>
<div class="input-row" style="margin-top:9px">
<button id="reset-button" class="button secondary" type="button">
Reset demonstration
</button>
</div>
</section>
<aside id="stats-panel" class="panel">
<div class="stat-grid">
<div class="stat">
<span id="bucket-count" class="stat-value">7</span>
<span class="stat-label">Buckets</span>
</div>
<div class="stat">
<span id="key-count" class="stat-value">6</span>
<span class="stat-label">Keys</span>
</div>
<div class="stat">
<span id="collision-count" class="stat-value">3</span>
<span class="stat-label">Collision groups</span>
</div>
<div class="stat">
<span id="shared-count" class="stat-value">6</span>
<span class="stat-label">Shared keys</span>
</div>
</div>
</aside>
<aside id="controls-panel" class="panel">
<strong>Camera</strong> drag to orbit · scroll to zoom<br />
<strong>Scene</strong> click a floating key to inspect<br />
<strong>Reset view</strong> double-click the scene
</aside>
<div id="toast" role="status" aria-live="polite"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Application state
// -------------------------------------------------------------------------
const BUCKET_COUNT = 7;
const BUCKET_SPACING = 2.35;
const COLORS = {
cyan: 0x65e6dd,
orange: 0xff9d76,
purple: 0xc4a7ff,
blue: 0x72b7ff,
green: 0x7cdeaa,
yellow: 0xf6d66f,
pink: 0xff83b6,
mint: 0x61dfd2
};
const STATIC_KEYS = [
{ key: "lion", hash: 434, bucket: 0, color: COLORS.yellow },
{ key: "zebra", hash: 532, bucket: 0, color: COLORS.pink },
{ key: "maple", hash: 527, bucket: 2, color: COLORS.orange },
{ key: "kiwi", hash: 436, bucket: 2, color: COLORS.green },
{ key: "cat", hash: 312, bucket: 4, color: COLORS.blue },
{ key: "pear", hash: 424, bucket: 4, color: COLORS.purple }
];
const CUSTOM_COLORS = [
COLORS.cyan,
COLORS.orange,
COLORS.purple,
COLORS.blue,
COLORS.green,
COLORS.yellow,
COLORS.pink,
COLORS.mint
];
const bucketItems = Array.from({ length: BUCKET_COUNT }, () => []);
const bucketXs = Array.from(
{ length: BUCKET_COUNT },
(_, index) => (index - (BUCKET_COUNT - 1) / 2) * BUCKET_SPACING
);
let allKeys = [];
let tokenRecords = [];
let selectedKey = null;
let pickables = [];
let collisionBadges = [];
let rowButtons = new Map();
const keyList = document.querySelector("#key-list");
const selection = document.querySelector("#selection");
const keyInput = document.querySelector("#key-input");
const hashForm = document.querySelector("#hash-form");
const resetButton = document.querySelector("#reset-button");
const toast = document.querySelector("#toast");
let toastTimer;
function hashString(value) {
let result = 0;
for (let index = 0; index < value.length; index++) {
result += value.charCodeAt(index);
}
return result;
}
function showToast(message) {
toast.textContent = message;
toast.classList.add("visible");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("visible"), 2600);
}
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const stage = document.querySelector("#stage");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111d);
scene.fog = new THREE.Fog(0x07111d, 21, 43);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
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;
stage.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xbcecff, 0x172235, 2.25);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xdaf8ff, 3.5);
keyLight.position.set(7, 13, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -15;
keyLight.shadow.camera.right = 15;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -8;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 40;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4bc8ff, 1.8);
rimLight.position.set(-10, 6, -8);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xff956f, 18, 20, 2);
warmLight.position.set(7, 5, -2);
scene.add(warmLight);
const world = new THREE.Group();
scene.add(world);
// Floor and platform.
const floorMaterial = new THREE.MeshStandardMaterial({
color: 0x081522,
roughness: 0.92,
metalness: 0.05
});
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(55, 38),
floorMaterial
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.43;
floor.receiveShadow = true;
world.add(floor);
const grid = new THREE.GridHelper(34, 34, 0x21667a, 0x143246);
grid.position.y = -0.415;
grid.material.transparent = true;
grid.material.opacity = 0.28;
world.add(grid);
const platformMaterial = new THREE.MeshStandardMaterial({
color: 0x102536,
roughness: 0.7,
metalness: 0.18,
flatShading: true
});
const platform = new THREE.Mesh(
new THREE.BoxGeometry(17.45, 0.35, 3.65),
platformMaterial
);
platform.position.y = -0.22;
platform.receiveShadow = true;
platform.castShadow = true;
world.add(platform);
const platformEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(platform.geometry),
new THREE.LineBasicMaterial({
color: 0x28566b,
transparent: true,
opacity: 0.7
})
);
platformEdges.position.copy(platform.position);
world.add(platformEdges);
const accentBar = new THREE.Mesh(
new THREE.BoxGeometry(16.8, 0.055, 0.08),
new THREE.MeshBasicMaterial({ color: 0x3acac5 })
);
accentBar.position.set(0, -0.025, 1.84);
world.add(accentBar);
// -------------------------------------------------------------------------
// Canvas texture helpers
// -------------------------------------------------------------------------
function roundedRectangle(context, x, y, width, height, radius) {
context.beginPath();
context.moveTo(x + radius, y);
context.lineTo(x + width - radius, y);
context.quadraticCurveTo(x + width, y, x + width, y + radius);
context.lineTo(x + width, y + height - radius);
context.quadraticCurveTo(
x + width,
y + height,
x + width - radius,
y + height
);
context.lineTo(x + radius, y + height);
context.quadraticCurveTo(x, y + height, x, y + height - radius);
context.lineTo(x, y + radius);
context.quadraticCurveTo(x, y, x + radius, y);
context.closePath();
}
function hexColor(value) {
return `#${value.toString(16).padStart(6, "0")}`;
}
function makeTokenTexture(key, hash, color) {
const canvas = document.createElement("canvas");
canvas.width = 640;
canvas.height = 200;
const context = canvas.getContext("2d");
const colorString = hexColor(color);
roundedRectangle(context, 8, 8, 624, 184, 28);
context.fillStyle = "rgba(5, 17, 29, 0.96)";
context.fill();
context.lineWidth = 7;
context.strokeStyle = colorString;
context.stroke();
context.textBaseline = "middle";
context.fillStyle = "#f4fbff";
context.font = `800 ${key.length > 8 ? 58 : 70}px system-ui`;
context.fillText(key, 35, 76);
context.fillStyle = colorString;
context.font = "700 31px ui-monospace, monospace";
context.fillText(`H ${hash} → ${hash % BUCKET_COUNT}`, 37, 145);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
return texture;
}
function makeBucketTexture(index) {
const canvas = document.createElement("canvas");
canvas.width = 160;
canvas.height = 160;
const context = canvas.getContext("2d");
context.beginPath();
context.arc(80, 80, 66, 0, Math.PI * 2);
context.fillStyle = "#071a28";
context.fill();
context.lineWidth = 6;
context.strokeStyle = "#56d9d4";
context.stroke();
context.fillStyle = "#eaffff";
context.font = "800 72px ui-monospace, monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(String(index), 80, 83);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
function makeCollisionTexture(count, bucket) {
const canvas = document.createElement("canvas");
canvas.width = 760;
canvas.height = 150;
const context = canvas.getContext("2d");
roundedRectangle(context, 5, 5, 750, 140, 24);
context.fillStyle = "rgba(42, 19, 18, 0.96)";
context.fill();
context.lineWidth = 5;
context.strokeStyle = "#ff9d76";
context.stroke();
context.fillStyle = "#ffb18f";
context.font = "800 36px system-ui";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(
`COLLISION · ${count} KEYS → BUCKET ${bucket}`,
380,
76
);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
function makeRuleTexture() {
const canvas = document.createElement("canvas");
canvas.width = 1800;
canvas.height = 280;
const context = canvas.getContext("2d");
roundedRectangle(context, 8, 8, 1784, 264, 28);
context.fillStyle = "rgba(5, 23, 36, 0.97)";
context.fill();
context.lineWidth = 7;
context.strokeStyle = "#65e6dd";
context.stroke();
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = "#65e6dd";
context.font = "800 36px system-ui";
context.fillText("EXPLICIT HASH RULE", 900, 55);
context.fillStyle = "#f0fbff";
context.font = "700 49px ui-monospace, monospace";
context.fillText(
"H(s) = Σ charCode(s[i]) bucket(s) = H(s) mod 7",
900,
128
);
context.fillStyle = "#9eb8cb";
context.font = "500 31px system-ui";
context.fillText(
"Different hash values can still have the same remainder.",
900,
205
);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
const ruleSprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: makeRuleTexture(),
transparent: true,
depthTest: false,
depthWrite: false,
toneMapped: false
})
);
ruleSprite.position.set(0, 4.85, -1.45);
ruleSprite.scale.set(9.7, 1.51, 1);
ruleSprite.renderOrder = 1;
world.add(ruleSprite);
// -------------------------------------------------------------------------
// Bucket array construction
// -------------------------------------------------------------------------
const bucketGroups = [];
const bucketMaterials = [];
const bucketMarkers = [];
const collisionHalos = [];
const innerMaterial = new THREE.MeshStandardMaterial({
color: 0x081c2b,
roughness: 0.88,
metalness: 0.05,
flatShading: true
});
function addBox(group, geometry, material, x, y, z) {
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
group.add(mesh);
return mesh;
}
for (let index = 0; index < BUCKET_COUNT; index++) {
const group = new THREE.Group();
group.position.x = bucketXs[index];
const material = new THREE.MeshStandardMaterial({
color: 0x123b4d,
emissive: 0x000000,
emissiveIntensity: 0,
roughness: 0.68,
metalness: 0.16,
flatShading: true
});
addBox(
group,
new THREE.BoxGeometry(2.08, 0.16, 2.46),
material,
0,
0.08,
0
);
addBox(
group,
new THREE.BoxGeometry(1.82, 0.025, 2.18),
innerMaterial,
0,
0.172,
0
);
addBox(
group,
new THREE.BoxGeometry(2.08, 0.73, 0.13),
material,
0,
0.45,
1.165
);
addBox(
group,
new THREE.BoxGeometry(2.08, 0.73, 0.13),
material,
0,
0.45,
-1.165
);
addBox(
group,
new THREE.BoxGeometry(0.13, 0.73, 2.33),
material,
-0.975,
0.45,
0
);
addBox(
group,
new THREE.BoxGeometry(0.13, 0.73, 2.33),
material,
0.975,
0.45,
0
);
const bucketSprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: makeBucketTexture(index),
transparent: true,
depthTest: false,
depthWrite: false,
toneMapped: false
})
);
bucketSprite.position.set(0, 0.45, 1.27);
bucketSprite.scale.set(0.48, 0.48, 1);
bucketSprite.renderOrder = 9;
group.add(bucketSprite);
const marker = new THREE.Mesh(
new THREE.TorusGeometry(0.17, 0.035, 6, 20),
new THREE.MeshBasicMaterial({
color: 0x8af4ec,
transparent: true,
opacity: 0.8
})
);
marker.rotation.x = Math.PI / 2;
marker.position.y = 0.34;
group.add(marker);
const halo = new THREE.Mesh(
new THREE.TorusGeometry(0.96, 0.038, 6, 32),
new THREE.MeshBasicMaterial({
color: 0xff9d76,
transparent: true,
opacity: 0.48
})
);
halo.rotation.x = Math.PI / 2;
halo.position.y = 0.27;
halo.visible = false;
group.add(halo);
world.add(group);
bucketGroups.push(group);
bucketMaterials.push(material);
bucketMarkers.push(marker);
collisionHalos.push(halo);
}
const arrayLabel = new THREE.Sprite(
new THREE.SpriteMaterial({
map: makeCollisionTexture(7, 0).clone(),
transparent: true,
depthTest: false,
depthWrite: false,
toneMapped: false
})
);
// Replace the generic collision texture with an array title.
const titleCanvas = document.createElement("canvas");
titleCanvas.width = 900;
titleCanvas.height = 150;
const titleContext = titleCanvas.getContext("2d");
roundedRectangle(titleContext, 5, 5, 890, 140, 24);
titleContext.fillStyle = "rgba(5, 22, 34, 0.96)";
titleContext.fill();
titleContext.lineWidth = 5;
titleContext.strokeStyle = "#4da9c2";
titleContext.stroke();
titleContext.fillStyle = "#bcecff";
titleContext.font = "800 43px system-ui";
titleContext.textAlign = "center";
titleContext.textBaseline = "middle";
titleContext.fillText("BUCKET ARRAY · SIZE 7", 450, 77);
const titleTexture = new THREE.CanvasTexture(titleCanvas);
titleTexture.colorSpace = THREE.SRGBColorSpace;
arrayLabel.material.map.dispose();
arrayLabel.material.map = titleTexture;
arrayLabel.material.needsUpdate = true;
arrayLabel.position.set(0, -0.1, 2.15);
arrayLabel.scale.set(3.7, 0.62, 1);
arrayLabel.renderOrder = 8;
world.add(arrayLabel);
// -------------------------------------------------------------------------
// Key tokens and mapping lines
// -------------------------------------------------------------------------
function createToken(data) {
const group = new THREE.Group();
const material = new THREE.MeshStandardMaterial({
color: data.color,
emissive: data.color,
emissiveIntensity: 0.12,
roughness: 0.45,
metalness: 0.18,
flatShading: true
});
const plaque = new THREE.Mesh(
new THREE.BoxGeometry(1.58, 0.59, 0.18),
material
);
plaque.position.x = 0.12;
plaque.castShadow = true;
group.add(plaque);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.22, 0.055, 6, 12),
material
);
ring.position.x = -0.92;
ring.castShadow = true;
group.add(ring);
const stem = new THREE.Mesh(
new THREE.BoxGeometry(0.38, 0.11, 0.12),
material
);
stem.position.set(-0.65, 0, 0);
group.add(stem);
const label = new THREE.Sprite(
new THREE.SpriteMaterial({
map: makeTokenTexture(data.key, data.hash, data.color),
transparent: true,
depthTest: false,
depthWrite: false,
toneMapped: false
})
);
label.position.set(0.14, 0, 0.14);
label.scale.set(1.55, 0.485, 1);
label.renderOrder = 10;
group.add(label);
const lineGeometry = new THREE.BufferGeometry();
lineGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(new Float32Array(6), 3)
);
const line = new THREE.Line(
lineGeometry,
new THREE.LineDashedMaterial({
color: data.color,
dashSize: 0.16,
gapSize: 0.11,
transparent: true,
opacity: 0.62
})
);
line.renderOrder = 3;
world.add(line);
const token = {
...data,
group,
material,
label,
line,
phase: Math.random() * Math.PI * 2,
baseY: 2.25,
baseZ: 0,
targetScale: 1
};
for (const object of [plaque, ring, stem, label]) {
object.userData.token = token;
pickables.push(object);
}
group.position.x = bucketXs[data.bucket];
world.add(group);
bucketItems[data.bucket].push(token);
tokenRecords.push(token);
return token;
}
function layoutBucket(bucketIndex) {
const items = bucketItems[bucketIndex];
items.forEach((token, itemIndex) => {
if (items.length === 1) {
token.baseZ = 0;
token.baseY = 2.25;
} else if (items.length === 2) {
token.baseZ = itemIndex === 0 ? -0.62 : 0.56;
token.baseY = itemIndex === 0 ? 2.25 : 3.22;
} else {
token.baseZ = (itemIndex - 1) * 0.7;
token.baseY = 2.25 + (itemIndex === 1 ? 1.03 : 0);
}
token.group.position.set(
bucketXs[bucketIndex],
token.baseY,
token.baseZ
);
});
bucketMarkers[bucketIndex].visible = items.length > 0;
collisionHalos[bucketIndex].visible = items.length > 1;
}
function updateConnector(token) {
const position = token.line.geometry.attributes.position;
position.setXYZ(
0,
token.group.position.x,
token.group.position.y - 0.34,
token.group.position.z
);
position.setXYZ(
1,
bucketXs[token.bucket],
0.34,
0
);
position.needsUpdate = true;
token.line.computeLineDistances();
token.line.geometry.computeBoundingSphere();
}
function updateCollisionBadges() {
for (const badge of collisionBadges) {
if (!badge) continue;
world.remove(badge);
badge.material.map.dispose();
badge.material.dispose();
}
collisionBadges = new Array(BUCKET_COUNT).fill(null);
for (let index = 0; index < BUCKET_COUNT; index++) {
const items = bucketItems[index];
if (items.length < 2) continue;
const badge = new THREE.Sprite(
new THREE.SpriteMaterial({
map: makeCollisionTexture(items.length, index),
transparent: true,
depthTest: false,
depthWrite: false,
toneMapped: false
})
);
badge.position.set(
bucketXs[index],
Math.max(...items.map((item) => item.baseY)) + 0.78,
0.25
);
badge.scale.set(1.9, 0.375, 1);
badge.renderOrder = 12;
badge.userData.baseY = badge.position.y;
world.add(badge);
collisionBadges[index] = badge;
}
}
// -------------------------------------------------------------------------
// UI mapping rows and selection
// -------------------------------------------------------------------------
function renderRows() {
keyList.replaceChildren();
rowButtons = new Map();
for (const data of allKeys) {
const row = document.createElement("button");
row.type = "button";
row.className = "hash-row";
row.setAttribute("aria-label", `Inspect ${data.key}`);
const keyCell = document.createElement("span");
keyCell.className = "key";
keyCell.textContent = data.key;
const hashCell = document.createElement("span");
hashCell.className = "number";
hashCell.textContent = String(data.hash);
const bucketCell = document.createElement("span");
bucketCell.className = "number";
bucketCell.textContent = String(data.bucket);
const stateCell = document.createElement("span");
const collision = bucketItems[data.bucket].length > 1;
stateCell.className = `collision-label${collision ? "" : " clear"}`;
stateCell.textContent = collision ? "COLLIDE" : "unique";
row.append(keyCell, hashCell, bucketCell, stateCell);
row.addEventListener("click", () => selectKey(data.key));
keyList.appendChild(row);
rowButtons.set(data.key, row);
}
updateStats();
updateRowSelection();
}
function updateStats() {
const collisionGroups = bucketItems.filter((items) => items.length > 1);
const sharedKeys = collisionGroups.reduce(
(total, items) => total + items.length,
0
);
document.querySelector("#bucket-count").textContent = BUCKET_COUNT;
document.querySelector("#key-count").textContent = allKeys.length;
document.querySelector("#collision-count").textContent = collisionGroups.length;
document.querySelector("#shared-count").textContent = sharedKeys;
}
function updateRowSelection() {
for (const [key, button] of rowButtons) {
const isSelected = key === selectedKey;
button.classList.toggle("selected", isSelected);
button.setAttribute("aria-pressed", String(isSelected));
}
}
function selectKey(key) {
selectedKey = key;
const data = allKeys.find((item) => item.key === key);
const selectedBucket = data ? data.bucket : null;
for (const token of tokenRecords) {
token.targetScale = token.key === key ? 1.09 : 1;
token.material.emissiveIntensity =
token.key === key ? 0.5 : 0.12;
}
for (let index = 0; index < BUCKET_COUNT; index++) {
const selected = index === selectedBucket;
bucketMaterials[index].emissive.setHex(
selected ? 0x08727c : 0x000000
);
bucketMaterials[index].emissiveIntensity = selected ? 0.55 : 0;
collisionHalos[index].material.opacity = selected ? 0.9 : 0.45;
}
updateRowSelection();
if (!data) {
selection.textContent =
"Select a key to trace its mapping through the hash rule.";
return;
}
const companions = bucketItems[data.bucket]
.filter((item) => item.key !== data.key)
.map((item) => `"${item.key}"`);
if (companions.length > 0) {
selection.textContent =
`Different keys can share a bucket.\n` +
`"${data.key}" and ${companions.join(", ")} are unequal, but both ` +
`map to bucket ${data.bucket}. ` +
`H("${data.key}") = ${data.hash}, and ${data.hash} mod 7 = ${data.bucket}.`;
} else {
selection.textContent =
`"${data.key}" hashes to ${data.hash}. ` +
`${data.hash} mod 7 = ${data.bucket}, so it maps to bucket ${data.bucket}. ` +
`No other key currently occupies that bucket.`;
}
}
// -------------------------------------------------------------------------
// Demo lifecycle
// -------------------------------------------------------------------------
function clearTokens() {
for (const token of tokenRecords) {
world.remove(token.group);
world.remove(token.line);
const geometries = new Set();
const materials = new Set();
token.group.traverse((object) => {
if (object.geometry) geometries.add(object.geometry);
if (object.material) materials.add(object.material);
});
geometries.forEach((geometry) => geometry.dispose());
materials.forEach((material) => {
if (material.map) material.map.dispose();
material.dispose();
});
token.line.geometry.dispose();
token.line.material.dispose();
}
tokenRecords = [];
pickables = [];
for (let index = 0; index < BUCKET_COUNT; index++) {
bucketItems[index].length = 0;
}
}
function resetDemo() {
clearTokens();
allKeys = [];
for (const data of STATIC_KEYS) {
const copy = { ...data };
allKeys.push(copy);
createToken(copy);
}
for (let index = 0; index < BUCKET_COUNT; index++) {
layoutBucket(index);
}
updateCollisionBadges();
renderRows();
selectKey("zebra");
}
resetDemo();
hashForm.addEventListener("submit", (event) => {
event.preventDefault();
const key = keyInput.value.trim();
if (!key) {
showToast("Enter a key first.");
keyInput.focus();
return;
}
if (allKeys.some((item) => item.key === key)) {
selectKey(key);
showToast(`"${key}" already exists in the demonstration.`);
return;
}
const hash = hashString(key);
const bucket = hash % BUCKET_COUNT;
const color =
CUSTOM_COLORS[allKeys.length % CUSTOM_COLORS.length];
const data = { key, hash, bucket, color, custom: true };
allKeys.push(data);
createToken(data);
layoutBucket(bucket);
updateCollisionBadges();
renderRows();
selectKey(key);
const collided = bucketItems[bucket].length > 1;
showToast(
collided
? `"${key}" → H ${hash} → bucket ${bucket}: collision with another key.`
: `"${key}" → H ${hash} → bucket ${bucket}.`
);
keyInput.value = "";
keyInput.focus();
});
resetButton.addEventListener("click", () => {
resetDemo();
keyInput.value = "apple";
showToast("The six-key demonstration has been restored.");
});
// -------------------------------------------------------------------------
// Custom camera controls — no addons or OrbitControls
// -------------------------------------------------------------------------
const orbit = {
azimuth: 0.29,
polar: 0.98,
distance: 20.5,
target: new THREE.Vector3(0, 1.7, 0),
dragging: false,
pointerId: null,
lastX: 0,
lastY: 0,
travel: 0
};
function updateCamera() {
const horizontal = orbit.distance * Math.sin(orbit.polar);
camera.position.set(
orbit.target.x + horizontal * Math.sin(orbit.azimuth),
orbit.target.y + orbit.distance * Math.cos(orbit.polar),
orbit.target.z + horizontal * Math.cos(orbit.azimuth)
);
camera.lookAt(orbit.target);
}
function resetCamera() {
orbit.azimuth = 0.29;
orbit.polar = 0.98;
orbit.distance = 20.5;
orbit.target.set(0, 1.7, 0);
updateCamera();
}
updateCamera();
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function pickToken(clientX, clientY) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
scene.updateMatrixWorld(true);
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(pickables, false);
return hits.length ? hits[0].object.userData.token : null;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
orbit.dragging = true;
orbit.pointerId = event.pointerId;
orbit.lastX = event.clientX;
orbit.lastY = event.clientY;
orbit.travel = 0;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!orbit.dragging || event.pointerId !== orbit.pointerId) return;
const deltaX = event.clientX - orbit.lastX;
const deltaY = event.clientY - orbit.lastY;
orbit.lastX = event.clientX;
orbit.lastY = event.clientY;
orbit.travel += Math.abs(deltaX) + Math.abs(deltaY);
orbit.azimuth -= deltaX * 0.006;
orbit.polar = THREE.MathUtils.clamp(
orbit.polar + deltaY * 0.005,
0.43,
1.35
);
updateCamera();
});
function endPointer(event) {
if (!orbit.dragging || event.pointerId !== orbit.pointerId) return;
if (orbit.travel < 6) {
const token = pickToken(event.clientX, event.clientY);
if (token) selectKey(token.key);
}
orbit.dragging = false;
orbit.pointerId = null;
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.distance = THREE.MathUtils.clamp(
orbit.distance + event.deltaY * 0.012,
11,
29
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
// -------------------------------------------------------------------------
// Ambient background particles
// -------------------------------------------------------------------------
const particlePositions = [];
for (let index = 0; index < 110; index++) {
particlePositions.push(
(Math.random() - 0.5) * 32,
1 + Math.random() * 10,
-9 + Math.random() * 12
);
}
const particleGeometry = new THREE.BufferGeometry();
particleGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(particlePositions, 3)
);
const particles = new THREE.Points(
particleGeometry,
new THREE.PointsMaterial({
color: 0x78cbd4,
size: 0.045,
transparent: true,
opacity: 0.45,
sizeAttenuation: true
})
);
world.add(particles);
// -------------------------------------------------------------------------
// Animation and resize
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
const elapsed = clock.getElapsedTime();
for (const token of tokenRecords) {
token.group.position.y =
token.baseY + Math.sin(elapsed * 1.35 + token.phase) * 0.055;
// Keep the physical key tags readable while orbiting.
token.group.quaternion.copy(camera.quaternion);
const currentScale = token.group.scale.x;
const nextScale = THREE.MathUtils.lerp(
currentScale,
token.targetScale,
0.12
);
token.group.scale.setScalar(nextScale);
updateConnector(token);
}
for (let index = 0; index < BUCKET_COUNT; index++) {
if (collisionHalos[index].visible) {
const pulse = 1 + Math.sin(elapsed * 2.2 + index) * 0.025;
collisionHalos[index].scale.setScalar(pulse);
}
bucketMarkers[index].rotation.z = elapsed * 0.22;
}
for (const badge of collisionBadges) {
if (!badge) continue;
badge.position.y =
badge.userData.baseY + Math.sin(elapsed * 1.7) * 0.035;
}
particles.rotation.y = elapsed * 0.008;
warmLight.intensity = 17 + Math.sin(elapsed * 1.2) * 2;
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", resize);
animate();
</script>
</body>
</html>
```