Prompt specification
Build or customize the Three.js 3D scene "Mean-and-variance counterfactual explorer" 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: Mean-and-variance counterfactual explorer
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/mean-and-variance-counterfactual-explorer-x1840
Scene Description Prompt:
Make one HTML file using Three.js from cdnjs for this voxel scene: Let users move a few observations while preserving their mean; update variance and standard deviation and distinguish squared units from original measurement units.
Working Three.js Starter (mean-and-variance-counterfactual-explorer-x1840):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mean-Lock Voxel Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #080c18;
--panel: #101625;
--panel-2: #151d2f;
--border: rgba(255, 255, 255, 0.09);
--text: #f4f7ff;
--muted: #9aa8bf;
--cyan: #4de3ff;
--green: #62e6a7;
--purple: #9b7cff;
--blue: #5795ff;
--amber: #ffc857;
--pink: #ff7797;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
min-height: 100%;
margin: 0;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
overflow: hidden;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#app {
display: grid;
grid-template-columns: 390px minmax(0, 1fr);
width: 100%;
height: 100vh;
}
#panel {
position: relative;
z-index: 3;
overflow-y: auto;
padding: 26px 24px 30px;
background:
radial-gradient(circle at 15% 0%, rgba(77, 227, 255, 0.08), transparent 27%),
linear-gradient(180deg, #111827 0%, #0b1120 100%);
border-right: 1px solid var(--border);
box-shadow: 16px 0 50px rgba(0, 0, 0, 0.22);
scrollbar-width: thin;
scrollbar-color: #34415b transparent;
}
.eyebrow {
margin: 0 0 9px;
color: var(--cyan);
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 2rem;
line-height: 1.08;
letter-spacing: -0.04em;
}
.intro {
margin: 12px 0 20px;
color: var(--muted);
font-size: 0.9rem;
line-height: 1.55;
}
.lock-banner {
position: relative;
overflow: hidden;
padding: 14px 15px;
border: 1px solid rgba(98, 230, 167, 0.22);
border-radius: 14px;
background:
linear-gradient(100deg, rgba(98, 230, 167, 0.11), rgba(77, 227, 255, 0.04));
}
.lock-banner::after {
position: absolute;
right: -22px;
bottom: -36px;
width: 95px;
height: 95px;
border: 1px solid rgba(98, 230, 167, 0.16);
border-radius: 50%;
content: "";
}
.lock-title {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 7px;
color: var(--green);
font-size: 0.75rem;
font-weight: 850;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.lock-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 15px var(--green);
}
#lockText {
position: relative;
z-index: 1;
margin: 0;
color: #c6d4c9;
font-size: 0.79rem;
line-height: 1.45;
}
.stats {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 8px;
margin: 14px 0;
}
.stat {
min-width: 0;
padding: 13px 10px 12px;
border: 1px solid var(--border);
border-radius: 13px;
background: rgba(255, 255, 255, 0.035);
}
.stat-label {
display: block;
margin-bottom: 7px;
color: var(--muted);
font-size: 0.67rem;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.stat-value {
display: block;
overflow: hidden;
font-size: 1.12rem;
font-weight: 800;
letter-spacing: -0.04em;
text-overflow: ellipsis;
white-space: nowrap;
}
.stat-unit {
margin-left: 2px;
color: var(--muted);
font-size: 0.67rem;
font-weight: 650;
letter-spacing: 0;
}
.mean .stat-value {
color: var(--cyan);
}
.variance .stat-value {
color: var(--amber);
}
.deviation .stat-value {
color: var(--green);
}
.section {
margin-top: 14px;
padding: 14px;
border: 1px solid var(--border);
border-radius: 14px;
background: rgba(255, 255, 255, 0.025);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 11px;
color: #dbe4f6;
font-size: 0.76rem;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.mode-switch {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 5px;
padding: 4px;
border: 1px solid var(--border);
border-radius: 10px;
background: #0b1220;
}
.mode-switch button {
padding: 7px 8px;
border: 0;
border-radius: 7px;
background: transparent;
color: var(--muted);
cursor: pointer;
font-size: 0.72rem;
font-weight: 700;
}
.mode-switch button.active {
background: #253149;
color: white;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
#formulaText {
min-height: 46px;
margin-top: 12px;
color: #cbd6e9;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.73rem;
line-height: 1.65;
}
.unit-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.unit-row label {
color: #dbe4f6;
font-size: 0.78rem;
font-weight: 750;
}
#unitInput {
width: 88px;
padding: 8px 10px;
border: 1px solid #34415b;
border-radius: 8px;
outline: none;
background: #0a1120;
color: var(--cyan);
font-weight: 800;
text-align: center;
}
#unitInput:focus {
border-color: var(--cyan);
box-shadow: 0 0 0 3px rgba(77, 227, 255, 0.1);
}
#unitExplain {
margin: 10px 0 0;
color: var(--muted);
font-size: 0.75rem;
line-height: 1.5;
}
.unit-key {
display: inline-block;
margin-right: 5px;
padding: 2px 6px;
border-radius: 5px;
background: rgba(255, 200, 87, 0.1);
color: var(--amber);
font-weight: 800;
}
.observations {
margin-top: 16px;
}
.observation-list {
display: grid;
gap: 8px;
}
.observation {
padding: 10px 11px 8px;
border: 1px solid rgba(255, 255, 255, 0.06);
border-left: 3px solid var(--pair-color);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
transition:
background 150ms ease,
border-color 150ms ease,
transform 150ms ease;
}
.observation:hover {
background: rgba(255, 255, 255, 0.045);
}
.observation.active {
border-color: rgba(255, 255, 255, 0.16);
border-left-color: var(--pair-color);
background: rgba(255, 255, 255, 0.075);
transform: translateX(2px);
}
.observation.partner {
background: rgba(255, 255, 255, 0.05);
}
.obs-top {
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
gap: 8px;
margin-bottom: 7px;
}
.obs-name {
display: flex;
align-items: center;
gap: 7px;
color: #e8eefb;
font-size: 0.77rem;
font-weight: 800;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 3px;
background: var(--pair-color);
box-shadow: 0 0 9px color-mix(in srgb, var(--pair-color) 60%, transparent);
}
.partner-tag {
color: #7f8ca4;
font-size: 0.66rem;
text-align: center;
}
.obs-value {
color: var(--pair-color);
font-size: 0.76rem;
font-weight: 850;
white-space: nowrap;
}
.observation input[type="range"] {
width: 100%;
height: 16px;
margin: 0;
accent-color: var(--pair-color);
cursor: ew-resize;
}
.notes {
margin-top: 16px;
padding: 13px 14px;
border: 1px solid rgba(77, 227, 255, 0.12);
border-radius: 13px;
background: rgba(77, 227, 255, 0.035);
}
.notes strong {
color: var(--cyan);
}
.notes p {
margin: 5px 0 0;
color: var(--muted);
font-size: 0.74rem;
line-height: 1.5;
}
#resetButton {
width: 100%;
margin-top: 14px;
padding: 11px 14px;
border: 1px solid #39465f;
border-radius: 10px;
background: #1a2438;
color: white;
cursor: pointer;
font-weight: 800;
transition:
background 150ms ease,
transform 150ms ease;
}
#resetButton:hover {
background: #25324a;
}
#resetButton:active {
transform: translateY(1px);
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 52% 30%, #17243b 0%, #0b1120 48%, #070b14 100%);
}
#threeCanvas {
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
}
.scene-chip {
position: absolute;
top: 20px;
left: 22px;
padding: 8px 11px;
border: 1px solid rgba(98, 230, 167, 0.2);
border-radius: 999px;
background: rgba(8, 14, 27, 0.72);
color: #b9c9d8;
font-size: 0.66rem;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
backdrop-filter: blur(10px);
pointer-events: none;
}
.scene-chip span {
margin-left: 5px;
color: var(--green);
}
.scene-help {
position: absolute;
bottom: 22px;
left: 50%;
width: max-content;
max-width: calc(100% - 40px);
padding: 9px 13px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 999px;
background: rgba(8, 14, 27, 0.76);
color: #aab7ca;
font-size: 0.7rem;
text-align: center;
transform: translateX(-50%);
backdrop-filter: blur(10px);
pointer-events: none;
}
.camera-help {
position: absolute;
right: 20px;
bottom: 62px;
color: #718099;
font-size: 0.66rem;
pointer-events: none;
}
#loading {
position: absolute;
inset: 0;
display: grid;
place-items: center;
background: #0b1120;
color: var(--cyan);
font-size: 0.85rem;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
transition: opacity 300ms ease;
}
#loading.hidden {
opacity: 0;
pointer-events: none;
}
@media (max-width: 860px) {
body {
overflow: auto;
}
#app {
display: flex;
flex-direction: column;
height: auto;
min-height: 100vh;
}
#stage {
order: -1;
height: 58vh;
min-height: 430px;
}
#panel {
overflow: visible;
border-right: 0;
border-top: 1px solid var(--border);
}
.camera-help {
display: none;
}
}
@media (max-width: 430px) {
#panel {
padding: 22px 17px 26px;
}
h1 {
font-size: 1.7rem;
}
.stat {
padding: 11px 8px;
}
.stat-value {
font-size: 1rem;
}
}
</style>
</head>
<body>
<div id="app">
<aside id="panel">
<p class="eyebrow">Interactive statistics</p>
<h1>Mean-Lock<br>Voxel Lab</h1>
<p class="intro">
Move an observation up or down. Its paired observation moves by the
opposite amount, keeping the mean fixed while the spread changes.
</p>
<div class="lock-banner">
<div class="lock-title">
<span class="lock-dot"></span>
Mean lock on
</div>
<p id="lockText"></p>
</div>
<div class="stats" aria-live="polite">
<article class="stat mean">
<span class="stat-label">Mean μ</span>
<span class="stat-value">
<span id="meanValue">6.00</span>
<span id="meanUnit" class="stat-unit">m</span>
</span>
</article>
<article class="stat variance">
<span class="stat-label">Variance</span>
<span class="stat-value">
<span id="varianceValue">7.00</span>
<span id="varianceUnit" class="stat-unit">m²</span>
</span>
</article>
<article class="stat deviation">
<span class="stat-label">Std. dev.</span>
<span class="stat-value">
<span id="stdValue">2.65</span>
<span id="stdUnit" class="stat-unit">m</span>
</span>
</article>
</div>
<section class="section">
<div class="section-title">Calculation method</div>
<div class="mode-switch" role="group" aria-label="Variance method">
<button id="populationButton" class="active" type="button">
Population · N
</button>
<button id="sampleButton" type="button">
Sample · N−1
</button>
</div>
<div id="formulaText"></div>
</section>
<section class="section">
<div class="section-title">Measurement units</div>
<div class="unit-row">
<label for="unitInput">Original measurement unit</label>
<input
id="unitInput"
type="text"
value="m"
maxlength="8"
autocomplete="off"
spellcheck="false"
aria-label="Original measurement unit"
>
</div>
<p id="unitExplain"></p>
</section>
<section class="observations">
<div class="section-title">
<span>Move observations</span>
<span style="color: var(--muted); font-size: 0.63rem;">
linked pairs
</span>
</div>
<div id="observationList" class="observation-list"></div>
</section>
<div class="notes">
<strong>Why variance has squared units</strong>
<p>
Variance averages squared deviations, so its unit is the original
unit squared. Taking a square root gives standard deviation in the
original measurement unit.
</p>
</div>
<button id="resetButton" type="button">Reset observations</button>
</aside>
<main id="stage">
<canvas
id="threeCanvas"
tabindex="0"
aria-label="Interactive three-dimensional voxel chart"
></canvas>
<div class="scene-chip">Mean lock <span>● active</span></div>
<div class="camera-help">Drag background to orbit · Scroll to zoom</div>
<div class="scene-help">
Drag a tower vertically · Its highlighted partner balances the change
</div>
<div id="loading">Building voxel lab…</div>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const INITIAL_VALUES = [2, 4, 5, 7, 8, 10];
const FIXED_MEAN = 6;
const FIXED_PAIR_SUM = 12;
const MIN_VALUE = 0.5;
const MAX_VALUE = 11.5;
const STEP = 0.5;
const VOXEL_HEIGHT = 0.5;
const PAIR_COLORS = [0x9b7cff, 0x5795ff, 0x2dd4bf];
const PAIR_HEX = ["#9b7cff", "#5795ff", "#2dd4bf"];
const PARTNER = [5, 4, 3, 2, 1, 0];
const PAIR_FOR_OBSERVATION = [0, 1, 2, 2, 1, 0];
const X_POSITIONS = [-7.5, -4.5, -1.5, 1.5, 4.5, 7.5];
const state = {
values: [...INITIAL_VALUES],
active: 2,
population: true,
unit: "m"
};
const observationList = $("observationList");
const observationElements = [];
for (let i = 0; i < 6; i++) {
const row = document.createElement("div");
row.className = "observation";
row.style.setProperty("--pair-color", PAIR_HEX[PAIR_FOR_OBSERVATION[i]]);
row.innerHTML = `
<div class="obs-top">
<button
class="obs-name"
type="button"
aria-label="Select observation ${i + 1}"
>
<span class="swatch"></span>
<span>O${i + 1}</span>
</button>
<span class="partner-tag">paired with O${PARTNER[i] + 1}</span>
<output class="obs-value" id="obsValue${i}"></output>
</div>
<input
id="obsSlider${i}"
type="range"
min="${MIN_VALUE}"
max="${MAX_VALUE}"
step="${STEP}"
aria-label="Observation ${i + 1} value"
>
`;
observationList.appendChild(row);
observationElements.push(row);
row.querySelector(".obs-name").addEventListener("click", () => {
selectObservation(i);
});
row.querySelector("input").addEventListener("input", (event) => {
const requestedValue = Number(event.target.value);
selectObservation(i);
setObservationValue(i, requestedValue);
});
}
function currentUnit() {
return state.unit || "units";
}
function squaredUnit() {
const unit = currentUnit();
return unit === "units" ? "units²" : `${unit}²`;
}
function selectObservation(index) {
state.active = index;
updateHighlights();
updateObservationUI();
}
function setObservationValue(index, rawValue) {
const clamped = Math.max(MIN_VALUE, Math.min(MAX_VALUE, rawValue));
const stepped = Math.round(clamped / STEP) * STEP;
const partner = PARTNER[index];
state.values[index] = Number(stepped.toFixed(1));
state.values[partner] = Number((FIXED_PAIR_SUM - stepped).toFixed(1));
updateAll();
}
function calculateStatistics() {
const n = state.values.length;
const mean = state.values.reduce((sum, value) => sum + value, 0) / n;
const squaredSum = state.values.reduce(
(sum, value) => sum + (value - mean) ** 2,
0
);
const divisor = state.population ? n : n - 1;
const variance = squaredSum / divisor;
const standardDeviation = Math.sqrt(variance);
return { n, mean, squaredSum, variance, standardDeviation };
}
function updateStatistics() {
const stats = calculateStatistics();
$("meanValue").textContent = stats.mean.toFixed(2);
$("varianceValue").textContent = stats.variance.toFixed(2);
$("stdValue").textContent = stats.standardDeviation.toFixed(2);
$("meanUnit").textContent = currentUnit();
$("stdUnit").textContent = currentUnit();
$("varianceUnit").textContent = squaredUnit();
const varianceSymbol = state.population ? "σ²" : "s²";
const deviationSymbol = state.population ? "σ" : "s";
const divisor = state.population ? stats.n : stats.n - 1;
$("formulaText").textContent =
`${varianceSymbol} = Σ(x − μ)² / ${divisor} = ` +
`${stats.variance.toFixed(2)} ${squaredUnit()}\n` +
`${deviationSymbol} = √${varianceSymbol} = ` +
`${stats.standardDeviation.toFixed(2)} ${currentUnit()}`;
$("unitExplain").textContent =
`The mean and standard deviation use ${currentUnit()}. ` +
`Variance uses ${squaredUnit()} because it is based on squared deviations.`;
$("lockText").textContent =
`Each mirrored pair stays at ${FIXED_PAIR_SUM.toFixed(1)} ${currentUnit()}. ` +
`The total remains ${(FIXED_MEAN * stats.n).toFixed(1)} ${currentUnit()}, ` +
`so the mean remains ${stats.mean.toFixed(2)} ${currentUnit()}.`;
}
function updateObservationUI() {
for (let i = 0; i < 6; i++) {
const partner = PARTNER[i];
const row = observationElements[i];
const slider = $(`obsSlider${i}`);
slider.value = state.values[i];
$(`obsValue${i}`).textContent =
`${state.values[i].toFixed(1)} ${currentUnit()}`;
row.classList.toggle("active", i === state.active);
row.classList.toggle("partner", i === PARTNER[state.active]);
}
}
function updateAll() {
updateStatistics();
updateObservationUI();
updateScene();
updateHighlights();
}
$("populationButton").addEventListener("click", () => {
state.population = true;
$("populationButton").classList.add("active");
$("sampleButton").classList.remove("active");
updateStatistics();
});
$("sampleButton").addEventListener("click", () => {
state.population = false;
$("sampleButton").classList.add("active");
$("populationButton").classList.remove("active");
updateStatistics();
});
$("unitInput").addEventListener("input", (event) => {
state.unit = event.target.value.trim() || "units";
updateAll();
});
$("resetButton").addEventListener("click", () => {
state.values = [...INITIAL_VALUES];
state.active = 2;
updateAll();
});
// ---------------------------------------------------------------------
// Three.js scene
// ---------------------------------------------------------------------
const canvas = $("threeCanvas");
const stage = $("stage");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x080c18);
scene.fog = new THREE.Fog(0x080c18, 25, 47);
const camera = new THREE.PerspectiveCamera(38, 1, 0.1, 100);
const cameraState = {
theta: 0.35,
phi: 1.16,
radius: 24,
target: new THREE.Vector3(0, 3.7, 0)
};
function updateCamera() {
const { theta, phi, radius, target } = cameraState;
const sinPhi = Math.sin(phi);
camera.position.set(
target.x + radius * sinPhi * Math.sin(theta),
target.y + radius * Math.cos(phi),
target.z + radius * sinPhi * Math.cos(theta)
);
camera.lookAt(target);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xc7e2ff, 0x151426, 1.7);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.5);
keyLight.position.set(-8, 17, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -14;
keyLight.shadow.camera.right = 14;
keyLight.shadow.camera.top = 16;
keyLight.shadow.camera.bottom = -8;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 45;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x42dfff, 16, 30, 2);
cyanLight.position.set(5, 7, 7);
scene.add(cyanLight);
const purpleLight = new THREE.PointLight(0x8065ff, 13, 26, 2);
purpleLight.position.set(-8, 5, 4);
scene.add(purpleLight);
const floor = new THREE.Mesh(
new THREE.BoxGeometry(21, 0.3, 9),
new THREE.MeshStandardMaterial({
color: 0x101827,
roughness: 0.92,
metalness: 0.03
})
);
floor.position.y = -0.17;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(20, 20, 0x3b5878, 0x26374f);
grid.position.y = 0.005;
grid.material.transparent = true;
grid.material.opacity = 0.26;
scene.add(grid);
const backRail = new THREE.Mesh(
new THREE.BoxGeometry(20, 12.8, 0.12),
new THREE.MeshStandardMaterial({
color: 0x0b1322,
roughness: 1,
transparent: true,
opacity: 0.68
})
);
backRail.position.set(0, 6.35, -4.35);
backRail.receiveShadow = true;
scene.add(backRail);
function roundedRectPath(context, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
context.beginPath();
context.moveTo(x + r, y);
context.arcTo(x + width, y, x + width, y + height, r);
context.arcTo(x + width, y + height, x, y + height, r);
context.arcTo(x, y + height, x, y, r);
context.arcTo(x, y, x + width, y, r);
context.closePath();
}
function createLabel(
initialText,
width = 1.8,
height = 0.46,
background = "rgba(8, 15, 29, 0.9)",
foreground = "#ffffff",
border = "rgba(255,255,255,0.16)"
) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 128;
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(width, height, 1);
sprite.renderOrder = 10;
sprite.userData.draw = (
text,
nextBackground = background,
nextForeground = foreground,
nextBorder = border
) => {
const context = labelCanvas.getContext("2d");
context.clearRect(0, 0, labelCanvas.width, labelCanvas.height);
roundedRectPath(context, 7, 9, 498, 108, 24);
context.fillStyle = nextBackground;
context.fill();
context.lineWidth = 3;
context.strokeStyle = nextBorder;
context.stroke();
context.fillStyle = nextForeground;
context.font = "700 48px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 256, 65, 468);
texture.needsUpdate = true;
};
sprite.userData.draw(initialText);
return sprite;
}
const meanPlane = new THREE.Mesh(
new THREE.PlaneGeometry(18, 8),
new THREE.MeshBasicMaterial({
color: 0x4de3ff,
transparent: true,
opacity: 0.075,
side: THREE.DoubleSide,
depthWrite: false
})
);
meanPlane.rotation.x = -Math.PI / 2;
meanPlane.position.y = FIXED_MEAN;
meanPlane.renderOrder = 1;
scene.add(meanPlane);
const meanBorderGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-9, FIXED_MEAN, -4),
new THREE.Vector3(9, FIXED_MEAN, -4),
new THREE.Vector3(9, FIXED_MEAN, 4),
new THREE.Vector3(-9, FIXED_MEAN, 4)
]);
const meanBorder = new THREE.LineLoop(
meanBorderGeometry,
new THREE.LineBasicMaterial({
color: 0x4de3ff,
transparent: true,
opacity: 0.42
})
);
scene.add(meanBorder);
const meanFrontLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-9, FIXED_MEAN, 4.05),
new THREE.Vector3(9, FIXED_MEAN, 4.05)
]),
new THREE.LineDashedMaterial({
color: 0x4de3ff,
dashSize: 0.28,
gapSize: 0.16,
transparent: true,
opacity: 0.8
})
);
meanFrontLine.computeLineDistances();
scene.add(meanFrontLine);
const meanLabel = createLabel(
"μ = 6.00 m",
2.35,
0.58,
"rgba(15, 54, 70, 0.94)",
"#8ff2ff",
"rgba(77, 227, 255, 0.5)"
);
meanLabel.position.set(-7.9, FIXED_MEAN + 0.62, 4.1);
scene.add(meanLabel);
const verticalScale = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-9.5, 0, 4.05),
new THREE.Vector3(-9.5, 12, 4.05)
]),
new THREE.LineBasicMaterial({
color: 0x63738b,
transparent: true,
opacity: 0.65
})
);
scene.add(verticalScale);
for (let value = 0; value <= 12; value += 2) {
const tick = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-9.65, value, 4.05),
new THREE.Vector3(-9.35, value, 4.05)
]),
new THREE.LineBasicMaterial({
color: 0x8da0b9,
transparent: true,
opacity: 0.75
})
);
scene.add(tick);
const label = createLabel(
String(value),
0.55,
0.28,
"rgba(8, 15, 29, 0.78)",
"#9aa8bf",
"rgba(255,255,255,0.05)"
);
label.position.set(-9.9, value, 4.08);
scene.add(label);
}
const axisLabel = createLabel(
"OBSERVATION VALUE",
2.55,
0.43,
"rgba(8, 15, 29, 0.85)",
"#8b9ab0",
"rgba(255,255,255,0.08)"
);
axisLabel.position.set(0, 0.32, 4.35);
scene.add(axisLabel);
const voxelGeometry = new THREE.BoxGeometry(0.44, 0.44, 0.44);
const pickGeometry = new THREE.BoxGeometry(1.04, 1, 1.04);
const pickMaterial = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
colorWrite: false
});
const towerItems = [];
const pickMeshes = [];
const dummy = new THREE.Object3D();
for (let i = 0; i < 6; i++) {
const group = new THREE.Group();
group.position.x = X_POSITIONS[i];
scene.add(group);
const pairColor = PAIR_COLORS[PAIR_FOR_OBSERVATION[i]];
const base = new THREE.Mesh(
new THREE.BoxGeometry(1.25, 0.16, 1.25),
new THREE.MeshStandardMaterial({
color: 0x202b3d,
roughness: 0.65,
metalness: 0.15
})
);
base.position.y = 0.08;
base.receiveShadow = true;
group.add(base);
const material = new THREE.MeshStandardMaterial({
color: pairColor,
emissive: pairColor,
emissiveIntensity: 0.04,
roughness: 0.32,
metalness: 0.08
});
const instances = new THREE.InstancedMesh(
voxelGeometry,
material,
24
);
instances.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
instances.castShadow = true;
instances.receiveShadow = true;
instances.frustumCulled = false;
group.add(instances);
const pickMesh = new THREE.Mesh(pickGeometry, pickMaterial);
pickMesh.userData.observationIndex = i;
group.add(pickMesh);
pickMeshes.push(pickMesh);
const valueLabel = createLabel(
"0.0",
1.4,
0.36,
"rgba(8, 15, 29, 0.88)",
"#ffffff",
"rgba(255,255,255,0.16)"
);
scene.add(valueLabel);
const idLabel = createLabel(
`O${i + 1}`,
0.78,
0.31,
"rgba(8, 15, 29, 0.85)",
PAIR_HEX[PAIR_FOR_OBSERVATION[i]],
"rgba(255,255,255,0.08)"
);
idLabel.position.set(X_POSITIONS[i], 0.28, 0.9);
scene.add(idLabel);
towerItems.push({
group,
instances,
material,
pickMesh,
valueLabel
});
}
const pairLines = [];
const pairPointCount = 31;
for (let pair = 0; pair < 3; pair++) {
const positions = new Float32Array(pairPointCount * 3);
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.BufferAttribute(positions, 3)
);
const material = new THREE.LineBasicMaterial({
color: PAIR_COLORS[pair],
transparent: true,
opacity: 0.25
});
const line = new THREE.Line(geometry, material);
line.frustumCulled = false;
scene.add(line);
pairLines.push(line);
}
const deviationLines = [];
for (let i = 0; i < 6; i++) {
const positions = new Float32Array(6);
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.BufferAttribute(positions, 3)
);
const material = new THREE.LineDashedMaterial({
color: 0x4de3ff,
dashSize: 0.14,
gapSize: 0.1,
transparent: true,
opacity: 0.62
});
const line = new THREE.Line(geometry, material);
line.frustumCulled = false;
scene.add(line);
deviationLines.push(line);
}
function updateScene() {
for (let i = 0; i < 6; i++) {
const value = state.values[i];
const item = towerItems[i];
const voxelCount = Math.round(value / VOXEL_HEIGHT);
for (let voxel = 0; voxel < voxelCount; voxel++) {
dummy.position.set(0, (voxel + 0.5) * VOXEL_HEIGHT, 0);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
item.instances.setMatrixAt(voxel, dummy.matrix);
}
item.instances.count = voxelCount;
item.instances.instanceMatrix.needsUpdate = true;
item.pickMesh.scale.set(1, value, 1);
item.pickMesh.position.y = value / 2;
item.valueLabel.position.set(
X_POSITIONS[i],
value + 0.48,
0.92
);
item.valueLabel.userData.draw(
value.toFixed(1),
"rgba(8, 15, 29, 0.88)",
"#ffffff",
"rgba(255,255,255,0.16)"
);
const deviation = deviationLines[i];
const positions = deviation.geometry.attributes.position.array;
const lower = Math.min(FIXED_MEAN, value);
const upper = Math.max(FIXED_MEAN, value);
positions[0] = X_POSITIONS[i];
positions[1] = lower;
positions[2] = 0.74;
positions[3] = X_POSITIONS[i];
positions[4] = upper;
positions[5] = 0.74;
deviation.geometry.attributes.position.needsUpdate = true;
deviation.computeLineDistances();
deviation.material.color.setHex(
value >= FIXED_MEAN ? 0xffc857 : 0x4de3ff
);
}
for (let pair = 0; pair < 3; pair++) {
const leftIndex = pair;
const rightIndex = 5 - pair;
const start = new THREE.Vector3(
X_POSITIONS[leftIndex],
state.values[leftIndex] + 0.35,
0
);
const end = new THREE.Vector3(
X_POSITIONS[rightIndex],
state.values[rightIndex] + 0.35,
0
);
const control = new THREE.Vector3(
(start.x + end.x) / 2,
Math.max(start.y, end.y) + 2.0,
0
);
const positions = pairLines[pair].geometry.attributes.position.array;
for (let point = 0; point < pairPointCount; point++) {
const t = point / (pairPointCount - 1);
const inverse = 1 - t;
const x =
inverse * inverse * start.x +
2 * inverse * t * control.x +
t * t * end.x;
const y =
inverse * inverse * start.y +
2 * inverse * t * control.y +
t * t * end.y;
const z =
inverse * inverse * start.z +
2 * inverse * t * control.z +
t * t * end.z;
positions[point * 3] = x;
positions[point * 3 + 1] = y;
positions[point * 3 + 2] = z;
}
pairLines[pair].geometry.attributes.position.needsUpdate = true;
}
meanLabel.userData.draw(
`μ = ${FIXED_MEAN.toFixed(2)} ${currentUnit()}`,
"rgba(15, 54, 70, 0.94)",
"#8ff2ff",
"rgba(77, 227, 255, 0.5)"
);
}
function updateHighlights() {
const activePartner = PARTNER[state.active];
for (let i = 0; i < 6; i++) {
const item = towerItems[i];
if (i === state.active) {
item.material.emissiveIntensity = 0.48;
} else if (i === activePartner) {
item.material.emissiveIntensity = 0.25;
} else {
item.material.emissiveIntensity = 0.035;
}
}
for (let pair = 0; pair < 3; pair++) {
pairLines[pair].material.opacity =
PAIR_FOR_OBSERVATION[state.active] === pair ? 0.95 : 0.22;
}
}
// ---------------------------------------------------------------------
// Direct manipulation and custom camera controls
// ---------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let pointerAction = null;
let hoverIndex = -1;
function setRayFromEvent(event) {
const rect = canvas.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);
}
function getHitObservation(event) {
setRayFromEvent(event);
const hits = raycaster.intersectObjects(pickMeshes, false);
return hits.length ? hits[0].object.userData.observationIndex : -1;
}
canvas.addEventListener("pointerdown", (event) => {
canvas.focus();
const hitIndex = getHitObservation(event);
if (hitIndex >= 0) {
selectObservation(hitIndex);
pointerAction = {
type: "value",
pointerId: event.pointerId,
startY: event.clientY,
startValue: state.values[hitIndex],
index: hitIndex
};
canvas.style.cursor = "ns-resize";
} else {
pointerAction = {
type: "orbit",
pointerId: event.pointerId,
startX: event.clientX,
startY: event.clientY,
theta: cameraState.theta,
phi: cameraState.phi
};
canvas.style.cursor = "grabbing";
}
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (pointerAction?.type === "value") {
const pixelsPerUnit = 21;
const delta = (pointerAction.startY - event.clientY) / pixelsPerUnit;
setObservationValue(
pointerAction.index,
pointerAction.startValue + delta
);
return;
}
if (pointerAction?.type === "orbit") {
const deltaX = event.clientX - pointerAction.startX;
const deltaY = event.clientY - pointerAction.startY;
cameraState.theta =
pointerAction.theta - deltaX * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
pointerAction.phi + deltaY * 0.005,
0.55,
1.48
);
updateCamera();
return;
}
const hitIndex = getHitObservation(event);
hoverIndex = hitIndex;
canvas.style.cursor = hitIndex >= 0 ? "ns-resize" : "grab";
});
function endPointerAction(event) {
if (!pointerAction) return;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
pointerAction = null;
canvas.style.cursor = hoverIndex >= 0 ? "ns-resize" : "grab";
}
canvas.addEventListener("pointerup", endPointerAction);
canvas.addEventListener("pointercancel", endPointerAction);
canvas.addEventListener("pointerleave", () => {
if (!pointerAction) {
hoverIndex = -1;
canvas.style.cursor = "grab";
}
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.012,
16,
31
);
updateCamera();
},
{ passive: false }
);
document.addEventListener("keydown", (event) => {
if (["INPUT", "TEXTAREA", "BUTTON"].includes(document.activeElement?.tagName)) {
return;
}
let direction = 0;
if (event.key === "ArrowUp" || event.key === "ArrowRight") {
direction = 1;
} else if (
event.key === "ArrowDown" ||
event.key === "ArrowLeft"
) {
direction = -1;
}
if (direction !== 0) {
event.preventDefault();
setObservationValue(
state.active,
state.values[state.active] + direction * STEP
);
}
});
function resize() {
const width = stage.clientWidth;
const height = stage.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / Math.max(height, 1);
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(stage);
resize();
updateAll();
function animate(time) {
requestAnimationFrame(animate);
const pulse = 0.5 + Math.sin(time * 0.003) * 0.08;
meanPlane.material.opacity = 0.065 + pulse * 0.025;
meanBorder.material.opacity = 0.36 + pulse * 0.18;
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
$("loading").classList.add("hidden");
</script>
</body>
</html>
```