Prompt specification
Build or customize the Three.js 3D scene "Survey Only Beside the Bus Stop" 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: Survey Only Beside the Bus Stop
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/survey-only-beside-the-bus-stop-x3258
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring a voxel neighborhood survey beside a bus stop. Arrange three residential blocks around a road, with a stop near one block and a walking route from each. Give resident tokens visible group symbols and a published fictional population count. During a short morning sequence, only residents who pass the interviewer enter the sample tray. Place the sample and full-population proportions side by side, and let the viewer replay the same movement schedule after relocating the interviewer. The selection rule should remain visible, making the sample's dependence on location easy to follow.
Working Three.js Starter (survey-only-beside-the-bus-stop-x3258):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Morning Survey</title>
<style>
:root {
--ink: #173047;
--muted: #657487;
--paper: rgba(250, 252, 247, 0.94);
--line: rgba(23, 48, 71, 0.13);
--a: #147d92;
--b: #e85d55;
--c: #d19a16;
--accent: #7656d8;
--good: #23856d;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
color: var(--ink);
background: #dce9ed;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button { font: inherit; }
#scene {
position: fixed;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene:active { cursor: grabbing; }
.title-card {
position: fixed;
top: 18px;
left: 18px;
width: min(430px, calc(100vw - 36px));
padding: 16px 18px;
border: 1px solid var(--line);
border-radius: 18px;
background: var(--paper);
box-shadow: 0 12px 36px rgba(36, 57, 73, 0.13);
backdrop-filter: blur(12px);
pointer-events: none;
}
.eyebrow {
margin: 0 0 5px;
color: var(--accent);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(22px, 2.4vw, 32px);
line-height: 1.05;
letter-spacing: -0.035em;
}
.subtitle {
margin: 8px 0 12px;
max-width: 390px;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.title-meta {
display: flex;
flex-wrap: wrap;
gap: 7px;
}
.pill {
display: inline-flex;
align-items: center;
gap: 6px;
min-height: 27px;
padding: 5px 9px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(255, 255, 255, 0.72);
color: #415267;
font-size: 11px;
font-weight: 700;
}
.pill strong { color: var(--ink); }
.panel {
position: fixed;
top: 18px;
right: 18px;
width: 420px;
max-height: calc(100vh - 36px);
overflow: auto;
padding: 17px;
border: 1px solid var(--line);
border-radius: 18px;
background: var(--paper);
box-shadow: 0 12px 36px rgba(36, 57, 73, 0.13);
backdrop-filter: blur(12px);
scrollbar-width: thin;
}
.panel-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}
.panel h2,
.dock h2 {
margin: 0;
font-size: 16px;
letter-spacing: -0.02em;
}
.small {
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.sample-count {
flex: 0 0 auto;
padding: 7px 10px;
border-radius: 11px;
background: #eef0fb;
color: #5741aa;
font-size: 12px;
font-weight: 800;
white-space: nowrap;
}
.comparison {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin: 12px 0 16px;
}
.comparison-column {
min-width: 0;
padding: 11px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(255, 255, 255, 0.66);
}
.comparison-column.sample-column {
border-color: rgba(118, 86, 216, 0.28);
background: rgba(244, 241, 255, 0.76);
}
.column-title {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 5px;
margin-bottom: 10px;
}
.column-title strong { font-size: 12px; }
.column-title span { color: var(--muted); font-size: 10px; }
.bar-row {
display: grid;
grid-template-columns: 17px minmax(0, 1fr);
gap: 4px 7px;
align-items: center;
margin: 9px 0;
}
.symbol {
display: inline-grid;
place-items: center;
width: 17px;
height: 17px;
color: var(--group-color);
font-size: 15px;
line-height: 1;
font-weight: 900;
}
.group-name {
overflow: hidden;
color: #44566a;
font-size: 10px;
font-weight: 700;
text-overflow: ellipsis;
white-space: nowrap;
}
.metric {
grid-column: 2;
color: var(--muted);
font-size: 9px;
font-variant-numeric: tabular-nums;
}
.track {
grid-column: 2;
height: 5px;
overflow: hidden;
border-radius: 99px;
background: #e5e9e8;
}
.fill {
width: 0;
height: 100%;
border-radius: inherit;
background: var(--group-color);
transition: width 180ms ease-out;
}
.section-label {
margin: 14px 0 8px;
color: #596a7b;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.locations {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.location-button {
min-height: 52px;
padding: 8px 10px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.75);
color: var(--ink);
text-align: left;
cursor: pointer;
transition: transform 120ms ease, border-color 120ms ease, background 120ms ease;
}
.location-button:hover {
transform: translateY(-1px);
border-color: rgba(118, 86, 216, 0.42);
}
.location-button.active {
border-color: var(--accent);
background: #f0ecff;
box-shadow: inset 0 0 0 1px rgba(118, 86, 216, 0.15);
}
.location-button strong {
display: block;
font-size: 11px;
}
.location-button span {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.location-note {
min-height: 34px;
margin: 9px 0 0;
padding: 8px 10px;
border-radius: 10px;
background: #f0f3f2;
color: #536476;
font-size: 10px;
line-height: 1.45;
}
.timeline {
display: grid;
grid-template-columns: auto 1fr auto;
gap: 9px;
align-items: center;
margin-top: 12px;
}
.timeline-track {
height: 7px;
overflow: hidden;
border-radius: 99px;
background: #dfe5e3;
}
#timeline-fill {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #7656d8, #a687ed);
}
#time-label {
color: var(--muted);
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.actions {
display: grid;
grid-template-columns: 1fr 1.3fr;
gap: 8px;
margin-top: 10px;
}
.action {
min-height: 38px;
padding: 8px 11px;
border: 1px solid var(--line);
border-radius: 11px;
background: white;
color: var(--ink);
font-size: 11px;
font-weight: 800;
cursor: pointer;
transition: transform 120ms ease, background 120ms ease;
}
.action:hover { transform: translateY(-1px); }
.action.primary { border-color: #7656d8; background: #7656d8; color: white; }
.dock {
position: fixed;
left: 18px;
bottom: 18px;
width: min(430px, calc(100vw - 36px));
padding: 15px 17px;
border: 1px solid var(--line);
border-radius: 18px;
background: var(--paper);
box-shadow: 0 12px 36px rgba(36, 57, 73, 0.13);
backdrop-filter: blur(12px);
pointer-events: none;
}
.rule {
display: grid;
grid-template-columns: 30px 1fr;
gap: 10px;
align-items: start;
}
.rule-number {
display: grid;
place-items: center;
width: 28px;
height: 28px;
border-radius: 9px;
background: #e9f5ef;
color: var(--good);
font-size: 12px;
font-weight: 900;
}
.rule p {
margin: 4px 0 0;
color: #526477;
font-size: 11px;
line-height: 1.45;
}
.rule p strong { color: var(--ink); }
.lock-line {
display: flex;
align-items: center;
gap: 7px;
margin-top: 11px;
padding-top: 10px;
border-top: 1px solid var(--line);
color: #596b7c;
font-size: 10px;
line-height: 1.4;
}
.lock-dot {
width: 8px;
height: 8px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--good);
box-shadow: 0 0 0 4px rgba(35, 133, 109, 0.11);
}
.camera-help {
position: fixed;
right: 22px;
bottom: 20px;
padding: 8px 11px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(250, 252, 247, 0.82);
color: #647487;
font-size: 10px;
pointer-events: none;
}
#camera-reset {
margin-left: 7px;
padding: 0;
border: 0;
background: transparent;
color: var(--accent);
font-size: 10px;
font-weight: 800;
cursor: pointer;
pointer-events: auto;
}
.fallback {
position: fixed;
inset: 0;
display: none;
place-items: center;
padding: 30px;
background: #eef4f4;
color: var(--ink);
text-align: center;
}
@media (max-width: 900px) {
.panel { width: 350px; }
.title-card, .dock { width: 350px; }
}
@media (max-width: 700px) {
.title-card {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 12px 14px;
}
.subtitle { display: none; }
.panel {
top: 112px;
right: 10px;
width: calc(100vw - 20px);
max-height: 33vh;
padding: 12px;
}
.comparison { margin: 8px 0 10px; }
.comparison-column { padding: 8px; }
.dock {
left: 10px;
bottom: 10px;
width: calc(100vw - 20px);
padding: 11px 13px;
}
.dock .small, .camera-help { display: none; }
.rule p { font-size: 10px; }
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel neighborhood morning survey"></canvas>
<header class="title-card">
<p class="eyebrow">Fictional neighborhood survey</p>
<h1>Voxel Morning Survey</h1>
<p class="subtitle">
Watch a fixed departure schedule meet a movable interviewer. The resident
roster is published in advance; only qualifying passers can enter the tray.
</p>
<div class="title-meta">
<span class="pill"><strong>Published roster: 120 residents</strong></span>
<span class="pill">Schedule <strong>S-0418</strong></span>
<span class="pill">Morning run <strong>12 seconds</strong></span>
</div>
</header>
<aside class="panel" aria-label="Population and sample comparison">
<div class="panel-head">
<div>
<h2>Population beside the sample</h2>
<div class="small">Fictional full roster versus residents actually sampled.</div>
</div>
<div class="sample-count" id="sample-count" aria-live="polite">0 / 24 sampled</div>
</div>
<div class="comparison">
<section class="comparison-column">
<div class="column-title">
<strong>Full population</strong>
<span>N = 120</span>
</div>
<div id="full-bars"></div>
</section>
<section class="comparison-column sample-column">
<div class="column-title">
<strong>Sample</strong>
<span id="sample-n">n = 0</span>
</div>
<div id="sample-bars"></div>
</section>
</div>
<div class="section-label">Relocate the interviewer</div>
<div class="locations">
<button class="location-button" data-location="west" aria-pressed="false">
<strong>West gate</strong>
<span>A route only</span>
</button>
<button class="location-button" data-location="east" aria-pressed="false">
<strong>East gate</strong>
<span>B route only</span>
</button>
<button class="location-button" data-location="cross" aria-pressed="false">
<strong>Crosswalk</strong>
<span>A + B routes</span>
</button>
<button class="location-button" data-location="bus" aria-pressed="true">
<strong>Bus stop</strong>
<span>All three routes</span>
</button>
</div>
<div class="location-note" id="location-note">
The bus stop receives all three walking routes, but the first 24 qualifying
crossings still determine the sample.
</div>
<div class="timeline">
<span class="small">Morning</span>
<div class="timeline-track"><div id="timeline-fill"></div></div>
<span id="time-label">0.0 / 12.0s</span>
</div>
<div class="actions">
<button class="action" id="play-button">Pause</button>
<button class="action primary" id="replay-button">Replay locked schedule</button>
</div>
<div class="small" id="sample-status" style="margin-top:8px" aria-live="polite">
Waiting for the first qualifying passer.
</div>
</aside>
<section class="dock" aria-label="Visible sampling rule">
<div class="rule">
<div class="rule-number">✓</div>
<div>
<h2>Selection rule stays visible</h2>
<p>
<strong>Qualify:</strong> pass within 2.0 m of the interviewer.
Then fill the tray with the <strong>first 24 qualifying residents</strong>.
Everyone else keeps walking.
</p>
</div>
</div>
<div class="lock-line">
<span class="lock-dot"></span>
<span>
Relocation changes who is encountered, but every departure time, walking
speed, and route is stored and replayed unchanged.
</span>
</div>
</section>
<div class="camera-help">
Drag to orbit · wheel to zoom · click a ring to relocate
<button id="camera-reset">Reset view</button>
</div>
<div class="fallback" id="fallback">
<div>
<h2>WebGL is unavailable</h2>
<p>This scene needs a browser with WebGL enabled.</p>
</div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Published fictional roster and deterministic movement schedule
// -------------------------------------------------------------------------
const GROUPS = [
{ id: "A", name: "Larkspur", symbol: "●", color: 0x147d92, css: "#147d92", count: 48 },
{ id: "B", name: "Juniper", symbol: "■", color: 0xe85d55, css: "#e85d55", count: 36 },
{ id: "C", name: "Clover", symbol: "▲", color: 0xd19a16, css: "#d19a16", count: 36 }
];
const TOTAL_POPULATION = GROUPS.reduce((sum, group) => sum + group.count, 0);
const SAMPLE_TARGET = 24;
const CAPTURE_RADIUS = 2.0;
const DURATION = 12.0;
const SCHEDULE_ID = "S-0418";
const canvas = document.getElementById("scene");
let renderer;
try {
renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
} catch (error) {
document.getElementById("fallback").style.display = "grid";
throw error;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce9ed);
scene.fog = new THREE.Fog(0xdce9ed, 39, 72);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
120
);
const cameraState = {
radius: 39,
theta: 0.72,
phi: 0.83,
target: new THREE.Vector3(0, 0, 0)
};
function updateCamera() {
const { radius, theta, phi, target } = cameraState;
camera.position.set(
target.x + radius * Math.sin(phi) * Math.sin(theta),
target.y + radius * Math.cos(phi),
target.z + radius * Math.sin(phi) * Math.cos(theta)
);
camera.lookAt(target);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xf4fbff, 0x84927d, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff1cf, 3.1);
sun.position.set(-13, 24, 16);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -27;
sun.shadow.camera.right = 27;
sun.shadow.camera.top = 22;
sun.shadow.camera.bottom = -22;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 65;
sun.shadow.normalBias = 0.035;
scene.add(sun);
const material = (color, roughness = 0.86, metalness = 0.0) =>
new THREE.MeshStandardMaterial({ color, roughness, metalness });
const mats = {
ground: material(0xcbd9bd),
road: material(0x46515a),
sidewalk: material(0xd8ddd5),
curb: material(0xf2eee3),
white: material(0xfaf7ed),
dark: material(0x273744),
wood: material(0x9a6b4d),
leaf: material(0x5d9869),
glass: new THREE.MeshStandardMaterial({
color: 0x9ed7dc,
roughness: 0.25,
metalness: 0.05,
emissive: 0x153d46,
emissiveIntensity: 0.12
}),
windowWarm: new THREE.MeshStandardMaterial({
color: 0xffd88c,
roughness: 0.4,
emissive: 0xffa83d,
emissiveIntensity: 0.2
})
};
function box(w, h, d, mat, x = 0, y = 0, z = 0, parent = scene) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), mat);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeTextSprite(text, options = {}) {
const image = document.createElement("canvas");
image.width = 512;
image.height = 128;
const context = image.getContext("2d");
context.clearRect(0, 0, 512, 128);
context.fillStyle = options.background || "rgba(24, 43, 58, 0.91)";
context.fillRect(0, 0, 512, 128);
context.strokeStyle = options.border || "rgba(255,255,255,0.24)";
context.lineWidth = 5;
context.strokeRect(3, 3, 506, 122);
context.fillStyle = options.color || "#ffffff";
context.font = `800 ${options.fontSize || 46}px system-ui, sans-serif`;
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 256, 66, 472);
const texture = new THREE.CanvasTexture(image);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: options.depthTest ?? false,
depthWrite: false
}));
const width = options.width || 5;
sprite.scale.set(width, width / 4, 1);
return sprite;
}
function makeSymbolTexture(group) {
const image = document.createElement("canvas");
image.width = 96;
image.height = 96;
const context = image.getContext("2d");
context.shadowColor = "rgba(0,0,0,0.35)";
context.shadowBlur = 8;
context.shadowOffsetY = 3;
context.fillStyle = group.css;
context.strokeStyle = "#ffffff";
context.lineWidth = 7;
context.lineJoin = "round";
context.beginPath();
if (group.id === "A") {
context.arc(48, 48, 29, 0, Math.PI * 2);
} else if (group.id === "B") {
context.rect(17, 17, 62, 62);
} else {
context.moveTo(48, 13);
context.lineTo(83, 78);
context.lineTo(13, 78);
context.closePath();
}
context.fill();
context.stroke();
const texture = new THREE.CanvasTexture(image);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
return texture;
}
const symbolTextures = new Map(
GROUPS.map(group => [group.id, makeSymbolTexture(group)])
);
// -------------------------------------------------------------------------
// Voxel environment
// -------------------------------------------------------------------------
box(46, 0.32, 29, mats.ground, 0, -0.22, 0);
box(44, 0.10, 5.8, mats.road, 0, -0.02, 0);
box(44, 0.13, 1.25, mats.sidewalk, 0, 0.015, -3.48);
box(44, 0.13, 1.25, mats.sidewalk, 0, 0.015, 3.48);
box(44, 0.16, 0.18, mats.curb, 0, 0.08, -2.86);
box(44, 0.16, 0.18, mats.curb, 0, 0.08, 2.86);
for (let x = -20; x <= 20; x += 2.15) {
box(0.95, 0.025, 0.12, mats.white, x, 0.06, 0);
}
// Zebra crossing at the common A/B intersection.
for (let z = -2.35; z <= 2.35; z += 0.68) {
box(2.6, 0.028, 0.34, mats.white, 0, 0.075, z);
}
function addTree(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0, z);
scene.add(group);
box(0.28 * scale, 1.45 * scale, 0.28 * scale, mats.wood, 0, 0.72 * scale, 0, group);
box(1.25 * scale, 0.85 * scale, 1.05 * scale, mats.leaf, 0, 1.55 * scale, 0, group);
box(0.75 * scale, 0.65 * scale, 0.78 * scale, mats.leaf, -0.25 * scale, 2.05 * scale, 0.06 * scale, group);
}
function addHouse(x, z, width, depth, height, roofColor, index) {
const group = new THREE.Group();
group.position.set(x, 0.08, z);
scene.add(group);
const wallColors = [0xf3e4ca, 0xe5dfce, 0xf0cdbb, 0xe5e9d8];
const wall = material(wallColors[index % wallColors.length]);
const roof = material(roofColor);
box(width, height, depth, wall, 0, height / 2, 0, group);
box(width * 0.78, 0.30, depth * 0.78, roof, 0, height + 0.15, 0, group);
box(width * 0.48, 0.26, depth * 0.48, roof, 0, height + 0.42, 0, group);
const windowMat = index % 3 === 0 ? mats.windowWarm : mats.glass;
box(0.36, 0.48, 0.05, windowMat, -width * 0.25, height * 0.57, depth / 2 + 0.03, group);
box(0.36, 0.48, 0.05, windowMat, width * 0.25, height * 0.57, depth / 2 + 0.03, group);
box(0.42, 0.86, 0.06, mats.dark, 0, 0.44, depth / 2 + 0.04, group);
box(width * 0.18, 0.22, depth * 0.18, mats.curb, width * 0.25, 0.11, depth / 2 + 0.24, group);
}
function addBlock(groupIndex, centerX, centerZ, sizeX, sizeZ) {
const group = GROUPS[groupIndex];
const platformColor = material(new THREE.Color(group.color).lerp(new THREE.Color(0xf3eee0), 0.82));
box(sizeX, 0.16, sizeZ, platformColor, centerX, 0.02, centerZ);
const houseXs = groupIndex === 2
? [-2.4, 0, 2.4]
: [-2.4, 0, 2.4];
let index = groupIndex * 2;
for (const dx of houseXs) {
for (const dz of [-1.55, 1.55]) {
addHouse(
centerX + dx,
centerZ + dz,
1.55 + (index % 2) * 0.12,
1.40,
1.55 + ((index + 1) % 3) * 0.33,
group.color,
index++
);
}
}
const label = makeTextSprite(
`${group.symbol} ${group.id} · ${group.name.toUpperCase()} · ${group.count}`,
{
width: 6.2,
background: "rgba(25, 44, 58, 0.93)",
border: group.css,
fontSize: 40
}
);
label.position.set(centerX, 4.15, centerZ);
scene.add(label);
addTree(centerX - sizeX / 2 + 0.55, centerZ + sizeZ / 2 - 0.7, 0.82);
addTree(centerX + sizeX / 2 - 0.65, centerZ + sizeZ / 2 - 0.75, 0.74);
}
addBlock(0, -10, -8.5, 8.2, 7.0);
addBlock(1, 10, -8.5, 8.2, 7.0);
addBlock(2, -7.5, 8.6, 8.2, 7.0);
addTree(-15.3, 3.6, 0.9);
addTree(14.2, 3.7, 0.95);
addTree(12.7, -3.8, 0.72);
const rosterSign = makeTextSprite("PUBLISHED FICTIONAL ROSTER · 120", {
width: 7.2,
background: "rgba(28, 54, 67, 0.94)",
border: "#d9eee8",
fontSize: 42
});
rosterSign.position.set(1.0, 3.7, -4.3);
scene.add(rosterSign);
box(0.18, 3.2, 0.18, mats.dark, 1.0, 1.6, -4.3);
// -------------------------------------------------------------------------
// Routes, interviewer positions, bus stop
// -------------------------------------------------------------------------
const vector = (x, z) => new THREE.Vector3(x, 0, z);
const BUS_POINT = vector(-0.8, 4.7);
const ROUTES = [
[
vector(-6.7, -5.3),
vector(-5.0, -2.4),
vector(-2.0, -0.8),
vector(0.0, 0.0),
vector(-0.8, 2.5),
BUS_POINT
],
[
vector(6.7, -5.3),
vector(5.0, -2.4),
vector(2.0, -0.8),
vector(0.0, 0.0),
vector(-0.8, 2.5),
BUS_POINT
],
[
vector(-5.5, 6.0),
vector(-8.0, 6.3),
vector(-9.0, 5.0),
vector(-9.0, 3.5),
vector(-8.0, 2.8),
vector(-6.0, 3.0),
vector(-5.5, 4.2),
vector(-3.8, 4.7),
BUS_POINT
]
];
const LOCATIONS = {
west: {
name: "West gate",
exposure: "A route only",
position: vector(-5.0, -2.4),
trayOffset: new THREE.Vector3(2.7, 0, 0.5),
note: "The west gate is encountered only by residents leaving Larkspur block A."
},
east: {
name: "East gate",
exposure: "B route only",
position: vector(5.0, -2.4),
trayOffset: new THREE.Vector3(2.7, 0, 0.5),
note: "The east gate is encountered only by residents leaving Juniper block B."
},
cross: {
name: "Crosswalk",
exposure: "A + B routes",
position: vector(0.0, 0.0),
trayOffset: new THREE.Vector3(3.0, 0, 2.6),
note: "Both northern routes use the crosswalk. The block C route never reaches it."
},
bus: {
name: "Bus stop",
exposure: "All three routes",
position: BUS_POINT.clone(),
trayOffset: new THREE.Vector3(3.0, 0, 0.1),
note: "The bus stop receives all three routes, but the first 24 qualifying crossings determine the sample."
}
};
function addRoute(points, group) {
const linePoints = points.map(point => new THREE.Vector3(point.x, 0.075, point.z));
const geometry = new THREE.BufferGeometry().setFromPoints(linePoints);
const lineMaterial = new THREE.LineDashedMaterial({
color: group.color,
dashSize: 0.42,
gapSize: 0.20,
transparent: true,
opacity: 0.82
});
const line = new THREE.Line(geometry, lineMaterial);
line.computeLineDistances();
scene.add(line);
const dotPositions = [];
for (let index = 0; index < points.length - 1; index++) {
const a = points[index];
const b = points[index + 1];
const dx = b.x - a.x;
const dz = b.z - a.z;
const length = Math.hypot(dx, dz);
const steps = Math.ceil(length / 0.44);
for (let step = 0; step < steps; step++) {
const t = step / steps;
dotPositions.push({
x: a.x + dx * t,
z: a.z + dz * t,
angle: Math.atan2(dx, dz)
});
}
}
const dots = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.17, 0.035, 0.31),
material(group.color),
dotPositions.length
);
const dummy = new THREE.Object3D();
dotPositions.forEach((dot, index) => {
dummy.position.set(dot.x, 0.09, dot.z);
dummy.rotation.set(0, dot.angle, 0);
dummy.updateMatrix();
dots.setMatrixAt(index, dummy.matrix);
});
dots.instanceMatrix.needsUpdate = true;
dots.receiveShadow = true;
scene.add(dots);
}
GROUPS.forEach((group, index) => addRoute(ROUTES[index], group));
// Bus shelter beside the southern block.
const shelter = new THREE.Group();
shelter.position.copy(BUS_POINT).add(new THREE.Vector3(-1.8, 0, 0));
scene.add(shelter);
box(2.8, 0.20, 1.65, mats.dark, 0, 2.35, 0, shelter);
box(2.4, 0.06, 1.35, mats.glass, 0, 2.22, 0, shelter);
box(0.14, 2.25, 0.14, mats.dark, -1.25, 1.12, -0.65, shelter);
box(0.14, 2.25, 0.14, mats.dark, 1.25, 1.12, -0.65, shelter);
box(0.14, 2.25, 0.14, mats.dark, -1.25, 1.12, 0.65, shelter);
box(0.14, 2.25, 0.14, mats.dark, 1.25, 1.12, 0.65, shelter);
box(2.0, 0.16, 0.46, mats.wood, 0, 0.72, 0.46, shelter);
const busSign = makeTextSprite("BUS STOP", {
width: 2.5,
background: "rgba(28, 54, 67, 0.95)",
border: "#f4d66d",
fontSize: 54
});
busSign.position.set(0, 3.0, 0);
shelter.add(busSign);
// -------------------------------------------------------------------------
// Relocation markers
// -------------------------------------------------------------------------
const locationMarkers = {};
const markerHitTargets = [];
for (const [id, location] of Object.entries(LOCATIONS)) {
const group = new THREE.Group();
group.position.copy(location.position);
scene.add(group);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(1.05, 0.09, 10, 42),
new THREE.MeshStandardMaterial({
color: 0xffffff,
emissive: 0xffffff,
emissiveIntensity: 0.18,
roughness: 0.45
})
);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.15;
group.add(ring);
const hit = new THREE.Mesh(
new THREE.CylinderGeometry(1.25, 1.25, 1.5, 16),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false
})
);
hit.position.y = 0.75;
hit.userData.locationId = id;
group.add(hit);
markerHitTargets.push(hit);
const label = makeTextSprite(`${location.name.toUpperCase()} · ${location.exposure}`, {
width: 4.7,
background: "rgba(26, 48, 63, 0.84)",
border: id === "bus" ? "#f4d66d" : "#b8cbd1",
fontSize: 36
});
label.position.set(0, 1.35, 0);
group.add(label);
locationMarkers[id] = { group, ring, label };
}
// -------------------------------------------------------------------------
// Interviewer, visible capture radius, and physical sample tray
// -------------------------------------------------------------------------
const interviewer = new THREE.Group();
scene.add(interviewer);
const interviewerBody = material(0xe95e5b);
const interviewerPants = material(0x30455a);
box(0.72, 0.90, 0.46, interviewerBody, 0, 0.78, 0, interviewer);
box(0.26, 0.58, 0.28, interviewerPants, -0.21, 0.29, 0, interviewer);
box(0.26, 0.58, 0.28, interviewerPants, 0.21, 0.29, 0, interviewer);
box(0.34, 0.34, 0.34, material(0xe5b18e), 0, 1.42, 0, interviewer);
box(0.38, 0.18, 0.38, material(0x593b35), 0, 1.62, 0, interviewer);
const clipboard = box(0.38, 0.48, 0.07, mats.white, 0.48, 0.90, 0.14, interviewer);
clipboard.rotation.z = -0.12;
const interviewerLabel = makeTextSprite("INTERVIEWER", {
width: 2.8,
background: "rgba(118, 86, 216, 0.95)",
border: "#ffffff",
fontSize: 45
});
interviewerLabel.position.set(0, 2.15, 0);
interviewer.add(interviewerLabel);
const captureRing = new THREE.Mesh(
new THREE.CircleGeometry(CAPTURE_RADIUS, 64),
new THREE.MeshBasicMaterial({
color: 0x5bcaa8,
transparent: true,
opacity: 0.15,
side: THREE.DoubleSide,
depthWrite: false
})
);
captureRing.rotation.x = -Math.PI / 2;
captureRing.position.y = 0.11;
scene.add(captureRing);
const captureEdge = new THREE.Mesh(
new THREE.RingGeometry(CAPTURE_RADIUS - 0.045, CAPTURE_RADIUS, 64),
new THREE.MeshBasicMaterial({
color: 0x2b9a78,
transparent: true,
opacity: 0.72,
side: THREE.DoubleSide,
depthWrite: false
})
);
captureEdge.rotation.x = -Math.PI / 2;
captureEdge.position.y = 0.12;
scene.add(captureEdge);
const tray = new THREE.Group();
scene.add(tray);
box(4.25, 0.14, 2.05, material(0x8d6aaf), 0, 0.08, 0, tray);
box(4.35, 0.23, 0.10, material(0x62478a), 0, 0.22, -1.02, tray);
box(4.35, 0.23, 0.10, material(0x62478a), 0, 0.22, 1.02, tray);
box(0.10, 0.23, 2.08, material(0x62478a), -2.15, 0.22, 0, tray);
box(0.10, 0.23, 2.08, material(0x62478a), 2.15, 0.22, 0, tray);
const trayLabel = makeTextSprite("SAMPLE TRAY · 24 SLOTS", {
width: 4.0,
background: "rgba(83, 55, 126, 0.95)",
border: "#d9c8ff",
fontSize: 39
});
trayLabel.position.set(0, 1.42, 0);
tray.add(trayLabel);
// -------------------------------------------------------------------------
// Resident tokens
// -------------------------------------------------------------------------
const residentBodyGeometry = new THREE.BoxGeometry(0.42, 0.72, 0.31);
const residentHeadGeometry = new THREE.BoxGeometry(0.29, 0.29, 0.29);
const groupBodyMaterials = new Map(
GROUPS.map(group => [group.id, material(group.color)])
);
const headMaterial = material(0xe7b693);
const badgeMaterials = new Map(
GROUPS.map(group => [
group.id,
new THREE.SpriteMaterial({
map: symbolTextures.get(group.id),
transparent: true,
depthWrite: false
})
])
);
let randomSeed = 418;
function random() {
randomSeed = (randomSeed * 1664525 + 1013904223) >>> 0;
return randomSeed / 4294967296;
}
function preparePathData(path) {
const cumulative = [0];
let total = 0;
for (let index = 0; index < path.length - 1; index++) {
total += path[index].distanceTo(path[index + 1]);
cumulative.push(total);
}
return { path, cumulative, total };
}
function positionOnPath(pathData, distance) {
const { path, cumulative, total } = pathData;
if (distance <= 0) {
const direction = path[1].clone().sub(path[0]).normalize();
return { position: path[0].clone(), direction };
}
if (distance >= total) {
const direction = path[path.length - 1].clone()
.sub(path[path.length - 2]).normalize();
return { position: path[path.length - 1].clone(), direction };
}
for (let index = 0; index < path.length - 1; index++) {
if (distance <= cumulative[index + 1]) {
const segmentLength = cumulative[index + 1] - cumulative[index];
const t = (distance - cumulative[index]) / segmentLength;
const position = path[index].clone().lerp(path[index + 1], t);
const direction = path[index + 1].clone().sub(path[index]).normalize();
return { position, direction };
}
}
return { position: path[path.length - 1].clone(), direction: new THREE.Vector3(0, 0, 1) };
}
const residents = [];
let residentId = 0;
GROUPS.forEach((group, groupIndex) => {
for (let index = 0; index < group.count; index++) {
const root = new THREE.Group();
scene.add(root);
const body = new THREE.Mesh(residentBodyGeometry, groupBodyMaterials.get(group.id));
body.position.y = 0.48;
body.castShadow = true;
root.add(body);
const head = new THREE.Mesh(residentHeadGeometry, headMaterial);
head.position.y = 1.02;
head.castShadow = true;
root.add(head);
const badge = new THREE.Sprite(badgeMaterials.get(group.id));
badge.position.y = 1.48;
badge.scale.set(0.65, 0.65, 1);
root.add(badge);
let start;
if (groupIndex === 0) {
start = vector(-6.7 + (random() - 0.5) * 1.7, -5.4 + (random() - 0.5) * 1.1);
} else if (groupIndex === 1) {
start = vector(6.7 + (random() - 0.5) * 1.7, -5.4 + (random() - 0.5) * 1.1);
} else {
start = vector(-5.5 + (random() - 0.5) * 1.5, 5.9 + (random() - 0.5) * 0.8);
}
const path = [start, ...ROUTES[groupIndex].map(point => point.clone())];
const pathData = preparePathData(path);
const startDelay =
groupIndex === 0 ? 0.12 + index * 0.115 + random() * 0.08 :
groupIndex === 1 ? 0.25 + index * 0.145 + random() * 0.08 :
0.70 + index * 0.120 + random() * 0.08;
residents.push({
id: residentId++,
groupIndex,
group,
root,
pathData,
startDelay,
speed: 2.55 + random() * 0.45,
selected: false,
trayed: false,
entryElapsed: 0,
entryFrom: new THREE.Vector3(),
entryTarget: new THREE.Vector3()
});
}
});
function residentPosition(resident, time) {
const elapsed = Math.max(0, time - resident.startDelay);
const distance = elapsed * resident.speed;
return positionOnPath(resident.pathData, distance);
}
// -------------------------------------------------------------------------
// Deterministic crossing calculation
//
// Each resident's nearest approach to the current interviewer location is
// calculated from their stored path. Events are sorted by crossing time,
// and only the first 24 are planned for the tray. This makes replay
// independent of frame rate and ensures relocation uses the same schedule.
// -------------------------------------------------------------------------
function nearestApproach(resident, marker) {
const { path, cumulative } = resident.pathData;
let best = { distance: Infinity, time: Infinity };
for (let index = 0; index < path.length - 1; index++) {
const a = path[index];
const b = path[index + 1];
const abx = b.x - a.x;
const abz = b.z - a.z;
const lengthSquared = abx * abx + abz * abz;
if (lengthSquared === 0) continue;
const t = THREE.MathUtils.clamp(
((marker.x - a.x) * abx + (marker.z - a.z) * abz) / lengthSquared,
0,
1
);
const closestX = a.x + abx * t;
const closestZ = a.z + abz * t;
const distance = Math.hypot(marker.x - closestX, marker.z - closestZ);
const distanceAlongPath = cumulative[index] +
t * Math.sqrt(lengthSquared);
const time = resident.startDelay + distanceAlongPath / resident.speed;
if (distance < best.distance) {
best = { distance, time };
}
}
return best;
}
let currentLocationId = "bus";
let plannedEvents = [];
let eventIndex = 0;
let simulationTime = 0;
let playing = true;
let complete = false;
let sampleCount = 0;
const sampleCounts = [0, 0, 0];
function buildPlannedEvents() {
const marker = LOCATIONS[currentLocationId].position;
const events = [];
for (const resident of residents) {
const approach = nearestApproach(resident, marker);
if (approach.distance <= CAPTURE_RADIUS + 0.0001) {
events.push({
resident,
time: approach.time,
slot: -1
});
}
}
events.sort((a, b) => a.time - b.time || a.resident.id - b.resident.id);
events.slice(0, SAMPLE_TARGET).forEach((event, index) => {
event.slot = index;
});
return events.slice(0, SAMPLE_TARGET);
}
function resetResidents() {
sampleCount = 0;
eventIndex = 0;
sampleCounts.fill(0);
simulationTime = 0;
playing = true;
complete = false;
for (const resident of residents) {
resident.selected = false;
resident.trayed = false;
resident.entryElapsed = 0;
resident.root.position.copy(resident.pathData.path[0]);
resident.root.position.y = 0.06;
resident.root.rotation.set(0, 0, 0);
resident.root.scale.setScalar(0.72);
}
plannedEvents = buildPlannedEvents();
updatePlayButton();
renderComparison();
updateStatus();
}
function setLocation(id, replay = true) {
currentLocationId = id;
const location = LOCATIONS[id];
interviewer.position.copy(location.position);
interviewer.position.y = 0;
captureRing.position.set(location.position.x, 0.11, location.position.z);
captureEdge.position.set(location.position.x, 0.12, location.position.z);
tray.position.copy(location.position).add(location.trayOffset);
tray.position.y = 0;
for (const [markerId, marker] of Object.entries(locationMarkers)) {
const active = markerId === id;
marker.ring.material.color.set(active ? 0xf4c45d : 0xffffff);
marker.ring.material.emissive.set(active ? 0x8c6411 : 0xffffff);
marker.ring.material.emissiveIntensity = active ? 0.65 : 0.12;
marker.ring.scale.setScalar(active ? 1.10 : 1.0);
}
document.querySelectorAll(".location-button").forEach(button => {
const active = button.dataset.location === id;
button.classList.toggle("active", active);
button.setAttribute("aria-pressed", String(active));
});
document.getElementById("location-note").textContent = location.note;
resetResidents();
if (!replay) {
playing = false;
updatePlayButton();
}
}
function captureResident(event) {
const resident = event.resident;
if (resident.selected || sampleCount >= SAMPLE_TARGET) return;
const crossingPosition = residentPosition(resident, event.time).position;
crossingPosition.y = 0.06;
resident.root.position.copy(crossingPosition);
resident.root.rotation.y = Math.atan2(
residentPosition(resident, event.time).direction.x,
residentPosition(resident, event.time).direction.z
);
const column = event.slot % 8;
const row = Math.floor(event.slot / 8);
resident.entryFrom.copy(crossingPosition);
resident.entryTarget.set(
tray.position.x + (column - 3.5) * 0.48,
0.16,
tray.position.z + (row - 1) * 0.48
);
resident.selected = true;
resident.entryElapsed = 0;
sampleCount++;
sampleCounts[resident.groupIndex]++;
updateStatus();
renderComparison();
}
function updateEntry(resident, dt) {
resident.entryElapsed += dt;
const t = THREE.MathUtils.clamp(resident.entryElapsed / 0.82, 0, 1);
const eased = 1 - Math.pow(1 - t, 3);
resident.root.position.lerpVectors(resident.entryFrom, resident.entryTarget, eased);
resident.root.position.y += Math.sin(t * Math.PI) * 0.42;
resident.root.scale.setScalar(THREE.MathUtils.lerp(0.72, 0.46, eased));
if (t >= 1) {
resident.trayed = true;
resident.root.position.copy(resident.entryTarget);
resident.root.scale.setScalar(0.46);
}
}
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
function makeBarRows(container, sample) {
container.innerHTML = "";
GROUPS.forEach((group, index) => {
const row = document.createElement("div");
row.className = "bar-row";
row.style.setProperty("--group-color", group.css);
row.innerHTML = `
<span class="symbol" aria-label="${group.name} ${group.id}">${group.symbol}</span>
<span class="group-name">${group.name} (${group.id})</span>
<span class="metric" data-metric="${index}"></span>
<div class="track"><div class="fill" data-fill="${index}"></div></div>
`;
container.appendChild(row);
});
}
makeBarRows(document.getElementById("full-bars"), false);
makeBarRows(document.getElementById("sample-bars"), true);
function renderComparison() {
GROUPS.forEach((group, index) => {
const fullPercent = group.count / TOTAL_POPULATION * 100;
const fullMetric = document.querySelector(`#full-bars [data-metric="${index}"]`);
const fullFill = document.querySelector(`#full-bars [data-fill="${index}"]`);
fullMetric.textContent = `${group.count} · ${fullPercent.toFixed(1)}%`;
fullFill.style.width = `${fullPercent}%`;
const sampleMetric = document.querySelector(`#sample-bars [data-metric="${index}"]`);
const sampleFill = document.querySelector(`#sample-bars [data-fill="${index}"]`);
const samplePercent = sampleCount ? sampleCounts[index] / sampleCount * 100 : 0;
sampleMetric.textContent = sampleCount
? `${sampleCounts[index]} · ${samplePercent.toFixed(1)}%`
: "0 · 0.0%";
sampleFill.style.width = `${samplePercent}%`;
});
document.getElementById("sample-count").textContent = `${sampleCount} / ${SAMPLE_TARGET} sampled`;
document.getElementById("sample-n").textContent = `n = ${sampleCount}`;
}
function updateStatus() {
const status = document.getElementById("sample-status");
if (sampleCount === 0) {
status.textContent = `At ${LOCATIONS[currentLocationId].name}: waiting for the first qualifying passer.`;
} else if (sampleCount < SAMPLE_TARGET) {
status.textContent = `${sampleCount} qualifying residents have entered the tray; later arrivals can still qualify.`;
} else {
status.textContent = "Tray full at 24. Later passers keep walking but are not sampled.";
}
}
function updatePlayButton() {
const button = document.getElementById("play-button");
button.textContent = complete ? "Replay" : playing ? "Pause" : "Resume";
}
document.querySelectorAll(".location-button").forEach(button => {
button.addEventListener("click", () => setLocation(button.dataset.location, true));
});
document.getElementById("replay-button").addEventListener("click", () => {
resetResidents();
});
document.getElementById("play-button").addEventListener("click", () => {
if (complete) {
resetResidents();
} else {
playing = !playing;
updatePlayButton();
}
});
// -------------------------------------------------------------------------
// Direct camera controls and marker picking
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let pointerDown = false;
let pointerMoved = false;
let pointerX = 0;
let pointerY = 0;
canvas.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
pointerDown = true;
pointerMoved = false;
pointerX = event.clientX;
pointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
if (!pointerDown) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
if (Math.abs(dx) + Math.abs(dy) > 2) pointerMoved = true;
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.42,
1.23
);
pointerX = event.clientX;
pointerY = event.clientY;
updateCamera();
});
canvas.addEventListener("pointerup", event => {
if (!pointerDown) return;
pointerDown = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
if (!pointerMoved) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(markerHitTargets, false);
if (hits.length) {
setLocation(hits[0].object.userData.locationId, true);
}
}
});
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.025,
23,
57
);
updateCamera();
}, { passive: false });
canvas.addEventListener("contextmenu", event => event.preventDefault());
document.getElementById("camera-reset").addEventListener("click", () => {
cameraState.radius = 39;
cameraState.theta = 0.72;
cameraState.phi = 0.83;
cameraState.target.set(0, 0, 0);
updateCamera();
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
// -------------------------------------------------------------------------
// Simulation loop
// -------------------------------------------------------------------------
setLocation("bus", false);
resetResidents();
let previousTime = performance.now();
function animate(now) {
requestAnimationFrame(animate);
const dt = Math.min(0.05, (now - previousTime) / 1000);
previousTime = now;
if (playing) {
simulationTime = Math.min(DURATION, simulationTime + dt);
}
while (
eventIndex < plannedEvents.length &&
plannedEvents[eventIndex].time <= simulationTime + 0.00001
) {
captureResident(plannedEvents[eventIndex]);
eventIndex++;
}
for (const resident of residents) {
if (resident.selected) {
if (!resident.trayed) updateEntry(resident, dt);
} else {
const motion = residentPosition(resident, simulationTime);
resident.root.position.copy(motion.position);
resident.root.position.y = 0.06;
resident.root.rotation.y = Math.atan2(motion.direction.x, motion.direction.z);
}
}
if (simulationTime >= DURATION && !complete) {
complete = true;
playing = false;
updatePlayButton();
}
document.getElementById("timeline-fill").style.width =
`${simulationTime / DURATION * 100}%`;
document.getElementById("time-label").textContent =
`${simulationTime.toFixed(1)} / ${DURATION.toFixed(1)}s`;
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```