Prompt specification
Build or customize the Three.js 3D scene "Nested loops and single loop trace" 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: Nested loops and single loop trace
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/nested-loops-and-single-loop-trace-x1842
Scene Description Prompt:
Please use Three.js from cdnjs for a stylized scene based on this idea: nested loops and single loop trace. Animate a one-dimensional iteration beside all pairs of a small grid; count visited items exactly so linear and quadratic growth arise from visible work. Return one self-contained HTML file.
Working Three.js Starter (nested-loops-and-single-loop-trace-x1842):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Nested Loops — One Trace vs. Every Pair</title>
<style>
:root {
color-scheme: dark;
--bg: #07101d;
--panel: rgba(12, 24, 42, 0.78);
--line: rgba(174, 210, 255, 0.16);
--text: #eef6ff;
--muted: #91a7bf;
--cyan: #55e7ff;
--pink: #ff58b8;
--amber: #ffc65c;
--purple: #8a72ff;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input { font: inherit; }
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas:active { cursor: grabbing; }
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 50% 45%, transparent 34%, rgba(2, 7, 15, 0.22) 72%, rgba(2, 7, 15, 0.72) 110%),
linear-gradient(180deg, rgba(4, 10, 20, 0.28), transparent 30%, transparent 72%, rgba(4, 10, 20, 0.45));
z-index: 1;
}
.hud {
position: fixed;
z-index: 2;
pointer-events: none;
}
.glass {
background: var(--panel);
border: 1px solid var(--line);
box-shadow: 0 16px 50px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
.intro {
top: 24px;
left: 26px;
width: 330px;
}
.eyebrow {
margin-bottom: 8px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.2em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(26px, 3vw, 42px);
line-height: 0.98;
letter-spacing: -0.045em;
}
h1 span {
color: #91a7bf;
font-weight: 500;
}
.intro p {
max-width: 300px;
margin: 13px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.counters {
top: 24px;
left: 50%;
display: flex;
gap: 10px;
transform: translateX(-50%);
}
.counter {
width: 174px;
padding: 12px 14px 11px;
border-radius: 14px;
transition: border-color 220ms ease, box-shadow 220ms ease;
}
.counter.single { border-top-color: rgba(85, 231, 255, 0.65); }
.counter.pairs { border-top-color: rgba(255, 88, 184, 0.65); }
.counter.complete {
border-color: rgba(85, 231, 255, 0.8);
box-shadow: 0 0 28px rgba(85, 231, 255, 0.13);
}
.counter.pairs.complete {
border-color: rgba(255, 88, 184, 0.8);
box-shadow: 0 0 28px rgba(255, 88, 184, 0.13);
}
.counter-label {
display: flex;
align-items: center;
justify-content: space-between;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.counter-value {
display: flex;
align-items: baseline;
gap: 6px;
margin-top: 4px;
}
.counter-value strong {
font-size: 29px;
line-height: 1;
letter-spacing: -0.04em;
font-variant-numeric: tabular-nums;
}
.counter.single strong { color: var(--cyan); }
.counter.pairs strong { color: var(--pink); }
.counter-value small {
color: var(--muted);
font-size: 11px;
}
.meter {
height: 3px;
margin-top: 10px;
overflow: hidden;
border-radius: 4px;
background: rgba(255, 255, 255, 0.07);
}
.meter > i {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
transition: width 70ms linear;
}
.single .meter > i {
background: linear-gradient(90deg, #258ca3, var(--cyan));
box-shadow: 0 0 12px var(--cyan);
}
.pairs .meter > i {
background: linear-gradient(90deg, #633aa6, var(--pink));
box-shadow: 0 0 12px var(--pink);
}
.controls {
top: 24px;
right: 26px;
width: 234px;
padding: 13px;
border-radius: 15px;
pointer-events: auto;
}
.control-title {
margin-bottom: 10px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 6px;
}
button {
min-height: 34px;
border: 1px solid rgba(180, 215, 255, 0.15);
border-radius: 9px;
background: rgba(255, 255, 255, 0.055);
color: var(--text);
cursor: pointer;
font-size: 10px;
font-weight: 750;
transition: transform 120ms ease, background 120ms ease, border-color 120ms ease;
}
button:hover:not(:disabled) {
transform: translateY(-1px);
background: rgba(255, 255, 255, 0.11);
border-color: rgba(180, 215, 255, 0.3);
}
button:active:not(:disabled) { transform: translateY(0); }
button:disabled { opacity: 0.38; cursor: default; }
#pauseBtn {
border-color: rgba(85, 231, 255, 0.28);
color: var(--cyan);
}
.speed-row {
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
gap: 9px;
margin-top: 12px;
color: var(--muted);
font-size: 10px;
}
#speed {
width: 100%;
accent-color: var(--cyan);
cursor: pointer;
}
#speedValue {
min-width: 28px;
color: var(--text);
text-align: right;
font-variant-numeric: tabular-nums;
}
.control-note {
margin: 9px 0 0;
color: #7289a2;
font-size: 9px;
line-height: 1.45;
}
.legend {
bottom: 25px;
left: 26px;
display: flex;
flex-wrap: wrap;
gap: 13px;
padding: 9px 12px;
border-radius: 10px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.04em;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.dot {
width: 7px;
height: 7px;
border-radius: 50%;
box-shadow: 0 0 9px currentColor;
}
.dot.cyan { color: var(--cyan); background: var(--cyan); }
.dot.pink { color: var(--pink); background: var(--pink); }
.dot.amber { color: var(--amber); background: var(--amber); }
.equations {
bottom: 24px;
left: 50%;
display: flex;
gap: 9px;
transform: translateX(-50%);
}
.equation {
min-width: 230px;
padding: 10px 13px;
border-radius: 12px;
font-size: 10px;
}
.equation code {
display: block;
margin-bottom: 5px;
color: #c5d4e4;
font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
font-size: 9px;
}
.equation strong {
font-size: 11px;
letter-spacing: 0.02em;
}
.equation.single strong { color: var(--cyan); }
.equation.pairs strong { color: var(--pink); }
.hint {
right: 26px;
bottom: 27px;
color: #6f879f;
font-size: 9px;
letter-spacing: 0.03em;
text-align: right;
}
#status {
position: fixed;
z-index: 3;
top: 113px;
left: 50%;
max-width: 560px;
padding: 7px 12px;
border: 1px solid rgba(180, 215, 255, 0.11);
border-radius: 20px;
background: rgba(6, 15, 28, 0.66);
color: #9fb3c8;
pointer-events: none;
transform: translateX(-50%);
font-size: 10px;
text-align: center;
backdrop-filter: blur(10px);
}
@media (max-width: 1050px) {
.intro p { display: none; }
.intro { width: 230px; }
.counter { width: 150px; }
.equations { left: 26px; transform: none; }
.hint { display: none; }
}
@media (max-width: 760px) {
.intro {
top: 15px;
left: 15px;
}
.eyebrow, .intro p { display: none; }
h1 { font-size: 23px; }
h1 br { display: none; }
h1 span { display: block; }
.counters {
top: 75px;
left: 15px;
right: 15px;
transform: none;
}
.counter {
flex: 1;
width: auto;
padding: 9px 10px;
}
.counter-value strong { font-size: 23px; }
.controls {
top: 15px;
right: 15px;
width: 154px;
padding: 9px;
}
.control-title, .control-note { display: none; }
.button-row { gap: 4px; }
button { min-height: 30px; font-size: 9px; }
.speed-row { margin-top: 8px; font-size: 9px; }
#status {
top: 145px;
width: calc(100% - 30px);
}
.legend { display: none; }
.equations { display: none; }
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="vignette"></div>
<header class="hud intro">
<div class="eyebrow">Iteration landscape / Three.js</div>
<h1>One trace.<br><span>Every ordered pair.</span></h1>
<p>
A 4×4 grid contains 16 items. One loop visits 16 items;
nested loops visit all 16 × 16 = 256 pairs.
</p>
</header>
<section class="hud counters" aria-label="Exact visit counters">
<article class="counter glass single" id="singleCard">
<div class="counter-label">
<span>Single loop</span>
<span id="singleState">tracing</span>
</div>
<div class="counter-value">
<strong id="singleCount">0</strong>
<small>/ 16 visits</small>
</div>
<div class="meter"><i id="singleMeter"></i></div>
</article>
<article class="counter glass pairs" id="pairsCard">
<div class="counter-label">
<span>Nested loops</span>
<span id="pairsState">tracing</span>
</div>
<div class="counter-value">
<strong id="pairsCount">0</strong>
<small>/ 256 visits</small>
</div>
<div class="meter"><i id="pairsMeter"></i></div>
</article>
</section>
<section class="hud controls glass" aria-label="Animation controls">
<div class="control-title">Logical-step controls</div>
<div class="button-row">
<button id="pauseBtn" type="button">Pause</button>
<button id="stepBtn" type="button">Step</button>
<button id="replayBtn" type="button">Replay</button>
</div>
<div class="speed-row">
<span>Speed</span>
<input id="speed" type="range" min="0.5" max="4" step="0.5" value="1.5">
<span id="speedValue">1.5×</span>
</div>
<p class="control-note">Step advances each algorithm by exactly one body execution—not by frame.</p>
</section>
<section class="hud equations" aria-label="Growth formulas">
<div class="equation glass single">
<code>for item in items: visit(item)</code>
<strong>16 items → 16 visits</strong>
</div>
<div class="equation glass pairs">
<code>for i in items: for j in items: visit(i, j)</code>
<strong>16 × 16 → 256 visits</strong>
</div>
</section>
<div class="hud legend glass">
<span><i class="dot cyan"></i>single-loop probe</span>
<span><i class="dot pink"></i>current pair</span>
<span><i class="dot amber"></i>pair endpoint</span>
</div>
<div class="hud hint">Drag to orbit · wheel to zoom · double-click to reset</div>
<div id="status" role="status" aria-live="polite">Preparing the first logical iteration…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const sceneHost = document.getElementById("scene");
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute(
"aria-label",
"Interactive three-dimensional comparison of a single loop and nested loops"
);
sceneHost.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07101d);
scene.fog = new THREE.Fog(0x07101d, 48, 130);
const camera = new THREE.PerspectiveCamera(
35,
window.innerWidth / window.innerHeight,
0.1,
180
);
// Camera controls are implemented directly, without addons.
const cameraTarget = new THREE.Vector3(0, 0, 0);
const desired = {
yaw: 0,
pitch: 0.57,
radius: 31
};
const current = {
yaw: 0,
pitch: 0.57,
radius: 31
};
function resetCamera() {
const halfFov = THREE.MathUtils.degToRad(camera.fov * 0.5);
const widthNeeded = 29;
desired.yaw = 0;
desired.pitch = 0.57;
desired.radius = Math.max(
31,
widthNeeded / (2 * Math.tan(halfFov) * camera.aspect)
);
current.yaw = desired.yaw;
current.pitch = desired.pitch;
current.radius = desired.radius;
}
function updateCamera(dt) {
const easing = 1 - Math.exp(-12 * dt);
current.yaw += (desired.yaw - current.yaw) * easing;
current.pitch += (desired.pitch - current.pitch) * easing;
current.radius += (desired.radius - current.radius) * easing;
const spherical = new THREE.Spherical(
current.radius,
current.pitch,
current.yaw
);
camera.position.setFromSpherical(spherical).add(cameraTarget);
camera.lookAt(cameraTarget);
}
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
desired.yaw -= dx * 0.005;
desired.pitch = THREE.MathUtils.clamp(
desired.pitch + dy * 0.004,
0.28,
1.16
);
});
function stopDragging(event) {
dragging = false;
if (event && renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener("dblclick", resetCamera);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
desired.radius = THREE.MathUtils.clamp(
desired.radius * Math.exp(event.deltaY * 0.001),
18,
95
);
},
{ passive: false }
);
resetCamera();
// Lighting.
scene.add(new THREE.HemisphereLight(0xb8e4ff, 0x101728, 1.45));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.15);
keyLight.position.set(-5, 17, 10);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -17;
keyLight.shadow.camera.right = 17;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -12;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 45;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x32dfff, 16, 10, 2);
cyanLight.position.set(-3.4, 2.2, 2.3);
scene.add(cyanLight);
const pinkLight = new THREE.PointLight(0xff3eac, 18, 10, 2);
pinkLight.position.set(5.6, 2.3, 1.7);
scene.add(pinkLight);
function roundedRectShape(width, depth, radius) {
const x = -width / 2;
const y = -depth / 2;
const shape = new THREE.Shape();
shape.moveTo(x + radius, y);
shape.lineTo(x + width - radius, y);
shape.quadraticCurveTo(x + width, y, x + width, y + radius);
shape.lineTo(x + width, y + depth - radius);
shape.quadraticCurveTo(
x + width,
y + depth,
x + width - radius,
y + depth
);
shape.lineTo(x + radius, y + depth);
shape.quadraticCurveTo(x, y + depth, x, y + depth - radius);
shape.lineTo(x, y + radius);
shape.quadraticCurveTo(x, y, x + radius, y);
shape.closePath();
return shape;
}
function roundedSlabGeometry(width, depth, height, radius) {
const geometry = new THREE.ExtrudeGeometry(
roundedRectShape(width, depth, radius),
{
depth: height,
bevelEnabled: true,
bevelSegments: 2,
steps: 1,
bevelSize: 0.025,
bevelThickness: 0.025,
curveSegments: 8
}
);
geometry.center();
geometry.rotateX(Math.PI / 2);
return geometry;
}
// Main stage.
const stage = new THREE.Mesh(
roundedSlabGeometry(27, 10.6, 0.26, 0.65),
new THREE.MeshStandardMaterial({
color: 0x0b1727,
roughness: 0.9,
metalness: 0.08
})
);
stage.position.y = -0.21;
stage.receiveShadow = true;
scene.add(stage);
// Subtle grid drawn directly on the stage.
const gridVertices = [];
for (let x = -13; x <= 13; x += 1) {
gridVertices.push(x, -0.068, -5.05, x, -0.068, 5.05);
}
for (let z = -5; z <= 5; z += 1) {
gridVertices.push(-13.15, -0.068, z, 13.15, -0.068, z);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridVertices, 3)
);
scene.add(
new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x5d87ad,
transparent: true,
opacity: 0.11
})
)
);
const panelMaterial = new THREE.MeshStandardMaterial({
color: 0x101e31,
roughness: 0.76,
metalness: 0.12
});
function addPanel(x, z, width, depth) {
const panel = new THREE.Mesh(
roundedSlabGeometry(width, depth, 0.08, 0.25),
panelMaterial
);
panel.position.set(x, 0, z);
panel.receiveShadow = true;
scene.add(panel);
return panel;
}
addPanel(-10.15, 0, 5.2, 5.2);
addPanel(-3.35, 0, 7.1, 2.45);
addPanel(5.6, 0, 5.2, 5.2);
// Shared number textures for the source grid and 1D strip.
const indexTextures = [];
for (let i = 0; i < 16; i++) {
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, 128, 128);
ctx.fillStyle = "#eaf7ff";
ctx.font = "700 68px ui-sans-serif, system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(String(i), 64, 67);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
indexTextures.push(texture);
}
function numberSprite(index, scale, opacity = 1) {
const material = new THREE.SpriteMaterial({
map: indexTextures[index],
transparent: true,
opacity,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(scale, scale, 1);
sprite.renderOrder = 12;
return sprite;
}
function panelLabel(title, subtitle, accent, width) {
const canvas = document.createElement("canvas");
canvas.width = 1024;
canvas.height = 256;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, 1024, 256);
ctx.textAlign = "center";
ctx.fillStyle = accent;
ctx.font = "800 64px ui-sans-serif, system-ui, sans-serif";
ctx.fillText(title, 512, 80);
ctx.fillStyle = "#94abc2";
ctx.font = "600 31px ui-sans-serif, system-ui, sans-serif";
ctx.fillText(subtitle, 512, 151);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(width, width / 4, 1);
sprite.renderOrder = 20;
return sprite;
}
const sourceLabel = panelLabel(
"SOURCE GRID",
"4 × 4 = 16 addressable items",
"#55e7ff",
4.45
);
sourceLabel.position.set(-10.15, 0.72, -3.08);
scene.add(sourceLabel);
const singleLabel = panelLabel(
"SINGLE LOOP",
"one dimension · one visit per item",
"#55e7ff",
5.2
);
singleLabel.position.set(-3.35, 0.7, -1.7);
scene.add(singleLabel);
const pairLabel = panelLabel(
"NESTED LOOPS",
"every ordered pair · 16 × 16 matrix",
"#ff58b8",
4.8
);
pairLabel.position.set(5.6, 0.72, -3.08);
scene.add(pairLabel);
// Source grid.
const sourceTiles = [];
const sourceTileGeometry = new THREE.BoxGeometry(0.86, 0.16, 0.86);
const sourcePitch = 1.04;
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 4; col++) {
const index = row * 4 + col;
const material = new THREE.MeshStandardMaterial({
color: 0x172a40,
emissive: 0x000000,
roughness: 0.7,
metalness: 0.08
});
const tile = new THREE.Mesh(sourceTileGeometry, material);
tile.position.set(
-10.15 + (col - 1.5) * sourcePitch,
0.14,
(row - 1.5) * sourcePitch
);
tile.castShadow = true;
tile.receiveShadow = true;
tile.userData.index = index;
tile.userData.targetScale = 1;
scene.add(tile);
sourceTiles.push(tile);
const number = numberSprite(index, 0.4, 0.92);
number.position.set(tile.position.x, 0.36, tile.position.z);
scene.add(number);
}
}
// One-dimensional array.
const stripTiles = [];
const stripPositions = [];
const stripPitch = 0.355;
const stripCenter = -3.35;
for (let i = 0; i < 16; i++) {
const x = stripCenter + (i - 7.5) * stripPitch;
stripPositions.push(x);
const tile = new THREE.Mesh(
new THREE.BoxGeometry(0.29, 0.14, 0.36),
new THREE.MeshStandardMaterial({
color: 0x183247,
emissive: 0x000000,
roughness: 0.65,
metalness: 0.08
})
);
tile.position.set(x, 0.13, 0);
tile.castShadow = true;
tile.receiveShadow = true;
scene.add(tile);
stripTiles.push(tile);
const number = numberSprite(i, 0.2, 0.62);
number.position.set(x, 0.15, 0.49);
scene.add(number);
}
const stripAxis = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(stripCenter - 3.0, 0.075, 0),
new THREE.Vector3(stripCenter + 3.0, 0.075, 0)
]),
new THREE.LineBasicMaterial({
color: 0x55e7ff,
transparent: true,
opacity: 0.25
})
);
scene.add(stripAxis);
// 16 × 16 ordered-pair matrix.
const MATRIX_SIZE = 16;
const CELL = 0.205;
const CELL_GAP = 0.035;
const CELL_PITCH = CELL + CELL_GAP;
const MATRIX_CENTER = 5.6;
const MATRIX_WIDTH = MATRIX_SIZE * CELL + (MATRIX_SIZE - 1) * CELL_GAP;
function matrixX(column) {
return MATRIX_CENTER + (column - 7.5) * CELL_PITCH;
}
function matrixZ(row) {
return (row - 7.5) * CELL_PITCH;
}
const matrixGeometry = new THREE.BoxGeometry(CELL, 0.075, CELL);
const matrixMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
emissive: 0x32102c,
emissiveIntensity: 0.04,
roughness: 0.68,
metalness: 0.12,
vertexColors: true
});
const matrix = new THREE.InstancedMesh(
matrixGeometry,
matrixMaterial,
MATRIX_SIZE * MATRIX_SIZE
);
matrix.instanceMatrix.setUsage(THREE.StaticDrawUsage);
matrix.castShadow = true;
matrix.receiveShadow = true;
scene.add(matrix);
const dummy = new THREE.Object3D();
const unvisitedA = new THREE.Color(0x17243a);
const unvisitedB = new THREE.Color(0x201a38);
for (let row = 0; row < MATRIX_SIZE; row++) {
for (let col = 0; col < MATRIX_SIZE; col++) {
dummy.position.set(matrixX(col), 0.105, matrixZ(row));
dummy.updateMatrix();
matrix.setMatrixAt(row * MATRIX_SIZE + col, dummy.matrix);
matrix.setColorAt(
row * MATRIX_SIZE + col,
(row + col) % 2 ? unvisitedA : unvisitedB
);
}
}
matrix.instanceColor.needsUpdate = true;
// Row and column scanners.
const rowGuide = new THREE.Mesh(
new THREE.BoxGeometry(MATRIX_WIDTH + 0.12, 0.025, 0.035),
new THREE.MeshBasicMaterial({
color: 0xff58b8,
transparent: true,
opacity: 0.42
})
);
rowGuide.position.y = 0.2;
scene.add(rowGuide);
const colGuide = new THREE.Mesh(
new THREE.BoxGeometry(0.035, 0.025, MATRIX_WIDTH + 0.12),
new THREE.MeshBasicMaterial({
color: 0xff58b8,
transparent: true,
opacity: 0.42
})
);
colGuide.position.y = 0.2;
scene.add(colGuide);
// Moving probes.
const singleProbe = new THREE.Group();
const singleRing = new THREE.Mesh(
new THREE.TorusGeometry(0.225, 0.028, 8, 32),
new THREE.MeshBasicMaterial({
color: 0x55e7ff,
transparent: true,
opacity: 0.9
})
);
singleRing.rotation.x = Math.PI / 2;
singleRing.position.y = 0.26;
singleProbe.add(singleRing);
const singleCore = new THREE.Mesh(
new THREE.SphereGeometry(0.075, 16, 12),
new THREE.MeshBasicMaterial({ color: 0xd8fbff })
);
singleCore.position.y = 0.29;
singleProbe.add(singleCore);
scene.add(singleProbe);
const pairProbe = new THREE.Group();
const pairCore = new THREE.Mesh(
new THREE.BoxGeometry(0.245, 0.13, 0.245),
new THREE.MeshBasicMaterial({
color: 0xff58b8,
transparent: true,
opacity: 0.85
})
);
pairCore.position.y = 0.16;
pairProbe.add(pairCore);
const pairRing = new THREE.Mesh(
new THREE.TorusGeometry(0.225, 0.025, 8, 32),
new THREE.MeshBasicMaterial({
color: 0xff9bd3,
transparent: true,
opacity: 0.8
})
);
pairRing.rotation.x = Math.PI / 2;
pairRing.position.y = 0.24;
pairProbe.add(pairRing);
scene.add(pairProbe);
// Ambient particles.
const particlePositions = [];
for (let i = 0; i < 170; i++) {
particlePositions.push(
(Math.random() - 0.5) * 34,
1 + Math.random() * 9,
(Math.random() - 0.5) * 18 - 2
);
}
const particleGeometry = new THREE.BufferGeometry();
particleGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(particlePositions, 3)
);
const particles = new THREE.Points(
particleGeometry,
new THREE.PointsMaterial({
color: 0x78b9e8,
size: 0.025,
transparent: true,
opacity: 0.45,
depthWrite: false
})
);
scene.add(particles);
// Exact algorithm state. Every increment corresponds to one visited item/pair.
const MAX_SINGLE = 16;
const MAX_PAIRS = 256;
const state = {
singleVisited: 0,
pairVisited: 0,
playing: true,
speed: 1.5,
startDelay: 0.4,
activeSingle: 0,
activePairRow: 0,
activePairColumn: 0,
complete: false,
singlePulse: 0,
pairPulse: 0
};
const singleTarget = new THREE.Vector3(stripPositions[0], 0, 0);
const pairTarget = new THREE.Vector3(matrixX(0), 0, matrixZ(0));
const singleCountEl = document.getElementById("singleCount");
const pairsCountEl = document.getElementById("pairsCount");
const singleMeterEl = document.getElementById("singleMeter");
const pairsMeterEl = document.getElementById("pairsMeter");
const singleStateEl = document.getElementById("singleState");
const pairsStateEl = document.getElementById("pairsState");
const singleCardEl = document.getElementById("singleCard");
const pairsCardEl = document.getElementById("pairsCard");
const statusEl = document.getElementById("status");
const pauseBtn = document.getElementById("pauseBtn");
const stepBtn = document.getElementById("stepBtn");
const replayBtn = document.getElementById("replayBtn");
const speedEl = document.getElementById("speed");
const speedValueEl = document.getElementById("speedValue");
const visitedSingleA = new THREE.Color(0x1b5264);
const visitedSingleB = new THREE.Color(0x55e7ff);
const visitedPairA = new THREE.Color(0x41235f);
const visitedPairB = new THREE.Color(0xff58b8);
function setPlaying(playing) {
state.playing = playing && !state.complete;
pauseBtn.textContent = state.playing ? "Pause" : "Resume";
pauseBtn.disabled = state.complete;
}
function updateHUD() {
singleCountEl.textContent = String(state.singleVisited);
pairsCountEl.textContent = String(state.pairVisited);
singleMeterEl.style.width = `${(state.singleVisited / MAX_SINGLE) * 100}%`;
pairsMeterEl.style.width = `${(state.pairVisited / MAX_PAIRS) * 100}%`;
const singleDone = state.singleVisited === MAX_SINGLE;
const pairsDone = state.pairVisited === MAX_PAIRS;
singleStateEl.textContent = singleDone ? "complete" : state.playing ? "tracing" : "paused";
pairsStateEl.textContent = pairsDone ? "complete" : state.playing ? "tracing" : "paused";
singleCardEl.classList.toggle("complete", singleDone);
pairsCardEl.classList.toggle("complete", pairsDone);
if (state.complete) {
statusEl.textContent =
"Both sweeps complete: 16 linear visits versus 256 pair visits — 16× more work.";
} else if (singleDone) {
statusEl.textContent =
`Single loop is complete. Nested loops continue at ${state.pairVisited} / 256 visits.`;
} else {
const nextRow = state.activePairRow + 1;
const nextColumn = state.activePairColumn + 1;
statusEl.textContent =
`Both algorithms advance one logical iteration per beat · next pair (${nextRow}, ${nextColumn})`;
}
}
function updateSourceHighlights() {
for (const tile of sourceTiles) {
tile.material.color.set(0x172a40);
tile.material.emissive.set(0x000000);
tile.material.emissiveIntensity = 1;
tile.userData.targetScale = 1;
}
const singleTile = sourceTiles[state.activeSingle];
singleTile.material.color.set(0x1b4f61);
singleTile.material.emissive.set(0x55e7ff);
singleTile.material.emissiveIntensity = 0.34;
singleTile.userData.targetScale = 1.07;
const rowTile = sourceTiles[state.activePairRow];
rowTile.material.color.set(0x45203f);
rowTile.material.emissive.set(0xff58b8);
rowTile.material.emissiveIntensity = 0.3;
rowTile.userData.targetScale = 1.06;
const colTile = sourceTiles[state.activePairColumn];
colTile.material.color.set(0x493821);
colTile.material.emissive.set(0xffc65c);
colTile.material.emissiveIntensity = 0.3;
colTile.userData.targetScale = 1.06;
}
function primeTrace() {
state.activeSingle = 0;
state.activePairRow = 0;
state.activePairColumn = 0;
singleTarget.set(stripPositions[0], 0, 0);
pairTarget.set(matrixX(0), 0, matrixZ(0));
singleProbe.position.copy(singleTarget);
pairProbe.position.copy(pairTarget);
rowGuide.position.z = matrixZ(0);
colGuide.position.x = matrixX(0);
updateSourceHighlights();
}
function visitSingle(index) {
state.activeSingle = index;
singleTarget.set(stripPositions[index], 0, 0);
const amount = (index + 1) / MAX_SINGLE;
const color = visitedSingleA.clone().lerp(visitedSingleB, amount);
stripTiles[index].material.color.copy(color);
stripTiles[index].material.emissive.set(0x55e7ff);
stripTiles[index].material.emissiveIntensity = 0.22 + amount * 0.25;
state.singlePulse = 1;
}
function visitPair(index) {
const row = Math.floor(index / MATRIX_SIZE);
const column = index % MATRIX_SIZE;
state.activePairRow = row;
state.activePairColumn = column;
pairTarget.set(matrixX(column), 0, matrixZ(row));
rowGuide.position.z = matrixZ(row);
colGuide.position.x = matrixX(column);
const amount = (index + 1) / MAX_PAIRS;
const color = visitedPairA.clone().lerp(visitedPairB, 0.25 + amount * 0.75);
matrix.setColorAt(index, color);
matrix.instanceColor.needsUpdate = true;
state.pairPulse = 1;
}
function executeOneLogicalTick() {
if (state.complete) return;
const visitedSingleThisTick =
state.singleVisited < MAX_SINGLE ? state.singleVisited++ : -1;
const visitedPairThisTick =
state.pairVisited < MAX_PAIRS ? state.pairVisited++ : -1;
if (visitedSingleThisTick >= 0) visitSingle(visitedSingleThisTick);
if (visitedPairThisTick >= 0) visitPair(visitedPairThisTick);
updateSourceHighlights();
updateHUD();
if (
state.singleVisited === MAX_SINGLE &&
state.pairVisited === MAX_PAIRS
) {
state.complete = true;
matrixMaterial.emissiveIntensity = 0.25;
setPlaying(false);
pauseBtn.textContent = "Complete";
stepBtn.disabled = true;
}
}
function resetTrace() {
state.singleVisited = 0;
state.pairVisited = 0;
state.activeSingle = 0;
state.activePairRow = 0;
state.activePairColumn = 0;
state.complete = false;
state.startDelay = 0.4;
state.singlePulse = 0;
state.pairPulse = 0;
for (let i = 0; i < stripTiles.length; i++) {
stripTiles[i].material.color.set(0x183247);
stripTiles[i].material.emissive.set(0x000000);
stripTiles[i].material.emissiveIntensity = 1;
}
for (let row = 0; row < MATRIX_SIZE; row++) {
for (let col = 0; col < MATRIX_SIZE; col++) {
matrix.setColorAt(
row * MATRIX_SIZE + col,
(row + col) % 2 ? unvisitedA : unvisitedB
);
}
}
matrix.instanceColor.needsUpdate = true;
matrixMaterial.emissiveIntensity = 0.04;
stepBtn.disabled = false;
primeTrace();
updateHUD();
setPlaying(true);
}
pauseBtn.addEventListener("click", () => {
if (state.complete) return;
setPlaying(!state.playing);
updateHUD();
});
stepBtn.addEventListener("click", () => {
if (state.complete) return;
state.startDelay = 0;
setPlaying(false);
executeOneLogicalTick();
});
replayBtn.addEventListener("click", resetTrace);
speedEl.addEventListener("input", () => {
state.speed = Number(speedEl.value);
speedValueEl.textContent = `${state.speed.toFixed(1)}×`;
});
window.addEventListener("keydown", (event) => {
if (event.code === "Space") {
event.preventDefault();
pauseBtn.click();
} else if (event.code === "ArrowRight") {
event.preventDefault();
stepBtn.click();
} else if (event.key.toLowerCase() === "r") {
resetTrace();
}
});
function onResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
}
window.addEventListener("resize", onResize);
resetTrace();
// Animation loop. The accumulator never skips logical iterations:
// at most one exact body execution is committed per animation frame.
const clock = new THREE.Clock();
let accumulator = 0;
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
updateCamera(dt);
if (state.startDelay > 0) {
state.startDelay = Math.max(0, state.startDelay - dt);
} else if (state.playing) {
accumulator += dt * 1000;
const interval = 75 / state.speed;
if (accumulator >= interval) {
accumulator = Math.max(0, accumulator - interval);
executeOneLogicalTick();
}
} else {
accumulator = 0;
}
const probeEase = 1 - Math.exp(-22 * dt);
singleProbe.position.lerp(singleTarget, probeEase);
pairProbe.position.lerp(pairTarget, probeEase);
const bob = Math.sin(elapsed * 4.5) * 0.035;
singleCore.position.y = 0.29 + bob;
pairCore.position.y = 0.16 + bob * 0.55;
state.singlePulse = Math.max(0, state.singlePulse - dt * 4.5);
state.pairPulse = Math.max(0, state.pairPulse - dt * 4.5);
singleRing.scale.setScalar(1 + (1 - state.singlePulse) * 0.9);
singleRing.material.opacity = 0.25 + state.singlePulse * 0.7;
pairRing.scale.setScalar(1 + (1 - state.pairPulse) * 0.85);
pairRing.material.opacity = 0.2 + state.pairPulse * 0.65;
for (const tile of sourceTiles) {
const target = tile.userData.targetScale;
const scale = THREE.MathUtils.lerp(tile.scale.x, target, probeEase);
tile.scale.set(scale, 1, scale);
}
particles.rotation.y = elapsed * 0.006;
particles.position.y = Math.sin(elapsed * 0.16) * 0.12;
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```