Prompt specification
Build or customize the Three.js 3D scene "RC charging curve model board" 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: RC charging curve model board
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/rc-charging-curve-model-board-x1661
Scene Description Prompt:
Make one HTML file using Three.js from cdnjs for this low-poly scene: Build a virtual resistor-capacitor loop with a switch and synchronized voltage plot; use the analytic exponential response and display the time constant explicitly.
Working Three.js Starter (rc-charging-curve-model-board-x1661):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Low-Poly RC Circuit Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #07111d;
--panel: rgba(8, 20, 33, 0.88);
--panel-border: rgba(113, 218, 255, 0.18);
--text: #eaf8ff;
--muted: #8ca8b9;
--cyan: #55e7ff;
--green: #60efba;
--orange: #ffb45c;
--red: #ff657a;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--text);
}
button,
input,
select {
font: inherit;
}
button {
color: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
touch-action: none;
}
.topbar {
position: fixed;
top: 18px;
left: 20px;
right: 20px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
pointer-events: none;
z-index: 5;
}
.brand {
padding: 12px 15px;
border-left: 3px solid var(--cyan);
background: linear-gradient(90deg, rgba(5, 16, 28, 0.92), rgba(5, 16, 28, 0));
text-shadow: 0 2px 12px #000;
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.22em;
text-transform: uppercase;
}
.brand h1 {
margin: 3px 0 0;
font-size: clamp(20px, 2.2vw, 30px);
font-weight: 760;
letter-spacing: -0.035em;
}
.brand p {
margin: 4px 0 0;
color: var(--muted);
font-size: 12px;
}
.status-group {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 13px;
border: 1px solid var(--panel-border);
border-radius: 999px;
background: var(--panel);
backdrop-filter: blur(12px);
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.22);
}
.status-dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--orange);
box-shadow: 0 0 13px var(--orange);
}
.status-dot.closed {
background: var(--green);
box-shadow: 0 0 13px var(--green);
}
#statusText {
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
white-space: nowrap;
}
#liveClock {
color: var(--muted);
font-size: 11px;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.panel {
position: fixed;
z-index: 4;
border: 1px solid var(--panel-border);
border-radius: 18px;
background: var(--panel);
backdrop-filter: blur(15px);
box-shadow:
0 18px 55px rgba(0, 0, 0, 0.32),
inset 0 1px rgba(255, 255, 255, 0.025);
}
#controls {
left: 20px;
bottom: 20px;
width: 335px;
max-height: calc(100vh - 105px);
padding: 17px;
overflow: auto;
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 13px;
}
.panel-heading h2 {
margin: 0;
font-size: 12px;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.panel-heading span {
color: var(--muted);
font-size: 10px;
}
#switchButton {
width: 100%;
display: flex;
align-items: center;
gap: 12px;
padding: 11px 12px;
margin-bottom: 14px;
border: 1px solid rgba(255, 180, 92, 0.3);
border-radius: 12px;
background: rgba(255, 180, 92, 0.07);
cursor: pointer;
text-align: left;
transition: 160ms ease;
}
#switchButton:hover {
transform: translateY(-1px);
border-color: rgba(255, 180, 92, 0.65);
}
#switchButton.is-closed {
border-color: rgba(96, 239, 186, 0.35);
background: rgba(96, 239, 186, 0.075);
}
.switch-glyph {
position: relative;
width: 39px;
height: 24px;
flex: 0 0 auto;
border-radius: 999px;
background: #172633;
border: 1px solid #314656;
}
.switch-glyph::after {
content: "";
position: absolute;
top: 3px;
left: 3px;
width: 16px;
height: 16px;
border-radius: 50%;
background: var(--orange);
box-shadow: 0 0 12px rgba(255, 180, 92, 0.45);
transition: 180ms ease;
}
.is-closed .switch-glyph::after {
left: 18px;
background: var(--green);
box-shadow: 0 0 12px rgba(96, 239, 186, 0.55);
}
#switchButton strong,
#switchButton small {
display: block;
}
#switchButton strong {
font-size: 11px;
letter-spacing: 0.12em;
}
#switchButton small {
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.control-row {
margin-bottom: 12px;
}
.control-label {
display: flex;
justify-content: space-between;
align-items: baseline;
margin-bottom: 7px;
font-size: 11px;
}
.control-label span {
color: var(--muted);
}
output {
color: var(--cyan);
font-weight: 750;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
accent-color: var(--cyan);
cursor: pointer;
}
select {
width: 100%;
padding: 8px 10px;
color: var(--text);
border: 1px solid #294253;
border-radius: 9px;
outline: none;
background: #0b1b29;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin: 14px 0;
}
.small-button {
padding: 9px 10px;
border: 1px solid #294658;
border-radius: 9px;
background: #102332;
cursor: pointer;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.11em;
transition: 140ms ease;
}
.small-button:hover {
background: #173346;
border-color: #47748d;
}
.equation {
padding: 11px 12px;
border: 1px solid rgba(85, 231, 255, 0.12);
border-radius: 11px;
background: rgba(85, 231, 255, 0.04);
}
.equation-main {
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
font-weight: 750;
}
.equation-sub {
margin-top: 5px;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.tau-card {
display: grid;
grid-template-columns: auto 1fr;
gap: 12px;
align-items: center;
margin-top: 11px;
padding: 12px;
border: 1px solid rgba(255, 180, 92, 0.22);
border-radius: 11px;
background: rgba(255, 180, 92, 0.055);
}
.tau-number {
color: var(--orange);
font-size: 24px;
font-weight: 800;
letter-spacing: -0.04em;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.tau-number small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 8px;
letter-spacing: 0.18em;
}
#tauEquation,
#atTau {
font-size: 10px;
line-height: 1.55;
}
#tauEquation {
color: var(--text);
}
#atTau {
color: var(--muted);
}
.readouts {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-top: 12px;
}
.readout {
padding: 9px 7px;
border: 1px solid rgba(255, 255, 255, 0.065);
border-radius: 9px;
background: rgba(255, 255, 255, 0.025);
text-align: center;
}
.readout span {
display: block;
color: var(--muted);
font-size: 8px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.readout strong {
display: block;
margin-top: 4px;
font-size: 12px;
font-variant-numeric: tabular-nums;
}
#plotPanel {
top: 91px;
right: 20px;
width: min(430px, calc(100vw - 40px));
padding: 16px;
}
.plot-legend {
display: flex;
align-items: center;
gap: 7px;
color: var(--muted);
font-size: 10px;
}
.legend-line {
width: 19px;
height: 3px;
border-radius: 2px;
background: var(--cyan);
box-shadow: 0 0 9px rgba(85, 231, 255, 0.6);
}
#plot {
display: block;
width: 100%;
height: 260px;
margin-top: 8px;
border-radius: 11px;
}
.plot-note {
margin: 8px 2px 0;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.plot-note strong {
color: var(--orange);
}
.help {
position: fixed;
left: 50%;
bottom: 18px;
z-index: 3;
transform: translateX(-50%);
padding: 7px 11px;
border: 1px solid rgba(255, 255, 255, 0.07);
border-radius: 999px;
color: #7895a7;
background: rgba(5, 14, 24, 0.62);
font-size: 10px;
pointer-events: none;
white-space: nowrap;
}
@media (max-width: 760px) {
.topbar {
top: 10px;
left: 10px;
right: 10px;
}
.brand {
padding: 9px 11px;
}
.brand p,
#liveClock {
display: none;
}
#controls {
top: 68px;
left: 10px;
right: 10px;
bottom: auto;
width: auto;
max-height: 31vh;
padding: 13px;
}
#plotPanel {
top: auto;
left: 10px;
right: 10px;
bottom: 10px;
width: auto;
padding: 11px;
}
#plot {
height: 190px;
}
.help {
display: none;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<header class="topbar">
<div class="brand">
<div class="eyebrow">Interactive electronics / analytic model</div>
<h1>RC Circuit Lab</h1>
<p>Low-poly resistor-capacitor charging system</p>
</div>
<div class="status-group">
<span id="statusDot" class="status-dot"></span>
<span id="statusText">SWITCH OPEN</span>
<span id="liveClock">t = 0 ms</span>
</div>
</header>
<section id="controls" class="panel">
<div class="panel-heading">
<h2>Circuit Controls</h2>
<span>Analytic response</span>
</div>
<button id="switchButton" type="button" aria-label="Toggle circuit switch">
<span class="switch-glyph"></span>
<span>
<strong>CIRCUIT SWITCH</strong>
<small id="switchAction">OPEN — click to close</small>
</span>
</button>
<div class="control-row">
<label class="control-label" for="rSlider">
<span>Resistance</span>
<output id="rOut">2.20 kΩ</output>
</label>
<input id="rSlider" type="range" min="100" max="10000" step="100" value="2200">
</div>
<div class="control-row">
<label class="control-label" for="cSlider">
<span>Capacitance</span>
<output id="cOut">100 µF</output>
</label>
<input id="cSlider" type="range" min="10" max="1000" step="10" value="100">
</div>
<div class="control-row">
<label class="control-label" for="vSlider">
<span>Supply voltage</span>
<output id="vOut">5.0 V</output>
</label>
<input id="vSlider" type="range" min="1" max="12" step="0.1" value="5">
</div>
<div class="control-row">
<label class="control-label" for="speedSelect">
<span>Simulation speed</span>
</label>
<select id="speedSelect">
<option value="0.25">0.25× real time</option>
<option value="0.5">0.5× real time</option>
<option value="1" selected>1× real time</option>
<option value="2">2× real time</option>
<option value="4">4× real time</option>
</select>
</div>
<div class="button-row">
<button id="pauseButton" class="small-button" type="button">PAUSE</button>
<button id="resetButton" class="small-button" type="button">RESET</button>
</div>
<div class="equation">
<div class="equation-main">V<sub>C</sub>(t) = V<sub>S</sub>(1 − e<sup>−t/τ</sup>)</div>
<div class="equation-sub">τ = RC · I(t) = (V<sub>S</sub>/R)e<sup>−t/τ</sup></div>
</div>
<div class="tau-card">
<div class="tau-number">
<span id="tauValue">220 ms</span>
<small>TIME CONSTANT τ</small>
</div>
<div>
<div id="tauEquation">2.20 kΩ × 100 µF = 220 ms</div>
<div id="atTau">At τ: 3.16 V (63.2% of 5.0 V)</div>
</div>
</div>
<div class="readouts">
<div class="readout">
<span>Capacitor</span>
<strong id="vcReadout">0.00 V</strong>
</div>
<div class="readout">
<span>Current</span>
<strong id="currentReadout">0.00 mA</strong>
</div>
<div class="readout">
<span>Elapsed</span>
<strong id="timeReadout">0 ms</strong>
</div>
</div>
</section>
<section id="plotPanel" class="panel">
<div class="panel-heading">
<h2>Synchronized Voltage Plot</h2>
<div class="plot-legend">
<span class="legend-line"></span>
<span>V<sub>C</sub>(t)</span>
</div>
</div>
<canvas id="plot" aria-label="Capacitor voltage versus charging time"></canvas>
<p class="plot-note">
The dashed marker is <strong>τ = RC</strong>, where the capacitor reaches
<strong>63.2%</strong> of the supply voltage.
</p>
</section>
<div class="help">Drag to orbit · scroll to zoom · click the 3D switch to toggle it</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
// -------------------------------------------------------------------------
// Simulation state
// -------------------------------------------------------------------------
let R = Number($("rSlider").value);
let Cmicro = Number($("cSlider").value);
let Vs = Number($("vSlider").value);
let speed = Number($("speedSelect").value);
let tau = R * Cmicro * 1e-6;
let maxTime = 5 * tau;
let charging = false;
let paused = false;
let chargeTime = 0;
const switchButton = $("switchButton");
const pauseButton = $("pauseButton");
const plotCanvas = $("plot");
const plotContext = plotCanvas.getContext("2d");
function formatResistance(value) {
return value >= 1000
? `${(value / 1000).toFixed(2)} kΩ`
: `${value} Ω`;
}
function formatCapacitance(value) {
return `${value} µF`;
}
function formatDuration(seconds) {
if (seconds < 1) {
const ms = seconds * 1000;
return `${ms.toFixed(ms < 10 ? 1 : 0)} ms`;
}
if (seconds < 60) {
return `${seconds.toFixed(2)} s`;
}
const minutes = Math.floor(seconds / 60);
const remainder = seconds - minutes * 60;
return `${minutes}m ${remainder.toFixed(1)}s`;
}
function formatCurrent(amps) {
if (Math.abs(amps) >= 1) {
return `${amps.toFixed(2)} A`;
}
return `${(amps * 1000).toFixed(2)} mA`;
}
function analyticVoltage(time) {
return Vs * (1 - Math.exp(-time / tau));
}
function analyticCurrent(time) {
if (!charging || time >= maxTime) return 0;
return (Vs / R) * Math.exp(-time / tau);
}
// -------------------------------------------------------------------------
// Three.js setup
// -------------------------------------------------------------------------
const mount = $("scene");
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
mount.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111d);
scene.fog = new THREE.Fog(0x07111d, 17, 34);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
80
);
// Direct camera controls: no examples/addons modules are used.
const cameraTarget = new THREE.Vector3(0, 0.55, 0);
let cameraYaw = 0.64;
let cameraPitch = 0.72;
let cameraRadius = 11.7;
function updateCamera() {
const horizontalRadius = cameraRadius * Math.cos(cameraPitch);
camera.position.set(
cameraTarget.x + horizontalRadius * Math.sin(cameraYaw),
cameraTarget.y + cameraRadius * Math.sin(cameraPitch),
cameraTarget.z + horizontalRadius * Math.cos(cameraYaw)
);
camera.lookAt(cameraTarget);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0x9ddfff, 0x14202d, 2.0);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xd9f5ff, 3.1);
keyLight.position.set(4, 10, 6);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -10;
keyLight.shadow.camera.right = 10;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 30;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x1ac8ff, 22, 15, 2);
rimLight.position.set(-4, 4, -4);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xff9f50, 16, 12, 2);
warmLight.position.set(4, 3, 3);
scene.add(warmLight);
function standardMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.58,
metalness: 0.12,
flatShading: true,
...options
});
}
function addMesh(geometry, material, parent = scene) {
const mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addCylinderBetween(
start,
end,
radius,
material,
parent = scene,
radialSegments = 8
) {
const a = new THREE.Vector3(...start);
const b = new THREE.Vector3(...end);
const direction = b.clone().sub(a);
const length = direction.length();
const geometry = new THREE.CylinderGeometry(
radius,
radius,
length,
radialSegments,
1,
false
);
const mesh = addMesh(geometry, material, parent);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
return mesh;
}
// Circuit board.
const boardMaterial = standardMaterial(0x10283a, {
roughness: 0.82,
metalness: 0.08
});
const board = addMesh(
new THREE.BoxGeometry(13.4, 0.2, 9.2),
boardMaterial
);
board.position.set(0, -0.14, 0);
const boardEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(board.geometry),
new THREE.LineBasicMaterial({
color: 0x2a6379,
transparent: true,
opacity: 0.52
})
);
boardEdges.position.copy(board.position);
scene.add(boardEdges);
const grid = new THREE.GridHelper(12, 24, 0x2b6075, 0x183747);
grid.position.y = -0.025;
grid.material.transparent = true;
grid.material.opacity = 0.43;
scene.add(grid);
// Shared component materials.
const wireMaterial = standardMaterial(0x30d7ca, {
roughness: 0.34,
metalness: 0.35,
emissive: 0x075c58,
emissiveIntensity: 0.32
});
const terminalMaterial = standardMaterial(0xb5c6ce, {
roughness: 0.26,
metalness: 0.8
});
const resistorMaterial = standardMaterial(0xd6a66d, {
roughness: 0.72,
emissive: 0x35170a,
emissiveIntensity: 0.12
});
const resistorBandMaterial = standardMaterial(0x553b29, {
roughness: 0.7
});
const capacitorMaterialA = standardMaterial(0x30bdf3, {
roughness: 0.3,
metalness: 0.55,
emissive: 0x0a5f8f,
emissiveIntensity: 0.15
});
const capacitorMaterialB = standardMaterial(0x62f0c6, {
roughness: 0.3,
metalness: 0.55,
emissive: 0x087a60,
emissiveIntensity: 0.15
});
const batteryMaterial = standardMaterial(0xf08a43, {
roughness: 0.66,
emissive: 0x6b1f05,
emissiveIntensity: 0.18
});
const switchMaterial = standardMaterial(0xff667b, {
roughness: 0.38,
metalness: 0.42,
emissive: 0x6b1020,
emissiveIntensity: 0.22
});
const darkPlastic = standardMaterial(0x162633, {
roughness: 0.76,
metalness: 0.08
});
// Small mounting pads.
const padMaterial = standardMaterial(0x1b3d4d, {
roughness: 0.86,
metalness: 0.04
});
[
[-3, 0],
[0, -1.5],
[3, 0],
[0, 1.5]
].forEach(([x, z]) => {
const pad = addMesh(
new THREE.CylinderGeometry(0.82, 0.9, 0.07, 12),
padMaterial
);
pad.position.set(x, 0.01, z);
});
// -------------------------------------------------------------------------
// Wires
// -------------------------------------------------------------------------
function addWire(points) {
for (let i = 0; i < points.length - 1; i++) {
addCylinderBetween(points[i], points[i + 1], 0.065, wireMaterial);
}
for (let i = 1; i < points.length - 1; i++) {
const joint = addMesh(
new THREE.IcosahedronGeometry(0.09, 0),
wireMaterial
);
joint.position.set(...points[i]);
}
}
addWire([
[-2.2, 0.78, 0],
[-1.2, 0.78, 0],
[-1.2, 0.78, -1.5]
]);
addWire([
[1.2, 0.78, -1.5],
[2.2, 0.78, -1.5],
[2.2, 0.78, 0]
]);
addWire([
[3.8, 0.78, 0],
[4.35, 0.78, 0],
[4.35, 0.78, 1.5],
[1.2, 0.78, 1.5]
]);
addWire([
[-1.2, 0.78, 1.5],
[-4.35, 0.78, 1.5],
[-4.35, 0.78, 0],
[-3.8, 0.78, 0]
]);
// -------------------------------------------------------------------------
// Battery
// -------------------------------------------------------------------------
const battery = new THREE.Group();
scene.add(battery);
const batteryBody = addMesh(
new THREE.BoxGeometry(1.1, 0.9, 0.92),
batteryMaterial,
battery
);
batteryBody.position.set(-3, 0.78, 0);
const batteryStripe = addMesh(
new THREE.BoxGeometry(0.12, 0.92, 0.94),
standardMaterial(0xffbd68),
battery
);
batteryStripe.position.set(-3, 0.78, 0);
const batteryCap = addMesh(
new THREE.CylinderGeometry(0.16, 0.16, 0.15, 10),
terminalMaterial,
battery
);
batteryCap.position.set(-3, 1.3, 0);
addCylinderBetween(
[-3.8, 0.78, 0],
[-3.55, 0.78, 0],
0.13,
terminalMaterial,
battery
);
addCylinderBetween(
[-2.45, 0.78, 0],
[-2.2, 0.78, 0],
0.13,
terminalMaterial,
battery
);
// -------------------------------------------------------------------------
// Resistor
// -------------------------------------------------------------------------
addCylinderBetween(
[-1.2, 0.78, -1.5],
[-0.84, 0.78, -1.5],
0.09,
terminalMaterial
);
addCylinderBetween(
[-0.84, 0.78, -1.5],
[0.84, 0.78, -1.5],
0.28,
resistorMaterial,
scene,
12
);
addCylinderBetween(
[0.84, 0.78, -1.5],
[1.2, 0.78, -1.5],
0.09,
terminalMaterial
);
[-0.58, -0.25, 0.08, 0.48].forEach((x, index) => {
addCylinderBetween(
[x - 0.055, 0.78, -1.5],
[x + 0.055, 0.78, -1.5],
0.289,
resistorBandMaterial,
scene,
12
);
});
// -------------------------------------------------------------------------
// Capacitor
// -------------------------------------------------------------------------
addCylinderBetween(
[2.2, 0.78, 0],
[2.68, 0.78, 0],
0.09,
terminalMaterial
);
addCylinderBetween(
[3.32, 0.78, 0],
[3.8, 0.78, 0],
0.09,
terminalMaterial
);
addCylinderBetween(
[2.68, 0.78, 0],
[2.8, 0.78, 0],
0.55,
capacitorMaterialA,
scene,
16
);
addCylinderBetween(
[3.2, 0.78, 0],
[3.32, 0.78, 0],
0.55,
capacitorMaterialB,
scene,
16
);
const chargeGlowMaterial = new THREE.MeshBasicMaterial({
color: 0x58e8ff,
transparent: true,
opacity: 0,
depthWrite: false
});
const chargeGlow = addMesh(
new THREE.CylinderGeometry(0.31, 0.31, 0.39, 12),
chargeGlowMaterial
);
chargeGlow.rotation.z = Math.PI / 2;
chargeGlow.position.set(3, 0.78, 0);
chargeGlow.castShadow = false;
// -------------------------------------------------------------------------
// Switch
// -------------------------------------------------------------------------
const switchBase = addMesh(
new THREE.BoxGeometry(2.55, 0.12, 0.56),
darkPlastic
);
switchBase.position.set(0, 0.65, 1.5);
const contactMaterial = standardMaterial(0xd7e4e8, {
roughness: 0.22,
metalness: 0.85
});
[-1.2, 1.2].forEach((x) => {
const contact = addMesh(
new THREE.SphereGeometry(0.14, 10, 7),
contactMaterial
);
contact.position.set(x, 0.9, 1.5);
});
const pivot = addMesh(
new THREE.CylinderGeometry(0.17, 0.17, 0.26, 10),
contactMaterial
);
pivot.position.set(-1.2, 0.91, 1.5);
const switchLever = new THREE.Group();
switchLever.position.set(-1.2, 0.95, 1.5);
scene.add(switchLever);
const leverBeam = addMesh(
new THREE.BoxGeometry(2.25, 0.13, 0.17),
switchMaterial,
switchLever
);
leverBeam.position.x = 1.125;
const leverHandle = addMesh(
new THREE.SphereGeometry(0.2, 10, 7),
switchMaterial,
switchLever
);
leverHandle.position.set(2.18, 0, 0);
const switchHitMeshes = [leverBeam, leverHandle];
// -------------------------------------------------------------------------
// Billboard labels
// -------------------------------------------------------------------------
function roundedRect(context, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
context.beginPath();
context.moveTo(x + r, y);
context.arcTo(x + width, y, x + width, y + height, r);
context.arcTo(x + width, y + height, x, y + height, r);
context.arcTo(x, y + height, x, y, r);
context.arcTo(x, y, x + width, y, r);
context.closePath();
}
function createLabel(text, accent = "#55e7ff") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(2.45, 0.6125, 1);
sprite.renderOrder = 30;
sprite.userData = {
canvas,
context: canvas.getContext("2d"),
texture,
accent,
text: ""
};
updateLabel(sprite, text);
return sprite;
}
function updateLabel(sprite, text) {
if (sprite.userData.text === text) return;
const { canvas, context, texture, accent } = sprite.userData;
sprite.userData.text = text;
context.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(
context,
5,
9,
canvas.width - 10,
canvas.height - 18,
24
);
context.fillStyle = "rgba(5, 17, 29, 0.9)";
context.fill();
context.lineWidth = 3;
context.strokeStyle = accent;
context.globalAlpha = 0.68;
context.stroke();
context.globalAlpha = 1;
let fontSize = 42;
context.font = `700 ${fontSize}px system-ui, sans-serif`;
while (
context.measureText(text).width > 474 &&
fontSize > 23
) {
fontSize -= 1;
context.font = `700 ${fontSize}px system-ui, sans-serif`;
}
context.fillStyle = "#eaf8ff";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2, canvas.height / 2 + 1);
texture.needsUpdate = true;
}
const sourceLabel = createLabel("5 V SOURCE", "#ffb45c");
sourceLabel.position.set(-3, 1.82, 0);
scene.add(sourceLabel);
const resistorLabel = createLabel("R = 2.20 kΩ", "#ffb45c");
resistorLabel.position.set(0, 1.58, -1.5);
scene.add(resistorLabel);
const capacitorLabel = createLabel("C = 100 µF", "#55e7ff");
capacitorLabel.position.set(3, 1.62, 0);
scene.add(capacitorLabel);
const voltageLabel = createLabel("V_C = 0.00 V", "#60efba");
voltageLabel.position.set(3, 2.16, 0);
scene.add(voltageLabel);
const switchLabel = createLabel("SWITCH", "#ff657a");
switchLabel.position.set(0, 1.58, 1.5);
scene.add(switchLabel);
// -------------------------------------------------------------------------
// Current particles
// -------------------------------------------------------------------------
const currentPath = [
[-2.2, 0.98, 0],
[-1.2, 0.98, 0],
[-1.2, 0.98, -1.5],
[1.2, 0.98, -1.5],
[2.2, 0.98, -1.5],
[2.2, 0.98, 0],
[3.8, 0.98, 0],
[4.35, 0.98, 0],
[4.35, 0.98, 1.5],
[1.2, 0.98, 1.5],
[-1.2, 0.98, 1.5],
[-4.35, 0.98, 1.5],
[-4.35, 0.98, 0],
[-3.8, 0.98, 0],
[-2.2, 0.98, 0]
].map((point) => new THREE.Vector3(...point));
const cumulativeLengths = [0];
for (let i = 1; i < currentPath.length; i++) {
cumulativeLengths.push(
cumulativeLengths[i - 1] +
currentPath[i].distanceTo(currentPath[i - 1])
);
}
const pathLength = cumulativeLengths[cumulativeLengths.length - 1];
function sampleCurrentPath(fraction) {
const distance = ((fraction % 1) + 1) % 1 * pathLength;
for (let i = 0; i < currentPath.length - 1; i++) {
if (distance <= cumulativeLengths[i + 1]) {
const segmentLength =
cumulativeLengths[i + 1] - cumulativeLengths[i];
const local = segmentLength === 0
? 0
: (distance - cumulativeLengths[i]) / segmentLength;
return currentPath[i].clone().lerp(
currentPath[i + 1],
THREE.MathUtils.clamp(local, 0, 1)
);
}
}
return currentPath[0].clone();
}
const particleGroup = new THREE.Group();
scene.add(particleGroup);
const particleGeometry = new THREE.IcosahedronGeometry(0.095, 0);
const particleMaterial = new THREE.MeshBasicMaterial({
color: 0xffd166
});
const particles = [];
for (let i = 0; i < 18; i++) {
const particle = new THREE.Mesh(particleGeometry, particleMaterial);
particleGroup.add(particle);
particles.push(particle);
}
let flowOffset = 0;
// -------------------------------------------------------------------------
// Plot rendering
// -------------------------------------------------------------------------
function drawPlot(voltage) {
const rect = plotCanvas.getBoundingClientRect();
const width = Math.max(100, rect.width);
const height = Math.max(100, rect.height);
const dpr = Math.min(window.devicePixelRatio, 2);
const targetWidth = Math.round(width * dpr);
const targetHeight = Math.round(height * dpr);
if (
plotCanvas.width !== targetWidth ||
plotCanvas.height !== targetHeight
) {
plotCanvas.width = targetWidth;
plotCanvas.height = targetHeight;
}
const context = plotContext;
context.setTransform(dpr, 0, 0, dpr, 0, 0);
context.clearRect(0, 0, width, height);
const margin = {
left: 49,
right: 15,
top: 20,
bottom: 37
};
const plotWidth = width - margin.left - margin.right;
const plotHeight = height - margin.top - margin.bottom;
const xToPixel = (time) =>
margin.left + (time / maxTime) * plotWidth;
const yToPixel = (value) =>
margin.top + plotHeight - (value / Vs) * plotHeight;
context.fillStyle = "#07131e";
roundedRect(context, 0, 0, width, height, 11);
context.fill();
// Grid.
context.lineWidth = 1;
for (let i = 0; i <= 5; i++) {
const x = margin.left + (i / 5) * plotWidth;
const isTau = i === 1;
context.beginPath();
context.setLineDash(isTau ? [4, 4] : []);
context.strokeStyle = isTau
? "rgba(255, 180, 92, 0.42)"
: "rgba(109, 158, 180, 0.13)";
context.moveTo(x, margin.top);
context.lineTo(x, margin.top + plotHeight);
context.stroke();
context.setLineDash([]);
context.fillStyle = isTau ? "#ffb45c" : "#7795a8";
context.font = "10px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "top";
context.fillText(
i === 0 ? "0" : `${i}τ`,
x,
margin.top + plotHeight + 9
);
}
for (let i = 0; i <= 4; i++) {
const fraction = i / 4;
const y = margin.top + plotHeight - fraction * plotHeight;
context.beginPath();
context.strokeStyle = "rgba(109, 158, 180, 0.13)";
context.moveTo(margin.left, y);
context.lineTo(margin.left + plotWidth, y);
context.stroke();
context.fillStyle = "#7795a8";
context.font = "9px system-ui, sans-serif";
context.textAlign = "right";
context.textBaseline = "middle";
context.fillText(
`${Math.round(fraction * 100)}%`,
margin.left - 7,
y
);
}
// The 63.2% reference.
const tauY = yToPixel(Vs * 0.632);
context.beginPath();
context.setLineDash([3, 5]);
context.strokeStyle = "rgba(255, 180, 92, 0.48)";
context.lineWidth = 1;
context.moveTo(margin.left, tauY);
context.lineTo(margin.left + plotWidth, tauY);
context.stroke();
context.setLineDash([]);
context.fillStyle = "#ffb45c";
context.font = "9px system-ui, sans-serif";
context.textAlign = "right";
context.textBaseline = "bottom";
context.fillText(
"63.2%",
margin.left + plotWidth - 2,
tauY - 3
);
function drawCurve(endTime, color, lineWidth, dashed = false) {
context.beginPath();
context.setLineDash(dashed ? [3, 5] : []);
context.strokeStyle = color;
context.lineWidth = lineWidth;
context.lineJoin = "round";
context.lineCap = "round";
const steps = 220;
for (let i = 0; i <= steps; i++) {
const time = endTime * (i / steps);
const value = analyticVoltage(time);
const x = xToPixel(time);
const y = yToPixel(value);
if (i === 0) context.moveTo(x, y);
else context.lineTo(x, y);
}
context.stroke();
context.setLineDash([]);
}
// Complete analytic response.
drawCurve(maxTime, "rgba(85, 231, 255, 0.27)", 2, true);
// Bright portion reached by the synchronized simulation.
const reachedTime = Math.min(chargeTime, maxTime);
drawCurve(reachedTime, "#55e7ff", 3);
// Current time cursor.
const cursorX = xToPixel(reachedTime);
const cursorY = yToPixel(voltage);
context.beginPath();
context.setLineDash([3, 4]);
context.strokeStyle = "rgba(255, 255, 255, 0.28)";
context.lineWidth = 1;
context.moveTo(cursorX, margin.top);
context.lineTo(cursorX, margin.top + plotHeight);
context.stroke();
context.setLineDash([]);
context.beginPath();
context.fillStyle = "#07131e";
context.strokeStyle = "#ffffff";
context.lineWidth = 2.5;
context.arc(cursorX, cursorY, 5.5, 0, Math.PI * 2);
context.fill();
context.stroke();
const timeLabel = `t = ${formatDuration(chargeTime)}`;
context.font = "600 10px system-ui, sans-serif";
const labelWidth = context.measureText(timeLabel).width + 14;
let labelX = cursorX + 9;
let labelY = margin.top + 4;
if (labelX + labelWidth > width - 4) {
labelX = cursorX - labelWidth - 9;
}
context.fillStyle = "rgba(5, 17, 29, 0.92)";
context.strokeStyle = "rgba(85, 231, 255, 0.5)";
context.lineWidth = 1;
roundedRect(context, labelX, labelY, labelWidth, 22, 6);
context.fill();
context.stroke();
context.fillStyle = "#dffaff";
context.textAlign = "left";
context.textBaseline = "middle";
context.fillText(timeLabel, labelX + 7, labelY + 11);
// Axis titles.
context.fillStyle = "#7897aa";
context.font = "9px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "bottom";
context.fillText(
"charging time",
margin.left + plotWidth / 2,
height - 2
);
context.save();
context.translate(10, margin.top + plotHeight / 2);
context.rotate(-Math.PI / 2);
context.fillText("V_C", 0, 0);
context.restore();
}
// -------------------------------------------------------------------------
// UI and simulation controls
// -------------------------------------------------------------------------
function refreshParameters() {
tau = R * Cmicro * 1e-6;
maxTime = 5 * tau;
$("rOut").textContent = formatResistance(R);
$("cOut").textContent = formatCapacitance(Cmicro);
$("vOut").textContent = `${Vs.toFixed(1)} V`;
$("tauValue").textContent = formatDuration(tau);
$("tauEquation").textContent =
`${formatResistance(R)} × ${formatCapacitance(Cmicro)} = ${formatDuration(tau)}`;
$("atTau").textContent =
`At τ: ${(Vs * 0.632).toFixed(2)} V (63.2% of ${Vs.toFixed(1)} V)`;
updateLabel(sourceLabel, `${Vs.toFixed(1)} V SOURCE`);
updateLabel(resistorLabel, `R = ${formatResistance(R)}`);
updateLabel(capacitorLabel, `C = ${formatCapacitance(Cmicro)}`);
}
function resetSimulation() {
charging = false;
paused = false;
chargeTime = 0;
flowOffset = 0;
}
function toggleSwitch() {
charging = !charging;
paused = false;
if (charging && chargeTime >= maxTime) {
chargeTime = 0;
}
}
switchButton.addEventListener("click", toggleSwitch);
pauseButton.addEventListener("click", () => {
paused = !paused;
});
$("resetButton").addEventListener("click", resetSimulation);
$("rSlider").addEventListener("input", (event) => {
R = Number(event.target.value);
refreshParameters();
resetSimulation();
});
$("cSlider").addEventListener("input", (event) => {
Cmicro = Number(event.target.value);
refreshParameters();
resetSimulation();
});
$("vSlider").addEventListener("input", (event) => {
Vs = Number(event.target.value);
refreshParameters();
resetSimulation();
});
$("speedSelect").addEventListener("change", (event) => {
speed = Number(event.target.value);
});
function updateUI(voltage, current) {
switchButton.classList.toggle("is-closed", charging);
$("switchAction").textContent = charging
? "CLOSED — click to open"
: "OPEN — click to close";
$("statusDot").classList.toggle("closed", charging);
if (paused) {
$("statusText").textContent = "PAUSED";
} else if (charging) {
$("statusText").textContent =
chargeTime >= maxTime ? "5τ REACHED" : "SWITCH CLOSED";
} else {
$("statusText").textContent = "SWITCH OPEN";
}
$("liveClock").textContent = `t = ${formatDuration(chargeTime)}`;
$("vcReadout").textContent = `${voltage.toFixed(2)} V`;
$("currentReadout").textContent = formatCurrent(current);
$("timeReadout").textContent = formatDuration(chargeTime);
pauseButton.textContent = paused ? "RESUME" : "PAUSE";
}
// -------------------------------------------------------------------------
// Direct mouse/touch camera and 3D switch interaction
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let dragging = false;
let movedDistance = 0;
let lastPointerX = 0;
let lastPointerY = 0;
function pointerHitsSwitch(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
return raycaster.intersectObjects(switchHitMeshes, false).length > 0;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
movedDistance = 0;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) {
renderer.domElement.style.cursor = pointerHitsSwitch(event)
? "pointer"
: "grab";
return;
}
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
movedDistance += Math.abs(dx) + Math.abs(dy);
cameraYaw -= dx * 0.006;
cameraPitch = THREE.MathUtils.clamp(
cameraPitch + dy * 0.005,
0.24,
1.28
);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
updateCamera();
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (!dragging) return;
const wasClick = movedDistance < 7;
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
if (wasClick && pointerHitsSwitch(event)) {
toggleSwitch();
}
renderer.domElement.style.cursor = "grab";
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius + event.deltaY * 0.008,
7.2,
19
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.style.cursor = "grab";
// -------------------------------------------------------------------------
// Resize and animation
// -------------------------------------------------------------------------
function onResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
}
window.addEventListener("resize", onResize);
refreshParameters();
resetSimulation();
let lastTime = performance.now();
let lastLabelTime = 0;
let switchBlend = 0;
function animate(now) {
requestAnimationFrame(animate);
const dt = Math.min((now - lastTime) / 1000, 0.05);
lastTime = now;
if (charging && !paused) {
chargeTime = Math.min(maxTime, chargeTime + dt * speed);
}
const voltage = analyticVoltage(chargeTime);
const current = analyticCurrent(chargeTime);
const voltageFraction = Vs > 0 ? voltage / Vs : 0;
// Animate the physical switch lever.
const switchTarget = charging ? 1 : 0;
switchBlend += (switchTarget - switchBlend) * (1 - Math.exp(-dt * 12));
switchLever.rotation.y = (1 - switchBlend) * 0.82;
switchMaterial.emissiveIntensity = 0.22 + switchBlend * 0.3;
resistorMaterial.emissiveIntensity = 0.12 + voltageFraction * 0.32;
wireMaterial.emissiveIntensity = 0.22 + voltageFraction * 0.42;
capacitorMaterialA.emissiveIntensity = 0.15 + voltageFraction * 1.15;
capacitorMaterialB.emissiveIntensity = 0.15 + voltageFraction * 1.15;
chargeGlowMaterial.opacity = 0.015 + voltageFraction * 0.19;
// Current particles slow according to I(t) = I0 exp(-t/tau).
particleGroup.visible = charging && !paused && chargeTime < maxTime;
if (particleGroup.visible) {
const decay = Math.exp(-chargeTime / tau);
flowOffset += dt * speed * 0.23 * decay;
particles.forEach((particle, index) => {
const fraction = (index / particles.length + flowOffset) % 1;
particle.position.copy(sampleCurrentPath(fraction));
});
}
if (now - lastLabelTime > 70) {
updateLabel(voltageLabel, `V_C = ${voltage.toFixed(2)} V`);
lastLabelTime = now;
}
updateUI(voltage, current);
drawPlot(voltage);
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```