Prompt specification
Build or customize the Three.js 3D scene "Run-and-turn microorganism path" 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: Run-and-turn microorganism path
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/run-and-turn-microorganism-path-x0850
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows flagellated microbes. Trace an invented microbe alternating straight runs with reorientation inside a bounded chamber; show its heading history without claiming the motion represents every bacterial species. Stylized solid forms.
Working Three.js Starter (run-and-turn-microorganism-path-x0850):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Flagellated Microbes — Abstract Motion Study</title>
<style>
:root {
color-scheme: dark;
--bg: #061119;
--panel: rgba(8, 25, 33, 0.82);
--panel-border: rgba(164, 221, 230, 0.17);
--text: #e9f4f3;
--muted: #89a5aa;
--run: #ffb45c;
--turn: #59dfd0;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--text);
}
#stage,
#stage canvas {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
}
#stage canvas {
touch-action: none;
cursor: grab;
}
#stage canvas:active {
cursor: grabbing;
}
.ui {
position: fixed;
inset: 0;
z-index: 5;
pointer-events: none;
}
.panel {
position: absolute;
pointer-events: auto;
border: 1px solid var(--panel-border);
border-radius: 14px;
background: var(--panel);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.22);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
#identity {
top: 22px;
left: 22px;
width: min(390px, calc(100vw - 44px));
padding: 19px 21px 17px;
}
.eyebrow {
margin-bottom: 8px;
color: var(--turn);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.22em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(22px, 2.3vw, 31px);
font-weight: 650;
letter-spacing: -0.035em;
line-height: 1.08;
}
.subtitle {
margin: 8px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
#phase {
display: inline-flex;
align-items: center;
gap: 8px;
margin-top: 14px;
padding: 7px 10px;
border: 1px solid rgba(255, 180, 92, 0.3);
border-radius: 999px;
color: var(--run);
background: rgba(255, 180, 92, 0.08);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
#phase[data-state="turn"] {
color: var(--turn);
border-color: rgba(89, 223, 208, 0.35);
background: rgba(89, 223, 208, 0.08);
}
#phase-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 13px currentColor;
}
#history-panel {
top: 22px;
right: 22px;
width: min(330px, calc(100vw - 44px));
padding: 16px 17px 13px;
}
.panel-title {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 11px;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
#history-id {
color: var(--muted);
font-weight: 650;
letter-spacing: 0.08em;
}
#history-canvas {
display: block;
width: 100%;
height: 142px;
border: 1px solid rgba(164, 221, 230, 0.1);
border-radius: 9px;
background:
linear-gradient(rgba(255, 255, 255, 0.018), rgba(255, 255, 255, 0)),
rgba(2, 12, 17, 0.38);
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 13px;
margin-top: 11px;
color: var(--muted);
font-size: 10px;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 15px;
height: 2px;
border-radius: 2px;
background: var(--run);
}
.swatch.turn {
background: var(--turn);
}
#stats-panel {
top: 235px;
right: 22px;
width: min(330px, calc(100vw - 44px));
padding: 15px 17px;
}
.stats-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px 18px;
}
.stat-label {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.stat-value {
display: block;
font-variant-numeric: tabular-nums;
font-size: 15px;
font-weight: 650;
}
#controls {
right: 22px;
bottom: 22px;
display: flex;
gap: 8px;
padding: 9px;
}
button {
border: 1px solid rgba(164, 221, 230, 0.16);
border-radius: 8px;
padding: 9px 12px;
color: var(--text);
background: rgba(255, 255, 255, 0.045);
font: inherit;
font-size: 11px;
font-weight: 650;
cursor: pointer;
transition: background 150ms ease, border-color 150ms ease, transform 150ms ease;
}
button:hover {
border-color: rgba(89, 223, 208, 0.45);
background: rgba(89, 223, 208, 0.09);
}
button:active {
transform: translateY(1px);
}
#disclaimer {
left: 22px;
bottom: 22px;
width: min(470px, calc(100vw - 44px));
padding: 13px 15px;
color: #9db3b7;
font-size: 11px;
line-height: 1.55;
}
#disclaimer strong {
color: #d7e6e6;
font-weight: 700;
}
#camera-help {
position: absolute;
left: 50%;
bottom: 25px;
transform: translateX(-50%);
color: rgba(205, 225, 226, 0.55);
font-size: 10px;
letter-spacing: 0.05em;
white-space: nowrap;
}
#specimen-label {
position: absolute;
z-index: 7;
padding: 6px 9px;
border: 1px solid rgba(255, 180, 92, 0.38);
border-radius: 7px;
color: #ffd19a;
background: rgba(16, 24, 27, 0.84);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
pointer-events: none;
transform: translate(-50%, -100%);
white-space: nowrap;
}
@media (max-width: 760px) {
#identity {
top: 12px;
left: 12px;
width: calc(100vw - 24px);
padding: 14px 16px;
}
#history-panel {
top: auto;
right: 12px;
bottom: 87px;
width: calc(100vw - 24px);
padding: 11px 12px 10px;
}
#history-canvas {
height: 92px;
}
#stats-panel {
display: none;
}
#controls {
right: 12px;
bottom: 12px;
}
#disclaimer {
left: 12px;
bottom: 65px;
width: calc(100vw - 24px);
max-height: 108px;
overflow: auto;
padding: 10px 12px;
font-size: 9px;
}
#camera-help {
display: none;
}
}
</style>
</head>
<body>
<div id="stage" aria-label="Interactive 3D chamber containing stylized flagellated microbes"></div>
<div class="ui">
<header id="identity" class="panel">
<div class="eyebrow">Abstract motion study / Chamber 04</div>
<h1>Flagellated forms</h1>
<p class="subtitle">
Click a microbe to inspect it. Its invented motion alternates between
straight runs and deliberate reorientation inside the chamber.
</p>
<div id="phase" data-state="run">
<span id="phase-dot"></span>
<span id="phase-text">Straight run</span>
</div>
</header>
<section id="history-panel" class="panel">
<div class="panel-title">
<span>Heading history</span>
<span id="history-id">M-07</span>
</div>
<canvas id="history-canvas"></canvas>
<div class="legend">
<span><i class="swatch"></i> Straight run</span>
<span><i class="swatch turn"></i> Reorientation</span>
</div>
</section>
<section id="stats-panel" class="panel">
<div class="panel-title">
<span>Specimen telemetry</span>
<span id="specimen-id">M-07</span>
</div>
<div class="stats-grid">
<div>
<span class="stat-label">Heading</span>
<span id="heading-value" class="stat-value">0°</span>
</div>
<div>
<span class="stat-label">Speed</span>
<span id="speed-value" class="stat-value">0.00</span>
</div>
<div>
<span class="stat-label">Turn target</span>
<span id="turn-value" class="stat-value">—</span>
</div>
<div>
<span class="stat-label">Run ends in</span>
<span id="run-value" class="stat-value">—</span>
</div>
</div>
</section>
<nav id="controls" class="panel" aria-label="Simulation controls">
<button id="pause-button" type="button">Pause</button>
<button id="clear-button" type="button">Clear paths</button>
<button id="camera-button" type="button">Reset camera</button>
</nav>
<aside id="disclaimer" class="panel">
<strong>Stylized, invented behavior.</strong>
The organism, timing, and state changes are illustrative. This is not a
physical model of bacterial swimming and does not represent the motion of
every bacterial species.
</aside>
<div id="camera-help">Drag to orbit · Scroll to zoom · Click a microbe to select</div>
<div id="specimen-label">M-07 / tracking</div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene
// -------------------------------------------------------------------------
const RUN_COLOR = 0xffb45c;
const TURN_COLOR = 0x59dfd0;
const CHAMBER_X = 8.4;
const CHAMBER_Z = 5.1;
const MAX_TRAIL_POINTS = 560;
const MAX_RECORDS = 440;
const stage = document.getElementById("stage");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x061119);
scene.fog = new THREE.Fog(0x061119, 20, 43);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
stage.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xc6f4ff, 0x102028, 1.65);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.8);
keyLight.position.set(-7, 12, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -13;
keyLight.shadow.camera.right = 13;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.bias = -0.0006;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x59dfd0, 25, 18, 2);
cyanLight.position.set(7, 4, -5);
scene.add(cyanLight);
const amberLight = new THREE.PointLight(0xffb45c, 22, 16, 2);
amberLight.position.set(-6, 3, 4);
scene.add(amberLight);
// -------------------------------------------------------------------------
// Deterministic random helper
// -------------------------------------------------------------------------
let randomSeed = 70419;
function random() {
randomSeed |= 0;
randomSeed = (randomSeed + 0x6d2b79f5) | 0;
let t = Math.imul(randomSeed ^ (randomSeed >>> 15), 1 | randomSeed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
function randomRange(min, max) {
return min + (max - min) * random();
}
function wrapAngle(angle) {
return Math.atan2(Math.sin(angle), Math.cos(angle));
}
function shortestAngle(from, to) {
return Math.atan2(Math.sin(to - from), Math.cos(to - from));
}
function smoothstep(value) {
return value * value * (3 - 2 * value);
}
// -------------------------------------------------------------------------
// Bounded chamber
// -------------------------------------------------------------------------
const floorMaterial = new THREE.MeshStandardMaterial({
color: 0x0d242c,
roughness: 0.82,
metalness: 0.08
});
const floor = new THREE.Mesh(
new THREE.BoxGeometry(18.5, 0.18, 11.5),
floorMaterial
);
floor.position.y = -0.12;
floor.receiveShadow = true;
scene.add(floor);
const wallMaterial = new THREE.MeshStandardMaterial({
color: 0x8bd6dc,
transparent: true,
opacity: 0.055,
roughness: 0.5,
metalness: 0,
side: THREE.DoubleSide,
depthWrite: false
});
const wallGeometryX = new THREE.BoxGeometry(0.08, 3.1, 11.5);
const wallGeometryZ = new THREE.BoxGeometry(18.5, 3.1, 0.08);
for (const x of [-9.25, 9.25]) {
const wall = new THREE.Mesh(wallGeometryX, wallMaterial);
wall.position.set(x, 1.45, 0);
scene.add(wall);
}
for (const z of [-5.75, 5.75]) {
const wall = new THREE.Mesh(wallGeometryZ, wallMaterial);
wall.position.set(0, 1.45, z);
scene.add(wall);
}
const chamberEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(18.5, 3.1, 11.5)),
new THREE.LineBasicMaterial({
color: 0x72cbd2,
transparent: true,
opacity: 0.34
})
);
chamberEdges.position.y = 1.45;
scene.add(chamberEdges);
const gridPositions = [];
for (let x = -9; x <= 9; x += 1) {
gridPositions.push(x, 0.005, -5.5, x, 0.005, 5.5);
}
for (let z = -5; z <= 5; z += 1) {
gridPositions.push(-9, 0.005, z, 9, 0.005, z);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridPositions, 3)
);
scene.add(
new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x76bfc7,
transparent: true,
opacity: 0.11
})
)
);
// -------------------------------------------------------------------------
// Shared geometry and materials
// -------------------------------------------------------------------------
const bodyGeometry = new THREE.SphereGeometry(1, 32, 20);
const ridgeGeometry = new THREE.TorusGeometry(0.29, 0.018, 7, 28);
const tailSegmentGeometry = new THREE.CylinderGeometry(0.035, 0.05, 1, 8);
const headingMarkerGeometry = new THREE.ConeGeometry(0.07, 0.22, 12);
const haloGeometry = new THREE.TorusGeometry(0.46, 0.025, 8, 40);
const selectionRing = new THREE.Mesh(
new THREE.TorusGeometry(0.83, 0.025, 8, 56),
new THREE.MeshBasicMaterial({
color: RUN_COLOR,
transparent: true,
opacity: 0.75,
depthWrite: false
})
);
selectionRing.rotation.x = Math.PI / 2;
selectionRing.position.y = 0.035;
scene.add(selectionRing);
// -------------------------------------------------------------------------
// Microbes
// -------------------------------------------------------------------------
const microbes = [];
const initialSpecs = [
{ x: -5.4, z: -2.2, color: 0x61d6c8, id: "M-03" },
{ x: -1.8, z: 2.7, color: 0x9b8cff, id: "M-05" },
{ x: 2.1, z: -0.9, color: 0xffb45c, id: "M-07" },
{ x: 5.4, z: 2.0, color: 0xff7895, id: "M-09" },
{ x: -4.7, z: 3.4, color: 0x76a9ff, id: "M-11" }
];
function createTrailLine(color) {
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(new Float32Array(MAX_TRAIL_POINTS * 3), 3)
);
geometry.setDrawRange(0, 0);
const material = new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.2,
depthWrite: false
});
const line = new THREE.Line(geometry, material);
line.frustumCulled = false;
scene.add(line);
return line;
}
function createMicrobe(spec, index) {
const root = new THREE.Group();
root.position.set(spec.x, 0.48, spec.z);
const bodyPivot = new THREE.Group();
root.add(bodyPivot);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: spec.color,
emissive: spec.color,
emissiveIntensity: 0.05,
roughness: 0.28,
metalness: 0.08
});
const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
body.scale.set(0.38, 0.3, 0.7);
body.castShadow = true;
body.receiveShadow = true;
body.userData.microbeIndex = index;
bodyPivot.add(body);
const ridgeMaterial = new THREE.MeshStandardMaterial({
color: 0x14323a,
roughness: 0.46,
metalness: 0.16
});
for (const z of [-0.26, 0, 0.26]) {
const ridge = new THREE.Mesh(ridgeGeometry, ridgeMaterial);
ridge.position.z = z;
ridge.scale.set(1.15, 0.84, 1);
bodyPivot.add(ridge);
}
const markerMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
emissive: spec.color,
emissiveIntensity: 0.45,
roughness: 0.25
});
const marker = new THREE.Mesh(headingMarkerGeometry, markerMaterial);
marker.rotation.x = Math.PI / 2;
marker.position.set(0, 0.32, 0.57);
bodyPivot.add(marker);
const turnHaloMaterial = new THREE.MeshBasicMaterial({
color: TURN_COLOR,
transparent: true,
opacity: 0.68,
depthWrite: false
});
const turnHalo = new THREE.Mesh(haloGeometry, turnHaloMaterial);
turnHalo.visible = false;
bodyPivot.add(turnHalo);
const tailMaterial = new THREE.MeshStandardMaterial({
color: 0xb8d8d7,
emissive: 0x2b7775,
emissiveIntensity: 0.14,
roughness: 0.4,
metalness: 0.05
});
const tailSegments = [];
for (let i = 0; i < 11; i++) {
const segment = new THREE.Mesh(tailSegmentGeometry, tailMaterial);
segment.castShadow = true;
root.add(segment);
tailSegments.push(segment);
}
const runTrail = createTrailLine(RUN_COLOR);
const turnTrail = createTrailLine(TURN_COLOR);
const arcGeometry = new THREE.BufferGeometry();
arcGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(new Float32Array(33 * 3), 3)
);
arcGeometry.setDrawRange(0, 0);
const arc = new THREE.Line(
arcGeometry,
new THREE.LineBasicMaterial({
color: TURN_COLOR,
transparent: true,
opacity: 0.9,
depthWrite: false
})
);
arc.frustumCulled = false;
scene.add(arc);
scene.add(root);
const microbe = {
index,
id: spec.id,
root,
bodyPivot,
body,
bodyMaterial,
marker,
markerMaterial,
turnHalo,
turnHaloMaterial,
tailSegments,
runTrail,
turnTrail,
arc,
x: spec.x,
z: spec.z,
heading: Math.atan2(-spec.x, -spec.z) + randomRange(-0.5, 0.5),
speed: randomRange(1.8, 2.45),
state: "run",
runElapsed: 0,
runDuration: randomRange(3.2, 6.2),
turnElapsed: 0,
turnDuration: 1.2,
turnStart: 0,
turnTarget: 0,
turnDelta: 0,
phase: randomRange(0, Math.PI * 2),
records: [],
runTrailPoints: [],
turnTrailPoints: [],
lastHistoryState: null,
historyAccumulator: 0
};
microbes.push(microbe);
return microbe;
}
initialSpecs.forEach(createMicrobe);
let selectedIndex = 2;
let selectedMicrobe = microbes[selectedIndex];
// -------------------------------------------------------------------------
// History and state transitions
// -------------------------------------------------------------------------
function beginTurn(microbe, targetHeading) {
if (microbe.state === "turn") return;
microbe.state = "turn";
microbe.turnStart = microbe.heading;
microbe.turnTarget = wrapAngle(targetHeading);
microbe.turnDelta = shortestAngle(microbe.turnStart, microbe.turnTarget);
microbe.turnElapsed = 0;
microbe.turnDuration = randomRange(0.85, 1.55);
}
function inwardTurnHeading(microbe) {
return Math.atan2(-microbe.x, -microbe.z) + randomRange(-0.8, 0.8);
}
function updateMicrobe(microbe, delta, simulationTime) {
if (microbe.state === "run") {
microbe.runElapsed += delta;
if (microbe.runElapsed >= microbe.runDuration) {
const direction = random() < 0.5 ? -1 : 1;
const amount = randomRange(0.85, 2.45);
beginTurn(microbe, microbe.heading + direction * amount);
}
} else {
microbe.turnElapsed += delta;
const progress = Math.min(1, microbe.turnElapsed / microbe.turnDuration);
const eased = smoothstep(progress);
microbe.heading = wrapAngle(
microbe.turnStart + microbe.turnDelta * eased
);
if (progress >= 1) {
microbe.heading = microbe.turnTarget;
microbe.state = "run";
microbe.runElapsed = 0;
microbe.runDuration = randomRange(3.1, 6.5);
}
}
const currentSpeed =
microbe.speed * (microbe.state === "run" ? 1 : 0.15);
microbe.x += Math.sin(microbe.heading) * currentSpeed * delta;
microbe.z += Math.cos(microbe.heading) * currentSpeed * delta;
const outside =
Math.abs(microbe.x) > CHAMBER_X ||
Math.abs(microbe.z) > CHAMBER_Z;
if (outside) {
microbe.x = THREE.MathUtils.clamp(
microbe.x,
-CHAMBER_X,
CHAMBER_X
);
microbe.z = THREE.MathUtils.clamp(
microbe.z,
-CHAMBER_Z,
CHAMBER_Z
);
beginTurn(microbe, inwardTurnHeading(microbe));
}
const bob = Math.sin(simulationTime * 2.2 + microbe.phase) * 0.025;
microbe.root.position.set(microbe.x, 0.48 + bob, microbe.z);
microbe.root.rotation.y = microbe.heading;
const banking =
microbe.state === "turn"
? Math.sin(
(microbe.turnElapsed / microbe.turnDuration) * Math.PI
) * 0.2
: Math.sin(simulationTime * 1.5 + microbe.phase) * 0.025;
microbe.bodyPivot.rotation.x = banking;
microbe.turnHalo.visible = microbe.state === "turn";
microbe.turnHaloMaterial.opacity =
0.4 + Math.sin(simulationTime * 9) * 0.18;
updateTail(microbe, simulationTime);
updateTurnArc(microbe);
microbe.historyAccumulator += delta;
if (microbe.historyAccumulator >= 0.09) {
microbe.historyAccumulator = 0;
recordHistory(microbe, simulationTime);
}
}
function recordHistory(microbe, simulationTime) {
const point = {
x: microbe.x,
z: microbe.z,
heading: microbe.heading,
headingDegrees:
((microbe.heading * 180) / Math.PI + 360) % 360,
state: microbe.state,
time: simulationTime
};
if (
microbe.lastHistoryState &&
microbe.lastHistoryState !== microbe.state
) {
microbe.runTrailPoints.push(point);
microbe.turnTrailPoints.push(point);
}
const targetTrail =
microbe.state === "run"
? microbe.runTrailPoints
: microbe.turnTrailPoints;
targetTrail.push(point);
if (targetTrail.length > MAX_TRAIL_POINTS) {
targetTrail.shift();
}
microbe.records.push(point);
if (microbe.records.length > MAX_RECORDS) {
microbe.records.shift();
}
microbe.lastHistoryState = microbe.state;
updateTrailGeometry(microbe.runTrail, microbe.runTrailPoints);
updateTrailGeometry(microbe.turnTrail, microbe.turnTrailPoints);
}
function updateTrailGeometry(line, points) {
const position = line.geometry.getAttribute("position");
const count = Math.min(points.length, MAX_TRAIL_POINTS);
for (let i = 0; i < count; i++) {
position.setXYZ(i, points[i].x, 0.065, points[i].z);
}
position.needsUpdate = true;
line.geometry.setDrawRange(0, count);
}
// -------------------------------------------------------------------------
// Solid, articulated flagella
// -------------------------------------------------------------------------
const tailUp = new THREE.Vector3(0, 1, 0);
function updateTail(microbe, simulationTime) {
const points = [];
const whip = microbe.state === "turn" ? 1.9 : 0.72;
for (let i = 0; i <= 11; i++) {
const u = i / 11;
const wave = Math.sin(
simulationTime * 7.2 - u * 8.4 + microbe.phase
);
const amplitude = (0.035 + u * 0.16) * whip;
points.push(
new THREE.Vector3(
wave * amplitude * u,
Math.cos(simulationTime * 5.1 - u * 7.5 + microbe.phase) *
amplitude *
0.45,
-0.62 - u * 1.62
)
);
}
const direction = new THREE.Vector3();
const midpoint = new THREE.Vector3();
for (let i = 0; i < microbe.tailSegments.length; i++) {
const a = points[i];
const b = points[i + 1];
const segment = microbe.tailSegments[i];
direction.subVectors(b, a);
const length = direction.length();
midpoint.copy(a).add(b).multiplyScalar(0.5);
segment.position.copy(midpoint);
segment.scale.set(1, length, 1);
segment.quaternion.setFromUnitVectors(
tailUp,
direction.normalize()
);
}
}
function updateTurnArc(microbe) {
if (microbe.state !== "turn") {
microbe.arc.visible = false;
return;
}
microbe.arc.visible = true;
const position = microbe.arc.geometry.getAttribute("position");
const radius = 1.18;
for (let i = 0; i <= 32; i++) {
const progress = i / 32;
const angle = microbe.turnStart + microbe.turnDelta * progress;
position.setXYZ(
i,
microbe.x + Math.sin(angle) * radius,
0.09,
microbe.z + Math.cos(angle) * radius
);
}
position.needsUpdate = true;
microbe.arc.geometry.setDrawRange(0, 33);
}
// -------------------------------------------------------------------------
// Selection
// -------------------------------------------------------------------------
function applySelection() {
selectedMicrobe = microbes[selectedIndex];
microbes.forEach((microbe, index) => {
const isSelected = index === selectedIndex;
microbe.bodyMaterial.emissiveIntensity = isSelected ? 0.3 : 0.045;
microbe.markerMaterial.emissiveIntensity = isSelected ? 0.8 : 0.3;
microbe.runTrail.material.opacity = isSelected ? 0.95 : 0.14;
microbe.turnTrail.material.opacity = isSelected ? 0.9 : 0.14;
microbe.runTrail.material.linewidth = isSelected ? 2 : 1;
microbe.turnTrail.material.linewidth = isSelected ? 2 : 1;
});
document.getElementById("history-id").textContent =
selectedMicrobe.id;
document.getElementById("specimen-id").textContent =
selectedMicrobe.id;
}
applySelection();
// -------------------------------------------------------------------------
// Custom camera controls — no addon imports
// -------------------------------------------------------------------------
const cameraState = {
radius: 23,
theta: 0.66,
phi: 1.02,
target: new THREE.Vector3(0, 0.4, 0)
};
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 = 23;
cameraState.theta = 0.66;
cameraState.phi = 1.02;
cameraState.target.set(0, 0.4, 0);
updateCamera();
}
updateCamera();
const pointer = {
active: false,
moved: false,
id: null,
x: 0,
y: 0
};
const raycaster = new THREE.Raycaster();
const pointerNdc = new THREE.Vector2();
renderer.domElement.addEventListener("pointerdown", (event) => {
pointer.active = true;
pointer.moved = false;
pointer.id = event.pointerId;
pointer.x = event.clientX;
pointer.y = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointer.active || event.pointerId !== pointer.id) return;
const dx = event.clientX - pointer.x;
const dy = event.clientY - pointer.y;
if (Math.abs(dx) + Math.abs(dy) > 3) {
pointer.moved = true;
}
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.42,
1.38
);
pointer.x = event.clientX;
pointer.y = event.clientY;
updateCamera();
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (event.pointerId !== pointer.id) return;
if (!pointer.moved) {
const rect = renderer.domElement.getBoundingClientRect();
pointerNdc.x =
((event.clientX - rect.left) / rect.width) * 2 - 1;
pointerNdc.y =
-((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointerNdc, camera);
const hits = raycaster.intersectObjects(
microbes.map((microbe) => microbe.body),
false
);
if (hits.length) {
selectedIndex = hits[0].object.userData.microbeIndex;
applySelection();
}
}
pointer.active = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointer.active = false;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.012,
12,
32
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
// -------------------------------------------------------------------------
// UI and heading-history chart
// -------------------------------------------------------------------------
const phaseElement = document.getElementById("phase");
const phaseText = document.getElementById("phase-text");
const headingValue = document.getElementById("heading-value");
const speedValue = document.getElementById("speed-value");
const turnValue = document.getElementById("turn-value");
const runValue = document.getElementById("run-value");
const specimenLabel = document.getElementById("specimen-label");
const historyCanvas = document.getElementById("history-canvas");
const historyContext = historyCanvas.getContext("2d");
function drawHistory() {
const width = historyCanvas.clientWidth;
const height = historyCanvas.clientHeight;
const ratio = Math.min(window.devicePixelRatio || 1, 2);
if (
historyCanvas.width !== Math.floor(width * ratio) ||
historyCanvas.height !== Math.floor(height * ratio)
) {
historyCanvas.width = Math.floor(width * ratio);
historyCanvas.height = Math.floor(height * ratio);
}
historyContext.setTransform(ratio, 0, 0, ratio, 0, 0);
historyContext.clearRect(0, 0, width, height);
const padding = {
left: 31,
right: 10,
top: 12,
bottom: 22
};
const chartWidth = width - padding.left - padding.right;
const chartHeight = height - padding.top - padding.bottom;
historyContext.lineWidth = 1;
historyContext.font = "9px system-ui, sans-serif";
historyContext.textBaseline = "middle";
for (const angle of [0, 90, 180, 270]) {
const y = padding.top + (angle / 360) * chartHeight;
historyContext.strokeStyle = "rgba(150, 190, 195, 0.11)";
historyContext.beginPath();
historyContext.moveTo(padding.left, y);
historyContext.lineTo(width - padding.right, y);
historyContext.stroke();
historyContext.fillStyle = "rgba(159, 185, 188, 0.6)";
historyContext.textAlign = "right";
historyContext.fillText(`${angle}°`, padding.left - 6, y);
}
const now = simulationTime;
const visibleSeconds = 24;
historyContext.textAlign = "left";
historyContext.fillStyle = "rgba(159, 185, 188, 0.6)";
historyContext.fillText("−24s", padding.left, height - 8);
historyContext.textAlign = "right";
historyContext.fillText("now", width - padding.right, height - 8);
const records = selectedMicrobe.records;
for (let i = 1; i < records.length; i++) {
const a = records[i - 1];
const b = records[i];
if (b.time < now - visibleSeconds) continue;
const angleDifference = Math.abs(
b.headingDegrees - a.headingDegrees
);
if (angleDifference > 180) continue;
const x1 =
padding.left +
((a.time - (now - visibleSeconds)) / visibleSeconds) *
chartWidth;
const x2 =
padding.left +
((b.time - (now - visibleSeconds)) / visibleSeconds) *
chartWidth;
const y1 =
padding.top + (a.headingDegrees / 360) * chartHeight;
const y2 =
padding.top + (b.headingDegrees / 360) * chartHeight;
historyContext.strokeStyle =
b.state === "run" ? "#ffb45c" : "#59dfd0";
historyContext.lineWidth = 2;
historyContext.beginPath();
historyContext.moveTo(x1, y1);
historyContext.lineTo(x2, y2);
historyContext.stroke();
}
if (records.length) {
const latest = records[records.length - 1];
const x =
padding.left +
((latest.time - (now - visibleSeconds)) / visibleSeconds) *
chartWidth;
const y =
padding.top + (latest.headingDegrees / 360) * chartHeight;
historyContext.fillStyle =
latest.state === "run" ? "#ffb45c" : "#59dfd0";
historyContext.beginPath();
historyContext.arc(x, y, 3.2, 0, Math.PI * 2);
historyContext.fill();
}
}
function updateInterface() {
const microbe = selectedMicrobe;
const isTurning = microbe.state === "turn";
phaseElement.dataset.state = microbe.state;
phaseText.textContent = isTurning ? "Reorienting" : "Straight run";
const degrees =
((microbe.heading * 180) / Math.PI + 360) % 360;
headingValue.textContent = `${Math.round(degrees)}°`;
const visibleSpeed =
microbe.speed * (isTurning ? 0.15 : 1);
speedValue.textContent = visibleSpeed.toFixed(2);
if (isTurning) {
const turnDegrees = Math.abs(
(microbe.turnDelta * 180) / Math.PI
);
turnValue.textContent = `${Math.round(turnDegrees)}°`;
runValue.textContent = "—";
} else {
turnValue.textContent = "—";
runValue.textContent = `${Math.max(
0,
microbe.runDuration - microbe.runElapsed
).toFixed(1)}s`;
}
specimenLabel.textContent =
`${microbe.id} / ${isTurning ? "reorienting" : "running"}`;
}
const projectedPosition = new THREE.Vector3();
function updateSpecimenLabel() {
projectedPosition.set(
selectedMicrobe.x,
1.12,
selectedMicrobe.z
);
projectedPosition.project(camera);
const visible =
projectedPosition.z > -1 &&
projectedPosition.z < 1;
specimenLabel.style.display = visible ? "block" : "none";
const x = (projectedPosition.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projectedPosition.y * 0.5 + 0.5) * window.innerHeight;
specimenLabel.style.left = `${x}px`;
specimenLabel.style.top = `${y}px`;
}
// -------------------------------------------------------------------------
// Controls
// -------------------------------------------------------------------------
let paused = false;
const pauseButton = document.getElementById("pause-button");
pauseButton.addEventListener("click", () => {
paused = !paused;
pauseButton.textContent = paused ? "Resume" : "Pause";
});
document.getElementById("camera-button").addEventListener(
"click",
resetCamera
);
document.getElementById("clear-button").addEventListener(
"click",
() => {
microbes.forEach((microbe) => {
microbe.records = [];
microbe.runTrailPoints = [];
microbe.turnTrailPoints = [];
microbe.lastHistoryState = null;
microbe.historyAccumulator = 0;
updateTrailGeometry(microbe.runTrail, []);
updateTrailGeometry(microbe.turnTrail, []);
});
}
);
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
let simulationTime = 0;
let interfaceAccumulator = 0;
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (!paused) {
simulationTime += delta;
for (const microbe of microbes) {
updateMicrobe(microbe, delta, simulationTime);
}
}
const pulse = 1 + Math.sin(simulationTime * 2.8) * 0.055;
selectionRing.position.x = selectedMicrobe.x;
selectionRing.position.z = selectedMicrobe.z;
selectionRing.scale.setScalar(pulse);
selectionRing.material.opacity = 0.62 + Math.sin(simulationTime * 2.8) * 0.14;
interfaceAccumulator += delta;
if (interfaceAccumulator >= 0.08) {
interfaceAccumulator = 0;
updateInterface();
drawHistory();
}
updateSpecimenLabel();
renderer.render(scene, camera);
}
animate();
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
drawHistory();
});
</script>
</body>
</html>
```