Prompt specification
Build or customize the Three.js 3D scene "Stomatal aperture comparison" 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: Stomatal aperture comparison
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/stomatal-aperture-comparison-x0790
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows leaf stomata. Animate the guard-cell pair between open and narrow schematic states; symbolic gas arrows pass through the opening while a caption explains that regulation involves multiple environmental signals. Low-poly.
Working Three.js Starter (stomatal-aperture-comparison-x0790):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>The Stomatal Gate</title>
<style>
:root {
--ink: #173d2d;
--muted: #627267;
--paper: #e9ecdf;
--lime: #78b94f;
--amber: #d4933b;
--teal: #3c9f9a;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--paper);
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
position: relative;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
#scene canvas:focus-visible {
outline: 2px solid rgba(60, 159, 154, 0.9);
outline-offset: -4px;
}
.topbar {
position: fixed;
top: 28px;
left: 32px;
right: 32px;
z-index: 5;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 24px;
pointer-events: none;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
}
.brand-mark {
position: relative;
width: 39px;
height: 39px;
flex: 0 0 auto;
border-radius: 90% 10% 90% 10%;
background: linear-gradient(145deg, #96ca65, #4f8d40);
transform: rotate(-18deg);
box-shadow: 0 8px 20px rgba(42, 83, 47, 0.14);
}
.brand-mark::after {
content: "";
position: absolute;
top: 6px;
left: 18px;
width: 2px;
height: 27px;
border-radius: 2px;
background: rgba(244, 250, 230, 0.8);
transform: rotate(20deg);
}
.eyebrow {
margin: 0 0 5px;
color: #728071;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(28px, 3vw, 42px);
font-weight: 500;
letter-spacing: -0.035em;
line-height: 1;
}
.subtitle {
margin-top: 8px;
color: var(--muted);
font-size: 12px;
letter-spacing: 0.02em;
}
.status {
min-width: 174px;
padding: 11px 13px;
border: 1px solid rgba(31, 73, 49, 0.13);
border-radius: 13px;
background: rgba(249, 250, 242, 0.72);
box-shadow: 0 10px 35px rgba(43, 66, 48, 0.08);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
}
.status-row {
display: flex;
align-items: center;
gap: 8px;
}
.status-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--lime);
box-shadow: 0 0 0 4px rgba(120, 185, 79, 0.13);
transition: background 180ms ease;
}
#statusText {
font-size: 10px;
font-weight: 850;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.state-meter {
height: 3px;
margin-top: 9px;
overflow: hidden;
border-radius: 3px;
background: rgba(29, 69, 46, 0.1);
}
#stateFill {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #72a84b, #9acb61);
}
.legend {
position: fixed;
top: 104px;
right: 32px;
z-index: 5;
display: flex;
gap: 15px;
padding: 9px 12px;
border: 1px solid rgba(31, 73, 49, 0.1);
border-radius: 11px;
background: rgba(249, 250, 242, 0.64);
color: #526357;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.04em;
backdrop-filter: blur(10px);
pointer-events: none;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.legend i {
display: inline-block;
width: 16px;
height: 3px;
border-radius: 4px;
}
.legend .amber {
background: var(--amber);
}
.legend .teal {
background: var(--teal);
}
.caption {
position: fixed;
left: 32px;
bottom: 28px;
z-index: 6;
width: min(540px, calc(100vw - 64px));
padding: 18px 20px 16px;
border: 1px solid rgba(31, 73, 49, 0.13);
border-radius: 19px;
background: rgba(249, 250, 242, 0.86);
box-shadow: 0 18px 55px rgba(46, 72, 52, 0.12);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
pointer-events: none;
}
.caption-head {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 8px;
}
.caption-number {
display: grid;
width: 25px;
height: 25px;
place-items: center;
border-radius: 8px;
background: #dce8cf;
color: #41633b;
font-size: 10px;
font-weight: 900;
letter-spacing: 0.08em;
}
.caption-copy {
margin: 0;
color: #45594b;
font-size: 13px;
line-height: 1.55;
}
.caption-copy strong {
color: var(--ink);
font-weight: 800;
}
.caption-copy em {
color: #47743f;
font-style: normal;
font-weight: 750;
}
.signals {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-top: 13px;
}
.signal {
padding: 5px 8px;
border: 1px solid rgba(50, 96, 57, 0.13);
border-radius: 999px;
background: rgba(228, 237, 217, 0.64);
color: #536b54;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.help {
position: fixed;
right: 32px;
bottom: 30px;
z-index: 5;
color: rgba(40, 70, 50, 0.58);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.06em;
pointer-events: none;
}
.callout {
position: fixed;
top: 0;
left: 0;
z-index: 4;
display: flex;
align-items: center;
gap: 9px;
padding: 8px 11px;
border: 1px solid rgba(29, 73, 46, 0.13);
border-radius: 10px;
background: rgba(248, 250, 241, 0.76);
box-shadow: 0 9px 24px rgba(42, 71, 47, 0.08);
backdrop-filter: blur(10px);
transform: translate(13px, -50%);
pointer-events: none;
}
.callout::before {
content: "";
position: absolute;
top: 50%;
right: 100%;
width: 25px;
height: 1px;
background: rgba(35, 79, 50, 0.34);
}
.callout-dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--lime);
}
.callout b {
display: block;
color: #31523b;
font-size: 9px;
letter-spacing: 0.1em;
}
.callout small {
display: block;
margin-top: 2px;
color: #778278;
font-size: 9px;
}
@media (max-width: 760px) {
.topbar {
top: 18px;
left: 18px;
right: 18px;
}
.brand-mark {
width: 33px;
height: 33px;
}
.brand-mark::after {
left: 15px;
height: 22px;
}
.subtitle {
display: none;
}
.status {
min-width: 136px;
padding: 9px 10px;
}
#statusText {
font-size: 8px;
}
.legend {
top: 84px;
right: 18px;
gap: 10px;
font-size: 8px;
}
.caption {
left: 12px;
bottom: 12px;
width: calc(100vw - 24px);
padding: 14px 15px 13px;
border-radius: 15px;
}
.caption-copy {
font-size: 11px;
line-height: 1.45;
}
.signals {
gap: 4px;
margin-top: 9px;
}
.signal {
padding: 4px 6px;
font-size: 7px;
}
.help,
.callout {
display: none;
}
}
</style>
</head>
<body>
<main
id="scene"
aria-label="Interactive low-poly diagram of a leaf stoma opening and closing"
></main>
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<p class="eyebrow">Plant biophysics · interactive model</p>
<h1>The stomatal gate</h1>
<div class="subtitle">A schematic view of two cells coordinating a living opening</div>
</div>
</div>
<div class="status" role="status" aria-live="polite">
<div class="status-row">
<span class="status-dot" id="statusDot" aria-hidden="true"></span>
<span id="statusText">Narrow pore</span>
</div>
<div class="state-meter" aria-hidden="true">
<i id="stateFill"></i>
</div>
</div>
</header>
<div class="legend" aria-label="Gas movement legend">
<span><i class="amber"></i> CO₂ inward</span>
<span><i class="teal"></i> O₂ outward</span>
</div>
<section class="caption" aria-labelledby="captionTitle">
<div class="caption-head">
<span class="caption-number">01</span>
<p class="eyebrow" id="captionTitle">Why the gate moves</p>
</div>
<p class="caption-copy">
<strong>Guard cells</strong> change turgor to widen or narrow the pore.
Their response integrates
<em>light, internal CO₂, water availability, humidity, and circadian timing</em>
— making stomatal opening a coordinated state rather than a simple on/off switch.
</p>
<div class="signals" aria-label="Environmental signals">
<span class="signal">Light</span>
<span class="signal">CO₂</span>
<span class="signal">Water</span>
<span class="signal">Humidity</span>
<span class="signal">Circadian clock</span>
</div>
</section>
<div class="help">Drag to orbit · Scroll to zoom · Double-click to reset</div>
<div class="callout" id="callout" aria-hidden="true">
<span class="callout-dot"></span>
<span>
<b>GUARD CELL PAIR</b>
<small>shape changes with turgor</small>
</span>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Renderer, scene, and lighting
// ------------------------------------------------------------
const host = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
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.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
host.appendChild(renderer.domElement);
renderer.domElement.tabIndex = 0;
renderer.domElement.setAttribute(
"aria-label",
"Three-dimensional leaf stoma. Drag to orbit and scroll to zoom."
);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe9ecdf);
scene.fog = new THREE.Fog(0xe9ecdf, 23, 42);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
80
);
const hemisphere = new THREE.HemisphereLight(0xffffff, 0x6e8063, 2.25);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff8e7, 3.1);
keyLight.position.set(-4.5, 7, 11);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -9;
keyLight.shadow.camera.right = 9;
keyLight.shadow.camera.top = 9;
keyLight.shadow.camera.bottom = -9;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.0008;
scene.add(keyLight);
scene.add(keyLight.target);
const rimLight = new THREE.DirectionalLight(0xb8dfcf, 1.2);
rimLight.position.set(7, -2, 7);
scene.add(rimLight);
const backdrop = new THREE.Mesh(
new THREE.PlaneGeometry(60, 60),
new THREE.MeshStandardMaterial({
color: 0xe5e9dc,
roughness: 1,
metalness: 0
})
);
backdrop.position.z = -1.2;
backdrop.receiveShadow = true;
scene.add(backdrop);
// ------------------------------------------------------------
// Low-poly leaf surface
// ------------------------------------------------------------
const leafRoot = new THREE.Group();
leafRoot.rotation.set(-0.025, -0.08, -0.04);
scene.add(leafRoot);
const leafOutline = [
[0.00, 5.65],
[1.15, 4.80],
[2.60, 3.55],
[3.62, 2.05],
[4.00, 0.25],
[3.74, -1.45],
[3.03, -3.06],
[1.84, -4.45],
[0.66, -5.32],
[0.00, -5.70],
[-0.76, -5.25],
[-2.05, -4.18],
[-3.25, -2.90],
[-3.91, -1.25],
[-4.05, 0.45],
[-3.55, 2.25],
[-2.54, 3.75],
[-1.00, 4.95]
];
const leafPalette = [
0x79a957,
0x70a050,
0x83b25c,
0x769f52,
0x8ab660,
0x6e984c
];
const frontPositions = [];
const frontColors = [];
for (let i = 0; i < leafOutline.length; i++) {
const a = leafOutline[i];
const b = leafOutline[(i + 1) % leafOutline.length];
frontPositions.push(
0, 0, 0.04,
b[0], b[1], 0.04,
a[0], a[1], 0.04
);
const color = new THREE.Color(leafPalette[i % leafPalette.length]);
color.offsetHSL(0, 0, (i % 3 - 1) * 0.012);
for (let v = 0; v < 3; v++) {
frontColors.push(color.r, color.g, color.b);
}
}
const leafGeometry = new THREE.BufferGeometry();
leafGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(frontPositions, 3)
);
leafGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(frontColors, 3)
);
leafGeometry.computeVertexNormals();
const leafFace = new THREE.Mesh(
leafGeometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.94,
metalness: 0,
flatShading: true,
side: THREE.DoubleSide
})
);
leafFace.castShadow = true;
leafFace.receiveShadow = true;
leafRoot.add(leafFace);
// Leaf edge and thickness.
const sidePositions = [];
for (let i = 0; i < leafOutline.length; i++) {
const a = leafOutline[i];
const b = leafOutline[(i + 1) % leafOutline.length];
sidePositions.push(
a[0], a[1], 0.04,
a[0], a[1], -0.34,
b[0], b[1], 0.04,
b[0], b[1], 0.04,
a[0], a[1], -0.34,
b[0], b[1], -0.34
);
}
const leafSideGeometry = new THREE.BufferGeometry();
leafSideGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(sidePositions, 3)
);
leafSideGeometry.computeVertexNormals();
const leafSide = new THREE.Mesh(
leafSideGeometry,
new THREE.MeshStandardMaterial({
color: 0x527b43,
roughness: 1,
flatShading: true,
side: THREE.DoubleSide
})
);
leafSide.castShadow = true;
leafSide.receiveShadow = true;
leafRoot.add(leafSide);
// Short petiole.
const stem = new THREE.Mesh(
new THREE.CylinderGeometry(0.105, 0.14, 1.15, 6),
new THREE.MeshStandardMaterial({
color: 0x69844c,
roughness: 0.95,
flatShading: true
})
);
stem.position.set(0, -6.05, -0.06);
stem.rotation.z = -0.06;
stem.castShadow = true;
leafRoot.add(stem);
// ------------------------------------------------------------
// Subtle polygonal epidermal cell outlines
// ------------------------------------------------------------
function pointInPolygon(x, y, polygon) {
let inside = false;
for (
let i = 0, j = polygon.length - 1;
i < polygon.length;
j = i++
) {
const xi = polygon[i][0];
const yi = polygon[i][1];
const xj = polygon[j][0];
const yj = polygon[j][1];
const intersects =
yi > y !== yj > y &&
x < ((xj - xi) * (y - yi)) / (yj - yi) + xi;
if (intersects) inside = !inside;
}
return inside;
}
const cellLineMaterial = new THREE.LineBasicMaterial({
color: 0x315e3e,
transparent: true,
opacity: 0.2,
depthWrite: false
});
for (let row = 0; row < 9; row++) {
const cy = -4.65 + row * 1.16;
const rowOffset = row % 2 === 0 ? 0 : 0.72;
for (let col = -3; col <= 3; col++) {
const cx = col * 1.53 + rowOffset;
const radius = 0.86;
const points = [];
let valid = true;
for (let k = 0; k < 6; k++) {
const angle =
Math.PI / 6 +
(k * Math.PI) / 3 +
0.035 * Math.sin(row * 7.1 + col * 4.3 + k);
const r = radius * (1 + 0.055 * Math.sin(row + col * 2 + k * 3));
const x = cx + Math.cos(angle) * r;
const y = cy + Math.sin(angle) * r;
if (!pointInPolygon(x, y, leafOutline)) {
valid = false;
break;
}
points.push(new THREE.Vector3(x, y, 0.075));
}
if (!valid || points.length !== 6) continue;
const line = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints(points),
cellLineMaterial
);
leafRoot.add(line);
}
}
// ------------------------------------------------------------
// Faceted vein network
// ------------------------------------------------------------
const veinMaterial = new THREE.MeshStandardMaterial({
color: 0xa7c878,
roughness: 0.9,
flatShading: true
});
function cylinderBetween(a, b, radius = 0.028) {
const start = new THREE.Vector3(...a);
const end = new THREE.Vector3(...b);
const direction = end.clone().sub(start);
const length = direction.length();
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius, length, 5),
veinMaterial
);
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.castShadow = true;
leafRoot.add(mesh);
return mesh;
}
const midribPoints = [
[0.00, -5.28, 0.11],
[0.03, -3.60, 0.11],
[-0.02, -1.70, 0.11],
[0.02, 0.15, 0.11],
[0.00, 2.05, 0.11],
[-0.03, 3.80, 0.11],
[0.00, 5.25, 0.11]
];
for (let i = 0; i < midribPoints.length - 1; i++) {
cylinderBetween(midribPoints[i], midribPoints[i + 1], 0.037);
}
const branchLevels = [-4.15, -2.85, -1.55, -0.20, 1.25, 2.70, 4.02];
for (const y of branchLevels) {
for (const sign of [-1, 1]) {
const reach = 3.35 * (1 - Math.abs(y) / 7.1);
const endY = y + 0.88;
const endX = sign * reach;
const start = [0, y, 0.11];
const middle = [sign * reach * 0.48, y + 0.43, 0.11];
const end = [endX, endY, 0.11];
cylinderBetween(start, middle, 0.024);
cylinderBetween(middle, end, 0.019);
}
}
// ------------------------------------------------------------
// Guard cells: custom low-poly, morphing geometry
// ------------------------------------------------------------
const stomaRoot = new THREE.Group();
stomaRoot.position.set(0.95, 0.35, 0.055);
leafRoot.add(stomaRoot);
const GUARD_LENGTH = 3.25;
const RINGS = 12;
const SEGMENTS = 7;
function profileAt(u, openness) {
const sine = Math.max(0, Math.sin(Math.PI * u));
const taper = Math.pow(sine, 0.52);
const rx = (0.39 + openness * 0.10) * taper + 0.012;
const rz = (0.17 + openness * 0.08) * taper + 0.012;
const innerOffset =
(0.025 + openness * 0.395) * Math.pow(sine, 0.67);
return {
rx,
rz,
innerOffset,
y: (u - 0.5) * GUARD_LENGTH
};
}
function guardPoint(side, ring, segment, openness) {
const u = ring / (RINGS - 1);
const p = profileAt(u, openness);
const angle = (segment / SEGMENTS) * Math.PI * 2;
const centerX = side * (p.innerOffset + p.rx);
return new THREE.Vector3(
centerX + p.rx * Math.cos(angle),
p.y,
0.31 + p.rz * Math.sin(angle)
);
}
function capPoint(side, cap, openness) {
const u = cap === 0 ? 0 : 1;
const p = profileAt(u, openness);
return new THREE.Vector3(
side * (p.innerOffset + p.rx),
p.y + (cap === 0 ? -0.025 : 0.025),
0.31
);
}
function makeGuardCell(side, palette) {
const triangleSpecs = [];
for (let ring = 0; ring < RINGS - 1; ring++) {
for (let segment = 0; segment < SEGMENTS; segment++) {
const nextSegment = (segment + 1) % SEGMENTS;
triangleSpecs.push([
{ ring, segment },
{ ring: ring + 1, segment },
{ ring, segment: nextSegment }
]);
triangleSpecs.push([
{ ring: ring + 1, segment },
{ ring: ring + 1, segment: nextSegment },
{ ring, segment: nextSegment }
]);
}
}
for (let segment = 0; segment < SEGMENTS; segment++) {
const nextSegment = (segment + 1) % SEGMENTS;
triangleSpecs.push([
{ cap: 0 },
{ ring: 0, segment },
{ ring: 0, segment: nextSegment }
]);
triangleSpecs.push([
{ cap: 1 },
{ ring: RINGS - 1, segment: nextSegment },
{ ring: RINGS - 1, segment }
]);
}
const positionArray = new Float32Array(triangleSpecs.length * 9);
const colorArray = new Float32Array(triangleSpecs.length * 9);
const color = new THREE.Color();
triangleSpecs.forEach((triangle, triangleIndex) => {
const shadeIndex =
(triangleIndex * 5 + (side > 0 ? 2 : 0)) % palette.length;
color.set(palette[shadeIndex]);
color.offsetHSL(0, 0, ((triangleIndex % 4) - 1.5) * 0.008);
for (let vertex = 0; vertex < 3; vertex++) {
const colorIndex = triangleIndex * 9 + vertex * 3;
colorArray[colorIndex] = color.r;
colorArray[colorIndex + 1] = color.g;
colorArray[colorIndex + 2] = color.b;
}
});
const geometry = new THREE.BufferGeometry();
const positionAttribute = new THREE.BufferAttribute(positionArray, 3);
positionAttribute.setUsage(THREE.DynamicDrawUsage);
geometry.setAttribute("position", positionAttribute);
geometry.setAttribute(
"color",
new THREE.BufferAttribute(colorArray, 3)
);
const material = new THREE.MeshStandardMaterial({
vertexColors: true,
color: 0xffffff,
roughness: 0.76,
metalness: 0,
flatShading: true,
side: THREE.DoubleSide
});
const mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.frustumCulled = false;
stomaRoot.add(mesh);
function update(openness) {
triangleSpecs.forEach((triangle, triangleIndex) => {
triangle.forEach((spec, vertex) => {
const point =
spec.cap !== undefined
? capPoint(side, spec.cap, openness)
: guardPoint(side, spec.ring, spec.segment, openness);
const index = triangleIndex * 9 + vertex * 3;
positionArray[index] = point.x;
positionArray[index + 1] = point.y;
positionArray[index + 2] = point.z;
});
});
positionAttribute.needsUpdate = true;
geometry.computeVertexNormals();
}
update(0);
return { mesh, update };
}
const leftGuard = makeGuardCell(
-1,
[0x79b94f, 0x70aa49, 0x8ac55b, 0x659d43]
);
const rightGuard = makeGuardCell(
1,
[0x82bf53, 0x75b14b, 0x91c85c, 0x6ca449]
);
// Low-poly nuclei embedded in the guard cells.
const nuclei = [];
for (const side of [-1, 1]) {
const nucleus = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.135, 0),
new THREE.MeshStandardMaterial({
color: side < 0 ? 0x244d36 : 0x2d5c3b,
roughness: 0.9,
flatShading: true
})
);
nucleus.castShadow = true;
stomaRoot.add(nucleus);
nuclei.push({ mesh: nucleus, side });
}
function updateNuclei(openness) {
const u = 0.57;
for (const { mesh, side } of nuclei) {
const p = profileAt(u, openness);
mesh.position.set(
side * (p.innerOffset + p.rx * 0.56),
p.y + 0.18,
0.515
);
}
}
// ------------------------------------------------------------
// Dark pore aperture, matching the changing inner cell edges
// ------------------------------------------------------------
const PORE_SAMPLES = 28;
const porePositions = new Float32Array(PORE_SAMPLES * 2 * 3);
const poreIndices = [];
for (let i = 0; i < PORE_SAMPLES - 1; i++) {
const a = i * 2;
const b = a + 1;
const c = a + 2;
const d = a + 3;
poreIndices.push(a, b, c, b, d, c);
}
const poreGeometry = new THREE.BufferGeometry();
const porePositionAttribute = new THREE.BufferAttribute(
porePositions,
3
);
porePositionAttribute.setUsage(THREE.DynamicDrawUsage);
poreGeometry.setAttribute("position", porePositionAttribute);
poreGeometry.setIndex(poreIndices);
const pore = new THREE.Mesh(
poreGeometry,
new THREE.MeshBasicMaterial({
color: 0x173e2c,
side: THREE.DoubleSide
})
);
pore.position.z = 0.055;
pore.frustumCulled = false;
stomaRoot.add(pore);
function updatePore(openness) {
for (let i = 0; i < PORE_SAMPLES; i++) {
const t = i / (PORE_SAMPLES - 1);
const y = (t - 0.5) * GUARD_LENGTH * 0.95;
const u = y / GUARD_LENGTH + 0.5;
const p = profileAt(u, openness);
const halfWidth = p.innerOffset * 0.96 + 0.002;
const index = i * 6;
porePositions[index] = -halfWidth;
porePositions[index + 1] = y;
porePositions[index + 2] = 0;
porePositions[index + 3] = halfWidth;
porePositions[index + 4] = y;
porePositions[index + 5] = 0;
}
porePositionAttribute.needsUpdate = true;
}
// ------------------------------------------------------------
// Symbolic gas arrows
// ------------------------------------------------------------
function makeGasArrow(color, direction) {
const group = new THREE.Group();
const material = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0,
depthWrite: false,
side: THREE.DoubleSide
});
const shaft = new THREE.Mesh(
new THREE.CylinderGeometry(0.045, 0.045, 0.57, 6),
material
);
shaft.rotation.x = Math.PI / 2;
shaft.position.z = -0.08;
group.add(shaft);
const head = new THREE.Mesh(
new THREE.ConeGeometry(0.135, 0.29, 6),
material
);
head.rotation.x = Math.PI / 2;
head.position.z = 0.35;
group.add(head);
group.scale.z = direction;
group.renderOrder = 3;
stomaRoot.add(group);
return { group, material };
}
const co2Arrow = makeGasArrow(0xd4933b, -1);
const o2Arrow = makeGasArrow(0x3c9f9a, 1);
co2Arrow.group.position.set(-0.21, 0.30, 1.65);
o2Arrow.group.position.set(0.21, -0.30, -1.65);
function makeLabelSprite(text, color) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 180;
const context = canvas.getContext("2d");
const radius = 34;
const x = 8;
const y = 8;
const width = 496;
const height = 164;
context.beginPath();
context.moveTo(x + radius, y);
context.lineTo(x + width - radius, y);
context.quadraticCurveTo(
x + width, y, x + width, y + radius
);
context.lineTo(x + width, y + height - radius);
context.quadraticCurveTo(
x + width, y + height,
x + width - radius, y + height
);
context.lineTo(x + radius, y + height);
context.quadraticCurveTo(
x, y + height, x, y + height - radius
);
context.lineTo(x, y + radius);
context.quadraticCurveTo(x, y, x + radius, y);
context.closePath();
context.fillStyle = "rgba(20, 52, 36, 0.88)";
context.fill();
context.lineWidth = 5;
context.strokeStyle = color;
context.stroke();
context.fillStyle = "#f5f8ed";
context.font = "700 54px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 256, 91);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
opacity: 0,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(1.25, 0.44, 1);
sprite.renderOrder = 8;
stomaRoot.add(sprite);
return sprite;
}
const co2Label = makeLabelSprite("CO₂ IN", "#d4933b");
co2Label.position.set(-0.74, 0.80, 1.45);
const o2Label = makeLabelSprite("O₂ OUT", "#3c9f9a");
o2Label.position.set(0.74, -0.62, 1.45);
// ------------------------------------------------------------
// Direct camera controls: no external controls module
// ------------------------------------------------------------
const cameraState = {
theta: 0.16,
phi: 0.58,
radius: 18,
target: new THREE.Vector3(0.35, 0.15, 0)
};
let userMovedCamera = false;
let dragging = false;
let dragPointerId = null;
let previousX = 0;
let previousY = 0;
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
const cosPhi = Math.cos(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPhi * Math.cos(cameraState.theta),
cameraState.target.y +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.z + cameraState.radius * cosPhi
);
camera.lookAt(cameraState.target);
camera.updateMatrixWorld();
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
dragPointerId = event.pointerId;
previousX = event.clientX;
previousY = event.clientY;
userMovedCamera = true;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging || event.pointerId !== dragPointerId) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi + dy * 0.005,
0.28,
1.35
);
updateCamera();
});
function endDrag(event) {
if (event.pointerId !== dragPointerId) return;
dragging = false;
dragPointerId = null;
renderer.domElement.style.cursor = "grab";
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
userMovedCamera = true;
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
11,
27
);
updateCamera();
},
{ passive: false }
);
function resetCamera() {
const portrait = window.innerWidth / window.innerHeight < 0.9;
cameraState.theta = 0.16;
cameraState.phi = 0.58;
cameraState.radius = portrait ? 21.5 : 18;
cameraState.target.set(
portrait ? 0 : 0.35,
portrait ? -0.35 : 0.15,
0
);
updateCamera();
}
renderer.domElement.addEventListener("dblclick", resetCamera);
renderer.domElement.addEventListener("keydown", (event) => {
let handled = true;
userMovedCamera = true;
switch (event.key) {
case "ArrowLeft":
cameraState.theta -= 0.08;
break;
case "ArrowRight":
cameraState.theta += 0.08;
break;
case "ArrowUp":
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - 0.06,
0.28,
1.35
);
break;
case "ArrowDown":
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi + 0.06,
0.28,
1.35
);
break;
case "+":
case "=":
cameraState.radius = Math.max(11, cameraState.radius - 0.7);
break;
case "-":
case "_":
cameraState.radius = Math.min(27, cameraState.radius + 0.7);
break;
case "0":
resetCamera();
break;
default:
handled = false;
}
if (handled) {
event.preventDefault();
updateCamera();
}
});
renderer.domElement.style.cursor = "grab";
// ------------------------------------------------------------
// Responsive layout
// ------------------------------------------------------------
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
const portrait = aspect < 0.9;
renderer.setSize(width, height, false);
camera.aspect = aspect;
camera.updateProjectionMatrix();
leafRoot.position.x = portrait ? 0 : 0.65;
if (!userMovedCamera) {
cameraState.radius = portrait ? 21.5 : aspect < 1.25 ? 19.5 : 18;
cameraState.target.set(
portrait ? 0 : 0.35,
portrait ? -0.35 : 0.15,
0
);
}
updateCamera();
}
window.addEventListener("resize", resize);
resize();
// ------------------------------------------------------------
// Animation
// ------------------------------------------------------------
const statusText = document.querySelector("#statusText");
const statusDot = document.querySelector("#statusDot");
const stateFill = document.querySelector("#stateFill");
const callout = document.querySelector("#callout");
const clamp01 = (value) => THREE.MathUtils.clamp(value, 0, 1);
function smooth01(value) {
const x = clamp01(value);
return x * x * (3 - 2 * x);
}
function opennessAt(time) {
const phase = time % 10;
if (phase < 1) return 0;
if (phase < 4) return smooth01((phase - 1) / 3);
if (phase < 6) return 1;
if (phase < 9) return 1 - smooth01((phase - 6) / 3);
return 0;
}
const clock = new THREE.Clock();
const projectedAnchor = new THREE.Vector3();
const worldAnchor = new THREE.Vector3();
let lastStatus = "";
renderer.setAnimationLoop(() => {
const time = clock.getElapsedTime();
const openness = opennessAt(time);
leftGuard.update(openness);
rightGuard.update(openness);
updateNuclei(openness);
updatePore(openness);
const gasStrength = smooth01((openness - 0.06) / 0.65);
const co2Travel = (time * 0.31 + 0.12) % 1;
const o2Travel = (time * 0.31 + 0.62) % 1;
co2Arrow.group.position.z = 1.7 - co2Travel * 3.4;
o2Arrow.group.position.z = -1.7 + o2Travel * 3.4;
co2Arrow.material.opacity = gasStrength * 0.9;
o2Arrow.material.opacity = gasStrength * 0.9;
co2Label.material.opacity = gasStrength * 0.95;
o2Label.material.opacity = gasStrength * 0.95;
const isOpening =
opennessAt(time + 0.025) > opennessAt(time - 0.025);
let status;
if (openness > 0.965) {
status = "Open pore";
} else if (openness < 0.035) {
status = "Narrow pore";
} else {
status = isOpening ? "Opening" : "Closing";
}
if (status !== lastStatus) {
statusText.textContent = status;
statusDot.style.background = isOpening ? "#78b94f" : "#d4933b";
lastStatus = status;
}
stateFill.style.width = `${(openness * 100).toFixed(1)}%`;
// Project the guard-cell annotation into screen space.
leafRoot.updateWorldMatrix(true, true);
worldAnchor.set(1.48, 0.78, 0.62);
stomaRoot.localToWorld(worldAnchor);
projectedAnchor.copy(worldAnchor).project(camera);
const screenX = (projectedAnchor.x * 0.5 + 0.5) * window.innerWidth;
const screenY = (-projectedAnchor.y * 0.5 + 0.5) * window.innerHeight;
callout.style.left = `${screenX}px`;
callout.style.top = `${screenY}px`;
callout.style.opacity =
projectedAnchor.z > -1 && projectedAnchor.z < 1 ? "1" : "0";
renderer.render(scene, camera);
});
</script>
</body>
</html>
```