Prompt specification
Build or customize the Three.js 3D scene "Ordered drawer binary-search model" 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: Ordered drawer binary-search model
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/ordered-drawer-binary-search-model-x1849
Scene Description Prompt:
Build numbered drawers in sorted order with low, high, and midpoint markers; search for a target by halving the remaining candidate interval. Build this with Three.js from cdnjs as a low-poly scene in one self-contained HTML file.
Working Three.js Starter (ordered-drawer-binary-search-model-x1849):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Binary Search Drawers</title>
<style>
:root {
color-scheme: dark;
--bg: #07131f;
--panel: rgba(10, 24, 37, 0.88);
--border: rgba(157, 216, 255, 0.16);
--text: #eef8ff;
--muted: #91a9bb;
--cyan: #59d9ff;
--green: #50e3a4;
--red: #ff6b7a;
--amber: #ffc857;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 75% 20%, #123149 0%, transparent 45%),
var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
#hud {
position: fixed;
z-index: 10;
top: 20px;
left: 20px;
width: 350px;
max-height: calc(100vh - 40px);
}
.panel {
padding: 20px;
overflow: auto;
border: 1px solid var(--border);
border-radius: 18px;
background: var(--panel);
box-shadow:
0 22px 60px rgba(0, 0, 0, 0.34),
inset 0 1px rgba(255, 255, 255, 0.04);
backdrop-filter: blur(16px);
}
.eyebrow {
margin-bottom: 8px;
color: var(--cyan);
font-size: 0.7rem;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(1.55rem, 3vw, 2rem);
line-height: 1.08;
letter-spacing: -0.035em;
}
.intro {
margin: 12px 0 18px;
color: var(--muted);
font-size: 0.88rem;
line-height: 1.55;
}
.control-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
}
label {
color: #c6d7e4;
font-size: 0.78rem;
font-weight: 700;
}
select {
min-width: 112px;
padding: 9px 12px;
border: 1px solid var(--border);
border-radius: 9px;
outline: none;
background: #10283a;
color: white;
font: inherit;
font-weight: 800;
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-bottom: 16px;
}
button {
padding: 10px 11px;
border: 1px solid var(--border);
border-radius: 10px;
background: rgba(255, 255, 255, 0.055);
color: var(--text);
cursor: pointer;
font: inherit;
font-size: 0.78rem;
font-weight: 800;
transition:
transform 120ms ease,
background 120ms ease,
border-color 120ms ease,
opacity 120ms ease;
}
button:hover:not(:disabled) {
transform: translateY(-1px);
border-color: rgba(89, 217, 255, 0.5);
background: rgba(89, 217, 255, 0.1);
}
button:active:not(:disabled) {
transform: translateY(0);
}
button:disabled {
cursor: not-allowed;
opacity: 0.38;
}
button.primary {
border-color: rgba(89, 217, 255, 0.4);
background: linear-gradient(135deg, #167e9f, #135f83);
}
button.auto.active {
border-color: rgba(255, 200, 87, 0.55);
background: rgba(255, 200, 87, 0.12);
color: #ffe39b;
}
#metrics {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 7px;
margin-bottom: 14px;
}
.metric {
padding: 9px 6px;
border: 1px solid rgba(255, 255, 255, 0.07);
border-radius: 9px;
background: rgba(0, 0, 0, 0.13);
text-align: center;
}
.metric span {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 0.57rem;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.metric strong {
font-size: 1.02rem;
}
.metric.low strong {
color: var(--green);
}
.metric.high strong {
color: var(--red);
}
.metric.mid strong {
color: var(--amber);
}
.progress-title {
display: flex;
justify-content: space-between;
margin-bottom: 7px;
color: var(--muted);
font-size: 0.68rem;
font-weight: 700;
}
.progress {
height: 6px;
overflow: hidden;
margin-bottom: 17px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.08);
}
#progressFill {
width: 100%;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #2c91b4, var(--cyan));
transition: width 280ms ease;
}
.legend {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin-bottom: 16px;
}
.legend div {
color: var(--muted);
font-size: 0.68rem;
font-weight: 700;
}
.legend i {
display: inline-block;
width: 8px;
height: 8px;
margin-right: 6px;
border-radius: 50%;
vertical-align: 1px;
}
.trace-heading {
margin-bottom: 8px;
color: #c6d7e4;
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#trace {
max-height: 116px;
overflow: auto;
}
.trace-item {
padding: 7px 0;
border-top: 1px solid rgba(255, 255, 255, 0.06);
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.69rem;
line-height: 1.45;
}
.trace-item:first-child {
border-top: 0;
}
.trace-empty {
color: #627b8d;
font-size: 0.75rem;
line-height: 1.5;
}
#statusBox {
position: fixed;
z-index: 10;
bottom: 20px;
left: 50%;
display: flex;
align-items: center;
gap: 12px;
width: min(650px, calc(100vw - 40px));
padding: 13px 17px;
transform: translateX(-50%);
border: 1px solid var(--border);
border-radius: 14px;
background: rgba(8, 21, 33, 0.9);
box-shadow: 0 14px 40px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(14px);
}
.status-dot {
flex: 0 0 auto;
width: 10px;
height: 10px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 14px currentColor;
}
#statusBox[data-kind="success"] .status-dot {
background: var(--green);
}
#statusBox[data-kind="warning"] .status-dot {
background: var(--amber);
}
#statusKind {
display: block;
margin-bottom: 2px;
color: var(--cyan);
font-size: 0.57rem;
font-weight: 900;
letter-spacing: 0.14em;
text-transform: uppercase;
}
#statusBox[data-kind="success"] #statusKind {
color: var(--green);
}
#statusBox[data-kind="warning"] #statusKind {
color: var(--amber);
}
#statusText {
font-size: 0.82rem;
line-height: 1.35;
}
#viewHelp {
position: fixed;
z-index: 10;
top: 20px;
right: 20px;
display: flex;
align-items: center;
gap: 10px;
padding: 9px 12px;
border: 1px solid var(--border);
border-radius: 12px;
background: rgba(8, 21, 33, 0.74);
color: var(--muted);
font-size: 0.66rem;
font-weight: 700;
letter-spacing: 0.03em;
backdrop-filter: blur(10px);
}
#resetView {
padding: 6px 9px;
font-size: 0.65rem;
}
@media (max-width: 700px) {
#hud {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
max-height: 47vh;
}
.panel {
padding: 15px;
border-radius: 14px;
}
.intro {
display: none;
}
h1 {
font-size: 1.45rem;
}
#metrics {
margin-bottom: 10px;
}
.legend,
.trace-heading,
#trace {
display: none;
}
.progress {
margin-bottom: 0;
}
#viewHelp {
display: none;
}
#statusBox {
bottom: 10px;
width: calc(100vw - 20px);
padding: 11px 13px;
}
}
</style>
</head>
<body>
<div id="hud">
<section class="panel">
<div class="eyebrow">Algorithm Lab · 01</div>
<h1>Binary Search Drawers</h1>
<p class="intro">
The drawers are sorted from 1 to 12. Compare the target with the
midpoint, discard the impossible half, and repeat.
</p>
<div class="control-row">
<label for="targetSelect">Target drawer</label>
<select id="targetSelect" aria-label="Target drawer"></select>
</div>
<div class="buttons">
<button id="searchButton" class="primary" type="button">
Halve interval
</button>
<button id="autoButton" class="auto" type="button">
Auto search
</button>
<button id="resetButton" type="button">Reset search</button>
<button id="randomButton" type="button">Random target</button>
</div>
<div id="metrics">
<div class="metric low">
<span>Low</span>
<strong id="lowMetric">1</strong>
</div>
<div class="metric high">
<span>High</span>
<strong id="highMetric">12</strong>
</div>
<div class="metric mid">
<span>Mid</span>
<strong id="midMetric">6</strong>
</div>
<div class="metric">
<span>Left</span>
<strong id="remainingMetric">12</strong>
</div>
</div>
<div class="progress-title">
<span>Remaining candidate interval</span>
<span id="intervalReadout">[1, 12] · 12 candidates</span>
</div>
<div class="progress"><div id="progressFill"></div></div>
<div class="legend">
<div><i style="background:#50e3a4"></i>Low</div>
<div><i style="background:#ff6b7a"></i>High</div>
<div><i style="background:#ffc857"></i>Midpoint</div>
</div>
<div class="trace-heading">Comparison trace</div>
<div id="trace"></div>
</section>
</div>
<div id="viewHelp">
<span>DRAG TO ORBIT · SCROLL TO ZOOM · CLICK A DRAWER</span>
<button id="resetView" type="button">Reset view</button>
</div>
<div id="statusBox" data-kind="info">
<span class="status-dot"></span>
<div>
<span id="statusKind">Ready</span>
<strong id="statusText">
Choose a target, then halve the remaining candidate interval.
</strong>
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Constants and state
// -------------------------------------------------------------------------
const DRAWER_COUNT = 12;
const DRAWER_WIDTH = 1.1;
const DRAWER_SPACING = 1.25;
const TOTAL_WIDTH =
(DRAWER_COUNT - 1) * DRAWER_SPACING + DRAWER_WIDTH;
const COLORS = {
low: 0x50e3a4,
high: 0xff6b7a,
midpoint: 0xffc857,
candidate: 0x2f7594,
candidateEmissive: 0x072d3d,
eliminated: 0x253542,
eliminatedEmissive: 0x000000,
found: 0x31d69b,
foundEmissive: 0x087956
};
let target = 8;
let low = 0;
let high = DRAWER_COUNT - 1;
let midpoint = Math.floor((low + high) / 2);
let foundIndex = -1;
let comparisonCount = 0;
let autoPlaying = false;
let autoTimer = null;
let trace = [];
const targetSelect = document.querySelector("#targetSelect");
const searchButton = document.querySelector("#searchButton");
const autoButton = document.querySelector("#autoButton");
const resetButton = document.querySelector("#resetButton");
const randomButton = document.querySelector("#randomButton");
const resetViewButton = document.querySelector("#resetView");
const lowMetric = document.querySelector("#lowMetric");
const highMetric = document.querySelector("#highMetric");
const midMetric = document.querySelector("#midMetric");
const remainingMetric = document.querySelector("#remainingMetric");
const intervalReadout = document.querySelector("#intervalReadout");
const progressFill = document.querySelector("#progressFill");
const traceElement = document.querySelector("#trace");
const statusBox = document.querySelector("#statusBox");
const statusKind = document.querySelector("#statusKind");
const statusText = document.querySelector("#statusText");
for (let i = 1; i <= DRAWER_COUNT; i++) {
const option = document.createElement("option");
option.value = String(i);
option.textContent = `Drawer ${i}`;
targetSelect.appendChild(option);
}
targetSelect.value = String(target);
// -------------------------------------------------------------------------
// Three.js setup
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07131f);
scene.fog = new THREE.Fog(0x07131f, 24, 58);
const camera = new THREE.PerspectiveCamera(
40,
window.innerWidth / window.innerHeight,
0.1,
120
);
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.15;
renderer.domElement.setAttribute(
"aria-label",
"Interactive low-poly scene of numbered drawers"
);
document.body.prepend(renderer.domElement);
const clock = new THREE.Clock();
const sceneRoot = new THREE.Group();
scene.add(sceneRoot);
scene.add(new THREE.HemisphereLight(0xa5ddff, 0x172331, 2.25));
scene.add(new THREE.AmbientLight(0x6d94ad, 0.65));
const keyLight = new THREE.DirectionalLight(0xd9f3ff, 3.1);
keyLight.position.set(7, 13, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -13;
keyLight.shadow.camera.right = 13;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -7;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 40;
keyLight.shadow.bias = -0.0002;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x3fa9ff, 1.5);
rimLight.position.set(-10, 6, -8);
scene.add(rimLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(80, 80),
new THREE.MeshStandardMaterial({
color: 0x0a1823,
roughness: 0.95,
metalness: 0.02
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -1.3;
floor.receiveShadow = true;
scene.add(floor);
const platform = new THREE.Mesh(
new THREE.CylinderGeometry(9.25, 9.75, 0.55, 12, 1, false),
new THREE.MeshStandardMaterial({
color: 0x152d3e,
roughness: 0.82,
metalness: 0.08,
flatShading: true
})
);
platform.position.y = -0.68;
platform.receiveShadow = true;
platform.castShadow = true;
sceneRoot.add(platform);
const pedestal = new THREE.Mesh(
new THREE.CylinderGeometry(3.8, 4.7, 0.36, 8),
new THREE.MeshStandardMaterial({
color: 0x0e202d,
roughness: 0.9,
flatShading: true
})
);
pedestal.position.y = -1.11;
pedestal.receiveShadow = true;
sceneRoot.add(pedestal);
const cabinetBase = new THREE.Mesh(
new THREE.BoxGeometry(TOTAL_WIDTH + 0.42, 0.4, 1.78),
new THREE.MeshStandardMaterial({
color: 0x0d1b26,
roughness: 0.74,
metalness: 0.16,
flatShading: true
})
);
cabinetBase.position.y = -0.18;
cabinetBase.castShadow = true;
cabinetBase.receiveShadow = true;
sceneRoot.add(cabinetBase);
const baseTrim = new THREE.Mesh(
new THREE.BoxGeometry(TOTAL_WIDTH + 0.5, 0.07, 1.86),
new THREE.MeshStandardMaterial({
color: 0x2f6f88,
roughness: 0.55,
metalness: 0.25,
flatShading: true
})
);
baseTrim.position.set(0, 0.035, 0);
baseTrim.castShadow = true;
sceneRoot.add(baseTrim);
// -------------------------------------------------------------------------
// Texture and marker helpers
// -------------------------------------------------------------------------
function createNumberTexture(number) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 192;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "#f1fbff";
context.textAlign = "center";
context.textBaseline = "middle";
context.font = '900 112px "Arial Black", Arial, sans-serif';
context.fillText(String(number), 128, 102);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(
8,
renderer.capabilities.getMaxAnisotropy()
);
return texture;
}
function createMarker(color, labelHeight) {
const group = new THREE.Group();
group.visible = false;
const stemMaterial = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.28,
roughness: 0.5,
metalness: 0.15,
flatShading: true
});
const stem = new THREE.Mesh(
new THREE.CylinderGeometry(0.025, 0.04, 0.5, 6),
stemMaterial
);
stem.position.y = 0.25;
const head = new THREE.Mesh(
new THREE.OctahedronGeometry(0.14, 0),
new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.5,
roughness: 0.36,
metalness: 0.2,
flatShading: true
})
);
head.position.y = 0.58;
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const spriteMaterial = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false,
toneMapped: false
});
const label = new THREE.Sprite(spriteMaterial);
label.scale.set(1.35, 0.3375, 1);
label.position.y = labelHeight;
label.renderOrder = 20;
group.add(stem, head, label);
sceneRoot.add(group);
return {
group,
head,
label,
canvas,
context,
texture,
color: `#${new THREE.Color(color).getHexString()}`,
baseY: 1.36
};
}
function setMarkerText(marker, text) {
const context = marker.context;
const canvas = marker.canvas;
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(5, 15, 24, 0.88)";
context.fillRect(4, 4, canvas.width - 8, canvas.height - 8);
context.strokeStyle = marker.color;
context.lineWidth = 6;
context.strokeRect(5, 5, canvas.width - 10, canvas.height - 10);
context.fillStyle = "#f4fbff";
context.textAlign = "center";
context.textBaseline = "middle";
context.font = "800 51px Arial, sans-serif";
context.fillText(text, canvas.width / 2, canvas.height / 2 + 2);
marker.texture.needsUpdate = true;
}
const lowMarker = createMarker(COLORS.low, 0.96);
const midpointMarker = createMarker(COLORS.midpoint, 1.08);
const highMarker = createMarker(COLORS.high, 1.36);
midpointMarker.baseY = 1.5;
setMarkerText(lowMarker, "LOW 1");
setMarkerText(midpointMarker, "MID 6");
setMarkerText(highMarker, "HIGH 12");
// -------------------------------------------------------------------------
// Drawer construction
// -------------------------------------------------------------------------
const drawerX = [];
const drawers = [];
const frontMeshes = [];
for (let i = 0; i < DRAWER_COUNT; i++) {
const x = (i - (DRAWER_COUNT - 1) / 2) * DRAWER_SPACING;
drawerX.push(x);
const group = new THREE.Group();
group.position.x = x;
sceneRoot.add(group);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0x17384a,
roughness: 0.76,
metalness: 0.08,
flatShading: true,
transparent: true,
opacity: 1
});
const body = new THREE.Mesh(
new THREE.BoxGeometry(DRAWER_WIDTH, 1.3, 1.08),
bodyMaterial
);
body.position.y = 0.69;
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const frontMaterial = new THREE.MeshStandardMaterial({
color: COLORS.candidate,
emissive: COLORS.candidateEmissive,
emissiveIntensity: 0.45,
roughness: 0.62,
metalness: 0.12,
flatShading: true,
transparent: true,
opacity: 0.94
});
const front = new THREE.Mesh(
new THREE.BoxGeometry(DRAWER_WIDTH - 0.055, 1.12, 0.12),
frontMaterial
);
front.position.set(0, 0.7, 0.59);
front.castShadow = true;
front.receiveShadow = true;
front.userData.drawerIndex = i;
group.add(front);
frontMeshes.push(front);
const inset = new THREE.Mesh(
new THREE.BoxGeometry(DRAWER_WIDTH - 0.2, 0.86, 0.025),
new THREE.MeshStandardMaterial({
color: 0x102b3b,
roughness: 0.9,
transparent: true,
opacity: 0.35
})
);
inset.position.set(0, 0.72, 0.657);
group.add(inset);
const numberMaterial = new THREE.MeshBasicMaterial({
map: createNumberTexture(i + 1),
transparent: true,
opacity: 1,
depthWrite: false,
toneMapped: false
});
const number = new THREE.Mesh(
new THREE.PlaneGeometry(0.52, 0.42),
numberMaterial
);
number.position.set(0, 0.88, 0.666);
number.renderOrder = 2;
group.add(number);
const handle = new THREE.Mesh(
new THREE.BoxGeometry(0.38, 0.075, 0.1),
new THREE.MeshStandardMaterial({
color: 0xaec7d4,
roughness: 0.35,
metalness: 0.72,
flatShading: true
})
);
handle.position.set(0, 0.37, 0.72);
handle.castShadow = true;
group.add(handle);
const lowStripe = new THREE.Mesh(
new THREE.BoxGeometry(0.42, 0.035, 0.025),
new THREE.MeshBasicMaterial({ color: COLORS.low })
);
lowStripe.position.set(-0.27, 1.2, 0.675);
lowStripe.visible = false;
group.add(lowStripe);
const highStripe = new THREE.Mesh(
new THREE.BoxGeometry(0.42, 0.035, 0.025),
new THREE.MeshBasicMaterial({ color: COLORS.high })
);
highStripe.position.set(0.27, 1.2, 0.675);
highStripe.visible = false;
group.add(highStripe);
drawers.push({
group,
bodyMaterial,
frontMaterial,
numberMaterial,
front,
lowStripe,
highStripe,
targetColor: new THREE.Color(COLORS.candidate),
targetEmissive: new THREE.Color(COLORS.candidateEmissive),
targetBodyColor: new THREE.Color(0x17384a),
targetOpacity: 0.94,
targetBodyOpacity: 1,
targetNumberOpacity: 1
});
}
const intervalBar = new THREE.Mesh(
new THREE.BoxGeometry(1, 0.055, 0.09),
new THREE.MeshBasicMaterial({
color: 0x59d9ff,
transparent: true,
opacity: 0.72
})
);
intervalBar.position.set(0, -0.02, 1.01);
sceneRoot.add(intervalBar);
// -------------------------------------------------------------------------
// Search state and UI
// -------------------------------------------------------------------------
function setStatus(message, kind = "info") {
statusText.textContent = message;
statusBox.dataset.kind = kind;
statusKind.textContent =
kind === "success"
? "Found"
: kind === "warning"
? "Search step"
: kind === "paused"
? "Paused"
: "Ready";
}
function addTrace(message) {
trace.push(message);
if (trace.length > 12) trace.shift();
renderTrace();
}
function renderTrace() {
traceElement.replaceChildren();
if (trace.length === 0) {
const empty = document.createElement("div");
empty.className = "trace-empty";
empty.textContent =
"No comparisons yet. The midpoint starts at drawer 6.";
traceElement.appendChild(empty);
return;
}
trace.slice(-6).forEach((message) => {
const item = document.createElement("div");
item.className = "trace-item";
item.textContent = message;
traceElement.appendChild(item);
});
}
function updateUI() {
const hasInterval = low <= high;
const candidateCount = hasInterval ? high - low + 1 : 0;
lowMetric.textContent = hasInterval ? String(low + 1) : "—";
highMetric.textContent = hasInterval ? String(high + 1) : "—";
midMetric.textContent =
midpoint !== null ? String(midpoint + 1) : "—";
remainingMetric.textContent = String(candidateCount);
intervalReadout.textContent = hasInterval
? `[${low + 1}, ${high + 1}] · ${candidateCount} candidates`
: "Empty interval";
progressFill.style.width = `${
(candidateCount / DRAWER_COUNT) * 100
}%`;
searchButton.disabled = foundIndex >= 0 || !hasInterval;
autoButton.disabled = foundIndex >= 0 || !hasInterval;
}
function placeMarker(marker, index, visible) {
marker.group.visible = visible;
if (!visible || index === null || index === undefined) return;
marker.group.position.set(
drawerX[index],
marker.baseY,
0.4
);
}
function applyVisualState() {
const hasInterval = low <= high;
drawers.forEach((drawer, index) => {
const eliminated = !hasInterval || index < low || index > high;
const isFound = index === foundIndex;
const isMidpoint = index === midpoint && !isFound;
drawer.lowStripe.visible = hasInterval && index === low;
drawer.highStripe.visible = hasInterval && index === high;
if (isFound) {
drawer.targetColor.setHex(COLORS.found);
drawer.targetEmissive.setHex(COLORS.foundEmissive);
drawer.targetBodyColor.setHex(0x205c50);
drawer.targetOpacity = 1;
drawer.targetBodyOpacity = 1;
drawer.targetNumberOpacity = 1;
} else if (eliminated) {
drawer.targetColor.setHex(COLORS.eliminated);
drawer.targetEmissive.setHex(COLORS.eliminatedEmissive);
drawer.targetBodyColor.setHex(0x101b24);
drawer.targetOpacity = 0.22;
drawer.targetBodyOpacity = 0.42;
drawer.targetNumberOpacity = 0.25;
} else if (isMidpoint) {
drawer.targetColor.setHex(COLORS.midpoint);
drawer.targetEmissive.setHex(0x6a4308);
drawer.targetBodyColor.setHex(0x5e4a27);
drawer.targetOpacity = 1;
drawer.targetBodyOpacity = 1;
drawer.targetNumberOpacity = 1;
} else {
drawer.targetColor.setHex(COLORS.candidate);
drawer.targetEmissive.setHex(COLORS.candidateEmissive);
drawer.targetBodyColor.setHex(0x17384a);
drawer.targetOpacity = 0.94;
drawer.targetBodyOpacity = 1;
drawer.targetNumberOpacity = 1;
}
});
placeMarker(lowMarker, low, hasInterval);
placeMarker(highMarker, high, hasInterval);
placeMarker(
midpointMarker,
midpoint,
midpoint !== null && hasInterval
);
if (hasInterval) {
setMarkerText(lowMarker, `LOW ${low + 1}`);
setMarkerText(highMarker, `HIGH ${high + 1}`);
setMarkerText(
midpointMarker,
foundIndex === midpoint
? `MID ${midpoint + 1} ✓`
: `MID ${midpoint + 1}`
);
intervalBar.visible = true;
intervalBar.position.x =
(drawerX[low] + drawerX[high]) / 2;
intervalBar.scale.x = Math.max(
0.1,
(high - low + 1) * DRAWER_SPACING - 0.18
);
} else {
intervalBar.visible = false;
}
updateUI();
}
function resetSearch(message = "Search reset. Choose a target and begin.") {
stopAuto();
low = 0;
high = DRAWER_COUNT - 1;
midpoint = Math.floor((low + high) / 2);
foundIndex = -1;
comparisonCount = 0;
trace = [];
renderTrace();
applyVisualState();
setStatus(message);
}
function performSearchStep() {
if (foundIndex >= 0 || low > high) return;
const mid = Math.floor((low + high) / 2);
midpoint = mid;
comparisonCount++;
const midpointValue = mid + 1;
const oldLow = low + 1;
const oldHigh = high + 1;
if (target === midpointValue) {
foundIndex = mid;
addTrace(
`${target} = drawer ${midpointValue} → target found.`
);
applyVisualState();
setStatus(
`Found drawer ${target} after ${comparisonCount} comparison${
comparisonCount === 1 ? "" : "s"
}.`,
"success"
);
stopAuto();
return;
}
if (target < midpointValue) {
high = mid - 1;
addTrace(
`${target} < ${midpointValue} → discard ${midpointValue}–${oldHigh}; keep [${low + 1}, ${high + 1}].`
);
setStatus(
`Target ${target} is below drawer ${midpointValue}. The right half was discarded.`,
"warning"
);
} else {
low = mid + 1;
addTrace(
`${target} > ${midpointValue} → discard ${oldLow}–${midpointValue}; keep [${low + 1}, ${high + 1}].`
);
setStatus(
`Target ${target} is above drawer ${midpointValue}. The left half was discarded.`,
"warning"
);
}
midpoint = low <= high ? Math.floor((low + high) / 2) : null;
applyVisualState();
}
function scheduleAuto() {
clearTimeout(autoTimer);
if (!autoPlaying || foundIndex >= 0 || low > high) return;
autoTimer = window.setTimeout(() => {
performSearchStep();
scheduleAuto();
}, 850);
}
function stopAuto() {
clearTimeout(autoTimer);
autoTimer = null;
if (autoPlaying) {
autoPlaying = false;
autoButton.classList.remove("active");
autoButton.textContent = "Auto search";
}
}
function selectTarget(value, message) {
stopAuto();
target = Number(value);
targetSelect.value = String(target);
resetSearch(
message ||
`Target drawer ${target} selected. Halve the interval to search.`
);
}
targetSelect.addEventListener("change", () => {
selectTarget(targetSelect.value);
});
searchButton.addEventListener("click", () => {
stopAuto();
performSearchStep();
});
autoButton.addEventListener("click", () => {
if (autoPlaying) {
stopAuto();
setStatus("Auto search paused.", "paused");
return;
}
autoPlaying = true;
autoButton.classList.add("active");
autoButton.textContent = "Pause auto";
performSearchStep();
scheduleAuto();
});
resetButton.addEventListener("click", () => {
resetSearch();
});
randomButton.addEventListener("click", () => {
const nextTarget =
Math.floor(Math.random() * DRAWER_COUNT) + 1;
selectTarget(
nextTarget,
`Random target drawer ${nextTarget} selected.`
);
});
// -------------------------------------------------------------------------
// Custom camera controls: orbit, zoom, click selection
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let cameraTheta = 0;
let cameraPhi = 1.03;
let cameraZoom = 1;
let dragging = false;
let dragMoved = false;
let previousPointerX = 0;
let previousPointerY = 0;
function getBaseCameraRadius() {
const aspect = window.innerWidth / window.innerHeight;
const verticalFov = THREE.MathUtils.degToRad(camera.fov);
const fitWidth = TOTAL_WIDTH + 3.2;
const widthDistance =
fitWidth / (2 * Math.tan(verticalFov / 2) * aspect);
const heightDistance = 8.5 / (2 * Math.tan(verticalFov / 2));
return Math.max(22, widthDistance, heightDistance);
}
function updateCamera() {
const radius = getBaseCameraRadius() * cameraZoom;
const horizontalRadius = radius * Math.sin(cameraPhi);
camera.position.set(
horizontalRadius * Math.sin(cameraTheta),
radius * Math.cos(cameraPhi),
horizontalRadius * Math.cos(cameraTheta)
);
camera.lookAt(0, 0.48, 0);
}
function resetCameraView() {
cameraTheta = 0;
cameraPhi = 1.03;
cameraZoom = 1;
updateCamera();
}
function pickDrawer(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;
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(
frontMeshes,
false
);
return intersections.length
? intersections[0].object.userData.drawerIndex
: null;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
dragMoved = false;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (dragging) {
const deltaX = event.clientX - previousPointerX;
const deltaY = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
if (Math.abs(deltaX) + Math.abs(deltaY) > 3) {
dragMoved = true;
}
cameraTheta -= deltaX * 0.006;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi + deltaY * 0.005,
0.58,
1.38
);
updateCamera();
} else {
const selected = pickDrawer(event);
renderer.domElement.style.cursor =
selected === null ? "grab" : "pointer";
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (!dragging) return;
dragging = false;
renderer.domElement.style.cursor = "grab";
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
if (!dragMoved) {
const selected = pickDrawer(event);
if (selected !== null) {
selectTarget(
selected + 1,
`Target drawer ${selected + 1} selected by clicking its front.`
);
}
}
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
renderer.domElement.style.cursor = "grab";
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraZoom = THREE.MathUtils.clamp(
cameraZoom * (1 + event.deltaY * 0.001),
0.62,
1.65
);
updateCamera();
},
{ passive: false }
);
resetViewButton.addEventListener("click", resetCameraView);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
updateCamera();
});
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
function animate() {
const delta = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
const blend = 1 - Math.exp(-delta * 9);
drawers.forEach((drawer, index) => {
drawer.frontMaterial.color.lerp(
drawer.targetColor,
blend
);
drawer.frontMaterial.emissive.lerp(
drawer.targetEmissive,
blend
);
drawer.bodyMaterial.color.lerp(
drawer.targetBodyColor,
blend
);
drawer.frontMaterial.opacity = THREE.MathUtils.lerp(
drawer.frontMaterial.opacity,
drawer.targetOpacity,
blend
);
drawer.bodyMaterial.opacity = THREE.MathUtils.lerp(
drawer.bodyMaterial.opacity,
drawer.targetBodyOpacity,
blend
);
drawer.numberMaterial.opacity = THREE.MathUtils.lerp(
drawer.numberMaterial.opacity,
drawer.targetNumberOpacity,
blend
);
if (index === midpoint) {
drawer.front.scale.y =
1 + Math.sin(elapsed * 4.2) * 0.014;
drawer.frontMaterial.emissiveIntensity =
0.5 + Math.sin(elapsed * 4.2) * 0.18;
} else if (index === foundIndex) {
drawer.front.scale.y =
1 + Math.sin(elapsed * 5.5) * 0.025;
drawer.frontMaterial.emissiveIntensity =
0.65 + Math.sin(elapsed * 5.5) * 0.2;
} else {
drawer.front.scale.y = 1;
drawer.frontMaterial.emissiveIntensity = 0.4;
}
});
[lowMarker, midpointMarker, highMarker].forEach((marker) => {
marker.head.rotation.y += delta * 1.8;
});
midpointMarker.head.scale.setScalar(
1 + Math.sin(elapsed * 5) * 0.13
);
intervalBar.material.opacity =
0.58 + Math.sin(elapsed * 3.5) * 0.15;
renderer.render(scene, camera);
}
// Initialize the visualization.
resetCameraView();
renderTrace();
applyVisualState();
setStatus(
"Choose a target, then halve the remaining candidate interval."
);
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```