Prompt specification
Build or customize the Three.js 3D scene "Semipermeable bag in a beaker" 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: Semipermeable bag in a beaker
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/semipermeable-bag-in-a-beaker-x0861
Scene Description Prompt:
Semipermeable bag in a beaker. Model a flexible transparent bag containing solute beads inside a water-filled beaker; label water passage separately from solutes that cannot cross the membrane. Please build this with Three.js from cdnjs in one self-contained HTML file, using low-poly forms.
Working Three.js Starter (semipermeable-bag-in-a-beaker-x0861):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Osmosis in a Semipermeable Bag</title>
<style>
:root {
--ink: #17324d;
--muted: #60758a;
--water: #079bc4;
--solute: #d83f87;
--panel: rgba(255, 255, 255, 0.86);
--border: rgba(36, 74, 104, 0.14);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #f2f7fb;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
canvas.dragging {
cursor: grabbing;
}
#leaders {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
z-index: 4;
pointer-events: none;
overflow: visible;
}
#leaders line {
fill: none;
stroke-width: 2;
stroke-linecap: round;
}
#leaders circle {
stroke: white;
stroke-width: 2;
}
#waterLine {
stroke: var(--water);
}
#soluteLine {
stroke: var(--solute);
stroke-dasharray: 6 5;
}
#waterDot {
fill: var(--water);
}
#soluteDot {
fill: var(--solute);
}
.intro {
position: fixed;
top: 24px;
left: 26px;
z-index: 10;
width: min(380px, calc(100vw - 52px));
pointer-events: none;
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 7px;
margin-bottom: 8px;
color: #43738d;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 18px;
height: 3px;
border-radius: 4px;
background: linear-gradient(90deg, #31b9d5, #7869d8);
}
h1 {
margin: 0;
font-size: clamp(25px, 3vw, 38px);
line-height: 1.08;
letter-spacing: -0.035em;
}
.intro p {
max-width: 350px;
margin: 10px 0 0;
color: var(--muted);
font-size: 14px;
line-height: 1.5;
}
.callout {
position: fixed;
z-index: 8;
width: 238px;
padding: 12px 14px 13px;
border: 1px solid var(--border);
border-left-width: 4px;
border-radius: 12px;
background: var(--panel);
box-shadow:
0 12px 30px rgba(37, 68, 92, 0.12),
0 2px 6px rgba(37, 68, 92, 0.06);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
pointer-events: none;
opacity: 0;
transition: opacity 180ms ease;
}
.callout.visible {
opacity: 1;
}
.callout.water {
border-left-color: var(--water);
}
.callout.solute {
border-left-color: var(--solute);
}
.callout-label {
display: block;
margin-bottom: 5px;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.water .callout-label {
color: var(--water);
}
.solute .callout-label {
color: var(--solute);
}
.callout strong {
display: block;
font-size: 15px;
line-height: 1.25;
}
.callout small {
display: block;
margin-top: 5px;
color: var(--muted);
font-size: 11.5px;
line-height: 1.4;
}
.controls {
position: fixed;
left: 50%;
bottom: 22px;
z-index: 12;
display: flex;
align-items: center;
gap: 9px;
padding: 8px;
transform: translateX(-50%);
border: 1px solid var(--border);
border-radius: 14px;
background: rgba(255, 255, 255, 0.88);
box-shadow: 0 10px 30px rgba(37, 68, 92, 0.12);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
}
button {
appearance: none;
min-width: 72px;
padding: 9px 13px;
border: 0;
border-radius: 9px;
background: #edf5f9;
color: var(--ink);
font: inherit;
font-size: 12px;
font-weight: 750;
cursor: pointer;
transition:
transform 140ms ease,
background 140ms ease;
}
button:hover {
transform: translateY(-1px);
background: #e1edf3;
}
button.primary {
background: #176f93;
color: white;
}
button.primary:hover {
background: #125f7e;
}
.hint {
padding: 0 8px 0 3px;
color: var(--muted);
font-size: 11px;
white-space: nowrap;
}
.scale-note {
position: fixed;
right: 22px;
bottom: 24px;
z-index: 9;
padding: 7px 10px;
border: 1px solid var(--border);
border-radius: 999px;
background: rgba(255, 255, 255, 0.74);
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.05em;
text-transform: uppercase;
pointer-events: none;
}
#loading {
position: fixed;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
background: #f2f7fb;
color: var(--muted);
font-size: 14px;
font-weight: 700;
}
#loading.hidden {
display: none;
}
@media (max-width: 700px) {
.intro {
top: 16px;
left: 17px;
width: calc(100vw - 34px);
}
.intro p {
display: none;
}
h1 {
max-width: 290px;
font-size: 25px;
}
.callout {
width: 190px;
padding: 10px 11px;
}
.callout small {
display: none;
}
.callout strong {
font-size: 13px;
}
.controls {
bottom: 13px;
}
.hint,
.scale-note {
display: none;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<svg id="leaders" aria-hidden="true">
<line id="waterLine"></line>
<line id="soluteLine"></line>
<circle id="waterDot" r="4"></circle>
<circle id="soluteDot" r="4"></circle>
</svg>
<header class="intro">
<div class="eyebrow">Low-poly biology model</div>
<h1>Osmosis in a semipermeable bag</h1>
<p>
A flexible membrane permits water passage while retaining larger
solute particles inside the bag.
</p>
</header>
<div id="waterCallout" class="callout water">
<span class="callout-label">Water passage</span>
<strong>Water can cross the membrane</strong>
<small>Small H₂O molecules move through the semipermeable wall.</small>
</div>
<div id="soluteCallout" class="callout solute">
<span class="callout-label">Solute retention</span>
<strong>Solute cannot cross the membrane</strong>
<small>The larger magenta beads remain confined inside the bag.</small>
</div>
<div class="controls">
<button id="pauseButton" class="primary" type="button">Pause</button>
<button id="resetButton" type="button">Reset</button>
<span class="hint">Drag to orbit · Scroll to zoom · Double-click to reset view</span>
</div>
<div class="scale-note">Schematic · not to scale</div>
<div id="loading">Loading the Three.js model…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const sceneContainer = document.getElementById("scene");
const loading = document.getElementById("loading");
const pauseButton = document.getElementById("pauseButton");
const resetButton = document.getElementById("resetButton");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xf2f7fb);
scene.fog = new THREE.Fog(0xf2f7fb, 11, 23);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
sceneContainer.appendChild(renderer.domElement);
// ------------------------------------------------------------
// Lighting and ground
// ------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0xe8f8ff, 0x66758a, 2.0));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.8);
keyLight.position.set(5, 8, 6);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -6;
keyLight.shadow.camera.right = 6;
keyLight.shadow.camera.top = 6;
keyLight.shadow.camera.bottom = -6;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 22;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0x9acfff, 0.8);
fillLight.position.set(-5, 3, -4);
scene.add(fillLight);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(30, 30),
new THREE.MeshStandardMaterial({
color: 0xdce7ee,
roughness: 0.96,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -2.39;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(18, 36, 0x8ca9ba, 0xaec4d1);
grid.position.y = -2.385;
grid.material.transparent = true;
grid.material.opacity = 0.18;
scene.add(grid);
// ------------------------------------------------------------
// Beaker and surrounding water
// ------------------------------------------------------------
const beaker = new THREE.Group();
scene.add(beaker);
const glassMaterial = new THREE.MeshStandardMaterial({
color: 0xcdebf3,
transparent: true,
opacity: 0.17,
roughness: 0.12,
metalness: 0.04,
side: THREE.DoubleSide,
depthWrite: false
});
const glassWall = new THREE.Mesh(
new THREE.CylinderGeometry(3.08, 3.08, 4.35, 40, 1, true),
glassMaterial
);
glassWall.position.y = -0.1;
glassWall.renderOrder = 7;
beaker.add(glassWall);
const glassBottom = new THREE.Mesh(
new THREE.CylinderGeometry(3.08, 3.08, 0.08, 40),
glassMaterial.clone()
);
glassBottom.position.y = -2.255;
glassBottom.renderOrder = 7;
beaker.add(glassBottom);
const rim = new THREE.Mesh(
new THREE.TorusGeometry(3.08, 0.055, 6, 40),
new THREE.MeshStandardMaterial({
color: 0xbadde8,
roughness: 0.2,
metalness: 0.08,
transparent: true,
opacity: 0.68
})
);
rim.rotation.x = Math.PI / 2;
rim.position.y = 2.075;
beaker.add(rim);
const waterMaterial = new THREE.MeshPhongMaterial({
color: 0x48b9e4,
transparent: true,
opacity: 0.18,
shininess: 90,
specular: 0xc9f5ff,
depthWrite: false,
side: THREE.DoubleSide
});
const outsideWater = new THREE.Mesh(
new THREE.CylinderGeometry(2.94, 2.94, 3.8, 40),
waterMaterial
);
outsideWater.position.y = -0.34;
outsideWater.renderOrder = 1;
beaker.add(outsideWater);
const waterSurface = new THREE.Mesh(
new THREE.CircleGeometry(2.94, 40),
new THREE.MeshBasicMaterial({
color: 0x77d8f2,
transparent: true,
opacity: 0.17,
side: THREE.DoubleSide,
depthWrite: false
})
);
waterSurface.rotation.x = -Math.PI / 2;
waterSurface.position.y = 1.56;
waterSurface.renderOrder = 2;
beaker.add(waterSurface);
// ------------------------------------------------------------
// Flexible bag geometry
// ------------------------------------------------------------
const BAG_BOTTOM = -1.92;
const BAG_TOP = 1.30;
// Vertical profile of the bag: y, horizontal radius, depth radius.
const bagProfile = [
{ y: -1.92, rx: 0.12, rz: 0.10 },
{ y: -1.72, rx: 0.52, rz: 0.36 },
{ y: -1.20, rx: 0.86, rz: 0.58 },
{ y: -0.35, rx: 1.10, rz: 0.73 },
{ y: 0.50, rx: 1.04, rz: 0.69 },
{ y: 1.03, rx: 0.70, rz: 0.46 },
{ y: 1.30, rx: 0.30, rz: 0.21 }
];
function profileAt(y) {
if (y <= bagProfile[0].y) return bagProfile[0];
for (let i = 0; i < bagProfile.length - 1; i++) {
const a = bagProfile[i];
const b = bagProfile[i + 1];
if (y <= b.y) {
const t = (y - a.y) / (b.y - a.y);
return {
rx: THREE.MathUtils.lerp(a.rx, b.rx, t),
rz: THREE.MathUtils.lerp(a.rz, b.rz, t)
};
}
}
return bagProfile[bagProfile.length - 1];
}
const BAG_RINGS = 20;
const BAG_SEGMENTS = 28;
function createBagGeometry() {
const positions = [];
const indices = [];
const metadata = [];
const ringProfiles = [];
for (let i = 0; i < BAG_RINGS; i++) {
const t = i / (BAG_RINGS - 1);
const y = THREE.MathUtils.lerp(BAG_BOTTOM, BAG_TOP, t);
const profile = profileAt(y);
ringProfiles.push(profile);
for (let j = 0; j < BAG_SEGMENTS; j++) {
const angle = (j / BAG_SEGMENTS) * Math.PI * 2;
const cos = Math.cos(angle);
const sin = Math.sin(angle);
positions.push(profile.rx * cos, y, profile.rz * sin);
metadata.push({ y, t, cos, sin, ring: i });
}
}
for (let i = 0; i < BAG_RINGS - 1; i++) {
for (let j = 0; j < BAG_SEGMENTS; j++) {
const nextJ = (j + 1) % BAG_SEGMENTS;
const a = i * BAG_SEGMENTS + j;
const b = i * BAG_SEGMENTS + nextJ;
const c = (i + 1) * BAG_SEGMENTS + j;
const d = (i + 1) * BAG_SEGMENTS + nextJ;
indices.push(a, c, b, b, c, d);
}
}
const bottomCenter = positions.length / 3;
positions.push(0, BAG_BOTTOM, 0);
const topCenter = positions.length / 3;
positions.push(0, BAG_TOP, 0);
for (let j = 0; j < BAG_SEGMENTS; j++) {
const nextJ = (j + 1) % BAG_SEGMENTS;
indices.push(
bottomCenter,
nextJ,
j
);
const topRing = (BAG_RINGS - 1) * BAG_SEGMENTS;
indices.push(
topCenter,
topRing + j,
topRing + nextJ
);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
geometry.userData.metadata = metadata;
geometry.userData.ringProfiles = ringProfiles;
geometry.userData.bottomCenter = bottomCenter;
geometry.userData.topCenter = topCenter;
return geometry;
}
const bagGeometry = createBagGeometry();
const bagShell = new THREE.Mesh(
bagGeometry,
new THREE.MeshPhongMaterial({
color: 0x82e2e8,
transparent: true,
opacity: 0.19,
shininess: 100,
specular: 0xffffff,
side: THREE.DoubleSide,
depthWrite: false
})
);
bagShell.renderOrder = 4;
scene.add(bagShell);
const innerWater = new THREE.Mesh(
bagGeometry,
new THREE.MeshBasicMaterial({
color: 0x44bde7,
transparent: true,
opacity: 0.075,
side: THREE.DoubleSide,
depthWrite: false
})
);
innerWater.scale.set(0.965, 0.987, 0.965);
innerWater.position.y = 0.012;
innerWater.renderOrder = 3;
scene.add(innerWater);
const membraneWire = new THREE.Mesh(
bagGeometry,
new THREE.MeshBasicMaterial({
color: 0x148da4,
wireframe: true,
transparent: true,
opacity: 0.12,
depthWrite: false
})
);
membraneWire.renderOrder = 5;
scene.add(membraneWire);
const bagTie = new THREE.Mesh(
new THREE.TorusGeometry(0.265, 0.043, 6, 18),
new THREE.MeshStandardMaterial({
color: 0x178b9f,
roughness: 0.52
})
);
bagTie.rotation.x = Math.PI / 2;
bagTie.position.y = 1.305;
bagTie.castShadow = true;
scene.add(bagTie);
function bagOffset(y, time) {
const t = (y - BAG_BOTTOM) / (BAG_TOP - BAG_BOTTOM);
const x =
0.095 *
Math.sin(time * 0.78 + t * 2.25) *
Math.sin(Math.PI * t * 0.78);
const z =
0.065 *
Math.sin(time * 0.62 + 1.15 + t * 2.0) *
Math.sin(Math.PI * t * 0.8);
return { x, z };
}
function updateBagGeometry(time) {
const position = bagGeometry.attributes.position.array;
const metadata = bagGeometry.userData.metadata;
const profiles = bagGeometry.userData.ringProfiles;
for (let i = 0; i < metadata.length; i++) {
const m = metadata[i];
const profile = profiles[m.ring];
const offset = bagOffset(m.y, time);
const ripple =
0.034 *
Math.sin(time * 1.12 + m.ring * 0.34 + m.t * 3.1) *
Math.sin(Math.PI * m.t);
position[i * 3] =
profile.rx * m.cos + offset.x + ripple * m.cos;
position[i * 3 + 1] = m.y;
position[i * 3 + 2] =
profile.rz * m.sin + offset.z + ripple * m.sin;
}
const bottomIndex = bagGeometry.userData.bottomCenter;
const topIndex = bagGeometry.userData.topCenter;
const bottomOffset = bagOffset(BAG_BOTTOM, time);
const topOffset = bagOffset(BAG_TOP, time);
position[bottomIndex * 3] = bottomOffset.x;
position[bottomIndex * 3 + 1] = BAG_BOTTOM;
position[bottomIndex * 3 + 2] = bottomOffset.z;
position[topIndex * 3] = topOffset.x;
position[topIndex * 3 + 1] = BAG_TOP;
position[topIndex * 3 + 2] = topOffset.z;
bagGeometry.attributes.position.needsUpdate = true;
bagGeometry.computeVertexNormals();
}
function boundaryRadius(y, theta) {
const profile = profileAt(y);
const cos = Math.cos(theta);
const sin = Math.sin(theta);
return 1 /
Math.sqrt(
(cos * cos) / (profile.rx * profile.rx) +
(sin * sin) / (profile.rz * profile.rz)
);
}
function surfacePoint(theta, y, push = 0, time = simTime) {
const profile = profileAt(y);
const cos = Math.cos(theta);
const sin = Math.sin(theta);
const radius = boundaryRadius(y, theta);
const offset = bagOffset(y, time);
const t = (y - BAG_BOTTOM) / (BAG_TOP - BAG_BOTTOM);
const ripple =
0.034 *
Math.sin(time * 1.12 + t * 3.1) *
Math.sin(Math.PI * t);
return new THREE.Vector3(
(radius + push) * cos + offset.x + ripple * cos,
y,
(radius + push) * sin + offset.z + ripple * sin
);
}
// ------------------------------------------------------------
// Stylized low-poly water molecules
// ------------------------------------------------------------
const oxygenGeometry = new THREE.IcosahedronGeometry(0.076, 0);
const hydrogenGeometry = new THREE.IcosahedronGeometry(0.045, 0);
const oxygenMaterial = new THREE.MeshStandardMaterial({
color: 0x168fbd,
roughness: 0.42,
metalness: 0.02,
flatShading: true
});
const hydrogenMaterial = new THREE.MeshStandardMaterial({
color: 0xf0fbff,
roughness: 0.5,
metalness: 0,
flatShading: true
});
function createWaterMolecule(scale = 1) {
const group = new THREE.Group();
const oxygen = new THREE.Mesh(oxygenGeometry, oxygenMaterial);
group.add(oxygen);
const hydrogenA = new THREE.Mesh(hydrogenGeometry, hydrogenMaterial);
hydrogenA.position.set(-0.058, 0.042, 0);
group.add(hydrogenA);
const hydrogenB = new THREE.Mesh(hydrogenGeometry, hydrogenMaterial);
hydrogenB.position.set(0.058, 0.042, 0);
group.add(hydrogenB);
group.scale.setScalar(scale);
return group;
}
let randomSeed = 49271;
function random() {
randomSeed =
(randomSeed * 1664525 + 1013904223) >>> 0;
return randomSeed / 4294967296;
}
const staticWaterMolecules = [];
// Molecules distributed in the water outside the bag.
for (let i = 0; i < 30; i++) {
const molecule = createWaterMolecule(0.82);
let x, y, z;
for (let attempt = 0; attempt < 80; attempt++) {
y = THREE.MathUtils.lerp(-2.04, 1.46, random());
const angle = random() * Math.PI * 2;
const radius = Math.sqrt(random()) * 2.73;
x = Math.cos(angle) * radius;
z = Math.sin(angle) * radius;
const bagRadius = boundaryRadius(y, angle);
const distance = Math.hypot(x, z);
if (distance > bagRadius + 0.18) break;
}
molecule.position.set(x, y, z);
molecule.rotation.set(
random() * Math.PI,
random() * Math.PI,
random() * Math.PI
);
molecule.userData.spin = 0.15 + random() * 0.3;
molecule.userData.rotation = molecule.rotation.clone();
staticWaterMolecules.push(molecule);
scene.add(molecule);
}
// A smaller amount of visibly contained water inside the bag.
for (let i = 0; i < 9; i++) {
const molecule = createWaterMolecule(0.72);
const y = THREE.MathUtils.lerp(-1.5, 0.93, random());
const angle = random() * Math.PI * 2;
const limit = Math.max(0.1, boundaryRadius(y, angle) - 0.25);
const radius = Math.sqrt(random()) * limit;
molecule.position.set(
Math.cos(angle) * radius,
y,
Math.sin(angle) * radius
);
molecule.rotation.set(
random() * Math.PI,
random() * Math.PI,
random() * Math.PI
);
molecule.userData.spin = 0.15 + random() * 0.25;
molecule.userData.rotation = molecule.rotation.clone();
staticWaterMolecules.push(molecule);
scene.add(molecule);
}
// Animated molecules cross radially through the membrane.
const crossingMolecules = [];
for (let i = 0; i < 18; i++) {
const molecule = createWaterMolecule(0.88);
crossingMolecules.push({
mesh: molecule,
theta: random() * Math.PI * 2,
y: THREE.MathUtils.lerp(-1.42, 0.95, random()),
phase: random(),
speed: 0.065 + random() * 0.065,
direction: i % 5 === 0 ? -1 : 1
});
scene.add(molecule);
}
function smoothstep(edge0, edge1, x) {
const t = THREE.MathUtils.clamp(
(x - edge0) / (edge1 - edge0),
0,
1
);
return t * t * (3 - 2 * t);
}
function updateWaterMolecules(time) {
for (const molecule of staticWaterMolecules) {
const spin = molecule.userData.spin;
const rotation = molecule.userData.rotation;
molecule.rotation.x = rotation.x + time * spin * 0.6;
molecule.rotation.y = rotation.y + time * spin;
molecule.rotation.z = rotation.z + time * spin * 0.4;
}
for (const data of crossingMolecules) {
const progress = (time * data.speed + data.phase) % 1;
const boundary = boundaryRadius(data.y, data.theta);
const outerRadius = boundary + 0.64;
const innerRadius = Math.max(0.08, boundary - 0.42);
const radius =
data.direction > 0
? THREE.MathUtils.lerp(
outerRadius,
innerRadius,
progress
)
: THREE.MathUtils.lerp(
innerRadius,
outerRadius,
progress
);
const cos = Math.cos(data.theta);
const sin = Math.sin(data.theta);
const offset = bagOffset(data.y, time);
data.mesh.position.set(
radius * cos + offset.x,
data.y + 0.035 * Math.sin(progress * Math.PI * 2),
radius * sin + offset.z
);
const fade =
smoothstep(0, 0.09, progress) *
smoothstep(0, 0.09, 1 - progress);
data.mesh.scale.setScalar(
0.88 * Math.max(0.04, fade)
);
data.mesh.rotation.x += 0.012;
data.mesh.rotation.y += 0.019;
data.mesh.rotation.z += 0.009;
}
}
// ------------------------------------------------------------
// Solute beads: kept inside the membrane
// ------------------------------------------------------------
const soluteGeometry = new THREE.IcosahedronGeometry(0.13, 0);
const soluteMaterials = [
new THREE.MeshStandardMaterial({
color: 0xd83f87,
roughness: 0.38,
metalness: 0.05,
emissive: 0x3c0828,
emissiveIntensity: 0.18,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: 0xef5b9c,
roughness: 0.42,
metalness: 0.02,
emissive: 0x3c0828,
emissiveIntensity: 0.14,
flatShading: true
})
];
const soluteBeads = [];
for (let i = 0; i < 12; i++) {
const mesh = new THREE.Mesh(
soluteGeometry,
soluteMaterials[i % soluteMaterials.length]
);
const scale = 0.75 + random() * 0.48;
mesh.scale.setScalar(scale);
mesh.castShadow = true;
soluteBeads.push({
mesh,
scale,
baseRadius: random() * 0.54,
baseAngle: random() * Math.PI * 2,
baseY: THREE.MathUtils.lerp(-1.38, 0.88, random()),
phase: random() * Math.PI * 2
});
scene.add(mesh);
}
// One bead repeatedly approaches the wall and is repelled.
const attemptBead = new THREE.Mesh(
soluteGeometry,
soluteMaterials[0]
);
attemptBead.scale.setScalar(1.05);
attemptBead.castShadow = true;
scene.add(attemptBead);
const attemptTheta = -0.48;
const attemptY = 0.12;
// A pulsing no-entry marker on the membrane.
const barrier = new THREE.Group();
const barrierRing = new THREE.Mesh(
new THREE.RingGeometry(0.11, 0.145, 16),
new THREE.MeshBasicMaterial({
color: 0xd83f87,
transparent: true,
opacity: 0.78,
side: THREE.DoubleSide,
depthTest: false
})
);
barrierRing.renderOrder = 12;
barrier.add(barrierRing);
const barrierCrossGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-0.065, -0.065, 0),
new THREE.Vector3(0.065, 0.065, 0),
new THREE.Vector3(-0.065, 0.065, 0),
new THREE.Vector3(0.065, -0.065, 0)
]);
const barrierCross = new THREE.LineSegments(
barrierCrossGeometry,
new THREE.LineBasicMaterial({
color: 0xd83f87,
transparent: true,
opacity: 0.9,
depthTest: false
})
);
barrierCross.renderOrder = 13;
barrier.add(barrierCross);
scene.add(barrier);
function updateSolute(time) {
for (const bead of soluteBeads) {
const angle =
bead.baseAngle +
0.12 * Math.sin(time * 0.55 + bead.phase);
const radius =
bead.baseRadius +
0.075 * Math.sin(time * 0.9 + bead.phase * 1.7);
const y =
bead.baseY +
0.16 * Math.sin(time * 0.48 + bead.phase);
let x = Math.cos(angle) * radius;
let z = Math.sin(angle) * radius;
const currentAngle = Math.atan2(z, x);
const wall = boundaryRadius(y, currentAngle);
const safeRadius = wall - (0.15 * bead.scale + 0.035);
const distance = Math.hypot(x, z);
if (distance > safeRadius) {
const correction = safeRadius / distance;
x *= correction;
z *= correction;
}
const offset = bagOffset(y, time);
bead.mesh.position.set(
x + offset.x,
y,
z + offset.z
);
bead.mesh.rotation.x = time * 0.42 + bead.phase;
bead.mesh.rotation.y = time * 0.58 + bead.phase;
bead.mesh.rotation.z = time * 0.31;
}
const wall = boundaryRadius(attemptY, attemptTheta);
const gap =
0.18 +
0.18 *
(0.5 + 0.5 * Math.sin(time * 1.55));
const radius = wall - gap;
const offset = bagOffset(attemptY, time);
attemptBead.position.set(
Math.cos(attemptTheta) * radius + offset.x,
attemptY,
Math.sin(attemptTheta) * radius + offset.z
);
attemptBead.rotation.x = time * 0.55;
attemptBead.rotation.y = time * 0.72;
attemptBead.rotation.z = time * 0.38;
barrier.position.copy(
surfacePoint(attemptTheta, attemptY, 0.02, time)
);
const profile = profileAt(attemptY);
const normal = new THREE.Vector3(
Math.cos(attemptTheta) / profile.rx,
0,
Math.sin(attemptTheta) / profile.rz
).normalize();
barrier.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 0, 1),
normal
);
const pulse = 1 + 0.12 * Math.sin(time * 3.0);
barrier.scale.setScalar(pulse);
barrierRing.material.opacity = 0.65 + 0.18 * Math.sin(time * 3.0);
}
// ------------------------------------------------------------
// Direct camera controls: orbit, pinch zoom, wheel zoom
// ------------------------------------------------------------
const cameraState = {
radius: 9.15,
theta: 0.62,
phi: 1.18,
target: new THREE.Vector3(0, -0.12, 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);
camera.updateMatrixWorld();
}
function resetCamera() {
cameraState.radius = 9.15;
cameraState.theta = 0.62;
cameraState.phi = 1.18;
updateCamera();
}
const pointers = new Map();
let previousPinchDistance = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.classList.add("dragging");
if (pointers.size < 2) {
previousPinchDistance = 0;
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
const pointer = pointers.get(event.pointerId);
if (!pointer) return;
const dx = event.clientX - pointer.x;
const dy = event.clientY - pointer.y;
pointer.x = event.clientX;
pointer.y = event.clientY;
if (pointers.size === 1) {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi + dy * 0.005,
0.42,
1.68
);
} else if (pointers.size === 2) {
const values = [...pointers.values()];
const distance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
if (previousPinchDistance > 0) {
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius *
(previousPinchDistance / distance),
6.3,
13.5
);
}
previousPinchDistance = distance;
}
});
function releasePointer(event) {
pointers.delete(event.pointerId);
if (pointers.size < 2) {
previousPinchDistance = 0;
}
if (pointers.size === 0) {
renderer.domElement.classList.remove("dragging");
}
}
renderer.domElement.addEventListener("pointerup", releasePointer);
renderer.domElement.addEventListener("pointercancel", releasePointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.006,
6.3,
13.5
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
// ------------------------------------------------------------
// Screen-space labels and leader lines
// ------------------------------------------------------------
const svg = document.getElementById("leaders");
const waterCallout = document.getElementById("waterCallout");
const soluteCallout = document.getElementById("soluteCallout");
const waterLine = document.getElementById("waterLine");
const soluteLine = document.getElementById("soluteLine");
const waterDot = document.getElementById("waterDot");
const soluteDot = document.getElementById("soluteDot");
function projectToScreen(worldPosition) {
const projected = worldPosition.clone().project(camera);
return {
x: (projected.x * 0.5 + 0.5) * window.innerWidth,
y: (-projected.y * 0.5 + 0.5) * window.innerHeight
};
}
function positionCallout(
element,
line,
dot,
anchor,
side
) {
const screen = projectToScreen(anchor);
const width = element.offsetWidth;
const height = element.offsetHeight;
const mobile = window.innerWidth < 700;
const gap = mobile ? 26 : 70;
let x;
let y;
if (side === "right") {
x = screen.x + gap;
y = screen.y - height * 0.55;
} else {
x = screen.x - width - gap;
y = screen.y + height * 0.25;
}
x = THREE.MathUtils.clamp(
x,
12,
Math.max(12, window.innerWidth - width - 12)
);
y = THREE.MathUtils.clamp(
y,
mobile ? 88 : 104,
Math.max(100, window.innerHeight - height - 92)
);
element.style.left = `${x}px`;
element.style.top = `${y}px`;
const endX = side === "right" ? x : x + width;
const endY = y + height * 0.5;
line.setAttribute("x1", screen.x);
line.setAttribute("y1", screen.y);
line.setAttribute("x2", endX);
line.setAttribute("y2", endY);
dot.setAttribute("cx", screen.x);
dot.setAttribute("cy", screen.y);
element.classList.add("visible");
}
function updateCallouts() {
const waterAnchor = surfacePoint(0.75, 0.45, 0.13, simTime);
positionCallout(
waterCallout,
waterLine,
waterDot,
waterAnchor,
"right"
);
positionCallout(
soluteCallout,
soluteLine,
soluteDot,
attemptBead.position,
"left"
);
}
// ------------------------------------------------------------
// Resize and animation
// ------------------------------------------------------------
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setPixelRatio(
Math.min(window.devicePixelRatio, 2)
);
renderer.setSize(width, height);
svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
}
window.addEventListener("resize", resize);
resize();
updateCamera();
let simTime = 0;
let playing = true;
let previousTime = performance.now();
pauseButton.addEventListener("click", () => {
playing = !playing;
pauseButton.textContent = playing ? "Pause" : "Play";
pauseButton.setAttribute(
"aria-pressed",
String(!playing)
);
});
resetButton.addEventListener("click", () => {
simTime = 0;
resetCamera();
});
function animate(now) {
requestAnimationFrame(animate);
const delta = Math.min(
(now - previousTime) / 1000,
0.05
);
previousTime = now;
if (playing) {
simTime += delta;
}
updateBagGeometry(simTime);
updateWaterMolecules(simTime);
updateSolute(simTime);
updateCamera();
renderer.render(scene, camera);
updateCallouts();
if (!loading.classList.contains("hidden")) {
loading.classList.add("hidden");
}
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```