Prompt specification
Build or customize the Three.js 3D scene "Recombination and cloning comparison simulator" 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: Recombination and cloning comparison simulator
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/recombination-and-cloning-comparison-simulator-x0956
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts sexual reproduction and genetic variation. Compare a toy clonal population with a recombining population using the same initial symbolic variation; track combinations separately from allele counts and avoid ranking one universally superior. Voxel style.
Working Three.js Starter (recombination-and-cloning-comparison-simulator-x0956):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Two Ways to Make Variation</title>
<style>
:root {
--bg: #07111e;
--panel: rgba(8, 20, 34, 0.82);
--panel-solid: #0b1b2c;
--line: rgba(164, 206, 232, 0.16);
--text: #e7f2f7;
--muted: #91a9ba;
--clonal: #58c7ff;
--recomb: #ff9f43;
--A: #52e0c2;
--a: #ff6b8a;
--B: #ffd166;
--b: #7f8cff;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 35%, #132a40 0, #07111e 55%, #040a12 100%);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, select { font: inherit; }
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.glass {
background: var(--panel);
border: 1px solid var(--line);
box-shadow: 0 14px 40px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
header {
position: fixed;
top: 18px;
left: 22px;
right: 22px;
z-index: 5;
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 20px;
pointer-events: none;
}
.eyebrow {
color: #83d8ed;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 4px 0 5px;
font-size: clamp(22px, 2.4vw, 34px);
line-height: 1.05;
letter-spacing: -0.035em;
}
.subtitle {
margin: 0;
max-width: 710px;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.legend {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
align-items: center;
gap: 8px 12px;
max-width: 410px;
padding: 10px 12px;
border-radius: 12px;
font-size: 10px;
color: #b9cad5;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 5px;
white-space: nowrap;
}
.swatch {
width: 10px;
height: 10px;
border-radius: 2px;
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.18);
}
.legend-note {
flex-basis: 100%;
color: #7891a4;
line-height: 1.35;
}
#metrics {
position: fixed;
z-index: 4;
top: 108px;
left: 50%;
width: min(1080px, calc(100% - 44px));
transform: translateX(-50%);
display: grid;
grid-template-columns: 1fr 1fr;
gap: 28px;
pointer-events: none;
}
.metric-card {
border-radius: 15px;
padding: 13px 15px 12px;
overflow: hidden;
position: relative;
}
.metric-card::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 3px;
background: var(--accent);
}
.metric-head {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 12px;
margin-bottom: 10px;
}
.metric-title {
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
font-weight: 850;
letter-spacing: 0.05em;
}
.metric-title::before {
content: "";
width: 9px;
height: 9px;
border-radius: 2px;
background: var(--accent);
box-shadow: 0 0 14px color-mix(in srgb, var(--accent) 55%, transparent);
}
.metric-subtitle {
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.generation-pill {
flex: 0 0 auto;
border: 1px solid var(--line);
border-radius: 999px;
padding: 5px 8px;
color: #a9c0cf;
font: 700 9px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.section-label {
display: flex;
justify-content: space-between;
align-items: baseline;
margin: 9px 0 6px;
color: #8ca5b6;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.section-label span {
color: #607b8e;
font-size: 8px;
font-weight: 600;
letter-spacing: 0;
text-transform: none;
}
.count-row {
display: grid;
grid-template-columns: 23px 1fr 112px;
align-items: center;
gap: 7px;
margin: 5px 0;
font-size: 9px;
}
.locus {
color: #718a9b;
font: 800 9px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.count-track {
display: flex;
height: 7px;
overflow: hidden;
border-radius: 2px;
background: #142838;
}
.count-track span { height: 100%; }
.count-nums {
display: flex;
justify-content: flex-end;
gap: 10px;
font: 700 9px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.combo-cloud {
display: flex;
flex-wrap: wrap;
gap: 5px;
min-height: 25px;
}
.combo-chip {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 4px 6px;
border: 1px solid rgba(153, 202, 226, 0.15);
border-radius: 5px;
background: rgba(23, 48, 68, 0.65);
color: #d7e7ef;
font: 700 9px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.combo-chip i {
color: #7893a6;
font-style: normal;
font-size: 8px;
}
.metric-foot {
display: flex;
justify-content: space-between;
gap: 10px;
margin-top: 8px;
padding-top: 8px;
border-top: 1px solid rgba(153, 202, 226, 0.09);
color: #718c9f;
font: 600 8px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.bottom-left,
.bottom-right {
position: fixed;
z-index: 4;
bottom: 91px;
width: min(340px, calc(50% - 36px));
border-radius: 13px;
padding: 12px 14px;
pointer-events: none;
}
.bottom-left { left: 20px; }
.bottom-right { right: 20px; }
.small-title {
color: #85a2b4;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
#context-copy {
margin: 6px 0 8px;
color: #c5d7e1;
font-size: 11px;
line-height: 1.45;
}
.no-ranking {
padding-top: 8px;
border-top: 1px solid rgba(153, 202, 226, 0.1);
color: #8da7b7;
font-size: 9px;
line-height: 1.45;
}
.no-ranking strong { color: #d7e9f2; }
#events {
list-style: none;
margin: 7px 0 0;
padding: 0;
max-height: 92px;
overflow: hidden;
}
#events li {
display: grid;
grid-template-columns: 42px 1fr;
gap: 8px;
padding: 4px 0;
color: #9eb4c3;
font-size: 9px;
line-height: 1.35;
border-bottom: 1px solid rgba(153, 202, 226, 0.06);
}
#events li:last-child { border-bottom: 0; }
#events li span {
color: #5f8297;
font: 700 8px ui-monospace, SFMono-Regular, Menlo, monospace;
}
#dock {
position: fixed;
z-index: 7;
left: 50%;
bottom: 18px;
transform: translateX(-50%);
width: min(1120px, calc(100% - 40px));
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
gap: 9px;
padding: 10px 12px;
border-radius: 14px;
}
.control-group {
display: flex;
align-items: center;
gap: 6px;
}
.dock-label {
margin-right: 3px;
color: #708b9e;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
button, select {
border: 1px solid rgba(159, 202, 226, 0.16);
border-radius: 8px;
background: #10263a;
color: #c8dce7;
padding: 7px 10px;
font-size: 10px;
font-weight: 700;
cursor: pointer;
transition:
background 120ms ease,
border-color 120ms ease,
transform 120ms ease;
}
button:hover, select:hover {
background: #17354b;
border-color: rgba(159, 202, 226, 0.32);
}
button:active { transform: translateY(1px); }
button.active {
color: #07111e;
background: #9de8f4;
border-color: #9de8f4;
}
#play-btn {
min-width: 76px;
color: #07111e;
background: #a6e7f2;
border-color: #a6e7f2;
}
select {
padding: 6px 8px;
background: #10263a;
outline: none;
}
.separator {
width: 1px;
height: 25px;
background: rgba(159, 202, 226, 0.14);
margin: 0 3px;
}
#tooltip {
position: fixed;
z-index: 20;
display: none;
pointer-events: none;
max-width: 250px;
padding: 8px 10px;
border: 1px solid rgba(159, 202, 226, 0.22);
border-radius: 8px;
background: rgba(5, 14, 24, 0.94);
color: #e0edf3;
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.35);
font: 700 10px ui-monospace, SFMono-Regular, Menlo, monospace;
line-height: 1.45;
}
@media (max-width: 860px) {
header {
top: 12px;
left: 12px;
right: 12px;
}
.legend { display: none; }
#metrics {
top: 86px;
width: calc(100% - 24px);
gap: 10px;
}
.metric-card { padding: 10px; }
.metric-subtitle, .section-label span { display: none; }
.count-row { grid-template-columns: 18px 1fr 92px; gap: 4px; }
.count-nums { gap: 5px; font-size: 8px; }
.bottom-left,
.bottom-right { display: none; }
#dock {
width: calc(100% - 20px);
bottom: 10px;
padding: 8px;
}
.dock-label { display: none; }
.separator { display: none; }
}
@media (max-width: 580px) {
h1 { font-size: 21px; }
.subtitle { font-size: 10px; max-width: 330px; }
#metrics { top: 78px; }
.metric-title { font-size: 10px; }
.generation-pill { display: none; }
.section-label { font-size: 7px; }
.count-row { grid-template-columns: 16px 1fr 73px; }
.count-nums { gap: 3px; font-size: 7px; }
.combo-chip { padding: 3px 4px; font-size: 7px; }
.metric-foot { display: none; }
button, select { padding: 6px 7px; font-size: 9px; }
}
</style>
</head>
<body>
<div id="scene" aria-label="Interactive three-dimensional comparison of clonal and recombining populations"></div>
<header>
<div>
<div class="eyebrow">Toy population genetics · interactive voxel model</div>
<h1>Two ways to make variation</h1>
<p class="subtitle">
Both populations begin with the same eight diploid founders and the same four
haplotypes. Clonal reproduction copies individuals; recombining reproduction
mates individuals and crosses homologs. Compare properties in context—not a universal winner.
</p>
</div>
<div class="legend glass">
<div class="legend-item"><i class="swatch" style="background:var(--A)"></i>A</div>
<div class="legend-item"><i class="swatch" style="background:var(--a)"></i>a</div>
<div class="legend-item"><i class="swatch" style="background:var(--B)"></i>B</div>
<div class="legend-item"><i class="swatch" style="background:var(--b)"></i>b</div>
<div class="legend-note">
Each organism has two homologous tracks. Bottom voxel = locus 1; top voxel = locus 2.
</div>
</div>
</header>
<main id="metrics">
<section class="metric-card glass" style="--accent:var(--clonal)">
<div class="metric-head">
<div>
<div class="metric-title">CLONAL</div>
<div class="metric-subtitle">Exact-copy lineages</div>
</div>
<div class="generation-pill">G0 · N=8</div>
</div>
<div class="section-label">
Allele counts
<span>per-locus marginal totals</span>
</div>
<div id="clonal-counts"></div>
<div class="section-label">
Diploid combinations
<span>unique haplotype pairs</span>
</div>
<div id="clonal-combos" class="combo-cloud"></div>
<div class="metric-foot">
<span id="clonal-haps"></span>
<span id="clonal-delta"></span>
</div>
</section>
<section class="metric-card glass" style="--accent:var(--recomb)">
<div class="metric-head">
<div>
<div class="metric-title">RECOMBINING</div>
<div class="metric-subtitle">Random mating + meiotic crossover</div>
</div>
<div class="generation-pill">G0 · N=8</div>
</div>
<div class="section-label">
Allele counts
<span>per-locus marginal totals</span>
</div>
<div id="recomb-counts"></div>
<div class="section-label">
Diploid combinations
<span>unique haplotype pairs</span>
</div>
<div id="recomb-combos" class="combo-cloud"></div>
<div class="metric-foot">
<span id="recomb-haps"></span>
<span id="recomb-delta"></span>
</div>
</section>
</main>
<aside class="bottom-left glass">
<div class="small-title">Context note</div>
<p id="context-copy"></p>
<div class="no-ranking">
<strong>Not a leaderboard.</strong> Recombination changes how existing alleles are
paired; selection can change allele frequencies. Which property is useful depends
on the environment and the question.
</div>
</aside>
<aside class="bottom-right glass">
<div class="small-title">Generation events</div>
<ul id="events" aria-live="polite"></ul>
</aside>
<nav id="dock" class="glass" aria-label="Simulation controls">
<div class="control-group">
<button id="play-btn" type="button">Play</button>
<button id="step-btn" type="button">Step</button>
<button id="reset-btn" type="button">Reset</button>
</div>
<div class="separator"></div>
<div class="control-group">
<span class="dock-label">Context</span>
<button class="context-btn active" data-context="mixed" type="button">Mixed</button>
<button class="context-btn" data-context="l1" type="button">Shift L1</button>
<button class="context-btn" data-context="l2" type="button">Shift L2</button>
</div>
<div class="separator"></div>
<div class="control-group">
<label class="dock-label" for="speed">Speed</label>
<select id="speed">
<option value="0.5">0.5×</option>
<option value="1" selected>1×</option>
<option value="2">2×</option>
<option value="4">4×</option>
</select>
</div>
</nav>
<div id="tooltip"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Model
// -------------------------------------------------------------------------
const POP_SIZE = 8;
const SEED = 20240517;
const ALLELE_COLORS = {
A: 0x52e0c2,
a: 0xff6b8a,
B: 0xffd166,
b: 0x7f8cff
};
const ALLELE_CSS = {
A: "#52e0c2",
a: "#ff6b8a",
B: "#ffd166",
b: "#7f8cff"
};
// Each founder carries two haplotypes. The same four haplotypes are repeated
// so that both populations start with identical allele and combination data.
const founderPattern = [
["AB", "Ab"],
["AB", "ab"],
["Ab", "aB"],
["aB", "ab"],
["AB", "Ab"],
["AB", "ab"],
["Ab", "aB"],
["aB", "ab"]
];
const contexts = {
mixed: {
label: "Mixed",
copy:
"No locus is preferred. Clonal copying preserves the four founder pairings, " +
"while recombination samples new pairings from the same starting alleles."
},
l1: {
label: "Shift at locus 1",
copy:
"A is favored at locus 1 while B/b is neutral. Weighted reproduction can " +
"change marginal allele counts as well as the combinations that contain them."
},
l2: {
label: "Shift at locus 2",
copy:
"B is favored at locus 2 while A/a is neutral. A useful combination depends " +
"on this context and on which alleles are actually present."
}
};
let context = "mixed";
let generation = 0;
let running = false;
let rng = mulberry32(SEED);
let populations = {
clonal: makeInitialPopulation(),
recomb: makeInitialPopulation()
};
function makeInitialPopulation() {
return founderPattern.map(h => ({ haps: [...h] }));
}
function clonePopulation(pop) {
return pop.map(g => ({ haps: [...g.haps] }));
}
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 combinationKey(genome) {
return [...genome.haps].sort().join("/");
}
function statsFor(pop) {
const alleles = { A: 0, a: 0, B: 0, b: 0 };
const combinations = new Map();
const haplotypes = new Set();
for (const genome of pop) {
for (const hap of genome.haps) {
haplotypes.add(hap);
alleles.A += (hap[0] === "A") ? 1 : 0;
alleles.a += (hap[0] === "a") ? 1 : 0;
alleles.B += (hap[1] === "B") ? 1 : 0;
alleles.b += (hap[1] === "b") ? 1 : 0;
}
const key = combinationKey(genome);
combinations.set(key, (combinations.get(key) || 0) + 1);
}
return { alleles, combinations, haplotypes };
}
function fitness(genome) {
if (context === "mixed") return 1;
const favored = context === "l1" ? "A" : "B";
const copies = genome.haps.reduce(
(sum, hap) => sum + Number(hap[0] === favored),
0
);
return 1 + 0.16 * (copies - 1);
}
function chooseParent(pop) {
if (context === "mixed") {
return Math.floor(rng() * pop.length);
}
const weights = pop.map(fitness);
const maxWeight = Math.max(...weights);
const scaled = weights.map(w => Math.exp((w - maxWeight) * 8));
const total = scaled.reduce((a, b) => a + b, 0);
let r = rng() * total;
for (let i = 0; i < scaled.length; i++) {
r -= scaled[i];
if (r <= 0) return i;
}
return pop.length - 1;
}
function nextClonal(pop) {
if (context === "mixed") {
return clonePopulation(pop);
}
const next = [];
for (let i = 0; i < POP_SIZE; i++) {
const parent = pop[chooseParent(pop)];
next.push({ haps: [...parent.haps] });
}
return next;
}
function makeGamete(parent) {
const donorIndex = rng() < 0.5 ? 0 : 1;
const donor = parent.haps[donorIndex];
const alternate = parent.haps[1 - donorIndex];
// A crossover between the two symbolic loci.
if (donor !== alternate && rng() < 0.72) {
return donor[0] + alternate[1];
}
return donor;
}
function nextRecombining(pop) {
const next = [];
for (let i = 0; i < POP_SIZE; i++) {
let p1 = chooseParent(pop);
let p2 = chooseParent(pop);
while (p2 === p1) {
p2 = chooseParent(pop);
}
const gamete1 = makeGamete(pop[p1]);
const gamete2 = makeGamete(pop[p2]);
next.push({ haps: [gamete1, gamete2] });
}
return next;
}
function resetSimulation(message = null) {
rng = mulberry32(SEED);
generation = 0;
populations = {
clonal: makeInitialPopulation(),
recomb: makeInitialPopulation()
};
events = [];
addEvent(
"Both sides start with L1 A/a = 8/8, L2 B/b = 8/8, and 4 diploid combinations.",
"start"
);
if (message) addEvent(message, "context");
updateAll();
}
function stepGeneration() {
const before = {
clonal: statsFor(populations.clonal),
recomb: statsFor(populations.recomb)
};
populations.clonal = nextClonal(populations.clonal);
populations.recomb = nextRecombining(populations.recomb);
generation++;
const after = {
clonal: statsFor(populations.clonal),
recomb: statsFor(populations.recomb)
};
addChangeEvent("Clonal", before.clonal, after.clonal, false);
addChangeEvent("Recombining", before.recomb, after.recomb, true);
updateAll();
pulseBreedingGlyphs();
}
function addChangeEvent(label, before, after, isRecombining) {
const newCombinations = [...after.combinations.keys()]
.filter(key => !before.combinations.has(key));
const lostCombinations = [...before.combinations.keys()]
.filter(key => !after.combinations.has(key));
const alleleChanges = Object.keys(after.alleles)
.filter(key => after.alleles[key] !== before.alleles[key])
.map(key => `${key} ${before.alleles[key]}→${after.alleles[key]}`);
if (newCombinations.length) {
addEvent(
`${label}: new pairings ${newCombinations.join(", ")}.`,
isRecombining ? "recomb" : "clonal"
);
}
if (lostCombinations.length) {
addEvent(
`${label}: pairings no longer present: ${lostCombinations.join(", ")}.`,
isRecombining ? "recomb" : "clonal"
);
}
if (alleleChanges.length) {
addEvent(
`${label}: allele counts shifted (${alleleChanges.join(", ")}).`,
"allele"
);
}
if (!newCombinations.length && !lostCombinations.length && !alleleChanges.length) {
addEvent(
isRecombining
? "Recombining: observed allele totals and pairings stayed unchanged this step."
: "Clonal: exact-copy lineages retained the same observed state.",
isRecombining ? "recomb" : "clonal"
);
}
}
// -------------------------------------------------------------------------
// UI state and metric rendering
// -------------------------------------------------------------------------
const $ = id => document.getElementById(id);
let events = [];
function addEvent(text, kind) {
events.unshift({ generation, text, kind });
events = events.slice(0, 6);
$("events").innerHTML = events.map(event => `
<li>
<span>G${event.generation}</span>
<div>${event.text}</div>
</li>
`).join("");
}
function formatCountRow(locus, first, second, counts) {
const firstWidth = counts[first] / 16 * 100;
const secondWidth = counts[second] / 16 * 100;
return `
<div class="count-row">
<div class="locus">${locus}</div>
<div class="count-track" aria-hidden="true">
<span style="width:${firstWidth}%;background:${ALLELE_CSS[first]}"></span>
<span style="width:${secondWidth}%;background:${ALLELE_CSS[second]}"></span>
</div>
<div class="count-nums">
<b style="color:${ALLELE_CSS[first]}">${first} ${counts[first]}</b>
<b style="color:${ALLELE_CSS[second]}">${second} ${counts[second]}</b>
</div>
</div>
`;
}
function renderMetric(prefix, pop) {
const stats = statsFor(pop);
const founder = statsFor(makeInitialPopulation());
$(`${prefix}-counts`).innerHTML =
formatCountRow("L1", "A", "a", stats.alleles) +
formatCountRow("L2", "B", "b", stats.alleles);
const combinations = [...stats.combinations.entries()]
.sort((a, b) => a[0].localeCompare(b[0]));
$(`${prefix}-combos`).innerHTML = combinations.map(([key, count]) => `
<span class="combo-chip"><b>${key}</b><i>×${count}</i></span>
`).join("");
$(`${prefix}-haps`).textContent =
`${stats.haplotypes.size}/4 haplotypes present`;
const comboDelta = stats.combinations.size - founder.combinations.size;
const aDelta = stats.alleles.A - founder.alleles.A;
const bDelta = stats.alleles.B - founder.alleles.B;
$(`${prefix}-delta`).textContent =
`from start: Δcomb ${comboDelta >= 0 ? "+" : ""}${comboDelta} · ` +
`ΔA ${aDelta >= 0 ? "+" : ""}${aDelta} · ΔB ${bDelta >= 0 ? "+" : ""}${bDelta}`;
document.querySelectorAll(".generation-pill").forEach(pill => {
pill.textContent = `G${generation} · N=${POP_SIZE}`;
});
}
function updateContextCopy() {
const c = statsFor(populations.clonal);
const r = statsFor(populations.recomb);
const observed =
` Currently observed: ${c.combinations.size} clonal vs ${r.combinations.size} ` +
`recombining diploid combinations. These counts describe different patterns, ` +
`not an overall biological ranking.`;
$("context-copy").textContent = contexts[context].copy + observed;
}
function updateAll() {
renderMetric("clonal", populations.clonal);
renderMetric("recomb", populations.recomb);
updatePopulationVisual(popVisuals.clonal, populations.clonal);
updatePopulationVisual(popVisuals.recomb, populations.recomb);
updateContextCopy();
}
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111e);
scene.fog = new THREE.FogExp2(0x07111e, 0.021);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ 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;
$("scene").appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xc9efff, 0x07101b, 1.7);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.25);
keyLight.position.set(7, 13, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -14;
keyLight.shadow.camera.right = 14;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -8;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0xff9e55, 24, 25, 2);
rimLight.position.set(8, 4, -6);
scene.add(rimLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(70, 70),
new THREE.MeshStandardMaterial({
color: 0x06101b,
roughness: 0.95,
metalness: 0.05
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.34;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(60, 60, 0x17374b, 0x0d2434);
grid.position.y = -0.325;
grid.material.transparent = true;
grid.material.opacity = 0.38;
scene.add(grid);
// Small background voxels.
const dustGeometry = new THREE.BoxGeometry(1, 1, 1);
const dustMaterial = new THREE.MeshBasicMaterial({
color: 0x8fc3d8,
transparent: true,
opacity: 0.18
});
const dust = new THREE.InstancedMesh(dustGeometry, dustMaterial, 70);
const dummy = new THREE.Object3D();
for (let i = 0; i < 70; i++) {
dummy.position.set(
(rng() - 0.5) * 34,
rng() * 10 - 0.2,
(rng() - 0.5) * 25
);
const size = 0.025 + rng() * 0.07;
dummy.scale.setScalar(size);
dummy.rotation.set(rng() * Math.PI, rng() * Math.PI, rng() * Math.PI);
dummy.updateMatrix();
dust.setMatrixAt(i, dummy.matrix);
}
dust.instanceMatrix.needsUpdate = true;
scene.add(dust);
function createTextSprite(text, options = {}) {
const {
width = 512,
height = 128,
worldWidth = 3,
worldHeight = 0.75,
color = "#dcecf4",
background = "rgba(6, 17, 29, 0.82)",
border = "rgba(158, 206, 232, 0.2)",
fontSize = 44,
font = "700 44px ui-monospace, SFMono-Regular, Menlo, monospace"
} = options;
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
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(worldWidth, worldHeight, 1);
sprite.renderOrder = 20;
const label = { sprite, canvas, ctx, texture, options: { ...options, fontSize, font } };
setTextSprite(label, text, color, background, border);
return label;
}
function setTextSprite(label, text, color, background, border) {
const { canvas, ctx, texture, options } = label;
const w = canvas.width;
const h = canvas.height;
ctx.clearRect(0, 0, w, h);
ctx.fillStyle = background;
ctx.fillRect(0, 0, w, h);
ctx.strokeStyle = border;
ctx.lineWidth = 4;
ctx.strokeRect(2, 2, w - 4, h - 4);
let size = options.fontSize;
ctx.font = options.font.replace(/\d+px/, `${size}px`);
while (ctx.measureText(text).width > w - 36 && size > 18) {
size -= 2;
ctx.font = options.font.replace(/\d+px/, `${size}px`);
}
ctx.fillStyle = color;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, w / 2, h / 2 + 1);
texture.needsUpdate = true;
}
function addEdges(mesh, color = 0x24475d, opacity = 0.8) {
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(mesh.geometry),
new THREE.LineBasicMaterial({
color,
transparent: true,
opacity
})
);
mesh.add(edges);
return edges;
}
const sharedGeometries = {
slab: new THREE.BoxGeometry(5.65, 0.3, 4.15),
rim: new THREE.BoxGeometry(5.95, 0.16, 4.45),
cell: new THREE.BoxGeometry(0.85, 0.07, 0.68),
body: new THREE.BoxGeometry(0.52, 0.5, 0.5),
head: new THREE.BoxGeometry(0.34, 0.31, 0.34),
allele: new THREE.BoxGeometry(0.18, 0.18, 0.12),
stackCube: new THREE.BoxGeometry(0.28, 0.18, 0.28)
};
function createOrganism(accent) {
const group = new THREE.Group();
const plate = new THREE.Mesh(
sharedGeometries.cell,
new THREE.MeshStandardMaterial({
color: 0x173348,
roughness: 0.8,
metalness: 0.08
})
);
plate.position.y = 0.225;
plate.receiveShadow = true;
addEdges(plate);
group.add(plate);
const body = new THREE.Mesh(
sharedGeometries.body,
new THREE.MeshStandardMaterial({
color: 0xb7cad3,
roughness: 0.55,
metalness: 0.08,
emissive: 0x000000
})
);
body.position.y = 0.51;
body.castShadow = true;
body.receiveShadow = true;
addEdges(body, accent, 0.7);
group.add(body);
const head = new THREE.Mesh(
sharedGeometries.head,
new THREE.MeshStandardMaterial({
color: 0xe0edf1,
roughness: 0.5,
metalness: 0.05
})
);
head.position.y = 0.94;
head.castShadow = true;
addEdges(head, accent, 0.7);
group.add(head);
const markerMaterials = [];
const markers = [];
for (let homolog = 0; homolog < 2; homolog++) {
for (let locus = 0; locus < 2; locus++) {
const material = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.35,
metalness: 0.08,
emissive: 0x111111,
emissiveIntensity: 0.15
});
markerMaterials.push(material);
const marker = new THREE.Mesh(sharedGeometries.allele, material);
marker.position.set(
homolog === 0 ? -0.125 : 0.125,
locus === 0 ? 0.59 : 0.86,
0.305
);
marker.castShadow = true;
addEdges(marker, 0x15202b, 0.8);
group.add(marker);
markers.push(marker);
}
}
const genotypeLabel = createTextSprite("AB/Ab", {
width: 320,
height: 80,
worldWidth: 1.36,
worldHeight: 0.34,
fontSize: 40
});
genotypeLabel.sprite.position.set(0, 1.43, 0);
group.add(genotypeLabel.sprite);
group.userData = {
body,
markers,
markerMaterials,
genotypeLabel,
pulse: 0
};
return group;
}
function createPopulationVisual(kind, x) {
const group = new THREE.Group();
group.position.x = x;
const accent = kind === "clonal" ? 0x58c7ff : 0xff9f43;
const accentCSS = kind === "clonal" ? "#58c7ff" : "#ff9f43";
const rim = new THREE.Mesh(
sharedGeometries.rim,
new THREE.MeshStandardMaterial({
color: 0x091522,
roughness: 0.85,
metalness: 0.1
})
);
rim.position.y = -0.07;
rim.receiveShadow = true;
addEdges(rim, accent, 0.48);
group.add(rim);
const slab = new THREE.Mesh(
sharedGeometries.slab,
new THREE.MeshStandardMaterial({
color: 0x10283b,
roughness: 0.8,
metalness: 0.08
})
);
slab.position.y = 0.08;
slab.receiveShadow = true;
addEdges(slab, accent, 0.45);
group.add(slab);
const title = createTextSprite(
kind === "clonal" ? "CLONAL" : "RECOMBINING",
{
width: 640,
height: 130,
worldWidth: 4.0,
worldHeight: 0.81,
color: accentCSS,
border: kind === "clonal"
? "rgba(88, 199, 255, 0.42)"
: "rgba(255, 159, 67, 0.42)",
fontSize: 56
}
);
title.sprite.position.set(0, 3.78, -0.25);
group.add(title.sprite);
const subtitle = createTextSprite(
kind === "clonal"
? "EXACT COPY · HOMOLOGS STAY TOGETHER"
: "MATE · CROSSOVER · REASSORT",
{
width: 640,
height: 90,
worldWidth: 3.8,
worldHeight: 0.54,
color: "#90aaba",
background: "rgba(6, 17, 29, 0.58)",
fontSize: 27
}
);
subtitle.sprite.position.set(0, 3.24, -0.25);
group.add(subtitle.sprite);
const countTitle = createTextSprite("ALLELE COUNTS · STACKS", {
width: 480,
height: 80,
worldWidth: 2.6,
worldHeight: 0.43,
color: "#7693a5",
background: "rgba(6, 17, 29, 0.58)",
fontSize: 28
});
countTitle.sprite.position.set(0, 3.03, -1.3);
group.add(countTitle.sprite);
const organisms = [];
const organismPositions = [];
for (let row = 0; row < 2; row++) {
for (let col = 0; col < 4; col++) {
const organism = createOrganism(accent);
organism.position.set(
-1.8 + col * 1.2,
0,
0.02 + row * 1.05
);
organismPositions.push(organism.position.clone());
organisms.push(organism);
group.add(organism);
}
}
const stackSpecs = [
{ key: "A", locus: "L1", x: -1.85 },
{ key: "a", locus: "L1", x: -0.75 },
{ key: "B", locus: "L2", x: 0.35 },
{ key: "b", locus: "L2", x: 1.45 }
];
const stacks = [];
for (const spec of stackSpecs) {
const stack = new THREE.Group();
stack.position.set(spec.x, 0.24, -1.28);
const material = new THREE.MeshStandardMaterial({
color: ALLELE_COLORS[spec.key],
roughness: 0.45,
metalness: 0.05,
emissive: ALLELE_COLORS[spec.key],
emissiveIntensity: 0.08
});
const cubes = [];
for (let i = 0; i < 16; i++) {
const cube = new THREE.Mesh(sharedGeometries.stackCube, material);
cube.position.y = i * 0.19;
cube.castShadow = true;
addEdges(cube, 0x152332, 0.7);
cube.visible = false;
stack.add(cube);
cubes.push(cube);
}
const label = createTextSprite(`${spec.locus} ${spec.key} · 0`, {
width: 280,
height: 76,
worldWidth: 0.93,
worldHeight: 0.25,
color: ALLELE_CSS[spec.key],
background: "rgba(6, 17, 29, 0.72)",
fontSize: 30
});
label.sprite.position.set(0, -0.24, 0.22);
stack.add(label.sprite);
group.add(stack);
stacks.push({ ...spec, cubes, label });
}
// A small breeding glyph above each habitat.
const flash = new THREE.Group();
flash.position.set(0, 2.15, -0.45);
flash.visible = false;
const flashMaterials = [];
for (let i = 0; i < 4; i++) {
const material = new THREE.MeshBasicMaterial({
color: kind === "clonal" ? accent : ALLELE_COLORS[i % 2 ? "A" : "B"],
transparent: true,
opacity: 0.9,
depthTest: false
});
flashMaterials.push(material);
const cube = new THREE.Mesh(
new THREE.BoxGeometry(0.18, 0.18, 0.18),
material
);
cube.position.set(
kind === "clonal" ? 0 : (i % 2 ? 0.28 : -0.28),
kind === "clonal" ? (i - 1.5) * 0.22 : (i < 2 ? -0.16 : 0.16),
0
);
cube.rotation.z = kind === "clonal" ? 0 : (i % 2 ? 0.7 : -0.7);
flash.add(cube);
}
group.add(flash);
scene.add(group);
return {
kind,
group,
accent,
organisms,
organismPositions,
stacks,
flash,
flashMaterials,
flashLife: 0
};
}
const popVisuals = {
clonal: createPopulationVisual("clonal", -4.7),
recomb: createPopulationVisual("recomb", 4.7)
};
function updatePopulationVisual(visual, pop) {
const stats = statsFor(pop);
pop.forEach((genome, index) => {
const organism = visual.organisms[index];
const data = organism.userData;
data.body.userData.genome = genome;
for (let homolog = 0; homolog < 2; homolog++) {
for (let locus = 0; locus < 2; locus++) {
const allele = genome.haps[homolog][locus];
const markerIndex = homolog * 2 + locus;
data.markerMaterials[markerIndex].color.setHex(ALLELE_COLORS[allele]);
data.markerMaterials[markerIndex].emissive.setHex(ALLELE_COLORS[allele]);
data.markerMaterials[markerIndex].emissiveIntensity = 0.1;
}
}
setTextSprite(
data.genotypeLabel,
genome.haps.join("/"),
"#d9eaf1",
"rgba(5, 15, 25, 0.82)",
"rgba(155, 203, 228, 0.16)"
);
data.pulse = 1;
});
for (const stack of visual.stacks) {
const count = stats.alleles[stack.key];
stack.cubes.forEach((cube, index) => {
cube.visible = index < count;
});
setTextSprite(
stack.label,
`${stack.locus} ${stack.key} · ${count}`,
ALLELE_CSS[stack.key],
"rgba(6, 17, 29, 0.78)",
"rgba(155, 203, 228, 0.14)"
);
}
}
function pulseBreedingGlyphs() {
popVisuals.clonal.flashLife = 1;
popVisuals.recomb.flashLife = 1;
}
// Shared founder tray in the center.
const founderTray = new THREE.Group();
founderTray.position.set(0, 0, -0.45);
const tray = new THREE.Mesh(
new THREE.BoxGeometry(2.35, 0.28, 1.35),
new THREE.MeshStandardMaterial({
color: 0x102538,
roughness: 0.8
})
);
tray.position.y = -0.08;
tray.receiveShadow = true;
addEdges(tray, 0x91aec0, 0.35);
founderTray.add(tray);
["AB", "Ab", "aB", "ab"].forEach((hap, index) => {
const x = -0.78 + index * 0.52;
for (let locus = 0; locus < 2; locus++) {
const allele = hap[locus];
const voxel = new THREE.Mesh(
new THREE.BoxGeometry(0.24, 0.24, 0.24),
new THREE.MeshStandardMaterial({
color: ALLELE_COLORS[allele],
roughness: 0.4,
emissive: ALLELE_COLORS[allele],
emissiveIntensity: 0.08
})
);
voxel.position.set(x, 0.2 + locus * 0.25, 0);
voxel.castShadow = true;
addEdges(voxel, 0x172532, 0.8);
founderTray.add(voxel);
}
const label = createTextSprite(hap, {
width: 180,
height: 70,
worldWidth: 0.5,
worldHeight: 0.2,
color: "#a8c0ce",
background: "rgba(6, 17, 29, 0.58)",
fontSize: 31
});
label.sprite.position.set(x, -0.14, 0.43);
founderTray.add(label.sprite);
});
const sameLabel = createTextSprite("SAME FOR BOTH", {
width: 460,
height: 90,
worldWidth: 2.15,
worldHeight: 0.42,
color: "#c7e8f2",
border: "rgba(151, 213, 232, 0.35)",
fontSize: 35
});
sameLabel.sprite.position.set(0, 1.08, 0);
founderTray.add(sameLabel.sprite);
const founderLabel = createTextSprite("4 START HAPLOTYPES", {
width: 460,
height: 80,
worldWidth: 2.1,
worldHeight: 0.36,
color: "#7693a6",
background: "rgba(6, 17, 29, 0.56)",
fontSize: 28
});
founderLabel.sprite.position.set(0, 1.47, 0);
founderTray.add(founderLabel.sprite);
scene.add(founderTray);
// -------------------------------------------------------------------------
// Direct camera controls: drag to orbit, wheel to zoom
// -------------------------------------------------------------------------
const view = {
theta: 0.12,
phi: 1.02,
radius: window.innerWidth < 760 ? 24 : 19,
target: new THREE.Vector3(0, 1.05, 0)
};
const desiredView = {
theta: view.theta,
phi: view.phi,
radius: view.radius
};
const canvas = renderer.domElement;
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
canvas.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
dragging = true;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
$("tooltip").style.display = "none";
});
canvas.addEventListener("pointermove", event => {
if (dragging) {
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
desiredView.theta -= dx * 0.006;
desiredView.phi = THREE.MathUtils.clamp(
desiredView.phi - dy * 0.005,
0.48,
1.32
);
return;
}
updateHover(event);
});
canvas.addEventListener("pointerup", event => {
dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
});
canvas.addEventListener("pointerleave", () => {
dragging = false;
$("tooltip").style.display = "none";
clearHover();
});
canvas.addEventListener("wheel", event => {
event.preventDefault();
desiredView.radius = THREE.MathUtils.clamp(
desiredView.radius + event.deltaY * 0.012,
12,
30
);
}, { passive: false });
canvas.addEventListener("dblclick", () => {
desiredView.theta = 0.12;
desiredView.phi = 1.02;
desiredView.radius = window.innerWidth < 760 ? 24 : 19;
});
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const hoverTargets = [];
let hoveredBody = null;
for (const visual of Object.values(popVisuals)) {
for (const organism of visual.organisms) {
hoverTargets.push(organism.userData.body);
}
}
function clearHover() {
if (hoveredBody) {
hoveredBody.material.emissive.setHex(0x000000);
hoveredBody.material.emissiveIntensity = 0;
}
hoveredBody = null;
}
function updateHover(event) {
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 intersections = raycaster.intersectObjects(hoverTargets, false);
if (!intersections.length) {
clearHover();
$("tooltip").style.display = "none";
return;
}
const body = intersections[0].object;
if (body !== hoveredBody) {
clearHover();
hoveredBody = body;
hoveredBody.material.emissive.setHex(0x16354a);
hoveredBody.material.emissiveIntensity = 0.7;
}
const genome = body.userData.genome;
const tooltip = $("tooltip");
tooltip.innerHTML = `
${genome.haps.join(" / ")}<br>
L1: ${genome.haps[0][0]} / ${genome.haps[1][0]}<br>
L2: ${genome.haps[0][1]} / ${genome.haps[1][1]}
`;
tooltip.style.display = "block";
const x = Math.min(event.clientX + 14, window.innerWidth - 220);
const y = Math.min(event.clientY + 14, window.innerHeight - 95);
tooltip.style.left = `${x}px`;
tooltip.style.top = `${y}px`;
}
// -------------------------------------------------------------------------
// Controls and keyboard shortcuts
// -------------------------------------------------------------------------
function setRunning(value) {
running = value;
$("play-btn").textContent = running ? "Pause" : "Play";
}
$("play-btn").addEventListener("click", () => setRunning(!running));
$("step-btn").addEventListener("click", () => stepGeneration());
$("reset-btn").addEventListener("click", () => {
setRunning(false);
resetSimulation();
});
document.querySelectorAll(".context-btn").forEach(button => {
button.addEventListener("click", () => {
context = button.dataset.context;
document.querySelectorAll(".context-btn").forEach(other => {
other.classList.toggle("active", other === button);
});
setRunning(false);
resetSimulation(
`Context changed to “${contexts[context].label}”; both sides were reset to the same founders.`
);
});
});
window.addEventListener("keydown", event => {
if (["INPUT", "SELECT", "TEXTAREA"].includes(document.activeElement.tagName)) return;
if (event.code === "Space") {
event.preventDefault();
setRunning(!running);
} else if (event.code === "ArrowRight") {
event.preventDefault();
setRunning(false);
stepGeneration();
} else if (event.key.toLowerCase() === "r") {
setRunning(false);
resetSimulation();
}
});
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
let accumulator = 0;
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
// Smooth the direct camera controls.
view.theta = THREE.MathUtils.lerp(view.theta, desiredView.theta, 0.1);
view.phi = THREE.MathUtils.lerp(view.phi, desiredView.phi, 0.1);
view.radius = THREE.MathUtils.lerp(view.radius, desiredView.radius, 0.1);
const sinPhi = Math.sin(view.phi);
camera.position.set(
view.target.x + view.radius * sinPhi * Math.sin(view.theta),
view.target.y + view.radius * Math.cos(view.phi),
view.target.z + view.radius * sinPhi * Math.cos(view.theta)
);
camera.lookAt(view.target);
if (running) {
accumulator += delta;
const interval = 1.35 / Number($("speed").value);
if (accumulator >= interval) {
accumulator -= interval;
stepGeneration();
}
}
for (const visual of Object.values(popVisuals)) {
for (const organism of visual.organisms) {
const data = organism.userData;
data.pulse *= 0.90;
const scale = 1 + data.pulse * 0.11;
organism.scale.set(scale, 1 + data.pulse * 0.055, scale);
}
if (visual.flashLife > 0) {
visual.flashLife = Math.max(0, visual.flashLife - delta * 1.6);
visual.flash.visible = true;
const s = 0.75 + (1 - visual.flashLife) * 0.85;
visual.flash.scale.setScalar(s);
visual.flash.rotation.y += delta * 2.2;
for (const material of visual.flashMaterials) {
material.opacity = visual.flashLife * 0.9;
}
} else {
visual.flash.visible = false;
}
}
dust.rotation.y += delta * 0.008;
rimLight.intensity = 23 + Math.sin(clock.elapsedTime * 0.8) * 2;
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
resetSimulation();
animate();
</script>
</body>
</html>
```