Prompt specification
Build or customize the Three.js 3D scene "Search-boundary exploration rig" 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: Search-boundary exploration rig
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/search-boundary-exploration-rig-x1852
Scene Description Prompt:
Make one HTML file using Three.js from cdnjs for this voxel scene: Let users choose targets near boundaries, duplicates, or missing values; show a precisely stated binary-search variant and handle interval updates without skipping valid candidates.
Working Three.js Starter (search-boundary-exploration-rig-x1852):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Binary Search Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #07101d;
--panel: #0d192b;
--panel-2: #111f34;
--border: #263a55;
--text: #edf5ff;
--muted: #93a7c2;
--cyan: #25d8f5;
--blue: #3978dd;
--green: #39e39b;
--purple: #aa76ff;
--pink: #ff5ca8;
--yellow: #ffd166;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
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;
}
.app {
min-height: 100vh;
display: flex;
flex-direction: column;
}
header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 17px 22px;
border-bottom: 1px solid var(--border);
background: linear-gradient(90deg, #0b1728, #091321);
z-index: 2;
}
.eyebrow {
color: var(--cyan);
font-size: 0.73rem;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
h1 {
margin: 4px 0 5px;
font-size: clamp(1.25rem, 2.3vw, 1.8rem);
line-height: 1.1;
}
.array-line {
margin: 0;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.82rem;
}
.array-line strong {
color: var(--text);
font-weight: 600;
}
.header-note {
max-width: 360px;
color: var(--muted);
font-size: 0.82rem;
line-height: 1.45;
text-align: right;
}
.workspace {
flex: 1;
min-height: 0;
display: grid;
grid-template-columns: minmax(0, 1fr) 410px;
}
#stage {
position: relative;
min-height: 620px;
overflow: hidden;
background:
radial-gradient(circle at 48% 34%, #162b48 0, #0b1728 38%, #07101d 78%);
}
#stage canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.scene-top {
position: absolute;
top: 18px;
left: 18px;
right: 18px;
z-index: 3;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 14px;
pointer-events: none;
}
.scene-title,
.target-badge {
border: 1px solid rgba(120, 160, 210, 0.25);
border-radius: 12px;
background: rgba(7, 16, 29, 0.74);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.18);
backdrop-filter: blur(8px);
}
.scene-title {
padding: 11px 13px;
}
.scene-title strong {
display: block;
font-size: 0.86rem;
}
.scene-title span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 0.73rem;
}
.target-badge {
padding: 10px 13px;
color: var(--pink);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.84rem;
white-space: nowrap;
}
.legend {
position: absolute;
z-index: 3;
left: 18px;
bottom: 18px;
display: flex;
flex-wrap: wrap;
gap: 7px;
max-width: min(660px, calc(100% - 36px));
pointer-events: none;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 8px;
border: 1px solid rgba(120, 160, 210, 0.2);
border-radius: 8px;
background: rgba(7, 16, 29, 0.76);
color: #c7d5e7;
font-size: 0.69rem;
backdrop-filter: blur(8px);
}
.swatch {
width: 9px;
height: 9px;
border-radius: 2px;
box-shadow: 0 0 8px currentColor;
}
.camera-hint {
position: absolute;
z-index: 3;
right: 18px;
bottom: 18px;
padding: 7px 10px;
border-radius: 8px;
background: rgba(7, 16, 29, 0.72);
color: var(--muted);
font-size: 0.69rem;
pointer-events: none;
}
aside {
min-height: 0;
overflow-y: auto;
padding: 14px;
border-left: 1px solid var(--border);
background: #091422;
scrollbar-color: #314967 #091422;
}
.card {
margin-bottom: 12px;
padding: 13px;
border: 1px solid var(--border);
border-radius: 13px;
background: linear-gradient(145deg, var(--panel-2), var(--panel));
}
.card h2 {
margin: 0 0 10px;
font-size: 0.82rem;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.preset-group + .preset-group {
margin-top: 11px;
}
.preset-label {
margin-bottom: 6px;
color: var(--muted);
font-size: 0.67rem;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.preset-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 6px;
}
.preset {
min-height: 35px;
padding: 6px 8px;
border: 1px solid #2b405c;
border-radius: 8px;
background: #122239;
cursor: pointer;
font-size: 0.72rem;
text-align: left;
transition: 120ms ease;
}
.preset:hover {
border-color: #4b6e98;
background: #172b46;
}
.preset.active {
border-color: var(--cyan);
background: rgba(37, 216, 245, 0.12);
box-shadow: inset 0 0 0 1px rgba(37, 216, 245, 0.13);
}
.preset small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 0.62rem;
}
.target-row {
display: grid;
grid-template-columns: 1fr 75px;
align-items: center;
gap: 10px;
margin-top: 12px;
}
input[type="range"] {
width: 100%;
accent-color: var(--cyan);
}
input[type="number"] {
width: 100%;
padding: 7px 8px;
border: 1px solid #304968;
border-radius: 8px;
outline: none;
background: #07111f;
color: var(--text);
}
input[type="number"]:focus {
border-color: var(--cyan);
}
.button-row {
display: grid;
grid-template-columns: 1.25fr 0.9fr 0.9fr;
gap: 7px;
margin-top: 11px;
}
.button {
min-height: 36px;
padding: 7px 9px;
border: 1px solid #304968;
border-radius: 8px;
background: #162a44;
cursor: pointer;
font-size: 0.76rem;
font-weight: 700;
}
.button:hover {
filter: brightness(1.12);
}
.button.primary {
border-color: #22b9d2;
background: linear-gradient(135deg, #138ea5, #17627f);
}
.speed-row {
display: grid;
grid-template-columns: auto 1fr 42px;
align-items: center;
gap: 8px;
margin-top: 10px;
color: var(--muted);
font-size: 0.7rem;
}
.status-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.status-box {
min-height: 64px;
padding: 9px;
border: 1px solid #263d59;
border-radius: 9px;
background: #0a1626;
}
.status-box.wide {
grid-column: 1 / -1;
}
.status-box span {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 0.64rem;
font-weight: 750;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.status-box strong {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.86rem;
line-height: 1.35;
}
.cyan {
color: var(--cyan);
}
.green {
color: var(--green);
}
.purple {
color: var(--purple);
}
.pink {
color: var(--pink);
}
pre {
margin: 9px 0;
overflow-x: auto;
padding: 11px;
border: 1px solid #293e59;
border-radius: 9px;
background: #07111f;
color: #d9e9ff;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.72rem;
line-height: 1.5;
}
.definition {
margin: 0;
color: #c8d8ec;
font-size: 0.76rem;
line-height: 1.48;
}
.invariant {
margin-top: 9px;
padding: 9px;
border-left: 3px solid var(--blue);
border-radius: 0 7px 7px 0;
background: rgba(57, 120, 221, 0.08);
color: #c9d8eb;
font-size: 0.71rem;
line-height: 1.45;
}
.safe-note {
margin-top: 8px;
padding: 9px;
border: 1px solid rgba(255, 209, 102, 0.28);
border-radius: 8px;
background: rgba(255, 209, 102, 0.07);
color: #f8dfa8;
font-size: 0.71rem;
line-height: 1.45;
}
.trace-list {
max-height: 275px;
overflow-y: auto;
scrollbar-color: #314967 #091422;
}
.empty-trace {
padding: 13px 4px;
color: var(--muted);
font-size: 0.74rem;
line-height: 1.45;
}
.trace-row {
padding: 9px 0;
border-top: 1px solid #233750;
}
.trace-row:first-child {
border-top: 0;
}
.trace-main {
color: #e7f1ff;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.7rem;
line-height: 1.45;
}
.trace-reason {
margin-top: 4px;
color: var(--muted);
font-size: 0.68rem;
line-height: 1.4;
}
.trace-index {
margin-right: 6px;
color: var(--cyan);
}
@media (max-width: 980px) {
.workspace {
display: block;
}
#stage {
min-height: 68vh;
}
aside {
overflow: visible;
border-top: 1px solid var(--border);
border-left: 0;
}
.header-note {
display: none;
}
}
@media (max-width: 560px) {
header {
padding: 14px;
}
.array-line {
font-size: 0.68rem;
overflow-wrap: anywhere;
}
#stage {
min-height: 570px;
}
.scene-title span,
.camera-hint {
display: none;
}
.legend {
gap: 4px;
}
.legend-item {
font-size: 0.61rem;
}
}
</style>
</head>
<body>
<div class="app">
<header>
<div>
<div class="eyebrow">Interactive search laboratory</div>
<h1>Voxel Binary Search</h1>
<p class="array-line">
A =
<strong>[2, 4, 4, 7, 11, 11, 11, 16, 19, 23, 29, 31]</strong>
</p>
</div>
<div class="header-note">
Explore the first-index lower-bound variant on a sorted array containing
duplicates and gaps.
</div>
</header>
<main class="workspace">
<section id="stage" aria-label="Interactive three-dimensional voxel search scene">
<div class="scene-top">
<div class="scene-title">
<strong>Sorted voxel towers</strong>
<span>Height and label both represent the stored value.</span>
</div>
<div class="target-badge" id="targetBadge">target x = 2</div>
</div>
<div class="legend" aria-hidden="true">
<div class="legend-item">
<span class="swatch" style="color:#3978dd;background:#3978dd"></span>
active interval
</div>
<div class="legend-item">
<span class="swatch" style="color:#25d8f5;background:#25d8f5"></span>
midpoint
</div>
<div class="legend-item">
<span class="swatch" style="color:#39e39b;background:#39e39b"></span>
first match
</div>
<div class="legend-item">
<span class="swatch" style="color:#aa76ff;background:#aa76ff"></span>
equal duplicates
</div>
<div class="legend-item">
<span class="swatch" style="color:#ff5ca8;background:#ff5ca8"></span>
target / insertion
</div>
</div>
<div class="camera-hint">
Drag to orbit · wheel to zoom · click a tower to select its value
</div>
</section>
<aside>
<section class="card">
<h2>Choose a target</h2>
<div class="preset-group">
<div class="preset-label">Array boundaries</div>
<div class="preset-grid">
<button class="preset active" data-target="2">
First value
<small>x = 2</small>
</button>
<button class="preset" data-target="3">
Just above first
<small>x = 3 · missing</small>
</button>
<button class="preset" data-target="29">
One below last
<small>x = 29</small>
</button>
<button class="preset" data-target="31">
Last value
<small>x = 31</small>
</button>
<button class="preset" data-target="32">
Past the end
<small>x = 32 · insertion n</small>
</button>
</div>
</div>
<div class="preset-group">
<div class="preset-label">Duplicate values</div>
<div class="preset-grid">
<button class="preset" data-target="4">
Two copies
<small>x = 4</small>
</button>
<button class="preset" data-target="11">
Three copies
<small>x = 11</small>
</button>
</div>
</div>
<div class="preset-group">
<div class="preset-label">Missing values</div>
<div class="preset-grid">
<button class="preset" data-target="6">
Between 4 and 7
<small>x = 6</small>
</button>
<button class="preset" data-target="13">
Between 11 and 16
<small>x = 13</small>
</button>
<button class="preset" data-target="30">
Between 29 and 31
<small>x = 30</small>
</button>
</div>
</div>
<div class="target-row">
<input
id="targetRange"
type="range"
min="0"
max="33"
step="1"
value="2"
aria-label="Search target"
>
<input
id="targetNumber"
type="number"
min="0"
max="33"
step="1"
value="2"
aria-label="Numeric search target"
>
</div>
<div class="button-row">
<button class="button primary" id="playButton">Play</button>
<button class="button" id="stepButton">Step</button>
<button class="button" id="resetButton">Reset</button>
</div>
<div class="speed-row">
<label for="speedRange">Speed</label>
<input id="speedRange" type="range" min="1" max="5" value="3">
<span id="speedLabel">3×</span>
</div>
</section>
<section class="card">
<h2>Live state</h2>
<div class="status-grid">
<div class="status-box">
<span>Remaining interval</span>
<strong class="cyan" id="intervalState">[0, 12)</strong>
</div>
<div class="status-box">
<span>Candidate</span>
<strong id="candidateState">not selected</strong>
</div>
<div class="status-box wide">
<span>Last comparison</span>
<strong id="decisionState">—</strong>
</div>
<div class="status-box wide">
<span>Result</span>
<strong id="resultState" aria-live="polite">
Press Play or Step to run the search.
</strong>
</div>
</div>
</section>
<section class="card">
<h2>Precisely stated variant</h2>
<p class="definition">
<strong>Lower-bound search:</strong> return the first index
<strong>p</strong> such that <strong>A[p] ≥ x</strong>. If no value
equals x, p is the insertion position.
</p>
<pre><code>lowerBound(x):
L = 0; R = n
while L < R:
m = L + floor((R - L) / 2)
if A[m] < x:
L = m + 1
else:
R = m
return L</code></pre>
<div class="invariant">
<strong>Interval invariant:</strong> every index below L has a value
< x, and every index at or above R has a value ≥ x. Therefore the
lower bound remains inside the half-open interval [L, R).
</div>
<div class="safe-note">
<strong>Why R = m is safe:</strong> when A[m] = x, index m remains a
valid candidate. Using R = m − 1 would incorrectly discard it and
could skip the first equal-valued index.
</div>
<p class="definition" style="margin-top:9px">
For duplicate handling, after finding p = lowerBound(x), the same
routine at x + 1 gives q. All equal-valued candidate indices are
exactly the half-open range <strong>[p, q)</strong>.
</p>
</section>
<section class="card">
<h2>Comparison trace</h2>
<div class="trace-list" id="traceList">
<div class="empty-trace">
No comparisons yet. The trace records both the interval before and
after every update.
</div>
</div>
</section>
</aside>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Search data and state
// -------------------------------------------------------------------------
const values = Object.freeze([
2, 4, 4, 7, 11, 11, 11, 16, 19, 23, 29, 31
]);
const n = values.length;
const state = {
target: 2,
lo: 0,
hi: n,
mid: null,
decision: "—",
step: 0,
running: false,
done: false,
resultP: null,
resultQ: null,
trace: [],
timer: null
};
const stage = document.getElementById("stage");
const targetRange = document.getElementById("targetRange");
const targetNumber = document.getElementById("targetNumber");
const playButton = document.getElementById("playButton");
const stepButton = document.getElementById("stepButton");
const resetButton = document.getElementById("resetButton");
const speedRange = document.getElementById("speedRange");
const speedLabel = document.getElementById("speedLabel");
const traceList = document.getElementById("traceList");
const delays = [1400, 1000, 650, 350, 120];
// This is the exact same lower-bound routine used by the animation.
function lowerBound(array, x) {
let L = 0;
let R = array.length;
while (L < R) {
const m = L + Math.floor((R - L) / 2);
if (array[m] < x) {
L = m + 1;
} else {
R = m;
}
}
return L;
}
function stopTimer() {
if (state.timer !== null) {
clearTimeout(state.timer);
state.timer = null;
}
}
function pauseSearch() {
state.running = false;
stopTimer();
updatePlayButton();
}
function updatePlayButton() {
if (state.running) {
playButton.textContent = "Pause";
} else if (state.done) {
playButton.textContent = "Replay";
} else if (state.step > 0) {
playButton.textContent = "Continue";
} else {
playButton.textContent = "Play";
}
}
function resetSearch() {
stopTimer();
state.target = Number(targetNumber.value);
state.lo = 0;
state.hi = n;
state.mid = null;
state.decision = "—";
state.step = 0;
state.running = false;
state.done = false;
state.resultP = null;
state.resultQ = null;
state.trace = [];
renderTrace();
refreshUI();
refreshScene();
updatePlayButton();
}
function finishSearch() {
state.done = true;
state.running = false;
stopTimer();
const p = state.lo;
const q = lowerBound(values, state.target + 1);
state.resultP = p;
state.resultQ = q;
updatePlayButton();
}
function performStep() {
if (state.done) return;
const beforeL = state.lo;
const beforeR = state.hi;
if (beforeL >= beforeR) {
finishSearch();
refreshUI();
refreshScene();
return;
}
const m = beforeL + Math.floor((beforeR - beforeL) / 2);
const value = values[m];
let relation;
let reason;
if (value < state.target) {
relation = "<";
state.lo = m + 1;
reason =
`A[${m}] < x. Because the array is sorted, every index through ` +
`${m} is too small, so L = m + 1.`;
} else if (value > state.target) {
relation = ">";
state.hi = m;
reason =
`A[${m}] > x. Every index from ${m} onward is too large, so ` +
`R = m.`;
} else {
relation = "=";
state.hi = m;
reason =
`A[${m}] = x. Index ${m} remains a possible first candidate, so ` +
`R = m — deliberately not m − 1.`;
}
state.mid = m;
state.decision = `${value} ${relation} ${state.target}`;
state.step++;
state.trace.push({
step: state.step,
beforeL,
beforeR,
m,
value,
relation,
afterL: state.lo,
afterR: state.hi,
reason
});
if (state.lo === state.hi) {
finishSearch();
}
renderTrace();
refreshUI();
refreshScene();
}
function scheduleNextStep() {
stopTimer();
if (!state.running || state.done) return;
state.timer = setTimeout(() => {
state.timer = null;
performStep();
if (state.running && !state.done) {
scheduleNextStep();
}
}, delays[Number(speedRange.value) - 1]);
}
function startSearch() {
if (state.done) {
resetSearch();
}
state.running = true;
updatePlayButton();
scheduleNextStep();
}
function setTarget(value) {
const numericValue = Math.max(
0,
Math.min(33, Math.round(Number(value)))
);
targetRange.value = String(numericValue);
targetNumber.value = String(numericValue);
resetSearch();
document.querySelectorAll(".preset").forEach((button) => {
button.classList.toggle(
"active",
Number(button.dataset.target) === numericValue
);
});
}
function renderTrace() {
traceList.replaceChildren();
if (state.trace.length === 0) {
const empty = document.createElement("div");
empty.className = "empty-trace";
empty.textContent =
"No comparisons yet. The trace records both the interval before and " +
"after every update.";
traceList.append(empty);
return;
}
state.trace.forEach((entry) => {
const row = document.createElement("div");
row.className = "trace-row";
const main = document.createElement("div");
main.className = "trace-main";
const index = document.createElement("span");
index.className = "trace-index";
index.textContent = `#${entry.step}`;
main.append(
index,
document.createTextNode(
`[${entry.beforeL}, ${entry.beforeR}) ` +
`m = ${entry.m}, A[m] = ${entry.value} ${entry.relation} x → ` +
`[${entry.afterL}, ${entry.afterR})`
)
);
const reason = document.createElement("div");
reason.className = "trace-reason";
reason.textContent = entry.reason;
row.append(main, reason);
traceList.append(row);
});
traceList.scrollTop = traceList.scrollHeight;
}
function refreshUI() {
document.getElementById("targetBadge").textContent =
`target x = ${state.target}`;
document.getElementById("intervalState").textContent =
`[${state.lo}, ${state.hi})`;
document.getElementById("candidateState").textContent =
state.mid === null
? "not selected"
: `m = ${state.mid}, A[m] = ${values[state.mid]}`;
document.getElementById("decisionState").textContent = state.decision;
const resultElement = document.getElementById("resultState");
if (!state.done) {
resultElement.className = "";
resultElement.textContent =
state.step === 0
? "Press Play or Step to run the search."
: "Search in progress. The lower bound remains in the live interval.";
return;
}
const p = state.resultP;
const q = state.resultQ;
const exact = p < n && values[p] === state.target;
if (exact) {
const count = q - p;
resultElement.className = "green";
resultElement.textContent =
`Exact match. Canonical first index p = ${p}. ` +
`All equal-valued candidates are [${p}, ${q}) — ${count} index` +
`${count === 1 ? "" : "es"}.`;
} else {
resultElement.className = "pink";
resultElement.textContent =
`No value equals x. lower_bound = ${p}, an insertion point ` +
(p < n
? `before A[${p}] = ${values[p]}.`
: "at the end of the array.");
}
}
// -------------------------------------------------------------------------
// Three.js voxel scene
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.fog = new THREE.FogExp2(0x07101d, 0.018);
const camera = new THREE.PerspectiveCamera(
42,
1,
0.1,
160
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.18;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute(
"aria-label",
"Three-dimensional visualization of the sorted array and binary-search interval"
);
stage.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xb8ddff, 0x172033, 2.1);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.5);
keyLight.position.set(8, 18, 11);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -20;
keyLight.shadow.camera.right = 20;
keyLight.shadow.camera.top = 22;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 60;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x21d4fd, 35, 30, 2);
cyanLight.position.set(-9, 6, 7);
scene.add(cyanLight);
const pinkLight = new THREE.PointLight(0xff4f9c, 22, 26, 2);
pinkLight.position.set(10, 8, -7);
scene.add(pinkLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(60, 60),
new THREE.MeshStandardMaterial({
color: 0x081321,
roughness: 0.92,
metalness: 0.04
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.055;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(52, 52, 0x345170, 0x182b42);
grid.position.y = -0.045;
grid.material.transparent = true;
grid.material.opacity = 0.3;
scene.add(grid);
const BLOCK = 0.43;
const SPACING = 1.18;
const CUBE_WIDTH = 0.74;
const cubeGeometry = new THREE.BoxGeometry(1, 1, 1);
const itemMaterials = [];
const padMaterials = [];
const pickMeshes = [];
const colors = {
outside: new THREE.Color("#243552"),
active: new THREE.Color("#3978dd"),
candidate: new THREE.Color("#25d8f5"),
first: new THREE.Color("#39e39b"),
duplicate: new THREE.Color("#aa76ff"),
target: new THREE.Color("#ff5ca8")
};
function makeTowerLabel(index, value) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 76;
const context = canvas.getContext("2d");
context.fillStyle = "rgba(6, 14, 27, 0.88)";
context.fillRect(4, 4, 248, 68);
context.strokeStyle = "rgba(135, 180, 225, 0.45)";
context.lineWidth = 2;
context.strokeRect(4, 4, 248, 68);
context.fillStyle = "#dceeff";
context.font = "700 27px ui-monospace, monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(`i ${index} • v ${value}`, 128, 38);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(1.25, 0.37, 1);
sprite.renderOrder = 20;
return sprite;
}
function xForIndex(index) {
return (index - (n - 1) / 2) * SPACING;
}
values.forEach((value, index) => {
const x = xForIndex(index);
const padMaterial = new THREE.MeshStandardMaterial({
color: 0x12213a,
emissive: 0x0b1830,
emissiveIntensity: 0.4,
roughness: 0.72,
metalness: 0.12
});
const pad = new THREE.Mesh(
new THREE.BoxGeometry(0.92, 0.06, 1.28),
padMaterial
);
pad.position.set(x, 0.03, 0);
pad.receiveShadow = true;
scene.add(pad);
padMaterials.push(padMaterial);
const material = new THREE.MeshStandardMaterial({
color: colors.outside,
emissive: colors.outside,
emissiveIntensity: 0.16,
roughness: 0.43,
metalness: 0.14
});
itemMaterials.push(material);
for (let level = 0; level < value; level++) {
const cube = new THREE.Mesh(cubeGeometry, material);
cube.scale.set(CUBE_WIDTH, BLOCK - 0.035, CUBE_WIDTH);
cube.position.set(x, level * BLOCK + BLOCK / 2, 0);
cube.castShadow = true;
cube.receiveShadow = true;
cube.userData.arrayIndex = index;
pickMeshes.push(cube);
scene.add(cube);
}
const label = makeTowerLabel(index, value);
label.position.set(x, value * BLOCK + 0.48, 0);
scene.add(label);
});
// Midpoint cage.
const candidateGroup = new THREE.Group();
const candidateFillMaterial = new THREE.MeshBasicMaterial({
color: colors.candidate,
transparent: true,
opacity: 0.09,
depthWrite: false
});
const candidateEdgeMaterial = new THREE.LineBasicMaterial({
color: colors.candidate,
transparent: true,
opacity: 0.95
});
candidateGroup.add(
new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
candidateFillMaterial
)
);
candidateGroup.add(
new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(1, 1, 1)),
candidateEdgeMaterial
)
);
scene.add(candidateGroup);
// Horizontal plane at the selected target value.
const targetPlane = new THREE.Mesh(
new THREE.PlaneGeometry(16.2, 4.6),
new THREE.MeshBasicMaterial({
color: colors.target,
transparent: true,
opacity: 0.12,
side: THREE.DoubleSide,
depthWrite: false
})
);
targetPlane.rotation.x = -Math.PI / 2;
scene.add(targetPlane);
const targetOutline = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.PlaneGeometry(16.2, 4.6)),
new THREE.LineBasicMaterial({
color: colors.target,
transparent: true,
opacity: 0.72
})
);
targetOutline.rotation.x = -Math.PI / 2;
scene.add(targetOutline);
// Final insertion-position marker.
const insertionMarker = new THREE.Group();
const insertionLine = new THREE.Mesh(
new THREE.CylinderGeometry(0.035, 0.035, 11.8, 8),
new THREE.MeshBasicMaterial({
color: colors.target,
transparent: true,
opacity: 0.88
})
);
insertionLine.position.y = 5.9;
const insertionRing = new THREE.Mesh(
new THREE.RingGeometry(0.28, 0.4, 32),
new THREE.MeshBasicMaterial({
color: colors.target,
side: THREE.DoubleSide,
transparent: true,
opacity: 0.9
})
);
insertionRing.rotation.x = -Math.PI / 2;
insertionRing.position.y = 0.055;
insertionMarker.add(insertionLine, insertionRing);
insertionMarker.visible = false;
scene.add(insertionMarker);
function insertionX(index) {
if (index === 0) return xForIndex(0) - SPACING * 0.5;
if (index === n) return xForIndex(n - 1) + SPACING * 0.5;
return (xForIndex(index - 1) + xForIndex(index)) * 0.5;
}
function refreshScene() {
const exact =
state.done &&
state.resultP < n &&
values[state.resultP] === state.target;
for (let index = 0; index < n; index++) {
let color = colors.outside;
let emissiveIntensity = 0.12;
if (
state.done &&
exact &&
index >= state.resultP &&
index < state.resultQ
) {
if (index === state.resultP) {
color = colors.first;
emissiveIntensity = 0.7;
} else {
color = colors.duplicate;
emissiveIntensity = 0.55;
}
} else if (state.mid === index && !state.done) {
color = colors.candidate;
emissiveIntensity = 0.72;
} else if (index >= state.lo && index < state.hi) {
color = colors.active;
emissiveIntensity = 0.3;
}
itemMaterials[index].color.copy(color);
itemMaterials[index].emissive.copy(color);
itemMaterials[index].emissiveIntensity = emissiveIntensity;
padMaterials[index].color.copy(color).multiplyScalar(0.38);
padMaterials[index].emissive.copy(color);
padMaterials[index].emissiveIntensity = 0.22;
}
if (state.mid !== null && !state.done) {
const height = values[state.mid] * BLOCK;
candidateGroup.visible = true;
candidateGroup.position.set(
xForIndex(state.mid),
height / 2,
0
);
candidateGroup.scale.set(
CUBE_WIDTH + 0.09,
height + 0.04,
CUBE_WIDTH + 0.09
);
} else {
candidateGroup.visible = false;
}
const targetHeight = state.target * BLOCK;
targetPlane.position.y = targetHeight;
targetOutline.position.y = targetHeight + 0.005;
if (state.done) {
insertionMarker.visible = true;
insertionMarker.position.x = insertionX(state.resultP);
const markerColor = exact ? colors.first : colors.target;
insertionLine.material.color.copy(markerColor);
insertionRing.material.color.copy(markerColor);
} else {
insertionMarker.visible = false;
}
}
// -------------------------------------------------------------------------
// Direct camera controls: orbit, zoom, and tower picking
// -------------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 5.6, 0);
let cameraRadius = 28;
let cameraYaw = -0.28;
let cameraPolar = 1.02;
function updateCamera() {
const horizontal = cameraRadius * Math.sin(cameraPolar);
camera.position.set(
cameraTarget.x + horizontal * Math.sin(cameraYaw),
cameraTarget.y + cameraRadius * Math.cos(cameraPolar),
cameraTarget.z + horizontal * Math.cos(cameraYaw)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraRadius = 28;
cameraYaw = -0.28;
cameraPolar = 1.02;
updateCamera();
}
updateCamera();
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let dragging = false;
let pointerId = null;
let previousX = 0;
let previousY = 0;
let dragDistance = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
pointerId = event.pointerId;
previousX = event.clientX;
previousY = event.clientY;
dragDistance = 0;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging || event.pointerId !== pointerId) return;
const deltaX = event.clientX - previousX;
const deltaY = event.clientY - previousY;
dragDistance += Math.abs(deltaX) + Math.abs(deltaY);
previousX = event.clientX;
previousY = event.clientY;
cameraYaw -= deltaX * 0.006;
cameraPolar = THREE.MathUtils.clamp(
cameraPolar + deltaY * 0.005,
0.34,
1.46
);
updateCamera();
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (!dragging || event.pointerId !== pointerId) return;
dragging = false;
renderer.domElement.releasePointerCapture(event.pointerId);
// A short pointer press selects the value of the clicked tower.
if (dragDistance < 5) {
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 hits = raycaster.intersectObjects(pickMeshes, false);
if (hits.length > 0) {
const index = hits[0].object.userData.arrayIndex;
setTarget(values[index]);
}
}
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
14,
48
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
window.addEventListener("keydown", (event) => {
if (event.key === "ArrowLeft") {
cameraYaw += 0.08;
updateCamera();
} else if (event.key === "ArrowRight") {
cameraYaw -= 0.08;
updateCamera();
} else if (event.key === "ArrowUp") {
cameraPolar = Math.max(0.34, cameraPolar - 0.06);
updateCamera();
} else if (event.key === "ArrowDown") {
cameraPolar = Math.min(1.46, cameraPolar + 0.06);
updateCamera();
}
});
// -------------------------------------------------------------------------
// UI events and rendering
// -------------------------------------------------------------------------
document.querySelectorAll(".preset").forEach((button) => {
button.addEventListener("click", () => {
setTarget(button.dataset.target);
});
});
targetRange.addEventListener("input", () => {
setTarget(targetRange.value);
});
targetNumber.addEventListener("change", () => {
setTarget(targetNumber.value);
});
playButton.addEventListener("click", () => {
if (state.running) {
pauseSearch();
} else {
startSearch();
}
});
stepButton.addEventListener("click", () => {
pauseSearch();
performStep();
});
resetButton.addEventListener("click", resetSearch);
speedRange.addEventListener("input", () => {
speedLabel.textContent = `${speedRange.value}×`;
});
const resizeObserver = new ResizeObserver(() => {
const width = stage.clientWidth;
const height = stage.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / Math.max(height, 1);
camera.updateProjectionMatrix();
});
resizeObserver.observe(stage);
function animate(time) {
requestAnimationFrame(animate);
const pulse = 0.5 + 0.5 * Math.sin(time * 0.0045);
candidateEdgeMaterial.opacity = 0.68 + pulse * 0.32;
candidateFillMaterial.opacity = 0.055 + pulse * 0.055;
targetPlane.material.opacity = 0.08 + pulse * 0.065;
renderer.render(scene, camera);
}
refreshUI();
refreshScene();
requestAnimationFrame(animate);
</script>
</body>
</html>
```