Prompt specification
Build or customize the Three.js 3D scene "Selective membrane sorting chamber" 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: Selective membrane sorting chamber
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/selective-membrane-sorting-chamber-x0854
Scene Description Prompt:
Only matching particles cross membrane channels between stylized chambers in a simplified biological analogy. Build one HTML scene with Three.js from cdnjs.
Working Three.js Starter (selective-membrane-sorting-chamber-x0854):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Selective Passage — Three.js Membrane Analogy</title>
<style>
:root {
color-scheme: dark;
--cyan: #5ce1e6;
--amber: #ffb454;
--violet: #c58cff;
--ink: #eaf7ff;
--muted: #8ca9bc;
--panel: rgba(8, 18, 31, 0.66);
--line: rgba(150, 213, 242, 0.17);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 52% 42%, #16334b 0%, #091523 43%, #040811 100%);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--ink);
}
#stage, #stage canvas {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
}
#stage canvas {
display: block;
touch-action: none;
outline: none;
}
#hud {
position: fixed;
inset: 0;
z-index: 2;
pointer-events: none;
}
.top {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 20px;
padding: 24px 28px;
}
.brand {
max-width: 480px;
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 8px;
margin-bottom: 10px;
color: #9ac8dc;
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.live-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 14px var(--cyan);
}
h1 {
margin: 0;
font-size: clamp(27px, 3vw, 43px);
font-weight: 620;
letter-spacing: -0.045em;
line-height: 1;
}
.subtitle {
margin: 10px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.stats {
display: flex;
align-items: stretch;
gap: 8px;
}
.stat {
min-width: 116px;
padding: 12px 14px;
border: 1px solid var(--line);
border-radius: 13px;
background: var(--panel);
backdrop-filter: blur(14px);
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.18);
}
.stat-label {
display: block;
margin-bottom: 5px;
color: #7f9eb2;
font: 650 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.stat-value {
display: flex;
align-items: baseline;
gap: 7px;
font: 650 22px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.stat-value small {
color: #7894a6;
font-size: 9px;
font-weight: 600;
letter-spacing: 0.08em;
}
.actions {
display: flex;
gap: 8px;
margin-top: 10px;
pointer-events: auto;
}
button {
appearance: none;
border: 1px solid var(--line);
border-radius: 10px;
padding: 9px 12px;
color: #cce3ef;
background: rgba(15, 32, 48, 0.78);
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.09em;
text-transform: uppercase;
cursor: pointer;
transition: 160ms ease;
}
button:hover {
color: white;
border-color: rgba(130, 221, 241, 0.45);
background: rgba(22, 49, 69, 0.9);
transform: translateY(-1px);
}
button:active { transform: translateY(0); }
.bottom {
position: absolute;
right: 28px;
bottom: 24px;
left: 28px;
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 18px;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.key {
display: flex;
align-items: center;
gap: 9px;
min-width: 142px;
padding: 10px 12px;
border: 1px solid var(--line);
border-radius: 12px;
background: var(--panel);
backdrop-filter: blur(14px);
}
.key-dot {
position: relative;
width: 20px;
height: 20px;
flex: 0 0 auto;
border: 1px solid currentColor;
border-radius: 50%;
box-shadow: inset 0 0 9px currentColor, 0 0 12px color-mix(in srgb, currentColor 35%, transparent);
}
.key-dot::after {
position: absolute;
inset: 5px;
border-radius: 50%;
background: currentColor;
content: "";
}
.key strong {
display: block;
color: #e7f6ff;
font: 700 11px/1.15 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.key span {
display: block;
margin-top: 3px;
color: #7894a6;
font-size: 9px;
}
.hint {
max-width: 290px;
padding: 11px 13px;
border: 1px solid var(--line);
border-radius: 12px;
color: #7894a6;
background: rgba(7, 16, 27, 0.52);
backdrop-filter: blur(12px);
font-size: 10px;
line-height: 1.55;
text-align: right;
}
.hint b { color: #b8d5e4; font-weight: 650; }
#tooltip {
position: fixed;
z-index: 3;
padding: 7px 9px;
border: 1px solid var(--line);
border-radius: 8px;
color: #dff5ff;
background: rgba(5, 13, 23, 0.88);
font: 600 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
pointer-events: none;
opacity: 0;
transform: translate(-50%, calc(-100% - 10px));
transition: opacity 120ms ease;
white-space: nowrap;
}
@media (max-width: 760px) {
.top { padding: 18px; }
.subtitle { display: none; }
.stats { flex-direction: column; }
.stat { min-width: 112px; padding: 9px 11px; }
.stat-value { font-size: 18px; }
.actions { justify-content: flex-end; }
.bottom {
right: 16px;
bottom: 16px;
left: 16px;
align-items: stretch;
flex-direction: column;
}
.legend { display: grid; grid-template-columns: repeat(3, 1fr); }
.key { min-width: 0; padding: 9px; }
.key span { display: none; }
.hint { max-width: none; text-align: left; }
}
</style>
</head>
<body>
<main id="stage" aria-label="Interactive 3D membrane transport model"></main>
<div id="hud">
<section class="top">
<div class="brand">
<div class="eyebrow">
<span class="live-dot"></span>
<span id="status">Live selectivity model</span>
</div>
<h1>Selective Passage</h1>
<p class="subtitle">
A simplified membrane analogy: particles cross only when their molecular
identity matches the channel.
</p>
</div>
<aside>
<div class="stats">
<div class="stat">
<span class="stat-label">Successful passages</span>
<div class="stat-value"><span id="passed">00</span><small>MATCH</small></div>
</div>
<div class="stat">
<span class="stat-label">Rejected pairings</span>
<div class="stat-value"><span id="blocked">00</span><small>NO MATCH</small></div>
</div>
</div>
<div class="actions">
<button id="pause" type="button">Pause</button>
<button id="reset" type="button">Reset</button>
</div>
</aside>
</section>
<section class="bottom">
<div class="legend" aria-label="Particle and channel identities">
<div class="key" style="color: var(--cyan)">
<span class="key-dot"></span>
<div><strong>A / CYAN</strong><span>A passes only gate A</span></div>
</div>
<div class="key" style="color: var(--amber)">
<span class="key-dot"></span>
<div><strong>B / AMBER</strong><span>B passes only gate B</span></div>
</div>
<div class="key" style="color: var(--violet)">
<span class="key-dot"></span>
<div><strong>C / VIOLET</strong><span>C passes only gate C</span></div>
</div>
</div>
<div class="hint">
<b>Drag</b> to orbit · <b>Scroll</b> to zoom · <b>Click</b> a particle to call its matching gate
</div>
</section>
</div>
<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";
const stage = document.querySelector("#stage");
const tooltip = document.querySelector("#tooltip");
const passedEl = document.querySelector("#passed");
const blockedEl = document.querySelector("#blocked");
const statusEl = document.querySelector("#status");
const pauseButton = document.querySelector("#pause");
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x07111d, 18, 35);
const camera = new THREE.PerspectiveCamera(
42,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.setClearColor(0x000000, 0);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
stage.appendChild(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xa9e9ff, 0x07101d, 1.45));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.4);
keyLight.position.set(4, 10, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -12;
keyLight.shadow.camera.right = 12;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x4ddce8, 34, 16, 2);
cyanLight.position.set(-6, 2, 3);
scene.add(cyanLight);
const violetLight = new THREE.PointLight(0xb66dff, 28, 16, 2);
violetLight.position.set(6, 1, -2);
scene.add(violetLight);
const types = [
{ letter: "A", name: "CYAN", color: 0x5ce1e6 },
{ letter: "B", name: "AMBER", color: 0xffb454 },
{ letter: "C", name: "VIOLET", color: 0xc58cff }
];
const channels = [
{ type: 0, y: 1.45, z: -2.65 },
{ type: 1, y: -1.45, z: 0.0 },
{ type: 2, y: 2.15, z: 2.65 }
];
const particles = [];
const particleCores = [];
const rejectionMarks = [];
let successfulPassages = 0;
let rejectedPairings = 0;
let paused = false;
let selectedParticle = null;
const cameraState = {
radius: 19.5,
theta: 0.57,
phi: 1.13,
target: new THREE.Vector3(0, -0.15, 0)
};
const tempObject = new THREE.Object3D();
const tempVector = new THREE.Vector3();
const tempVector2 = new THREE.Vector3();
function roundedRect(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
}
function canvasTexture(canvas) {
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.needsUpdate = true;
return texture;
}
function makeTextSprite(text, color, width = 2.2, height = 0.52) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const ctx = canvas.getContext("2d");
const cssColor = `#${new THREE.Color(color).getHexString()}`;
roundedRect(ctx, 8, 10, 496, 108, 26);
ctx.fillStyle = "rgba(5, 13, 23, 0.82)";
ctx.fill();
ctx.strokeStyle = cssColor;
ctx.lineWidth = 3;
ctx.stroke();
ctx.fillStyle = cssColor;
ctx.font = "700 43px ui-monospace, SFMono-Regular, Menlo, monospace";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 256, 65);
const material = new THREE.SpriteMaterial({
map: canvasTexture(canvas),
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(width, height, 1);
sprite.renderOrder = 20;
return sprite;
}
function makeLetterSprite(type) {
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 128;
const ctx = canvas.getContext("2d");
const cssColor = `#${new THREE.Color(type.color).getHexString()}`;
ctx.beginPath();
ctx.arc(64, 64, 46, 0, Math.PI * 2);
ctx.fillStyle = "rgba(5, 13, 23, 0.9)";
ctx.fill();
ctx.strokeStyle = cssColor;
ctx.lineWidth = 5;
ctx.stroke();
ctx.fillStyle = "#f0fbff";
ctx.font = "700 49px ui-monospace, SFMono-Regular, Menlo, monospace";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(type.letter, 64, 66);
const material = new THREE.SpriteMaterial({
map: canvasTexture(canvas),
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(0.34, 0.34, 1);
sprite.position.y = 0.31;
sprite.renderOrder = 22;
return sprite;
}
function makeGlowTexture() {
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 128;
const ctx = canvas.getContext("2d");
const gradient = ctx.createRadialGradient(64, 64, 0, 64, 64, 64);
gradient.addColorStop(0, "rgba(255,255,255,0.95)");
gradient.addColorStop(0.16, "rgba(255,255,255,0.52)");
gradient.addColorStop(0.48, "rgba(255,255,255,0.15)");
gradient.addColorStop(1, "rgba(255,255,255,0)");
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 128, 128);
return canvasTexture(canvas);
}
const glowTexture = makeGlowTexture();
function makeRejectionTexture() {
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.strokeStyle = "#ff657a";
ctx.lineWidth = 10;
ctx.lineCap = "round";
ctx.shadowColor = "#ff657a";
ctx.shadowBlur = 16;
ctx.beginPath();
ctx.moveTo(34, 34);
ctx.lineTo(94, 94);
ctx.moveTo(94, 34);
ctx.lineTo(34, 94);
ctx.stroke();
return canvasTexture(canvas);
}
const rejectionTexture = makeRejectionTexture();
// Ground and reference grid.
const shadowFloor = new THREE.Mesh(
new THREE.PlaneGeometry(32, 26),
new THREE.ShadowMaterial({ color: 0x000000, opacity: 0.2 })
);
shadowFloor.rotation.x = -Math.PI / 2;
shadowFloor.position.y = -5.02;
shadowFloor.receiveShadow = true;
scene.add(shadowFloor);
const grid = new THREE.GridHelper(30, 30, 0x24506a, 0x153044);
grid.position.y = -5;
grid.material.transparent = true;
grid.material.opacity = 0.34;
scene.add(grid);
// Translucent chamber volumes.
function createChamber(side) {
const chamber = new THREE.Group();
const volume = new THREE.Mesh(
new THREE.BoxGeometry(6.7, 10, 8.8),
new THREE.MeshBasicMaterial({
color: side < 0 ? 0x0a3a57 : 0x302044,
transparent: true,
opacity: 0.035,
depthWrite: false,
side: THREE.DoubleSide
})
);
volume.position.x = side * 3.65;
chamber.add(volume);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(volume.geometry),
new THREE.LineBasicMaterial({
color: side < 0 ? 0x4a9db8 : 0x9a70ba,
transparent: true,
opacity: 0.16
})
);
edges.position.copy(volume.position);
chamber.add(edges);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(6.7, 8.8),
new THREE.MeshStandardMaterial({
color: side < 0 ? 0x0b334d : 0x281a3d,
emissive: side < 0 ? 0x061725 : 0x160b22,
emissiveIntensity: 0.35,
transparent: true,
opacity: 0.24,
roughness: 0.85,
side: THREE.DoubleSide
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.set(side * 3.65, -4.96, 0);
floor.receiveShadow = true;
chamber.add(floor);
const label = makeTextSprite(
side < 0 ? "EXTRACELLULAR" : "CYTOPLASM",
side < 0 ? 0x6fd9ec : 0xc991ff,
side < 0 ? 3.0 : 2.15,
0.48
);
label.position.set(side * 3.65, 4.55, -1.55);
chamber.add(label);
scene.add(chamber);
}
createChamber(-1);
createChamber(1);
// A membrane slab with actual circular openings.
const membraneShape = new THREE.Shape();
membraneShape.moveTo(-4.7, -5);
membraneShape.lineTo(4.7, -5);
membraneShape.lineTo(4.7, 5);
membraneShape.lineTo(-4.7, 5);
membraneShape.closePath();
for (const channel of channels) {
const hole = new THREE.Path();
hole.absarc(-channel.z, channel.y, 0.72, 0, Math.PI * 2, true);
membraneShape.holes.push(hole);
}
const membraneGeometry = new THREE.ExtrudeGeometry(membraneShape, {
depth: 0.44,
bevelEnabled: true,
bevelSize: 0.035,
bevelThickness: 0.035,
bevelSegments: 2,
curveSegments: 32
});
const membrane = new THREE.Mesh(
membraneGeometry,
new THREE.MeshPhysicalMaterial({
color: 0x17405b,
emissive: 0x061724,
emissiveIntensity: 0.5,
transparent: true,
opacity: 0.56,
roughness: 0.32,
metalness: 0.14,
clearcoat: 0.4,
side: THREE.DoubleSide
})
);
membrane.rotation.y = Math.PI / 2;
membrane.position.x = -0.22;
membrane.castShadow = true;
membrane.receiveShadow = true;
scene.add(membrane);
const membraneEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(membraneGeometry, 32),
new THREE.LineBasicMaterial({
color: 0x67b4cf,
transparent: true,
opacity: 0.42
})
);
membrane.add(membraneEdges);
// Small membrane beads suggest a stylized lipid bilayer.
const beadPositions = [];
for (let y = -4.55; y <= 4.55; y += 0.42) {
for (let z = -4.2; z <= 4.2; z += 0.42) {
const nearOpening = channels.some(
channel => Math.hypot(y - channel.y, z - channel.z) < 0.88
);
if (!nearOpening) beadPositions.push(new THREE.Vector3(0.245, y, z));
}
}
const beadMesh = new THREE.InstancedMesh(
new THREE.SphereGeometry(0.038, 7, 6),
new THREE.MeshBasicMaterial({
color: 0x8ad8e5,
transparent: true,
opacity: 0.28,
depthWrite: false
}),
beadPositions.length
);
beadPositions.forEach((position, index) => {
tempObject.position.copy(position);
tempObject.scale.setScalar(1);
tempObject.updateMatrix();
beadMesh.setMatrixAt(index, tempObject.matrix);
});
scene.add(beadMesh);
// Selective channel sleeves and receptor collars.
for (let index = 0; index < channels.length; index++) {
const channel = channels[index];
const type = types[channel.type];
const group = new THREE.Group();
group.position.set(0, channel.y, channel.z);
const shellMaterial = new THREE.MeshBasicMaterial({
color: type.color,
transparent: true,
opacity: 0.105,
side: THREE.DoubleSide,
depthWrite: false,
blending: THREE.AdditiveBlending
});
const shell = new THREE.Mesh(
new THREE.CylinderGeometry(0.64, 0.64, 3.3, 32, 1, true),
shellMaterial
);
shell.rotation.z = Math.PI / 2;
group.add(shell);
const ringMaterial = new THREE.MeshBasicMaterial({
color: type.color,
transparent: true,
opacity: 0.57,
depthWrite: false
});
for (const x of [-1.55, -0.78, 0, 0.78, 1.55]) {
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.645, 0.018, 8, 48),
ringMaterial
);
ring.rotation.y = Math.PI / 2;
ring.position.x = x;
group.add(ring);
}
for (const side of [-1, 1]) {
const collar = new THREE.Mesh(
new THREE.TorusGeometry(0.68, 0.065, 10, 48),
ringMaterial
);
collar.rotation.y = Math.PI / 2;
collar.position.x = side * 1.64;
group.add(collar);
for (let toothIndex = 0; toothIndex < 7; toothIndex++) {
const angle = (toothIndex / 7) * Math.PI * 2;
const tooth = new THREE.Mesh(
new THREE.BoxGeometry(0.25, 0.13, 0.13),
ringMaterial
);
tooth.position.set(
side * 1.64,
Math.cos(angle) * 0.57,
Math.sin(angle) * 0.57
);
tooth.rotation.x = angle;
group.add(tooth);
}
}
const aperture = new THREE.Mesh(
new THREE.TorusGeometry(0.46, 0.024, 8, 48),
ringMaterial
);
aperture.rotation.y = Math.PI / 2;
group.add(aperture);
const label = makeTextSprite(
`${type.letter} / ${type.name}`,
type.color,
2.0,
0.48
);
label.position.set(0, 1.02, 0);
group.add(label);
channel.group = group;
channel.ringMaterial = ringMaterial;
channel.shellMaterial = shellMaterial;
channel.flash = 0;
scene.add(group);
}
const membraneLabel = makeTextSprite(
"SELECTIVE MEMBRANE",
0x8ec8de,
3.15,
0.42
);
membraneLabel.position.set(0.35, -4.35, 0.4);
scene.add(membraneLabel);
// Sparse suspended motes provide depth without competing with the particles.
function createMotes(side, color, count) {
const positions = new Float32Array(count * 3);
for (let i = 0; i < count; i++) {
positions[i * 3] = side * (0.8 + Math.random() * 6.1);
positions[i * 3 + 1] = -4.6 + Math.random() * 9.2;
positions[i * 3 + 2] = -4.1 + Math.random() * 8.2;
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
const points = new THREE.Points(
geometry,
new THREE.PointsMaterial({
color,
size: 0.035,
transparent: true,
opacity: 0.32,
depthWrite: false,
blending: THREE.AdditiveBlending
})
);
scene.add(points);
}
createMotes(-1, 0x67d8e6, 180);
createMotes(1, 0xb88bdb, 180);
function createParticle(typeIndex, index) {
const type = types[typeIndex];
const group = new THREE.Group();
const core = new THREE.Mesh(
new THREE.SphereGeometry(0.145, 18, 14),
new THREE.MeshStandardMaterial({
color: type.color,
emissive: type.color,
emissiveIntensity: 0.82,
roughness: 0.2,
metalness: 0.12
})
);
core.castShadow = true;
const halo = new THREE.Sprite(
new THREE.SpriteMaterial({
map: glowTexture,
color: type.color,
transparent: true,
opacity: 0.48,
depthWrite: false,
blending: THREE.AdditiveBlending
})
);
halo.scale.set(0.72, 0.72, 1);
const particle = {
index,
typeIndex,
group,
core,
pos: new THREE.Vector3(),
side: Math.random() < 0.5 ? -1 : 1,
state: "roam",
targetChannel: typeIndex,
timer: Math.random() * 3,
speed: 1.15 + Math.random() * 0.9,
velocityY: (Math.random() - 0.5) * 0.48,
velocityZ: (Math.random() - 0.5) * 0.48,
crossTime: 0,
crossDuration: 2.2 + Math.random() * 0.6,
blockedTime: 0,
phase: Math.random() * Math.PI * 2,
selection: 0
};
core.userData.particle = particle;
group.add(halo, core, makeLetterSprite(type));
scene.add(group);
particles.push(particle);
particleCores.push(core);
}
for (let i = 0; i < 24; i++) {
createParticle(i % types.length, i);
}
function spawnRejectionMark(position) {
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: rejectionTexture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.position.copy(position);
sprite.position.y += 0.38;
sprite.scale.set(0.62, 0.62, 1);
sprite.renderOrder = 30;
scene.add(sprite);
rejectionMarks.push({ sprite, life: 0.65, maxLife: 0.65 });
}
function resetSimulation() {
successfulPassages = 0;
rejectedPairings = 0;
selectedParticle = null;
for (const mark of rejectionMarks) {
scene.remove(mark.sprite);
mark.sprite.material.dispose();
}
rejectionMarks.length = 0;
particles.forEach((particle, index) => {
particle.side = index % 2 === 0 ? -1 : 1;
particle.pos.set(
particle.side * (2.0 + Math.random() * 4.25),
-4.25 + Math.random() * 8.5,
-3.85 + Math.random() * 7.7
);
particle.state = "roam";
particle.timer = 0.4 + Math.random() * 2.8;
particle.targetChannel = particle.typeIndex;
particle.velocityY = (Math.random() - 0.5) * 0.48;
particle.velocityZ = (Math.random() - 0.5) * 0.48;
particle.selection = 0;
// Begin several particles with an immediate, visibly valid passage.
if (index < 6) {
particle.state = "seek";
particle.targetChannel = particle.typeIndex;
particle.timer = 0;
}
});
}
function updateParticles(dt, elapsed) {
for (const particle of particles) {
if (particle.state === "roam") {
particle.timer -= dt;
particle.velocityY +=
Math.sin(elapsed * 0.9 + particle.phase) * 0.035 * dt;
particle.velocityZ +=
Math.cos(elapsed * 0.75 + particle.phase) * 0.035 * dt;
particle.velocityY *= 0.998;
particle.velocityZ *= 0.998;
particle.pos.y += particle.velocityY * dt;
particle.pos.z += particle.velocityZ * dt;
if (particle.pos.y < -4.42 || particle.pos.y > 4.42) {
particle.pos.y = THREE.MathUtils.clamp(
particle.pos.y,
-4.42,
4.42
);
particle.velocityY *= -1;
}
if (particle.pos.z < -3.9 || particle.pos.z > 3.9) {
particle.pos.z = THREE.MathUtils.clamp(
particle.pos.z,
-3.9,
3.9
);
particle.velocityZ *= -1;
}
if (particle.timer <= 0) {
// Deliberately attempt a random gate. The match check below
// is the only path that allows a side change.
particle.targetChannel =
Math.floor(Math.random() * channels.length);
particle.state = "seek";
}
}
if (particle.state === "seek") {
const channel = channels[particle.targetChannel];
tempVector.set(
particle.side * 1.72,
channel.y,
channel.z
);
tempVector2.subVectors(tempVector, particle.pos);
const distance = tempVector2.length();
const step = particle.speed * dt;
if (distance <= step) {
particle.pos.copy(tempVector);
if (particle.typeIndex === channel.type) {
particle.state = "cross";
particle.crossTime = 0;
channel.flash = 1;
} else {
particle.state = "blocked";
particle.blockedTime = 0;
rejectedPairings++;
spawnRejectionMark(particle.pos);
}
} else {
particle.pos.addScaledVector(
tempVector2.normalize(),
step
);
}
}
if (particle.state === "blocked") {
particle.blockedTime += dt;
// Bounce back into the originating chamber.
particle.pos.x += particle.side * dt * 2.5;
particle.pos.y += Math.sin(elapsed * 7 + particle.phase) * dt * 0.12;
if (particle.blockedTime > 0.62) {
particle.state = "roam";
particle.timer = 0.45 + Math.random() * 0.8;
}
}
if (particle.state === "cross") {
particle.crossTime += dt;
const channel = channels[particle.targetChannel];
const t = Math.min(
particle.crossTime / particle.crossDuration,
1
);
const eased = t * t * (3 - 2 * t);
particle.pos.x = THREE.MathUtils.lerp(
particle.side * 1.72,
-particle.side * 1.72,
eased
);
particle.pos.y =
channel.y + Math.sin(t * Math.PI) * 0.045;
particle.pos.z =
channel.z + Math.sin(t * Math.PI * 2) * 0.025;
if (t >= 1) {
particle.side *= -1;
particle.state = "roam";
particle.timer = 0.5 + Math.random() * 1.3;
particle.pos.x = particle.side * 1.85;
successfulPassages++;
}
}
particle.selection = Math.max(
0,
particle.selection - dt * 1.8
);
const pulse =
1 +
Math.sin(elapsed * 2.5 + particle.phase) * 0.025 +
particle.selection * 0.28;
particle.group.position.copy(particle.pos);
particle.group.scale.setScalar(pulse);
}
}
function updateEffects(dt) {
for (const channel of channels) {
channel.flash = Math.max(0, channel.flash - dt * 1.25);
channel.ringMaterial.opacity = 0.5 + channel.flash * 0.42;
channel.shellMaterial.opacity = 0.095 + channel.flash * 0.14;
}
for (let i = rejectionMarks.length - 1; i >= 0; i--) {
const mark = rejectionMarks[i];
mark.life -= dt;
const life = Math.max(0, mark.life / mark.maxLife);
mark.sprite.material.opacity = life;
mark.sprite.scale.setScalar(0.45 + (1 - life) * 0.35);
mark.sprite.position.y += dt * 0.3;
if (mark.life <= 0) {
scene.remove(mark.sprite);
mark.sprite.material.dispose();
rejectionMarks.splice(i, 1);
}
}
}
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 resetCamera() {
cameraState.radius = 19.5;
cameraState.theta = 0.57;
cameraState.phi = 1.13;
cameraState.target.set(0, -0.15, 0);
updateCamera();
}
updateCamera();
resetSimulation();
// Direct camera controls: no examples/addons are used.
let dragging = false;
let pointerId = null;
let lastX = 0;
let lastY = 0;
let downX = 0;
let downY = 0;
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const canvas = renderer.domElement;
canvas.addEventListener("pointerdown", event => {
dragging = true;
pointerId = event.pointerId;
lastX = downX = event.clientX;
lastY = downY = event.clientY;
canvas.setPointerCapture(pointerId);
canvas.style.cursor = "grabbing";
});
canvas.addEventListener("pointermove", event => {
if (dragging && event.pointerId === pointerId) {
const dx = event.clientX - lastX;
const dy = event.clientY - lastY;
lastX = event.clientX;
lastY = event.clientY;
cameraState.theta -= dx * 0.0055;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi + dy * 0.0045,
0.48,
1.46
);
updateCamera();
tooltip.style.opacity = "0";
} else {
updatePointer(event);
const hit = raycaster.intersectObjects(particleCores, false)[0];
canvas.style.cursor = hit ? "pointer" : "grab";
}
});
function endPointer(event) {
if (!dragging || event.pointerId !== pointerId) return;
const travel = Math.hypot(
event.clientX - downX,
event.clientY - downY
);
if (travel < 6 && event.button === 0) {
updatePointer(event);
const hit = raycaster.intersectObjects(particleCores, false)[0];
if (hit) {
const particle = hit.object.userData.particle;
selectedParticle = particle;
particle.selection = 1.5;
// A click requests the particle's own matching channel.
particle.targetChannel = particle.typeIndex;
particle.state = "seek";
particle.timer = 0;
tooltip.textContent =
`${types[particle.typeIndex].letter} → matching gate`;
tooltip.style.left = `${event.clientX}px`;
tooltip.style.top = `${event.clientY}px`;
tooltip.style.opacity = "1";
setTimeout(() => {
tooltip.style.opacity = "0";
}, 1100);
}
}
dragging = false;
pointerId = null;
canvas.style.cursor = "grab";
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener(
"wheel",
event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
11.5,
28
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetCamera);
function updatePointer(event) {
pointer.x = (event.clientX / innerWidth) * 2 - 1;
pointer.y = -(event.clientY / innerHeight) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
function togglePause() {
paused = !paused;
pauseButton.textContent = paused ? "Resume" : "Pause";
statusEl.textContent = paused ? "Model paused" : "Live selectivity model";
}
pauseButton.addEventListener("click", togglePause);
document.querySelector("#reset").addEventListener("click", resetSimulation);
addEventListener("keydown", event => {
if (event.code === "Space") {
event.preventDefault();
togglePause();
}
if (event.key.toLowerCase() === "r") {
resetSimulation();
}
});
addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
});
const clock = new THREE.Clock();
let uiTimer = 0;
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.035);
const elapsed = clock.elapsedTime;
if (!paused) {
updateParticles(dt, elapsed);
}
updateEffects(dt);
uiTimer += dt;
if (uiTimer > 0.12) {
passedEl.textContent = String(successfulPassages).padStart(2, "0");
blockedEl.textContent = String(rejectedPairings).padStart(2, "0");
uiTimer = 0;
}
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```