Prompt specification
Build or customize the Three.js 3D scene "Two founding groups from one source" 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: Two founding groups from one source
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/two-founding-groups-from-one-source-x0902
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows the founder effect. Draw two independent small founder samples into separate island trays; expand each under neutral rules and compare inherited frequencies without environmental differences. Stylized solid forms.
Working Three.js Starter (two-founding-groups-from-one-source-x0902):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Two Islands — Founder Effect</title>
<style>
:root {
--paper: #f3efe5;
--ink: #253b38;
--muted: #71807b;
--a: #ec695c;
--a-soft: #f7c1ba;
--b: #2b9b94;
--b-soft: #b9ded9;
--cream: #fffaf0;
--line: rgba(37, 59, 56, 0.14);
--shadow: 0 12px 35px rgba(41, 52, 45, 0.12);
}
* { 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 { font: inherit; }
#app {
position: fixed;
inset: 0;
overflow: hidden;
}
#scene {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene:active { cursor: grabbing; }
.vignette {
position: absolute;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 50% 45%, transparent 35%, rgba(60, 64, 50, 0.055) 100%),
linear-gradient(to bottom, rgba(255,255,255,0.18), transparent 28%);
}
header {
position: absolute;
z-index: 10;
top: 24px;
left: 28px;
pointer-events: none;
}
.eyebrow {
margin-bottom: 5px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(24px, 3vw, 38px);
line-height: 1;
letter-spacing: -0.055em;
font-weight: 850;
}
.subtitle {
margin-top: 8px;
color: var(--muted);
font-size: 12px;
font-weight: 550;
}
.source-pill {
position: absolute;
z-index: 11;
top: 28px;
left: 50%;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 9px;
padding: 9px 13px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(255, 250, 240, 0.82);
box-shadow: 0 6px 22px rgba(52, 58, 48, 0.07);
backdrop-filter: blur(10px);
pointer-events: none;
white-space: nowrap;
color: var(--muted);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.035em;
}
.source-pill .source-mark {
width: 18px;
height: 18px;
display: grid;
place-items: center;
border-radius: 50%;
background:
linear-gradient(90deg, var(--a) 0 50%, var(--b) 50% 100%);
box-shadow: inset 0 0 0 2px var(--cream);
}
.source-pill b { color: var(--ink); }
.stats {
position: absolute;
z-index: 12;
top: 102px;
left: 28px;
right: 28px;
display: flex;
justify-content: space-between;
pointer-events: none;
}
.card {
width: 302px;
padding: 15px 16px 13px;
border: 1px solid rgba(37, 59, 56, 0.12);
border-radius: 17px;
background: rgba(255, 250, 240, 0.88);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
}
.card-head {
display: grid;
grid-template-columns: 32px 1fr auto;
align-items: center;
gap: 9px;
margin-bottom: 12px;
}
.island-badge {
width: 31px;
height: 31px;
display: grid;
place-items: center;
border-radius: 10px;
background: var(--ink);
color: white;
font-size: 13px;
font-weight: 850;
box-shadow: 0 4px 10px rgba(37, 59, 56, 0.18);
}
.card.b .island-badge { background: #665a8b; }
.card-title strong {
display: block;
font-size: 13px;
line-height: 1.15;
}
.card-title small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
font-weight: 650;
}
.big {
text-align: right;
font-variant-numeric: tabular-nums;
}
.big strong {
display: block;
font-size: 23px;
line-height: 0.95;
letter-spacing: -0.05em;
}
.big small {
color: var(--muted);
font-size: 9px;
font-weight: 800;
}
.track-row {
display: flex;
justify-content: space-between;
align-items: baseline;
margin: 8px 0 4px;
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.03em;
}
.track-row b {
color: var(--ink);
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.track {
position: relative;
height: 7px;
overflow: hidden;
border-radius: 999px;
background: var(--b);
box-shadow: inset 0 0 0 1px rgba(37, 59, 56, 0.08);
}
.track .fill {
display: block;
height: 100%;
width: 50%;
border-radius: inherit;
background: var(--a);
transition: width 500ms cubic-bezier(.2,.75,.25,1);
}
.track::after {
content: "";
position: absolute;
top: -2px;
bottom: -2px;
left: 50%;
width: 1px;
background: rgba(255, 250, 240, 0.9);
box-shadow: 0 0 0 1px rgba(37, 59, 56, 0.13);
}
.delta {
margin-top: 11px;
padding-top: 9px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 9px;
font-weight: 700;
}
.delta.positive { color: #b5483e; }
.delta.negative { color: #167d78; }
.rules {
position: absolute;
z-index: 11;
left: 28px;
bottom: 30px;
width: 276px;
padding: 14px 15px;
border: 1px solid var(--line);
border-radius: 15px;
background: rgba(255, 250, 240, 0.8);
backdrop-filter: blur(10px);
pointer-events: none;
}
.rules strong {
display: block;
margin-bottom: 7px;
font-size: 11px;
}
.rule-line {
color: var(--muted);
font-size: 9px;
line-height: 1.6;
}
.allele-key {
display: flex;
gap: 13px;
align-items: center;
margin: 10px 0 8px;
font-size: 9px;
font-weight: 750;
}
.allele-key span {
display: inline-flex;
align-items: center;
gap: 5px;
}
.dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--a);
box-shadow: inset 0 0 0 1px rgba(0,0,0,0.08);
}
.dot.b { background: var(--b); }
.pair {
width: 18px;
height: 9px;
display: inline-flex;
gap: 2px;
}
.pair i {
display: block;
width: 7px;
height: 9px;
border-radius: 5px;
background: var(--a);
}
.pair i:last-child { background: var(--b); }
.camera-tools {
position: absolute;
z-index: 13;
top: 25px;
right: 28px;
display: flex;
align-items: center;
gap: 8px;
pointer-events: none;
}
.camera-hint {
color: var(--muted);
font-size: 9px;
font-weight: 650;
}
.camera-tools button {
pointer-events: auto;
border: 1px solid var(--line);
border-radius: 999px;
padding: 7px 10px;
color: var(--ink);
background: rgba(255, 250, 240, 0.82);
cursor: pointer;
font-size: 9px;
font-weight: 750;
}
.comparison {
position: absolute;
z-index: 10;
left: 50%;
bottom: 151px;
transform: translateX(-50%);
max-width: min(620px, calc(100vw - 40px));
padding: 7px 12px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(255, 250, 240, 0.76);
color: var(--muted);
text-align: center;
backdrop-filter: blur(10px);
pointer-events: none;
white-space: nowrap;
font-size: 9px;
font-weight: 720;
}
.controls {
position: absolute;
z-index: 20;
left: 50%;
bottom: 24px;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 9px;
width: min(790px, calc(100vw - 40px));
padding: 10px;
border: 1px solid rgba(37, 59, 56, 0.14);
border-radius: 19px;
background: rgba(255, 250, 240, 0.93);
box-shadow: 0 18px 50px rgba(37, 48, 42, 0.18);
backdrop-filter: blur(15px);
}
.control-button {
height: 42px;
border: 1px solid var(--line);
border-radius: 12px;
background: #fffdf7;
color: var(--ink);
cursor: pointer;
font-weight: 800;
transition: transform 120ms ease, background 120ms ease;
}
.control-button:hover { transform: translateY(-1px); background: white; }
.control-button:active { transform: translateY(1px); }
.icon-button {
width: 42px;
flex: 0 0 42px;
font-size: 22px;
line-height: 1;
}
.primary-button {
min-width: 102px;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
border: 0;
color: white;
background: var(--ink);
box-shadow: 0 7px 16px rgba(37, 59, 56, 0.2);
}
#playIcon { font-size: 10px; }
.secondary-button {
padding: 0 14px;
white-space: nowrap;
font-size: 10px;
}
.timeline {
flex: 1;
min-width: 170px;
padding: 0 7px;
}
.timeline-label {
margin-bottom: 5px;
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.steps {
display: grid;
grid-template-columns: repeat(6, 1fr);
gap: 4px;
}
.step {
position: relative;
height: 22px;
padding: 0;
border: 0;
border-radius: 7px;
color: var(--muted);
background: transparent;
cursor: pointer;
font-size: 9px;
font-weight: 800;
}
.step::before {
content: "";
position: absolute;
left: 0;
right: 0;
top: 3px;
height: 3px;
border-radius: 999px;
background: #d9ded7;
}
.step span {
position: relative;
z-index: 1;
display: inline-block;
padding-top: 6px;
}
.step.active { color: var(--ink); }
.step.active::before { background: var(--ink); }
.world-tag {
position: absolute;
z-index: 8;
transform: translate(-50%, -50%);
padding: 4px 7px;
border: 1px solid rgba(37, 59, 56, 0.12);
border-radius: 999px;
color: var(--muted);
background: rgba(255, 250, 240, 0.75);
backdrop-filter: blur(5px);
pointer-events: none;
white-space: nowrap;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#loading {
position: absolute;
z-index: 100;
inset: 0;
display: grid;
place-items: center;
background: var(--paper);
color: var(--muted);
font-size: 11px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
transition: opacity 350ms ease;
}
#loading.hidden { opacity: 0; pointer-events: none; }
@media (max-width: 1050px) {
.rules { display: none; }
.comparison { bottom: 139px; }
}
@media (max-width: 700px) {
header { top: 16px; left: 16px; }
.eyebrow { font-size: 8px; }
.subtitle { display: none; }
.source-pill {
top: 68px;
padding: 7px 10px;
font-size: 8px;
}
.stats {
top: 105px;
left: 8px;
right: 8px;
gap: 7px;
}
.card {
width: auto;
flex: 1;
min-width: 0;
padding: 10px;
border-radius: 13px;
}
.card-head {
grid-template-columns: 27px 1fr;
gap: 7px;
margin-bottom: 8px;
}
.island-badge {
width: 27px;
height: 27px;
border-radius: 8px;
font-size: 11px;
}
.card-title strong { font-size: 11px; }
.card-title small { font-size: 7px; }
.big { display: none; }
.track-row { margin-top: 6px; font-size: 8px; }
.track-row b { font-size: 9px; }
.delta { margin-top: 7px; padding-top: 7px; font-size: 7px; }
.camera-tools { top: 14px; right: 12px; }
.camera-hint { display: none; }
.comparison {
bottom: 139px;
max-width: calc(100vw - 16px);
overflow: hidden;
text-overflow: ellipsis;
font-size: 8px;
}
.controls {
bottom: 8px;
width: calc(100vw - 12px);
gap: 5px;
padding: 7px;
border-radius: 15px;
}
.control-button { height: 38px; }
.icon-button { width: 36px; flex-basis: 36px; }
.primary-button { min-width: 72px; }
.secondary-button { display: none; }
.timeline { min-width: 120px; padding: 0 3px; }
.timeline-label { font-size: 7px; }
}
</style>
</head>
<body>
<div id="app">
<canvas id="scene" aria-label="Interactive 3D founder effect simulation with two island trays"></canvas>
<div class="vignette"></div>
<header>
<div class="eyebrow">Population genetics · interactive model</div>
<h1>Two islands. Different beginnings.</h1>
<div class="subtitle">Independent founder samples expand under identical neutral rules.</div>
</header>
<div class="source-pill">
<span class="source-mark"></span>
Shared source <b>p(A) = 0.50</b>
</div>
<div class="camera-tools">
<span class="camera-hint">Drag to orbit · scroll to zoom</span>
<button id="resetView" type="button">Reset view</button>
</div>
<section class="stats" aria-label="Island allele frequencies">
<article class="card a">
<div class="card-head">
<span class="island-badge">A</span>
<div class="card-title">
<strong>Island A</strong>
<small id="popA">8 individuals · generation 0</small>
</div>
<div class="big">
<strong id="nowA">68.8%</strong>
<small>A allele</small>
</div>
</div>
<div class="track-row"><span>FOUNDER SAMPLE</span><b id="founderA">68.8%</b></div>
<div class="track"><span class="fill" id="barFounderA"></span></div>
<div class="track-row"><span>NOW</span><b id="nowLabelA">68.8%</b></div>
<div class="track"><span class="fill" id="barNowA"></span></div>
<div class="delta positive" id="deltaA">+18.8 percentage points from source</div>
</article>
<article class="card b">
<div class="card-head">
<span class="island-badge">B</span>
<div class="card-title">
<strong>Island B</strong>
<small id="popB">8 individuals · generation 0</small>
</div>
<div class="big">
<strong id="nowB">31.3%</strong>
<small>A allele</small>
</div>
</div>
<div class="track-row"><span>FOUNDER SAMPLE</span><b id="founderB">31.3%</b></div>
<div class="track"><span class="fill" id="barFounderB"></span></div>
<div class="track-row"><span>NOW</span><b id="nowLabelB">31.3%</b></div>
<div class="track"><span class="fill" id="barNowB"></span></div>
<div class="delta negative" id="deltaB">−18.8 percentage points from source</div>
</article>
</section>
<div id="tagA" class="world-tag">8 founders</div>
<div id="tagB" class="world-tag">8 founders</div>
<aside class="rules">
<strong>Same environment. Random inheritance.</strong>
<div class="allele-key">
<span><i class="dot"></i>A allele</span>
<span><i class="dot b"></i>a allele</span>
<span><i class="pair"><i></i><i></i></i>one individual</span>
</div>
<div class="rule-line">
No selection · no migration · no mutation<br />
Back strip: founders · center field: descendants
</div>
</aside>
<div class="comparison" id="comparison">
Founder gap: 37.5 percentage points. No migration connects the trays.
</div>
<nav class="controls" aria-label="Simulation controls">
<button class="control-button icon-button" id="previous" type="button" aria-label="Previous generation">‹</button>
<button class="control-button primary-button" id="play" type="button">
<span id="playIcon">▶</span><span id="playLabel">Expand</span>
</button>
<button class="control-button icon-button" id="next" type="button" aria-label="Next generation">›</button>
<div class="timeline">
<div class="timeline-label">Neutral expansion</div>
<div class="steps" id="steps"></div>
</div>
<button class="control-button secondary-button" id="redraw" type="button">Redraw founders</button>
</nav>
<div id="loading">Preparing the islands…</div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const canvas = document.querySelector("#scene");
const loading = document.querySelector("#loading");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false
});
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(0xf3efe5);
scene.fog = new THREE.Fog(0xf3efe5, 19, 38);
const camera = new THREE.PerspectiveCamera(
40,
window.innerWidth / window.innerHeight,
0.1,
100
);
const hemi = new THREE.HemisphereLight(0xfff9eb, 0x809183, 2.15);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff8e9, 3.1);
sun.position.set(-6, 11, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -12;
sun.shadow.camera.right = 12;
sun.shadow.camera.top = 12;
sun.shadow.camera.bottom = -12;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 30;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xc9e0d8, 0.8);
fill.position.set(7, 5, -8);
scene.add(fill);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(70, 70),
new THREE.MeshStandardMaterial({
color: 0xf3efe5,
roughness: 1,
metalness: 0
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.18;
floor.receiveShadow = true;
scene.add(floor);
// Shared solid-form geometry and materials keep the two environments identical.
const geometry = {
tray: new THREE.CylinderGeometry(2.73, 2.86, 0.22, 64),
rim: new THREE.TorusGeometry(2.61, 0.13, 12, 72),
shelf: new THREE.BoxGeometry(3.25, 0.065, 0.43),
tokenBase: new THREE.CylinderGeometry(0.092, 0.105, 0.028, 12),
bead: new THREE.SphereGeometry(0.052, 12, 9),
sourceBase: new THREE.CylinderGeometry(1.03, 1.1, 0.14, 48),
sourceRim: new THREE.TorusGeometry(0.95, 0.075, 10, 56)
};
function makeIslandGeometry() {
const shape = new THREE.Shape();
const points = 36;
for (let i = 0; i < points; i++) {
const angle = (i / points) * Math.PI * 2;
const radius =
2.22 +
0.055 * Math.sin(angle * 3 + 0.4) +
0.035 * Math.cos(angle * 5 - 0.6);
const x = Math.cos(angle) * radius;
const y = Math.sin(angle) * radius;
if (i === 0) shape.moveTo(x, y);
else shape.lineTo(x, y);
}
shape.closePath();
const geo = new THREE.ExtrudeGeometry(shape, {
depth: 0.12,
bevelEnabled: true,
bevelSegments: 2,
steps: 1,
bevelSize: 0.045,
bevelThickness: 0.035
});
geo.rotateX(-Math.PI / 2);
geo.computeVertexNormals();
return geo;
}
geometry.island = makeIslandGeometry();
const material = {
tray: new THREE.MeshStandardMaterial({
color: 0xdcc8a5,
roughness: 0.86,
metalness: 0
}),
rim: new THREE.MeshStandardMaterial({
color: 0xc6ae88,
roughness: 0.78
}),
island: new THREE.MeshStandardMaterial({
color: 0xaec89f,
roughness: 0.94
}),
shelf: new THREE.MeshStandardMaterial({
color: 0xfff8e9,
roughness: 0.82
}),
base: new THREE.MeshStandardMaterial({
color: 0xfffaf0,
roughness: 0.65
}),
alleleA: new THREE.MeshStandardMaterial({
color: 0xec695c,
roughness: 0.52
}),
alleleB: new THREE.MeshStandardMaterial({
color: 0x2b9b94,
roughness: 0.52
})
};
function meshWith(geo, mat, castShadow = false) {
const mesh = new THREE.Mesh(geo, mat);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
return mesh;
}
function createToken(genotype, scale = 1) {
const group = new THREE.Group();
const base = meshWith(geometry.tokenBase, material.base);
base.position.y = 0.014;
group.add(base);
[-1, 1].forEach((side, index) => {
const allele = genotype[index];
const bead = meshWith(
geometry.bead,
allele === 0 ? material.alleleA : material.alleleB
);
bead.scale.set(1, 1.38, 1);
bead.position.set(side * 0.048, 0.087, 0);
group.add(bead);
});
group.scale.setScalar(scale);
return group;
}
function buildIsland(id) {
const group = new THREE.Group();
const tray = meshWith(geometry.tray, material.tray, true);
group.add(tray);
const rim = meshWith(geometry.rim, material.rim, true);
rim.rotation.x = Math.PI / 2;
rim.position.y = 0.15;
group.add(rim);
const island = meshWith(geometry.island, material.island, true);
island.position.y = 0.075;
group.add(island);
const shelf = meshWith(geometry.shelf, material.shelf, true);
shelf.position.set(0, 0.245, -1.67);
group.add(shelf);
scene.add(group);
return {
id,
group,
founderGroups: [],
descendantGroups: [],
generations: []
};
}
const islands = [buildIsland("A"), buildIsland("B")];
const sourceGroup = new THREE.Group();
const sourceBase = meshWith(geometry.sourceBase, material.shelf, true);
sourceGroup.add(sourceBase);
const sourceRim = meshWith(geometry.sourceRim, material.rim, true);
sourceRim.rotation.x = Math.PI / 2;
sourceRim.position.y = 0.1;
sourceGroup.add(sourceRim);
// A balanced diploid source population: ten A and ten a alleles.
const sourceGenotypes = [
[0, 0], [0, 1], [0, 1], [1, 1], [0, 0],
[1, 1], [0, 1], [0, 1], [0, 0], [1, 1]
];
sourceGenotypes.forEach((genotype, i) => {
const token = createToken(genotype, 0.66);
token.position.set(
(i % 5 - 2) * 0.28,
0.085,
(Math.floor(i / 5) - 0.5) * 0.34
);
sourceGroup.add(token);
});
scene.add(sourceGroup);
// ---------- Neutral population model ----------
const MAX_GENERATION = 5;
const FOUNDER_COUNT = 8;
const MAX_VISIBLE = 64;
function mulberry32(seed) {
return function () {
let t = seed += 0x6D2B79F5;
t = Math.imul(t ^ t >>> 15, t | 1);
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
return ((t ^ t >>> 14) >>> 0) / 4294967296;
};
}
function shuffle(array, random) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
function drawIndependentFounders(random) {
const founders = [];
for (let i = 0; i < FOUNDER_COUNT; i++) {
const r = random();
if (r < 0.25) founders.push([0, 0]);
else if (r < 0.75) founders.push([0, 1]);
else founders.push([1, 1]);
}
return founders;
}
function evolveNeutral(previous, random) {
const next = [];
// Each generation doubles in size. Parents are sampled randomly,
// and each child inherits one allele from each randomly chosen parent.
for (let i = 0; i < previous.length * 2; i++) {
const parent1 = previous[Math.floor(random() * previous.length)];
const parent2 = previous[Math.floor(random() * previous.length)];
const allele1 = parent1[Math.floor(random() * 2)];
const allele2 = parent2[Math.floor(random() * 2)];
next.push([allele1, allele2]);
}
return shuffle(next, random);
}
function alleleFrequency(population) {
let a = 0;
let total = 0;
for (const genotype of population) {
a += genotype[0] === 0 ? 1 : 0;
a += genotype[1] === 0 ? 1 : 0;
total += 2;
}
return total ? a / total : 0;
}
let randomSeed = 1729;
let simulationRandom = mulberry32(randomSeed);
// A valid illustrative draw from the balanced source:
// A founders contain 11 A and 5 a alleles.
// B founders contain 5 A and 11 a alleles.
const initialA = shuffle([
[0, 0], [0, 0], [0, 0], [0, 0], [0, 0],
[0, 1], [1, 1], [1, 1]
], simulationRandom);
const initialB = shuffle([
[0, 0], [0, 0], [0, 1],
[1, 1], [1, 1], [1, 1], [1, 1], [1, 1]
], simulationRandom);
function buildGenerations(founderA, founderB) {
const generationsA = [founderA];
const generationsB = [founderB];
for (let g = 1; g <= MAX_GENERATION; g++) {
generationsA.push(evolveNeutral(generationsA[g - 1], simulationRandom));
generationsB.push(evolveNeutral(generationsB[g - 1], simulationRandom));
}
islands[0].generations = generationsA;
islands[1].generations = generationsB;
}
// ---------- Small tween engine ----------
const tweens = [];
function tweenScale(group, from, to, duration, delay = 0, onComplete = null) {
tweens.push({
group,
from,
to,
duration,
delay,
start: performance.now() + delay,
onComplete
});
}
function updateTweens(now) {
for (let i = tweens.length - 1; i >= 0; i--) {
const tween = tweens[i];
if (now < tween.start) continue;
const progress = Math.min((now - tween.start) / tween.duration, 1);
const eased = 1 - Math.pow(1 - progress, 3);
const scale = THREE.MathUtils.lerp(tween.from, tween.to, eased);
tween.group.scale.setScalar(scale);
if (progress >= 1) {
if (tween.onComplete) tween.onComplete();
tweens.splice(i, 1);
}
}
}
// ---------- 3D population rendering ----------
function removeGroups(groups) {
for (const group of groups) {
if (group.parent) group.parent.remove(group);
}
}
function rebuildFounders(island, animate = true) {
removeGroups(island.founderGroups);
const groups = [];
island.generations[0].forEach((genotype, i) => {
const token = createToken(genotype, 0.9);
token.position.set((i - (FOUNDER_COUNT - 1) / 2) * 0.42, 0.285, -1.67);
island.group.add(token);
groups.push(token);
if (animate) {
token.scale.setScalar(0.01);
tweenScale(token, 0.01, 0.9, 420, i * 26);
}
});
island.founderGroups = groups;
}
function createDescendantField(island, generation) {
const population = island.generations[generation];
const count = Math.min(population.length, MAX_VISIBLE);
const columns = Math.min(8, count);
const rows = Math.ceil(count / columns);
const groups = [];
for (let i = 0; i < count; i++) {
const row = Math.floor(i / columns);
const col = i % columns;
const countInRow = Math.min(columns, count - row * columns);
const x = (col - (countInRow - 1) / 2) * 0.37;
const z = 0.16 + (row - (rows - 1) / 2) * 0.37;
const token = createToken(population[i], 0.79);
token.position.set(x, 0.255, z);
island.group.add(token);
groups.push(token);
}
return groups;
}
function showGeneration(island, generation, animate = true) {
const previousGroups = island.descendantGroups;
const nextGroups = createDescendantField(island, generation);
island.descendantGroups = nextGroups;
if (!animate) {
removeGroups(previousGroups);
nextGroups.forEach(group => group.scale.setScalar(0.79));
return;
}
previousGroups.forEach((group, i) => {
tweenScale(group, 0.79, 0.01, 220, i * 2, () => {
if (group.parent) group.parent.remove(group);
});
});
nextGroups.forEach((group, i) => {
group.scale.setScalar(0.01);
tweenScale(group, 0.01, 0.79, 480, 55 + i * 7);
});
}
// ---------- Interface ----------
const stepContainer = document.querySelector("#steps");
const stepButtons = [];
for (let g = 0; g <= MAX_GENERATION; g++) {
const button = document.createElement("button");
button.type = "button";
button.className = "step";
button.setAttribute("aria-label", `Generation ${g}`);
button.innerHTML = `<span>${g}</span>`;
button.addEventListener("click", () => {
stopPlayback();
setGeneration(g, true);
});
stepContainer.appendChild(button);
stepButtons.push(button);
}
let currentGeneration = 0;
let playing = false;
let playbackTimer = null;
function percent(value) {
return `${(value * 100).toFixed(1)}%`;
}
function updateCard(prefix, founderFrequency, nowFrequency, populationSize) {
document.querySelector(`#founder${prefix}`).textContent = percent(founderFrequency);
document.querySelector(`#now${prefix}`).textContent = percent(nowFrequency);
document.querySelector(`#nowLabel${prefix}`).textContent = percent(nowFrequency);
document.querySelector(`#barFounder${prefix}`).style.width = percent(founderFrequency);
document.querySelector(`#barNow${prefix}`).style.width = percent(nowFrequency);
document.querySelector(`#pop${prefix}`).textContent =
`${populationSize} individuals · generation ${currentGeneration}`;
const delta = (nowFrequency - 0.5) * 100;
const deltaElement = document.querySelector(`#delta${prefix}`);
const sign = delta >= 0 ? "+" : "−";
deltaElement.textContent =
`${sign}${Math.abs(delta).toFixed(1)} percentage points from source`;
deltaElement.classList.toggle("positive", delta >= 0);
deltaElement.classList.toggle("negative", delta < 0);
}
function updateHUD() {
const a = islands[0].generations[currentGeneration];
const b = islands[1].generations[currentGeneration];
const founderA = alleleFrequency(islands[0].generations[0]);
const founderB = alleleFrequency(islands[1].generations[0]);
const nowA = alleleFrequency(a);
const nowB = alleleFrequency(b);
updateCard("A", founderA, nowA, a.length);
updateCard("B", founderB, nowB, b.length);
stepButtons.forEach((button, index) => {
button.classList.toggle("active", index === currentGeneration);
});
const founderGap = Math.abs(founderA - founderB) * 100;
const currentGap = Math.abs(nowA - nowB) * 100;
document.querySelector("#comparison").textContent =
`Founder gap ${founderGap.toFixed(1)} points → current gap ${currentGap.toFixed(1)} points. ` +
`No migration connects the trays.`;
}
function setGeneration(generation, animate = true) {
currentGeneration = THREE.MathUtils.clamp(generation, 0, MAX_GENERATION);
showGeneration(islands[0], currentGeneration, animate);
showGeneration(islands[1], currentGeneration, animate);
updateHUD();
}
function updatePlaybackButton() {
document.querySelector("#playIcon").textContent = playing ? "Ⅱ" : "▶";
document.querySelector("#playLabel").textContent = playing ? "Pause" : "Expand";
}
function stopPlayback() {
if (playbackTimer) clearInterval(playbackTimer);
playbackTimer = null;
playing = false;
updatePlaybackButton();
}
function startPlayback() {
if (currentGeneration >= MAX_GENERATION) {
setGeneration(0, true);
}
playing = true;
updatePlaybackButton();
playbackTimer = setInterval(() => {
if (currentGeneration >= MAX_GENERATION) {
stopPlayback();
return;
}
setGeneration(currentGeneration + 1, true);
if (currentGeneration >= MAX_GENERATION) stopPlayback();
}, 1500);
}
document.querySelector("#play").addEventListener("click", () => {
if (playing) stopPlayback();
else startPlayback();
});
document.querySelector("#previous").addEventListener("click", () => {
stopPlayback();
setGeneration(currentGeneration - 1, true);
});
document.querySelector("#next").addEventListener("click", () => {
stopPlayback();
setGeneration(currentGeneration + 1, true);
});
document.querySelector("#redraw").addEventListener("click", () => {
stopPlayback();
randomSeed = (Date.now() ^ Math.floor(Math.random() * 0xffffffff)) >>> 0;
simulationRandom = mulberry32(randomSeed);
const foundersA = drawIndependentFounders(simulationRandom);
const foundersB = drawIndependentFounders(simulationRandom);
buildGenerations(foundersA, foundersB);
islands.forEach(island => rebuildFounders(island, true));
setGeneration(0, true);
});
// ---------- Custom camera controls ----------
const cameraTarget = new THREE.Vector3(0, 0, -0.3);
let cameraTheta = 0;
let cameraPhi = 0.87;
let cameraRadius = 15.5;
let userAdjustedCamera = false;
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
let portraitLayout = false;
function updateCamera() {
camera.position.set(
cameraTarget.x + cameraRadius * Math.sin(cameraPhi) * Math.sin(cameraTheta),
cameraTarget.y + cameraRadius * Math.cos(cameraPhi),
cameraTarget.z + cameraRadius * Math.sin(cameraPhi) * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraTheta = 0;
cameraPhi = portraitLayout ? 0.97 : 0.87;
cameraRadius = portraitLayout ? 19 : recommendedDesktopRadius();
userAdjustedCamera = false;
updateCamera();
}
function recommendedDesktopRadius() {
const aspect = window.innerWidth / window.innerHeight;
return THREE.MathUtils.clamp(24.7 / aspect, 15.5, 20);
}
canvas.addEventListener("pointerdown", event => {
dragging = true;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
cameraTheta -= dx * 0.005;
cameraPhi = THREE.MathUtils.clamp(cameraPhi + dy * 0.004, 0.46, 1.27);
userAdjustedCamera = true;
updateCamera();
});
function endDrag(event) {
dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener("dblclick", resetCamera);
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius + event.deltaY * 0.012,
portraitLayout ? 14 : 11,
portraitLayout ? 25 : 24
);
userAdjustedCamera = true;
updateCamera();
}, { passive: false });
document.querySelector("#resetView").addEventListener("click", resetCamera);
window.addEventListener("keydown", event => {
if (event.code === "Space") {
event.preventDefault();
if (playing) stopPlayback();
else startPlayback();
}
if (event.code === "ArrowRight") {
stopPlayback();
setGeneration(currentGeneration + 1, true);
}
if (event.code === "ArrowLeft") {
stopPlayback();
setGeneration(currentGeneration - 1, true);
}
});
// ---------- Responsive layout and projected labels ----------
function positionLabel(element, island, localPosition) {
const position = new THREE.Vector3(
localPosition[0],
localPosition[1],
localPosition[2]
);
island.group.localToWorld(position);
position.project(camera);
const visible = position.z > -1 && position.z < 1;
element.style.display = visible ? "block" : "none";
element.style.left = `${(position.x * 0.5 + 0.5) * window.innerWidth}px`;
element.style.top = `${(-position.y * 0.5 + 0.5) * window.innerHeight}px`;
}
function updateLabels() {
positionLabel(document.querySelector("#tagA"), islands[0], [0, 0.7, -1.72]);
positionLabel(document.querySelector("#tagB"), islands[1], [0, 0.7, -1.72]);
}
function onResize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
const nowPortrait = aspect < 0.9;
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
camera.aspect = aspect;
camera.updateProjectionMatrix();
if (nowPortrait) {
islands[0].group.position.set(0, 0, 2.85);
islands[1].group.position.set(0, 0, -2.75);
sourceGroup.visible = false;
cameraTarget.set(0, 0, 0.05);
} else {
islands[0].group.position.set(-4.15, 0, 0.35);
islands[1].group.position.set(4.15, 0, 0.35);
sourceGroup.visible = true;
sourceGroup.position.set(0, 0, -3.35);
cameraTarget.set(0, 0, -0.35);
}
if (nowPortrait !== portraitLayout || !userAdjustedCamera) {
portraitLayout = nowPortrait;
cameraRadius = nowPortrait ? 19 : recommendedDesktopRadius();
}
updateCamera();
}
window.addEventListener("resize", onResize);
// ---------- Start ----------
buildGenerations(initialA, initialB);
islands.forEach(island => rebuildFounders(island, false));
onResize();
setGeneration(0, false);
updatePlaybackButton();
const clock = new THREE.Clock();
function frame(now) {
updateTweens(now);
updateLabels();
renderer.render(scene, camera);
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
requestAnimationFrame(() => {
loading.classList.add("hidden");
setTimeout(() => loading.remove(), 400);
});
</script>
</body>
</html>
```