Prompt specification
Build or customize the Three.js 3D scene "Random and self-selected groups comparison" 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: Random and self-selected groups comparison
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/random-and-self-selected-groups-comparison-x1818
Scene Description Prompt:
Please make a stylized Three.js scene in one standalone HTML file using cdnjs. Create two assignment mechanisms on the same synthetic units and compare baseline balance across repeated runs; show that randomization does not guarantee perfect balance every time.
Working Three.js Starter (random-and-self-selected-groups-comparison-x1818):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Weighted Assignment Lab</title>
<style>
:root {
--bg: #06111d;
--panel: rgba(8, 20, 34, 0.84);
--panel-border: rgba(145, 206, 220, 0.16);
--text: #eef8fb;
--muted: #8fa9b6;
--random: #ff9468;
--balanced: #57e1d1;
--warning: #ffd166;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
user-select: none;
}
button,
select {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#scene canvas:active {
cursor: grabbing;
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 2;
}
.topbar {
position: absolute;
top: 22px;
left: 24px;
right: 24px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 24px;
}
.brand {
max-width: 590px;
padding: 17px 20px 18px;
border: 1px solid var(--panel-border);
border-radius: 18px;
background:
linear-gradient(135deg, rgba(14, 34, 52, 0.9), rgba(6, 17, 29, 0.76));
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.22);
backdrop-filter: blur(14px);
}
.eyebrow {
display: block;
margin-bottom: 7px;
color: var(--balanced);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(27px, 3vw, 43px);
font-weight: 760;
letter-spacing: -0.045em;
line-height: 1.04;
}
.brand p {
max-width: 540px;
margin: 9px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.controls {
display: flex;
align-items: center;
justify-content: flex-end;
flex-wrap: wrap;
gap: 9px;
pointer-events: auto;
}
button,
select {
height: 42px;
border: 1px solid rgba(151, 211, 224, 0.2);
border-radius: 12px;
background: rgba(12, 29, 45, 0.86);
color: var(--text);
padding: 0 14px;
outline: none;
backdrop-filter: blur(12px);
transition:
transform 160ms ease,
border-color 160ms ease,
background 160ms ease;
}
button:hover:not(:disabled),
select:hover {
transform: translateY(-1px);
border-color: rgba(87, 225, 209, 0.55);
background: rgba(18, 42, 58, 0.94);
}
button:disabled {
opacity: 0.42;
cursor: not-allowed;
}
button.primary {
border-color: rgba(87, 225, 209, 0.55);
background: linear-gradient(135deg, #4dd6c7, #2caeaa);
color: #032221;
font-weight: 800;
box-shadow: 0 10px 30px rgba(40, 190, 177, 0.18);
}
select {
cursor: pointer;
}
.status {
width: 100%;
padding-top: 2px;
color: var(--muted);
font-size: 11px;
text-align: right;
}
.metrics {
position: absolute;
top: 158px;
right: 24px;
width: 350px;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.metric {
min-height: 86px;
padding: 13px 14px;
border: 1px solid var(--panel-border);
border-radius: 15px;
background: var(--panel);
box-shadow: 0 14px 40px rgba(0, 0, 0, 0.18);
backdrop-filter: blur(14px);
}
.metric span {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.metric strong {
display: block;
font-size: 24px;
font-weight: 760;
letter-spacing: -0.035em;
}
.metric small {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.metric.random strong {
color: var(--random);
}
.metric.balanced strong {
color: var(--balanced);
}
.metric.verdict {
grid-column: 1 / -1;
min-height: 70px;
}
.metric.verdict strong {
font-size: 16px;
line-height: 1.35;
}
.camera-hint {
position: absolute;
right: 25px;
bottom: 248px;
padding: 8px 11px;
border: 1px solid rgba(145, 206, 220, 0.12);
border-radius: 10px;
background: rgba(5, 15, 27, 0.56);
color: rgba(180, 207, 216, 0.72);
font-size: 10px;
letter-spacing: 0.04em;
}
.chart-panel {
position: absolute;
left: 50%;
bottom: 17px;
width: min(1120px, calc(100% - 34px));
transform: translateX(-50%);
padding: 15px 17px 13px;
border: 1px solid var(--panel-border);
border-radius: 19px;
background:
linear-gradient(180deg, rgba(10, 26, 42, 0.92), rgba(5, 16, 28, 0.91));
box-shadow: 0 22px 60px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(16px);
pointer-events: auto;
}
.chart-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin-bottom: 11px;
}
.chart-title {
font-size: 12px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.chart-subtitle {
margin-top: 4px;
color: var(--muted);
font-size: 10px;
}
.legend {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 13px;
color: var(--muted);
font-size: 10px;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
white-space: nowrap;
}
.legend-dot {
width: 8px;
height: 8px;
border-radius: 50%;
}
.legend-dot.random {
background: var(--random);
box-shadow: 0 0 12px rgba(255, 148, 104, 0.55);
}
.legend-dot.balanced {
background: var(--balanced);
box-shadow: 0 0 12px rgba(87, 225, 209, 0.55);
}
.catalog {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
margin-bottom: 12px;
padding-top: 10px;
border-top: 1px solid rgba(145, 206, 220, 0.1);
}
.catalog-label {
flex: 0 0 auto;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.chips {
display: flex;
gap: 6px;
min-width: 0;
overflow-x: auto;
scrollbar-width: none;
}
.chips::-webkit-scrollbar {
display: none;
}
.chip {
flex: 0 0 auto;
display: flex;
align-items: center;
gap: 6px;
padding: 5px 8px;
border: 1px solid rgba(145, 206, 220, 0.11);
border-radius: 8px;
background: rgba(255, 255, 255, 0.035);
color: #c9dbe1;
font-size: 9px;
}
.chip i {
width: 7px;
height: 7px;
border-radius: 2px;
background: var(--chip-color);
}
.chip b {
color: var(--text);
font-size: 10px;
}
#trialGrid {
display: grid;
grid-template-columns: repeat(12, minmax(0, 1fr));
gap: 7px;
}
.trial-cell {
min-width: 0;
padding: 7px 6px 6px;
border: 1px solid rgba(145, 206, 220, 0.09);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
transition:
border-color 180ms ease,
background 180ms ease,
transform 180ms ease;
}
.trial-cell.current {
transform: translateY(-2px);
border-color: rgba(87, 225, 209, 0.52);
background: rgba(87, 225, 209, 0.07);
}
.trial-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 4px;
margin-bottom: 5px;
color: #c7dbe3;
font-size: 9px;
font-weight: 800;
}
.seed {
overflow: hidden;
color: #617d89;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 7px;
font-weight: 500;
text-overflow: ellipsis;
white-space: nowrap;
}
.plot {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 3px;
height: 47px;
padding: 0 3px;
border-bottom: 1px solid rgba(145, 206, 220, 0.16);
background:
repeating-linear-gradient(
to top,
transparent 0,
transparent 11px,
rgba(145, 206, 220, 0.055) 11px,
rgba(145, 206, 220, 0.055) 12px
);
}
.bar-slot {
position: relative;
height: 100%;
}
.gap-fill {
position: absolute;
right: 50%;
bottom: 0;
width: 9px;
max-width: 80%;
min-height: 0;
border-radius: 4px 4px 1px 1px;
transform: translateX(50%);
transition: height 500ms cubic-bezier(0.22, 1, 0.36, 1);
}
.gap-fill.random {
background: linear-gradient(to top, #d85d3d, var(--random));
box-shadow: 0 0 13px rgba(255, 148, 104, 0.22);
}
.gap-fill.balanced {
background: linear-gradient(to top, #27aaa0, var(--balanced));
box-shadow: 0 0 13px rgba(87, 225, 209, 0.22);
}
.gap-dot {
position: absolute;
right: 50%;
bottom: -2px;
width: 7px;
height: 7px;
border-radius: 50%;
opacity: 0;
transform: translateX(50%);
}
.gap-dot.random {
background: var(--random);
box-shadow: 0 0 9px rgba(255, 148, 104, 0.7);
}
.gap-dot.balanced {
background: var(--balanced);
box-shadow: 0 0 9px rgba(87, 225, 209, 0.7);
}
.gap-dot.visible {
opacity: 1;
}
.trial-values {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 3px;
margin-top: 5px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 8px;
text-align: center;
}
.trial-values span:first-child {
color: var(--random);
}
.trial-values span:last-child {
color: var(--balanced);
}
.chart-footer {
margin-top: 8px;
color: #69828d;
font-size: 9px;
line-height: 1.45;
}
@media (max-width: 960px) {
.topbar {
top: 12px;
left: 12px;
right: 12px;
}
.brand {
max-width: 470px;
padding: 13px 15px;
}
.brand p {
display: none;
}
.controls {
max-width: 330px;
}
.controls button,
.controls select {
height: 37px;
padding: 0 10px;
font-size: 11px;
}
.metrics {
top: 126px;
right: 12px;
width: 310px;
}
.metric {
min-height: 72px;
padding: 10px 12px;
}
.metric strong {
font-size: 20px;
}
.metric.verdict strong {
font-size: 14px;
}
.chart-panel {
width: calc(100% - 20px);
bottom: 10px;
padding: 12px;
}
.camera-hint {
display: none;
}
}
@media (max-width: 680px) {
.topbar {
display: block;
}
.brand {
max-width: none;
}
.brand h1 {
font-size: 27px;
}
.controls {
max-width: none;
margin-top: 8px;
justify-content: flex-start;
}
.status {
display: none;
}
.metrics {
top: 132px;
left: 10px;
right: 10px;
width: auto;
grid-template-columns: repeat(3, 1fr);
}
.metric {
min-height: 66px;
}
.metric span {
font-size: 8px;
}
.metric strong {
font-size: 18px;
}
.metric small {
display: none;
}
.metric.verdict {
grid-column: 1 / -1;
min-height: 55px;
}
.chart-panel {
padding: 10px;
}
.chart-header {
align-items: flex-start;
}
.chart-subtitle {
display: none;
}
.catalog-label {
display: none;
}
#trialGrid {
grid-template-columns: repeat(6, minmax(0, 1fr));
gap: 5px;
}
.trial-cell {
padding: 5px 4px;
}
.chart-footer {
display: none;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="hud">
<header class="topbar">
<div class="brand">
<span class="eyebrow">Synthetic systems / weighted assignment</span>
<h1>Balance is not random.</h1>
<p>
The same eight weighted units are assigned repeatedly. A coin-flip
baseline can land perfectly, but it cannot promise perfect balance.
A greedy balancer chooses the currently lighter side.
</p>
</div>
<div class="controls">
<button id="runAll" class="primary">Run 12 trials</button>
<button id="nextTrial">Next trial</button>
<select id="speed" aria-label="Animation speed">
<option value="1">1× speed</option>
<option value="2">2× speed</option>
<option value="4" selected>4× speed</option>
<option value="8">8× speed</option>
</select>
<button id="reset">Reset</button>
<div id="status" class="status" aria-live="polite">Preparing experiment…</div>
</div>
</header>
<section class="metrics" aria-label="Experiment statistics">
<div class="metric random">
<span>Random exact runs</span>
<strong id="randomExact">—</strong>
<small id="randomMean">Mean absolute gap: —</small>
</div>
<div class="metric balanced">
<span>Balanced exact runs</span>
<strong id="balancedExact">—</strong>
<small>Greedy: heaviest to lighter side</small>
</div>
<div class="metric verdict">
<span>Conclusion</span>
<strong id="verdict">Repeated trials are required.</strong>
<small id="verdictDetail">
Both mechanisms receive exactly the same synthetic catalog.
</small>
</div>
</section>
<div class="camera-hint">
DRAG TO ORBIT · SCROLL TO ZOOM
</div>
<section class="chart-panel">
<div class="chart-header">
<div>
<div class="chart-title">Absolute load gap by trial</div>
<div class="chart-subtitle">
Lower is better · 0 kg means both teams carry exactly 20 kg
</div>
</div>
<div class="legend">
<div class="legend-item">
<span class="legend-dot random"></span>
Random baseline
</div>
<div class="legend-item">
<span class="legend-dot balanced"></span>
Greedy balancer
</div>
</div>
</div>
<div class="catalog">
<div class="catalog-label">Shared catalog</div>
<div id="catalog" class="chips"></div>
</div>
<div id="trialGrid"></div>
<div class="chart-footer">
Every trial uses the same unit IDs and weights. Only the assignment
rule changes. Randomness may produce an exact result by chance, but it
does not guarantee one on every run.
</div>
</section>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Experiment data
// -------------------------------------------------------------------------
const RANDOM_COLOR = 0xff9468;
const BALANCED_COLOR = 0x57e1d1;
const units = [
{ id: "U01", weight: 8 },
{ id: "U02", weight: 7 },
{ id: "U03", weight: 6 },
{ id: "U04", weight: 5 },
{ id: "U05", weight: 4 },
{ id: "U06", weight: 4 },
{ id: "U07", weight: 3 },
{ id: "U08", weight: 3 }
];
const TOTAL_WEIGHT = units.reduce((sum, unit) => sum + unit.weight, 0);
const TRIAL_COUNT = 12;
function mulberry32(seed) {
let value = seed >>> 0;
return function () {
value += 0x6d2b79f5;
let t = value;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function assignRandom(seed) {
const random = mulberry32(seed);
const totals = [0, 0];
const assignments = units.map((unit) => {
const side = random() < 0.5 ? 0 : 1;
totals[side] += unit.weight;
return side;
});
return { assignments, totals };
}
function assignGreedy() {
const totals = [0, 0];
// Units are already ordered from heaviest to lightest.
const assignments = units.map((unit) => {
const side = totals[0] <= totals[1] ? 0 : 1;
totals[side] += unit.weight;
return side;
});
return { assignments, totals };
}
function gapOf(totals) {
return Math.abs(totals[0] - totals[1]);
}
function makeSeedSchedule() {
const seeds = [];
for (let i = 0; i < TRIAL_COUNT; i++) {
seeds.push((0x5eed0000 + i * 104729) >>> 0);
}
// Keep the experiment reproducible while ensuring the visualization
// demonstrates both possible random outcomes.
if (!seeds.some((seed) => gapOf(assignRandom(seed).totals) === 0)) {
for (
let candidate = 0x5eed0000 + TRIAL_COUNT * 104729;
candidate < 0x5eed0000 + 500000;
candidate += 104729
) {
if (gapOf(assignRandom(candidate).totals) === 0) {
seeds[TRIAL_COUNT - 1] = candidate >>> 0;
break;
}
}
}
if (seeds.every((seed) => gapOf(assignRandom(seed).totals) === 0)) {
for (let candidate = 0x70000000; candidate < 0x71000000; candidate++) {
if (gapOf(assignRandom(candidate).totals) > 0) {
seeds[1] = candidate >>> 0;
break;
}
}
}
return seeds;
}
const seedSchedule = makeSeedSchedule();
const results = [];
let busy = false;
let userInteracted = false;
// -------------------------------------------------------------------------
// Three.js setup
// -------------------------------------------------------------------------
const container = document.getElementById("scene");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x06111d);
scene.fog = new THREE.FogExp2(0x06111d, 0.025);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.18;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
container.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
const orbit = {
target: new THREE.Vector3(0, 1.35, -0.1),
radius: 19.5,
theta: 0,
phi: 0.97,
targetRadius: 19.5,
targetTheta: 0,
targetPhi: 0.97,
dragging: false,
pointerX: 0,
pointerY: 0
};
function updateCamera() {
const damping = 0.085;
orbit.radius +=
(orbit.targetRadius - orbit.radius) * damping;
orbit.theta +=
(orbit.targetTheta - orbit.theta) * damping;
orbit.phi +=
(orbit.targetPhi - orbit.phi) * damping;
const spherical = new THREE.Spherical(
orbit.radius,
orbit.phi,
orbit.theta
);
camera.position.setFromSpherical(spherical).add(orbit.target);
camera.lookAt(orbit.target);
}
renderer.domElement.addEventListener("pointerdown", (event) => {
orbit.dragging = true;
orbit.pointerX = event.clientX;
orbit.pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!orbit.dragging) return;
const dx = event.clientX - orbit.pointerX;
const dy = event.clientY - orbit.pointerY;
orbit.pointerX = event.clientX;
orbit.pointerY = event.clientY;
orbit.targetTheta -= dx * 0.006;
orbit.targetPhi = THREE.MathUtils.clamp(
orbit.targetPhi - dy * 0.005,
0.5,
1.42
);
});
function endDrag(event) {
orbit.dragging = false;
if (event?.pointerId !== undefined) {
try {
renderer.domElement.releasePointerCapture(event.pointerId);
} catch (_) {}
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.targetRadius = THREE.MathUtils.clamp(
orbit.targetRadius + event.deltaY * 0.012,
12.5,
27
);
},
{ passive: false }
);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
const hemisphere = new THREE.HemisphereLight(0xa8e7ff, 0x0a1823, 2.0);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.4);
keyLight.position.set(4, 13, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -16;
keyLight.shadow.camera.right = 16;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -12;
keyLight.shadow.bias = -0.0003;
scene.add(keyLight);
const randomLight = new THREE.PointLight(RANDOM_COLOR, 28, 12, 2);
randomLight.position.set(-7, 4, 2);
scene.add(randomLight);
const balancedLight = new THREE.PointLight(BALANCED_COLOR, 28, 12, 2);
balancedLight.position.set(7, 4, 2);
scene.add(balancedLight);
// Ground and grid
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(38, 26),
new THREE.MeshStandardMaterial({
color: 0x071521,
roughness: 0.94,
metalness: 0.08
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.08;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(30, 30, 0x246678, 0x123342);
grid.position.y = -0.055;
grid.material.transparent = true;
grid.material.opacity = 0.28;
scene.add(grid);
// Decorative particles
const particlePositions = [];
let particleState = 0xabc123;
for (let i = 0; i < 110; i++) {
particleState = (particleState * 1664525 + 1013904223) >>> 0;
const x = ((particleState / 4294967296) - 0.5) * 28;
particleState = (particleState * 1664525 + 1013904223) >>> 0;
const z = ((particleState / 4294967296) - 0.5) * 19;
particleState = (particleState * 1664525 + 1013904223) >>> 0;
const y = 0.4 + (particleState / 4294967296) * 6;
particlePositions.push(x, y, z);
}
const particleGeometry = new THREE.BufferGeometry();
particleGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(particlePositions, 3)
);
const particles = new THREE.Points(
particleGeometry,
new THREE.PointsMaterial({
color: 0x67cbd0,
size: 0.035,
transparent: true,
opacity: 0.35,
depthWrite: false
})
);
scene.add(particles);
// -------------------------------------------------------------------------
// Canvas-based labels; no external fonts or assets
// -------------------------------------------------------------------------
function roundedRect(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 createPanelSprite(worldWidth, worldHeight) {
const canvas = document.createElement("canvas");
canvas.width = 768;
canvas.height = 192;
const context = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(worldWidth, worldHeight, 1);
sprite.renderOrder = 20;
const panel = {
sprite,
canvas,
context,
texture,
draw(title, subtitle, accent = "#57e1d1", status = "#eef8fb") {
context.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(
context,
6,
8,
canvas.width - 12,
canvas.height - 16,
25
);
context.fillStyle = "rgba(5, 15, 27, 0.88)";
context.fill();
context.lineWidth = 3;
context.strokeStyle = "rgba(150, 213, 225, 0.22)";
context.stroke();
roundedRect(context, 24, 28, 8, 136, 4);
context.fillStyle = accent;
context.fill();
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = status;
context.font = "800 42px system-ui, sans-serif";
context.fillText(title, canvas.width / 2 + 4, 73);
context.fillStyle = "#91abb7";
context.font = "600 24px system-ui, sans-serif";
context.fillText(subtitle, canvas.width / 2 + 4, 128);
texture.needsUpdate = true;
}
};
return panel;
}
const unitLabelTextures = new Map();
function getUnitLabelTexture(weight) {
if (unitLabelTextures.has(weight)) {
return unitLabelTextures.get(weight);
}
const canvas = document.createElement("canvas");
canvas.width = 192;
canvas.height = 96;
const context = canvas.getContext("2d");
roundedRect(context, 8, 8, 176, 80, 18);
context.fillStyle = "rgba(3, 10, 18, 0.86)";
context.fill();
context.strokeStyle = "rgba(255,255,255,0.26)";
context.lineWidth = 3;
context.stroke();
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = "#ffffff";
context.font = "800 38px system-ui, sans-serif";
context.fillText(`${weight} kg`, 96, 48);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
unitLabelTextures.set(weight, texture);
return texture;
}
const unitGeometry = new THREE.BoxGeometry(0.56, 0.5, 0.56);
const unitEdgeGeometry = new THREE.EdgesGeometry(unitGeometry);
const unitLabelGeometry = new THREE.PlaneGeometry(0.43, 0.22);
const weightColors = new Map([
[8, 0x9b6cff],
[7, 0xed5da8],
[6, 0xff8057],
[5, 0xf6c453],
[4, 0x4bd18a],
[3, 0x42bce8]
]);
function makeUnit(unit, accent) {
const group = new THREE.Group();
const material = new THREE.MeshStandardMaterial({
color: weightColors.get(unit.weight) ?? 0x5ce1d0,
roughness: 0.3,
metalness: 0.28,
emissive: weightColors.get(unit.weight) ?? 0x5ce1d0,
emissiveIntensity: 0.09
});
const body = new THREE.Mesh(unitGeometry, material);
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const edgeMaterial = new THREE.LineBasicMaterial({
color: accent,
transparent: true,
opacity: 0.92
});
const edges = new THREE.LineSegments(unitEdgeGeometry, edgeMaterial);
group.add(edges);
const labelMaterial = new THREE.MeshBasicMaterial({
map: getUnitLabelTexture(unit.weight),
transparent: true,
depthWrite: false
});
const label = new THREE.Mesh(unitLabelGeometry, labelMaterial);
label.position.set(0, 0, 0.286);
group.add(label);
group.userData.dispose = () => {
material.dispose();
edgeMaterial.dispose();
labelMaterial.dispose();
};
return group;
}
// -------------------------------------------------------------------------
// Stations
// -------------------------------------------------------------------------
const stations = {};
function createStation({
x,
accent,
title,
subtitle,
titleColor,
key
}) {
const group = new THREE.Group();
group.position.set(x, 0, 0.15);
scene.add(group);
const baseMaterial = new THREE.MeshStandardMaterial({
color: 0x0a1b29,
roughness: 0.64,
metalness: 0.35
});
const base = new THREE.Mesh(
new THREE.BoxGeometry(6.15, 0.3, 4.55),
baseMaterial
);
base.position.y = 0.1;
base.receiveShadow = true;
group.add(base);
const frontRail = new THREE.Mesh(
new THREE.BoxGeometry(5.85, 0.055, 0.055),
new THREE.MeshBasicMaterial({ color: accent })
);
frontRail.position.set(0, 0.27, 2.285);
group.add(frontRail);
const platformMaterial = new THREE.MeshStandardMaterial({
color: 0x102636,
roughness: 0.47,
metalness: 0.38,
emissive: accent,
emissiveIntensity: 0.045
});
const platformGeometry = new THREE.BoxGeometry(2.25, 0.26, 2.08);
[-1.48, 1.48].forEach((platformX) => {
const platform = new THREE.Mesh(platformGeometry, platformMaterial);
platform.position.set(platformX, 0.38, 0.42);
platform.receiveShadow = true;
platform.castShadow = true;
group.add(platform);
});
const teamLabels = [
createPanelSprite(1.72, 0.43),
createPanelSprite(1.72, 0.43)
];
teamLabels[0].draw("TEAM A", "side 0", titleColor);
teamLabels[1].draw("TEAM B", "side 1", titleColor);
teamLabels[0].sprite.position.set(-1.48, 0.43, 2.42);
teamLabels[1].sprite.position.set(1.48, 0.43, 2.42);
group.add(teamLabels[0].sprite, teamLabels[1].sprite);
// Balance beam
const beamGroup = new THREE.Group();
beamGroup.position.set(0, 3.02, -1.38);
group.add(beamGroup);
const beamMaterial = new THREE.MeshStandardMaterial({
color: accent,
emissive: accent,
emissiveIntensity: 0.45,
metalness: 0.5,
roughness: 0.3
});
const beam = new THREE.Mesh(
new THREE.BoxGeometry(4.65, 0.1, 0.12),
beamMaterial
);
beam.castShadow = true;
beamGroup.add(beam);
const padGeometry = new THREE.CylinderGeometry(0.34, 0.34, 0.1, 24);
const pads = [];
[-2.32, 2.32].forEach((padX) => {
const pad = new THREE.Mesh(padGeometry, beamMaterial);
pad.position.set(padX, -0.27, 0);
pad.castShadow = true;
beamGroup.add(pad);
pads.push(pad);
});
const pivot = new THREE.Mesh(
new THREE.CylinderGeometry(0.17, 0.23, 0.65, 20),
new THREE.MeshStandardMaterial({
color: 0x7b98a4,
metalness: 0.75,
roughness: 0.25
})
);
pivot.position.y = -0.28;
beamGroup.add(pivot);
const titlePanel = createPanelSprite(4.85, 1.12);
titlePanel.draw(title, subtitle, titleColor, titleColor);
titlePanel.sprite.position.set(0, 5.0, -0.75);
group.add(titlePanel.sprite);
const metricPanel = createPanelSprite(4.45, 1.02);
metricPanel.draw(
"A — kg B — kg",
"awaiting unit placement",
titleColor,
"#eef8fb"
);
metricPanel.sprite.position.set(0, 4.02, -0.68);
group.add(metricPanel.sprite);
return {
key,
group,
accent,
titleColor,
beamGroup,
beamMaterial,
pads,
titlePanel,
metricPanel,
counts: [0, 0],
totals: [0, 0],
placed: []
};
}
stations.random = createStation({
x: -6.25,
accent: RANDOM_COLOR,
title: "RANDOM BASELINE",
subtitle: "Independent coin flip for every unit",
titleColor: "#ff9468",
key: "random"
});
stations.balanced = createStation({
x: 6.25,
accent: BALANCED_COLOR,
title: "GREEDY BALANCER",
subtitle: "Place the next heaviest unit on the lighter side",
titleColor: "#57e1d1",
key: "balanced"
});
// Shared catalog in the center
const catalogPedestal = new THREE.Mesh(
new THREE.CylinderGeometry(2.4, 2.65, 0.25, 48),
new THREE.MeshStandardMaterial({
color: 0x0b2130,
roughness: 0.7,
metalness: 0.4
})
);
catalogPedestal.position.set(0, 0.06, -3.05);
catalogPedestal.receiveShadow = true;
scene.add(catalogPedestal);
const catalogRing = new THREE.Mesh(
new THREE.TorusGeometry(2.18, 0.025, 8, 80),
new THREE.MeshBasicMaterial({
color: 0x57e1d1,
transparent: true,
opacity: 0.42
})
);
catalogRing.rotation.x = Math.PI / 2;
catalogRing.position.set(0, 0.2, -3.05);
scene.add(catalogRing);
units.forEach((unit, index) => {
const col = index % 4;
const row = Math.floor(index / 4);
const token = new THREE.Mesh(
new THREE.BoxGeometry(0.46, 0.32, 0.46),
new THREE.MeshStandardMaterial({
color: weightColors.get(unit.weight),
emissive: weightColors.get(unit.weight),
emissiveIntensity: 0.09,
roughness: 0.35,
metalness: 0.28
})
);
token.position.set(-1.05 + col * 0.7, 0.42, -3.25 + row * 0.6);
token.castShadow = true;
scene.add(token);
const label = new THREE.Mesh(
new THREE.PlaneGeometry(0.37, 0.18),
new THREE.MeshBasicMaterial({
map: getUnitLabelTexture(unit.weight),
transparent: true,
depthWrite: false
})
);
label.position.copy(token.position);
label.position.z += 0.236;
scene.add(label);
});
const catalogPanel = createPanelSprite(4.4, 1.05);
catalogPanel.draw(
"SHARED UNIT CATALOG",
`${units.length} units · ${TOTAL_WEIGHT} kg total`,
"#57e1d1",
"#eef8fb"
);
catalogPanel.sprite.position.set(0, 2.42, -3.35);
scene.add(catalogPanel.sprite);
const currentUnitPanel = createPanelSprite(3.1, 0.83);
currentUnitPanel.draw(
"READY",
"waiting for a trial",
"#ffd166",
"#eef8fb"
);
currentUnitPanel.sprite.position.set(0, 1.83, -2.05);
scene.add(currentUnitPanel.sprite);
// -------------------------------------------------------------------------
// Animation helpers
// -------------------------------------------------------------------------
const tweens = [];
function tweenUnit(group, destination, duration, arcHeight = 1.45) {
return new Promise((resolve) => {
tweens.push({
group,
from: group.position.clone(),
to: destination.clone(),
duration,
arcHeight,
startedAt: performance.now(),
resolve
});
});
}
function updateTweens(now) {
for (let i = tweens.length - 1; i >= 0; i--) {
const tween = tweens[i];
const raw = Math.min(1, (now - tween.startedAt) / tween.duration);
const eased =
raw < 0.5
? 4 * raw * raw * raw
: 1 - Math.pow(-2 * raw + 2, 3) / 2;
tween.group.position.lerpVectors(tween.from, tween.to, eased);
tween.group.position.y +=
Math.sin(Math.PI * eased) * tween.arcHeight;
tween.group.rotation.y =
Math.sin(Math.PI * eased) * 0.38 * Math.sign(tween.to.x || 1);
tween.group.rotation.z =
Math.sin(Math.PI * eased) * 0.08;
if (raw >= 1) {
tween.group.position.copy(tween.to);
tween.group.rotation.set(0, 0, 0);
tweens.splice(i, 1);
tween.resolve();
}
}
}
function clearStation(station) {
station.placed.forEach((unit) => {
scene.remove(unit);
unit.userData.dispose?.();
});
station.placed = [];
station.counts = [0, 0];
station.totals = [0, 0];
station.beamGroup.rotation.z = 0;
station.beamMaterial.color.setHex(station.accent);
station.beamMaterial.emissive.setHex(station.accent);
station.metricPanel.draw(
"A — kg B — kg",
"awaiting unit placement",
station.titleColor,
"#eef8fb"
);
}
function updateStationMetric(station, complete = false, seed = 0) {
const [a, b] = station.totals;
const gap = Math.abs(a - b);
const exact = gap === 0;
const statusColor = exact ? "#57e1d1" : "#ff9468";
if (station.key === "random") {
station.metricPanel.draw(
`A ${a} kg B ${b} kg`,
complete
? `seed 0x${seed.toString(16).slice(-6)} · Δ ${gap} kg`
: `placing units · Δ ${gap} kg`,
statusColor,
"#eef8fb"
);
} else {
station.metricPanel.draw(
`A ${a} kg B ${b} kg`,
complete
? `Δ ${gap} kg · ${exact ? "EXACT" : "NOT EXACT"}`
: `placing units · Δ ${gap} kg`,
statusColor,
"#eef8fb"
);
}
const tilt = THREE.MathUtils.clamp(
((b - a) / Math.max(TOTAL_WEIGHT / 2, 1)) * 0.26,
-0.26,
0.26
);
station.beamGroup.rotation.z = -tilt;
const beamColor = exact ? 0x57e1d1 : 0xff9468;
station.beamMaterial.color.setHex(beamColor);
station.beamMaterial.emissive.setHex(beamColor);
}
function destinationFor(station, side, index) {
const row = Math.floor(index / 3);
const col = index % 3;
const sideCenter = side === 0 ? -1.48 : 1.48;
const offsetX = (col - 1) * 0.66;
const offsetZ = -0.34 + row * 0.69;
return new THREE.Vector3(
station.group.position.x + sideCenter + offsetX,
0.68 + row * 0.54,
station.group.position.z + 0.42 + offsetZ
);
}
function clearAllStations() {
clearStation(stations.random);
clearStation(stations.balanced);
}
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
const runAllButton = document.getElementById("runAll");
const nextButton = document.getElementById("nextTrial");
const resetButton = document.getElementById("reset");
const speedSelect = document.getElementById("speed");
const statusElement = document.getElementById("status");
const randomExactElement = document.getElementById("randomExact");
const balancedExactElement = document.getElementById("balancedExact");
const randomMeanElement = document.getElementById("randomMean");
const verdictElement = document.getElementById("verdict");
const verdictDetailElement = document.getElementById("verdictDetail");
const unitColors = {
8: "#9b6cff",
7: "#ed5da8",
6: "#ff8057",
5: "#f6c453",
4: "#4bd18a",
3: "#42bce8"
};
document.getElementById("catalog").innerHTML = units
.map(
(unit) => `
<div class="chip">
<i style="--chip-color:${unitColors[unit.weight]}"></i>
<span>${unit.id}</span>
<b>${unit.weight} kg</b>
</div>
`
)
.join("");
const trialGrid = document.getElementById("trialGrid");
const trialCells = [];
function createTrialCells() {
trialGrid.innerHTML = "";
for (let i = 0; i < TRIAL_COUNT; i++) {
const cell = document.createElement("div");
cell.className = "trial-cell";
cell.innerHTML = `
<div class="trial-head">
<span>T${String(i + 1).padStart(2, "0")}</span>
<span class="seed">—</span>
</div>
<div class="plot">
<div class="bar-slot">
<i class="gap-fill random"></i>
<i class="gap-dot random"></i>
</div>
<div class="bar-slot">
<i class="gap-fill balanced"></i>
<i class="gap-dot balanced"></i>
</div>
</div>
<div class="trial-values">
<span>—</span>
<span>—</span>
</div>
`;
trialGrid.appendChild(cell);
trialCells.push(cell);
}
}
function setBar(cell, type, gap) {
const fill = cell.querySelector(`.gap-fill.${type}`);
const dot = cell.querySelector(`.gap-dot.${type}`);
const height = Math.min(100, (gap / 12) * 100);
fill.style.height = `${height}%`;
dot.classList.toggle("visible", gap === 0);
fill.style.opacity = gap === 0 ? "0" : "1";
}
function updateTrialCell(index, result) {
const cell = trialCells[index];
const randomGap = result.randomGap;
const balancedGap = result.balancedGap;
cell.querySelector(".seed").textContent =
`0x${result.seed.toString(16).slice(-5)}`;
cell.querySelectorAll(".trial-values span")[0].textContent =
`R ${randomGap}`;
cell.querySelectorAll(".trial-values span")[1].textContent =
`G ${balancedGap}`;
setBar(cell, "random", randomGap);
setBar(cell, "balanced", balancedGap);
cell.title =
`Trial ${index + 1}\n` +
`Seed: 0x${result.seed.toString(16)}\n` +
`Random gap: ${randomGap} kg\n` +
`Greedy gap: ${balancedGap} kg`;
}
function updateStatistics() {
if (results.length === 0) {
randomExactElement.textContent = "—";
balancedExactElement.textContent = "—";
randomMeanElement.textContent = "Mean absolute gap: —";
verdictElement.textContent = "Repeated trials are required.";
verdictDetailElement.textContent =
"Both mechanisms receive exactly the same synthetic catalog.";
return;
}
const randomExact = results.filter(
(result) => result.randomGap === 0
).length;
const balancedExact = results.filter(
(result) => result.balancedGap === 0
).length;
const meanGap =
results.reduce(
(sum, result) => sum + result.randomGap,
0
) / results.length;
randomExactElement.textContent =
`${randomExact}/${results.length}`;
balancedExactElement.textContent =
`${balancedExact}/${results.length}`;
randomMeanElement.textContent =
`Mean absolute gap: ${meanGap.toFixed(1)} kg`;
if (randomExact < results.length) {
verdictElement.textContent =
`Random missed exact balance on ${results.length - randomExact} run${results.length - randomExact === 1 ? "" : "s"}.`;
verdictDetailElement.textContent =
"A lucky exact run does not turn coin flips into a guarantee.";
} else {
verdictElement.textContent =
"Random was exact here, but still provides no guarantee.";
verdictDetailElement.textContent =
"Different seeds can produce different load gaps.";
}
}
function setBusy(value) {
busy = value;
runAllButton.disabled = value;
nextButton.disabled = value || results.length >= TRIAL_COUNT;
resetButton.disabled = value;
runAllButton.textContent = value
? "Running experiment…"
: "Run 12 trials";
}
function resetTrialData() {
results.length = 0;
clearAllStations();
createTrialCells();
updateStatistics();
currentUnitPanel.draw(
"READY",
"waiting for a trial",
"#ffd166",
"#eef8fb"
);
}
// -------------------------------------------------------------------------
// Trial execution
// -------------------------------------------------------------------------
async function executeTrial() {
const index = results.length;
const seed = seedSchedule[index];
const random = assignRandom(seed);
const greedy = assignGreedy();
trialCells.forEach((cell, cellIndex) => {
cell.classList.toggle("current", cellIndex === index);
});
clearStation(stations.random);
clearStation(stations.balanced);
statusElement.textContent =
`Trial ${index + 1} / ${TRIAL_COUNT} · seed 0x${seed.toString(16).slice(-6)}`;
const duration = 300 / Number(speedSelect.value);
for (let unitIndex = 0; unitIndex < units.length; unitIndex++) {
const unit = units[unitIndex];
currentUnitPanel.draw(
`${unit.id} · ${unit.weight} kg`,
`same unit entering both mechanisms`,
"#ffd166",
"#eef8fb"
);
const randomUnit = makeUnit(unit, RANDOM_COLOR);
const balancedUnit = makeUnit(unit, BALANCED_COLOR);
randomUnit.position.set(-0.14, 0.92, -2.0);
balancedUnit.position.set(0.14, 0.92, -2.0);
scene.add(randomUnit, balancedUnit);
const randomIndex = stations.random.counts[
random.assignments[unitIndex]
];
const balancedIndex = stations.balanced.counts[
greedy.assignments[unitIndex]
];
const randomDestination = destinationFor(
stations.random,
random.assignments[unitIndex],
randomIndex
);
const balancedDestination = destinationFor(
stations.balanced,
greedy.assignments[unitIndex],
balancedIndex
);
await Promise.all([
tweenUnit(randomUnit, randomDestination, duration, 1.55),
tweenUnit(balancedUnit, balancedDestination, duration, 1.75)
]);
stations.random.counts[random.assignments[unitIndex]]++;
stations.balanced.counts[greedy.assignments[unitIndex]]++;
stations.random.totals[random.assignments[unitIndex]] += unit.weight;
stations.balanced.totals[greedy.assignments[unitIndex]] += unit.weight;
stations.random.placed.push(randomUnit);
stations.balanced.placed.push(balancedUnit);
updateStationMetric(stations.random, false, seed);
updateStationMetric(stations.balanced, false, seed);
}
updateStationMetric(stations.random, true, seed);
updateStationMetric(stations.balanced, true, seed);
const result = {
seed,
randomGap: gapOf(random.totals),
balancedGap: gapOf(greedy.totals),
randomTotals: [...random.totals],
balancedTotals: [...greedy.totals]
};
results.push(result);
updateTrialCell(index, result);
updateStatistics();
return result;
}
async function runAllTrials() {
if (busy) return;
setBusy(true);
resetTrialData();
for (let i = 0; i < TRIAL_COUNT; i++) {
await executeTrial();
}
trialCells.forEach((cell) => cell.classList.remove("current"));
const exactCount = results.filter(
(result) => result.randomGap === 0
).length;
statusElement.textContent =
`Complete · random exact on ${exactCount}/${TRIAL_COUNT} trials`;
setBusy(false);
nextButton.disabled = true;
}
async function runNextTrial() {
if (busy || results.length >= TRIAL_COUNT) return;
setBusy(true);
await executeTrial();
statusElement.textContent =
`Trial ${results.length} complete · run the full batch for comparison`;
setBusy(false);
}
runAllButton.addEventListener("click", () => {
userInteracted = true;
runAllTrials();
});
nextButton.addEventListener("click", () => {
userInteracted = true;
runNextTrial();
});
resetButton.addEventListener("click", () => {
userInteracted = true;
resetTrialData();
statusElement.textContent = "Experiment reset.";
});
speedSelect.addEventListener("change", () => {
userInteracted = true;
statusElement.textContent =
`Animation speed: ${speedSelect.value}×`;
});
createTrialCells();
updateStatistics();
// -------------------------------------------------------------------------
// Render loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate(now) {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
updateTweens(now);
updateCamera();
particles.rotation.y = elapsed * 0.008;
catalogRing.rotation.z = elapsed * 0.12;
randomLight.intensity =
25 + Math.sin(elapsed * 1.7) * 3;
balancedLight.intensity =
25 + Math.sin(elapsed * 1.7 + 1.5) * 3;
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
// Start the demonstration automatically unless the user has already
// interacted with the controls.
setTimeout(() => {
if (!userInteracted) {
runAllTrials();
}
}, 650);
</script>
</body>
</html>
```