Prompt specification
Build or customize the Three.js 3D scene "Binomial count column display" 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: Binomial count column display
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/binomial-count-column-display-x1769
Scene Description Prompt:
Build outcome-count columns for a fixed number of independent binary trials; compute exact probabilities and label both trial count and success probability. Use Three.js from cdnjs in a single HTML file, with low-poly forms.
Working Three.js Starter (binomial-count-column-display-x1769):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Exact Binomial Outcome Columns</title>
<style>
:root {
--ink: #17312d;
--muted: #65736f;
--paper: #f3f0e7;
--card: #fffdf7;
--line: #d9d6cb;
--green: #246c5d;
--lime: #b9d86d;
--orange: #ed8c5a;
--deep: #19342f;
}
* {
box-sizing: border-box;
}
html {
scroll-behavior: smooth;
}
body {
margin: 0;
min-width: 320px;
color: var(--ink);
background:
radial-gradient(circle at 8% 0%, rgba(185, 216, 109, 0.16), transparent 27rem),
var(--paper);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
.topbar {
border-bottom: 1px solid rgba(23, 49, 45, 0.14);
background: rgba(243, 240, 231, 0.82);
backdrop-filter: blur(14px);
}
.topbar-inner {
width: min(1480px, calc(100% - 40px));
min-height: 72px;
margin: 0 auto;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
font-size: 0.82rem;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.brand-mark {
width: 30px;
height: 34px;
display: grid;
place-items: center;
color: var(--deep);
background: var(--lime);
clip-path: polygon(50% 0, 94% 24%, 94% 76%, 50% 100%, 6% 76%, 6% 24%);
}
.brand-mark span {
font-size: 0.72rem;
transform: translateY(-1px);
}
.top-note {
color: var(--muted);
font-size: 0.78rem;
letter-spacing: 0.08em;
text-transform: uppercase;
}
main {
width: min(1480px, calc(100% - 40px));
margin: 0 auto;
padding: 62px 0 80px;
}
.hero {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(250px, 370px);
align-items: end;
gap: 54px;
margin-bottom: 34px;
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 9px;
margin-bottom: 18px;
color: var(--green);
font-size: 0.76rem;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 24px;
height: 2px;
background: currentColor;
}
h1 {
max-width: 950px;
margin: 0;
font-size: clamp(2.8rem, 6vw, 6.2rem);
font-weight: 780;
line-height: 0.94;
letter-spacing: -0.065em;
}
.hero-copy {
padding-bottom: 5px;
}
.hero-copy p {
margin: 0 0 21px;
color: var(--muted);
font-size: 1.02rem;
line-height: 1.65;
}
.method-tags {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.method-tags span {
padding: 7px 10px;
border: 1px solid rgba(23, 49, 45, 0.14);
border-radius: 999px;
color: var(--ink);
background: rgba(255, 253, 247, 0.55);
font-size: 0.72rem;
font-weight: 750;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.workspace {
display: grid;
grid-template-columns: 310px minmax(0, 1fr);
gap: 18px;
align-items: stretch;
}
.controls {
display: flex;
flex-direction: column;
padding: 27px;
color: #f7f4e9;
border-radius: 22px;
background:
radial-gradient(circle at 100% 0%, rgba(185, 216, 109, 0.14), transparent 16rem),
var(--deep);
box-shadow: 0 22px 70px rgba(25, 52, 47, 0.16);
}
.panel-kicker {
margin-bottom: 8px;
color: var(--lime);
font-size: 0.7rem;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.controls h2 {
margin: 0 0 28px;
font-size: 1.65rem;
letter-spacing: -0.035em;
}
.control {
margin-bottom: 29px;
}
.control-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 16px;
margin-bottom: 13px;
}
.control label {
font-size: 0.86rem;
font-weight: 700;
}
.control output {
color: var(--lime);
font-size: 0.88rem;
font-weight: 800;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
--fill: 50%;
width: 100%;
height: 5px;
margin: 7px 0;
appearance: none;
border-radius: 999px;
background: linear-gradient(
to right,
var(--lime) 0,
var(--lime) var(--fill),
rgba(255, 255, 255, 0.16) var(--fill),
rgba(255, 255, 255, 0.16) 100%
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 19px;
height: 19px;
appearance: none;
border: 3px solid var(--deep);
border-radius: 50%;
background: var(--lime);
box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.32);
}
input[type="range"]::-moz-range-thumb {
width: 15px;
height: 15px;
border: 3px solid var(--deep);
border-radius: 50%;
background: var(--lime);
box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.32);
}
input[type="range"]:focus-visible {
outline: 2px solid var(--lime);
outline-offset: 7px;
}
.range-ends {
display: flex;
justify-content: space-between;
margin-top: 7px;
color: rgba(247, 244, 233, 0.48);
font-size: 0.67rem;
font-weight: 700;
letter-spacing: 0.08em;
}
.stat-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-top: 3px;
}
.stat {
min-height: 84px;
padding: 13px;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 12px;
background: rgba(255, 255, 255, 0.045);
}
.stat span {
display: block;
margin-bottom: 9px;
color: rgba(247, 244, 233, 0.52);
font-size: 0.64rem;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.stat strong {
display: block;
font-size: 1.22rem;
font-variant-numeric: tabular-nums;
letter-spacing: -0.02em;
}
.formula-card {
margin-top: 18px;
padding: 16px;
border: 1px solid rgba(185, 216, 109, 0.25);
border-radius: 14px;
background: rgba(185, 216, 109, 0.075);
}
.formula-card span {
display: block;
margin-bottom: 8px;
color: var(--lime);
font-size: 0.65rem;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.formula-main {
margin-bottom: 9px;
font-family: Georgia, "Times New Roman", serif;
font-size: 1rem;
line-height: 1.5;
}
.formula-note {
margin: 0;
color: rgba(247, 244, 233, 0.56);
font-size: 0.72rem;
line-height: 1.5;
}
.chart-card {
min-width: 0;
overflow: hidden;
border: 1px solid rgba(23, 49, 45, 0.13);
border-radius: 22px;
background: var(--card);
box-shadow: 0 22px 70px rgba(23, 49, 45, 0.09);
}
.scene-wrap {
position: relative;
height: 640px;
overflow: hidden;
background: #f1ede3;
}
#canvasHost,
#labelLayer {
position: absolute;
inset: 0;
}
#canvasHost canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#canvasHost canvas:active {
cursor: grabbing;
}
#labelLayer {
z-index: 3;
overflow: hidden;
pointer-events: none;
}
.scene-chip {
position: absolute;
z-index: 5;
top: 17px;
left: 17px;
display: flex;
flex-direction: column;
gap: 3px;
padding: 10px 13px;
border: 1px solid rgba(23, 49, 45, 0.12);
border-radius: 10px;
background: rgba(255, 253, 247, 0.82);
box-shadow: 0 8px 25px rgba(23, 49, 45, 0.07);
backdrop-filter: blur(8px);
pointer-events: none;
}
.scene-chip span {
color: var(--muted);
font-size: 0.59rem;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.scene-chip strong {
font-size: 0.86rem;
font-variant-numeric: tabular-nums;
}
#pChip {
left: 181px;
}
.reset-view {
position: absolute;
z-index: 6;
top: 17px;
right: 17px;
padding: 9px 12px;
border: 1px solid rgba(23, 49, 45, 0.14);
border-radius: 9px;
color: var(--ink);
background: rgba(255, 253, 247, 0.82);
cursor: pointer;
font-size: 0.72rem;
font-weight: 750;
backdrop-filter: blur(8px);
}
.reset-view:hover {
background: #fffdf7;
}
.reset-view:focus-visible {
outline: 2px solid var(--green);
outline-offset: 3px;
}
.bar-label {
--leader: 8px;
position: absolute;
width: 70px;
padding: 4px 5px 5px;
border: 1px solid rgba(23, 49, 45, 0.15);
border-radius: 7px;
color: var(--ink);
background: rgba(255, 253, 247, 0.91);
box-shadow: 0 5px 14px rgba(23, 49, 45, 0.1);
text-align: center;
transform: translate(-50%, -100%);
backdrop-filter: blur(5px);
}
.bar-label::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
width: 1px;
height: var(--leader);
background: rgba(23, 49, 45, 0.35);
}
.bar-label strong,
.bar-label span {
display: block;
white-space: nowrap;
}
.bar-label strong {
margin-bottom: 2px;
font-size: 0.67rem;
font-variant-numeric: tabular-nums;
}
.bar-label span {
color: var(--green);
font-size: 0.59rem;
font-weight: 750;
font-variant-numeric: tabular-nums;
}
.axis-note {
position: absolute;
z-index: 4;
bottom: 16px;
padding: 7px 10px;
border-radius: 8px;
color: rgba(23, 49, 45, 0.62);
background: rgba(255, 253, 247, 0.68);
font-size: 0.63rem;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
pointer-events: none;
}
.axis-x {
left: 17px;
}
.axis-y {
right: 17px;
}
.chart-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 22px;
min-height: 60px;
padding: 14px 19px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 0.73rem;
line-height: 1.45;
}
.chart-footer strong {
color: var(--ink);
}
.camera-hint {
flex: none;
color: var(--muted);
font-size: 0.68rem;
}
.ledger {
margin-top: 18px;
overflow: hidden;
border: 1px solid rgba(23, 49, 45, 0.14);
border-radius: 16px;
background: rgba(255, 253, 247, 0.72);
}
.ledger summary {
padding: 17px 20px;
cursor: pointer;
font-size: 0.8rem;
font-weight: 800;
letter-spacing: 0.04em;
}
.table-wrap {
max-height: 420px;
overflow: auto;
border-top: 1px solid var(--line);
}
table {
width: 100%;
border-collapse: collapse;
font-size: 0.79rem;
font-variant-numeric: tabular-nums;
}
th,
td {
padding: 11px 20px;
border-bottom: 1px solid rgba(23, 49, 45, 0.08);
text-align: left;
}
th {
position: sticky;
top: 0;
color: var(--muted);
background: #f8f5ed;
font-size: 0.66rem;
letter-spacing: 0.09em;
text-transform: uppercase;
}
td:nth-child(2),
td:nth-child(3),
th:nth-child(2),
th:nth-child(3) {
text-align: right;
}
@media (max-width: 980px) {
.hero {
grid-template-columns: 1fr;
gap: 25px;
}
.hero-copy {
max-width: 680px;
}
.workspace {
grid-template-columns: 1fr;
}
.controls {
display: grid;
grid-template-columns: 1fr 1fr;
column-gap: 30px;
}
.controls > .panel-heading,
.controls > .formula-card {
grid-column: 1 / -1;
}
.controls > .panel-heading {
margin-bottom: 0;
}
.stat-grid {
align-self: end;
margin-bottom: 29px;
}
}
@media (max-width: 680px) {
.topbar-inner,
main {
width: min(100% - 24px, 1480px);
}
.top-note {
display: none;
}
main {
padding-top: 42px;
}
h1 {
font-size: clamp(2.65rem, 14vw, 4.4rem);
}
.controls {
display: block;
padding: 22px;
}
.stat-grid {
margin-bottom: 0;
}
.scene-wrap {
height: 510px;
}
#pChip {
top: 80px;
left: 17px;
}
.reset-view {
font-size: 0;
}
.reset-view::after {
content: "Reset";
font-size: 0.72rem;
}
.chart-footer {
display: block;
}
.camera-hint {
display: block;
margin-top: 7px;
}
.bar-label {
width: 60px;
}
}
@media (prefers-reduced-motion: reduce) {
html {
scroll-behavior: auto;
}
}
</style>
</head>
<body>
<header class="topbar">
<div class="topbar-inner">
<div class="brand">
<div class="brand-mark" aria-hidden="true"><span>Σ</span></div>
<span>Outcome Lab</span>
</div>
<div class="top-note">Independent binary trials · exact binomial model</div>
</div>
</header>
<main>
<section class="hero">
<div>
<div class="eyebrow">Exact probability, no sampling</div>
<h1>Count the outcomes. Keep the probability.</h1>
</div>
<div class="hero-copy">
<p>
Fix the number of independent trials and the chance of success.
Every possible success count becomes a faceted column with its
exact binomial probability.
</p>
<div class="method-tags">
<span>Deterministic</span>
<span>Low-poly 3D</span>
<span>Interactive</span>
</div>
</div>
</section>
<section class="workspace" aria-label="Binomial probability explorer">
<aside class="controls">
<div class="panel-heading">
<div class="panel-kicker">Model settings</div>
<h2>Set the experiment</h2>
</div>
<div class="control">
<div class="control-head">
<label for="trialRange">Fixed trial count · n</label>
<output id="trialValue" for="trialRange">18 trials</output>
</div>
<input
id="trialRange"
type="range"
min="1"
max="32"
step="1"
value="18"
>
<div class="range-ends">
<span>1</span>
<span>32 trials</span>
</div>
</div>
<div class="control">
<div class="control-head">
<label for="probabilityRange">Success probability · p</label>
<output id="probabilityValue" for="probabilityRange">35%</output>
</div>
<input
id="probabilityRange"
type="range"
min="0"
max="1"
step="0.01"
value="0.35"
>
<div class="range-ends">
<span>0%</span>
<span>100%</span>
</div>
</div>
<div class="stat-grid" aria-live="polite">
<div class="stat">
<span>Expected count</span>
<strong id="meanStat">6.3</strong>
</div>
<div class="stat">
<span>Most likely k</span>
<strong id="modeStat">6</strong>
</div>
<div class="stat">
<span>Variance</span>
<strong id="varianceStat">4.095</strong>
</div>
<div class="stat">
<span>Std. deviation</span>
<strong id="deviationStat">2.024</strong>
</div>
</div>
<div class="formula-card">
<span>Exact binomial probability</span>
<div class="formula-main" id="formulaMain"></div>
<p class="formula-note">
Evaluated directly with the binomial coefficient. No random
simulation and no probability rounding before plotting.
</p>
</div>
</aside>
<section class="chart-card">
<div class="scene-wrap" id="sceneWrap">
<div id="canvasHost"></div>
<div id="labelLayer" aria-hidden="true"></div>
<div class="scene-chip">
<span>Fixed trials · n</span>
<strong id="trialsChip">18</strong>
</div>
<div class="scene-chip" id="pChip">
<span>Success probability · p</span>
<strong id="probabilityChip">0.35</strong>
</div>
<button class="reset-view" id="resetView" type="button">
Reset view
</button>
<div class="axis-note axis-x">X axis · outcome count k</div>
<div class="axis-note axis-y">Y axis · exact probability</div>
</div>
<div class="chart-footer">
<div>
<strong>Read each column:</strong>
k is the number of successes; P is the exact probability of that
outcome. Heights are scaled relative to the most probable outcome.
</div>
<div class="camera-hint">
Drag to orbit · wheel to zoom · arrow keys to rotate
</div>
</div>
</section>
</section>
<details class="ledger">
<summary>Open the exact probability ledger</summary>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Outcome count k</th>
<th>Exact probability P(X = k)</th>
<th>Percentage</th>
</tr>
</thead>
<tbody id="probabilityRows"></tbody>
</table>
</div>
</details>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// DOM and model state
// -------------------------------------------------------------------------
const trialRange = document.querySelector("#trialRange");
const probabilityRange = document.querySelector("#probabilityRange");
const trialValue = document.querySelector("#trialValue");
const probabilityValue = document.querySelector("#probabilityValue");
const trialsChip = document.querySelector("#trialsChip");
const probabilityChip = document.querySelector("#probabilityChip");
const meanStat = document.querySelector("#meanStat");
const modeStat = document.querySelector("#modeStat");
const varianceStat = document.querySelector("#varianceStat");
const deviationStat = document.querySelector("#deviationStat");
const formulaMain = document.querySelector("#formulaMain");
const probabilityRows = document.querySelector("#probabilityRows");
const canvasHost = document.querySelector("#canvasHost");
const labelLayer = document.querySelector("#labelLayer");
const sceneWrap = document.querySelector("#sceneWrap");
const resetViewButton = document.querySelector("#resetView");
let n = Number(trialRange.value);
let p = Number(probabilityRange.value);
let probabilities = [];
let bars = [];
let labelElements = [];
const SPACING = 0.62;
const BAR_MAX_HEIGHT = 5.1;
const BAR_BOTTOM = 0.08;
// -------------------------------------------------------------------------
// Exact binomial calculation
// -------------------------------------------------------------------------
function binomialProbabilities(trialCount, successProbability) {
const q = 1 - successProbability;
const values = [];
let combination = 1;
for (let k = 0; k <= trialCount; k++) {
if (k > 0) {
combination = combination * (trialCount - k + 1) / k;
}
let probability;
if (successProbability === 0) {
probability = k === 0 ? 1 : 0;
} else if (successProbability === 1) {
probability = k === trialCount ? 1 : 0;
} else {
probability =
combination *
Math.pow(successProbability, k) *
Math.pow(q, trialCount - k);
}
values.push(probability);
}
return values;
}
function formatExact(value) {
if (value === 0) return "0";
if (value < 0.000001) return value.toExponential(5);
return Number(value.toPrecision(8)).toString();
}
function formatPercent(value) {
if (value === 0) return "0%";
if (value < 0.00001) return `${(value * 100).toExponential(3)}%`;
return `${Number((value * 100).toPrecision(5))}%`;
}
function mostLikelyCounts(trialCount, successProbability) {
if (successProbability === 0) return [0];
if (successProbability === 1) return [trialCount];
const raw = (trialCount + 1) * successProbability;
const lower = Math.floor(raw);
if (Number.isInteger(raw) && lower > 0) {
return [lower - 1, lower];
}
return [lower];
}
function updateRangeFill(input) {
const min = Number(input.min);
const max = Number(input.max);
const value = Number(input.value);
const percentage = ((value - min) / (max - min)) * 100;
input.style.setProperty("--fill", `${percentage}%`);
}
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xf1ede3);
scene.fog = new THREE.Fog(0xf1ede3, 28, 62);
const camera = new THREE.PerspectiveCamera(
42,
1,
0.1,
120
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
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;
renderer.domElement.setAttribute(
"aria-label",
"Interactive three-dimensional binomial probability chart"
);
renderer.domElement.tabIndex = 0;
canvasHost.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(
0xfff7df,
0x7d9189,
2.2
);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff2d5, 3.4);
keyLight.position.set(-8, 14, 10);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -18;
keyLight.shadow.camera.right = 18;
keyLight.shadow.camera.top = 18;
keyLight.shadow.camera.bottom = -18;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 55;
keyLight.shadow.bias = -0.00025;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0xaed8d1, 1.6);
rimLight.position.set(10, 7, -12);
scene.add(rimLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(100, 100),
new THREE.MeshStandardMaterial({
color: 0xeee9de,
roughness: 1,
metalness: 0
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.16;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(
80,
80,
0xc8c1b4,
0xded9cf
);
grid.position.y = -0.145;
grid.material.transparent = true;
grid.material.opacity = 0.38;
scene.add(grid);
const chartGroup = new THREE.Group();
scene.add(chartGroup);
const platform = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
color: 0xe5dfd2,
roughness: 0.95,
flatShading: true
})
);
platform.position.y = -0.09;
platform.receiveShadow = true;
chartGroup.add(platform);
const baseline = new THREE.Mesh(
new THREE.BoxGeometry(1, 0.035, 0.075),
new THREE.MeshStandardMaterial({
color: 0x9e9789,
roughness: 0.9
})
);
baseline.position.set(0, 0.025, 0.67);
chartGroup.add(baseline);
// Six-sided columns create the low-poly form.
const barGeometry = new THREE.CylinderGeometry(
0.31,
0.37,
1,
6,
1,
false
);
const edgeGeometry = new THREE.EdgesGeometry(barGeometry, 18);
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x17312d,
transparent: true,
opacity: 0.24
});
const baseGeometry = new THREE.CylinderGeometry(
0.37,
0.39,
0.055,
6
);
const baseMaterial = new THREE.MeshStandardMaterial({
color: 0xd0cabd,
roughness: 0.95,
flatShading: true
});
// -------------------------------------------------------------------------
// Camera controls implemented directly, without addons
// -------------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 2.15, 0);
let currentTheta = 0;
let desiredTheta = 0;
let currentPhi = 1.06;
let desiredPhi = 1.06;
let currentRadius = 12;
let desiredRadius = 12;
let userZoomed = false;
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
function fitRadius() {
const contentWidth = Math.max(3.4, (n - 1) * SPACING + 1.2);
const verticalFov = THREE.MathUtils.degToRad(camera.fov);
const horizontalFov =
2 * Math.atan(Math.tan(verticalFov / 2) * camera.aspect);
const widthDistance =
contentWidth / (2 * Math.tan(horizontalFov / 2));
return Math.max(8.6, widthDistance * 1.16);
}
function resetCamera() {
desiredTheta = 0;
desiredPhi = 1.06;
userZoomed = false;
desiredRadius = fitRadius();
}
function zoomBy(factor) {
const minimum = fitRadius() * 0.58;
const maximum = fitRadius() * 2.1;
desiredRadius = THREE.MathUtils.clamp(
desiredRadius * factor,
minimum,
maximum
);
userZoomed = true;
}
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const deltaX = event.clientX - lastPointerX;
const deltaY = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
desiredTheta -= deltaX * 0.006;
desiredPhi = THREE.MathUtils.clamp(
desiredPhi + deltaY * 0.004,
0.62,
1.38
);
});
function endDrag(event) {
dragging = false;
if (
event &&
renderer.domElement.hasPointerCapture(event.pointerId)
) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
event => {
event.preventDefault();
zoomBy(Math.exp(event.deltaY * 0.001));
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
renderer.domElement.addEventListener("keydown", event => {
const key = event.key;
if (key === "ArrowLeft") desiredTheta += 0.12;
else if (key === "ArrowRight") desiredTheta -= 0.12;
else if (key === "ArrowUp") {
desiredPhi = Math.max(0.62, desiredPhi - 0.08);
} else if (key === "ArrowDown") {
desiredPhi = Math.min(1.38, desiredPhi + 0.08);
} else if (key === "+" || key === "=") {
zoomBy(0.9);
} else if (key === "-") {
zoomBy(1.1);
} else if (key === "Home") {
resetCamera();
} else {
return;
}
event.preventDefault();
});
resetViewButton.addEventListener("click", resetCamera);
// -------------------------------------------------------------------------
// Bars and labels
// -------------------------------------------------------------------------
function clearChart() {
for (const child of [...chartGroup.children]) {
if (child.userData.ownedMaterial) {
child.material.dispose();
}
chartGroup.remove(child);
}
}
function buildBars() {
clearChart();
bars = [];
labelElements = [];
labelLayer.replaceChildren();
const maximumProbability = Math.max(...probabilities);
const totalWidth = Math.max(2.7, (n - 1) * SPACING + 0.9);
platform.scale.set(totalWidth + 1.25, 0.16, 2.65);
baseline.scale.x = totalWidth;
for (let k = 0; k <= n; k++) {
const x = (k - (n - 1) / 2) * SPACING;
const probability = probabilities[k];
const targetHeight =
maximumProbability > 0
? (probability / maximumProbability) * BAR_MAX_HEIGHT
: 0;
const base = new THREE.Mesh(baseGeometry, baseMaterial);
base.position.set(x, 0.005, 0);
base.receiveShadow = true;
chartGroup.add(base);
const hue = 0.47 + 0.36 * (k / Math.max(1, n - 1));
const lightness = 0.46 + 0.08 * (probability / maximumProbability);
const material = new THREE.MeshStandardMaterial({
color: new THREE.Color().setHSL(hue, 0.58, lightness),
roughness: 0.7,
metalness: 0.03,
flatShading: true
});
const mesh = new THREE.Mesh(barGeometry, material);
mesh.position.set(x, BAR_BOTTOM, 0);
mesh.scale.y = 0.001;
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.userData.ownedMaterial = true;
chartGroup.add(mesh);
const edges = new THREE.LineSegments(edgeGeometry, edgeMaterial);
mesh.add(edges);
const label = document.createElement("div");
label.className = "bar-label";
labelLayer.appendChild(label);
labelElements.push(label);
bars.push({
mesh,
k,
probability,
targetHeight,
currentHeight: 0
});
}
updateLabelText();
}
function updateLabelText() {
bars.forEach((bar, index) => {
const label = labelElements[index];
const probability = probabilities[bar.k];
label.innerHTML =
`<strong>k = ${bar.k}</strong>` +
`<span>P = ${formatExact(probability)}</span>`;
label.title =
`Outcome count k=${bar.k}; ` +
`exact probability ${formatExact(probability)} ` +
`(${formatPercent(probability)})`;
});
}
function updateBarTargets() {
const maximumProbability = Math.max(...probabilities);
bars.forEach(bar => {
bar.probability = probabilities[bar.k];
bar.targetHeight =
maximumProbability > 0
? (bar.probability / maximumProbability) * BAR_MAX_HEIGHT
: 0;
});
updateLabelText();
}
// -------------------------------------------------------------------------
// Interface updates
// -------------------------------------------------------------------------
function updateInterface() {
trialValue.textContent = `${n} ${n === 1 ? "trial" : "trials"}`;
probabilityValue.textContent = `${Math.round(p * 100)}%`;
trialsChip.textContent = String(n);
probabilityChip.textContent = p.toFixed(2);
const mean = n * p;
const variance = n * p * (1 - p);
const modes = mostLikelyCounts(n, p);
meanStat.textContent = Number(mean.toFixed(4)).toString();
modeStat.textContent = modes.join(" / ");
varianceStat.textContent = Number(variance.toFixed(5)).toString();
deviationStat.textContent = Number(Math.sqrt(variance).toFixed(4)).toString();
formulaMain.textContent =
`P(X = k) = C(${n}, k) · ${p.toFixed(2)}^k · ` +
`${(1 - p).toFixed(2)}^(${n} − k)`;
probabilityRows.innerHTML = probabilities
.map((probability, k) => `
<tr>
<td>${k} ${k === 1 ? "success" : "successes"}</td>
<td>${formatExact(probability)}</td>
<td>${formatPercent(probability)}</td>
</tr>
`)
.join("");
updateRangeFill(trialRange);
updateRangeFill(probabilityRange);
}
function updateModel(rebuild) {
n = Number(trialRange.value);
p = Number(probabilityRange.value);
probabilities = binomialProbabilities(n, p);
updateInterface();
if (rebuild) {
buildBars();
if (!userZoomed) {
desiredRadius = fitRadius();
} else {
desiredRadius = Math.max(desiredRadius, fitRadius() * 0.7);
}
} else {
updateBarTargets();
}
}
trialRange.addEventListener("input", () => {
updateModel(true);
});
probabilityRange.addEventListener("input", () => {
updateModel(false);
});
// -------------------------------------------------------------------------
// Projected DOM labels
// -------------------------------------------------------------------------
const projected = new THREE.Vector3();
function updateProjectedLabels() {
const width = canvasHost.clientWidth;
const height = canvasHost.clientHeight;
bars.forEach((bar, index) => {
projected.set(
bar.mesh.position.x,
BAR_BOTTOM + bar.currentHeight,
bar.mesh.position.z
);
projected.project(camera);
const label = labelElements[index];
if (
projected.z < -1 ||
projected.z > 1 ||
projected.x < -1.15 ||
projected.x > 1.15
) {
label.style.display = "none";
return;
}
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
// Three label tiers prevent adjacent labels from overlapping.
const tier = bar.k % 3;
const leader = 8 + tier * 34;
label.style.display = "block";
label.style.left = `${x}px`;
label.style.top = `${y - leader}px`;
label.style.setProperty("--leader", `${leader}px`);
});
}
// -------------------------------------------------------------------------
// Resize and animation
// -------------------------------------------------------------------------
function resizeScene() {
const width = canvasHost.clientWidth;
const height = canvasHost.clientHeight;
if (!width || !height) return;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
if (!userZoomed) {
desiredRadius = fitRadius();
} else {
desiredRadius = Math.max(desiredRadius, fitRadius() * 0.7);
}
}
const resizeObserver = new ResizeObserver(resizeScene);
resizeObserver.observe(canvasHost);
let previousTime = performance.now();
function animate(time) {
const delta = Math.min((time - previousTime) / 1000, 0.05);
previousTime = time;
const cameraEase = 1 - Math.exp(-delta * 8);
const barEase = 1 - Math.exp(-delta * 9);
currentTheta += (desiredTheta - currentTheta) * cameraEase;
currentPhi += (desiredPhi - currentPhi) * cameraEase;
currentRadius += (desiredRadius - currentRadius) * cameraEase;
camera.position.set(
cameraTarget.x +
currentRadius *
Math.sin(currentPhi) *
Math.sin(currentTheta),
cameraTarget.y + currentRadius * Math.cos(currentPhi),
cameraTarget.z +
currentRadius *
Math.sin(currentPhi) *
Math.cos(currentTheta)
);
camera.lookAt(cameraTarget);
camera.updateMatrixWorld();
bars.forEach(bar => {
bar.currentHeight +=
(bar.targetHeight - bar.currentHeight) * barEase;
if (Math.abs(bar.targetHeight - bar.currentHeight) < 0.0001) {
bar.currentHeight = bar.targetHeight;
}
bar.mesh.visible = bar.currentHeight > 0.001;
bar.mesh.scale.y = Math.max(0.001, bar.currentHeight);
bar.mesh.position.y = BAR_BOTTOM + bar.currentHeight / 2;
});
updateProjectedLabels();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
// Initial state
updateModel(true);
resizeScene();
desiredRadius = fitRadius();
currentRadius = desiredRadius;
requestAnimationFrame(animate);
</script>
</body>
</html>
```