Prompt specification
Build or customize the Three.js 3D scene "Recursive and iterative sum comparison" 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: Recursive and iterative sum comparison
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/recursive-and-iterative-sum-comparison-x1898
Scene Description Prompt:
Compute a small list sum with a recursive call stack and an iterative accumulator side by side; display equivalent results with different execution structures. Build this with Three.js from cdnjs as a stylized scene in one HTML file.
Working Three.js Starter (recursive-and-iterative-sum-comparison-x1898):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>One Sum — Two Execution Shapes</title>
<style>
:root {
--bg: #070b14;
--panel: rgba(10, 18, 34, 0.78);
--line: rgba(155, 205, 255, 0.15);
--text: #eef8ff;
--muted: #8ca3ba;
--cyan: #36e6ff;
--pink: #ff4fd8;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 20% 15%, rgba(27, 111, 153, 0.18), transparent 32%),
radial-gradient(circle at 80% 30%, rgba(161, 32, 130, 0.16), transparent 34%),
linear-gradient(145deg, #070b14 0%, #090e1a 55%, #060911 100%);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#scene canvas.dragging {
cursor: grabbing;
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
}
header {
position: absolute;
top: 24px;
left: 50%;
width: min(760px, calc(100% - 32px));
transform: translateX(-50%);
text-align: center;
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 9px;
margin-bottom: 8px;
color: #a8c3da;
font: 600 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 16px var(--cyan);
content: "";
}
h1 {
margin: 0;
font-size: clamp(28px, 4vw, 54px);
font-weight: 650;
line-height: 1.05;
letter-spacing: -0.045em;
text-shadow: 0 8px 40px rgba(0, 0, 0, 0.45);
}
h1 em {
color: transparent;
background: linear-gradient(90deg, var(--cyan), #d8f8ff 45%, var(--pink));
background-clip: text;
-webkit-background-clip: text;
font-style: normal;
}
header p {
margin: 10px 0 0;
color: var(--muted);
font-size: 14px;
letter-spacing: 0.01em;
}
.status {
display: inline-flex;
align-items: center;
gap: 9px;
margin-top: 13px;
padding: 7px 12px;
border: 1px solid rgba(142, 191, 225, 0.16);
border-radius: 999px;
background: rgba(8, 15, 28, 0.68);
color: #b8cede;
font: 500 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.035em;
backdrop-filter: blur(12px);
}
.status-dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px var(--cyan);
}
.method-key {
position: absolute;
top: 190px;
display: flex;
align-items: flex-start;
gap: 11px;
width: 240px;
color: var(--muted);
}
.method-key.left {
left: 28px;
}
.method-key.right {
right: 28px;
flex-direction: row-reverse;
text-align: right;
}
.method-number {
color: var(--cyan);
font: 700 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.method-key.right .method-number {
color: var(--pink);
}
.method-key b {
display: block;
margin-bottom: 6px;
color: #dcebf5;
font-size: 12px;
font-weight: 600;
}
.method-key code {
display: block;
font: 500 10px/1.55 ui-monospace, SFMono-Regular, Menlo, monospace;
opacity: 0.78;
}
.phase {
display: inline-block;
margin-top: 7px;
color: var(--cyan);
font: 600 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.method-key.right .phase {
color: var(--pink);
}
.phase[data-state="complete"] {
color: #a8ffcb;
}
.results {
position: absolute;
right: 28px;
bottom: 28px;
left: 28px;
display: flex;
justify-content: space-between;
}
.result {
width: 225px;
padding: 13px 15px;
border: 1px solid var(--line);
border-radius: 14px;
background: linear-gradient(145deg, rgba(13, 24, 43, 0.86), rgba(7, 13, 25, 0.72));
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.24);
backdrop-filter: blur(14px);
transition: border-color 240ms ease, box-shadow 240ms ease;
}
.result.recursive {
border-left: 2px solid rgba(54, 230, 255, 0.6);
}
.result.iterative {
border-right: 2px solid rgba(255, 79, 216, 0.6);
text-align: right;
}
.result.ready.recursive {
border-color: rgba(54, 230, 255, 0.5);
box-shadow: 0 0 35px rgba(54, 230, 255, 0.1);
}
.result.ready.iterative {
border-color: rgba(255, 79, 216, 0.5);
box-shadow: 0 0 35px rgba(255, 79, 216, 0.1);
}
.result-label {
display: block;
color: #8fa7bb;
font: 600 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.result strong {
display: block;
margin-top: 5px;
font: 650 31px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.result.recursive strong {
color: var(--cyan);
}
.result.iterative strong {
color: var(--pink);
}
.controls {
position: absolute;
bottom: 30px;
left: 50%;
display: flex;
align-items: center;
gap: 9px;
transform: translateX(-50%);
pointer-events: auto;
}
button {
appearance: none;
border: 1px solid rgba(145, 200, 235, 0.2);
border-radius: 10px;
padding: 10px 14px;
background: rgba(10, 20, 36, 0.88);
color: #dff5ff;
font: 600 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
cursor: pointer;
backdrop-filter: blur(10px);
transition: transform 150ms ease, border-color 150ms ease, background 150ms ease;
}
button:hover {
border-color: rgba(54, 230, 255, 0.55);
background: rgba(17, 34, 55, 0.95);
transform: translateY(-1px);
}
button:disabled {
cursor: default;
opacity: 0.42;
transform: none;
}
.tip {
margin-left: 7px;
color: #6f879c;
font: 500 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
white-space: nowrap;
}
.progress {
position: absolute;
right: 0;
bottom: 0;
left: 0;
height: 3px;
background: rgba(255, 255, 255, 0.035);
}
.progress span {
display: block;
width: 0;
height: 100%;
background: linear-gradient(90deg, var(--cyan), #b5f7ff 50%, var(--pink));
box-shadow: 0 0 18px rgba(54, 230, 255, 0.5);
transition: width 420ms ease;
}
@media (max-width: 1050px) {
.method-key {
display: none;
}
}
@media (max-width: 680px) {
header {
top: 18px;
}
header p {
font-size: 12px;
}
.status {
margin-top: 10px;
}
.results {
right: 14px;
bottom: 76px;
left: 14px;
}
.result {
width: 44%;
padding: 10px 12px;
}
.result strong {
font-size: 25px;
}
.controls {
bottom: 20px;
}
.tip {
display: none;
}
}
</style>
</head>
<body>
<div
id="scene"
role="img"
aria-label="A recursive call stack and an iterative accumulator loop computing the sum fourteen"
></div>
<div class="hud">
<header>
<div class="eyebrow">Algorithm field lab / execution structures</div>
<h1>One sum. <em>Two execution shapes.</em></h1>
<p>xs = [3, 2, 5, 4] · recursive descent versus iterative accumulation</p>
<div class="status" aria-live="polite">
<span class="status-dot"></span>
<span id="statusText">Preparing both executions…</span>
</div>
</header>
<aside class="method-key left">
<span class="method-number">01</span>
<div>
<b>Recursive call stack</b>
<code>f(i, acc)<br>→ f(i + 1, acc + xs[i])</code>
<span class="phase" id="recPhase" data-state="waiting">waiting</span>
</div>
</aside>
<aside class="method-key right">
<span class="method-number">02</span>
<div>
<b>Iterative accumulator</b>
<code>for (const x of xs)<br>acc += x</code>
<span class="phase" id="iterPhase" data-state="waiting">waiting</span>
</div>
</aside>
<div class="results" aria-live="polite">
<section class="result recursive" id="recResult">
<span class="result-label">Recursive result</span>
<strong id="recResultValue">…</strong>
</section>
<section class="result iterative" id="iterResult">
<span class="result-label">Iterative result</span>
<strong id="iterResultValue">…</strong>
</section>
</div>
<div class="controls">
<button id="replayButton" type="button">↻ Replay</button>
<button id="pauseButton" type="button">Pause</button>
<span class="tip">drag to orbit · scroll to zoom</span>
</div>
<div class="progress"><span id="progressFill"></span></div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Algorithm traces
// -------------------------------------------------------------------------
const values = [3, 2, 5, 4];
function buildRecursiveTrace(xs) {
const events = [];
function recursiveSum(index, accumulator) {
events.push({
type: "call",
index,
accumulator
});
if (index === xs.length) {
events.push({
type: "return",
index,
total: accumulator
});
return accumulator;
}
const total = recursiveSum(index + 1, accumulator + xs[index]);
events.push({
type: "return",
index,
total
});
return total;
}
const total = recursiveSum(0, 0);
return { total, events };
}
function buildIterativeTrace(xs) {
const events = [];
let accumulator = 0;
for (let index = 0; index < xs.length; index++) {
accumulator += xs[index];
events.push({
type: "step",
index,
value: xs[index],
accumulator
});
}
return {
total: accumulator,
events
};
}
const recursiveTrace = buildRecursiveTrace(values);
const iterativeTrace = buildIterativeTrace(values);
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
const container = document.getElementById("scene");
const scene = new THREE.Scene();
scene.fog = new THREE.FogExp2(0x070b14, 0.028);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
container.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const world = new THREE.Group();
scene.add(world);
const hemisphere = new THREE.HemisphereLight(0xb9e8ff, 0x07101e, 1.75);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xe9f7ff, 3.2);
keyLight.position.set(2, 9, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -10;
keyLight.shadow.camera.right = 10;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -8;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x28dfff, 55, 13, 2);
cyanLight.position.set(-6, 2.5, 3.5);
scene.add(cyanLight);
const pinkLight = new THREE.PointLight(0xff3dcf, 55, 13, 2);
pinkLight.position.set(6, 2.2, 3);
scene.add(pinkLight);
// Ground and grid.
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(30, 20),
new THREE.MeshStandardMaterial({
color: 0x070d18,
roughness: 0.88,
metalness: 0.12,
transparent: true,
opacity: 0.86
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -1.55;
floor.receiveShadow = true;
world.add(floor);
const grid = new THREE.GridHelper(26, 52, 0x235d76, 0x10263b);
grid.position.y = -1.535;
grid.material.transparent = true;
grid.material.opacity = 0.25;
world.add(grid);
// -------------------------------------------------------------------------
// Text sprites
// -------------------------------------------------------------------------
const textCanvas = document.createElement("canvas");
textCanvas.width = 1024;
textCanvas.height = 180;
const textContext = textCanvas.getContext("2d");
function roundedRect(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
}
function makeTextTexture(main, sub, accent) {
const ctx = textContext;
const accentColor = "#" + new THREE.Color(accent).getHexString();
ctx.clearRect(0, 0, textCanvas.width, textCanvas.height);
const gradient = ctx.createLinearGradient(0, 0, textCanvas.width, 0);
gradient.addColorStop(0, "rgba(12, 26, 47, 0.96)");
gradient.addColorStop(1, "rgba(7, 15, 30, 0.88)");
roundedRect(ctx, 3, 3, 1018, 174, 24);
ctx.fillStyle = gradient;
ctx.fill();
ctx.strokeStyle = accentColor;
ctx.globalAlpha = 0.48;
ctx.lineWidth = 3;
ctx.stroke();
ctx.globalAlpha = 1;
ctx.fillStyle = accentColor;
roundedRect(ctx, 25, 23, 7, 134, 4);
ctx.fill();
ctx.fillStyle = "#effaff";
ctx.font = "600 51px ui-monospace, SFMono-Regular, Menlo, monospace";
ctx.fillText(main, 57, 72, 925);
ctx.fillStyle = "#91a9bc";
ctx.font = "500 29px ui-monospace, SFMono-Regular, Menlo, monospace";
ctx.fillText(sub, 57, 132, 925);
const texture = new THREE.CanvasTexture(textCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.needsUpdate = true;
return texture;
}
function setSpriteText(sprite, main, sub, accent) {
const oldTexture = sprite.material.map;
sprite.material.map = makeTextTexture(main, sub, accent);
sprite.material.needsUpdate = true;
if (oldTexture) {
oldTexture.dispose();
}
}
function makeTextSprite(main, sub, accent, width) {
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: makeTextTexture(main, sub, accent),
transparent: true,
depthTest: false,
depthWrite: false,
toneMapped: false
})
);
sprite.scale.set(width, width / (1024 / 180), 1);
sprite.renderOrder = 10;
return sprite;
}
function makeSimpleText(text, color = "#ffffff", size = 0.8) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 256;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, 256, 256);
ctx.fillStyle = color;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = "700 104px ui-monospace, SFMono-Regular, Menlo, monospace";
ctx.fillText(text, 128, 132);
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,
toneMapped: false
})
);
sprite.scale.set(size, size, 1);
sprite.renderOrder = 12;
return sprite;
}
// -------------------------------------------------------------------------
// Reusable scene pieces
// -------------------------------------------------------------------------
function makeBoard(x, accent) {
const group = new THREE.Group();
const panel = new THREE.Mesh(
new THREE.BoxGeometry(5.3, 6.3, 0.18),
new THREE.MeshPhysicalMaterial({
color: 0x0a1426,
emissive: accent,
emissiveIntensity: 0.025,
roughness: 0.32,
metalness: 0.42,
transparent: true,
opacity: 0.82,
clearcoat: 0.35,
clearcoatRoughness: 0.5
})
);
panel.position.set(x, 1.7, -0.34);
panel.receiveShadow = true;
panel.castShadow = true;
group.add(panel);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(panel.geometry),
new THREE.LineBasicMaterial({
color: accent,
transparent: true,
opacity: 0.36
})
);
edges.position.copy(panel.position);
group.add(edges);
const topLine = new THREE.Mesh(
new THREE.BoxGeometry(4.55, 0.025, 0.035),
new THREE.MeshBasicMaterial({
color: accent,
transparent: true,
opacity: 0.72
})
);
topLine.position.set(x, 4.77, -0.21);
group.add(topLine);
const bottomLine = topLine.clone();
bottomLine.position.y = -1.37;
group.add(bottomLine);
world.add(group);
return group;
}
function makeCard(width, height, accent, x, y, z = 0.02) {
const group = new THREE.Group();
const material = new THREE.MeshStandardMaterial({
color: 0x0a172a,
emissive: accent,
emissiveIntensity: 0.055,
roughness: 0.36,
metalness: 0.46
});
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, 0.15),
material
);
mesh.castShadow = true;
mesh.receiveShadow = true;
group.add(mesh);
const edgeMaterial = new THREE.LineBasicMaterial({
color: accent,
transparent: true,
opacity: 0.38
});
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(mesh.geometry),
edgeMaterial
);
group.add(edges);
const label = makeTextSprite("INITIAL", "waiting", accent, width * 0.8);
label.position.z = 0.11;
group.add(label);
group.position.set(x, y, z);
world.add(group);
return {
group,
mesh,
edges,
edgeMaterial,
label,
accent,
baseY: y
};
}
const CYAN = 0x36e6ff;
const PINK = 0xff4fd8;
makeBoard(-3.35, CYAN);
makeBoard(3.35, PINK);
// Equality marker between the two structures.
const equalsSprite = makeSimpleText("=", "#dff8ff", 0.8);
equalsSprite.position.set(0, 1.5, 0.2);
world.add(equalsSprite);
// -------------------------------------------------------------------------
// Recursive call stack
// -------------------------------------------------------------------------
const recTitle = makeTextSprite(
"RECURSIVE",
"call stack • f(index, accumulator)",
CYAN,
4.45
);
recTitle.position.set(-3.35, 4.43, -0.12);
world.add(recTitle);
const recCardY = [-0.1, 0.74, 1.58, 2.42, 3.26];
const recCards = [];
for (let depth = 0; depth < recCardY.length; depth++) {
const card = makeCard(4.15, 0.64, CYAN, -3.35, recCardY[depth]);
card.group.visible = false;
card.group.scale.setScalar(0.88);
recCards.push(card);
}
const recConnectors = [];
for (let depth = 0; depth < recCardY.length - 1; depth++) {
const gapCenter =
(recCardY[depth] + 0.32 + recCardY[depth + 1] - 0.32) / 2;
const gapHeight = recCardY[depth + 1] - recCardY[depth] - 0.64;
const connector = new THREE.Mesh(
new THREE.CylinderGeometry(0.018, 0.018, gapHeight, 8),
new THREE.MeshBasicMaterial({
color: CYAN,
transparent: true,
opacity: 0.65
})
);
connector.position.set(-3.35, gapCenter, 0.12);
connector.visible = false;
world.add(connector);
recConnectors.push(connector);
}
const recResultCard = makeCard(2.7, 0.66, CYAN, -3.35, -1.08);
setSpriteText(
recResultCard.label,
"RESULT …",
"waiting for root return",
CYAN
);
const callPulse = new THREE.Mesh(
new THREE.SphereGeometry(0.07, 16, 16),
new THREE.MeshBasicMaterial({ color: 0xd8fbff })
);
callPulse.position.set(-3.35, recCardY[0], 0.48);
callPulse.visible = false;
world.add(callPulse);
// -------------------------------------------------------------------------
// Iterative loop
// -------------------------------------------------------------------------
const iterTitle = makeTextSprite(
"ITERATIVE",
"accumulator • for (const x of xs)",
PINK,
4.45
);
iterTitle.position.set(3.35, 4.43, -0.12);
world.add(iterTitle);
const loopCenter = new THREE.Vector3(3.35, 1.55, 0.12);
const loopRadiusX = 2.0;
const loopRadiusY = 2.1;
const nodeAngles = [Math.PI / 2, 0, -Math.PI / 2, -Math.PI];
const pathPoints = [];
for (let i = 0; i <= 160; i++) {
const angle = Math.PI / 2 - (i / 160) * Math.PI * 2;
pathPoints.push(
new THREE.Vector3(
loopCenter.x + Math.cos(angle) * loopRadiusX,
loopCenter.y + Math.sin(angle) * loopRadiusY,
0.06
)
);
}
const loopPath = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(pathPoints),
new THREE.LineBasicMaterial({
color: PINK,
transparent: true,
opacity: 0.42
})
);
world.add(loopPath);
// Small directional markers around the loop.
for (let i = 0; i < 12; i++) {
const angle = Math.PI / 2 - (i / 12) * Math.PI * 2;
const marker = new THREE.Mesh(
new THREE.ConeGeometry(0.035, 0.14, 3),
new THREE.MeshBasicMaterial({
color: PINK,
transparent: true,
opacity: 0.36
})
);
const x = loopCenter.x + Math.cos(angle) * loopRadiusX;
const y = loopCenter.y + Math.sin(angle) * loopRadiusY;
marker.position.set(x, y, 0.11);
const tangent = new THREE.Vector3(
Math.sin(angle),
-Math.cos(angle),
0
).normalize();
marker.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
tangent
);
world.add(marker);
}
const iterNodes = [];
for (let i = 0; i < values.length; i++) {
const angle = nodeAngles[i];
const x = loopCenter.x + Math.cos(angle) * loopRadiusX;
const y = loopCenter.y + Math.sin(angle) * loopRadiusY;
const group = new THREE.Group();
group.position.set(x, y, 0.27);
const core = new THREE.Mesh(
new THREE.SphereGeometry(0.31, 24, 24),
new THREE.MeshStandardMaterial({
color: 0x24112c,
emissive: PINK,
emissiveIntensity: 0.13,
roughness: 0.28,
metalness: 0.55
})
);
core.castShadow = true;
group.add(core);
const ringMaterial = new THREE.MeshBasicMaterial({
color: PINK,
transparent: true,
opacity: 0.28
});
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.43, 0.025, 8, 40),
ringMaterial
);
group.add(ring);
const label = makeSimpleText(String(values[i]), "#ffe5fa", 0.62);
label.position.z = 0.46;
group.add(label);
world.add(group);
iterNodes.push({ group, core, ring, ringMaterial, position: group.position });
}
const accumulatorCard = makeCard(2.75, 1.08, PINK, 3.35, 1.55, 0.38);
setSpriteText(
accumulatorCard.label,
"acc = 0",
"initialized accumulator",
PINK
);
const accumulatorHalo = new THREE.Mesh(
new THREE.TorusGeometry(0.96, 0.018, 8, 64),
new THREE.MeshBasicMaterial({
color: PINK,
transparent: true,
opacity: 0.25
})
);
accumulatorHalo.position.set(3.35, 1.55, 0.17);
world.add(accumulatorHalo);
const iterResultCard = makeCard(2.7, 0.66, PINK, 3.35, -1.08);
setSpriteText(
iterResultCard.label,
"RESULT …",
"waiting for loop completion",
PINK
);
const pointer = new THREE.Group();
pointer.position.copy(iterNodes[0].position);
pointer.position.z = 0.58;
const pointerCone = new THREE.Mesh(
new THREE.ConeGeometry(0.13, 0.35, 3),
new THREE.MeshBasicMaterial({ color: 0xffe9fb })
);
pointer.add(pointerCone);
const pointerCore = new THREE.Mesh(
new THREE.SphereGeometry(0.09, 16, 16),
new THREE.MeshBasicMaterial({ color: PINK })
);
pointerCore.position.y = -0.1;
pointer.add(pointerCore);
const pointerLight = new THREE.PointLight(PINK, 9, 3, 2);
pointer.add(pointerLight);
world.add(pointer);
const pointerTarget = pointer.position.clone();
const pointerTargetQuaternion = pointer.quaternion.clone();
// -------------------------------------------------------------------------
// Decorative particles
// -------------------------------------------------------------------------
let randomSeed = 1047;
function random() {
randomSeed = (randomSeed * 16807) % 2147483647;
return (randomSeed - 1) / 2147483646;
}
const particlePositions = [];
const particleColors = [];
for (let i = 0; i < 190; i++) {
const side = random() > 0.5 ? 1 : -1;
particlePositions.push(
side * (6.5 + random() * 6),
-1 + random() * 9,
-5 + random() * 4
);
const color = new THREE.Color(
random() > 0.5 ? CYAN : PINK
).multiplyScalar(0.35 + random() * 0.65);
particleColors.push(color.r, color.g, color.b);
}
const particleGeometry = new THREE.BufferGeometry();
particleGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(particlePositions, 3)
);
particleGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(particleColors, 3)
);
const particles = new THREE.Points(
particleGeometry,
new THREE.PointsMaterial({
size: 0.035,
vertexColors: true,
transparent: true,
opacity: 0.62,
depthWrite: false,
blending: THREE.AdditiveBlending
})
);
world.add(particles);
// -------------------------------------------------------------------------
// Custom camera controls — no addons
// -------------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 1.15, 0);
let targetAzimuth = 0;
let targetElevation = 0.11;
let targetDistance = 14.2;
let currentAzimuth = targetAzimuth;
let currentElevation = targetElevation;
let currentDistance = targetDistance;
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
renderer.domElement.classList.add("dragging");
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - previousPointerX;
const deltaY = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
targetAzimuth -= deltaX * 0.006;
targetElevation = THREE.MathUtils.clamp(
targetElevation + deltaY * 0.004,
-0.08,
0.5
);
});
function endDrag(event) {
dragging = false;
renderer.domElement.classList.remove("dragging");
if (event?.pointerId !== undefined) {
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
targetDistance = THREE.MathUtils.clamp(
targetDistance + event.deltaY * 0.008,
10,
21
);
},
{ passive: false }
);
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
camera.aspect = width / height;
camera.updateProjectionMatrix();
if (width < 680) {
targetDistance = 19.5;
world.scale.setScalar(0.68);
} else if (width < 1050) {
targetDistance = 16;
world.scale.setScalar(0.84);
} else {
targetDistance = 14.2;
world.scale.setScalar(1);
}
}
window.addEventListener("resize", resize);
resize();
// -------------------------------------------------------------------------
// Timeline
// -------------------------------------------------------------------------
const statusText = document.getElementById("statusText");
const recPhase = document.getElementById("recPhase");
const iterPhase = document.getElementById("iterPhase");
const recResult = document.getElementById("recResult");
const iterResult = document.getElementById("iterResult");
const recResultValue = document.getElementById("recResultValue");
const iterResultValue = document.getElementById("iterResultValue");
const progressFill = document.getElementById("progressFill");
const replayButton = document.getElementById("replayButton");
const pauseButton = document.getElementById("pauseButton");
const TICK_MS = 620;
const totalTicks = Math.max(
recursiveTrace.events.length,
iterativeTrace.events.length
);
let tick = -1;
let playing = true;
let paused = false;
let nextTickAt = performance.now() + 350;
let activeRecursiveDepth = -1;
let activeIterativeIndex = -1;
let recursiveComplete = false;
let iterativeComplete = false;
function setPhase(element, text, state) {
element.textContent = text;
element.dataset.state = state;
}
function resetTimeline() {
tick = -1;
playing = true;
paused = false;
nextTickAt = performance.now() + 350;
activeRecursiveDepth = -1;
activeIterativeIndex = -1;
recursiveComplete = false;
iterativeComplete = false;
recCards.forEach((card) => {
card.group.visible = false;
card.group.scale.setScalar(0.88);
});
recConnectors.forEach((connector) => {
connector.visible = false;
});
setSpriteText(
accumulatorCard.label,
"acc = 0",
"initialized accumulator",
PINK
);
setSpriteText(
recResultCard.label,
"RESULT …",
"waiting for root return",
CYAN
);
setSpriteText(
iterResultCard.label,
"RESULT …",
"waiting for loop completion",
PINK
);
recResultValue.textContent = "…";
iterResultValue.textContent = "…";
recResult.classList.remove("ready");
iterResult.classList.remove("ready");
setPhase(recPhase, "waiting", "waiting");
setPhase(iterPhase, "waiting", "waiting");
statusText.textContent = "Running both execution structures…";
progressFill.style.width = "0%";
callPulse.visible = false;
callPulse.position.set(-3.35, recCardY[0], 0.48);
pointer.position.copy(iterNodes[0].position);
pointer.position.z = 0.58;
pointerTarget.copy(pointer.position);
pauseButton.disabled = false;
pauseButton.textContent = "Pause";
}
function performTick() {
tick += 1;
// Recursive call / return event.
const recursiveEvent = recursiveTrace.events[tick];
if (recursiveEvent) {
activeRecursiveDepth = recursiveEvent.index;
const card = recCards[recursiveEvent.index];
if (recursiveEvent.type === "call") {
card.group.visible = true;
if (recursiveEvent.index < values.length) {
setSpriteText(
card.label,
`f(${recursiveEvent.index}) acc=${recursiveEvent.accumulator}`,
`+ ${values[recursiveEvent.index]} → f(${recursiveEvent.index + 1})`,
CYAN
);
} else {
setSpriteText(
card.label,
`f(${recursiveEvent.index}) BASE`,
`acc=${recursiveEvent.accumulator}`,
CYAN
);
}
if (recursiveEvent.index > 0) {
recConnectors[recursiveEvent.index - 1].visible = true;
}
setPhase(recPhase, "calling deeper", "running");
callPulse.visible = true;
callPulse.position.y = card.baseY + 0.25;
} else {
setSpriteText(
card.label,
`f(${recursiveEvent.index}) RETURN`,
`result = ${recursiveEvent.total}`,
CYAN
);
setPhase(recPhase, "unwinding stack", "running");
callPulse.visible = true;
callPulse.position.y = card.baseY;
if (recursiveEvent.index === 0) {
recursiveComplete = true;
recResultValue.textContent = String(recursiveEvent.total);
recResult.classList.add("ready");
setSpriteText(
recResultCard.label,
`RESULT ${recursiveEvent.total}`,
"root frame returned",
CYAN
);
setPhase(recPhase, "complete", "complete");
}
}
}
// Iterative accumulation event.
const iterativeEvent = iterativeTrace.events[tick];
if (iterativeEvent) {
activeIterativeIndex = iterativeEvent.index;
const node = iterNodes[iterativeEvent.index];
setSpriteText(
accumulatorCard.label,
`acc = ${iterativeEvent.accumulator}`,
`after xs[${iterativeEvent.index}] = ${iterativeEvent.value}`,
PINK
);
pointerTarget.copy(node.position);
pointerTarget.z = 0.58;
const previousNode = iterNodes[(iterativeEvent.index + 3) % 4];
const tangent = node.position.clone().sub(previousNode.position).normalize();
pointerTargetQuaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
tangent
);
setPhase(iterPhase, "accumulating", "running");
if (iterativeEvent.index === values.length - 1) {
iterativeComplete = true;
iterResultValue.textContent = String(iterativeTrace.total);
iterResult.classList.add("ready");
setSpriteText(
iterResultCard.label,
`RESULT ${iterativeTrace.total}`,
"loop completed",
PINK
);
setPhase(iterPhase, "complete", "complete");
}
} else if (iterativeComplete) {
setPhase(iterPhase, "complete", "complete");
}
if (recursiveComplete && iterativeComplete) {
statusText.textContent =
`Equivalent results: ${recursiveTrace.total} = ${iterativeTrace.total}`;
} else {
statusText.textContent = "Running both execution structures…";
}
progressFill.style.width = `${(tick / (totalTicks - 1)) * 100}%`;
if (tick >= totalTicks - 1) {
playing = false;
pauseButton.disabled = true;
pauseButton.textContent = "Complete";
}
}
replayButton.addEventListener("click", resetTimeline);
pauseButton.addEventListener("click", () => {
if (!playing) return;
paused = !paused;
pauseButton.textContent = paused ? "Resume" : "Pause";
if (!paused) {
nextTickAt = performance.now() + 80;
}
});
window.addEventListener("keydown", (event) => {
if (event.key.toLowerCase() === "r") {
resetTimeline();
}
if (event.code === "Space" && !event.repeat) {
event.preventDefault();
pauseButton.click();
}
});
resetTimeline();
// -------------------------------------------------------------------------
// Render loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
const up = new THREE.Vector3(0, 1, 0);
function animate(now) {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
const smoothing = 1 - Math.exp(-dt * 7);
if (playing && !paused && now >= nextTickAt) {
performTick();
nextTickAt = now + TICK_MS;
}
// Smooth custom camera movement.
currentAzimuth += (targetAzimuth - currentAzimuth) * smoothing;
currentElevation += (targetElevation - currentElevation) * smoothing;
currentDistance += (targetDistance - currentDistance) * smoothing;
const horizontalDistance =
currentDistance * Math.cos(currentElevation);
camera.position.set(
cameraTarget.x + Math.sin(currentAzimuth) * horizontalDistance,
cameraTarget.y + Math.sin(currentElevation) * currentDistance,
cameraTarget.z + Math.cos(currentAzimuth) * horizontalDistance
);
camera.lookAt(cameraTarget);
// Recursive frame highlights.
recCards.forEach((card, depth) => {
const isActive = depth === activeRecursiveDepth;
const targetScale = isActive ? 1.045 : 1;
const nextScale =
card.group.scale.x + (targetScale - card.group.scale.x) * smoothing;
card.group.scale.setScalar(nextScale);
card.mesh.material.emissiveIntensity =
isActive ? 0.23 + Math.sin(elapsed * 6) * 0.06 : 0.055;
card.edgeMaterial.opacity = isActive ? 0.95 : 0.35;
});
recConnectors.forEach((connector) => {
connector.material.opacity =
0.42 + Math.sin(elapsed * 4 + connector.position.y) * 0.14;
});
// Iterative node highlights.
iterNodes.forEach((node, index) => {
const isActive = index === activeIterativeIndex;
const targetScale = isActive ? 1.18 : 1;
const nextScale =
node.group.scale.x + (targetScale - node.group.scale.x) * smoothing;
node.group.scale.setScalar(nextScale);
node.core.material.emissiveIntensity = isActive ? 0.72 : 0.13;
node.ringMaterial.opacity = isActive ? 0.95 : 0.28;
node.ring.scale.setScalar(
isActive ? 1 + Math.sin(elapsed * 5) * 0.04 : 1
);
});
// Smooth pointer movement around the loop.
pointer.position.lerp(pointerTarget, smoothing);
pointer.quaternion.slerp(pointerTargetQuaternion, smoothing);
accumulatorHalo.rotation.z = elapsed * 0.12;
accumulatorHalo.material.opacity =
0.2 + Math.sin(elapsed * 2.5) * 0.07;
particles.rotation.y = Math.sin(elapsed * 0.05) * 0.08;
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```