Prompt specification
Build or customize the Three.js 3D scene "Sampling-design 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: Sampling-design counterfactual explorer
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/sampling-design-counterfactual-explorer-x1832
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts sampling bias and population representation. Let users switch selection mechanisms on the same synthetic population; compare repeated estimate distributions and show that larger biased samples need not remove systematic error. Voxel style.
Working Three.js Starter (sampling-design-counterfactual-explorer-x1832):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Voxel Sampling Lab</title>
<style>
:root {
--bg: #071116;
--panel: #0b171d;
--panel-2: #102129;
--line: #20363f;
--text: #e7f3f4;
--muted: #8ba2a9;
--mint: #73efad;
--lime: #d9ff72;
--cyan: #58d8ff;
--orange: #ffb45e;
--pink: #ff609b;
--green: #75efad;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
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 {
color: inherit;
font: inherit;
}
button:focus-visible {
outline: 2px solid var(--mint);
outline-offset: 3px;
}
.app {
height: 100dvh;
display: flex;
flex-direction: column;
overflow: hidden;
}
.topbar {
min-height: 88px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 17px 24px;
border-bottom: 1px solid var(--line);
background:
linear-gradient(90deg, rgba(115, 239, 173, 0.07), transparent 38%),
#09151a;
z-index: 3;
}
.brand {
display: flex;
align-items: center;
gap: 15px;
min-width: 0;
}
.brand-mark {
width: 45px;
height: 45px;
position: relative;
flex: 0 0 auto;
}
.brand-mark i {
position: absolute;
display: block;
background: var(--mint);
box-shadow: 0 0 18px rgba(115, 239, 173, 0.25);
}
.brand-mark i:nth-child(1) {
width: 21px;
height: 21px;
left: 0;
top: 12px;
}
.brand-mark i:nth-child(2) {
width: 21px;
height: 21px;
right: 0;
top: 0;
background: var(--lime);
}
.brand-mark i:nth-child(3) {
width: 21px;
height: 21px;
right: 0;
bottom: 0;
background: var(--cyan);
}
.eyebrow {
color: var(--mint);
font: 700 11px/1.3 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 4px 0 0;
font-size: clamp(20px, 2vw, 29px);
line-height: 1.1;
letter-spacing: -0.035em;
}
.top-meta {
display: flex;
gap: 8px;
flex-wrap: wrap;
justify-content: flex-end;
}
.meta-pill,
.small-pill {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 8px 10px;
border: 1px solid var(--line);
border-radius: 7px;
color: #bdd0d4;
background: rgba(255, 255, 255, 0.025);
font: 650 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
white-space: nowrap;
}
.meta-pill::before {
content: "";
width: 6px;
height: 6px;
background: var(--mint);
box-shadow: 0 0 8px var(--mint);
}
.workspace {
flex: 1;
min-height: 0;
display: grid;
grid-template-columns: minmax(0, 1fr) 440px;
}
.stage {
min-width: 0;
min-height: 0;
position: relative;
overflow: hidden;
background:
radial-gradient(circle at 46% 43%, rgba(37, 77, 82, 0.2), transparent 43%),
#071116;
}
#sceneCanvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#sceneCanvas:active {
cursor: grabbing;
}
.stage-top {
position: absolute;
top: 20px;
left: 20px;
right: 20px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 20px;
pointer-events: none;
z-index: 2;
}
.scene-copy {
max-width: 440px;
padding: 15px 16px;
border: 1px solid rgba(89, 129, 137, 0.28);
border-radius: 10px;
background: rgba(6, 17, 22, 0.76);
backdrop-filter: blur(10px);
box-shadow: 0 16px 45px rgba(0, 0, 0, 0.2);
}
.scene-copy .eyebrow {
color: var(--cyan);
}
.scene-copy h2 {
margin: 7px 0 5px;
font-size: 18px;
letter-spacing: -0.02em;
}
.scene-copy p {
margin: 0;
color: #9eb3b9;
font-size: 12px;
line-height: 1.5;
}
.glass-button {
pointer-events: auto;
border: 1px solid rgba(119, 160, 170, 0.32);
border-radius: 8px;
padding: 9px 11px;
color: #cfe0e3;
background: rgba(8, 20, 25, 0.78);
backdrop-filter: blur(8px);
cursor: pointer;
font: 700 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.glass-button:hover {
border-color: var(--mint);
color: white;
}
.stage-bottom {
position: absolute;
left: 20px;
right: 20px;
bottom: 18px;
display: flex;
justify-content: space-between;
align-items: flex-end;
gap: 16px;
pointer-events: none;
z-index: 2;
}
.legend {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
max-width: 680px;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 8px;
border: 1px solid rgba(79, 114, 123, 0.28);
border-radius: 6px;
color: #9eb2b8;
background: rgba(7, 18, 23, 0.76);
backdrop-filter: blur(7px);
font: 600 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.swatch {
width: 8px;
height: 8px;
display: inline-block;
flex: 0 0 auto;
}
.swatch.body {
background: var(--lime);
}
.swatch.metro {
background: var(--cyan);
}
.swatch.outlying {
background: #ff7b6e;
}
.swatch.pip {
width: 5px;
height: 5px;
border-radius: 50%;
background: white;
}
.camera-hint {
padding: 7px 9px;
color: #779097;
background: rgba(7, 18, 23, 0.65);
border-radius: 6px;
font: 600 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
white-space: nowrap;
}
.panel {
min-height: 0;
overflow-y: auto;
padding: 19px;
border-left: 1px solid var(--line);
background:
linear-gradient(180deg, rgba(115, 239, 173, 0.035), transparent 180px),
var(--panel);
scrollbar-width: thin;
scrollbar-color: #29444d transparent;
}
.section {
margin-bottom: 18px;
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 9px;
}
.section-heading h3 {
margin: 0;
font-size: 12px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.section-heading span,
.section-label {
color: var(--muted);
font: 600 10px/1.3 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.mechanism-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
}
.mechanism {
--accent: var(--cyan);
min-height: 86px;
position: relative;
display: flex;
align-items: flex-start;
gap: 9px;
padding: 11px;
text-align: left;
border: 1px solid #263d46;
border-radius: 9px;
background: #0e1c22;
cursor: pointer;
transition:
border-color 160ms ease,
transform 160ms ease,
background 160ms ease;
}
.mechanism:hover {
border-color: color-mix(in srgb, var(--accent) 70%, #263d46);
transform: translateY(-1px);
}
.mechanism[aria-pressed="true"] {
border-color: var(--accent);
background:
linear-gradient(135deg, color-mix(in srgb, var(--accent) 11%, transparent), transparent),
#102129;
box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--accent) 20%, transparent);
}
.mech-dot {
width: 9px;
height: 9px;
margin-top: 3px;
flex: 0 0 auto;
border-radius: 2px;
background: var(--accent);
box-shadow: 0 0 10px color-mix(in srgb, var(--accent) 50%, transparent);
}
.mech-copy {
min-width: 0;
display: flex;
flex-direction: column;
gap: 5px;
}
.mech-copy strong {
font-size: 12px;
}
.mech-copy small {
color: #829aa1;
font-size: 10px;
line-height: 1.35;
}
.mech-arrow {
margin-left: auto;
color: #526d75;
font-size: 17px;
}
.mechanism[aria-pressed="true"] .mech-arrow {
color: var(--accent);
}
.sample-row {
display: flex;
align-items: center;
gap: 10px;
margin-top: 13px;
}
.sample-sizes {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
flex: 1;
}
.sample-size {
padding: 9px 6px;
border: 1px solid #263d46;
border-radius: 7px;
background: #0e1c22;
color: #9fb4ba;
cursor: pointer;
font: 700 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.sample-size span {
display: block;
margin-top: 4px;
color: #5f7981;
font-size: 8px;
letter-spacing: 0.08em;
}
.sample-size[aria-pressed="true"] {
border-color: var(--mint);
color: var(--lime);
background: rgba(115, 239, 173, 0.09);
}
.action-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 10px;
}
.action-button {
padding: 11px 10px;
border: 1px solid #2b4650;
border-radius: 8px;
background: #12232a;
cursor: pointer;
font-size: 11px;
font-weight: 750;
}
.action-button.primary {
color: #102119;
border-color: var(--mint);
background: var(--mint);
}
.action-button.primary:hover {
background: #91f6c0;
}
.action-button.secondary:hover {
border-color: var(--cyan);
}
.action-button.playing {
color: var(--cyan);
border-color: var(--cyan);
}
.metrics {
display: grid;
grid-template-columns: 1.2fr 1fr 1fr;
gap: 7px;
}
.metric {
min-width: 0;
padding: 11px 10px;
border: 1px solid #213741;
border-radius: 8px;
background: #0d1a20;
}
.metric-label {
display: block;
margin-bottom: 7px;
color: #6f8991;
font: 700 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.metric-value {
display: block;
overflow: hidden;
color: #edf8f9;
font: 750 21px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
text-overflow: ellipsis;
}
.metric-value.primary {
color: var(--lime);
}
.metric-value.good {
color: var(--mint);
}
.metric-value.bad {
color: #ff789a;
}
.metric-sub {
display: block;
margin-top: 5px;
color: #58727a;
font-size: 9px;
}
.chart-card {
padding: 12px 12px 9px;
border: 1px solid #213741;
border-radius: 10px;
background:
radial-gradient(circle at 50% 30%, rgba(48, 91, 99, 0.12), transparent 60%),
#0a171c;
}
.chart-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 8px;
margin-bottom: 4px;
}
.chart-header h3 {
margin: 0 0 4px;
font-size: 12px;
}
.chart-header p {
margin: 0;
color: #6e8790;
font: 600 9px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.chart-badge {
padding: 5px 7px;
border: 1px solid #29444d;
border-radius: 5px;
color: var(--mint);
font: 700 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
white-space: nowrap;
}
#chart {
display: block;
width: 100%;
height: 240px;
margin-top: 3px;
}
.chart-legend {
display: flex;
flex-wrap: wrap;
gap: 9px 13px;
padding-top: 8px;
border-top: 1px solid #1a2e36;
}
.chart-legend-item {
display: inline-flex;
align-items: center;
gap: 5px;
color: #829ba2;
font: 600 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.line-swatch {
width: 17px;
height: 0;
border-top: 2px solid currentColor;
}
.line-swatch.dashed {
border-top-style: dashed;
}
.chart-note {
margin: 8px 0 0;
color: #617b83;
font-size: 9px;
line-height: 1.45;
}
.comparison {
width: 100%;
border-collapse: collapse;
overflow: hidden;
border: 1px solid #203740;
border-radius: 8px;
background: #0b181e;
font-size: 10px;
}
.comparison th {
padding: 8px 7px;
color: #637d85;
text-align: right;
border-bottom: 1px solid #203740;
font: 700 8px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.comparison th:first-child,
.comparison td:first-child {
text-align: left;
}
.comparison td {
padding: 8px 7px;
text-align: right;
border-bottom: 1px solid #182c34;
color: #a9bec3;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
.comparison tr:last-child td {
border-bottom: none;
}
.comparison tr.active {
background: rgba(115, 239, 173, 0.075);
}
.comparison tr.active td:first-child {
box-shadow: inset 2px 0 var(--mint);
}
.table-name {
display: inline-flex;
align-items: center;
gap: 6px;
}
.table-dot {
width: 6px;
height: 6px;
border-radius: 1px;
}
.bias-positive {
color: #ff8ba7 !important;
}
.bias-negative {
color: #68d6ff !important;
}
.bias-small {
color: var(--mint) !important;
}
.insight {
position: relative;
padding: 13px 13px 13px 16px;
border: 1px solid #29444d;
border-radius: 9px;
background: linear-gradient(135deg, rgba(88, 216, 255, 0.06), transparent 60%);
}
.insight::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 3px;
border-radius: 9px 0 0 9px;
background: var(--cyan);
}
.insight h4 {
margin: 0 0 6px;
color: #eef9fa;
font-size: 12px;
}
.insight p {
margin: 0;
color: #8fa7ad;
font-size: 10px;
line-height: 1.55;
}
.insight-readout {
margin-top: 8px;
color: #617c84;
font: 600 9px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;
}
@media (max-width: 950px) {
body {
overflow: auto;
}
.app {
height: auto;
min-height: 100dvh;
overflow: visible;
}
.topbar {
align-items: flex-start;
}
.top-meta {
max-width: 220px;
}
.workspace {
display: block;
}
.stage {
height: 62dvh;
min-height: 520px;
}
.panel {
overflow: visible;
border-left: none;
border-top: 1px solid var(--line);
}
}
@media (max-width: 560px) {
.topbar {
padding: 14px;
}
.top-meta {
display: none;
}
.stage {
min-height: 480px;
}
.stage-top {
top: 12px;
left: 12px;
right: 12px;
}
.scene-copy {
max-width: calc(100% - 80px);
padding: 12px;
}
.scene-copy p {
display: none;
}
.stage-bottom {
left: 12px;
right: 12px;
bottom: 12px;
}
.camera-hint {
display: none;
}
.legend {
gap: 5px;
}
.legend-item {
font-size: 8px;
}
.panel {
padding: 14px;
}
.mechanism-grid {
grid-template-columns: 1fr;
}
.mechanism {
min-height: 70px;
}
}
</style>
</head>
<body>
<div class="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<i></i><i></i><i></i>
</div>
<div>
<div class="eyebrow">Voxel sampling lab</div>
<h1>One population. Four ways in.</h1>
</div>
</div>
<div class="top-meta">
<div class="meta-pill">SYNTHETIC POPULATION · N = 240</div>
<div class="small-pill">TARGET: MEAN PRIORITY SCORE</div>
</div>
</header>
<main class="workspace">
<section class="stage" id="stage" aria-label="Interactive three-dimensional population sampling scene">
<div class="stage-top">
<div class="scene-copy">
<div class="eyebrow" id="stageBadge">MECHANISM / UNIFORM RANDOM</div>
<h2 id="mechanismTitle">Uniform random</h2>
<p id="mechanismDescription"></p>
</div>
<button class="glass-button" id="cameraReset" type="button">
RESET VIEW
</button>
</div>
<div class="stage-bottom">
<div class="legend" aria-label="Scene legend">
<span class="legend-item"><i class="swatch body"></i>Selected body</span>
<span class="legend-item"><i class="swatch metro"></i>Metro head</span>
<span class="legend-item"><i class="swatch outlying"></i>Outlying head</span>
<span class="legend-item"><i class="swatch pip"></i>Pip = response propensity</span>
</div>
<div class="camera-hint">DRAG TO ORBIT · SCROLL TO ZOOM</div>
</div>
</section>
<aside class="panel">
<section class="section">
<div class="section-heading">
<h3>Selection mechanism</h3>
<span>Same people every time</span>
</div>
<div class="mechanism-grid" id="mechanismGrid"></div>
<div class="sample-row">
<span class="section-label">SAMPLE<br />SIZE</span>
<div class="sample-sizes" id="sampleSizes">
<button class="sample-size" data-size="24" type="button" aria-pressed="false">
24 <span>SMALL</span>
</button>
<button class="sample-size" data-size="60" type="button" aria-pressed="true">
60 <span>MEDIUM</span>
</button>
<button class="sample-size" data-size="120" type="button" aria-pressed="false">
120 <span>LARGE</span>
</button>
</div>
</div>
<div class="action-row">
<button class="action-button primary" id="drawButton" type="button">
NEW SAMPLE
</button>
<button class="action-button secondary" id="playButton" type="button">
PLAY 12 DRAWS
</button>
</div>
</section>
<section class="section">
<div class="section-heading">
<h3>Current draw</h3>
<span id="currentCount">n = 60</span>
</div>
<div class="metrics">
<div class="metric">
<span class="metric-label">Estimate</span>
<span class="metric-value primary" id="currentEstimate">50.0</span>
<span class="metric-sub">sample mean</span>
</div>
<div class="metric">
<span class="metric-label">Population</span>
<span class="metric-value good" id="truthValue">50.0</span>
<span class="metric-sub">true mean</span>
</div>
<div class="metric">
<span class="metric-label">Draw offset</span>
<span class="metric-value" id="currentBias">0.0</span>
<span class="metric-sub">estimate − truth</span>
</div>
</div>
</section>
<section class="section">
<div class="section-heading">
<h3>Repeated estimates</h3>
<span>600 simulated draws</span>
</div>
<div class="chart-card">
<div class="chart-header">
<div>
<h3>Estimate distributions</h3>
<p>All four rules, evaluated on the same population</p>
</div>
<div class="chart-badge" id="chartBadge">n = 60</div>
</div>
<canvas id="chart" aria-label="Chart comparing repeated estimate distributions"></canvas>
<div class="chart-legend" id="chartLegend"></div>
<p class="chart-note" id="chartNote"></p>
</div>
</section>
<section class="section">
<div class="section-heading">
<h3>Mechanism comparison</h3>
<span>95% simulation band</span>
</div>
<table class="comparison">
<thead>
<tr>
<th>Rule</th>
<th>Mean</th>
<th>Bias</th>
<th>95% band</th>
</tr>
</thead>
<tbody id="comparisonBody"></tbody>
</table>
</section>
<section class="section">
<div class="insight">
<h4 id="insightTitle">More data reduces noise.</h4>
<p id="insightText"></p>
<div class="insight-readout" id="insightReadout"></div>
</div>
</section>
</aside>
</main>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Utilities and population model
// -------------------------------------------------------------------------
const $ = (selector) => document.querySelector(selector);
const clamp = (v, min, max) => Math.max(min, Math.min(max, v));
const mean = (values) => values.reduce((sum, value) => sum + value, 0) / values.length;
const fmt = (value) => Number(value).toFixed(1);
const signed = (value) => `${value >= 0 ? "+" : ""}${fmt(value)}`;
function mulberry32(seed) {
return function () {
let t = (seed += 0x6d2b79f5);
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function hashString(text) {
let hash = 2166136261;
for (let i = 0; i < text.length; i++) {
hash ^= text.charCodeAt(i);
hash = Math.imul(hash, 16777619);
}
return hash >>> 0;
}
function quantile(sorted, q) {
const position = (sorted.length - 1) * q;
const low = Math.floor(position);
const high = Math.ceil(position);
if (low === high) return sorted[low];
return sorted[low] + (sorted[high] - sorted[low]) * (position - low);
}
const MECHANISMS = {
random: {
short: "Random",
name: "Uniform random",
color: "#58d8ff",
ui: "Equal chance for every person",
description:
"Every person has the same inclusion chance. The estimate wanders around the population mean, and larger samples make it wander less."
},
volunteer: {
short: "Volunteer",
name: "Self-selected volunteers",
color: "#ffb45e",
ui: "Response propensity drives selection",
description:
"People with higher engagement are more likely to participate. Engagement tracks the score, so the sample over-represents high values."
},
convenience: {
short: "Convenience",
name: "Convenience sample",
color: "#ff609b",
ui: "Only the service-reachable zone",
description:
"The sampler can only reach the highlighted service zone. The peripheral group is missing, creating coverage error that more sampling cannot repair."
},
stratified: {
short: "Stratified",
name: "Stratified random",
color: "#75efad",
ui: "Balanced representation by zone",
description:
"Each zone receives equal representation, then people are sampled randomly inside each zone. Random error shrinks while the center stays at truth."
}
};
const POPULATION_ROWS = 12;
const POPULATION_COLS = 20;
const POPULATION_SIZE = POPULATION_ROWS * POPULATION_COLS;
const TRIAL_COUNT = 600;
const BASELINE_SIZE = 24;
function createPopulation() {
const random = mulberry32(918273);
const population = [];
for (let row = 0; row < POPULATION_ROWS; row++) {
for (let col = 0; col < POPULATION_COLS; col++) {
const zone = row < 8 ? "metro" : "outlying";
const target = zone === "metro" ? 55 : 40;
const bellNoise = (random() + random() + random() - 1.5) * 4.6;
population.push({
id: row * POPULATION_COLS + col,
row,
col,
zone,
score: target + bellNoise
});
}
}
// Center each zone exactly so the complete population mean is exactly 50.
for (const [zone, target] of [["metro", 55], ["outlying", 40]]) {
const members = population.filter((person) => person.zone === zone);
const zoneMean = mean(members.map((person) => person.score));
for (const person of members) {
person.score = target + (person.score - zoneMean);
person.responseWeight = clamp(0.02 + person.score * 0.013, 0.18, 0.92);
}
}
return population;
}
const population = createPopulation();
const populationTruth = mean(population.map((person) => person.score));
const metroMembers = population.filter((person) => person.zone === "metro");
const outlyingMembers = population.filter((person) => person.zone === "outlying");
const reachableMembers = population.filter((person) => person.row < 7);
const state = {
mechanism: "random",
sampleSize: 60,
selected: new Set(),
currentSample: [],
playing: false,
playTimer: null,
playCount: 0
};
const distributionCache = new Map();
function shuffled(list, random) {
const result = list.slice();
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}
function sampleMechanism(mechanism, sampleSize, random = Math.random) {
if (mechanism === "random") {
return shuffled(population, random).slice(0, sampleSize);
}
if (mechanism === "volunteer") {
// Exponential race: larger response weights are more likely to win.
const weighted = population.map((person) => ({
person,
key: Math.log(Math.max(random(), 1e-12)) / person.responseWeight
}));
weighted.sort((a, b) => b.key - a.key);
return weighted.slice(0, sampleSize).map((entry) => entry.person);
}
if (mechanism === "convenience") {
return shuffled(reachableMembers, random).slice(0, sampleSize);
}
if (mechanism === "stratified") {
const half = sampleSize / 2;
const metro = shuffled(metroMembers, random).slice(0, half);
const outlying = shuffled(outlyingMembers, random).slice(0, half);
return [...metro, ...outlying];
}
throw new Error(`Unknown mechanism: ${mechanism}`);
}
function simulateDistribution(mechanism, sampleSize) {
const cacheKey = `${mechanism}:${sampleSize}`;
if (distributionCache.has(cacheKey)) {
return distributionCache.get(cacheKey);
}
const random = mulberry32(hashString(`voxel-sampling-v1|${cacheKey}`));
const estimates = [];
for (let trial = 0; trial < TRIAL_COUNT; trial++) {
const sample = sampleMechanism(mechanism, sampleSize, random);
estimates.push(mean(sample.map((person) => person.score)));
}
const sorted = estimates.slice().sort((a, b) => a - b);
const distribution = {
estimates,
sorted,
mean: mean(estimates),
standardDeviation: Math.sqrt(
mean(estimates.map((value) => (value - mean(estimates)) ** 2))
),
low: quantile(sorted, 0.025),
high: quantile(sorted, 0.975)
};
distribution.bias = distribution.mean - populationTruth;
distribution.bandWidth = distribution.high - distribution.low;
distributionCache.set(cacheKey, distribution);
return distribution;
}
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const stage = $("#stage");
let renderer;
try {
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
} catch (error) {
stage.innerHTML = `
<div style="padding:40px;color:#d9e8ea;font-family:system-ui">
<h2>WebGL is unavailable</h2>
<p>This scene needs a browser with hardware-accelerated WebGL enabled.</p>
</div>`;
throw error;
}
renderer.domElement.id = "sceneCanvas";
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
stage.prepend(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071116);
scene.fog = new THREE.FogExp2(0x071116, 0.028);
const camera = new THREE.PerspectiveCamera(39, 1, 0.1, 100);
const cameraTarget = new THREE.Vector3(-0.55, 0.15, 0.1);
const cameraState = {
yaw: 0.58,
pitch: 0.63,
distance: 18.2,
target: cameraTarget
};
const hemisphere = new THREE.HemisphereLight(0xc9f6ff, 0x17252b, 2.1);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff4d9, 3.2);
keyLight.position.set(-5, 12, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -13;
keyLight.shadow.camera.right = 13;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.0008;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x58d8ff, 1.35);
rimLight.position.set(8, 6, -9);
scene.add(rimLight);
const pinkLight = new THREE.PointLight(0xff609b, 10, 13, 2);
pinkLight.position.set(6, 3, 3);
scene.add(pinkLight);
const dummy = new THREE.Object3D();
const color = new THREE.Color();
const COLORS = {
selectedBody: new THREE.Color(0xd9ff72),
selectedTile: new THREE.Color(0x4fe0aa),
metroBody: new THREE.Color(0x2b5163),
outlyingBody: new THREE.Color(0x633949),
metroHead: new THREE.Color(0x58d8ff),
outlyingHead: new THREE.Color(0xff7b6e),
dimTile: new THREE.Color(0x10262f),
pip: new THREE.Color(0xf4f0d8)
};
function makeTextSprite(text, options = {}) {
const {
color = "#e7f3f4",
background = "rgba(5, 17, 22, 0.80)",
border = "#29444d",
scale = [2.5, 0.47]
} = options;
const canvas = document.createElement("canvas");
canvas.width = 640;
canvas.height = 112;
const context = canvas.getContext("2d");
const material = new THREE.SpriteMaterial({
transparent: true,
depthTest: false,
depthWrite: false,
fog: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(scale[0], scale[1], 1);
sprite.renderOrder = 20;
function setText(value) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = background;
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = border;
context.lineWidth = 4;
context.strokeRect(2, 2, canvas.width - 4, canvas.height - 4);
context.font = "700 31px ui-monospace, SFMono-Regular, Menlo, monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = color;
context.fillText(String(value).toUpperCase(), canvas.width / 2, canvas.height / 2 + 1);
if (material.map) material.map.dispose();
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
material.map = texture;
material.needsUpdate = true;
}
setText(text);
return { sprite, setText };
}
function makeRectangleLine(x, z, width, depth, lineColor, y = 0.02) {
const points = [
new THREE.Vector3(x - width / 2, y, z - depth / 2),
new THREE.Vector3(x + width / 2, y, z - depth / 2),
new THREE.Vector3(x + width / 2, y, z + depth / 2),
new THREE.Vector3(x - width / 2, y, z + depth / 2),
new THREE.Vector3(x - width / 2, y, z - depth / 2)
];
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({
color: lineColor,
transparent: true,
opacity: 0.75
});
return new THREE.Line(geometry, material);
}
function buildEnvironment() {
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(38, 30),
new THREE.MeshStandardMaterial({
color: 0x081419,
roughness: 1,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.31;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(30, 30, 0x25404a, 0x142a32);
grid.position.y = -0.295;
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
const populationX = -2.25;
const platform = new THREE.Mesh(
new THREE.BoxGeometry(10.2, 0.18, 6.08),
new THREE.MeshStandardMaterial({
color: 0x0d2028,
roughness: 0.88,
metalness: 0.05
})
);
platform.position.set(populationX, -0.105, 0);
platform.receiveShadow = true;
scene.add(platform);
const serviceZone = new THREE.Mesh(
new THREE.BoxGeometry(9.96, 0.025, 3.31),
new THREE.MeshStandardMaterial({
color: 0x123d43,
roughness: 0.8,
metalness: 0.05
})
);
serviceZone.position.set(populationX, -0.002, -1.43);
serviceZone.receiveShadow = true;
scene.add(serviceZone);
scene.add(
makeRectangleLine(populationX, 0.94, 9.96, 3.31, 0x4ce2c0, 0.018),
makeRectangleLine(populationX, 1.41, 9.96, 4.68, 0xff7b6e, 0.018)
);
const metroLabel = makeTextSprite("METRO · 160", {
color: "#78ddff",
border: "#24556a",
scale: [2.25, 0.39]
});
metroLabel.sprite.position.set(populationX, 0.36, -3.38);
scene.add(metroLabel.sprite);
const outlyingLabel = makeTextSprite("OUTLYING · 80", {
color: "#ff9b8f",
border: "#693944",
scale: [2.45, 0.39]
});
outlyingLabel.sprite.position.set(populationX, 0.36, 3.38);
scene.add(outlyingLabel.sprite);
const serviceLabel = makeTextSprite("SERVICE ZONE", {
color: "#70efd2",
border: "#245e59",
scale: [1.95, 0.35]
});
serviceLabel.sprite.position.set(-7.2, 0.36, -1.43);
scene.add(serviceLabel.sprite);
const samplePlatform = new THREE.Mesh(
new THREE.BoxGeometry(3.75, 0.18, 3.2),
new THREE.MeshStandardMaterial({
color: 0x10252d,
roughness: 0.8,
metalness: 0.08
})
);
samplePlatform.position.set(4.35, -0.105, 1.5);
samplePlatform.receiveShadow = true;
scene.add(samplePlatform);
const sampleLabel = makeTextSprite("CURRENT SAMPLE", {
color: "#d9ff72",
border: "#4d6338",
scale: [2.25, 0.39]
});
sampleLabel.sprite.position.set(4.35, 0.43, 3.4);
scene.add(sampleLabel.sprite);
const northMarker = new THREE.Mesh(
new THREE.BoxGeometry(0.16, 0.03, 0.45),
new THREE.MeshBasicMaterial({ color: 0x58d8ff })
);
northMarker.position.set(-7.15, 0.03, -2.6);
scene.add(northMarker);
}
const personPositions = new Map();
for (const person of population) {
personPositions.set(person.id, {
x: -2.25 + (person.col - (POPULATION_COLS - 1) / 2) * 0.47,
z: (person.row - (POPULATION_ROWS - 1) / 2) * 0.47
});
}
let bodyMesh;
let headMesh;
let tileMesh;
let pipMesh;
let tokenMesh;
const lift = new Float32Array(POPULATION_SIZE);
let tokenData = [];
let sampleAnimationStart = performance.now();
function createInstancedMesh(geometry, material, count) {
const mesh = new THREE.InstancedMesh(geometry, material, count);
mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.frustumCulled = false;
scene.add(mesh);
return mesh;
}
function buildPopulationInstances() {
const standard = {
roughness: 0.72,
metalness: 0.06
};
bodyMesh = createInstancedMesh(
new THREE.BoxGeometry(0.2, 0.31, 0.18),
new THREE.MeshStandardMaterial({ color: 0xffffff, ...standard }),
POPULATION_SIZE
);
headMesh = createInstancedMesh(
new THREE.BoxGeometry(0.17, 0.17, 0.17),
new THREE.MeshStandardMaterial({ color: 0xffffff, ...standard }),
POPULATION_SIZE
);
tileMesh = createInstancedMesh(
new THREE.BoxGeometry(0.36, 0.04, 0.34),
new THREE.MeshStandardMaterial({ color: 0xffffff, ...standard }),
POPULATION_SIZE
);
pipMesh = createInstancedMesh(
new THREE.BoxGeometry(0.052, 0.052, 0.052),
new THREE.MeshBasicMaterial({ color: 0xffffff }),
POPULATION_SIZE
);
for (const person of population) {
const position = personPositions.get(person.id);
dummy.position.set(position.x, 0.025, position.z);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
tileMesh.setMatrixAt(person.id, dummy.matrix);
tileMesh.setColorAt(person.id, COLORS.dimTile);
headMesh.setColorAt(
person.id,
person.zone === "metro" ? COLORS.metroHead : COLORS.outlyingHead
);
}
tokenMesh = createInstancedMesh(
new THREE.BoxGeometry(0.18, 0.18, 0.18),
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.62,
metalness: 0.08
}),
120
);
tokenMesh.count = 0;
}
let gaugeTargetY = 2;
let gaugeY = 2;
let estimateMarker;
let estimateLabel;
let truthLabel;
function buildGauge() {
const track = new THREE.Mesh(
new THREE.BoxGeometry(0.11, 3.35, 0.11),
new THREE.MeshStandardMaterial({
color: 0x203b45,
roughness: 0.7,
metalness: 0.2
})
);
track.position.set(4.42, 1.82, -2.3);
scene.add(track);
for (let tick = 0; tick <= 4; tick++) {
const score = 30 + tick * 10;
const y = 0.35 + ((score - 30) / 40) * 3.1;
const tickMesh = new THREE.Mesh(
new THREE.BoxGeometry(0.38, 0.035, 0.08),
new THREE.MeshBasicMaterial({ color: 0x52717a })
);
tickMesh.position.set(4.42, y, -2.3);
scene.add(tickMesh);
}
const truthY = 0.35 + ((populationTruth - 30) / 40) * 3.1;
const truthMarker = new THREE.Mesh(
new THREE.BoxGeometry(0.93, 0.07, 0.24),
new THREE.MeshBasicMaterial({ color: 0xe8f4f5 })
);
truthMarker.position.set(4.42, truthY, -2.43);
scene.add(truthMarker);
estimateMarker = new THREE.Mesh(
new THREE.BoxGeometry(0.76, 0.14, 0.31),
new THREE.MeshStandardMaterial({
color: 0xd9ff72,
emissive: 0x526d16,
emissiveIntensity: 0.6,
roughness: 0.55
})
);
estimateMarker.position.set(4.42, gaugeY, -2.15);
scene.add(estimateMarker);
truthLabel = makeTextSprite(`POP ${fmt(populationTruth)}`, {
color: "#e8f4f5",
border: "#455d65",
scale: [1.42, 0.28]
});
truthLabel.sprite.position.set(5.42, truthY, -2.42);
scene.add(truthLabel.sprite);
estimateLabel = makeTextSprite("DRAW 50.0", {
color: "#d9ff72",
border: "#53653a",
scale: [1.42, 0.28]
});
estimateLabel.sprite.position.set(5.42, gaugeY, -2.1);
scene.add(estimateLabel.sprite);
const title = makeTextSprite("DRAW vs TRUTH", {
color: "#9db6bd",
border: "#29444d",
scale: [1.75, 0.32]
});
title.sprite.position.set(4.42, 3.85, -2.3);
scene.add(title.sprite);
}
function paintPopulation() {
for (const person of population) {
const selected = state.selected.has(person.id);
color.copy(
selected
? COLORS.selectedBody
: person.zone === "metro"
? COLORS.metroBody
: COLORS.outlyingBody
);
bodyMesh.setColorAt(person.id, color);
color.copy(selected ? COLORS.selectedTile : COLORS.dimTile);
tileMesh.setColorAt(person.id, color);
color.copy(selected ? COLORS.pip : new THREE.Color(0x71858a));
pipMesh.setColorAt(person.id, color);
}
bodyMesh.instanceColor.needsUpdate = true;
tileMesh.instanceColor.needsUpdate = true;
pipMesh.instanceColor.needsUpdate = true;
}
function updatePopulationSelection() {
state.selected = new Set(state.currentSample.map((person) => person.id));
paintPopulation();
tokenData = state.currentSample.slice();
tokenMesh.count = tokenData.length;
tokenData.forEach((person, index) => {
tokenMesh.setColorAt(
index,
person.zone === "metro" ? COLORS.metroHead : COLORS.outlyingHead
);
});
if (tokenMesh.instanceColor) tokenMesh.instanceColor.needsUpdate = true;
sampleAnimationStart = performance.now();
}
function updateGauge(estimate) {
gaugeTargetY = 0.35 + ((estimate - 30) / 40) * 3.1;
estimateLabel.setText(`DRAW ${fmt(estimate)}`);
}
// -------------------------------------------------------------------------
// UI and simulation chart
// -------------------------------------------------------------------------
function buildMechanismButtons() {
const grid = $("#mechanismGrid");
for (const [key, mechanism] of Object.entries(MECHANISMS)) {
const button = document.createElement("button");
button.type = "button";
button.className = "mechanism";
button.dataset.mechanism = key;
button.style.setProperty("--accent", mechanism.color);
button.setAttribute("aria-pressed", String(key === state.mechanism));
button.innerHTML = `
<span class="mech-dot"></span>
<span class="mech-copy">
<strong>${mechanism.short}</strong>
<small>${mechanism.ui}</small>
</span>
<span class="mech-arrow">›</span>
`;
button.addEventListener("click", () => {
state.mechanism = key;
updateMechanismUI();
drawCurrentSample();
renderChart();
renderComparison();
renderInsight();
});
grid.appendChild(button);
}
}
function updateMechanismUI() {
const mechanism = MECHANISMS[state.mechanism];
document.querySelectorAll(".mechanism").forEach((button) => {
button.setAttribute(
"aria-pressed",
String(button.dataset.mechanism === state.mechanism)
);
});
$("#stageBadge").textContent = `MECHANISM / ${mechanism.name.toUpperCase()}`;
$("#mechanismTitle").textContent = mechanism.name;
$("#mechanismDescription").textContent = mechanism.description;
}
function updateSampleSizeUI() {
document.querySelectorAll(".sample-size").forEach((button) => {
button.setAttribute(
"aria-pressed",
String(Number(button.dataset.size) === state.sampleSize)
);
});
$("#currentCount").textContent = `n = ${state.sampleSize}`;
$("#chartBadge").textContent = `n = ${state.sampleSize}`;
}
function drawCurrentSample() {
state.currentSample = sampleMechanism(state.mechanism, state.sampleSize);
const estimate = mean(state.currentSample.map((person) => person.score));
const bias = estimate - populationTruth;
$("#currentEstimate").textContent = fmt(estimate);
$("#currentBias").textContent = signed(bias);
$("#currentBias").className = `metric-value ${Math.abs(bias) < 0.8 ? "good" : "bad"}`;
$("#truthValue").textContent = fmt(populationTruth);
updatePopulationSelection();
updateGauge(estimate);
}
function getAllDistributions(sampleSize) {
const result = {};
for (const key of Object.keys(MECHANISMS)) {
result[key] = simulateDistribution(key, sampleSize);
}
return result;
}
function histogram(estimates, bins, xMin, xMax) {
const counts = new Array(bins).fill(0);
for (const value of estimates) {
const index = Math.floor(((value - xMin) / (xMax - xMin)) * bins);
counts[clamp(index, 0, bins - 1)]++;
}
const smoothed = new Array(bins).fill(0);
const bandwidth = 1.15;
for (let i = 0; i < bins; i++) {
for (let j = 0; j < bins; j++) {
smoothed[i] += counts[j] * Math.exp(-0.5 * ((i - j) / bandwidth) ** 2);
}
}
return smoothed;
}
function renderChart() {
const canvas = $("#chart");
const bounds = canvas.getBoundingClientRect();
if (bounds.width === 0) return;
const dpr = Math.min(window.devicePixelRatio, 2);
const width = bounds.width;
const height = bounds.height;
if (canvas.width !== Math.round(width * dpr) ||
canvas.height !== Math.round(height * dpr)) {
canvas.width = Math.round(width * dpr);
canvas.height = Math.round(height * dpr);
}
const context = canvas.getContext("2d");
context.setTransform(dpr, 0, 0, dpr, 0, 0);
context.clearRect(0, 0, width, height);
const distributions = getAllDistributions(state.sampleSize);
const baseline =
state.sampleSize > BASELINE_SIZE
? simulateDistribution(state.mechanism, BASELINE_SIZE)
: null;
const allValues = Object.values(distributions).flatMap((d) => d.estimates);
if (baseline) allValues.push(...baseline.estimates);
let xMin = Math.max(20, Math.floor((Math.min(...allValues) - 3) / 5) * 5);
let xMax = Math.min(80, Math.ceil((Math.max(...allValues) + 3) / 5) * 5);
if (xMax - xMin < 20) {
const middle = (xMin + xMax) / 2;
xMin = middle - 10;
xMax = middle + 10;
}
const margin = { left: 26, right: 10, top: 17, bottom: 33 };
const plotWidth = width - margin.left - margin.right;
const plotHeight = height - margin.top - margin.bottom;
const bins = 34;
const curves = {};
for (const [key, distribution] of Object.entries(distributions)) {
curves[key] = histogram(distribution.estimates, bins, xMin, xMax);
}
if (baseline) {
curves.baseline = histogram(baseline.estimates, bins, xMin, xMax);
}
let globalMax = 0;
for (const curve of Object.values(curves)) {
globalMax = Math.max(globalMax, ...curve);
}
globalMax = Math.max(globalMax, 1);
const xForIndex = (index) =>
margin.left + (index / (bins - 1)) * plotWidth;
const yForValue = (value) =>
margin.top + plotHeight - (value / globalMax) * (plotHeight - 20);
// Grid and axes.
context.lineWidth = 1;
context.strokeStyle = "rgba(92, 129, 139, 0.12)";
for (let i = 0; i <= 4; i++) {
const y = margin.top + (plotHeight * i) / 4;
context.beginPath();
context.moveTo(margin.left, y);
context.lineTo(width - margin.right, y);
context.stroke();
}
context.font = "9px ui-monospace, SFMono-Regular, Menlo, monospace";
context.fillStyle = "#617c84";
context.textAlign = "center";
const tickStep = xMax - xMin <= 30 ? 5 : 10;
for (let tick = xMin; tick <= xMax; tick += tickStep) {
const x = margin.left + ((tick - xMin) / (xMax - xMin)) * plotWidth;
context.strokeStyle = "rgba(92, 129, 139, 0.13)";
context.beginPath();
context.moveTo(x, margin.top);
context.lineTo(x, margin.top + plotHeight);
context.stroke();
context.fillText(String(tick), x, height - 17);
}
context.textAlign = "center";
context.fillStyle = "#58727a";
context.fillText("MEAN PRIORITY SCORE", margin.left + plotWidth / 2, height - 3);
function drawCurve(curve, curveColor, alpha, dashed, fill) {
if (!curve.length) return;
context.save();
context.beginPath();
curve.forEach((value, index) => {
const x = xForIndex(index);
const y = yForValue(value);
if (index === 0) context.moveTo(x, y);
else context.lineTo(x, y);
});
if (fill) {
const gradient = context.createLinearGradient(0, margin.top, 0, margin.top + plotHeight);
gradient.addColorStop(0, `${curveColor}45`);
gradient.addColorStop(1, `${curveColor}05`);
context.lineTo(xForIndex(curve.length - 1), margin.top + plotHeight);
context.lineTo(xForIndex(0), margin.top + plotHeight);
context.closePath();
context.fillStyle = gradient;
context.fill();
}
context.beginPath();
curve.forEach((value, index) => {
const x = xForIndex(index);
const y = yForValue(value);
if (index === 0) context.moveTo(x, y);
else context.lineTo(x, y);
});
context.strokeStyle = curveColor;
context.globalAlpha = alpha;
context.lineWidth = fill ? 2.5 : 1.45;
context.setLineDash(dashed ? [5, 5] : []);
context.stroke();
context.restore();
}
if (baseline) {
drawCurve(
curves.baseline,
MECHANISMS[state.mechanism].color,
0.46,
true,
false
);
}
for (const [key, mechanism] of Object.entries(MECHANISMS)) {
if (key === state.mechanism) continue;
drawCurve(curves[key], mechanism.color, 0.67, key === "random", false);
}
drawCurve(
curves[state.mechanism],
MECHANISMS[state.mechanism].color,
1,
false,
true
);
// Population truth line.
const truthX =
margin.left +
((populationTruth - xMin) / (xMax - xMin)) * plotWidth;
context.save();
context.strokeStyle = "rgba(232, 244, 245, 0.85)";
context.lineWidth = 1.2;
context.setLineDash([3, 4]);
context.beginPath();
context.moveTo(truthX, margin.top);
context.lineTo(truthX, margin.top + plotHeight);
context.stroke();
context.setLineDash([]);
context.font = "700 9px ui-monospace, SFMono-Regular, Menlo, monospace";
context.fillStyle = "#dcebed";
context.textAlign = truthX > width * 0.75 ? "right" : "left";
context.fillText(
`TRUTH ${fmt(populationTruth)}`,
truthX + (truthX > width * 0.75 ? -5 : 5),
margin.top + 9
);
context.restore();
const legend = $("#chartLegend");
legend.innerHTML = Object.entries(MECHANISMS)
.map(
([key, mechanism]) => `
<span class="chart-legend-item" style="color:${mechanism.color}">
<i class="line-swatch ${key === "random" ? "dashed" : ""}"></i>
<span style="color:#829ba2">${mechanism.short}</span>
</span>
`
)
.join("");
if (baseline) {
legend.insertAdjacentHTML(
"beforeend",
`
<span class="chart-legend-item" style="color:${MECHANISMS[state.mechanism].color}">
<i class="line-swatch dashed"></i>
<span style="color:#829ba2">same rule, n=24</span>
</span>
`
);
}
$("#chartNote").textContent = baseline
? `Solid curves use n = ${state.sampleSize}. The dotted curve repeats the highlighted rule at n = ${BASELINE_SIZE}: more data narrows the band, but does not relocate a biased center.`
: `All curves use n = ${state.sampleSize}. A narrow cloud is not automatically an accurate cloud; compare each center with the truth line.`;
}
function renderComparison() {
const distributions = getAllDistributions(state.sampleSize);
const body = $("#comparisonBody");
body.innerHTML = Object.entries(MECHANISMS)
.map(([key, mechanism]) => {
const distribution = distributions[key];
const biasClass =
Math.abs(distribution.bias) < 0.75
? "bias-small"
: distribution.bias > 0
? "bias-positive"
: "bias-negative";
return `
<tr class="${key === state.mechanism ? "active" : ""}">
<td>
<span class="table-name">
<i class="table-dot" style="background:${mechanism.color}"></i>
${mechanism.short}
</span>
</td>
<td>${fmt(distribution.mean)}</td>
<td class="${biasClass}">${signed(distribution.bias)}</td>
<td>${fmt(distribution.low)}–${fmt(distribution.high)}</td>
</tr>
`;
})
.join("");
}
function renderInsight() {
const distribution = simulateDistribution(state.mechanism, state.sampleSize);
const bias = distribution.bias;
const direction = bias >= 0 ? "above" : "below";
const magnitude = Math.abs(bias);
let title;
let text;
if (state.mechanism === "random") {
title = "More data reduces noise, not selection rules.";
text =
`At n = ${state.sampleSize}, uniform random sampling is centered near ` +
`${fmt(distribution.mean)}. Its band is narrower than the n = 24 band, ` +
`but its center remains at the population truth because every person has the same chance to enter.`;
} else if (state.mechanism === "volunteer") {
title = "More volunteers can mean the same mistake.";
text =
`The volunteer distribution is centered ${fmt(magnitude)} points ${direction} truth. ` +
`Increasing n makes the orange band narrower, but repeatedly applying the same ` +
`participation rule cannot remove its systematic selection bias.`;
} else if (state.mechanism === "convenience") {
title = "A bigger sample can still miss the same people.";
text =
`Every convenience draw comes from the service-reachable zone, so its center ` +
`stays ${fmt(magnitude)} points ${direction} truth. At n = ${state.sampleSize}, ` +
`there is less random wobble—but the omitted peripheral group remains omitted.`;
} else {
title = "Design the coverage before adding sample size.";
text =
`Stratified random sampling represents both zones equally. Its center stays near ` +
`${fmt(distribution.mean)} while its band narrows with n, showing variance reduction ` +
`without the systematic error of the volunteer or convenience rules.`;
}
$("#insightTitle").textContent = title;
$("#insightText").textContent = text;
$("#insightReadout").textContent =
`95% BAND WIDTH ${fmt(distribution.bandWidth)} POINTS · ` +
`CENTER OFFSET ${signed(bias)} POINTS`;
}
function stopPlayback() {
state.playing = false;
if (state.playTimer) {
clearInterval(state.playTimer);
state.playTimer = null;
}
$("#playButton").textContent = "PLAY 12 DRAWS";
$("#playButton").classList.remove("playing");
}
function startPlayback() {
state.playing = true;
state.playCount = 0;
$("#playButton").textContent = "STOP DRAWS";
$("#playButton").classList.add("playing");
state.playTimer = setInterval(() => {
drawCurrentSample();
state.playCount++;
if (state.playCount >= 12) {
stopPlayback();
}
}, 260);
}
// -------------------------------------------------------------------------
// Direct camera controls — no Three.js addons
// -------------------------------------------------------------------------
function updateCamera() {
const { yaw, pitch, distance, target } = cameraState;
camera.position.set(
target.x + distance * Math.sin(yaw) * Math.cos(pitch),
target.y + distance * Math.sin(pitch),
target.z + distance * Math.cos(yaw) * Math.cos(pitch)
);
camera.lookAt(target);
}
function resetCamera() {
cameraState.yaw = 0.58;
cameraState.pitch = 0.63;
cameraState.distance = 18.2;
cameraState.target.set(-0.55, 0.15, 0.1);
updateCamera();
}
const pointers = new Map();
let pinchDistance = 0;
function pointerDistance() {
const values = [...pointers.values()];
if (values.length < 2) return 0;
return Math.hypot(values[0].x - values[1].x, values[0].y - values[1].y);
}
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
pinchDistance = pointerDistance();
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointers.has(event.pointerId)) return;
const previous = pointers.get(event.pointerId);
const dx = event.clientX - previous.x;
const dy = event.clientY - previous.y;
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 1) {
cameraState.yaw -= dx * 0.007;
cameraState.pitch = clamp(cameraState.pitch + dy * 0.005, 0.25, 1.25);
} else if (pointers.size === 2) {
const nextDistance = pointerDistance();
if (pinchDistance > 0 && nextDistance > 0) {
cameraState.distance = clamp(
cameraState.distance * (pinchDistance / nextDistance),
8,
30
);
}
pinchDistance = nextDistance;
}
updateCamera();
});
function releasePointer(event) {
pointers.delete(event.pointerId);
pinchDistance = pointerDistance();
}
renderer.domElement.addEventListener("pointerup", releasePointer);
renderer.domElement.addEventListener("pointercancel", releasePointer);
renderer.domElement.addEventListener("contextmenu", (event) => event.preventDefault());
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.distance = clamp(
cameraState.distance * Math.exp(event.deltaY * 0.001),
8,
30
);
updateCamera();
},
{ passive: false }
);
$("#cameraReset").addEventListener("click", resetCamera);
// -------------------------------------------------------------------------
// Events, resize, and animation
// -------------------------------------------------------------------------
$("#sampleSizes").addEventListener("click", (event) => {
const button = event.target.closest(".sample-size");
if (!button) return;
state.sampleSize = Number(button.dataset.size);
updateSampleSizeUI();
drawCurrentSample();
renderChart();
renderComparison();
renderInsight();
});
$("#drawButton").addEventListener("click", drawCurrentSample);
$("#playButton").addEventListener("click", () => {
if (state.playing) stopPlayback();
else startPlayback();
});
function resizeScene() {
const width = stage.clientWidth;
const height = stage.clientHeight;
if (!width || !height) return;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
const sceneResizeObserver = new ResizeObserver(resizeScene);
sceneResizeObserver.observe(stage);
const chartResizeObserver = new ResizeObserver(() => renderChart());
chartResizeObserver.observe($("#chart"));
buildEnvironment();
buildPopulationInstances();
buildGauge();
buildMechanismButtons();
updateMechanismUI();
updateSampleSizeUI();
drawCurrentSample();
renderChart();
renderComparison();
renderInsight();
resizeScene();
resetCamera();
function animate(now) {
requestAnimationFrame(animate);
// Lift selected people and animate their response pips.
for (const person of population) {
const position = personPositions.get(person.id);
const selected = state.selected.has(person.id);
const targetLift = selected ? 0.14 : 0;
lift[person.id] += (targetLift - lift[person.id]) * 0.15;
const y = lift[person.id];
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.position.set(position.x, 0.235 + y, position.z);
dummy.updateMatrix();
bodyMesh.setMatrixAt(person.id, dummy.matrix);
dummy.position.set(position.x, 0.475 + y, position.z);
dummy.updateMatrix();
headMesh.setMatrixAt(person.id, dummy.matrix);
const pipScale = 0.45 + person.responseWeight * 0.65;
dummy.position.set(position.x, 0.62 + y, position.z);
dummy.scale.setScalar(pipScale);
dummy.updateMatrix();
pipMesh.setMatrixAt(person.id, dummy.matrix);
}
bodyMesh.instanceMatrix.needsUpdate = true;
headMesh.instanceMatrix.needsUpdate = true;
pipMesh.instanceMatrix.needsUpdate = true;
// Sample tokens pop into the tray with a slight stagger.
tokenData.forEach((person, index) => {
const progress = clamp((now - sampleAnimationStart - index * 7) / 260, 0, 1);
const eased = 1 - (1 - progress) ** 3;
const column = index % 12;
const row = Math.floor(index / 12);
const x = 4.35 + (column - 5.5) * 0.285;
const z = 1.5 + (row - 4.5) * 0.285;
const heightOffset = 0.09 + ((person.score - 30) / 40) * 0.32;
dummy.position.set(x, heightOffset, z);
dummy.rotation.set(0, 0, 0);
dummy.scale.setScalar(eased);
dummy.updateMatrix();
tokenMesh.setMatrixAt(index, dummy.matrix);
});
tokenMesh.instanceMatrix.needsUpdate = true;
// Smoothly move the estimate marker.
gaugeY += (gaugeTargetY - gaugeY) * 0.12;
estimateMarker.position.y = gaugeY;
estimateLabel.sprite.position.y = gaugeY;
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```