Prompt specification
Build or customize the Three.js 3D scene "Add quantities through visible regrouping" 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: Add quantities through visible regrouping
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/add-quantities-through-visible-regrouping-x2484
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows place-value arithmetic on an abacus. Let users enter two small numbers and add them on the counting frame. Animate every carry operation and verify that bead representation matches the resulting symbolic total. Voxel style.
Working Three.js Starter (add-quantities-through-visible-regrouping-x2484):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Abacus — Place-Value Arithmetic</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(9, 20, 35, 0.91);
--panel-border: rgba(132, 190, 222, 0.25);
--text: #ecf7ff;
--muted: #91a9bc;
--cyan: #51dfca;
--gold: #ffd166;
--orange: #ff8a3d;
--red: #ff647c;
--green: #72f1a6;
--blue: #70b7ff;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
"Liberation Mono", monospace;
color: var(--text);
}
button,
input {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene.dragging {
cursor: grabbing;
}
.panel {
position: fixed;
z-index: 10;
top: 18px;
left: 18px;
width: min(360px, calc(100vw - 36px));
max-height: calc(100vh - 36px);
overflow: auto;
padding: 18px;
background: var(--panel);
border: 1px solid var(--panel-border);
box-shadow:
0 18px 60px rgba(0, 0, 0, 0.36),
inset 0 1px rgba(255, 255, 255, 0.05);
backdrop-filter: blur(14px);
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 7px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 10px;
height: 10px;
background: var(--cyan);
box-shadow: 4px 4px 0 rgba(81, 223, 202, 0.25);
}
h1 {
margin: 0;
font-size: clamp(23px, 3vw, 31px);
line-height: 1.05;
letter-spacing: -0.045em;
}
.intro {
margin: 10px 0 17px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.input-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.field label {
display: block;
margin-bottom: 6px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.field.a label {
color: var(--cyan);
}
.field.b label {
color: var(--orange);
}
input {
width: 100%;
height: 47px;
padding: 0 12px;
color: var(--text);
background: rgba(255, 255, 255, 0.055);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 0;
outline: none;
font-size: 21px;
font-weight: 800;
}
input:focus {
border-color: var(--cyan);
box-shadow: 0 0 0 3px rgba(81, 223, 202, 0.1);
}
.field.b input:focus {
border-color: var(--orange);
box-shadow: 0 0 0 3px rgba(255, 138, 61, 0.1);
}
.actions {
display: grid;
grid-template-columns: 1fr 86px;
gap: 9px;
margin-top: 12px;
}
button {
min-height: 43px;
padding: 9px 12px;
color: var(--text);
background: rgba(255, 255, 255, 0.07);
border: 1px solid rgba(255, 255, 255, 0.16);
border-radius: 0;
cursor: pointer;
font-size: 11px;
font-weight: 900;
letter-spacing: 0.07em;
text-transform: uppercase;
transition:
background 120ms ease,
transform 120ms ease,
border-color 120ms ease;
}
button:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.12);
border-color: rgba(255, 255, 255, 0.32);
transform: translateY(-1px);
}
button:active:not(:disabled) {
transform: translateY(1px);
}
button:disabled {
cursor: wait;
opacity: 0.48;
}
.primary {
color: #06131d;
background: var(--cyan);
border-color: var(--cyan);
box-shadow: 5px 5px 0 rgba(81, 223, 202, 0.16);
}
.primary:hover:not(:disabled) {
background: #7cebdc;
border-color: #7cebdc;
}
.presets {
display: flex;
flex-wrap: wrap;
gap: 7px;
margin-top: 10px;
}
.presets button {
min-height: 31px;
padding: 6px 9px;
color: var(--muted);
font-size: 9px;
}
.readout {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1px;
margin-top: 16px;
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.1);
}
.readout > div {
padding: 11px 12px;
background: rgba(5, 14, 25, 0.88);
}
.readout span {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.readout strong {
font-size: 24px;
letter-spacing: -0.05em;
}
.status {
min-height: 71px;
margin-top: 12px;
padding: 11px 12px;
background: rgba(255, 255, 255, 0.045);
border-left: 3px solid var(--blue);
}
.status.carry {
border-left-color: var(--orange);
}
.status.good {
border-left-color: var(--green);
}
.status.error {
border-left-color: var(--red);
}
.status-title {
color: var(--text);
font-size: 11px;
font-weight: 900;
line-height: 1.4;
}
.status-detail {
margin-top: 4px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 8px 14px;
margin-top: 13px;
color: var(--muted);
font-size: 9px;
line-height: 1.4;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 10px;
height: 10px;
background: var(--gold);
box-shadow: 2px 2px 0 rgba(0, 0, 0, 0.3);
}
.swatch.lower {
background: var(--cyan);
}
.verification {
position: fixed;
z-index: 10;
right: 18px;
bottom: 18px;
width: min(370px, calc(100vw - 36px));
padding: 15px 17px;
background: rgba(7, 17, 31, 0.91);
border: 1px solid rgba(114, 241, 166, 0.38);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(14px);
pointer-events: none;
}
.verification.pending {
border-color: rgba(112, 183, 255, 0.38);
}
.verification.idle {
border-color: var(--panel-border);
}
.verification.error {
border-color: rgba(255, 100, 124, 0.5);
}
.verify-heading {
display: flex;
align-items: center;
gap: 9px;
color: var(--green);
font-size: 12px;
font-weight: 900;
letter-spacing: 0.08em;
}
.pending .verify-heading {
color: var(--blue);
}
.idle .verify-heading {
color: var(--muted);
}
.error .verify-heading {
color: var(--red);
}
.verify-icon {
display: grid;
width: 23px;
height: 23px;
place-items: center;
color: #07111f;
background: currentColor;
font-size: 14px;
}
.verify-icon span {
color: #07111f;
}
.verify-equation {
margin-top: 10px;
font-size: 18px;
font-weight: 900;
letter-spacing: -0.035em;
}
.verify-readback {
margin-top: 7px;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.camera-help {
position: fixed;
z-index: 5;
top: 18px;
right: 18px;
padding: 9px 11px;
color: var(--muted);
background: rgba(7, 17, 31, 0.72);
border: 1px solid rgba(255, 255, 255, 0.1);
font-size: 9px;
line-height: 1.5;
text-align: right;
}
.camera-help button {
min-height: 29px;
margin-top: 6px;
padding: 5px 9px;
font-size: 8px;
}
@media (max-width: 720px) {
.panel {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
max-height: 52vh;
padding: 13px;
}
.intro {
margin-bottom: 12px;
}
.camera-help {
top: auto;
right: 10px;
bottom: 119px;
}
.verification {
right: 10px;
bottom: 10px;
width: calc(100vw - 20px);
padding: 12px 14px;
}
.verify-equation {
font-size: 15px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive three-dimensional voxel abacus"></canvas>
<main class="panel">
<div class="eyebrow">Place-value laboratory</div>
<h1>Voxel Abacus</h1>
<p class="intro">
Enter two numbers from 0 to 99. The counting frame performs ordinary
decimal addition, visibly sending every carry to the next place.
</p>
<div class="input-grid">
<div class="field a">
<label for="numberA">Number A</label>
<input id="numberA" type="number" min="0" max="99" step="1" value="27">
</div>
<div class="field b">
<label for="numberB">Number B</label>
<input id="numberB" type="number" min="0" max="99" step="1" value="38">
</div>
</div>
<div class="actions">
<button id="addButton" class="primary">Add on frame</button>
<button id="clearButton">Clear</button>
</div>
<div class="presets" aria-label="Example additions">
<button data-a="27" data-b="38">27 + 38</button>
<button data-a="49" data-b="53">49 + 53</button>
<button data-a="99" data-b="99">99 + 99</button>
<button data-a="8" data-b="7">8 + 7</button>
</div>
<div class="readout" aria-label="Arithmetic readouts">
<div>
<span>Expected total</span>
<strong id="expectedValue">65</strong>
</div>
<div>
<span>Current frame</span>
<strong id="frameValue">000</strong>
</div>
</div>
<div id="status" class="status" role="status" aria-live="polite">
<div id="statusTitle" class="status-title">FRAME READY</div>
<div id="statusDetail" class="status-detail">
Upper bead down = 5. Each lower bead down = 1.
</div>
</div>
<div class="legend">
<span class="legend-item">
<i class="swatch"></i>
Upper bead: 5
</span>
<span class="legend-item">
<i class="swatch lower"></i>
Lower beads: 1 each
</span>
<span class="legend-item">Orange voxel = carry</span>
</div>
</main>
<aside class="camera-help">
Drag to orbit · Scroll to zoom
<br>Double-click the frame to reset
<button id="cameraReset">Reset camera</button>
</aside>
<aside id="verification" class="verification idle" aria-live="polite">
<div class="verify-heading">
<span class="verify-icon"><span>✓</span></span>
<span>READY TO VERIFY</span>
</div>
<div class="verify-equation">27 + 38 = 65</div>
<div class="verify-readback">
After the animation, the frame will be read back bead by bead.
</div>
</aside>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// DOM and state
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const numberAInput = document.querySelector("#numberA");
const numberBInput = document.querySelector("#numberB");
const addButton = document.querySelector("#addButton");
const clearButton = document.querySelector("#clearButton");
const cameraResetButton = document.querySelector("#cameraReset");
const expectedValueElement = document.querySelector("#expectedValue");
const frameValueElement = document.querySelector("#frameValue");
const statusElement = document.querySelector("#status");
const statusTitleElement = document.querySelector("#statusTitle");
const statusDetailElement = document.querySelector("#statusDetail");
const verificationElement = document.querySelector("#verification");
const reducedMotion = window.matchMedia(
"(prefers-reduced-motion: reduce)"
).matches;
const PLACE_NAMES = ["ONES", "TENS", "HUNDREDS"];
const PLACE_SHORT_NAMES = ["ones", "tens", "hundreds"];
let busy = false;
let expectedTotal = 65;
// -------------------------------------------------------------------------
// Three.js setup
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 12, 24);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
60
);
const cameraTarget = new THREE.Vector3(0, 0.25, 0);
let cameraYaw = -0.08;
let cameraPitch = 0.055;
let cameraRadius = window.innerWidth < 720 ? 9.6 : 8.6;
function updateCamera() {
const horizontalRadius = cameraRadius * Math.cos(cameraPitch);
camera.position.set(
cameraTarget.x + Math.sin(cameraYaw) * horizontalRadius,
cameraTarget.y + Math.sin(cameraPitch) * cameraRadius,
cameraTarget.z + Math.cos(cameraYaw) * horizontalRadius
);
camera.lookAt(cameraTarget);
}
updateCamera();
const hemisphereLight = new THREE.HemisphereLight(
0xb9e8ff,
0x1b1320,
1.8
);
scene.add(hemisphereLight);
const keyLight = new THREE.DirectionalLight(0xfff0d2, 3.1);
keyLight.position.set(4.5, 8, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -8;
keyLight.shadow.camera.right = 8;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -8;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4cd8ff, 1.7);
rimLight.position.set(-6, 4, -4);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xff8b45, 12, 8, 2);
warmLight.position.set(4, -0.3, 3.5);
scene.add(warmLight);
// -------------------------------------------------------------------------
// Materials and voxel construction helpers
// -------------------------------------------------------------------------
function standardMaterial(color, roughness = 0.65, metalness = 0.04) {
return new THREE.MeshStandardMaterial({
color,
roughness,
metalness,
flatShading: true
});
}
const frameMaterial = standardMaterial(0x805239, 0.74);
const frameEdgeMaterial = standardMaterial(0xa76d45, 0.68);
const beamMaterial = standardMaterial(0xd29a5b, 0.56);
const rodMaterial = standardMaterial(0x3d5365, 0.42, 0.35);
const floorMaterial = standardMaterial(0x0b1929, 0.88);
const gridMaterial = new THREE.MeshBasicMaterial({
color: 0x163149,
transparent: true,
opacity: 0.48
});
function addBox(
width,
height,
depth,
material,
x = 0,
y = 0,
z = 0,
parent = scene
) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// Voxel floor.
const floor = addBox(
18,
0.36,
12,
floorMaterial,
0,
-2.05,
0
);
floor.receiveShadow = true;
for (let i = -8; i <= 8; i += 1) {
addBox(14, 0.012, 0.025, gridMaterial, 0, -1.858, i);
}
for (let i = -7; i <= 7; i += 1) {
addBox(0.025, 0.012, 10, gridMaterial, i, -1.857, 0);
}
// Small decorative voxel blocks.
const decorationMaterials = [
standardMaterial(0x15314a, 0.8),
standardMaterial(0x1b4052, 0.8),
standardMaterial(0x22384a, 0.8)
];
[
[-4.4, -1.62, -2.4, 0.48],
[-5.2, -1.72, 1.7, 0.34],
[4.8, -1.68, -1.5, 0.42],
[5.4, -1.73, 2.2, 0.3],
[-3.8, -1.69, 3.2, 0.28]
].forEach(([x, y, z, size], index) => {
addBox(
size,
size,
size,
decorationMaterials[index % decorationMaterials.length],
x,
y,
z
);
});
// -------------------------------------------------------------------------
// Abacus frame
// -------------------------------------------------------------------------
const FRAME_LEFT = -2.02;
const FRAME_RIGHT = 2.02;
addBox(
FRAME_RIGHT - FRAME_LEFT + 0.38,
0.3,
0.5,
frameMaterial,
0,
2.08,
0
);
addBox(
FRAME_RIGHT - FRAME_LEFT + 0.38,
0.18,
0.58,
beamMaterial,
0,
0.62,
0.03
);
addBox(
FRAME_RIGHT - FRAME_LEFT + 0.38,
0.3,
0.5,
frameMaterial,
0,
-1.55,
0
);
addBox(0.31, 3.92, 0.5, frameMaterial, FRAME_LEFT, 0.25, 0);
addBox(0.31, 3.92, 0.5, frameMaterial, FRAME_RIGHT, 0.25, 0);
// Decorative frame joints.
for (const x of [FRAME_LEFT, FRAME_RIGHT]) {
addBox(0.48, 0.25, 0.66, frameEdgeMaterial, x, 2.08, 0);
addBox(0.48, 0.25, 0.66, frameEdgeMaterial, x, -1.55, 0);
addBox(0.48, 0.25, 0.66, frameEdgeMaterial, x, 0.62, 0);
}
// -------------------------------------------------------------------------
// Labels made using CanvasTexture sprites
// -------------------------------------------------------------------------
function makeLabelSprite(
text,
color = "#ecf7ff",
background = "rgba(7,17,31,0.82)",
width = 1.4,
height = 0.32
) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 128;
const context = labelCanvas.getContext("2d");
context.clearRect(0, 0, 512, 128);
if (background) {
context.fillStyle = background;
context.fillRect(0, 0, 512, 128);
}
context.font = "900 48px monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = color;
context.fillText(text, 256, 67);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.NearestFilter;
texture.magFilter = THREE.NearestFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(width, height, 1);
sprite.userData.texture = texture;
return sprite;
}
function disposeSprite(sprite) {
scene.remove(sprite);
sprite.material.map?.dispose();
sprite.material.dispose();
}
// -------------------------------------------------------------------------
// Beads and columns
// -------------------------------------------------------------------------
const UPPER_UP = 1.58;
const UPPER_DOWN = 0.92;
const LOWER_UP = [0.48, 0.34, 0.20, 0.06];
const LOWER_DOWN = [-0.08, -0.38, -0.68, -0.98];
function createVoxelBead(color, isUpper = false) {
const group = new THREE.Group();
const beadMaterial = standardMaterial(color, 0.4, 0.08);
const studMaterial = standardMaterial(
new THREE.Color(color).multiplyScalar(1.18),
0.32,
0.1
);
const width = isUpper ? 0.76 : 0.66;
const height = isUpper ? 0.33 : 0.27;
const depth = isUpper ? 0.5 : 0.46;
addBox(width, height, depth, beadMaterial, 0, 0, 0, group);
const studOffsets = isUpper ? [-0.23, 0, 0.23] : [-0.18, 0.18];
for (const offset of studOffsets) {
addBox(
0.11,
0.11,
0.075,
studMaterial,
offset,
0,
depth / 2 + 0.035,
group
);
}
group.traverse((object) => {
if (object.isMesh) {
object.castShadow = true;
object.receiveShadow = true;
}
});
return group;
}
function createHighlight(column) {
const group = new THREE.Group();
group.position.x = column.x;
const material = new THREE.MeshBasicMaterial({
color: 0x51dfca,
transparent: true,
opacity: 0,
depthWrite: false
});
addBox(0.96, 0.055, 0.7, material, 0, 1.95, 0.42, group);
addBox(0.96, 0.055, 0.7, material, 0, -1.35, 0.42, group);
addBox(0.055, 3.3, 0.7, material, -0.48, 0.3, 0.42, group);
addBox(0.055, 3.3, 0.7, material, 0.48, 0.3, 0.42, group);
group.visible = false;
scene.add(group);
return { group, material };
}
function createColumn(place, x, title) {
addBox(0.085, 3.36, 0.085, rodMaterial, x, 0.22, 0);
const upper = createVoxelBead(0xffca58, true);
upper.position.set(x, UPPER_UP, 0);
scene.add(upper);
const lower = [];
for (let index = 0; index < 4; index += 1) {
const bead = createVoxelBead(0x4dd6c7, false);
bead.position.set(x, LOWER_UP[index], 0);
scene.add(bead);
lower.push(bead);
}
const label = makeLabelSprite(
title,
"#bcd3e3",
"rgba(7,17,31,0.74)",
1.35,
0.32
);
label.position.set(x, 2.55, 0.36);
scene.add(label);
const column = {
place,
x,
title,
state: { upper: false, lower: 0 },
upper,
lower
};
column.highlight = createHighlight(column);
return column;
}
// Ordered from ones to hundreds.
const columns = [
createColumn(0, 1.25, "1s"),
createColumn(1, 0, "10s"),
createColumn(2, -1.25, "100s")
];
function columnDigit(column) {
return (column.state.upper ? 5 : 0) + column.state.lower;
}
function stateForDigit(digit) {
return digit < 5
? { upper: false, lower: digit }
: { upper: true, lower: digit - 5 };
}
function readFrame() {
return columns.reduce(
(total, column) => total + columnDigit(column) * 10 ** column.place,
0
);
}
function updateLiveReadout() {
frameValueElement.textContent = String(readFrame()).padStart(3, "0");
}
// -------------------------------------------------------------------------
// Promise-based tween system
// -------------------------------------------------------------------------
const tweens = [];
function easeInOutCubic(value) {
return value < 0.5
? 4 * value * value * value
: 1 - Math.pow(-2 * value + 2, 3) / 2;
}
function easeOutCubic(value) {
return 1 - Math.pow(1 - value, 3);
}
function tween(duration, update, easing = easeInOutCubic) {
if (reducedMotion) {
duration = Math.min(duration, 35);
}
return new Promise((resolve) => {
tweens.push({
start: performance.now(),
duration: Math.max(duration, 1),
update,
easing,
resolve
});
});
}
function delay(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
function updateTweens(now) {
for (let index = tweens.length - 1; index >= 0; index -= 1) {
const item = tweens[index];
const progress = Math.min(
1,
Math.max(0, (now - item.start) / item.duration)
);
item.update(item.easing(progress), progress);
if (progress >= 1) {
tweens.splice(index, 1);
item.resolve();
}
}
}
// -------------------------------------------------------------------------
// Bead animation and place highlighting
// -------------------------------------------------------------------------
async function pulseHighlight(column, color, duration = 340) {
const { group, material } = column.highlight;
material.color.set(color);
group.visible = true;
await tween(
duration,
(eased, progress) => {
const pulse = Math.sin(progress * Math.PI);
material.opacity = 0.12 + pulse * 0.68;
group.scale.set(
1 + pulse * 0.045,
1 + pulse * 0.018,
1 + pulse * 0.045
);
},
(value) => value
);
material.opacity = 0;
group.visible = false;
group.scale.set(1, 1, 1);
}
async function animateBeads(column, targetState, duration = 470) {
const upperFrom = column.upper.position.clone();
const upperTo = new THREE.Vector3(
column.x,
targetState.upper ? UPPER_DOWN : UPPER_UP,
0
);
const lowerMoves = column.lower.map((bead, index) => {
const isDown = index < targetState.lower;
return {
bead,
from: bead.position.clone(),
to: new THREE.Vector3(
column.x,
isDown ? LOWER_DOWN[index] : LOWER_UP[index],
0
)
};
});
await tween(duration, (eased, progress) => {
const hop = Math.sin(progress * Math.PI) * 0.035;
column.upper.position.lerpVectors(upperFrom, upperTo, eased);
column.upper.position.y += hop;
for (const move of lowerMoves) {
move.bead.position.lerpVectors(move.from, move.to, eased);
move.bead.position.y += hop;
}
});
column.state = { ...targetState };
}
async function animateColumnTo(place, digit, color = 0x51dfca) {
const column = columns[place];
const targetState = stateForDigit(digit);
const changed =
column.state.upper !== targetState.upper ||
column.state.lower !== targetState.lower;
if (changed) {
await Promise.all([
animateBeads(column, targetState, 470),
pulseHighlight(column, color, 520)
]);
} else {
await pulseHighlight(column, color, 380);
}
updateLiveReadout();
}
// -------------------------------------------------------------------------
// Carry animation
// -------------------------------------------------------------------------
async function animateFloatingText(text, x, y, color = "#ffad63") {
const sprite = makeLabelSprite(
text,
color,
"rgba(7,17,31,0.92)",
2.15,
0.43
);
sprite.position.set(x, y, 0.9);
scene.add(sprite);
await tween(
650,
(eased, progress) => {
sprite.position.y = y + progress * 0.58;
sprite.material.opacity = 1 - progress;
},
easeOutCubic
);
disposeSprite(sprite);
}
async function animateCarry(place) {
const nextPlace = place + 1;
if (nextPlace >= columns.length) {
throw new Error("The total exceeds the available frame.");
}
const source = columns[place];
const target = columns[nextPlace];
setStatus(
`CARRY · ${PLACE_NAMES[place]} → ${PLACE_NAMES[nextPlace]}`,
"One unit leaves this column and travels to the next place.",
"carry"
);
await pulseHighlight(source, 0xff8a3d, 260);
const token = new THREE.Group();
const tokenMaterial = new THREE.MeshStandardMaterial({
color: 0xff8a3d,
emissive: 0xff4d00,
emissiveIntensity: 1.25,
roughness: 0.35,
metalness: 0.05,
flatShading: true
});
const mainToken = addBox(
0.24,
0.24,
0.24,
tokenMaterial,
0,
0,
0,
token
);
mainToken.castShadow = true;
addBox(
0.12,
0.12,
0.12,
tokenMaterial,
-0.22,
-0.04,
0.08,
token
);
addBox(
0.09,
0.09,
0.09,
tokenMaterial,
0.2,
0.08,
-0.04,
token
);
token.position.set(source.x, 0.68, 0.65);
scene.add(token);
const textAnimation = animateFloatingText(
"CARRY 1",
(source.x + target.x) / 2,
1.15,
"#ffad63"
);
const targetPulse = pulseHighlight(target, 0xff8a3d, 520);
await tween(
560,
(eased, progress) => {
token.position.x = THREE.MathUtils.lerp(
source.x,
target.x,
eased
);
token.position.y =
0.68 + Math.sin(progress * Math.PI) * 0.9;
token.position.z =
0.65 + Math.sin(progress * Math.PI) * 0.25;
token.rotation.x = progress * Math.PI * 2;
token.rotation.y = progress * Math.PI * 3;
},
easeInOutCubic
);
await Promise.all([textAnimation, targetPulse]);
scene.remove(token);
tokenMaterial.dispose();
}
// -------------------------------------------------------------------------
// Arithmetic
// -------------------------------------------------------------------------
function setStatus(title, detail, tone = "idle") {
statusTitleElement.textContent = title;
statusDetailElement.textContent = detail;
statusElement.className = `status ${tone}`;
}
async function addOperand(value, label) {
let incomingCarry = 0;
for (let place = 0; place < columns.length; place += 1) {
const operandDigit = Math.floor(value / 10 ** place) % 10;
const currentDigit = columnDigit(columns[place]);
const columnTotal = currentDigit + operandDigit + incomingCarry;
const resultDigit = columnTotal % 10;
const outgoingCarry = columnTotal >= 10 ? 1 : 0;
const carryTerm = incomingCarry ? " + 1 carry" : "";
setStatus(
`ADDING ${label} · ${PLACE_NAMES[place]}`,
`${currentDigit} + ${operandDigit}${carryTerm} = ${columnTotal}. ` +
(outgoingCarry
? `Keep ${resultDigit}; carry 1 to ${PLACE_SHORT_NAMES[place + 1]}.`
: `Keep ${resultDigit} in this column.`),
outgoingCarry ? "carry" : "idle"
);
await animateColumnTo(
place,
resultDigit,
outgoingCarry ? 0xff8a3d : 0x51dfca
);
if (outgoingCarry) {
await animateCarry(place);
}
incomingCarry = outgoingCarry;
}
}
async function resetFrame(message = "FRAME CLEARED") {
await Promise.all(
columns.map((column) =>
animateBeads(
column,
{ upper: false, lower: 0 },
reducedMotion ? 30 : 430
)
)
);
updateLiveReadout();
setStatus(message, "Every column has been returned to zero.");
}
function setBusy(value) {
busy = value;
addButton.disabled = value;
clearButton.disabled = value;
numberAInput.disabled = value;
numberBInput.disabled = value;
addButton.textContent = value ? "Animating…" : "Add on frame";
document.querySelectorAll(".presets button").forEach((button) => {
button.disabled = value;
});
}
function clampInput(input) {
const value = Math.max(
0,
Math.min(99, Math.trunc(Number(input.value) || 0))
);
input.value = value;
return value;
}
function updatePreview() {
const a = Math.max(0, Math.min(99, Math.trunc(Number(numberAInput.value) || 0)));
const b = Math.max(0, Math.min(99, Math.trunc(Number(numberBInput.value) || 0)));
expectedTotal = a + b;
expectedValueElement.textContent = expectedTotal;
if (!busy) {
verificationElement.className = "verification pending";
verificationElement.innerHTML = `
<div class="verify-heading">
<span class="verify-icon"><span>→</span></span>
<span>READY TO ADD</span>
</div>
<div class="verify-equation">${a} + ${b} = ${expectedTotal}</div>
<div class="verify-readback">
The final frame will be read back from the beads and checked.
</div>
`;
}
}
async function runAddition() {
if (busy) return;
const a = clampInput(numberAInput);
const b = clampInput(numberBInput);
setBusy(true);
expectedTotal = a + b;
expectedValueElement.textContent = expectedTotal;
verificationElement.className = "verification pending";
verificationElement.innerHTML = `
<div class="verify-heading">
<span class="verify-icon"><span>→</span></span>
<span>ADDITION IN PROGRESS</span>
</div>
<div class="verify-equation">${a} + ${b} = ${expectedTotal}</div>
<div class="verify-readback">
Watching the ones, tens, and hundreds columns.
</div>
`;
try {
setStatus(
"PREPARING THE FRAME",
"All beads return to zero before the first operand is added."
);
await resetFrame("READY · ADDING FIRST OPERAND");
await addOperand(a, "A");
setStatus(
`FIRST OPERAND ADDED · ${a}`,
"Now adding the second operand to the current frame.",
"idle"
);
await delay(reducedMotion ? 40 : 240);
await addOperand(b, "B");
const frameTotal = readFrame();
const verified = frameTotal === expectedTotal;
const readbackParts = [];
for (let place = columns.length - 1; place >= 0; place -= 1) {
const digit = columnDigit(columns[place]);
if (digit > 0) {
readbackParts.push(`${digit} × ${10 ** place}`);
}
}
const readbackExpression = readbackParts.join(" + ") || "0";
verificationElement.className = verified
? "verification"
: "verification error";
verificationElement.innerHTML = `
<div class="verify-heading">
<span class="verify-icon"><span>${verified ? "✓" : "!"}</span></span>
<span>${verified ? "VERIFIED" : "VERIFICATION FAILED"}</span>
</div>
<div class="verify-equation">
${a} + ${b} = ${expectedTotal}
</div>
<div class="verify-readback">
Bead readback: ${readbackExpression} = ${frameTotal}.
${
verified
? "The physical frame matches the symbolic total."
: "The physical frame does not match the expected total."
}
</div>
`;
await Promise.all(
columns.map((column) =>
pulseHighlight(column, verified ? 0x72f1a6 : 0xff647c, 500)
)
);
if (verified) {
setStatus(
`VERIFIED · THE FRAME READS ${frameTotal}`,
`${a} + ${b} = ${expectedTotal}. Beads and symbolic arithmetic agree.`,
"good"
);
} else {
setStatus(
"VERIFICATION FAILED",
`Expected ${expectedTotal}, but the frame reads ${frameTotal}.`,
"error"
);
}
} catch (error) {
verificationElement.className = "verification error";
verificationElement.innerHTML = `
<div class="verify-heading">
<span class="verify-icon"><span>!</span></span>
<span>OVERFLOW</span>
</div>
<div class="verify-equation">The frame cannot hold this result.</div>
`;
setStatus(
"OVERFLOW",
error.message,
"error"
);
} finally {
setBusy(false);
}
}
async function clearEverything() {
if (busy) return;
setBusy(true);
await resetFrame("FRAME CLEARED");
expectedTotal = 0;
expectedValueElement.textContent = "0";
verificationElement.className = "verification idle";
verificationElement.innerHTML = `
<div class="verify-heading">
<span class="verify-icon"><span>✓</span></span>
<span>READY TO VERIFY</span>
</div>
<div class="verify-equation">Enter two numbers</div>
<div class="verify-readback">
After the animation, the frame will be read back bead by bead.
</div>
`;
setBusy(false);
}
// -------------------------------------------------------------------------
// Direct camera controls: orbit, zoom, reset
// -------------------------------------------------------------------------
let dragging = false;
let pointerX = 0;
let pointerY = 0;
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
canvas.classList.add("dragging");
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - pointerX;
const deltaY = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraYaw -= deltaX * 0.006;
cameraPitch = THREE.MathUtils.clamp(
cameraPitch + deltaY * 0.0045,
-0.42,
0.48
);
updateCamera();
});
function endDrag(event) {
dragging = false;
canvas.classList.remove("dragging");
if (event.pointerId !== undefined) {
try {
canvas.releasePointerCapture(event.pointerId);
} catch {
// Pointer capture may already have been released.
}
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.0009),
5.2,
13.5
);
updateCamera();
},
{ passive: false }
);
function resetCamera() {
cameraYaw = -0.08;
cameraPitch = 0.055;
cameraRadius = window.innerWidth < 720 ? 9.6 : 8.6;
updateCamera();
}
canvas.addEventListener("dblclick", resetCamera);
cameraResetButton.addEventListener("click", resetCamera);
// -------------------------------------------------------------------------
// UI events
// -------------------------------------------------------------------------
addButton.addEventListener("click", runAddition);
clearButton.addEventListener("click", clearEverything);
numberAInput.addEventListener("input", updatePreview);
numberBInput.addEventListener("input", updatePreview);
numberAInput.addEventListener("change", () => {
clampInput(numberAInput);
updatePreview();
});
numberBInput.addEventListener("change", () => {
clampInput(numberBInput);
updatePreview();
});
document.querySelectorAll(".presets button").forEach((button) => {
button.addEventListener("click", () => {
numberAInput.value = button.dataset.a;
numberBInput.value = button.dataset.b;
updatePreview();
});
});
window.addEventListener("keydown", (event) => {
if (event.key === "Enter" && !busy) {
runAddition();
}
});
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
camera.aspect = width / height;
camera.fov = width < 720 ? 48 : 42;
camera.updateProjectionMatrix();
updateCamera();
}
window.addEventListener("resize", resize);
resize();
function render(now) {
updateTweens(now);
renderer.render(scene, camera);
}
renderer.setAnimationLoop(render);
updateLiveReadout();
</script>
</body>
</html>
```