Prompt specification
Build or customize the Three.js 3D scene "Flagellated microbe motion model" 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: Flagellated microbe motion model
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/flagellated-microbe-motion-model-x0849
Scene Description Prompt:
Animate a low-poly microbe propelled by a rotating helical flagellum, with explicitly simplified hydrodynamics. Use Three.js from cdnjs in one HTML file.
Working Three.js Starter (flagellated-microbe-motion-model-x0849):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Helical Flagellum — Microbial Propulsion Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #050b16;
--panel: rgba(8, 19, 32, 0.78);
--border: rgba(127, 255, 231, 0.18);
--text: #e7fffb;
--muted: #7fa5a7;
--cyan: #55f4d0;
--pink: #ff579c;
--yellow: #ffd166;
}
* {
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;
}
.header {
position: fixed;
top: 20px;
left: 22px;
z-index: 5;
pointer-events: none;
}
.eyebrow {
margin-bottom: 6px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.24em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(22px, 3vw, 38px);
font-weight: 650;
letter-spacing: -0.045em;
line-height: 1;
}
.subtitle {
margin-top: 9px;
color: var(--muted);
font-size: 12px;
letter-spacing: 0.03em;
}
.model-card {
position: fixed;
top: 20px;
right: 22px;
z-index: 5;
width: 285px;
padding: 16px 17px;
border: 1px solid var(--border);
border-radius: 15px;
background: var(--panel);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.22);
backdrop-filter: blur(14px);
}
.model-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 12px;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.badge {
padding: 4px 7px;
border: 1px solid rgba(85, 244, 208, 0.25);
border-radius: 99px;
color: var(--cyan);
background: rgba(85, 244, 208, 0.07);
font-size: 9px;
letter-spacing: 0.08em;
}
.equations {
display: grid;
gap: 8px;
font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
font-size: 12px;
line-height: 1.4;
}
.equations div {
display: flex;
justify-content: space-between;
gap: 12px;
}
.equations span:first-child {
color: #c8fff4;
}
.equation-note {
margin-top: 12px;
padding-top: 11px;
border-top: 1px solid rgba(255, 255, 255, 0.07);
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.controls {
position: fixed;
z-index: 8;
left: 50%;
bottom: 20px;
width: min(760px, calc(100vw - 28px));
transform: translateX(-50%);
display: grid;
grid-template-columns: 1.2fr 1.2fr auto auto auto;
align-items: center;
gap: 15px;
padding: 14px 16px;
border: 1px solid var(--border);
border-radius: 17px;
background: rgba(7, 17, 29, 0.86);
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.34);
backdrop-filter: blur(16px);
}
.control label {
display: flex;
justify-content: space-between;
gap: 8px;
margin-bottom: 8px;
color: #a9c8c8;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.control output {
color: var(--cyan);
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 10px;
letter-spacing: 0;
text-transform: none;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
appearance: none;
border-radius: 99px;
outline: none;
background: #19323b;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 14px;
height: 14px;
appearance: none;
border: 2px solid #07131f;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px rgba(85, 244, 208, 0.6);
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border: 2px solid #07131f;
border-radius: 50%;
background: var(--cyan);
}
button {
height: 36px;
padding: 0 13px;
border: 1px solid rgba(85, 244, 208, 0.25);
border-radius: 9px;
color: var(--text);
background: rgba(85, 244, 208, 0.08);
font: inherit;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.09em;
cursor: pointer;
}
button:hover {
background: rgba(85, 244, 208, 0.16);
}
.toggle {
display: flex;
align-items: center;
gap: 7px;
color: #a9c8c8;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.05em;
white-space: nowrap;
cursor: pointer;
}
.toggle input {
accent-color: var(--cyan);
}
.stats {
position: fixed;
z-index: 5;
left: 22px;
bottom: 22px;
display: flex;
gap: 8px;
pointer-events: none;
}
.stat {
min-width: 92px;
padding: 9px 11px;
border: 1px solid rgba(255, 255, 255, 0.07);
border-radius: 10px;
background: rgba(7, 17, 29, 0.56);
}
.stat-label {
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.stat-value {
margin-top: 4px;
color: #dffff8;
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 12px;
}
.force-label {
position: fixed;
z-index: 4;
padding: 4px 7px;
border: 1px solid currentColor;
border-radius: 5px;
background: rgba(4, 11, 20, 0.78);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.13em;
pointer-events: none;
transform: translate(-50%, -50%);
white-space: nowrap;
}
#label-thrust {
color: var(--cyan);
}
#label-drag {
color: var(--pink);
}
#label-velocity {
color: var(--yellow);
}
.help {
position: fixed;
z-index: 4;
right: 22px;
bottom: 118px;
color: rgba(175, 210, 210, 0.6);
font-size: 10px;
pointer-events: none;
}
@media (max-width: 900px) {
.model-card {
top: 102px;
right: 14px;
width: 250px;
}
.stats {
bottom: 118px;
}
.help {
display: none;
}
}
@media (max-width: 700px) {
.header {
top: 14px;
left: 14px;
}
.subtitle {
display: none;
}
.model-card {
display: none;
}
.controls {
bottom: 12px;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.controls button,
.controls .toggle {
justify-self: stretch;
}
.stats {
left: 14px;
bottom: 132px;
}
.stat {
min-width: 78px;
}
}
</style>
</head>
<body>
<div id="stage"></div>
<header class="header">
<div class="eyebrow">Microbial propulsion / 01</div>
<h1>Helical Flagellum</h1>
<div class="subtitle">
Low-poly swimmer · resistive-force hydrodynamics
</div>
</header>
<aside class="model-card">
<div class="model-title">
<span>Hydrodynamic model</span>
<span class="badge">LOW RE</span>
</div>
<div class="equations">
<div><span>T = η(Ωr − v∥)</span></div>
<div><span>D∥ = −c∥v∥</span></div>
<div><span>D⊥ = −c⊥v⊥</span></div>
<div><span>τ = ℓD⊥ − cωω</span></div>
</div>
<div class="equation-note">
A deliberately reduced model: anisotropic body drag and slip-driven
flagellar thrust. No pressure-field solve, vortex shedding, or
surrounding-fluid inertia is included.
</div>
</aside>
<div class="stats">
<div class="stat">
<div class="stat-label">Speed</div>
<div class="stat-value" id="speed-value">0.00 L/s</div>
</div>
<div class="stat">
<div class="stat-label">Slip</div>
<div class="stat-value" id="slip-value">0.0</div>
</div>
<div class="stat">
<div class="stat-label">Drag</div>
<div class="stat-value" id="drag-value">0.00</div>
</div>
</div>
<div class="help">Drag to orbit · Scroll to zoom · Double-click to reset view</div>
<div id="label-thrust" class="force-label">THRUST</div>
<div id="label-drag" class="force-label">DRAG</div>
<div id="label-velocity" class="force-label">VELOCITY</div>
<section class="controls">
<div class="control">
<label for="rpm">
Flagellar drive
<output id="rpm-output">+720 rpm</output>
</label>
<input
id="rpm"
type="range"
min="-1200"
max="1200"
step="10"
value="720"
>
</div>
<div class="control">
<label for="resistance">
Fluid resistance
<output id="resistance-output">1.00×</output>
</label>
<input
id="resistance"
type="range"
min="0.5"
max="2.5"
step="0.05"
value="1"
>
</div>
<button id="pause" type="button" aria-pressed="false">PAUSE</button>
<button id="reset" type="button">RESET</button>
<label class="toggle">
<input id="show-forces" type="checkbox" checked>
Forces
</label>
</section>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
const stage = document.getElementById("stage");
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x050b16);
scene.fog = new THREE.Fog(0x050b16, 8, 20);
const camera = new THREE.PerspectiveCamera(
46,
window.innerWidth / window.innerHeight,
0.1,
100
);
// -------------------------------------------------------------------------
// Lighting and environment
// -------------------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0xa9e8ff, 0x07111d, 1.6));
const keyLight = new THREE.DirectionalLight(0xc8fff3, 3.2);
keyLight.position.set(4, 7, 3);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -7;
keyLight.shadow.camera.right = 7;
keyLight.shadow.camera.top = 7;
keyLight.shadow.camera.bottom = -7;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 20;
keyLight.shadow.bias = -0.001;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x237dff, 18, 9, 2);
rimLight.position.set(-4, 1.5, -3);
scene.add(rimLight);
const underLight = new THREE.PointLight(0x19e4bd, 5, 6, 2);
underLight.position.set(0, -0.4, 1);
scene.add(underLight);
const dish = new THREE.Mesh(
new THREE.CircleGeometry(5.4, 96),
new THREE.MeshStandardMaterial({
color: 0x06131e,
roughness: 0.96,
metalness: 0.03,
transparent: true,
opacity: 0.93
})
);
dish.rotation.x = -Math.PI / 2;
dish.position.y = -0.8;
dish.receiveShadow = true;
scene.add(dish);
const grid = new THREE.GridHelper(
11,
28,
0x2b7f83,
0x173441
);
grid.position.y = -0.785;
grid.material.transparent = true;
grid.material.opacity = 0.18;
scene.add(grid);
const dishRim = new THREE.Mesh(
new THREE.TorusGeometry(5.4, 0.025, 6, 128),
new THREE.MeshBasicMaterial({
color: 0x48ddc3,
transparent: true,
opacity: 0.42
})
);
dishRim.rotation.x = Math.PI / 2;
dishRim.position.y = -0.74;
scene.add(dishRim);
// Sparse fluid-like motes, decorative only.
const moteCount = 230;
const motePositions = new Float32Array(moteCount * 3);
for (let i = 0; i < moteCount; i++) {
const angle = Math.random() * Math.PI * 2;
const radius = Math.sqrt(Math.random()) * 5.1;
motePositions[i * 3] = Math.cos(angle) * radius;
motePositions[i * 3 + 1] = -0.45 + Math.random() * 2.2;
motePositions[i * 3 + 2] = Math.sin(angle) * radius;
}
const moteGeometry = new THREE.BufferGeometry();
moteGeometry.setAttribute(
"position",
new THREE.BufferAttribute(motePositions, 3)
);
const motes = new THREE.Points(
moteGeometry,
new THREE.PointsMaterial({
color: 0x79bdbb,
size: 0.022,
transparent: true,
opacity: 0.36,
depthWrite: false,
sizeAttenuation: true
})
);
scene.add(motes);
// -------------------------------------------------------------------------
// Low-poly microbe
// Local +X is the swimming direction. The flagellum trails toward -X.
// -------------------------------------------------------------------------
const microbe = new THREE.Group();
const bodyVisual = new THREE.Group();
microbe.add(bodyVisual);
scene.add(microbe);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0x31cdb5,
emissive: 0x063d39,
emissiveIntensity: 0.45,
roughness: 0.42,
metalness: 0.12,
flatShading: true
});
const body = new THREE.Mesh(
new THREE.IcosahedronGeometry(1, 2),
bodyMaterial
);
body.scale.set(1.16, 0.54, 0.57);
body.castShadow = true;
body.receiveShadow = true;
bodyVisual.add(body);
// Slightly darker forward cap.
const cap = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.42, 1),
new THREE.MeshStandardMaterial({
color: 0x159b91,
emissive: 0x052d2b,
emissiveIntensity: 0.35,
roughness: 0.5,
flatShading: true
})
);
cap.position.set(1.02, 0, 0);
cap.scale.set(0.55, 1.05, 1.08);
cap.castShadow = true;
bodyVisual.add(cap);
// Low-poly surface studs / receptors.
const studGeometry = new THREE.ConeGeometry(0.045, 0.16, 4);
const studMaterial = new THREE.MeshStandardMaterial({
color: 0x8affdf,
roughness: 0.55,
metalness: 0.08,
flatShading: true
});
const up = new THREE.Vector3(0, 1, 0);
const goldenAngle = Math.PI * (3 - Math.sqrt(5));
for (let i = 0; i < 18; i++) {
const y = 1 - 2 * ((i + 0.5) / 18);
const ringRadius = Math.sqrt(Math.max(0, 1 - y * y));
const theta = goldenAngle * i;
const unit = new THREE.Vector3(
Math.cos(theta) * ringRadius,
y,
Math.sin(theta) * ringRadius
);
const position = new THREE.Vector3(
unit.x * 1.16,
unit.y * 0.54,
unit.z * 0.57
);
const normal = new THREE.Vector3(
unit.x / 1.16,
unit.y / 0.54,
unit.z / 0.57
).normalize();
const stud = new THREE.Mesh(studGeometry, studMaterial);
stud.position.copy(position);
stud.quaternion.setFromUnitVectors(up, normal);
stud.castShadow = true;
bodyVisual.add(stud);
}
// Two segmented membrane bands.
const bandMaterial = new THREE.MeshStandardMaterial({
color: 0x087b76,
roughness: 0.5,
metalness: 0.1,
flatShading: true
});
for (const x of [-0.55, 0.52]) {
const band = new THREE.Mesh(
new THREE.TorusGeometry(0.48, 0.024, 4, 28),
bandMaterial
);
band.rotation.y = Math.PI / 2;
band.position.x = x;
band.scale.y = 0.91;
bodyVisual.add(band);
}
// -------------------------------------------------------------------------
// Helical flagellum
// -------------------------------------------------------------------------
const flagRadius = 0.21;
const flagTurns = 2.75;
class HelixCurve extends THREE.Curve {
getPoint(t, target = new THREE.Vector3()) {
const radiusEnvelope = flagRadius * (1 - Math.exp(-7 * t));
const angle = flagTurns * Math.PI * 2 * t;
target.set(
-1.05 - 3.45 * t,
Math.cos(angle) * radiusEnvelope,
Math.sin(angle) * radiusEnvelope
);
return target;
}
}
const helixCurve = new HelixCurve();
const flagGeometry = new THREE.TubeGeometry(
helixCurve,
220,
0.027,
8,
false
);
// Color one side of the filament so its axial rotation is visible.
const flagColors = new Float32Array(
flagGeometry.attributes.position.count * 3
);
const baseFlagColor = new THREE.Color(0x0a6870);
const brightFlagColor = new THREE.Color(0xc8fff3);
const tempColor = new THREE.Color();
let colorIndex = 0;
const tubularSegments = 220;
const radialSegments = 8;
for (let i = 0; i <= tubularSegments; i++) {
for (let j = 0; j <= radialSegments; j++) {
const around = (j / radialSegments) * Math.PI * 2;
const stripe = Math.pow(
Math.max(0, Math.cos(around - 0.55)),
8
);
const axialBand = i % 22 < 2 ? 0.58 : 1;
tempColor
.copy(baseFlagColor)
.lerp(brightFlagColor, stripe)
.multiplyScalar(axialBand);
flagColors[colorIndex++] = tempColor.r;
flagColors[colorIndex++] = tempColor.g;
flagColors[colorIndex++] = tempColor.b;
}
}
flagGeometry.setAttribute(
"color",
new THREE.BufferAttribute(flagColors, 3)
);
const flagSpin = new THREE.Group();
bodyVisual.add(flagSpin);
const flagMaterial = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.42,
metalness: 0.18,
flatShading: true
});
const flagellum = new THREE.Mesh(flagGeometry, flagMaterial);
flagellum.castShadow = true;
flagSpin.add(flagellum);
// Asymmetric rotating motor hub.
const motor = new THREE.Mesh(
new THREE.CylinderGeometry(0.16, 0.2, 0.18, 12),
new THREE.MeshStandardMaterial({
color: 0x137d78,
emissive: 0x052f2e,
emissiveIntensity: 0.4,
roughness: 0.4,
metalness: 0.3,
flatShading: true
})
);
motor.rotation.z = Math.PI / 2;
motor.position.x = -1.08;
motor.castShadow = true;
flagSpin.add(motor);
const motorMarker = new THREE.Mesh(
new THREE.BoxGeometry(0.17, 0.055, 0.055),
new THREE.MeshBasicMaterial({ color: 0xffd166 })
);
motorMarker.position.set(-1.08, 0.16, 0);
flagSpin.add(motorMarker);
// Bright marker beads make the corkscrew's rotation obvious.
const beadGeometry = new THREE.OctahedronGeometry(0.047, 0);
const beadMaterial = new THREE.MeshStandardMaterial({
color: 0xffd166,
emissive: 0x6d3d00,
emissiveIntensity: 0.75,
roughness: 0.35,
flatShading: true
});
for (let i = 0; i < 9; i++) {
const t = 0.09 + (i / 8) * 0.87;
const bead = new THREE.Mesh(beadGeometry, beadMaterial);
bead.position.copy(helixCurve.getPoint(t));
bead.castShadow = true;
flagSpin.add(bead);
}
// A subtle local glow attached to the organism.
const bodyGlow = new THREE.PointLight(0x29e6c1, 2.2, 3.5, 2);
bodyGlow.position.set(0.1, 0.1, 0);
bodyVisual.add(bodyGlow);
// -------------------------------------------------------------------------
// Force arrows
// -------------------------------------------------------------------------
const thrustArrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(),
1,
0x55f4d0,
0.16,
0.08
);
const dragArrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(),
1,
0xff579c,
0.16,
0.08
);
const velocityArrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(),
1,
0xffd166,
0.16,
0.08
);
scene.add(thrustArrow, dragArrow, velocityArrow);
const thrustTip = new THREE.Vector3();
const dragTip = new THREE.Vector3();
const velocityTip = new THREE.Vector3();
// -------------------------------------------------------------------------
// Simplified low-Reynolds-number hydrodynamics
// -------------------------------------------------------------------------
const state = {
position: new THREE.Vector3(),
velocity: new THREE.Vector3(),
heading: 0,
yawRate: 0,
phase: 0
};
const parameters = {
rpm: 720,
resistance: 1,
mass: 1,
eta: 0.03,
parallelDrag: 1.5,
perpendicularDrag: 7,
yawDrag: 2.6,
yawInertia: 1,
torqueArm: 0.65
};
let paused = false;
let showForces = true;
const bodyQuaternion = new THREE.Quaternion();
const forward = new THREE.Vector3();
const side = new THREE.Vector3();
const acceleration = new THREE.Vector3();
const dragVector = new THREE.Vector3();
const radial = new THREE.Vector3();
function updateBodyAxes() {
bodyQuaternion.setFromAxisAngle(
new THREE.Vector3(0, 1, 0),
state.heading
);
forward.set(1, 0, 0).applyQuaternion(bodyQuaternion);
side.set(0, 0, 1).applyQuaternion(bodyQuaternion);
}
function angleDelta(target, current) {
return Math.atan2(
Math.sin(target - current),
Math.cos(target - current)
);
}
function stepPhysics(dt) {
updateBodyAxes();
const omega = parameters.rpm * Math.PI * 2 / 60;
const vParallel = state.velocity.dot(forward);
const vPerpendicular = state.velocity.dot(side);
// T = eta * (omega * r - v_parallel)
const slip = omega * flagRadius - vParallel;
const thrust = parameters.eta * slip;
const cParallel =
parameters.parallelDrag * parameters.resistance;
const cPerpendicular =
parameters.perpendicularDrag * parameters.resistance;
const dragParallel = -cParallel * vParallel;
const dragPerpendicular = -cPerpendicular * vPerpendicular;
acceleration
.copy(forward)
.multiplyScalar(thrust + dragParallel)
.addScaledVector(side, dragPerpendicular)
.divideScalar(parameters.mass);
// Soft circular dish boundary.
const radius = Math.hypot(
state.position.x,
state.position.z
);
let boundaryTorque = 0;
if (radius > 4.15) {
radial.set(
state.position.x / radius,
0,
state.position.z / radius
);
const radialVelocity = state.velocity.dot(radial);
const wallForce =
-5.5 * (radius - 4.15) -
1.8 * radialVelocity;
acceleration.addScaledVector(radial, wallForce);
const desiredHeading = Math.atan2(
radial.z,
-radial.x
);
boundaryTorque =
1.8 *
angleDelta(desiredHeading, state.heading) *
Math.min(1, (radius - 4.15) / 0.65);
}
// Explicit Euler integration.
state.velocity.addScaledVector(acceleration, dt);
state.position.addScaledVector(state.velocity, dt);
// tau = l * D_perpendicular - c_omega * yaw_rate
const torque =
parameters.torqueArm * dragPerpendicular -
parameters.yawDrag *
parameters.resistance *
state.yawRate +
boundaryTorque;
state.yawRate +=
torque / parameters.yawInertia * dt;
state.heading += state.yawRate * dt;
state.phase =
(state.phase + omega * dt) % (Math.PI * 2);
}
function resetSimulation() {
state.position.set(-2.65, 0, -0.65);
state.velocity.set(0.06, 0, 0);
state.heading = 0.12;
state.yawRate = 0;
state.phase = 0;
cameraTarget.set(
state.position.x * 0.45,
0,
state.position.z * 0.45
);
}
// -------------------------------------------------------------------------
// Direct camera controls: no examples/addons modules
// -------------------------------------------------------------------------
let cameraTheta = 0.78;
let cameraPhi = 1.03;
let cameraRadius = 8.8;
const cameraTarget = new THREE.Vector3();
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraTheta -= dx * 0.005;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi - dy * 0.005,
0.28,
1.48
);
});
renderer.domElement.addEventListener("pointerup", () => {
dragging = false;
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
5.5,
15
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
cameraTheta = 0.78;
cameraPhi = 1.03;
cameraRadius = 8.8;
});
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
const rpmInput = document.getElementById("rpm");
const resistanceInput = document.getElementById("resistance");
const rpmOutput = document.getElementById("rpm-output");
const resistanceOutput =
document.getElementById("resistance-output");
const pauseButton = document.getElementById("pause");
const resetButton = document.getElementById("reset");
const forceToggle = document.getElementById("show-forces");
const speedValue = document.getElementById("speed-value");
const slipValue = document.getElementById("slip-value");
const dragValue = document.getElementById("drag-value");
rpmInput.addEventListener("input", () => {
parameters.rpm = Number(rpmInput.value);
rpmOutput.textContent =
`${parameters.rpm > 0 ? "+" : ""}${parameters.rpm} rpm`;
});
resistanceInput.addEventListener("input", () => {
parameters.resistance = Number(resistanceInput.value);
resistanceOutput.textContent =
`${parameters.resistance.toFixed(2)}×`;
});
pauseButton.addEventListener("click", () => {
paused = !paused;
pauseButton.textContent = paused ? "RESUME" : "PAUSE";
pauseButton.setAttribute("aria-pressed", String(paused));
});
resetButton.addEventListener("click", resetSimulation);
forceToggle.addEventListener("change", () => {
showForces = forceToggle.checked;
});
window.addEventListener("keydown", (event) => {
if (
event.code === "Space" &&
event.target.tagName !== "INPUT"
) {
event.preventDefault();
pauseButton.click();
}
});
// -------------------------------------------------------------------------
// Visualization helpers
// -------------------------------------------------------------------------
const arrowDirection = new THREE.Vector3();
function drawArrow(
arrow,
origin,
vector,
gain,
tip
) {
const length = vector.length();
if (!showForces || length < 0.0001) {
arrow.visible = false;
return;
}
arrow.visible = true;
arrow.position.copy(origin);
arrowDirection.copy(vector).normalize();
arrow.setDirection(arrowDirection);
const visualLength = Math.min(
2.25,
Math.max(0.14, length * gain)
);
arrow.setLength(
visualLength,
Math.min(0.18, visualLength * 0.28),
Math.min(0.09, visualLength * 0.14)
);
tip.copy(origin).addScaledVector(
arrowDirection,
visualLength
);
}
const labelThrust = document.getElementById("label-thrust");
const labelDrag = document.getElementById("label-drag");
const labelVelocity = document.getElementById("label-velocity");
const projectedPoint = new THREE.Vector3();
function positionLabel(element, worldPosition, visible) {
if (!visible) {
element.style.display = "none";
return;
}
projectedPoint.copy(worldPosition).project(camera);
const inView =
projectedPoint.z > -1 &&
projectedPoint.z < 1 &&
Math.abs(projectedPoint.x) < 1.25 &&
Math.abs(projectedPoint.y) < 1.25;
if (!inView) {
element.style.display = "none";
return;
}
element.style.display = "block";
element.style.left =
`${(projectedPoint.x * 0.5 + 0.5) *
window.innerWidth}px`;
element.style.top =
`${(-projectedPoint.y * 0.5 + 0.5) *
window.innerHeight}px`;
}
// -------------------------------------------------------------------------
// Main loop
// -------------------------------------------------------------------------
resetSimulation();
let previousTime = performance.now();
function frame(time) {
requestAnimationFrame(frame);
const dt = Math.min(
(time - previousTime) / 1000,
0.033
);
previousTime = time;
if (!paused) {
stepPhysics(dt);
}
updateBodyAxes();
const elapsed = time * 0.001;
const bob = Math.sin(elapsed * 2.15) * 0.027;
microbe.position.set(
state.position.x,
-0.05 + bob,
state.position.z
);
microbe.rotation.y = state.heading;
// A small body roll into turns.
bodyVisual.rotation.z = THREE.MathUtils.clamp(
-state.yawRate * 0.18,
-0.16,
0.16
);
// The flagellum rotates around its local X axis.
flagSpin.rotation.x = state.phase;
motes.rotation.y = elapsed * 0.006;
motes.position.y = Math.sin(elapsed * 0.16) * 0.035;
// Camera target follows part of the motion to keep the swimmer framed.
const desiredTarget = new THREE.Vector3(
state.position.x * 0.45,
0,
state.position.z * 0.45
);
cameraTarget.lerp(
desiredTarget,
1 - Math.exp(-dt * 1.8)
);
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x +
cameraRadius * sinPhi * Math.cos(cameraTheta),
cameraTarget.y +
cameraRadius * Math.cos(cameraPhi),
cameraTarget.z +
cameraRadius * sinPhi * Math.sin(cameraTheta)
);
camera.lookAt(cameraTarget);
camera.updateMatrixWorld();
// Recompute the force vectors for display.
const vParallel = state.velocity.dot(forward);
const vPerpendicular = state.velocity.dot(side);
const omega = parameters.rpm * Math.PI * 2 / 60;
const thrustValue =
parameters.eta * (omega * flagRadius - vParallel);
const dragParallel =
-parameters.parallelDrag *
parameters.resistance *
vParallel;
const dragPerpendicular =
-parameters.perpendicularDrag *
parameters.resistance *
vPerpendicular;
const thrustVector = new THREE.Vector3()
.copy(forward)
.multiplyScalar(thrustValue);
dragVector
.copy(forward)
.multiplyScalar(dragParallel)
.addScaledVector(side, dragPerpendicular);
const bodyPosition = microbe.position;
const thrustOrigin = bodyPosition.clone()
.add(new THREE.Vector3(0, 0.5, 0));
const dragOrigin = bodyPosition.clone()
.add(new THREE.Vector3(0, 0.08, 0));
const velocityOrigin = bodyPosition.clone()
.add(new THREE.Vector3(0, -0.42, 0));
drawArrow(
thrustArrow,
thrustOrigin,
thrustVector,
1.8,
thrustTip
);
drawArrow(
dragArrow,
dragOrigin,
dragVector,
1.65,
dragTip
);
drawArrow(
velocityArrow,
velocityOrigin,
state.velocity,
1.7,
velocityTip
);
positionLabel(
labelThrust,
thrustTip,
thrustArrow.visible
);
positionLabel(
labelDrag,
dragTip,
dragArrow.visible
);
positionLabel(
labelVelocity,
velocityTip,
velocityArrow.visible
);
const speed = state.velocity.length();
const slip = omega * flagRadius - vParallel;
const dragMagnitude = dragVector.length();
speedValue.textContent = `${speed.toFixed(2)} L/s`;
slipValue.textContent = slip.toFixed(1);
dragValue.textContent = dragMagnitude.toFixed(2);
renderer.render(scene, camera);
}
requestAnimationFrame(frame);
window.addEventListener("resize", () => {
camera.aspect =
window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(
Math.min(window.devicePixelRatio, 2)
);
renderer.setSize(
window.innerWidth,
window.innerHeight
);
});
</script>
</body>
</html>
```