Prompt specification
Build or customize the Three.js 3D scene "Population tokens passing a narrow gate" 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: Population tokens passing a narrow gate
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/population-tokens-passing-a-narrow-gate-x0885
Scene Description Prompt:
Illustrate a genetic bottleneck by randomly passing marked population tokens through a narrow gate. Low-poly Three.js from cdnjs, one HTML file.
Working Three.js Starter (population-tokens-passing-a-narrow-gate-x0885):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>The Genetic Bottleneck</title>
<style>
:root {
--ink: #20333d;
--muted: #6c797b;
--paper: #f2eee5;
--card: rgba(250, 247, 239, 0.9);
--teal: #258f83;
--coral: #df654f;
--amber: #e8ad45;
--line: rgba(32, 51, 61, 0.13);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--paper);
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
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;
}
.ui {
position: fixed;
inset: 0;
pointer-events: none;
}
header {
position: absolute;
top: 28px;
left: 30px;
width: min(490px, calc(100vw - 60px));
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 12px;
color: var(--teal);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.eyebrow::before {
width: 26px;
height: 2px;
content: "";
background: currentColor;
}
h1 {
max-width: 460px;
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(37px, 4.2vw, 62px);
font-weight: 500;
line-height: 0.94;
letter-spacing: -0.045em;
}
.intro {
max-width: 430px;
margin: 17px 0 0;
color: #526166;
font-size: 14px;
line-height: 1.55;
}
.panel {
position: absolute;
top: 24px;
right: 24px;
width: 330px;
padding: 18px;
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.75);
border-radius: 20px;
background: var(--card);
box-shadow:
0 18px 55px rgba(41, 54, 57, 0.13),
inset 0 0 0 1px var(--line);
backdrop-filter: blur(15px);
pointer-events: auto;
}
.panel-top {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 15px;
}
.panel-label {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.live-badge {
display: flex;
align-items: center;
gap: 7px;
padding: 6px 9px;
border-radius: 999px;
background: rgba(37, 143, 131, 0.09);
color: var(--teal);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.live-badge::before {
width: 6px;
height: 6px;
border-radius: 50%;
content: "";
background: var(--teal);
box-shadow: 0 0 0 4px rgba(37, 143, 131, 0.11);
animation: breathe 1.6s ease-in-out infinite;
}
@keyframes breathe {
50% {
opacity: 0.45;
transform: scale(0.82);
}
}
.status-row {
display: flex;
align-items: center;
gap: 9px;
min-height: 38px;
margin-bottom: 13px;
font-size: 13px;
font-weight: 700;
line-height: 1.35;
}
.status-dot {
flex: 0 0 auto;
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--amber);
box-shadow: 0 0 0 5px rgba(232, 173, 69, 0.13);
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
}
.stat {
padding: 11px 9px 10px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.42);
}
.stat span {
display: block;
margin-bottom: 6px;
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.stat strong {
font-family: Georgia, "Times New Roman", serif;
font-size: 23px;
font-weight: 500;
letter-spacing: -0.035em;
}
.progress-wrap {
margin: 14px 0 16px;
}
.progress-label {
display: flex;
justify-content: space-between;
margin-bottom: 7px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
}
.progress-track {
height: 6px;
overflow: hidden;
border-radius: 999px;
background: rgba(32, 51, 61, 0.09);
}
#progressFill {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--teal), #70b8a2);
transition: width 250ms ease;
}
.diversity {
padding: 13px;
border-radius: 13px;
background: rgba(37, 143, 131, 0.065);
}
.diversity-top {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 12px;
}
.diversity-title {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#diversityValue {
font-family: Georgia, "Times New Roman", serif;
font-size: 29px;
line-height: 1;
}
.diversity-bar {
height: 5px;
margin: 11px 0 8px;
overflow: hidden;
border-radius: 999px;
background: rgba(32, 51, 61, 0.09);
}
#diversityBar {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--coral), #efac7c);
transition: width 300ms ease;
}
.diversity-note {
color: var(--muted);
font-size: 9px;
line-height: 1.45;
}
.controls {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 13px;
}
button {
min-height: 39px;
border: 0;
border-radius: 11px;
cursor: pointer;
font-size: 11px;
font-weight: 800;
transition:
transform 150ms ease,
opacity 150ms ease,
background 150ms ease;
}
button:hover:not(:disabled) {
transform: translateY(-1px);
}
button:active:not(:disabled) {
transform: translateY(0);
}
button:disabled {
cursor: default;
opacity: 0.55;
}
#pauseBtn {
background: var(--ink);
color: #fff;
}
#resetBtn {
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.55);
color: var(--ink);
}
.speed-row {
display: flex;
align-items: center;
gap: 11px;
margin-top: 14px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
}
#speed {
flex: 1;
height: 4px;
appearance: none;
border-radius: 999px;
outline: none;
background: rgba(32, 51, 61, 0.12);
cursor: pointer;
}
#speed::-webkit-slider-thumb {
width: 15px;
height: 15px;
appearance: none;
border: 3px solid var(--paper);
border-radius: 50%;
background: var(--ink);
box-shadow: 0 1px 5px rgba(0, 0, 0, 0.2);
}
#speed::-moz-range-thumb {
width: 10px;
height: 10px;
border: 3px solid var(--paper);
border-radius: 50%;
background: var(--ink);
}
#speedLabel {
width: 30px;
color: var(--ink);
text-align: right;
}
.legend {
position: absolute;
bottom: 24px;
left: 30px;
width: 285px;
padding: 14px 16px;
border: 1px solid rgba(255, 255, 255, 0.65);
border-radius: 15px;
background: rgba(250, 247, 239, 0.82);
box-shadow: 0 12px 35px rgba(41, 54, 57, 0.09);
backdrop-filter: blur(12px);
}
.legend-title {
margin-bottom: 9px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.alleles {
display: flex;
gap: 7px;
margin-bottom: 10px;
}
.allele {
width: 20px;
height: 20px;
border: 2px solid rgba(255, 255, 255, 0.8);
border-radius: 50%;
box-shadow: 0 2px 5px rgba(32, 51, 61, 0.12);
}
.legend p {
margin: 0;
color: #59696d;
font-size: 10px;
line-height: 1.5;
}
.caption {
position: absolute;
right: 28px;
bottom: 27px;
max-width: 330px;
color: rgba(32, 51, 61, 0.67);
font-size: 11px;
line-height: 1.55;
text-align: right;
}
.caption strong {
color: var(--ink);
}
.camera-hint {
position: absolute;
left: 50%;
bottom: 27px;
transform: translateX(-50%);
color: rgba(32, 51, 61, 0.48);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.025em;
white-space: nowrap;
}
@media (max-width: 850px) {
header {
top: 19px;
left: 19px;
}
h1 {
font-size: 38px;
}
.intro {
max-width: 360px;
margin-top: 11px;
font-size: 12px;
}
.panel {
top: auto;
right: 14px;
bottom: 14px;
left: 14px;
width: auto;
padding: 14px;
border-radius: 17px;
}
.legend,
.caption,
.camera-hint {
display: none;
}
.panel-top,
.status-row {
margin-bottom: 9px;
}
.stats {
gap: 6px;
}
.stat {
padding: 8px;
}
.stat strong {
font-size: 19px;
}
.progress-wrap {
margin: 10px 0;
}
.diversity {
padding: 10px;
}
}
@media (max-width: 520px) {
header {
width: calc(100vw - 38px);
}
h1 {
max-width: 310px;
font-size: 33px;
}
.intro {
max-width: 315px;
}
.panel {
max-height: 47vh;
overflow-y: auto;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="ui">
<header>
<div class="eyebrow">Population genetics · Interactive model</div>
<h1>The Genetic<br />Bottleneck</h1>
<p class="intro">
A narrow gate samples a population at random. The few survivors may carry
only a fraction of the original genetic variation.
</p>
</header>
<section class="panel" aria-label="Simulation controls and statistics">
<div class="panel-top">
<span class="panel-label">Founder event</span>
<span class="live-badge">Running</span>
</div>
<div class="status-row" aria-live="polite">
<span class="status-dot" id="statusDot"></span>
<span id="statusText">Preparing the population…</span>
</div>
<div class="stats">
<div class="stat">
<span>Source</span>
<strong>96</strong>
</div>
<div class="stat">
<span>Founders</span>
<strong id="founderCount">0 / 12</strong>
</div>
<div class="stat">
<span>Gate</span>
<strong>1</strong>
</div>
</div>
<div class="progress-wrap">
<div class="progress-label">
<span>Random passage</span>
<span id="progressText">0%</span>
</div>
<div class="progress-track">
<div id="progressFill"></div>
</div>
</div>
<div class="diversity">
<div class="diversity-top">
<span class="diversity-title">Genetic diversity retained</span>
<strong id="diversityValue">—</strong>
</div>
<div class="diversity-bar">
<div id="diversityBar"></div>
</div>
<div class="diversity-note">
Expected heterozygosity across five loci, relative to the source population.
</div>
</div>
<div class="controls">
<button id="pauseBtn" type="button">Pause</button>
<button id="resetBtn" type="button">New bottleneck</button>
</div>
<label class="speed-row" for="speed">
<span>Speed</span>
<input id="speed" type="range" min="1" max="4" step="1" value="2" />
<span id="speedLabel">2×</span>
</label>
</section>
<aside class="legend">
<div class="legend-title">Allele markers</div>
<div class="alleles" id="alleles"></div>
<p>
Each token carries five marked loci. A random small sample can lose
alleles by chance—an early step in the founder effect.
</p>
</aside>
<div class="caption">
<strong>Drag</strong> to orbit · <strong>Scroll</strong> to zoom ·
<strong>Shift-drag</strong> to pan
</div>
<div class="camera-hint">Drag to orbit · Scroll to zoom · Shift-drag to pan</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene
// -------------------------------------------------------------------------
const sceneHost = document.getElementById("scene");
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.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute(
"aria-label",
"Interactive 3D genetic bottleneck simulation"
);
sceneHost.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xf1ede4);
scene.fog = new THREE.Fog(0xf1ede4, 25, 49);
const camera = new THREE.PerspectiveCamera(
40,
window.innerWidth / window.innerHeight,
0.1,
120
);
const cameraState = {
theta: 0.34,
phi: 1.03,
radius: 21,
target: new THREE.Vector3(0, 0.85, 0),
touched: false
};
const hemisphere = new THREE.HemisphereLight(0xffffff, 0x7f8175, 2.25);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff4dc, 3.2);
sun.position.set(-7, 15, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -15;
sun.shadow.camera.right = 15;
sun.shadow.camera.top = 11;
sun.shadow.camera.bottom = -11;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 40;
sun.shadow.bias = -0.0005;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x8bcac3, 0.85);
fill.position.set(10, 7, -10);
scene.add(fill);
const warmFill = new THREE.DirectionalLight(0xf0a082, 0.45);
warmFill.position.set(8, 4, 10);
scene.add(warmFill);
// -------------------------------------------------------------------------
// Palette and shared materials
// -------------------------------------------------------------------------
const ALLELE_COLORS = [
0xe15d49,
0xefb64c,
0x319b8f,
0x4d78c4,
0x9364b6,
0x7ca65f,
0xd985a2,
0x526472
];
const ALLELE_COUNT = ALLELE_COLORS.length;
const LOCI = 5;
const SOURCE_COUNT = 96;
const FOUNDER_LIMIT = 12;
const alleleMaterials = ALLELE_COLORS.map(
(color) =>
new THREE.MeshStandardMaterial({
color,
roughness: 0.78,
flatShading: true
})
);
const skinColors = [0xf1c7a3, 0xd99b72, 0xa96849, 0xf3d5b6, 0x80513a];
const skinMaterials = skinColors.map(
(color) =>
new THREE.MeshStandardMaterial({
color,
roughness: 0.9,
flatShading: true
})
);
const baseMaterial = new THREE.MeshStandardMaterial({
color: 0xfaf5e9,
roughness: 0.84,
flatShading: true
});
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0xd8d2c5,
roughness: 1
});
const sourceGroundMaterial = new THREE.MeshStandardMaterial({
color: 0xb8d6cf,
roughness: 1,
flatShading: true
});
const founderGroundMaterial = new THREE.MeshStandardMaterial({
color: 0xf0c6b7,
roughness: 1,
flatShading: true
});
const gateMaterial = new THREE.MeshStandardMaterial({
color: 0x304752,
roughness: 0.75,
flatShading: true
});
const gateCapMaterial = new THREE.MeshStandardMaterial({
color: 0xdf654f,
roughness: 0.78,
flatShading: true
});
// -------------------------------------------------------------------------
// Ground, habitats, and gate
// -------------------------------------------------------------------------
const ground = new THREE.Mesh(
new THREE.BoxGeometry(24.5, 0.5, 12),
groundMaterial
);
ground.position.y = -0.28;
ground.receiveShadow = true;
scene.add(ground);
const sourceArea = new THREE.Mesh(
new THREE.CircleGeometry(4.45, 40),
sourceGroundMaterial
);
sourceArea.rotation.x = -Math.PI / 2;
sourceArea.position.set(-6.35, 0.005, 0);
sourceArea.receiveShadow = true;
scene.add(sourceArea);
const founderArea = new THREE.Mesh(
new THREE.CircleGeometry(4.45, 40),
founderGroundMaterial
);
founderArea.rotation.x = -Math.PI / 2;
founderArea.position.set(6.35, 0.005, 0);
founderArea.receiveShadow = true;
scene.add(founderArea);
const sourceOutline = new THREE.Mesh(
new THREE.RingGeometry(4.45, 4.56, 48),
new THREE.MeshBasicMaterial({
color: 0x5c9e92,
transparent: true,
opacity: 0.38,
side: THREE.DoubleSide
})
);
sourceOutline.rotation.x = -Math.PI / 2;
sourceOutline.position.set(-6.35, 0.015, 0);
scene.add(sourceOutline);
const founderOutline = new THREE.Mesh(
new THREE.RingGeometry(4.45, 4.56, 48),
new THREE.MeshBasicMaterial({
color: 0xc97961,
transparent: true,
opacity: 0.4,
side: THREE.DoubleSide
})
);
founderOutline.rotation.x = -Math.PI / 2;
founderOutline.position.set(6.35, 0.015, 0);
scene.add(founderOutline);
const gate = new THREE.Group();
scene.add(gate);
const pillarGeometry = new THREE.BoxGeometry(1.05, 3.55, 0.9);
for (const side of [-1, 1]) {
const pillar = new THREE.Mesh(pillarGeometry, gateMaterial);
pillar.position.set(0, 1.76, side * 1.27);
pillar.castShadow = true;
pillar.receiveShadow = true;
gate.add(pillar);
const cap = new THREE.Mesh(
new THREE.BoxGeometry(1.25, 0.35, 1.08),
gateCapMaterial
);
cap.position.set(0, 3.62, side * 1.27);
cap.castShadow = true;
gate.add(cap);
}
const lintel = new THREE.Mesh(
new THREE.BoxGeometry(1.15, 0.72, 3.55),
gateMaterial
);
lintel.position.set(0, 3.75, 0);
lintel.castShadow = true;
gate.add(lintel);
const gateLight = new THREE.Mesh(
new THREE.PlaneGeometry(1.6, 3.15),
new THREE.MeshBasicMaterial({
color: 0x4da89c,
transparent: true,
opacity: 0.075,
side: THREE.DoubleSide,
depthWrite: false
})
);
gateLight.rotation.y = Math.PI / 2;
gateLight.position.set(0, 1.6, 0);
gate.add(gateLight);
// Funnel rails narrow toward the one-token opening.
const railMaterial = new THREE.MeshStandardMaterial({
color: 0x71817e,
roughness: 0.9,
flatShading: true
});
function addRail(x1, z1, x2, z2) {
const length = Math.hypot(x2 - x1, z2 - z1);
const rail = new THREE.Mesh(
new THREE.BoxGeometry(length, 0.3, 0.16),
railMaterial
);
rail.position.set((x1 + x2) / 2, 0.17, (z1 + z2) / 2);
rail.rotation.y = -Math.atan2(z2 - z1, x2 - x1);
rail.castShadow = true;
scene.add(rail);
}
addRail(-3.6, -2.35, -1.35, -0.98);
addRail(-3.6, 2.35, -1.35, 0.98);
const arrowGeometry = new THREE.ConeGeometry(0.16, 0.36, 3);
const arrowMaterial = new THREE.MeshStandardMaterial({
color: 0x4d9389,
roughness: 0.9,
flatShading: true
});
for (const x of [-4.1, -2.8, 2.45, 3.7]) {
const arrow = new THREE.Mesh(arrowGeometry, arrowMaterial);
arrow.rotation.z = -Math.PI / 2;
arrow.position.set(x, 0.07, 0);
scene.add(arrow);
}
// Low-poly stones around the perimeter.
const stoneGeometry = new THREE.DodecahedronGeometry(0.34, 0);
const stoneMaterial = new THREE.MeshStandardMaterial({
color: 0xa8aaa0,
roughness: 1,
flatShading: true
});
for (let i = 0; i < 20; i++) {
const stone = new THREE.Mesh(stoneGeometry, stoneMaterial);
const side = i % 2 === 0 ? -1 : 1;
stone.position.set(
-10.8 + Math.random() * 21.6,
0.12,
side * (5.05 + Math.random() * 0.45)
);
stone.rotation.set(
Math.random() * Math.PI,
Math.random() * Math.PI,
Math.random() * Math.PI
);
const scale = 0.6 + Math.random() * 0.7;
stone.scale.setScalar(scale);
stone.castShadow = true;
scene.add(stone);
}
// -------------------------------------------------------------------------
// Canvas labels
// -------------------------------------------------------------------------
function roundedRect(ctx, x, y, width, height, radius) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.arcTo(x + width, y, x + width, y + height, radius);
ctx.arcTo(x + width, y + height, x, y + height, radius);
ctx.arcTo(x, y + height, x, y, radius);
ctx.arcTo(x, y, x + width, y, radius);
ctx.closePath();
}
function makeWorldLabel(title, subtitle, accent, width = 4.5) {
const canvas = document.createElement("canvas");
canvas.width = 768;
canvas.height = 190;
const ctx = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(width, width * (190 / 768), 1);
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(ctx, 5, 5, 758, 180, 28);
ctx.fillStyle = "rgba(250,247,239,0.94)";
ctx.fill();
ctx.strokeStyle = "rgba(32,51,61,0.14)";
ctx.lineWidth = 3;
ctx.stroke();
roundedRect(ctx, 25, 28, 12, 134, 6);
ctx.fillStyle = accent;
ctx.fill();
ctx.fillStyle = "#20333d";
ctx.font = "700 48px Arial, sans-serif";
ctx.fillText(title, 60, 88);
ctx.fillStyle = "#6c797b";
ctx.font = "700 25px Arial, sans-serif";
ctx.fillText(subtitle, 62, 137);
texture.needsUpdate = true;
}
draw();
return { sprite, draw };
}
const sourceLabel = makeWorldLabel(
"SOURCE POPULATION",
"96 marked individuals",
"#258f83"
);
sourceLabel.sprite.position.set(-6.35, 0.42, 4.65);
scene.add(sourceLabel.sprite);
const founderLabel = makeWorldLabel(
"FOUNDER POPULATION",
"The genetic future",
"#df654f"
);
founderLabel.sprite.position.set(6.35, 0.42, 4.65);
scene.add(founderLabel.sprite);
const gateLabel = makeWorldLabel(
"NARROW GATE",
"CAPACITY: 1 AT A TIME",
"#e8ad45",
4.15
);
gateLabel.sprite.position.set(0, 4.55, 0);
scene.add(gateLabel.sprite);
function updateGateLabel(count) {
gateLabel.draw = null;
const canvas = gateLabel.sprite.material.map.image;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(ctx, 5, 5, 758, 180, 28);
ctx.fillStyle = "rgba(250,247,239,0.94)";
ctx.fill();
ctx.strokeStyle = "rgba(32,51,61,0.14)";
ctx.lineWidth = 3;
ctx.stroke();
roundedRect(ctx, 25, 28, 12, 134, 6);
ctx.fillStyle = "#e8ad45";
ctx.fill();
ctx.fillStyle = "#20333d";
ctx.font = "700 48px Arial, sans-serif";
ctx.fillText("NARROW GATE", 60, 88);
ctx.fillStyle = "#6c797b";
ctx.font = "700 25px Arial, sans-serif";
ctx.fillText(
`FOUNDERS: ${String(count).padStart(2, "0")} / ${FOUNDER_LIMIT}`,
62,
137
);
gateLabel.sprite.material.map.needsUpdate = true;
}
// -------------------------------------------------------------------------
// Population tokens
// -------------------------------------------------------------------------
const populationGroup = new THREE.Group();
scene.add(populationGroup);
const geometries = {
base: new THREE.CylinderGeometry(0.39, 0.42, 0.12, 8),
body: new THREE.ConeGeometry(0.28, 0.7, 5),
head: new THREE.IcosahedronGeometry(0.22, 0),
marker: new THREE.OctahedronGeometry(0.13, 0),
pip: new THREE.BoxGeometry(0.11, 0.085, 0.11)
};
function createToken(id, genome) {
const group = new THREE.Group();
const base = new THREE.Mesh(geometries.base, baseMaterial);
base.position.y = 0.07;
base.castShadow = true;
group.add(base);
const body = new THREE.Mesh(
geometries.body,
alleleMaterials[genome[0][0]]
);
body.position.y = 0.5;
body.castShadow = true;
group.add(body);
const head = new THREE.Mesh(
geometries.head,
skinMaterials[Math.floor(Math.random() * skinMaterials.length)]
);
head.position.y = 1.02;
head.castShadow = true;
group.add(head);
const marker = new THREE.Mesh(
geometries.marker,
alleleMaterials[genome[0][1]]
);
marker.position.y = 1.34;
marker.castShadow = true;
group.add(marker);
// Four additional loci are shown as colored pips around the token.
for (let locus = 1; locus < LOCI; locus++) {
const allele =
Math.random() < 0.5 ? genome[locus][0] : genome[locus][1];
const pip = new THREE.Mesh(
geometries.pip,
alleleMaterials[allele]
);
const angle =
((locus - 1) / (LOCI - 1)) * Math.PI * 2 + Math.random() * 0.18;
pip.position.set(
Math.cos(angle) * 0.39,
0.17,
Math.sin(angle) * 0.39
);
pip.rotation.y = angle;
group.add(pip);
}
return {
id,
genome,
group,
visual: group,
phase: Math.random() * Math.PI * 2,
state: "source",
progress: 0,
counted: false,
destination: new THREE.Vector3(),
path: null,
pathStops: []
};
}
function randomGenome() {
return Array.from({ length: LOCI }, () => [
Math.floor(Math.random() * ALLELE_COUNT),
Math.floor(Math.random() * ALLELE_COUNT)
]);
}
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
let tokens = [];
const founders = [];
let destinationSlots = [];
let sourceDiversity = 1;
let moving = null;
let waitTimer = 1.1;
let simulationTime = 0;
let running = true;
let complete = false;
let speed = 2;
let pulse = 0;
function heterozygosity(population) {
if (!population.length) return 0;
let total = 0;
for (let locus = 0; locus < LOCI; locus++) {
const counts = new Array(ALLELE_COUNT).fill(0);
for (const token of population) {
counts[token.genome[locus][0]]++;
counts[token.genome[locus][1]]++;
}
const homozygote = counts.reduce((sum, count) => {
const frequency = count / (population.length * 2);
return sum + frequency * frequency;
}, 0);
total += 1 - homozygote;
}
return total / LOCI;
}
function resetPopulation() {
populationGroup.clear();
tokens = [];
founders.length = 0;
moving = null;
waitTimer = 1.15;
simulationTime = 0;
running = true;
complete = false;
pulse = 0;
selectedHalo.visible = false;
selectedBadge.visible = false;
gatePulse.visible = false;
const sourceSlots = [];
for (let row = 0; row < 8; row++) {
for (let column = 0; column < 12; column++) {
sourceSlots.push({
x: -10.15 + column * 0.7 + (Math.random() - 0.5) * 0.09,
z: -2.45 + row * 0.7 + (Math.random() - 0.5) * 0.09
});
}
}
shuffle(sourceSlots);
for (let i = 0; i < SOURCE_COUNT; i++) {
const token = createToken(i + 1, randomGenome());
token.group.position.set(sourceSlots[i].x, 0, sourceSlots[i].z);
token.group.rotation.y = Math.random() * Math.PI * 2;
populationGroup.add(token.group);
tokens.push(token);
}
destinationSlots = [];
for (let row = 0; row < 3; row++) {
for (let column = 0; column < 4; column++) {
destinationSlots.push(
new THREE.Vector3(
4.85 + column * 0.9,
0,
-2 + row * 2
)
);
}
}
shuffle(destinationSlots);
sourceDiversity = heterozygosity(tokens);
updateUI();
}
// -------------------------------------------------------------------------
// Selection and movement through the gate
// -------------------------------------------------------------------------
const selectedHalo = new THREE.Mesh(
new THREE.TorusGeometry(0.53, 0.045, 4, 24),
new THREE.MeshBasicMaterial({
color: 0xf4bd4f,
transparent: true,
opacity: 0.95
})
);
selectedHalo.rotation.x = Math.PI / 2;
selectedHalo.visible = false;
scene.add(selectedHalo);
const gatePulse = new THREE.Mesh(
new THREE.RingGeometry(0.58, 0.72, 32),
new THREE.MeshBasicMaterial({
color: 0xdf654f,
transparent: true,
opacity: 0,
side: THREE.DoubleSide,
depthWrite: false
})
);
gatePulse.rotation.x = -Math.PI / 2;
gatePulse.position.set(0, 0.04, 0);
gatePulse.visible = false;
scene.add(gatePulse);
const badgeCanvas = document.createElement("canvas");
badgeCanvas.width = 192;
badgeCanvas.height = 88;
const badgeContext = badgeCanvas.getContext("2d");
const badgeTexture = new THREE.CanvasTexture(badgeCanvas);
badgeTexture.colorSpace = THREE.SRGBColorSpace;
const selectedBadge = new THREE.Sprite(
new THREE.SpriteMaterial({
map: badgeTexture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
selectedBadge.scale.set(0.82, 0.38, 1);
selectedBadge.visible = false;
scene.add(selectedBadge);
function updateBadge(id) {
badgeContext.clearRect(0, 0, 192, 88);
roundedRect(badgeContext, 5, 5, 182, 78, 18);
badgeContext.fillStyle = "rgba(32,51,61,0.94)";
badgeContext.fill();
badgeContext.fillStyle = "#ffffff";
badgeContext.font = "700 36px Arial, sans-serif";
badgeContext.textAlign = "center";
badgeContext.textBaseline = "middle";
badgeContext.fillText(`#${String(id).padStart(2, "0")}`, 96, 45);
badgeTexture.needsUpdate = true;
}
function selectFounder() {
const candidates = tokens.filter((token) => token.state === "source");
if (!candidates.length) {
complete = true;
updateUI();
return;
}
const token =
candidates[Math.floor(Math.random() * candidates.length)];
moving = token;
token.state = "moving";
token.progress = 0;
token.counted = false;
token.destination.copy(destinationSlots[founders.length]);
token.path = [
token.group.position.clone(),
new THREE.Vector3(-1.42, 0, (Math.random() - 0.5) * 0.18),
new THREE.Vector3(-0.52, 0, 0),
new THREE.Vector3(1.12, 0, 0),
token.destination.clone()
];
token.pathStops = [0, 0.24, 0.42, 0.6, 1];
selectedHalo.visible = true;
selectedBadge.visible = true;
updateBadge(token.id);
updateUI();
}
function countFounder() {
if (!moving || moving.counted) return;
moving.counted = true;
founders.push(moving);
pulse = 1;
updateUI();
}
function updateMoving(delta) {
if (!moving) return;
moving.progress = Math.min(1, moving.progress + delta / 4.8);
const t = moving.progress;
let segment = tokenSegment(moving, t);
const a = moving.path[segment];
const b = moving.path[segment + 1];
const start = moving.pathStops[segment];
const end = moving.pathStops[segment + 1];
let u = (t - start) / (end - start);
u = THREE.MathUtils.clamp(u, 0, 1);
u = u * u * (3 - 2 * u);
moving.group.position.lerpVectors(a, b, u);
moving.group.position.y = 0;
moving.visual.position.y =
Math.abs(Math.sin(simulationTime * 9 + moving.phase)) * 0.055;
moving.visual.rotation.z = Math.sin(simulationTime * 8) * 0.045;
if (moving.group.position.x >= 0) {
countFounder();
}
if (t >= 1) {
moving.group.position.copy(moving.destination);
moving.group.rotation.y = -Math.PI / 2;
moving.state = "right";
moving = null;
selectedHalo.visible = false;
selectedBadge.visible = false;
waitTimer = 0.36;
if (founders.length >= FOUNDER_LIMIT) {
complete = true;
}
updateUI();
}
}
function tokenSegment(token, t) {
for (let i = 0; i < token.pathStops.length - 1; i++) {
if (t <= token.pathStops[i + 1]) return i;
}
return token.pathStops.length - 2;
}
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
const founderCountEl = document.getElementById("founderCount");
const progressFillEl = document.getElementById("progressFill");
const progressTextEl = document.getElementById("progressText");
const diversityValueEl = document.getElementById("diversityValue");
const diversityBarEl = document.getElementById("diversityBar");
const statusTextEl = document.getElementById("statusText");
const statusDotEl = document.getElementById("statusDot");
const pauseBtn = document.getElementById("pauseBtn");
const resetBtn = document.getElementById("resetBtn");
const speedInput = document.getElementById("speed");
const speedLabel = document.getElementById("speedLabel");
const alleleLegend = document.getElementById("alleles");
for (const color of ALLELE_COLORS) {
const swatch = document.createElement("span");
swatch.className = "allele";
swatch.style.background = `#${color.toString(16).padStart(6, "0")}`;
alleleLegend.appendChild(swatch);
}
function updateUI() {
const count = founders.length;
const progress = (count / FOUNDER_LIMIT) * 100;
founderCountEl.textContent = `${count} / ${FOUNDER_LIMIT}`;
progressFillEl.style.width = `${progress}%`;
progressTextEl.textContent = `${Math.round(progress)}%`;
const currentDiversity = count ? heterozygosity(founders) : null;
const retained = currentDiversity
? (currentDiversity / sourceDiversity) * 100
: null;
diversityValueEl.textContent =
retained === null ? "—" : `${Math.round(retained)}%`;
diversityBarEl.style.width =
retained === null ? "0%" : `${THREE.MathUtils.clamp(retained, 0, 100)}%`;
if (complete) {
statusTextEl.textContent =
`Founder event complete — ${FOUNDER_LIMIT} of ${SOURCE_COUNT} passed.`;
statusDotEl.style.background = "#df654f";
statusDotEl.style.boxShadow = "0 0 0 5px rgba(223,101,79,0.13)";
} else if (!running) {
statusTextEl.textContent = "Simulation paused.";
statusDotEl.style.background = "#e8ad45";
statusDotEl.style.boxShadow = "0 0 0 5px rgba(232,173,69,0.13)";
} else if (moving) {
statusTextEl.textContent = `Founder #${String(moving.id).padStart(2, "0")} is crossing the gate.`;
statusDotEl.style.background = "#258f83";
statusDotEl.style.boxShadow = "0 0 0 5px rgba(37,143,131,0.13)";
} else {
statusTextEl.textContent = "Randomly selecting a founder…";
statusDotEl.style.background = "#e8ad45";
statusDotEl.style.boxShadow = "0 0 0 5px rgba(232,173,69,0.13)";
}
pauseBtn.textContent = complete ? "Complete" : running ? "Pause" : "Resume";
pauseBtn.disabled = complete;
updateGateLabel(count);
}
pauseBtn.addEventListener("click", () => {
if (complete) return;
running = !running;
updateUI();
});
resetBtn.addEventListener("click", resetPopulation);
speedInput.addEventListener("input", () => {
speed = Number(speedInput.value);
speedLabel.textContent = `${speed}×`;
});
// -------------------------------------------------------------------------
// Direct camera controls: orbit, zoom, and pan
// -------------------------------------------------------------------------
let dragging = false;
let dragButton = 0;
let previousX = 0;
let previousY = 0;
const canvas = renderer.domElement;
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
dragButton = event.button;
previousX = event.clientX;
previousY = event.clientY;
cameraState.touched = true;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
if (event.shiftKey || dragButton === 2) {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
const right = new THREE.Vector3()
.crossVectors(forward, camera.up)
.normalize();
const horizontalForward = new THREE.Vector3()
.crossVectors(camera.up, right)
.normalize();
const scale = cameraState.radius * 0.0012;
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(horizontalForward, dy * scale);
cameraState.target.x = THREE.MathUtils.clamp(
cameraState.target.x,
-5,
5
);
cameraState.target.z = THREE.MathUtils.clamp(
cameraState.target.z,
-4,
4
);
cameraState.target.y = THREE.MathUtils.clamp(
cameraState.target.y,
0.1,
2.5
);
} else {
cameraState.theta -= dx * 0.0055;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.0045,
0.48,
1.42
);
}
});
function endDrag(event) {
dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.touched = true;
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
11,
65
);
},
{ passive: false }
);
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z +
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
camera.aspect = aspect;
camera.fov = aspect < 0.8 ? 48 : 40;
camera.updateProjectionMatrix();
if (!cameraState.touched) {
cameraState.radius = aspect < 0.8 ? 46 : 21;
}
}
window.addEventListener("resize", resize);
resize();
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
const selectedBadgeOffset = new THREE.Vector3(0, 1.66, 0);
function updateIdleTokens() {
for (const token of tokens) {
if (token === moving) continue;
if (token.state === "source") {
token.visual.position.y =
Math.sin(simulationTime * 2 + token.phase) * 0.018;
token.visual.rotation.z =
Math.sin(simulationTime * 1.3 + token.phase) * 0.018;
} else {
token.visual.position.y =
Math.sin(simulationTime * 1.6 + token.phase) * 0.012;
}
}
}
function updateEffects(delta) {
if (pulse > 0) {
pulse = Math.max(0, pulse - delta * 1.8);
gatePulse.visible = true;
gatePulse.material.opacity = pulse * 0.58;
gatePulse.scale.setScalar(1 + (1 - pulse) * 1.6);
} else {
gatePulse.visible = false;
}
if (moving) {
selectedHalo.position.copy(moving.group.position);
selectedHalo.position.y = 0.045;
selectedBadge.position.copy(moving.group.position).add(selectedBadgeOffset);
}
}
let previousTime = performance.now();
function animate(now) {
requestAnimationFrame(animate);
const delta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (running && !complete) {
const scaledDelta = delta * speed;
simulationTime += scaledDelta;
waitTimer -= scaledDelta;
if (moving) {
updateMoving(scaledDelta);
} else if (waitTimer <= 0) {
selectFounder();
}
}
updateIdleTokens();
updateEffects(running ? delta * speed : 0);
updateCamera();
renderer.render(scene, camera);
}
resetPopulation();
updateCamera();
requestAnimationFrame(animate);
</script>
</body>
</html>
```