Prompt specification
Build or customize the Three.js 3D scene "Sorting workshop scaling exhibit" 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: Sorting workshop scaling exhibit
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/sorting-workshop-scaling-exhibit-x1843
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows algorithmic complexity and operation counts. Compose synthetic workloads of increasing size beside counted comparisons from chosen algorithms; label the counts measured in the toy implementation rather than universal wall-clock speed. Voxel style.
Working Three.js Starter (sorting-workshop-scaling-exhibit-x1843):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Complexity Lab — Voxel Comparison Workbench</title>
<style>
:root {
--bg: #070b14;
--panel: #0d1422;
--panel-2: #111c2e;
--line: #263650;
--text: #edf4ff;
--muted: #8494ad;
--cyan: #4de2c2;
--blue: #67a8ff;
--coral: #ff6f73;
--yellow: #ffc857;
--purple: #b892ff;
--green: #72d88a;
--shadow: 5px 5px 0 #02040a;
}
* {
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;
}
body {
overflow: hidden;
}
button,
select,
input {
font: inherit;
}
button,
select {
color: var(--text);
}
.app {
display: grid;
grid-template-rows: auto minmax(0, 1fr);
height: 100vh;
}
header {
position: relative;
z-index: 10;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
min-height: 84px;
padding: 16px 22px;
border-bottom: 2px solid var(--line);
background:
linear-gradient(90deg, rgba(77, 226, 194, 0.07), transparent 38%),
#0a111e;
box-shadow: 0 5px 0 rgba(0, 0, 0, 0.25);
}
.brand {
display: flex;
align-items: center;
gap: 14px;
min-width: 0;
}
.brand-mark {
position: relative;
width: 42px;
height: 42px;
flex: 0 0 auto;
background: var(--cyan);
border: 2px solid #071017;
box-shadow:
5px 5px 0 #163d43,
-5px -5px 0 #16313e;
transform: rotate(-4deg);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
background: #071017;
}
.brand-mark::before {
width: 22px;
height: 7px;
left: 8px;
top: 8px;
box-shadow: 0 12px 0 #071017;
}
.brand-mark::after {
width: 7px;
height: 22px;
right: 8px;
top: 8px;
}
.brand h1 {
margin: 0;
font-size: clamp(18px, 2vw, 27px);
line-height: 1;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.brand p {
margin: 7px 0 0;
color: var(--muted);
font-size: 12px;
letter-spacing: 0.04em;
}
.header-note {
max-width: 430px;
padding: 10px 13px;
border: 1px solid #3c536f;
background: #101a2a;
box-shadow: var(--shadow);
color: #b8c8dd;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.45;
text-transform: uppercase;
}
.header-note strong {
color: var(--yellow);
}
main {
display: grid;
grid-template-columns: minmax(0, 1fr) 355px;
min-height: 0;
}
.stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 35%, rgba(52, 87, 126, 0.17), transparent 48%),
#070b14;
}
.stage canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
outline: none;
cursor: grab;
touch-action: none;
}
.stage canvas:active {
cursor: grabbing;
}
.stage-top {
position: absolute;
z-index: 3;
top: 18px;
left: 20px;
right: 20px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 20px;
pointer-events: none;
}
.stage-title {
max-width: 470px;
padding: 12px 14px;
border-left: 4px solid var(--cyan);
background: rgba(8, 14, 25, 0.86);
box-shadow: var(--shadow);
}
.eyebrow {
margin: 0 0 6px;
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.stage-title h2 {
margin: 0;
font-size: clamp(15px, 1.8vw, 22px);
line-height: 1.12;
text-transform: uppercase;
}
.stage-title p {
margin: 7px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.4;
}
.legend {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 7px;
max-width: 390px;
padding: 10px;
border: 1px solid var(--line);
background: rgba(8, 14, 25, 0.86);
box-shadow: var(--shadow);
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 5px 7px;
background: #121d2f;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
white-space: nowrap;
}
.legend-item i {
width: 9px;
height: 9px;
background: var(--accent);
box-shadow: 2px 2px 0 rgba(0, 0, 0, 0.4);
}
.stage-bottom {
position: absolute;
z-index: 3;
right: 18px;
bottom: 16px;
left: 18px;
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 14px;
pointer-events: none;
}
.scale-note,
.camera-note {
padding: 9px 11px;
border: 1px solid var(--line);
background: rgba(8, 14, 25, 0.88);
color: #a8b8cd;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.4;
}
.scale-note strong {
color: var(--cyan);
}
.camera-note {
text-align: right;
}
.view-buttons {
display: flex;
gap: 7px;
margin-top: 8px;
pointer-events: auto;
}
.mini-button {
padding: 7px 9px;
border: 1px solid #3a4e6d;
border-radius: 0;
background: #111c2e;
color: #dce8f7;
box-shadow: 3px 3px 0 #02040a;
cursor: pointer;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 800;
text-transform: uppercase;
}
.mini-button:hover,
.mini-button.active {
border-color: var(--cyan);
color: var(--cyan);
}
aside {
min-height: 0;
overflow: auto;
border-left: 2px solid var(--line);
background: #0a111e;
scrollbar-color: #344864 #0a111e;
}
.control-section {
padding: 17px 18px;
border-bottom: 1px solid var(--line);
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 13px;
}
.section-heading h3 {
margin: 0;
font-size: 12px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.section-heading span {
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
text-transform: uppercase;
}
.algorithm-list {
display: grid;
gap: 7px;
}
.algorithm-option {
display: grid;
grid-template-columns: 18px 12px minmax(0, 1fr);
align-items: center;
gap: 8px;
padding: 9px 10px;
border: 1px solid #253550;
background: #101a2a;
cursor: pointer;
}
.algorithm-option:hover {
border-color: #49617e;
background: #132035;
}
.algorithm-option input {
width: 14px;
height: 14px;
margin: 0;
accent-color: var(--accent);
}
.algorithm-option .swatch {
width: 10px;
height: 10px;
background: var(--accent);
box-shadow: 2px 2px 0 rgba(0, 0, 0, 0.45);
}
.algorithm-option strong {
display: block;
font-size: 12px;
}
.algorithm-option small {
display: block;
margin-top: 2px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
}
.field-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.field label {
display: block;
margin-bottom: 6px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
select {
width: 100%;
height: 38px;
padding: 0 10px;
border: 1px solid #354b68;
border-radius: 0;
background: #111c2e;
outline: none;
font-size: 12px;
}
select:focus {
border-color: var(--cyan);
}
select:disabled {
opacity: 0.55;
}
.hint {
margin: 10px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.hint strong {
color: #c9d7e8;
}
.segmented {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 5px;
padding: 4px;
border: 1px solid #2d405e;
background: #080f1b;
}
.segmented button {
padding: 8px;
border: 1px solid transparent;
border-radius: 0;
background: transparent;
color: var(--muted);
cursor: pointer;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
font-weight: 800;
text-transform: uppercase;
}
.segmented button.active {
border-color: #4c6c91;
background: #17253a;
color: var(--cyan);
}
.check-row {
display: flex;
align-items: center;
gap: 8px;
margin-top: 12px;
color: #b6c5d9;
font-size: 11px;
}
.check-row input {
accent-color: var(--cyan);
}
.table-wrap {
overflow-x: auto;
border: 1px solid #2b3d59;
}
table {
width: 100%;
border-collapse: collapse;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
}
th,
td {
padding: 9px 8px;
border-bottom: 1px solid #23334d;
border-right: 1px solid #23334d;
text-align: right;
white-space: nowrap;
}
th:last-child,
td:last-child {
border-right: 0;
}
tbody tr:last-child td {
border-bottom: 0;
}
th {
background: #152136;
color: #dce8f6;
font-size: 9px;
}
td:first-child,
th:first-child {
text-align: left;
}
.table-alg {
display: inline-flex;
align-items: center;
gap: 5px;
}
.table-alg i {
width: 7px;
height: 7px;
background: var(--accent);
}
.export-button {
width: 100%;
margin-top: 9px;
padding: 9px;
border: 1px solid #3a4f6d;
border-radius: 0;
background: #142136;
color: #cbd9ea;
box-shadow: 3px 3px 0 #02040a;
cursor: pointer;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 800;
text-transform: uppercase;
}
.export-button:hover {
border-color: var(--cyan);
color: var(--cyan);
}
.method-note {
padding: 15px 18px 22px;
color: #899ab3;
font-size: 10px;
line-height: 1.6;
}
.method-note strong {
color: var(--yellow);
}
.method-note code {
color: #d3e0ef;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.tooltip {
position: absolute;
z-index: 8;
display: none;
min-width: 190px;
padding: 10px 12px;
border: 1px solid #4c6484;
background: rgba(7, 13, 24, 0.96);
box-shadow: 4px 4px 0 #02040a;
pointer-events: none;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.5;
}
.tooltip strong {
display: block;
margin-bottom: 3px;
color: var(--accent);
}
.loading {
position: absolute;
z-index: 20;
inset: 0;
display: grid;
place-items: center;
background: #070b14;
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
@media (max-width: 980px) {
body {
overflow: auto;
}
.app {
height: auto;
min-height: 100vh;
}
main {
grid-template-columns: 1fr;
}
.stage {
height: 68vh;
min-height: 520px;
}
aside {
border-top: 2px solid var(--line);
border-left: 0;
}
.header-note {
display: none;
}
}
@media (max-width: 600px) {
header {
padding: 14px;
}
.brand p {
max-width: 230px;
}
.stage {
height: 62vh;
min-height: 470px;
}
.stage-top {
top: 10px;
right: 10px;
left: 10px;
}
.stage-title {
max-width: 58%;
}
.legend {
max-width: 42%;
padding: 6px;
}
.legend-item {
padding: 4px;
font-size: 8px;
}
.stage-bottom {
right: 10px;
bottom: 10px;
left: 10px;
}
.camera-note {
display: none;
}
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>Complexity Lab</h1>
<p>Synthetic workloads · instrumented comparisons · voxel workbench</p>
</div>
</div>
<div class="header-note">
<strong>Measured toy counts</strong> — not wall-clock speed.<br />
Every number is a comparator call in the implementation shown here.
</div>
</header>
<main>
<section class="stage" id="stage" aria-label="Interactive 3D comparison chart">
<div class="loading" id="loading">Building voxel workbench…</div>
<div class="stage-top">
<div class="stage-title">
<p class="eyebrow">Experiment / instrumented key comparisons</p>
<h2 id="experimentTitle">Descending workloads</h2>
<p id="experimentSubtitle">Increasing synthetic arrays, measured beside comparison towers.</p>
</div>
<div class="legend" id="legend" aria-label="Algorithm legend"></div>
</div>
<div class="stage-bottom">
<div class="scale-note" id="scaleNote"></div>
<div class="camera-note">
Drag to orbit · wheel to zoom · hover a tower
<div class="view-buttons">
<button class="mini-button" id="resetView" type="button">Reset view</button>
<button class="mini-button" id="autoOrbit" type="button">Auto orbit</button>
<button class="mini-button" id="replay" type="button">Replay</button>
</div>
</div>
</div>
<div class="tooltip" id="tooltip"></div>
</section>
<aside>
<section class="control-section">
<div class="section-heading">
<h3>01 / Algorithm stack</h3>
<span>Choose up to 3</span>
</div>
<div class="algorithm-list" id="algorithmList"></div>
<p class="hint" id="algorithmHint"></p>
</section>
<section class="control-section">
<div class="section-heading">
<h3>02 / Workload recipe</h3>
<span>Deterministic</span>
</div>
<div class="field-grid">
<div class="field">
<label for="pattern">Array pattern</label>
<select id="pattern">
<option value="ascending">Ascending</option>
<option value="descending">Descending</option>
<option value="shuffled">Seeded shuffle</option>
<option value="nearly">Nearly sorted</option>
</select>
</div>
<div class="field">
<label for="maxSize">Largest N</label>
<select id="maxSize">
<option value="64">64 items</option>
<option value="96" selected>96 items</option>
<option value="128">128 items</option>
</select>
</div>
</div>
<p class="hint" id="recipeHint"></p>
</section>
<section class="control-section">
<div class="section-heading">
<h3>03 / Read the chart</h3>
<span>Tower height</span>
</div>
<div class="segmented" aria-label="Tower scale">
<button type="button" data-scale="log" class="active">Log scale</button>
<button type="button" data-scale="linear">Linear scale</button>
</div>
<label class="check-row">
<input id="showWorkloads" type="checkbox" checked />
Show synthetic workload voxels
</label>
<p class="hint">
Tower height is a visual scale, not a count of rendered cubes.
The exact measured count appears above every tower and in the table.
</p>
</section>
<section class="control-section">
<div class="section-heading">
<h3>04 / Measured counts</h3>
<span>Comparator calls</span>
</div>
<div class="table-wrap">
<table id="measurementsTable"></table>
</div>
<button class="export-button" id="exportButton" type="button">
Export measurements as CSV
</button>
</section>
<div class="method-note">
<strong>What is being measured?</strong><br />
Sorting routines increment a counter whenever two keys are compared.
Search routines increment it for each key/probe comparison.
Swaps, writes, allocations, index arithmetic, and language overhead are
not included. These are counts from this toy implementation—not
universal operation totals, benchmark scores, or wall-clock speed.
<br /><br />
Search target: the value at the middle index of the displayed workload.
Binary search requires ascending input, so selecting it forces the
workload pattern to ascending.
</div>
</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";
const stage = document.getElementById("stage");
const loading = document.getElementById("loading");
const tooltip = document.getElementById("tooltip");
const patternSelect = document.getElementById("pattern");
const maxSizeSelect = document.getElementById("maxSize");
const showWorkloadsInput = document.getElementById("showWorkloads");
const numberFormat = new Intl.NumberFormat("en-US");
const algorithms = {
linear: {
name: "Linear Search",
bound: "O(n)",
color: "#4de2c2",
description: "Compares the target with array keys from left to right.",
run(input) {
const array = [...input];
const target = array[Math.floor(array.length / 2)];
let comparisons = 0;
for (let i = 0; i < array.length; i++) {
comparisons++;
if (array[i] === target) break;
}
return comparisons;
}
},
binary: {
name: "Binary Search",
bound: "O(log n)",
color: "#67a8ff",
description: "Compares against the midpoint of an ascending array.",
run(input) {
const array = [...input];
const target = array[Math.floor(array.length / 2)];
let comparisons = 0;
let low = 0;
let high = array.length - 1;
while (low <= high) {
const middle = (low + high) >> 1;
comparisons++;
if (array[middle] === target) break;
if (array[middle] < target) low = middle + 1;
else high = middle - 1;
}
return comparisons;
}
},
bubble: {
name: "Bubble Sort",
bound: "O(n²)",
color: "#ff6f73",
description: "Compares every adjacent pair in each shrinking pass.",
run(input) {
const array = [...input];
let comparisons = 0;
for (let end = array.length - 1; end > 0; end--) {
for (let j = 0; j < end; j++) {
comparisons++;
if (array[j] > array[j + 1]) {
const temporary = array[j];
array[j] = array[j + 1];
array[j + 1] = temporary;
}
}
}
return comparisons;
}
},
selection: {
name: "Selection Sort",
bound: "O(n²)",
color: "#ffc857",
description: "Compares each candidate against the current minimum.",
run(input) {
const array = [...input];
let comparisons = 0;
for (let i = 0; i < array.length - 1; i++) {
let minimum = i;
for (let j = i + 1; j < array.length; j++) {
comparisons++;
if (array[j] < array[minimum]) minimum = j;
}
if (minimum !== i) {
const temporary = array[i];
array[i] = array[minimum];
array[minimum] = temporary;
}
}
return comparisons;
}
},
insertion: {
name: "Insertion Sort",
bound: "O(n²)",
color: "#b892ff",
description: "Compares a key against preceding keys while inserting it.",
run(input) {
const array = [...input];
let comparisons = 0;
for (let i = 1; i < array.length; i++) {
const key = array[i];
let j = i - 1;
while (j >= 0) {
comparisons++;
if (array[j] <= key) break;
array[j + 1] = array[j];
j--;
}
array[j + 1] = key;
}
return comparisons;
}
},
merge: {
name: "Merge Sort",
bound: "O(n log n)",
color: "#72d88a",
description: "Compares keys from adjacent sorted runs while merging.",
run(input) {
const array = [...input];
const buffer = new Array(array.length);
let comparisons = 0;
function mergeSort(left, right) {
if (right - left <= 1) return;
const middle = (left + right) >> 1;
mergeSort(left, middle);
mergeSort(middle, right);
let i = left;
let j = middle;
let output = left;
while (i < middle && j < right) {
comparisons++;
if (array[i] <= array[j]) {
buffer[output++] = array[i++];
} else {
buffer[output++] = array[j++];
}
}
while (i < middle) buffer[output++] = array[i++];
while (j < right) buffer[output++] = array[j++];
for (let k = left; k < right; k++) array[k] = buffer[k];
}
mergeSort(0, array.length);
return comparisons;
}
}
};
const patternNames = {
ascending: "Ascending",
descending: "Descending",
shuffled: "Seeded shuffle",
nearly: "Nearly sorted"
};
const state = {
selected: new Set(["linear", "bubble", "merge"]),
pattern: "descending",
preferredPattern: "descending",
maxN: 96,
scale: "log",
showWorkloads: true
};
function seededRandom(seed) {
let value = seed >>> 0;
return function random() {
value += 0x6d2b79f5;
let result = value;
result = Math.imul(result ^ (result >>> 15), result | 1);
result ^= result + Math.imul(result ^ (result >>> 7), result | 61);
return ((result ^ (result >>> 14)) >>> 0) / 4294967296;
};
}
function makeWorkload(n, pattern) {
const array = Array.from({ length: n }, (_, index) => index);
if (pattern === "descending") {
array.reverse();
} else if (pattern === "shuffled") {
const random = seededRandom(0xc0ffee + n * 97);
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
} else if (pattern === "nearly") {
for (let i = 1; i < array.length; i += 13) {
[array[i - 1], array[i]] = [array[i], array[i - 1]];
}
}
return array;
}
function sizesFor(maxN) {
return [8, maxN / 4, maxN / 2, maxN];
}
function computeMeasurements() {
const sizes = sizesFor(state.maxN);
return sizes.map((n) => {
const workload = makeWorkload(n, state.pattern);
const counts = [...state.selected].map((id) => ({
id,
count: algorithms[id].run(workload)
}));
return { n, workload, counts };
});
}
// ---------- Three.js scene ----------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x070b14);
scene.fog = new THREE.Fog(0x070b14, 31, 62);
const camera = new THREE.PerspectiveCamera(
42,
1,
0.1,
120
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.tabIndex = 0;
renderer.domElement.setAttribute(
"aria-label",
"3D chart. Drag to orbit, scroll to zoom, and hover over towers for measurements."
);
stage.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xb9dcff, 0x172033, 2.0);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffffff, 3.0);
sun.position.set(-12, 23, 15);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -28;
sun.shadow.camera.right = 28;
sun.shadow.camera.top = 20;
sun.shadow.camera.bottom = -20;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 65;
sun.shadow.bias = -0.0004;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x5f8fff, 1.35);
rimLight.position.set(18, 9, -17);
scene.add(rimLight);
const cyanLight = new THREE.PointLight(0x4de2c2, 24, 34, 2);
cyanLight.position.set(-15, 7, 10);
scene.add(cyanLight);
const platform = new THREE.Mesh(
new THREE.BoxGeometry(42, 0.55, 11.5),
new THREE.MeshStandardMaterial({
color: 0x0d1726,
roughness: 0.9,
metalness: 0.08
})
);
platform.position.set(0, -0.33, 0.7);
platform.receiveShadow = true;
scene.add(platform);
const grid = new THREE.GridHelper(42, 42, 0x35506e, 0x1a2b42);
grid.position.set(0, -0.035, 0.7);
grid.material.transparent = true;
grid.material.opacity = 0.48;
scene.add(grid);
function addCornerBlocks() {
const material = new THREE.MeshStandardMaterial({
color: 0x17263b,
roughness: 0.85
});
const positions = [
[-19.7, 0.55, 5.8],
[-19.7, 1.35, 5.8],
[19.7, 0.35, 5.8],
[19.7, 1.05, 5.8],
[-19.7, 0.4, -4.3],
[19.7, 0.7, -4.3]
];
positions.forEach(([x, y, z]) => {
const block = new THREE.Mesh(new THREE.BoxGeometry(0.55, 0.55, 0.55), material);
block.position.set(x, y, z);
block.castShadow = true;
block.receiveShadow = true;
scene.add(block);
});
}
addCornerBlocks();
let dynamicGroup = null;
let segmentMeshes = [];
let barMeshes = [];
let animationStart = performance.now();
const cameraState = {
target: new THREE.Vector3(0, 2.2, 0.7),
radius: 31,
theta: 0.53,
phi: 0.93,
autoOrbit: false
};
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z +
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
updateCamera();
function disposeTree(root) {
root.traverse((object) => {
if (object.geometry) object.geometry.dispose();
const materials = Array.isArray(object.material)
? object.material
: object.material
? [object.material]
: [];
materials.forEach((material) => {
if (material.map) material.map.dispose();
material.dispose();
});
});
}
function makeTextSprite(text, options = {}) {
const {
width = 2,
color = "#edf4ff",
background = "rgba(8, 14, 25, 0.90)",
border = "#344b69"
} = options;
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = background;
context.fillRect(4, 4, 504, 120);
context.strokeStyle = border;
context.lineWidth = 6;
context.strokeRect(4, 4, 504, 120);
context.fillStyle = color;
context.font = "800 47px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 256, 66, 475);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(width, width * 0.25, 1);
sprite.renderOrder = 20;
return sprite;
}
function buildScene(measurements) {
if (dynamicGroup) {
scene.remove(dynamicGroup);
disposeTree(dynamicGroup);
}
dynamicGroup = new THREE.Group();
scene.add(dynamicGroup);
segmentMeshes = [];
barMeshes = [];
const groupSpacing = 9.4;
const groupOffset = (measurements.length - 1) * groupSpacing * 0.5;
const selectedAlgorithms = [...state.selected];
const maximumCount = Math.max(
1,
...measurements.flatMap((measurement) =>
measurement.counts.map((entry) => entry.count)
)
);
const totalWorkloadVoxels = measurements.reduce(
(sum, measurement) => sum + measurement.n,
0
);
const workloadGeometry = new THREE.BoxGeometry(0.21, 0.21, 0.21);
const workloadMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.62,
metalness: 0.06
});
const workloadMesh = new THREE.InstancedMesh(
workloadGeometry,
workloadMaterial,
totalWorkloadVoxels
);
workloadMesh.castShadow = true;
workloadMesh.receiveShadow = true;
workloadMesh.visible = state.showWorkloads;
workloadMesh.instanceMatrix.setUsage(THREE.StaticDrawUsage);
const dummy = new THREE.Object3D();
const color = new THREE.Color();
let instanceIndex = 0;
measurements.forEach((measurement, groupIndex) => {
const groupX = groupIndex * groupSpacing - groupOffset;
const workloadCenterX = groupX - 2.75;
const columns = Math.min(14, measurement.n);
const rows = Math.ceil(measurement.n / columns);
const spacing = 0.28;
const width = (columns - 1) * spacing;
const depth = (rows - 1) * spacing;
const workloadBase = new THREE.Mesh(
new THREE.BoxGeometry(width + 0.55, 0.08, depth + 0.55),
new THREE.MeshStandardMaterial({
color: 0x101d30,
roughness: 0.95,
metalness: 0.03
})
);
workloadBase.position.set(
workloadCenterX,
0.025,
2.15 - depth * 0.5
);
workloadBase.receiveShadow = true;
workloadBase.visible = state.showWorkloads;
dynamicGroup.add(workloadBase);
measurement.workload.forEach((value, elementIndex) => {
const row = Math.floor(elementIndex / columns);
const column = elementIndex % columns;
dummy.position.set(
workloadCenterX - width * 0.5 + column * spacing,
0.18,
2.15 - depth * 0.5 + row * spacing
);
dummy.updateMatrix();
workloadMesh.setMatrixAt(instanceIndex, dummy.matrix);
const hue = 0.47 + (value / Math.max(1, measurement.n - 1)) * 0.25;
color.setHSL(hue, 0.67, 0.62);
workloadMesh.setColorAt(instanceIndex, color);
instanceIndex++;
});
const sizeLabel = makeTextSprite(`N = ${measurement.n}`, {
width: 2.15,
color: "#dceaff",
border: "#385271"
});
sizeLabel.position.set(workloadCenterX, 0.72, 4.28);
dynamicGroup.add(sizeLabel);
const barSpacing = 1.65;
const barStart =
groupX + 1.15 - ((selectedAlgorithms.length - 1) * barSpacing) / 2;
measurement.counts.forEach((entry, algorithmIndex) => {
const algorithm = algorithms[entry.id];
const barX = barStart + algorithmIndex * barSpacing;
const barZ = -0.9;
let visualHeight;
if (state.scale === "log") {
visualHeight =
0.45 +
8.55 *
(Math.log1p(entry.count) / Math.log1p(maximumCount));
} else {
visualHeight = 8.5 * (entry.count / maximumCount);
}
visualHeight = Math.max(0.055, visualHeight);
const pedestal = new THREE.Mesh(
new THREE.BoxGeometry(1.24, 0.11, 1.32),
new THREE.MeshStandardMaterial({
color: 0x17243a,
roughness: 0.88
})
);
pedestal.position.set(barX, 0.055, barZ);
pedestal.receiveShadow = true;
dynamicGroup.add(pedestal);
const segmentCount = 8;
const gap = Math.min(0.065, visualHeight / 18);
const segmentHeight =
(visualHeight - gap * (segmentCount - 1)) / segmentCount;
const barMaterial = new THREE.MeshStandardMaterial({
color: algorithm.color,
emissive: new THREE.Color(algorithm.color).multiplyScalar(0.08),
roughness: 0.67,
metalness: 0.08
});
for (let segment = 0; segment < segmentCount; segment++) {
const segmentMesh = new THREE.Mesh(
new THREE.BoxGeometry(1.04, segmentHeight, 1.04),
barMaterial.clone()
);
const finalY =
segmentHeight * 0.5 + segment * (segmentHeight + gap);
segmentMesh.position.set(barX, finalY, barZ);
segmentMesh.castShadow = true;
segmentMesh.receiveShadow = true;
segmentMesh.userData = {
finalY,
delay: algorithmIndex * 0.08 + segment * 0.025,
algorithm: entry.id,
algorithmName: algorithm.name,
color: algorithm.color,
n: measurement.n,
count: entry.count,
pattern: patternNames[state.pattern]
};
dynamicGroup.add(segmentMesh);
segmentMeshes.push(segmentMesh);
barMeshes.push(segmentMesh);
}
const countLabel = makeTextSprite(
`${numberFormat.format(entry.count)} CMP`,
{
width: 1.62,
color: algorithm.color,
border: algorithm.color
}
);
countLabel.position.set(barX, visualHeight + 0.72, barZ);
dynamicGroup.add(countLabel);
});
});
workloadMesh.instanceMatrix.needsUpdate = true;
if (workloadMesh.instanceColor) workloadMesh.instanceColor.needsUpdate = true;
dynamicGroup.add(workloadMesh);
animationStart = performance.now();
}
// ---------- UI ----------
function buildAlgorithmOptions() {
const list = document.getElementById("algorithmList");
list.innerHTML = Object.entries(algorithms)
.map(
([id, algorithm]) => `
<label class="algorithm-option" style="--accent:${algorithm.color}">
<input
type="checkbox"
value="${id}"
${state.selected.has(id) ? "checked" : ""}
aria-label="${algorithm.name}, ${algorithm.bound}"
/>
<span class="swatch"></span>
<span>
<strong>${algorithm.name}</strong>
<small>${algorithm.bound} · toy comparator calls</small>
</span>
</label>
`
)
.join("");
list.querySelectorAll("input").forEach((input) => {
input.addEventListener("change", () => {
const id = input.value;
if (input.checked) {
if (state.selected.size >= 3) {
input.checked = false;
document.getElementById("algorithmHint").textContent =
"Three-algorithm limit reached. Deselect one to add another.";
return;
}
state.selected.add(id);
if (id === "binary") {
state.preferredPattern = state.pattern;
state.pattern = "ascending";
}
} else {
if (state.selected.size === 1) {
input.checked = true;
return;
}
state.selected.delete(id);
if (id === "binary") {
state.pattern = state.preferredPattern;
}
}
patternSelect.value = state.pattern;
patternSelect.disabled = state.selected.has("binary");
rebuild();
});
});
}
function renderUI(measurements) {
const selectedAlgorithms = [...state.selected].map((id) => algorithms[id]);
const patternLabel = patternNames[state.pattern];
document.getElementById("experimentTitle").textContent =
`${patternLabel} workloads`;
document.getElementById("experimentSubtitle").textContent =
`Synthetic arrays of N = ${measurements
.map((measurement) => measurement.n)
.join(", ")} beside measured comparison towers.`;
document.getElementById("legend").innerHTML = selectedAlgorithms
.map(
(algorithm) => `
<span class="legend-item" style="--accent:${algorithm.color}">
<i></i>${algorithm.name}
</span>
`
)
.join("");
document.getElementById("algorithmHint").innerHTML = state.selected.has(
"binary"
)
? `<strong>Binary search selected.</strong> The shared workload is forced to ascending order so every algorithm receives a valid input.`
: `Target: the value at the middle index. Search and sort routines use the same displayed synthetic array.`;
document.getElementById("recipeHint").innerHTML =
`<strong>${patternLabel} array</strong> with unique integer keys. ` +
(state.pattern === "shuffled"
? `The shuffle uses a fixed seed, so repeated runs produce identical counts.`
: `Counts are deterministic for the selected size and pattern.`);
document.getElementById("scaleNote").innerHTML =
`<strong>${state.scale.toUpperCase()} HEIGHT SCALE</strong><br />` +
`Exact comparator counts are printed above each tower.`;
const table = document.getElementById("measurementsTable");
const header = `
<thead>
<tr>
<th>Size</th>
${selectedAlgorithms
.map(
(algorithm) => `
<th>
<span class="table-alg" style="--accent:${algorithm.color}">
<i></i>${algorithm.name}
</span>
</th>
`
)
.join("")}
</tr>
</thead>
`;
const rows = measurements
.map(
(measurement) => `
<tr>
<td>${measurement.n}</td>
${measurement.counts
.map(
(entry) => `<td>${numberFormat.format(entry.count)}</td>`
)
.join("")}
</tr>
`
)
.join("");
table.innerHTML = `${header}<tbody>${rows}</tbody>`;
patternSelect.value = state.pattern;
patternSelect.disabled = state.selected.has("binary");
maxSizeSelect.value = String(state.maxN);
showWorkloadsInput.checked = state.showWorkloads;
document.querySelectorAll("[data-scale]").forEach((button) => {
button.classList.toggle("active", button.dataset.scale === state.scale);
});
}
let lastMeasurements = [];
function rebuild() {
lastMeasurements = computeMeasurements();
renderUI(lastMeasurements);
buildScene(lastMeasurements);
}
patternSelect.addEventListener("change", () => {
if (state.selected.has("binary")) return;
state.pattern = patternSelect.value;
state.preferredPattern = state.pattern;
rebuild();
});
maxSizeSelect.addEventListener("change", () => {
state.maxN = Number(maxSizeSelect.value);
rebuild();
});
showWorkloadsInput.addEventListener("change", () => {
state.showWorkloads = showWorkloadsInput.checked;
rebuild();
});
document.querySelectorAll("[data-scale]").forEach((button) => {
button.addEventListener("click", () => {
state.scale = button.dataset.scale;
rebuild();
});
});
document.getElementById("resetView").addEventListener("click", () => {
cameraState.radius = 31;
cameraState.theta = 0.53;
cameraState.phi = 0.93;
cameraState.target.set(0, 2.2, 0.7);
updateCamera();
});
document.getElementById("autoOrbit").addEventListener("click", (event) => {
cameraState.autoOrbit = !cameraState.autoOrbit;
event.currentTarget.classList.toggle("active", cameraState.autoOrbit);
});
document.getElementById("replay").addEventListener("click", () => {
animationStart = performance.now();
});
document.getElementById("exportButton").addEventListener("click", () => {
const selectedAlgorithms = [...state.selected].map((id) => algorithms[id]);
const rows = [
["N", ...selectedAlgorithms.map((algorithm) => algorithm.name)],
...lastMeasurements.map((measurement) => [
measurement.n,
...measurement.counts.map((entry) => entry.count)
])
];
const csv = rows
.map((row) => row.map((value) => `"${value}"`).join(","))
.join("\n");
const blob = new Blob([csv], { type: "text/csv;charset=utf-8" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = "complexity-lab-measurements.csv";
link.click();
URL.revokeObjectURL(url);
});
// ---------- Direct camera controls ----------
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
tooltip.style.display = "none";
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (dragging) {
const deltaX = event.clientX - pointerX;
const deltaY = event.clientY - pointerY;
cameraState.theta -= deltaX * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi + deltaY * 0.005,
0.38,
1.34
);
pointerX = event.clientX;
pointerY = event.clientY;
return;
}
updateTooltip(event);
});
renderer.domElement.addEventListener("pointerup", (event) => {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener("pointerleave", () => {
tooltip.style.display = "none";
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
18,
54
);
},
{ passive: false }
);
renderer.domElement.addEventListener("keydown", (event) => {
if (event.key === "ArrowLeft") cameraState.theta -= 0.1;
if (event.key === "ArrowRight") cameraState.theta += 0.1;
if (event.key === "ArrowUp") {
cameraState.phi = Math.max(0.38, cameraState.phi - 0.08);
}
if (event.key === "ArrowDown") {
cameraState.phi = Math.min(1.34, cameraState.phi + 0.08);
}
});
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function updateTooltip(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(barMeshes, false);
if (!intersections.length) {
tooltip.style.display = "none";
return;
}
const data = intersections[0].object.userData;
tooltip.style.setProperty("--accent", data.color);
tooltip.innerHTML = `
<strong>${data.algorithmName}</strong>
N = ${data.n}<br />
${numberFormat.format(data.count)} key comparisons<br />
<span style="color:#8ea0b8">${data.pattern} workload</span>
`;
tooltip.style.display = "block";
const left = Math.min(
rect.width - 215,
Math.max(8, event.clientX - rect.left + 14)
);
const top = Math.min(
rect.height - 100,
Math.max(8, event.clientY - rect.top + 14)
);
tooltip.style.left = `${left}px`;
tooltip.style.top = `${top}px`;
}
// ---------- Resize and animation ----------
function resizeRenderer() {
const width = Math.max(1, stage.clientWidth);
const height = Math.max(1, stage.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resizeRenderer);
resizeObserver.observe(stage);
resizeRenderer();
function animate(now) {
requestAnimationFrame(animate);
if (cameraState.autoOrbit && !dragging) {
cameraState.theta += 0.00018 * 16.67;
}
updateCamera();
segmentMeshes.forEach((mesh) => {
const elapsed = (now - animationStart) / 1000;
const progress = THREE.MathUtils.clamp(
(elapsed - mesh.userData.delay) / 0.34,
0,
1
);
const eased = 1 - Math.pow(1 - progress, 3);
mesh.scale.y = Math.max(0.001, eased);
mesh.position.y = mesh.userData.finalY * eased;
});
renderer.render(scene, camera);
}
buildAlgorithmOptions();
rebuild();
loading.remove();
requestAnimationFrame(animate);
</script>
</body>
</html>
```