Prompt specification
Build or customize the Three.js 3D scene "Charging and discharging 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: Charging and discharging comparison
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/charging-and-discharging-comparison-x1662
Scene Description Prompt:
Make a stylized Three.js scene in a self-contained HTML file using cdnjs: charging and discharging comparison. Place two identical virtual capacitors in matched circuits, one charging and one discharging from a known initial state; show voltage and current directions consistently.
Working Three.js Starter (charging-and-discharging-comparison-x1662):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Capacitor Charging vs. Discharging</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(9, 20, 35, 0.82);
--border: rgba(148, 163, 184, 0.22);
--text: #e5edf7;
--muted: #8da2b8;
--charge: #5eead4;
--discharge: #fbbf24;
--current: #fde047;
--positive: #fb7185;
--negative: #60a5fa;
}
* {
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;
}
#app {
position: fixed;
inset: 0;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
header {
position: fixed;
z-index: 5;
top: 16px;
left: 20px;
right: 20px;
display: flex;
align-items: flex-start;
justify-content: space-between;
pointer-events: none;
}
.title-wrap {
max-width: 560px;
text-shadow: 0 2px 18px rgba(0, 0, 0, 0.6);
}
h1 {
margin: 0;
font-size: clamp(20px, 2.2vw, 32px);
letter-spacing: -0.04em;
font-weight: 750;
}
.subtitle {
margin-top: 5px;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.legend {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 8px;
max-width: 440px;
}
.legend span {
padding: 7px 10px;
border: 1px solid var(--border);
border-radius: 999px;
background: rgba(8, 18, 31, 0.76);
color: #c9d6e5;
font-size: 11px;
backdrop-filter: blur(10px);
}
.legend .gold {
color: var(--current);
}
.card {
position: fixed;
z-index: 5;
top: 92px;
width: min(330px, calc(50vw - 32px));
padding: 15px 16px;
border: 1px solid var(--border);
border-radius: 18px;
background: var(--panel);
box-shadow:
0 18px 50px rgba(0, 0, 0, 0.28),
inset 0 1px 0 rgba(255, 255, 255, 0.035);
backdrop-filter: blur(16px);
pointer-events: none;
}
#charge-card {
left: 20px;
border-top: 2px solid var(--charge);
}
#discharge-card {
right: 20px;
border-top: 2px solid var(--discharge);
}
.eyebrow {
color: var(--muted);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.card h2 {
margin: 4px 0 12px;
font-size: 19px;
letter-spacing: -0.02em;
}
#charge-card h2 {
color: var(--charge);
}
#discharge-card h2 {
color: var(--discharge);
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
}
.metric {
min-width: 0;
padding: 9px 8px;
border: 1px solid rgba(148, 163, 184, 0.12);
border-radius: 11px;
background: rgba(255, 255, 255, 0.025);
}
.metric .label {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric .value {
display: block;
overflow: hidden;
color: #f5f8fc;
font-size: 14px;
font-weight: 720;
white-space: nowrap;
text-overflow: ellipsis;
}
.direction {
margin-top: 11px;
padding: 9px 10px;
border-left: 3px solid var(--current);
border-radius: 6px;
background: rgba(253, 224, 71, 0.065);
color: #f8fafc;
font-size: 12px;
line-height: 1.45;
}
.formula,
.initial {
margin-top: 9px;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.formula code {
color: #dbeafe;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
.initial strong {
color: #dce7f4;
font-weight: 650;
}
.controls {
position: fixed;
z-index: 8;
left: 50%;
bottom: 18px;
display: flex;
align-items: center;
gap: 10px;
width: min(940px, calc(100vw - 28px));
padding: 11px 13px;
transform: translateX(-50%);
border: 1px solid var(--border);
border-radius: 16px;
background: rgba(8, 18, 31, 0.9);
box-shadow: 0 15px 45px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(16px);
}
button,
select {
min-height: 36px;
border: 1px solid rgba(148, 163, 184, 0.23);
border-radius: 10px;
background: rgba(148, 163, 184, 0.09);
color: var(--text);
font: inherit;
font-size: 12px;
font-weight: 650;
}
button {
padding: 0 13px;
cursor: pointer;
transition:
background 140ms ease,
border-color 140ms ease,
transform 140ms ease;
}
button:hover {
border-color: rgba(148, 163, 184, 0.45);
background: rgba(148, 163, 184, 0.16);
}
button:active {
transform: translateY(1px);
}
#play {
min-width: 88px;
border-color: rgba(94, 234, 212, 0.35);
background: rgba(94, 234, 212, 0.12);
color: #bffdf1;
}
.timeline-wrap {
display: flex;
flex: 1;
align-items: center;
gap: 10px;
min-width: 100px;
}
.time {
min-width: 62px;
color: #dce8f5;
font: 650 12px ui-monospace, SFMono-Regular, Menlo, monospace;
}
input[type="range"] {
width: 100%;
accent-color: var(--charge);
cursor: pointer;
}
.control-label {
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.note {
position: fixed;
z-index: 5;
right: 21px;
bottom: 91px;
max-width: 340px;
color: rgba(190, 207, 225, 0.67);
font-size: 10px;
line-height: 1.5;
text-align: right;
pointer-events: none;
}
@media (max-width: 820px) {
header {
top: 11px;
left: 13px;
right: 13px;
}
.legend {
display: none;
}
.card {
top: 70px;
width: calc(50vw - 18px);
padding: 11px;
}
#charge-card {
left: 10px;
}
#discharge-card {
right: 10px;
}
.card h2 {
margin-bottom: 8px;
font-size: 15px;
}
.metrics {
grid-template-columns: 1fr 1fr;
}
.metric:nth-child(3),
.formula,
.initial {
display: none;
}
.direction {
margin-top: 8px;
padding: 7px;
font-size: 10px;
}
.controls {
gap: 7px;
padding: 9px;
}
.control-label,
#view-reset {
display: none;
}
button {
padding: 0 10px;
}
.note {
display: none;
}
}
</style>
</head>
<body>
<div id="app"></div>
<header>
<div class="title-wrap">
<h1>Capacitor Energy Lab</h1>
<div class="subtitle">
Matched R–C circuits with an ideal 8 V source and τ = RC = 1.00 s.
Gold arrows show conventional current.
</div>
</div>
<div class="legend">
<span class="gold">◆ Conventional current</span>
<span style="color:var(--positive)">+ Plate A</span>
<span style="color:var(--negative)">− Plate B</span>
<span>Drag to orbit · wheel to zoom · shift-drag to pan</span>
</div>
</header>
<section id="charge-card" class="card">
<div class="eyebrow">Matched charging path</div>
<h2>CHARGING</h2>
<div class="metrics">
<div class="metric">
<span class="label">V_C</span>
<span id="charge-v" class="value">0.00 V</span>
</div>
<div class="metric">
<span class="label">I into A</span>
<span id="charge-i" class="value">+80.0 mA</span>
</div>
<div class="metric">
<span class="label">Charge</span>
<span id="charge-q" class="value">0.0 mC</span>
</div>
</div>
<div class="direction">
Current leaves the source’s <b>positive terminal</b>, passes through R,
and <b>enters plate A (+)</b>.
</div>
<div class="formula">
<code>V_C = 8(1 − e<sup>−t/τ</sup>)</code><br>
<code>I_C = 80e<sup>−t/τ</sup> mA</code>
</div>
<div class="initial">
<strong>Known initial state:</strong> V_C(0) = 0.00 V, Q(0) = 0.
The ideal switch closes at t = 0.
</div>
</section>
<section id="discharge-card" class="card">
<div class="eyebrow">Matched discharge load</div>
<h2>DISCHARGING</h2>
<div class="metrics">
<div class="metric">
<span class="label">V_C</span>
<span id="discharge-v" class="value">8.00 V</span>
</div>
<div class="metric">
<span class="label">I into A</span>
<span id="discharge-i" class="value">−80.0 mA</span>
</div>
<div class="metric">
<span class="label">Charge</span>
<span id="discharge-q" class="value">80.0 mC</span>
</div>
</div>
<div class="direction">
Current <b>leaves plate A (+)</b>, passes through the same R in the
opposite direction, and returns to plate B (−).
</div>
<div class="formula">
<code>V_C = 8e<sup>−t/τ</sup></code><br>
<code>I_C = −80e<sup>−t/τ</sup> mA</code>
</div>
<div class="initial">
<strong>Known initial state:</strong> V_C(0) = +8.00 V,
Q(0) = +80.0 mC. The discharge switch is closed at t = 0.
</div>
</section>
<div class="controls">
<button id="play" type="button">Pause</button>
<button id="reset" type="button">Reset</button>
<div class="timeline-wrap">
<span class="control-label">Time</span>
<input id="timeline" type="range" min="0" max="8" step="0.01" value="0"
aria-label="Simulation time">
<span id="time" class="time">0.00 s</span>
</div>
<span class="control-label">Speed</span>
<select id="speed" aria-label="Simulation speed">
<option value="0.25">0.25×</option>
<option value="0.5">0.5×</option>
<option value="1" selected>1×</option>
<option value="2">2×</option>
</select>
<button id="view-reset" type="button">Reset view</button>
</div>
<div class="note">
Current convention: I_C is positive when current enters plate A (+).
Therefore charging has positive I_C, while discharging has negative I_C.
Ideal source and switch; source resistance and inductance are omitted.
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Model constants
// -------------------------------------------------------------------------
const SOURCE_VOLTAGE = 8.0; // V
const RESISTANCE = 100.0; // ohm
const CAPACITANCE = 0.010; // F = 10,000 uF
const TAU = RESISTANCE * CAPACITANCE;
const MAX_CURRENT = SOURCE_VOLTAGE / RESISTANCE;
const MAX_TIME = 8.0;
const app = document.getElementById("app");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 20, 46);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
120
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
app.appendChild(renderer.domElement);
// -------------------------------------------------------------------------
// Lighting and environment
// -------------------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0xb9dcff, 0x152033, 1.7));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.0);
keyLight.position.set(-5, 12, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -14;
keyLight.shadow.camera.right = 14;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
keyLight.shadow.normalBias = 0.025;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x22d3ee, 32, 16, 2);
cyanLight.position.set(-6, 4, 2);
scene.add(cyanLight);
const amberLight = new THREE.PointLight(0xf59e0b, 32, 16, 2);
amberLight.position.set(6, 4, 1);
scene.add(amberLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(80, 80),
new THREE.MeshStandardMaterial({
color: 0x081321,
roughness: 0.96,
metalness: 0.08
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.25;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(60, 60, 0x1b4058, 0x10283a);
grid.position.y = -0.235;
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
// -------------------------------------------------------------------------
// Small geometry and texture helpers
// -------------------------------------------------------------------------
const Y_AXIS = new THREE.Vector3(0, 1, 0);
function cylinderBetween(parent, a, b, radius, material) {
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, 14),
material
);
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(Y_AXIS, direction.normalize());
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function roundedRect(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
}
function createTextSprite(
text,
{
color = "#dbeafe",
background = "rgba(7, 17, 31, 0.78)",
border = "rgba(148, 163, 184, 0.22)",
scale = [2, 0.5],
fontSize = 72
} = {}
) {
const canvas = document.createElement("canvas");
canvas.width = 1024;
canvas.height = 256;
const ctx = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(
8,
renderer.capabilities.getMaxAnisotropy()
);
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(scale[0], scale[1], 1);
sprite.renderOrder = 20;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (background) {
roundedRect(ctx, 10, 10, 1004, 236, 38);
ctx.fillStyle = background;
ctx.fill();
if (border) {
ctx.strokeStyle = border;
ctx.lineWidth = 3;
ctx.stroke();
}
}
ctx.fillStyle = color;
ctx.font = `750 ${fontSize}px Inter, system-ui, sans-serif`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 512, 130, 950);
}
draw();
sprite.userData.draw = draw;
sprite.userData.texture = texture;
return sprite;
}
function createCapLabel(initialVoltage, accent) {
const canvas = document.createElement("canvas");
canvas.width = 1024;
canvas.height = 320;
const ctx = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(
8,
renderer.capabilities.getMaxAnisotropy()
);
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(2.25, 0.70, 1);
sprite.renderOrder = 21;
function update(voltage, accentColor) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(ctx, 10, 10, 1004, 300, 38);
ctx.fillStyle = "rgba(7, 17, 31, 0.84)";
ctx.fill();
ctx.strokeStyle = "rgba(148, 163, 184, 0.25)";
ctx.lineWidth = 3;
ctx.stroke();
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#a9bbce";
ctx.font = "650 52px Inter, system-ui, sans-serif";
ctx.fillText("C = 10,000 µF", 512, 92);
ctx.fillStyle = accentColor;
ctx.font = "760 76px Inter, system-ui, sans-serif";
ctx.fillText(`V_C = ${voltage.toFixed(2)} V`, 512, 215);
texture.needsUpdate = true;
}
update(initialVoltage, accent);
sprite.userData.update = update;
return sprite;
}
function makeBoard(parent, accentColor) {
const boardMaterial = new THREE.MeshStandardMaterial({
color: 0x0d2033,
roughness: 0.72,
metalness: 0.3
});
const board = new THREE.Mesh(
new THREE.BoxGeometry(7.7, 0.24, 5.8),
boardMaterial
);
board.position.y = -0.10;
board.receiveShadow = true;
board.castShadow = true;
parent.add(board);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(board.geometry),
new THREE.LineBasicMaterial({
color: accentColor,
transparent: true,
opacity: 0.36
})
);
edges.position.copy(board.position);
parent.add(edges);
const accentStrip = new THREE.Mesh(
new THREE.BoxGeometry(7.15, 0.035, 0.055),
new THREE.MeshBasicMaterial({ color: accentColor })
);
accentStrip.position.set(0, 0.035, -2.74);
parent.add(accentStrip);
const screwMaterial = new THREE.MeshStandardMaterial({
color: 0x7890a6,
roughness: 0.34,
metalness: 0.85
});
for (const x of [-3.55, 3.55]) {
for (const z of [-2.58, 2.58]) {
const screw = new THREE.Mesh(
new THREE.CylinderGeometry(0.085, 0.085, 0.05, 18),
screwMaterial
);
screw.position.set(x, 0.045, z);
screw.castShadow = true;
parent.add(screw);
}
}
}
// -------------------------------------------------------------------------
// Wire path used by moving current arrows
// -------------------------------------------------------------------------
class WirePath {
constructor(points) {
this.points = points.map((p) => new THREE.Vector3(...p));
this.lengths = [];
this.total = 0;
for (let i = 0; i < this.points.length - 1; i++) {
const length = this.points[i].distanceTo(this.points[i + 1]);
this.lengths.push(length);
this.total += length;
}
}
sample(distance, position, tangent) {
let remaining =
((distance % this.total) + this.total) % this.total;
for (let i = 0; i < this.lengths.length; i++) {
const length = this.lengths[i];
if (remaining <= length || i === this.lengths.length - 1) {
const u = length > 0 ? remaining / length : 0;
position.lerpVectors(
this.points[i],
this.points[i + 1],
THREE.MathUtils.clamp(u, 0, 1)
);
tangent
.subVectors(this.points[i + 1], this.points[i])
.normalize();
return;
}
remaining -= length;
}
}
}
function addCurrentArrow(refs, position, direction) {
const mesh = new THREE.Mesh(
new THREE.ConeGeometry(0.13, 0.38, 3),
refs.currentMaterial
);
mesh.position.set(...position);
mesh.quaternion.setFromUnitVectors(
Y_AXIS,
new THREE.Vector3(...direction).normalize()
);
mesh.renderOrder = 8;
refs.group.add(mesh);
refs.staticArrows.push(mesh);
}
function addMovers(refs, paths) {
const coneGeometry = new THREE.ConeGeometry(0.115, 0.32, 3);
for (const path of paths) {
const count = Math.max(1, Math.round(path.total / 2));
for (let i = 0; i < count; i++) {
const mesh = new THREE.Mesh(
coneGeometry,
refs.currentMaterial
);
mesh.renderOrder = 8;
refs.group.add(mesh);
refs.movers.push({
mesh,
path,
offset: (path.total * i) / count
});
}
}
}
// -------------------------------------------------------------------------
// Circuit construction
// -------------------------------------------------------------------------
function createCircuit(centerX, mode) {
const group = new THREE.Group();
group.position.x = centerX;
scene.add(group);
const charging = mode === "charging";
const accent = charging ? 0x5eead4 : 0xfbbf24;
const accentCSS = charging ? "#5eead4" : "#fbbf24";
makeBoard(group, accent);
const refs = {
group,
staticArrows: [],
movers: [],
positiveMaterial: null,
negativeMaterial: null,
capLabel: null,
currentMaterial: new THREE.MeshBasicMaterial({
color: 0xfde047,
transparent: true,
opacity: 1,
depthWrite: false
})
};
const wireMaterial = new THREE.MeshStandardMaterial({
color: 0x8aa5bc,
roughness: 0.32,
metalness: 0.78,
emissive: 0x102737,
emissiveIntensity: 0.3
});
const resistorMaterial = new THREE.MeshStandardMaterial({
color: 0xd7b47b,
roughness: 0.42,
metalness: 0.35
});
const bandMaterial = new THREE.MeshStandardMaterial({
color: 0x263647,
roughness: 0.4,
metalness: 0.55
});
// Common top branch, interrupted by the resistor.
cylinderBetween(
group,
[-2.55, 0.25, -1.55],
[-0.78, 0.25, -1.55],
0.055,
wireMaterial
);
cylinderBetween(
group,
[0.78, 0.25, -1.55],
[2.55, 0.25, -1.55],
0.055,
wireMaterial
);
// Common bottom return branch.
cylinderBetween(
group,
[-2.55, 0.25, 1.55],
[2.55, 0.25, 1.55],
0.055,
wireMaterial
);
// Capacitor leads.
cylinderBetween(
group,
[2.55, 0.25, -1.55],
[2.55, 0.25, -0.27],
0.055,
wireMaterial
);
cylinderBetween(
group,
[2.55, 0.25, 0.27],
[2.55, 0.25, 1.55],
0.055,
wireMaterial
);
// Identical resistor in both circuits.
cylinderBetween(
group,
[-0.72, 0.34, -1.55],
[0.72, 0.34, -1.55],
0.19,
resistorMaterial
);
for (const x of [-0.48, -0.16, 0.16, 0.48]) {
cylinderBetween(
group,
[x - 0.035, 0.34, -1.55],
[x + 0.035, 0.34, -1.55],
0.195,
bandMaterial
);
}
// Identical capacitor: plate A at negative Z is designated (+).
const positiveMaterial = new THREE.MeshStandardMaterial({
color: 0x8193a5,
emissive: 0xfb405c,
emissiveIntensity: 0,
roughness: 0.26,
metalness: 0.78
});
const negativeMaterial = new THREE.MeshStandardMaterial({
color: 0x8193a5,
emissive: 0x348dff,
emissiveIntensity: 0,
roughness: 0.26,
metalness: 0.78
});
refs.positiveMaterial = positiveMaterial;
refs.negativeMaterial = negativeMaterial;
const plateGeometry = new THREE.BoxGeometry(1.15, 0.12, 0.19);
const positivePlate = new THREE.Mesh(
plateGeometry,
positiveMaterial
);
positivePlate.position.set(2.55, 0.34, -0.27);
positivePlate.castShadow = true;
group.add(positivePlate);
const negativePlate = new THREE.Mesh(
plateGeometry,
negativeMaterial
);
negativePlate.position.set(2.55, 0.34, 0.27);
negativePlate.castShadow = true;
group.add(negativePlate);
const dielectric = new THREE.Mesh(
new THREE.BoxGeometry(1.02, 0.07, 0.38),
new THREE.MeshPhysicalMaterial({
color: 0x60a5fa,
transparent: true,
opacity: 0.18,
roughness: 0.15,
transmission: 0.25,
thickness: 0.1
})
);
dielectric.position.set(2.55, 0.30, 0);
group.add(dielectric);
if (charging) {
// Ideal 8 V source in the left branch.
cylinderBetween(
group,
[-2.55, 0.25, -1.55],
[-2.55, 0.25, -0.62],
0.055,
wireMaterial
);
cylinderBetween(
group,
[-2.55, 0.25, 0.62],
[-2.55, 0.25, 1.55],
0.055,
wireMaterial
);
const sourceBody = new THREE.Mesh(
new THREE.BoxGeometry(0.86, 0.76, 1.14),
new THREE.MeshStandardMaterial({
color: 0x243c51,
roughness: 0.46,
metalness: 0.42
})
);
sourceBody.position.set(-2.55, 0.42, 0);
sourceBody.castShadow = true;
group.add(sourceBody);
const sourceCap = new THREE.Mesh(
new THREE.BoxGeometry(0.90, 0.12, 1.18),
new THREE.MeshStandardMaterial({
color: 0x3f6078,
roughness: 0.42,
metalness: 0.48
})
);
sourceCap.position.set(-2.55, 0.86, 0);
sourceCap.castShadow = true;
group.add(sourceCap);
const plusTerminal = new THREE.Mesh(
new THREE.CylinderGeometry(0.14, 0.14, 0.12, 18),
new THREE.MeshStandardMaterial({
color: 0xfb405c,
emissive: 0xfb405c,
emissiveIntensity: 0.25,
roughness: 0.3,
metalness: 0.45
})
);
plusTerminal.rotation.x = Math.PI / 2;
plusTerminal.position.set(-2.55, 0.46, -0.61);
group.add(plusTerminal);
const minusTerminal = new THREE.Mesh(
new THREE.CylinderGeometry(0.14, 0.14, 0.12, 18),
new THREE.MeshStandardMaterial({
color: 0x348dff,
emissive: 0x348dff,
emissiveIntensity: 0.25,
roughness: 0.3,
metalness: 0.45
})
);
minusTerminal.rotation.x = Math.PI / 2;
minusTerminal.position.set(-2.55, 0.46, 0.61);
group.add(minusTerminal);
const sourceLabel = createTextSprite("8 V DC", {
color: "#fde68a",
scale: [1.55, 0.42],
fontSize: 70
});
sourceLabel.position.set(-2.55, 1.55, 0.05);
group.add(sourceLabel);
const plusLabel = createTextSprite("+", {
color: "#fb7185",
background: "rgba(7, 17, 31, 0.65)",
scale: [0.45, 0.34],
fontSize: 92
});
plusLabel.position.set(-3.25, 1.02, -0.72);
group.add(plusLabel);
const minusLabel = createTextSprite("−", {
color: "#60a5fa",
background: "rgba(7, 17, 31, 0.65)",
scale: [0.45, 0.34],
fontSize: 92
});
minusLabel.position.set(-3.25, 1.02, 0.72);
group.add(minusLabel);
} else {
// Closed switch in the left branch.
cylinderBetween(
group,
[-2.55, 0.25, -1.55],
[-2.55, 0.25, -0.38],
0.055,
wireMaterial
);
cylinderBetween(
group,
[-2.55, 0.25, 0.38],
[-2.55, 0.25, 1.55],
0.055,
wireMaterial
);
const switchMaterial = new THREE.MeshStandardMaterial({
color: 0xfbbf24,
emissive: 0x7a4b00,
emissiveIntensity: 0.45,
roughness: 0.3,
metalness: 0.72
});
cylinderBetween(
group,
[-2.55, 0.31, -0.38],
[-2.55, 0.31, 0.38],
0.075,
switchMaterial
);
for (const z of [-0.38, 0.38]) {
const pivot = new THREE.Mesh(
new THREE.CylinderGeometry(0.14, 0.14, 0.18, 18),
new THREE.MeshStandardMaterial({
color: 0xcbd5e1,
roughness: 0.28,
metalness: 0.82
})
);
pivot.position.set(-2.55, 0.39, z);
group.add(pivot);
}
const switchLabel = createTextSprite("CLOSED SW", {
color: "#fde68a",
scale: [1.70, 0.42],
fontSize: 64
});
switchLabel.position.set(-2.55, 1.42, 0);
group.add(switchLabel);
}
// Labels.
const title = createTextSprite(
charging ? "CHARGING" : "DISCHARGING",
{
color: accentCSS,
scale: [2.85, 0.67],
fontSize: 76
}
);
title.position.set(0, 1.72, -2.48);
group.add(title);
const resistorLabel = createTextSprite("R = 100 Ω", {
color: "#e2e8f0",
scale: [1.65, 0.43],
fontSize: 66
});
resistorLabel.position.set(0, 1.10, -1.55);
group.add(resistorLabel);
const capLabel = createCapLabel(
charging ? 0 : SOURCE_VOLTAGE,
accentCSS
);
capLabel.position.set(2.45, 1.38, 0.15);
group.add(capLabel);
refs.capLabel = capLabel;
const plateAPos = createTextSprite("A +", {
color: "#fb7185",
scale: [0.73, 0.34],
fontSize: 68
});
plateAPos.position.set(3.38, 0.96, -0.32);
group.add(plateAPos);
const plateBNeg = createTextSprite("B −", {
color: "#60a5fa",
scale: [0.73, 0.34],
fontSize: 68
});
plateBNeg.position.set(3.38, 0.96, 0.32);
group.add(plateBNeg);
// Static arrows make the direction unambiguous even while paused.
if (charging) {
addCurrentArrow(refs, [0.20, 0.66, -1.55], [1, 0, 0]);
addCurrentArrow(refs, [2.55, 0.66, -0.95], [0, 0, 1]);
addCurrentArrow(refs, [0.20, 0.66, 1.55], [-1, 0, 0]);
addCurrentArrow(refs, [-2.55, 0.66, 0.95], [0, 0, -1]);
addMovers(refs, [
new WirePath([
[-2.55, 0.66, -1.55],
[2.55, 0.66, -1.55]
]),
new WirePath([
[2.55, 0.66, -1.55],
[2.55, 0.66, -0.27]
]),
new WirePath([
[2.55, 0.66, 0.27],
[2.55, 0.66, 1.55],
[-2.55, 0.66, 1.55]
])
]);
} else {
addCurrentArrow(refs, [0.20, 0.66, -1.55], [-1, 0, 0]);
addCurrentArrow(refs, [2.55, 0.66, -0.95], [0, 0, -1]);
addCurrentArrow(refs, [-0.20, 0.66, 1.55], [1, 0, 0]);
addCurrentArrow(refs, [-2.55, 0.66, 0.95], [0, 0, 1]);
addMovers(refs, [
new WirePath([
[2.55, 0.66, -0.27],
[2.55, 0.66, -1.55]
]),
new WirePath([
[2.55, 0.66, -1.55],
[-2.55, 0.66, -1.55]
]),
new WirePath([
[-2.55, 0.66, -1.55],
[-2.55, 0.66, 1.55]
]),
new WirePath([
[-2.55, 0.66, 1.55],
[2.55, 0.66, 1.55],
[2.55, 0.66, 0.27]
])
]);
}
return refs;
}
const chargingCircuit = createCircuit(-4.1, "charging");
const dischargingCircuit = createCircuit(4.1, "discharging");
// -------------------------------------------------------------------------
// Custom camera controls: orbit, pan, wheel zoom, and double-click reset.
// No examples or addons are imported.
// -------------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(0, 0.15, 0),
radius: 16.5,
theta: 0,
phi: 0.88
};
function defaultRadius() {
const aspect = window.innerWidth / window.innerHeight;
if (aspect < 0.8) return 40;
if (aspect < 1.05) return 29;
if (aspect < 1.45) return 20;
return 16.5;
}
function updateCamera() {
const { target, radius, theta, phi } = cameraState;
camera.position.set(
target.x + radius * Math.sin(phi) * Math.sin(theta),
target.y + radius * Math.cos(phi),
target.z + radius * Math.sin(phi) * Math.cos(theta)
);
camera.lookAt(target);
}
function resetCamera() {
cameraState.target.set(0, 0.15, 0);
cameraState.radius = defaultRadius();
cameraState.theta = 0;
cameraState.phi = 0.88;
updateCamera();
}
resetCamera();
let drag = null;
const canvas = renderer.domElement;
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
canvas.setPointerCapture(event.pointerId);
drag = {
id: event.pointerId,
x: event.clientX,
y: event.clientY,
pan: event.button === 2 || event.shiftKey
};
});
canvas.addEventListener("pointermove", (event) => {
if (!drag || drag.id !== event.pointerId) return;
const dx = event.clientX - drag.x;
const dy = event.clientY - drag.y;
drag.x = event.clientX;
drag.y = event.clientY;
if (drag.pan) {
const forward = camera.getWorldDirection(
new THREE.Vector3()
);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3()
.crossVectors(forward, camera.up)
.normalize();
const amount = cameraState.radius * 0.0014;
cameraState.target
.addScaledVector(right, -dx * amount)
.addScaledVector(forward, dy * amount);
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.32,
1.38
);
}
updateCamera();
});
function endDrag(event) {
if (drag && drag.id === event.pointerId) {
drag = null;
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
8.5,
46
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetCamera);
// -------------------------------------------------------------------------
// Simulation and UI
// -------------------------------------------------------------------------
const playButton = document.getElementById("play");
const resetButton = document.getElementById("reset");
const viewResetButton = document.getElementById("view-reset");
const timeline = document.getElementById("timeline");
const speedSelect = document.getElementById("speed");
const timeLabel = document.getElementById("time");
const chargeVElement = document.getElementById("charge-v");
const chargeIElement = document.getElementById("charge-i");
const chargeQElement = document.getElementById("charge-q");
const dischargeVElement = document.getElementById("discharge-v");
const dischargeIElement = document.getElementById("discharge-i");
const dischargeQElement = document.getElementById("discharge-q");
let simulationTime = 0;
let playing = true;
let speed = Number(speedSelect.value);
playButton.addEventListener("click", () => {
if (simulationTime >= MAX_TIME) {
simulationTime = 0;
playing = true;
} else {
playing = !playing;
}
});
resetButton.addEventListener("click", () => {
simulationTime = 0;
playing = true;
});
viewResetButton.addEventListener("click", resetCamera);
speedSelect.addEventListener("change", () => {
speed = Number(speedSelect.value);
});
timeline.addEventListener("input", () => {
simulationTime = Number(timeline.value);
playing = false;
});
const neutralPlate = new THREE.Color(0x8193a5);
const positivePlateColor = new THREE.Color(0xff405c);
const negativePlateColor = new THREE.Color(0x348dff);
function updateCapacitor(refs, chargeRatio) {
const ratio = THREE.MathUtils.clamp(chargeRatio, 0, 1);
refs.positiveMaterial.color
.copy(neutralPlate)
.lerp(positivePlateColor, ratio);
refs.negativeMaterial.color
.copy(neutralPlate)
.lerp(negativePlateColor, ratio);
refs.positiveMaterial.emissive.copy(positivePlateColor);
refs.negativeMaterial.emissive.copy(negativePlateColor);
refs.positiveMaterial.emissiveIntensity = 0.03 + ratio * 1.55;
refs.negativeMaterial.emissiveIntensity = 0.03 + ratio * 1.55;
}
function updateCurrent(refs, signedCurrent) {
const ratio = THREE.MathUtils.clamp(
Math.abs(signedCurrent) / MAX_CURRENT,
0,
1
);
refs.currentMaterial.opacity = ratio;
refs.currentMaterial.visible = ratio > 0.002;
for (const arrow of refs.staticArrows) {
arrow.visible = ratio > 0.002;
}
for (const mover of refs.movers) {
mover.mesh.visible = ratio > 0.002;
}
}
const moverPosition = new THREE.Vector3();
const moverTangent = new THREE.Vector3();
function updateMovingArrows(refs, ratio) {
if (ratio <= 0.002) return;
// The phase is used only for visual animation.
const phase = simulationTime * (0.35 + 2.0 * ratio);
for (const mover of refs.movers) {
const distance =
(phase * (0.65 + 1.8 * ratio) + mover.offset) %
mover.path.total;
mover.path.sample(distance, moverPosition, moverTangent);
mover.mesh.position.copy(moverPosition);
mover.mesh.quaternion.setFromUnitVectors(
Y_AXIS,
moverTangent
);
}
}
function signedMilliamps(value) {
const sign = value >= 0 ? "+" : "−";
return `${sign}${Math.abs(value * 1000).toFixed(1)} mA`;
}
function updateUI(chargeVoltage, chargeCurrent, dischargeVoltage, dischargeCurrent) {
chargeVElement.textContent = `${chargeVoltage.toFixed(2)} V`;
chargeIElement.textContent = signedMilliamps(chargeCurrent);
chargeQElement.textContent =
`${(chargeVoltage * CAPACITANCE * 1000).toFixed(1)} mC`;
dischargeVElement.textContent = `${dischargeVoltage.toFixed(2)} V`;
dischargeIElement.textContent = signedMilliamps(dischargeCurrent);
dischargeQElement.textContent =
`${(dischargeVoltage * CAPACITANCE * 1000).toFixed(1)} mC`;
chargingCircuit.capLabel.userData.update(
chargeVoltage,
"#5eead4"
);
dischargingCircuit.capLabel.userData.update(
dischargeVoltage,
"#fbbf24"
);
timeLabel.textContent = `${simulationTime.toFixed(2)} s`;
timeline.value = String(simulationTime);
playButton.textContent = playing ? "Pause" : "Play";
}
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
let lastUIUpdate = -Infinity;
function animate(now) {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (playing) {
simulationTime += delta * speed;
if (simulationTime >= MAX_TIME) {
simulationTime = MAX_TIME;
playing = false;
}
}
const decay = Math.exp(-simulationTime / TAU);
// Exact closed-form solutions for ideal first-order RC circuits.
const chargeVoltage =
SOURCE_VOLTAGE * (1 - decay);
const dischargeVoltage =
SOURCE_VOLTAGE * decay;
// I_C is positive when current enters plate A (+).
const chargeCurrent =
(SOURCE_VOLTAGE - chargeVoltage) / RESISTANCE;
const dischargeCurrent =
-dischargeVoltage / RESISTANCE;
updateCapacitor(
chargingCircuit,
chargeVoltage / SOURCE_VOLTAGE
);
updateCapacitor(
dischargingCircuit,
dischargeVoltage / SOURCE_VOLTAGE
);
updateCurrent(chargingCircuit, chargeCurrent);
updateCurrent(dischargingCircuit, dischargeCurrent);
updateMovingArrows(
chargingCircuit,
Math.abs(chargeCurrent) / MAX_CURRENT
);
updateMovingArrows(
dischargingCircuit,
Math.abs(dischargeCurrent) / MAX_CURRENT
);
if (now - lastUIUpdate > 75) {
updateUI(
chargeVoltage,
chargeCurrent,
dischargeVoltage,
dischargeCurrent
);
lastUIUpdate = now;
}
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
</script>
</body>
</html>
```