Prompt specification
Build or customize the Three.js 3D scene "Energy storage comparison exhibit" 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: Energy storage comparison exhibit
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/energy-storage-comparison-exhibit-x1607
Scene Description Prompt:
Compare a voxel capacitor and spring as energy-storage analogies, clearly distinguishing their physical mechanisms. One HTML file using Three.js from cdnjs.
Working Three.js Starter (energy-storage-comparison-exhibit-x1607):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Capacitor vs. Spring — Energy Storage</title>
<style>
:root {
color-scheme: dark;
--bg: #070b14;
--panel: rgba(12, 18, 32, 0.82);
--panel-border: rgba(154, 184, 220, 0.17);
--text: #edf5ff;
--muted: #9eb0c8;
--cyan: #63e3ff;
--red: #ff6473;
--blue: #5c91ff;
--amber: #ffb65c;
--green: #8bf1b8;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
outline: none;
touch-action: none;
}
#scene:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: -3px;
}
#hud {
position: fixed;
inset: 0;
pointer-events: none;
}
header {
position: absolute;
top: 22px;
left: 24px;
width: min(570px, calc(100vw - 410px));
}
.eyebrow {
margin-bottom: 7px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(25px, 3vw, 39px);
line-height: 1.05;
letter-spacing: -0.035em;
}
header p {
max-width: 560px;
margin: 11px 0 0;
color: var(--muted);
font-size: 14px;
line-height: 1.55;
}
header strong {
color: var(--text);
font-weight: 650;
}
#controls {
position: absolute;
top: 20px;
right: 20px;
width: 330px;
padding: 16px;
border: 1px solid var(--panel-border);
border-radius: 17px;
background: var(--panel);
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(16px);
pointer-events: auto;
}
.control-heading {
display: flex;
justify-content: space-between;
align-items: baseline;
gap: 12px;
margin-bottom: 9px;
}
.control-heading label {
color: var(--text);
font-size: 13px;
font-weight: 700;
}
#energy-readout {
color: var(--cyan);
font-variant-numeric: tabular-nums;
font-size: 13px;
font-weight: 800;
}
input[type="range"] {
width: 100%;
height: 6px;
margin: 5px 0 7px;
border-radius: 999px;
accent-color: var(--cyan);
cursor: pointer;
}
.range-labels {
display: flex;
justify-content: space-between;
margin-bottom: 13px;
color: #72849d;
font-size: 10px;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.control-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-top: 10px;
}
.control-row label {
color: var(--muted);
font-size: 12px;
}
button {
border: 1px solid rgba(99, 227, 255, 0.22);
border-radius: 9px;
padding: 7px 10px;
background: rgba(99, 227, 255, 0.08);
color: var(--cyan);
font: inherit;
font-size: 11px;
font-weight: 750;
cursor: pointer;
}
button:hover {
background: rgba(99, 227, 255, 0.15);
}
input[type="checkbox"] {
accent-color: var(--cyan);
}
#analogy-note {
margin: 13px 0 0;
padding-top: 12px;
border-top: 1px solid rgba(154, 184, 220, 0.12);
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
#analogy-note b {
color: var(--text);
}
#cards {
position: absolute;
right: 18px;
bottom: 18px;
left: 18px;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 18px;
pointer-events: none;
}
.card {
min-width: 0;
padding: 16px 17px;
border: 1px solid var(--panel-border);
border-radius: 17px;
background: var(--panel);
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.25);
backdrop-filter: blur(16px);
pointer-events: auto;
}
.card-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 8px;
}
.tag {
display: inline-flex;
align-items: center;
gap: 7px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.tag::before {
width: 8px;
height: 8px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 12px currentColor;
content: "";
}
.capacitor .tag {
color: var(--cyan);
}
.spring .tag {
color: var(--amber);
}
.formula {
color: #d8e8fb;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 13px;
}
.card h2 {
margin: 0 0 7px;
font-size: 20px;
letter-spacing: -0.025em;
}
.card > p {
margin: 0 0 11px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.values {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin: 10px 0 11px;
}
.value {
min-width: 0;
padding: 8px 9px;
border: 1px solid rgba(154, 184, 220, 0.1);
border-radius: 9px;
background: rgba(255, 255, 255, 0.025);
}
.value span {
display: block;
margin-bottom: 3px;
color: #72849d;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.value strong {
display: block;
overflow: hidden;
color: var(--text);
font-size: 12px;
font-variant-numeric: tabular-nums;
text-overflow: ellipsis;
white-space: nowrap;
}
.mechanism-list {
display: grid;
gap: 6px;
margin: 0;
padding: 0;
list-style: none;
}
.mechanism-list li {
position: relative;
padding-left: 15px;
color: var(--muted);
font-size: 11px;
line-height: 1.42;
}
.mechanism-list li::before {
position: absolute;
top: 0.48em;
left: 0;
width: 5px;
height: 5px;
border-radius: 50%;
background: var(--cyan);
content: "";
}
.spring .mechanism-list li::before {
background: var(--amber);
}
.mechanism-list b {
color: #dce9f9;
font-weight: 700;
}
.model-label {
position: absolute;
padding: 6px 9px;
border: 1px solid rgba(154, 184, 220, 0.15);
border-radius: 999px;
background: rgba(7, 11, 20, 0.72);
color: #dbeaff;
font-size: 9px;
font-weight: 850;
letter-spacing: 0.13em;
text-transform: uppercase;
white-space: nowrap;
transform: translate(-50%, -50%);
backdrop-filter: blur(9px);
transition: opacity 120ms linear;
}
#label-capacitor {
border-color: rgba(99, 227, 255, 0.25);
color: var(--cyan);
}
#label-spring {
border-color: rgba(255, 182, 92, 0.25);
color: var(--amber);
}
#gesture-hint {
position: absolute;
top: 112px;
left: 50%;
padding: 6px 10px;
border-radius: 999px;
background: rgba(7, 11, 20, 0.55);
color: #8396af;
font-size: 10px;
transform: translateX(-50%);
}
#fallback {
position: fixed;
inset: 0;
display: none;
place-items: center;
padding: 30px;
background: var(--bg);
color: var(--text);
text-align: center;
z-index: 100;
}
@media (max-width: 900px) {
header {
width: calc(100vw - 390px);
}
.card {
padding: 13px;
}
.card h2 {
font-size: 17px;
}
.mechanism-list li {
font-size: 10px;
}
}
@media (max-width: 760px) {
header {
top: 14px;
left: 14px;
width: calc(100vw - 28px);
}
header p {
display: none;
}
h1 {
font-size: 25px;
}
#controls {
top: 83px;
right: 12px;
width: min(285px, calc(100vw - 24px));
padding: 12px;
}
#analogy-note {
display: none;
}
#gesture-hint {
top: 72px;
}
#cards {
right: 10px;
bottom: 10px;
left: 10px;
display: flex;
gap: 10px;
overflow-x: auto;
scroll-snap-type: x mandatory;
pointer-events: auto;
scrollbar-width: none;
}
#cards::-webkit-scrollbar {
display: none;
}
.card {
min-width: min(86vw, 360px);
max-height: 43vh;
overflow-y: auto;
scroll-snap-align: center;
}
.model-label {
display: none;
}
}
@media (max-height: 650px) and (min-width: 761px) {
.mechanism-list {
display: none;
}
.card > p {
margin-bottom: 6px;
}
#cards {
bottom: 10px;
}
}
</style>
</head>
<body>
<canvas
id="scene"
tabindex="0"
aria-label="Interactive 3D comparison of a voxel capacitor and a compression spring. Drag to orbit and use the mouse wheel to zoom."
></canvas>
<div id="hud">
<header>
<div class="eyebrow">Energy storage · same promise, different physics</div>
<h1>Voxel capacitor vs. compression spring</h1>
<p>
Both can <strong>store potential energy and return it later</strong>.
The capacitor stores it in an <strong>electric field supported by separated charge</strong>;
the spring stores it in <strong>elastic strain of the material</strong>.
</p>
</header>
<section id="controls" aria-label="Simulation controls">
<div class="control-heading">
<label for="energy">Equal stored energy</label>
<output id="energy-readout" for="energy">90 mJ</output>
</div>
<input
id="energy"
type="range"
min="0"
max="100"
value="45"
aria-label="Stored energy in both devices"
>
<div class="range-labels">
<span>Empty</span>
<span>Maximum</span>
</div>
<div class="control-row">
<label for="show-mechanisms">Show fields and force arrows</label>
<input id="show-mechanisms" type="checkbox" checked>
</div>
<div class="control-row">
<span style="color:var(--muted);font-size:12px">
C = 100 nF · k = 2 N/m
</span>
<button id="reset-view" type="button">Reset view</button>
</div>
<p id="analogy-note">
<b>Where the analogy ends:</b>
the capacitor’s electrostatic force depends strongly on voltage,
while the spring’s restoring force is linear in compression.
“Voxel” describes the capacitor’s geometry—not a different storage law.
</p>
</section>
<div id="label-capacitor" class="model-label">Field storage</div>
<div id="label-spring" class="model-label">Strain storage</div>
<div id="gesture-hint">Drag to orbit · wheel to zoom · arrow keys to inspect</div>
<section id="cards" aria-label="Comparison of physical mechanisms">
<article class="card capacitor">
<div class="card-top">
<span class="tag">Electrostatic storage</span>
<span class="formula">U = ½CV² = Q²/(2C)</span>
</div>
<h2>Voxel capacitor</h2>
<p>
Voxelized electrodes are separated by a dielectric. The separated
charge establishes a field; that field contains the stored energy.
</p>
<div class="values">
<div class="value">
<span>Energy</span>
<strong id="cap-energy">90 mJ</strong>
</div>
<div class="value">
<span>Voltage</span>
<strong id="cap-voltage">1.34 kV</strong>
</div>
<div class="value">
<span>Charge</span>
<strong id="cap-charge">134 μC</strong>
</div>
</div>
<ul class="mechanism-list">
<li><b>Charging:</b> an external circuit moves electrons and builds voltage; electrons do not cross the dielectric.</li>
<li><b>Storage:</b> the electric field and dielectric polarization occupy the gap, with weaker fringing fields outside.</li>
<li><b>Return:</b> a connected load receives charge as the field collapses. No mechanical strain is required.</li>
</ul>
</article>
<article class="card spring">
<div class="card-top">
<span class="tag">Elastic storage</span>
<span class="formula">U = ½kx²</span>
</div>
<h2>Compression spring</h2>
<p>
External work changes the material’s shape. Interatomic bonds resist
that deformation, leaving the spring loaded with elastic strain energy.
</p>
<div class="values">
<div class="value">
<span>Energy</span>
<strong id="spring-energy">90 mJ</strong>
</div>
<div class="value">
<span>Compression</span>
<strong id="spring-compression">30.0 cm</strong>
</div>
<div class="value">
<span>Restoring force</span>
<strong id="spring-force">0.60 N</strong>
</div>
</div>
<ul class="mechanism-list">
<li><b>Loading:</b> mechanical work bends or compresses the spring, moving its material away from equilibrium.</li>
<li><b>Storage:</b> stress and strain reside in the spring material; separated free charge is not required.</li>
<li><b>Return:</b> the material relaxes and exerts an upward force as the compression is released.</li>
</ul>
</article>
</section>
</div>
<div id="fallback">
<div>
<h2>WebGL is unavailable</h2>
<p>This interactive comparison needs a browser with WebGL enabled.</p>
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const canvas = document.querySelector("#scene");
const fallback = document.querySelector("#fallback");
let renderer;
try {
renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
} catch (error) {
fallback.style.display = "grid";
throw error;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x070b14);
scene.fog = new THREE.FogExp2(0x070b14, 0.035);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
const view = {
theta: 0,
phi: 1.17,
radius: 9.6,
targetTheta: 0,
targetPhi: 1.17,
targetRadius: 9.6
};
const cameraTarget = new THREE.Vector3(0, 0.05, 0);
scene.add(new THREE.HemisphereLight(0xb9ddff, 0x111722, 1.7));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(4, 8, 6);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -8;
keyLight.shadow.camera.right = 8;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -8;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x38cfff, 18, 8, 2);
cyanLight.position.set(-3.2, 2.1, 2.2);
scene.add(cyanLight);
const amberLight = new THREE.PointLight(0xffa94d, 15, 8, 2);
amberLight.position.set(3.4, 1.8, 1.5);
scene.add(amberLight);
const grid = new THREE.GridHelper(24, 48, 0x1d3951, 0x102238);
grid.position.y = -1.51;
grid.material.transparent = true;
grid.material.opacity = 0.4;
scene.add(grid);
const capacitorGroup = new THREE.Group();
capacitorGroup.position.x = -2.55;
scene.add(capacitorGroup);
const springGroup = new THREE.Group();
springGroup.position.x = 2.55;
scene.add(springGroup);
function createPlatform(x, accentColor) {
const base = new THREE.Mesh(
new THREE.CylinderGeometry(1.53, 1.62, 0.12, 64),
new THREE.MeshStandardMaterial({
color: 0x0d1726,
metalness: 0.5,
roughness: 0.55
})
);
base.position.set(x, -1.44, 0);
base.receiveShadow = true;
scene.add(base);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(1.42, 0.012, 8, 96),
new THREE.MeshBasicMaterial({
color: accentColor,
transparent: true,
opacity: 0.6
})
);
ring.rotation.x = Math.PI / 2;
ring.position.set(x, -1.37, 0);
scene.add(ring);
}
createPlatform(-2.55, 0x4ddfff);
createPlatform(2.55, 0xffad57);
function makeCircleSprite(text, background, foreground = "#ffffff") {
const spriteCanvas = document.createElement("canvas");
spriteCanvas.width = 160;
spriteCanvas.height = 160;
const context = spriteCanvas.getContext("2d");
context.clearRect(0, 0, 160, 160);
context.beginPath();
context.arc(80, 80, 66, 0, Math.PI * 2);
context.fillStyle = background;
context.fill();
context.lineWidth = 5;
context.strokeStyle = "rgba(255,255,255,0.28)";
context.stroke();
context.fillStyle = foreground;
context.font = "800 102px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 80, 84);
const texture = new THREE.CanvasTexture(spriteCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(0.42, 0.42, 1);
return sprite;
}
function makeTextSprite(text, color) {
const spriteCanvas = document.createElement("canvas");
spriteCanvas.width = 128;
spriteCanvas.height = 128;
const context = spriteCanvas.getContext("2d");
context.clearRect(0, 0, 128, 128);
context.fillStyle = color;
context.font = "italic 800 76px Georgia, serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 64, 66);
const texture = new THREE.CanvasTexture(spriteCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(0.42, 0.42, 1);
return sprite;
}
// ---------------------------------------------------------------------
// Voxel capacitor
// ---------------------------------------------------------------------
const plateGeometry = new THREE.BoxGeometry(0.25, 0.25, 0.25);
const plateColumns = 7;
const plateRows = 4;
const plateCount = plateColumns * plateRows;
const dummy = new THREE.Object3D();
const positivePlateMaterial = new THREE.MeshStandardMaterial({
color: 0xb94855,
emissive: 0x5d111d,
emissiveIntensity: 0.55,
metalness: 0.58,
roughness: 0.3
});
const negativePlateMaterial = new THREE.MeshStandardMaterial({
color: 0x315eb8,
emissive: 0x102a72,
emissiveIntensity: 0.55,
metalness: 0.58,
roughness: 0.3
});
function createVoxelPlate(y, material) {
const mesh = new THREE.InstancedMesh(
plateGeometry,
material,
plateCount
);
mesh.castShadow = true;
mesh.receiveShadow = true;
let index = 0;
for (let row = 0; row < plateRows; row++) {
for (let column = 0; column < plateColumns; column++) {
dummy.position.set(
(column - (plateColumns - 1) / 2) * 0.255,
y,
(row - (plateRows - 1) / 2) * 0.255
);
dummy.rotation.set(0, 0, 0);
dummy.scale.setScalar(1);
dummy.updateMatrix();
mesh.setMatrixAt(index++, dummy.matrix);
}
}
mesh.instanceMatrix.needsUpdate = true;
capacitorGroup.add(mesh);
return mesh;
}
createVoxelPlate(0.68, positivePlateMaterial);
createVoxelPlate(-0.68, negativePlateMaterial);
// Neutral dielectric cells occupy the gap.
const dielectric = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.13, 0.13, 0.13),
new THREE.MeshStandardMaterial({
color: 0x80dfff,
emissive: 0x173f4c,
emissiveIntensity: 0.3,
transparent: true,
opacity: 0.22,
depthWrite: false,
roughness: 0.22
}),
18
);
let dielectricIndex = 0;
for (let row = 0; row < 3; row++) {
for (let column = 0; column < 6; column++) {
dummy.position.set(
(column - 2.5) * 0.29,
(row - 1) * 0.18,
((column + row) % 2 ? 1 : -1) * 0.19
);
dummy.rotation.set(0.35, 0.5, 0.2);
dummy.scale.setScalar(1);
dummy.updateMatrix();
dielectric.setMatrixAt(dielectricIndex++, dummy.matrix);
}
}
dielectric.instanceMatrix.needsUpdate = true;
capacitorGroup.add(dielectric);
// Charge markers are placed on the inner electrode surfaces.
const chargeGeometry = new THREE.SphereGeometry(0.042, 10, 8);
const positiveChargeMaterial = new THREE.MeshStandardMaterial({
color: 0xff7480,
emissive: 0xff304a,
emissiveIntensity: 1.4,
transparent: true,
opacity: 0.8,
roughness: 0.25
});
const negativeChargeMaterial = new THREE.MeshStandardMaterial({
color: 0x76a4ff,
emissive: 0x326dff,
emissiveIntensity: 1.4,
transparent: true,
opacity: 0.8,
roughness: 0.25
});
const positiveCharges = new THREE.InstancedMesh(
chargeGeometry,
positiveChargeMaterial,
plateCount
);
const negativeCharges = new THREE.InstancedMesh(
chargeGeometry,
negativeChargeMaterial,
plateCount
);
positiveCharges.frustumCulled = false;
negativeCharges.frustumCulled = false;
const chargePositions = [];
let chargeIndex = 0;
for (let row = 0; row < plateRows; row++) {
for (let column = 0; column < plateColumns; column++) {
const x = (column - (plateColumns - 1) / 2) * 0.255;
const z = (row - (plateRows - 1) / 2) * 0.255;
chargePositions.push(
{ x, y: 0.54, z },
{ x, y: -0.54, z }
);
dummy.position.set(x, 0.54, z);
dummy.scale.setScalar(1);
dummy.updateMatrix();
positiveCharges.setMatrixAt(chargeIndex, dummy.matrix);
dummy.position.set(x, -0.54, z);
dummy.updateMatrix();
negativeCharges.setMatrixAt(chargeIndex, dummy.matrix);
chargeIndex++;
}
}
capacitorGroup.add(positiveCharges, negativeCharges);
const positiveSign = makeCircleSprite("+", "#ad3547");
positiveSign.position.set(0, 1.13, 0);
capacitorGroup.add(positiveSign);
const negativeSign = makeCircleSprite("−", "#315eb8");
negativeSign.position.set(0, -1.08, 0);
capacitorGroup.add(negativeSign);
// Electric field lines and arrows run from the positive plate to the
// negative plate. The dielectric changes the field magnitude, not its
// fundamental source.
const fieldGroup = new THREE.Group();
capacitorGroup.add(fieldGroup);
const fieldLineMaterials = [];
const fieldArrowMaterials = [];
for (let index = 0; index < 7; index++) {
const x = (index - 3) * 0.225;
const z = index % 2 === 0 ? -0.16 : 0.16;
const edgeFactor = Math.abs(index - 3) / 3;
const spread = 0.12 * edgeFactor;
const curve = new THREE.CatmullRomCurve3([
new THREE.Vector3(x * 0.9 - spread * 0.35, 0.53, z),
new THREE.Vector3(x * 0.96 - spread, 0.24, z),
new THREE.Vector3(x, 0, z),
new THREE.Vector3(x * 0.96 + spread, -0.24, z),
new THREE.Vector3(x * 0.9 + spread * 0.35, -0.53, z)
]);
const lineMaterial = new THREE.LineBasicMaterial({
color: 0x6eeaff,
transparent: true,
opacity: 0.5,
depthWrite: false
});
const line = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(curve.getPoints(64)),
lineMaterial
);
fieldGroup.add(line);
fieldLineMaterials.push(lineMaterial);
const arrowMaterial = new THREE.MeshBasicMaterial({
color: 0xb5f6ff,
transparent: true,
opacity: 0.9
});
const arrow = new THREE.Mesh(
new THREE.ConeGeometry(0.052, 0.16, 10),
arrowMaterial
);
arrow.position.set(x, 0.02, z);
arrow.rotation.z = Math.PI;
fieldGroup.add(arrow);
fieldArrowMaterials.push(arrowMaterial);
}
const electricFieldLabel = makeTextSprite("E", "#8beeff");
electricFieldLabel.position.set(1.08, 0, 0);
electricFieldLabel.scale.set(0.36, 0.36, 1);
fieldGroup.add(electricFieldLabel);
// ---------------------------------------------------------------------
// Compression spring
// ---------------------------------------------------------------------
const springBottomY = -1.0;
const springTopRestY = 0.8;
class HelixCurve extends THREE.Curve {
constructor(y0, y1) {
super();
this.y0 = y0;
this.y1 = y1;
this.radius = 0.68;
this.turns = 8.5;
}
getPoint(t, target = new THREE.Vector3()) {
const angle = t * this.turns * Math.PI * 2;
const y = THREE.MathUtils.lerp(this.y0, this.y1, t);
return target.set(
Math.cos(angle) * this.radius,
y,
Math.sin(angle) * this.radius
);
}
}
const springMaterial = new THREE.MeshStandardMaterial({
color: 0x63e3ff,
emissive: 0x123d4d,
emissiveIntensity: 0.35,
metalness: 0.8,
roughness: 0.22
});
const springMesh = new THREE.Mesh(
new THREE.BufferGeometry(),
springMaterial
);
springMesh.castShadow = true;
springGroup.add(springMesh);
const capMaterial = new THREE.MeshStandardMaterial({
color: 0x26374e,
metalness: 0.7,
roughness: 0.3
});
const bottomCap = new THREE.Mesh(
new THREE.CylinderGeometry(0.9, 0.9, 0.16, 48),
capMaterial
);
bottomCap.position.y = springBottomY;
bottomCap.castShadow = true;
springGroup.add(bottomCap);
const topCap = new THREE.Mesh(
new THREE.CylinderGeometry(0.9, 0.9, 0.16, 48),
capMaterial.clone()
);
topCap.castShadow = true;
springGroup.add(topCap);
const strainMaterial = new THREE.MeshStandardMaterial({
color: 0xffc078,
emissive: 0xff7b25,
emissiveIntensity: 1.1,
roughness: 0.28
});
const strainDots = new THREE.InstancedMesh(
new THREE.SphereGeometry(0.035, 8, 6),
strainMaterial,
34
);
strainDots.frustumCulled = false;
springGroup.add(strainDots);
const appliedForce = new THREE.ArrowHelper(
new THREE.Vector3(0, -1, 0),
new THREE.Vector3(0.98, 0.5, 0),
0.5,
0xffb65c,
0.15,
0.09
);
const restoringForce = new THREE.ArrowHelper(
new THREE.Vector3(0, 1, 0),
new THREE.Vector3(-0.98, -0.7, 0),
0.5,
0x78efb0,
0.15,
0.09
);
springGroup.add(appliedForce, restoringForce);
// ---------------------------------------------------------------------
// Physical state and UI updates
// ---------------------------------------------------------------------
const MAX_ENERGY = 0.2; // joules
const CAPACITANCE = 1e-7; // farads, illustrative
const SPRING_CONSTANT = 2; // N/m, illustrative
const state = {
energy: MAX_ENERGY * 0.45,
springTopY: springTopRestY,
helixCurve: null
};
const energySlider = document.querySelector("#energy");
const energyReadout = document.querySelector("#energy-readout");
const mechanismsToggle = document.querySelector("#show-mechanisms");
const capEnergyElement = document.querySelector("#cap-energy");
const capVoltageElement = document.querySelector("#cap-voltage");
const capChargeElement = document.querySelector("#cap-charge");
const springEnergyElement = document.querySelector("#spring-energy");
const springCompressionElement = document.querySelector("#spring-compression");
const springForceElement = document.querySelector("#spring-force");
function formatEnergy(joules) {
if (joules < 0.0005) return "0 mJ";
if (joules < 0.1) return `${Math.round(joules * 1000)} mJ`;
return `${joules.toFixed(3)} J`;
}
function formatVoltage(volts) {
if (volts >= 1000) return `${(volts / 1000).toFixed(2)} kV`;
return `${volts.toFixed(0)} V`;
}
function rebuildSpringGeometry() {
const curve = new HelixCurve(
springBottomY + 0.1,
state.springTopY - 0.1
);
state.helixCurve = curve;
const nextGeometry = new THREE.TubeGeometry(
curve,
180,
0.057,
8,
false
);
springMesh.geometry.dispose();
springMesh.geometry = nextGeometry;
for (let index = 0; index < 34; index++) {
const t = index / 33;
const point = curve.getPoint(t);
dummy.position.copy(point);
dummy.scale.setScalar(1);
dummy.updateMatrix();
strainDots.setMatrixAt(index, dummy.matrix);
}
strainDots.instanceMatrix.needsUpdate = true;
topCap.position.y = state.springTopY;
}
function updatePhysicalState() {
const energy = state.energy;
const normalizedEnergy = energy / MAX_ENERGY;
// Capacitor: U = 1/2 C V² and U = Q²/(2C).
const charge = Math.sqrt(2 * CAPACITANCE * energy);
const voltage = charge / CAPACITANCE;
// Spring: U = 1/2 k x².
const compression = Math.sqrt(2 * energy / SPRING_CONSTANT);
const force = SPRING_CONSTANT * compression;
state.springTopY = springTopRestY - compression;
rebuildSpringGeometry();
// Charge and field strength scale with the square root of energy.
const amountScale = Math.sqrt(normalizedEnergy);
for (let index = 0; index < chargePositions.length; index++) {
const point = chargePositions[index];
const scale = 0.35 + amountScale * 1.05;
dummy.position.set(point.x, point.y, point.z);
dummy.scale.setScalar(scale);
dummy.updateMatrix();
if (index % 2 === 0) {
positiveCharges.setMatrixAt(index / 2, dummy.matrix);
} else {
negativeCharges.setMatrixAt((index - 1) / 2, dummy.matrix);
}
}
positiveCharges.instanceMatrix.needsUpdate = true;
negativeCharges.instanceMatrix.needsUpdate = true;
positiveChargeMaterial.opacity = 0.12 + amountScale * 0.88;
negativeChargeMaterial.opacity = 0.12 + amountScale * 0.88;
positiveSign.material.opacity = 0.12 + amountScale * 0.88;
negativeSign.material.opacity = 0.12 + amountScale * 0.88;
const fieldStrength = 0.16 + amountScale * 0.78;
fieldLineMaterials.forEach((material) => {
material.opacity = fieldStrength;
});
fieldArrowMaterials.forEach((material) => {
material.opacity = 0.2 + amountScale * 0.8;
});
dielectric.material.opacity = 0.12 + amountScale * 0.2;
// The spring becomes warmer in color as elastic strain increases.
const coolColor = new THREE.Color(0x63e3ff);
const hotColor = new THREE.Color(0xffb65c);
const springColor = coolColor.clone().lerp(hotColor, normalizedEnergy);
springMaterial.color.copy(springColor);
springMaterial.emissive.copy(springColor).multiplyScalar(0.25);
springMaterial.emissiveIntensity = 0.25 + normalizedEnergy * 0.65;
strainMaterial.opacity = 0.2 + normalizedEnergy * 0.8;
strainMaterial.transparent = true;
const arrowLength = 0.2 + amountScale * 0.55;
appliedForce.setLength(arrowLength, 0.15, 0.09);
restoringForce.setLength(arrowLength, 0.15, 0.09);
appliedForce.position.set(0.98, state.springTopY + 0.32, 0);
restoringForce.position.set(-0.98, springBottomY + 0.08, 0);
appliedForce.visible = energy > 0.00001;
restoringForce.visible = energy > 0.00001;
// Update all displayed values.
energyReadout.textContent = formatEnergy(energy);
capEnergyElement.textContent = formatEnergy(energy);
capVoltageElement.textContent = formatVoltage(voltage);
capChargeElement.textContent = `${(charge * 1e6).toFixed(0)} μC`;
springEnergyElement.textContent = formatEnergy(energy);
springCompressionElement.textContent = `${(compression * 100).toFixed(1)} cm`;
springForceElement.textContent = `${force.toFixed(2)} N`;
fieldGroup.visible = mechanismsToggle.checked;
appliedForce.visible =
mechanismsToggle.checked && energy > 0.00001;
restoringForce.visible =
mechanismsToggle.checked && energy > 0.00001;
}
energySlider.addEventListener("input", () => {
state.energy = MAX_ENERGY * (Number(energySlider.value) / 100);
updatePhysicalState();
});
mechanismsToggle.addEventListener("change", updatePhysicalState);
// ---------------------------------------------------------------------
// Direct camera controls: orbit, zoom, and keyboard access
// ---------------------------------------------------------------------
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
let pointerId = null;
function defaultRadius() {
return window.innerWidth < 760 ? 14.2 : 9.6;
}
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
pointerId = event.pointerId;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
canvas.setPointerCapture(pointerId);
canvas.style.cursor = "grabbing";
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - lastPointerX;
const deltaY = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
view.targetTheta -= deltaX * 0.006;
view.targetPhi = THREE.MathUtils.clamp(
view.targetPhi + deltaY * 0.005,
0.52,
1.48
);
});
function endDrag(event) {
if (!dragging) return;
dragging = false;
canvas.style.cursor = "grab";
if (pointerId !== null && canvas.hasPointerCapture(pointerId)) {
canvas.releasePointerCapture(pointerId);
}
pointerId = null;
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener("lostpointercapture", () => {
dragging = false;
canvas.style.cursor = "grab";
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
view.targetRadius = THREE.MathUtils.clamp(
view.targetRadius + event.deltaY * 0.008,
6.5,
18
);
},
{ passive: false }
);
canvas.addEventListener("keydown", (event) => {
let handled = true;
switch (event.key) {
case "ArrowLeft":
view.targetTheta += 0.09;
break;
case "ArrowRight":
view.targetTheta -= 0.09;
break;
case "ArrowUp":
view.targetPhi = Math.max(0.52, view.targetPhi - 0.07);
break;
case "ArrowDown":
view.targetPhi = Math.min(1.48, view.targetPhi + 0.07);
break;
case "+":
case "=":
view.targetRadius = Math.max(6.5, view.targetRadius - 0.5);
break;
case "-":
view.targetRadius = Math.min(18, view.targetRadius + 0.5);
break;
default:
handled = false;
}
if (handled) event.preventDefault();
});
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.style.cursor = "grab";
document.querySelector("#reset-view").addEventListener("click", () => {
view.targetTheta = 0;
view.targetPhi = 1.17;
view.targetRadius = defaultRadius();
});
// ---------------------------------------------------------------------
// Projected labels and render loop
// ---------------------------------------------------------------------
const capacitorLabel = document.querySelector("#label-capacitor");
const springLabel = document.querySelector("#label-spring");
const capacitorLabelPosition = new THREE.Vector3(-2.55, 1.55, 0);
const springLabelPosition = new THREE.Vector3(2.55, 1.34, 0);
const projected = new THREE.Vector3();
function placeLabel(element, worldPosition) {
projected.copy(worldPosition).project(camera);
const visible = projected.z > -1 && projected.z < 1;
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
element.style.opacity = visible ? "1" : "0";
}
function updateCamera() {
view.theta += (view.targetTheta - view.theta) * 0.12;
view.phi += (view.targetPhi - view.phi) * 0.12;
view.radius += (view.targetRadius - view.radius) * 0.12;
const offset = new THREE.Vector3().setFromSphericalCoords(
view.radius,
view.phi,
view.theta
);
camera.position.copy(cameraTarget).add(offset);
camera.lookAt(cameraTarget);
}
function animate() {
updateCamera();
placeLabel(capacitorLabel, capacitorLabelPosition);
placeLabel(springLabel, springLabelPosition);
renderer.render(scene, camera);
}
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
}
window.addEventListener("resize", resize);
updatePhysicalState();
updateCamera();
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```