Prompt specification
Build or customize the Three.js 3D scene "Precision-versus-range exploration tool" 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: Precision-versus-range exploration tool
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/precision-versus-range-exploration-tool-x1876
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring a low-poly number-representation workbench. Use an unsigned eight-bit toy format and let the user move the division between integer and fractional bits. Show the bit row above a number line whose tick spacing changes with the allocation. Provide a slider for a real-valued input, then display its rounded representable value and the rounding error. Keep the eight-bit budget fixed. Clearly mark the largest representable number and show what happens when the input exceeds that range under an explicitly selected saturation or overflow rule. Use blocks and measured spacing to make precision and range visible rather than relying only on a numeric table.
Working Three.js Starter (precision-versus-range-exploration-tool-x1876):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Eight-Bit Fixed-Point Workbench</title>
<style>
:root {
color-scheme: dark;
--bg: #07111e;
--panel: rgba(13, 24, 40, 0.94);
--line: rgba(148, 163, 184, 0.22);
--text: #e8eef8;
--muted: #94a3b8;
--cyan: #55d8f5;
--green: #58e0b0;
--amber: #ffb45c;
--red: #ff647c;
}
* { 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;
}
#scene {
position: fixed;
inset: 0 390px 0 0;
touch-action: none;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
}
#scene canvas:active { cursor: grabbing; }
.title-card {
position: fixed;
z-index: 5;
top: 18px;
left: 20px;
max-width: calc(100vw - 430px);
pointer-events: none;
text-shadow: 0 2px 14px #000;
}
.eyebrow {
color: var(--cyan);
font: 700 11px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: .17em;
text-transform: uppercase;
}
h1 {
margin: 7px 0 5px;
font-size: clamp(20px, 2.3vw, 31px);
line-height: 1.05;
letter-spacing: -.035em;
}
.subtitle {
color: #b8c6d8;
font-size: 12px;
line-height: 1.5;
}
.panel {
position: fixed;
z-index: 10;
top: 16px;
right: 16px;
bottom: 16px;
width: 358px;
overflow: auto;
padding: 18px;
border: 1px solid var(--line);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 20px 70px rgba(0, 0, 0, .42);
backdrop-filter: blur(16px);
}
.panel-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding-bottom: 14px;
border-bottom: 1px solid var(--line);
}
.panel-head strong {
font: 800 13px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: .08em;
}
.tiny-button {
border: 1px solid var(--line);
border-radius: 8px;
padding: 7px 9px;
background: rgba(255, 255, 255, .04);
color: var(--muted);
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
cursor: pointer;
}
.tiny-button:hover {
color: white;
border-color: rgba(85, 216, 245, .5);
}
.section {
padding: 15px 0;
border-bottom: 1px solid var(--line);
}
.section:last-child { border-bottom: 0; }
.section-title {
display: flex;
justify-content: space-between;
align-items: baseline;
margin-bottom: 10px;
font-size: 11px;
font-weight: 800;
letter-spacing: .1em;
text-transform: uppercase;
color: #c7d3e4;
}
.section-title span {
color: var(--muted);
font: 500 10px/1.3 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: .03em;
text-transform: none;
}
.split {
display: flex;
align-items: baseline;
justify-content: center;
gap: 8px;
margin: 2px 0 12px;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
.split strong {
font-size: 28px;
line-height: 1;
}
.split .integer strong { color: var(--green); }
.split .fraction strong { color: var(--amber); }
.split small { color: var(--muted); font-size: 10px; }
.split .dot { color: #526176; }
input[type="range"] {
width: 100%;
margin: 3px 0 0;
accent-color: var(--cyan);
cursor: pointer;
}
.range-ends {
display: flex;
justify-content: space-between;
margin-top: 3px;
color: #708097;
font: 500 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.formula {
margin-top: 10px;
color: #7f90a7;
font: 500 10px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.number-wrap {
display: flex;
gap: 8px;
align-items: center;
}
.number-wrap input {
width: 100%;
min-width: 0;
border: 1px solid var(--line);
border-radius: 10px;
padding: 10px 11px;
background: rgba(2, 8, 18, .58);
color: white;
font: 700 15px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
outline: none;
}
.number-wrap input:focus {
border-color: rgba(85, 216, 245, .7);
box-shadow: 0 0 0 3px rgba(85, 216, 245, .09);
}
.input-unit {
color: var(--muted);
font: 700 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.rule-buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.rule-buttons button {
border: 1px solid var(--line);
border-radius: 10px;
padding: 10px 8px;
background: rgba(255, 255, 255, .035);
color: #aebdd0;
font: 800 10px/1.25 ui-monospace, SFMono-Regular, Menlo, monospace;
cursor: pointer;
}
.rule-buttons button.active {
color: white;
border-color: rgba(85, 216, 245, .65);
background: rgba(85, 216, 245, .12);
box-shadow: inset 0 0 0 1px rgba(85, 216, 245, .08);
}
.rule-description {
min-height: 31px;
margin-top: 8px;
color: #8495aa;
font-size: 10px;
line-height: 1.5;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
min-height: 72px;
padding: 10px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, .025);
}
.metric-label {
color: #7e90a8;
font: 700 9px/1.25 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: .06em;
text-transform: uppercase;
}
.metric-value {
overflow-wrap: anywhere;
margin-top: 7px;
color: white;
font: 800 17px/1.05 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.metric-value.green { color: var(--green); }
.metric-value.amber { color: var(--amber); }
.metric-value.red { color: var(--red); }
.pattern {
display: flex;
align-items: center;
justify-content: center;
gap: 4px;
margin-top: 10px;
font: 900 18px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.pattern .bit {
display: grid;
place-items: center;
width: 25px;
height: 31px;
border-radius: 6px;
border: 1px solid var(--line);
background: rgba(255, 255, 255, .035);
color: #8393a8;
}
.pattern .bit.on.int { color: var(--green); border-color: rgba(88, 224, 176, .45); }
.pattern .bit.on.frac { color: var(--amber); border-color: rgba(255, 180, 92, .45); }
.pattern .point { color: white; padding: 0 2px; }
.status {
margin-top: 10px;
padding: 11px;
border: 1px solid rgba(88, 224, 176, .25);
border-radius: 11px;
background: rgba(88, 224, 176, .06);
}
.status.over {
border-color: rgba(255, 100, 124, .42);
background: rgba(255, 100, 124, .08);
}
.status-title {
color: var(--green);
font: 900 10px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: .1em;
}
.status.over .status-title { color: var(--red); }
.status-body {
margin-top: 5px;
color: #a8b6c8;
font-size: 10px;
line-height: 1.5;
}
.help {
margin-top: 12px;
color: #6f8097;
font-size: 10px;
line-height: 1.55;
}
.help strong { color: #a9b7c9; }
@media (max-width: 850px) {
#scene { inset: 0 0 45vh 0; }
.title-card { top: 12px; left: 14px; max-width: calc(100vw - 28px); }
.subtitle { display: none; }
.panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 43vh;
padding: 14px;
}
.section { padding: 12px 0; }
}
</style>
</head>
<body>
<div id="scene" aria-label="Interactive three-dimensional fixed-point workbench"></div>
<header class="title-card">
<div class="eyebrow">Low-poly laboratory / unsigned</div>
<h1>Eight-Bit Fixed-Point Workbench</h1>
<div class="subtitle">
Drag to orbit · wheel to zoom · click the absolute ruler to place the input
</div>
</header>
<aside class="panel">
<div class="panel-head">
<strong>UNSIGNED Q?.? · 8 BITS</strong>
<button id="resetView" class="tiny-button">RESET VIEW</button>
</div>
<section class="section">
<div class="section-title">
Binary-point allocation
<span>move the division</span>
</div>
<div class="split">
<div class="integer"><strong id="intBits">4</strong> <small>INT</small></div>
<div class="dot">·</div>
<div class="fraction"><strong id="fracBits">4</strong> <small>FRAC</small></div>
</div>
<input id="allocation" type="range" min="0" max="8" value="4"
aria-label="Number of integer bits" />
<div class="range-ends">
<span>0 integer</span>
<span>8 integer</span>
</div>
<div class="formula">
MAX = (2<sup>I</sup> − 1) · 2<sup>−F</sup><br>
LSB = 2<sup>−F</sup> · code space always contains 256 values
</div>
</section>
<section class="section">
<div class="section-title">
Real-valued input
<span>unsigned domain</span>
</div>
<div class="number-wrap">
<input id="valueNumber" type="number" min="0" max="300" step="0.0001"
value="10.2" aria-label="Real-valued input" />
<span class="input-unit">VALUE</span>
</div>
<input id="valueRange" type="range" min="0" max="300" step="0.001"
value="10.2" aria-label="Input value slider" />
<div class="range-ends">
<span>0</span>
<span>slider reaches 300 to expose overflow</span>
<span>300</span>
</div>
</section>
<section class="section">
<div class="section-title">
Selected out-of-range rule
<span>explicit</span>
</div>
<div class="rule-buttons">
<button id="saturationRule" class="active" type="button">SATURATION</button>
<button id="overflowRule" type="button">OVERFLOW → WRAP</button>
</div>
<div id="ruleDescription" class="rule-description"></div>
</section>
<section class="section">
<div class="section-title">
Stored result
<span>stored − input</span>
</div>
<div class="metrics">
<div class="metric">
<div class="metric-label">Rounded value</div>
<div id="storedValue" class="metric-value green">10.1875</div>
</div>
<div class="metric">
<div class="metric-label">Total error</div>
<div id="roundingError" class="metric-value amber">−0.0125</div>
</div>
<div class="metric">
<div class="metric-label">LSB / step</div>
<div id="lsbValue" class="metric-value">0.0625</div>
</div>
<div class="metric">
<div class="metric-label">Largest value</div>
<div id="maxValue" class="metric-value red">15.9375</div>
</div>
</div>
<div id="bitPattern" class="pattern" aria-label="Stored eight-bit code"></div>
<div id="status" class="status" aria-live="polite">
<div id="statusTitle" class="status-title">IN RANGE</div>
<div id="statusBody" class="status-body"></div>
</div>
</section>
<div class="help">
<strong>Reading the scene:</strong> the glowing blocks are all 256 possible
codes. The ruler uses an absolute numeric scale, so moving bits left makes
the representable range longer and the physical code spacing coarser.
The binary point moves through the eight-bit row above the ruler.
</div>
</aside>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// State and fixed-point arithmetic
// -------------------------------------------------------------------------
const DOM = {
scene: document.querySelector("#scene"),
allocation: document.querySelector("#allocation"),
intBits: document.querySelector("#intBits"),
fracBits: document.querySelector("#fracBits"),
valueRange: document.querySelector("#valueRange"),
valueNumber: document.querySelector("#valueNumber"),
saturationRule: document.querySelector("#saturationRule"),
overflowRule: document.querySelector("#overflowRule"),
ruleDescription: document.querySelector("#ruleDescription"),
storedValue: document.querySelector("#storedValue"),
roundingError: document.querySelector("#roundingError"),
lsbValue: document.querySelector("#lsbValue"),
maxValue: document.querySelector("#maxValue"),
bitPattern: document.querySelector("#bitPattern"),
status: document.querySelector("#status"),
statusTitle: document.querySelector("#statusTitle"),
statusBody: document.querySelector("#statusBody"),
resetView: document.querySelector("#resetView")
};
const state = {
integerBits: 4,
input: 10.2,
rule: "saturation"
};
const DOMAIN_MAX = 300;
const X_MIN = -7;
const X_MAX = 7;
const WORLD_PER_UNIT = (X_MAX - X_MIN) / DOMAIN_MAX;
const valueToX = value => X_MIN + value * WORLD_PER_UNIT;
const xToValue = x => (x - X_MIN) / WORLD_PER_UNIT;
const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
function formatNumber(value) {
if (!Number.isFinite(value)) return "—";
const rounded = Number(value.toFixed(6));
return Object.is(rounded, -0) ? "0" : String(rounded);
}
function formatSigned(value) {
if (!Number.isFinite(value)) return "—";
const rounded = Number(value.toFixed(6));
if (rounded > 0) return "+" + rounded;
return String(Object.is(rounded, -0) ? 0 : rounded);
}
function computeModel() {
const fractionBits = 8 - state.integerBits;
const lsb = Math.pow(2, -fractionBits);
const maxValue = 255 * lsb;
// Half-up rounding of the scaled, non-negative input.
const rawCode = Math.floor(state.input / lsb + 0.5);
let code;
if (rawCode <= 255) {
code = rawCode;
} else if (state.rule === "saturation") {
code = 255;
} else {
// Explicit unsigned overflow rule: wrap the scaled code modulo 256.
code = ((rawCode % 256) + 256) % 256;
}
const stored = code * lsb;
const error = stored - state.input;
const bits = code.toString(2).padStart(8, "0");
return {
integerBits: state.integerBits,
fractionBits,
lsb,
maxValue,
rawCode,
code,
stored,
error,
bits,
over: state.input > maxValue
};
}
// -------------------------------------------------------------------------
// Renderer, camera, and direct camera controls (no addons)
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
DOM.scene.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111e);
scene.fog = new THREE.Fog(0x07111e, 24, 44);
const camera = new THREE.OrthographicCamera(-10, 10, 6, -6, 0.1, 100);
const cameraTarget = new THREE.Vector3(0, 0.45, 0);
const spherical = new THREE.Spherical(28, 0.70, 0);
const defaultSpherical = new THREE.Spherical(28, 0.70, 0);
function updateCamera() {
camera.position.setFromSpherical(spherical).add(cameraTarget);
camera.lookAt(cameraTarget);
camera.updateProjectionMatrix();
}
function resize() {
const width = DOM.scene.clientWidth;
const height = DOM.scene.clientHeight;
if (!width || !height) return;
renderer.setSize(width, height, false);
const aspect = width / height;
const viewHeight = Math.max(10.5, 17.5 / aspect);
camera.left = -viewHeight * aspect / 2;
camera.right = viewHeight * aspect / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
}
new ResizeObserver(resize).observe(DOM.scene);
resize();
updateCamera();
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let pointerDown = false;
let dragDistance = 0;
let lastPointerX = 0;
let lastPointerY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
pointerDown = true;
dragDistance = 0;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!pointerDown) return;
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
dragDistance += Math.abs(dx) + Math.abs(dy);
spherical.theta -= dx * 0.006;
spherical.phi = clamp(spherical.phi + dy * 0.005, 0.32, 1.22);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
updateCamera();
});
renderer.domElement.addEventListener("pointerup", event => {
if (pointerDown && dragDistance < 5) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hit = raycaster.intersectObject(clickTarget)[0];
if (hit) {
const value = clamp(xToValue(hit.point.x), 0, DOMAIN_MAX);
setInput(value);
}
}
pointerDown = false;
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = false;
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
camera.zoom = clamp(camera.zoom * Math.exp(-event.deltaY * 0.001), 0.62, 2.25);
camera.updateProjectionMatrix();
}, { passive: false });
renderer.domElement.addEventListener("contextmenu", event => event.preventDefault());
DOM.resetView.addEventListener("click", () => {
spherical.copy(defaultSpherical);
camera.zoom = 1;
camera.updateProjectionMatrix();
updateCamera();
});
// -------------------------------------------------------------------------
// Lighting and materials
// -------------------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0xc7e7ff, 0x172033, 2.1));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.0);
keyLight.position.set(5, 11, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -11;
keyLight.shadow.camera.right = 11;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -8;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x45cfff, 32, 20, 2);
rimLight.position.set(-6, 3, -3);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xff9b55, 18, 16, 2);
warmLight.position.set(6, 2, 4);
scene.add(warmLight);
const material = (color, options = {}) =>
new THREE.MeshStandardMaterial({
color,
roughness: 0.72,
metalness: 0.08,
flatShading: true,
...options
});
// -------------------------------------------------------------------------
// Low-poly workbench
// -------------------------------------------------------------------------
const bench = new THREE.Group();
scene.add(bench);
const wood = material(0x563a2d, { roughness: 0.9 });
const woodEdge = material(0x3a2924, { roughness: 0.95 });
const slate = material(0x172436, { roughness: 0.8 });
const railMaterial = material(0x101a29, { roughness: 0.85 });
function addBox(parent, size, position, mat, castShadow = true) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(...size), mat);
mesh.position.set(...position);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
addBox(bench, [17.8, 0.36, 6.3], [0, -0.82, 0.25], wood);
addBox(bench, [17.45, 0.08, 5.95], [0, -0.60, 0.25], woodEdge, false);
addBox(bench, [15.25, 0.13, 1.65], [0, -0.49, 0.86], railMaterial);
addBox(bench, [8.6, 0.12, 1.35], [0, -0.49, -1.25], slate);
for (const x of [-7.65, 7.65]) {
for (const z of [-2.2, 2.7]) {
addBox(bench, [0.55, 4.4, 0.55], [x, -2.95, z], woodEdge);
}
}
addBox(bench, [15.3, 0.45, 0.22], [0, -1.35, 2.9], woodEdge);
addBox(bench, [15.3, 0.45, 0.22], [0, -1.35, -2.4], woodEdge);
// Subtle measured grid on the bench surface.
const gridPositions = [];
for (let x = -8; x <= 8.001; x += 0.5) {
gridPositions.push(x, -0.55, -2.72, x, -0.55, 3.15);
}
for (let z = -2.5; z <= 3.01; z += 0.5) {
gridPositions.push(-8.55, -0.55, z, 8.55, -0.55, z);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridPositions, 3)
);
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x66809a,
transparent: true,
opacity: 0.10
})
);
bench.add(grid);
// Low-poly fasteners.
const screwMaterial = material(0x9aa8b4, { metalness: 0.55, roughness: 0.4 });
for (const x of [-8.25, 8.25]) {
for (const z of [-2.62, 3.12]) {
const screw = new THREE.Mesh(
new THREE.CylinderGeometry(0.09, 0.09, 0.035, 8),
screwMaterial
);
screw.position.set(x, -0.52, z);
bench.add(screw);
}
}
// -------------------------------------------------------------------------
// Canvas sprite labels
// -------------------------------------------------------------------------
function makeTextSprite(initialText, initialColor = "#dbeafe", width = 1.5) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false,
depthTest: false
}));
sprite.renderOrder = 20;
sprite.scale.set(width, width / 4, 1);
function set(text, color = initialColor) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.textAlign = "center";
context.textBaseline = "middle";
let fontSize = 52;
context.font = `800 ${fontSize}px ui-monospace, SFMono-Regular, Menlo, monospace`;
while (context.measureText(text).width > 480 && fontSize > 22) {
fontSize -= 2;
context.font = `800 ${fontSize}px ui-monospace, SFMono-Regular, Menlo, monospace`;
}
context.shadowColor = "rgba(0,0,0,.95)";
context.shadowBlur = 9;
context.fillStyle = color;
context.fillText(text, 256, 65);
texture.needsUpdate = true;
}
set(initialText, initialColor);
return { sprite, set };
}
const rulerTitle = makeTextSprite(
"ABSOLUTE NUMERIC RULER · 0 — 300",
"#8fa8c0",
3.8
);
rulerTitle.sprite.position.set(0, -0.04, 1.72);
scene.add(rulerTitle.sprite);
const zeroLabel = makeTextSprite("0", "#8fa8c0", 0.55);
zeroLabel.sprite.position.set(valueToX(0), -0.22, 1.56);
scene.add(zeroLabel.sprite);
const domainLabel = makeTextSprite("300", "#8fa8c0", 0.8);
domainLabel.sprite.position.set(valueToX(300), -0.22, 1.56);
scene.add(domainLabel.sprite);
const gapLabel = makeTextSprite("CODE TICK GAP = 1/16", "#8fa8c0", 2.4);
gapLabel.sprite.position.set(-5.6, -0.22, 1.57);
scene.add(gapLabel.sprite);
// -------------------------------------------------------------------------
// Number line, code blocks, and range markers
// -------------------------------------------------------------------------
const axis = new THREE.Mesh(
new THREE.CylinderGeometry(0.038, 0.038, 14.15, 8),
material(0xb7c9d8, { metalness: 0.25 })
);
axis.rotation.z = Math.PI / 2;
axis.position.set(0, -0.18, 0.86);
axis.castShadow = true;
scene.add(axis);
const clickTarget = new THREE.Mesh(
new THREE.BoxGeometry(14.2, 0.9, 1.0),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
colorWrite: false
})
);
clickTarget.position.set(0, -0.15, 0.86);
scene.add(clickTarget);
const rangeBar = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshBasicMaterial({
color: 0x4be3b0,
transparent: true,
opacity: 0.17,
depthWrite: false
})
);
scene.add(rangeBar);
const overrunBar = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshBasicMaterial({
color: 0xff526f,
transparent: true,
opacity: 0.27,
depthWrite: false
})
);
scene.add(overrunBar);
const tileCount = 256;
const tileGeometry = new THREE.BoxGeometry(1, 1, 1);
const tileMaterial = material(0xffffff, { roughness: 0.58 });
const codeTiles = new THREE.InstancedMesh(tileGeometry, tileMaterial, tileCount);
codeTiles.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
codeTiles.castShadow = true;
codeTiles.receiveShadow = true;
scene.add(codeTiles);
const tickMaterial = material(0xa5b7c7, { roughness: 0.65 });
const codeTicks = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
tickMaterial,
tileCount
);
codeTicks.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
scene.add(codeTicks);
const dummy = new THREE.Object3D();
const instanceColor = new THREE.Color();
function makeMarker(color, labelText, labelWidth) {
const group = new THREE.Group();
const markerMaterial = material(color, {
emissive: color,
emissiveIntensity: 0.32,
roughness: 0.38
});
const stem = new THREE.Mesh(
new THREE.BoxGeometry(0.045, 1.05, 0.045),
markerMaterial
);
stem.position.y = 0.23;
group.add(stem);
const gem = new THREE.Mesh(
new THREE.OctahedronGeometry(0.13, 0),
markerMaterial
);
gem.position.y = 0.83;
group.add(gem);
const label = makeTextSprite(labelText, `#${new THREE.Color(color).getHexString()}`, labelWidth);
label.sprite.position.set(0, 1.16, 0);
group.add(label.sprite);
scene.add(group);
return { group, gem, label };
}
const maxMarker = makeMarker(0xff647c, "MAX 15.9375", 2.0);
const inputMarker = makeMarker(0x55d8f5, "INPUT 10.2", 1.55);
const outputMarker = makeMarker(0x58e0b0, "STORED 10.1875", 1.75);
const fullRangeMarker = new THREE.Group();
const fullStem = new THREE.Mesh(
new THREE.BoxGeometry(0.025, 0.72, 0.025),
new THREE.MeshBasicMaterial({ color: 0x728397, transparent: true, opacity: 0.65 })
);
fullStem.position.y = 0.05;
fullRangeMarker.add(fullStem);
const fullLabel = makeTextSprite("255 FULL-BYTE CEILING", "#728397", 2.35);
fullLabel.sprite.position.set(0, -0.35, 0);
fullRangeMarker.add(fullLabel.sprite);
fullRangeMarker.position.set(valueToX(255), -0.18, 0.86);
scene.add(fullRangeMarker);
// -------------------------------------------------------------------------
// Eight-bit row with a moving binary point
// -------------------------------------------------------------------------
const bitRow = new THREE.Group();
scene.add(bitRow);
const bitTitle = makeTextSprite(
"8 STORED CODE BITS · MSB → LSB",
"#c7d7e8",
4.0
);
bitTitle.sprite.position.set(0, 3.13, -0.8);
scene.add(bitTitle.sprite);
const allocationLabel = makeTextSprite(
"4 INTEGER | 4 FRACTION",
"#8fa8c0",
2.4
);
allocationLabel.sprite.position.set(0, 2.78, -0.8);
scene.add(allocationLabel.sprite);
const bitCubes = [];
const bitDigits = [];
const bitWeights = [];
for (let i = 0; i < 8; i++) {
const x = (i - 3.5) * 0.57;
const cube = new THREE.Mesh(
new THREE.BoxGeometry(0.46, 0.46, 0.46),
material(0x26364b, { roughness: 0.55 })
);
cube.position.set(x, 2.14, -0.82);
cube.castShadow = true;
cube.receiveShadow = true;
bitRow.add(cube);
const digit = makeTextSprite("0", "#e8eef8", 0.42);
digit.sprite.position.set(x, 2.14, -0.56);
bitRow.add(digit.sprite);
const weight = makeTextSprite("b7", "#8fa8c0", 0.95);
weight.sprite.position.set(x, 1.54, -0.79);
bitRow.add(weight.sprite);
bitCubes.push(cube);
bitDigits.push(digit);
bitWeights.push(weight);
}
const binaryPoint = new THREE.Group();
const pointGem = new THREE.Mesh(
new THREE.OctahedronGeometry(0.12, 0),
material(0xffffff, { emissive: 0xffffff, emissiveIntensity: 0.3 })
);
binaryPoint.add(pointGem);
const pointLabel = makeTextSprite("BINARY POINT", "#dce8f5", 1.15);
pointLabel.sprite.position.set(0, 0.39, 0);
binaryPoint.add(pointLabel.sprite);
binaryPoint.position.set(0, 2.14, -0.82);
bitRow.add(binaryPoint);
// Supports visually connect the bit row to the workbench.
for (const x of [-2.75, 2.75]) {
const support = new THREE.Mesh(
new THREE.CylinderGeometry(0.035, 0.045, 2.0, 6),
material(0x51647a, { metalness: 0.35 })
);
support.position.set(x, 0.42, -1.18);
support.castShadow = true;
scene.add(support);
}
// -------------------------------------------------------------------------
// Scene updates
// -------------------------------------------------------------------------
function updateScene(model) {
const { integerBits, fractionBits, lsb, maxValue, stored } = model;
// Fixed absolute scale: as LSB changes, the physical tick gap changes.
const codeSpacing = lsb * WORLD_PER_UNIT;
const blockWidth = codeSpacing * 0.68;
const tickWidth = codeSpacing * 0.19;
for (let code = 0; code < 256; code++) {
const value = code * lsb;
const x = valueToX(value);
dummy.position.set(x, -0.02, 0.88);
dummy.scale.set(blockWidth, 0.11, 0.34);
dummy.updateMatrix();
codeTiles.setMatrixAt(code, dummy.matrix);
const t = code / 255;
instanceColor.setHSL(0.46 + t * 0.25, 0.58, 0.46);
codeTiles.setColorAt(code, instanceColor);
dummy.position.set(x, 0.13, 0.86);
dummy.scale.set(tickWidth, 0.42, 0.026);
dummy.updateMatrix();
codeTicks.setMatrixAt(code, dummy.matrix);
}
codeTiles.instanceMatrix.needsUpdate = true;
if (codeTiles.instanceColor) codeTiles.instanceColor.needsUpdate = true;
codeTicks.instanceMatrix.needsUpdate = true;
const maxX = valueToX(maxValue);
const minX = valueToX(0);
rangeBar.position.set((minX + maxX) / 2, -0.35, 0.88);
rangeBar.scale.set(Math.max(maxX - minX, 0.00001), 0.055, 0.62);
const inputX = valueToX(state.input);
const over = state.input > maxValue;
overrunBar.visible = over;
if (over) {
overrunBar.position.set((maxX + inputX) / 2, -0.33, 0.9);
overrunBar.scale.set(Math.max(inputX - maxX, 0.00001), 0.07, 0.7);
}
maxMarker.group.position.set(maxX, -0.2, 0.86);
maxMarker.label.set(`MAX ${formatNumber(maxValue)}`, "#ff647c");
inputMarker.group.position.set(inputX, -0.2, 0.86);
inputMarker.label.set(`INPUT ${formatNumber(state.input)}`, "#55d8f5");
const storedX = valueToX(stored);
outputMarker.group.position.set(storedX, -0.2, 0.86);
outputMarker.label.set(`STORED ${formatNumber(stored)}`, "#58e0b0");
fullRangeMarker.visible = integerBits < 8;
gapLabel.set(`CODE TICK GAP = 1/${1 / lsb}`, "#8fa8c0");
allocationLabel.set(
`${integerBits} INTEGER | ${fractionBits} FRACTION`,
"#8fa8c0"
);
// Update bit cubes and their labels.
for (let i = 0; i < 8; i++) {
const bit = Number(model.bits[i]);
const isInteger = i < integerBits;
const cubeColor = bit
? (isInteger ? 0x42d6a4 : 0xffad52)
: 0x25364b;
bitCubes[i].material.color.setHex(cubeColor);
bitCubes[i].material.emissive.setHex(bit ? cubeColor : 0x000000);
bitCubes[i].material.emissiveIntensity = bit ? 0.14 : 0;
bitDigits[i].set(String(bit), bit ? "#ffffff" : "#718198");
const weight = isInteger
? Math.pow(2, integerBits - 1 - i)
: Math.pow(2, -(i - integerBits + 1));
bitWeights[i].set(
`b${7 - i} ×${formatNumber(weight)}`,
isInteger ? "#72e6bc" : "#ffc276"
);
}
const boundaryX = integerBits === 0
? -2.41
: integerBits === 8
? 2.41
: (integerBits - 4) * 0.57;
binaryPoint.position.x = boundaryX;
}
// -------------------------------------------------------------------------
// HTML/UI updates
// -------------------------------------------------------------------------
function updateUI(model) {
DOM.intBits.textContent = model.integerBits;
DOM.fracBits.textContent = model.fractionBits;
DOM.allocation.value = model.integerBits;
DOM.valueRange.value = state.input;
DOM.valueNumber.value = formatNumber(state.input);
DOM.saturationRule.classList.toggle("active", state.rule === "saturation");
DOM.overflowRule.classList.toggle("active", state.rule === "overflow");
DOM.ruleDescription.textContent = state.rule === "saturation"
? "Values above MAX clamp to code 255. The excess is visible as total error."
: "Values above MAX wrap modulo 256. Fractions can wrap back into the low end.";
DOM.storedValue.textContent = formatNumber(model.stored);
DOM.roundingError.textContent = formatSigned(model.error);
DOM.roundingError.className =
"metric-value " + (model.error < 0 ? "red" : model.error > 0 ? "green" : "amber");
DOM.lsbValue.textContent = formatNumber(model.lsb);
DOM.maxValue.textContent = formatNumber(model.maxValue);
DOM.bitPattern.replaceChildren();
for (let i = 0; i < 8; i++) {
if (i === model.integerBits) {
const point = document.createElement("span");
point.className = "point";
point.textContent = ".";
DOM.bitPattern.appendChild(point);
}
const bit = document.createElement("span");
bit.className = "bit" +
(i < model.integerBits ? " int" : " frac") +
(model.bits[i] === "1" ? " on" : "");
bit.textContent = model.bits[i];
DOM.bitPattern.appendChild(bit);
}
if (model.integerBits === 8) {
const point = document.createElement("span");
point.className = "point";
point.textContent = ".";
DOM.bitPattern.appendChild(point);
}
DOM.status.classList.toggle("over", model.over);
if (!model.over) {
DOM.statusTitle.textContent = "IN RANGE";
DOM.statusBody.textContent =
`The input scales to raw code ${model.rawCode}. ` +
`The nearest stored code is ${model.code}, giving ${formatNumber(model.stored)}.`;
} else if (state.rule === "saturation") {
DOM.statusTitle.textContent = "SATURATED";
DOM.statusBody.textContent =
`Input is ${formatNumber(state.input - model.maxValue)} above MAX. ` +
`The code is clamped to 255 and the stored value is MAX ${formatNumber(model.maxValue)}.`;
} else {
DOM.statusTitle.textContent = "OVERFLOW · WRAPPED";
DOM.statusBody.textContent =
`The scaled code ${model.rawCode} wraps modulo 256 to code ${model.code}. ` +
`The stored result jumps to ${formatNumber(model.stored)}.`;
}
}
function updateAll() {
const model = computeModel();
updateScene(model);
updateUI(model);
}
function setInput(value) {
if (!Number.isFinite(value)) return;
state.input = clamp(value, 0, DOMAIN_MAX);
updateAll();
}
DOM.allocation.addEventListener("input", event => {
state.integerBits = Number(event.target.value);
updateAll();
});
DOM.valueRange.addEventListener("input", event => {
setInput(Number(event.target.value));
});
DOM.valueNumber.addEventListener("input", event => {
const value = Number(event.target.value);
if (Number.isFinite(value)) setInput(value);
});
DOM.saturationRule.addEventListener("click", () => {
state.rule = "saturation";
updateAll();
});
DOM.overflowRule.addEventListener("click", () => {
state.rule = "overflow";
updateAll();
});
updateAll();
// Gentle marker pulse, while the scene remains geometrically static.
function animate(time) {
const pulse = 1 + Math.sin(time * 0.0032) * 0.07;
inputMarker.gem.scale.setScalar(pulse);
outputMarker.gem.scale.setScalar(1 + Math.sin(time * 0.0032 + 1.2) * 0.06);
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```