Prompt specification
Build or customize the Three.js 3D scene "RC parameter counterfactual explorer" 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 parameter counterfactual explorer
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/rc-parameter-counterfactual-explorer-x1664
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows charging and discharging in an RC circuit. Let users change resistance and capacitance independently in a virtual circuit; update time constant, current, and voltage while preserving physically consistent initial conditions at reset. Low-poly.
Working Three.js Starter (rc-parameter-counterfactual-explorer-x1664):
```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 {
--ink: #172a2c;
--muted: #617274;
--paper: rgba(250, 247, 238, 0.9);
--paper-strong: rgba(255, 253, 247, 0.96);
--line: rgba(23, 42, 44, 0.12);
--accent: #ed8748;
--accent-soft: rgba(237, 135, 72, 0.15);
--cyan: #42bfd0;
--shadow: 0 18px 50px rgba(35, 48, 45, 0.16);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 72% 30%, #f4ead7 0, #d9d2c2 55%, #c4beae 100%);
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body.discharge {
--accent: #42bfd0;
--accent-soft: rgba(66, 191, 208, 0.15);
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#viewport,
#viewport canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
}
#viewport canvas {
display: block;
touch-action: none;
cursor: grab;
}
#viewport canvas:active {
cursor: grabbing;
}
.topbar {
position: absolute;
z-index: 5;
top: 22px;
left: 24px;
right: 24px;
display: flex;
align-items: center;
justify-content: space-between;
pointer-events: none;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
}
.brand-mark {
position: relative;
width: 44px;
height: 44px;
border: 2px solid var(--ink);
border-radius: 13px;
background: rgba(255, 253, 247, 0.72);
box-shadow: 0 8px 24px rgba(35, 48, 45, 0.1);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
top: 10px;
bottom: 10px;
width: 5px;
border-radius: 4px;
background: var(--ink);
}
.brand-mark::before {
left: 12px;
transform: rotate(19deg);
}
.brand-mark::after {
right: 12px;
transform: rotate(-19deg);
}
.eyebrow {
margin: 0 0 2px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(20px, 2.1vw, 30px);
line-height: 1;
letter-spacing: -0.04em;
}
.status-pill {
display: flex;
align-items: center;
gap: 9px;
padding: 10px 14px;
border: 1px solid rgba(23, 42, 44, 0.11);
border-radius: 999px;
background: rgba(255, 253, 247, 0.76);
box-shadow: 0 8px 24px rgba(35, 48, 45, 0.08);
color: var(--muted);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 0 4px var(--accent-soft);
}
.panel {
position: absolute;
z-index: 4;
border: 1px solid rgba(23, 42, 44, 0.11);
border-radius: 22px;
background: var(--paper);
box-shadow: var(--shadow);
backdrop-filter: blur(16px) saturate(1.1);
}
.controls {
top: 100px;
left: 24px;
width: 316px;
padding: 20px;
}
.metrics {
top: 100px;
right: 24px;
width: 292px;
padding: 18px;
}
.panel-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 16px;
}
.panel-heading h2 {
margin: 0;
font-size: 16px;
letter-spacing: -0.025em;
}
.panel-heading p {
margin: 4px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.mini-badge {
flex: 0 0 auto;
padding: 5px 8px;
border-radius: 8px;
background: var(--accent-soft);
color: var(--accent);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9px;
font-weight: 900;
letter-spacing: 0.08em;
}
.mode-switch {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 5px;
margin-bottom: 20px;
padding: 5px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(23, 42, 44, 0.045);
}
.mode-switch button {
min-height: 39px;
border: 0;
border-radius: 10px;
background: transparent;
color: var(--muted);
cursor: pointer;
font-size: 11px;
font-weight: 850;
letter-spacing: 0.055em;
text-transform: uppercase;
transition:
background 160ms ease,
color 160ms ease,
box-shadow 160ms ease;
}
.mode-switch button.active {
background: var(--paper-strong);
color: var(--ink);
box-shadow: 0 4px 14px rgba(35, 48, 45, 0.1);
}
.control {
margin-top: 18px;
}
.control:first-of-type {
margin-top: 0;
}
.control-label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
}
.control-label label {
font-size: 12px;
font-weight: 800;
}
.number-wrap {
display: flex;
align-items: baseline;
gap: 5px;
min-width: 114px;
padding: 7px 9px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.5);
}
.number-wrap input {
width: 80px;
padding: 0;
border: 0;
outline: 0;
background: transparent;
color: var(--ink);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 12px;
font-weight: 800;
text-align: right;
}
.number-wrap span {
color: var(--muted);
font-size: 10px;
font-weight: 800;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 3px 0 0;
appearance: none;
border-radius: 99px;
outline: none;
background:
linear-gradient(
to right,
var(--accent) 0%,
var(--accent) var(--range-progress, 50%),
rgba(23, 42, 44, 0.12) var(--range-progress, 50%),
rgba(23, 42, 44, 0.12) 100%
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 17px;
height: 17px;
appearance: none;
border: 4px solid var(--paper-strong);
border-radius: 50%;
background: var(--accent);
box-shadow: 0 2px 8px rgba(23, 42, 44, 0.25);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 4px solid var(--paper-strong);
border-radius: 50%;
background: var(--accent);
box-shadow: 0 2px 8px rgba(23, 42, 44, 0.25);
}
.derived {
display: flex;
align-items: center;
justify-content: space-between;
margin: 20px 0 16px;
padding: 13px 14px;
border: 1px solid rgba(237, 135, 72, 0.18);
border-radius: 13px;
background: var(--accent-soft);
}
.derived span {
color: var(--muted);
font-size: 11px;
font-weight: 750;
}
.derived strong {
color: var(--accent);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 17px;
}
.formula {
min-height: 55px;
margin-bottom: 15px;
padding: 12px 13px;
border-radius: 12px;
background: rgba(23, 42, 44, 0.055);
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
line-height: 1.8;
}
.formula strong {
color: var(--ink);
font-weight: 800;
}
.initial-state {
min-height: 42px;
margin: 0 0 16px;
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
.initial-state strong {
color: var(--ink);
}
.button-row {
display: grid;
grid-template-columns: 1.35fr 1fr;
gap: 9px;
}
.button-row button {
min-height: 43px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.56);
cursor: pointer;
font-size: 11px;
font-weight: 850;
letter-spacing: 0.04em;
text-transform: uppercase;
transition:
transform 140ms ease,
background 140ms ease;
}
.button-row button:hover {
transform: translateY(-1px);
background: rgba(255, 255, 255, 0.86);
}
.button-row #runButton {
border-color: transparent;
background: var(--ink);
color: #fffdf7;
}
.button-row #runButton:hover {
background: #244043;
}
.metric-primary {
padding: 4px 3px 16px;
border-bottom: 1px solid var(--line);
}
.metric-primary .caption {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric-primary .big-number {
display: block;
color: var(--accent);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 32px;
font-weight: 850;
letter-spacing: -0.05em;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
}
.metric {
min-height: 93px;
padding: 15px 8px 12px;
border-bottom: 1px solid var(--line);
}
.metric:nth-child(odd) {
border-right: 1px solid var(--line);
padding-left: 3px;
}
.metric:nth-child(even) {
padding-right: 3px;
}
.metric .caption {
display: block;
margin-bottom: 6px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.metric .value {
display: block;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 18px;
font-weight: 850;
letter-spacing: -0.04em;
}
.meter {
height: 4px;
margin-top: 9px;
overflow: hidden;
border-radius: 99px;
background: rgba(23, 42, 44, 0.1);
}
.meter > div {
width: 0;
height: 100%;
border-radius: inherit;
background: var(--accent);
transition: width 70ms linear;
}
.current-meter > div {
background: var(--cyan);
}
.metric-footer {
display: flex;
justify-content: space-between;
gap: 12px;
padding: 13px 3px 1px;
color: var(--muted);
font-size: 9px;
line-height: 1.45;
}
.metric-footer strong {
color: var(--ink);
}
.scene-hint {
position: absolute;
z-index: 3;
right: 24px;
bottom: 22px;
display: flex;
align-items: center;
gap: 9px;
padding: 9px 12px;
border: 1px solid rgba(23, 42, 44, 0.1);
border-radius: 999px;
background: rgba(255, 253, 247, 0.64);
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.035em;
pointer-events: none;
}
.scene-hint span {
color: var(--ink);
font-size: 15px;
}
.toast {
position: absolute;
z-index: 10;
left: 50%;
bottom: 25px;
max-width: calc(100vw - 32px);
padding: 11px 16px;
border-radius: 999px;
background: rgba(23, 42, 44, 0.92);
color: #fffdf7;
box-shadow: var(--shadow);
font-size: 11px;
font-weight: 700;
opacity: 0;
pointer-events: none;
transform: translate(-50%, 14px);
transition:
opacity 180ms ease,
transform 180ms ease;
}
.toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 850px) {
.topbar {
top: 14px;
left: 14px;
right: 14px;
}
.controls {
top: auto;
left: 14px;
right: 14px;
bottom: 14px;
width: auto;
max-height: 48vh;
overflow: auto;
}
.metrics {
top: 78px;
right: 14px;
width: 252px;
}
.scene-hint {
display: none;
}
.metric-primary {
padding-bottom: 12px;
}
.metric-primary .big-number {
font-size: 27px;
}
.metric {
min-height: 80px;
padding-top: 11px;
}
}
@media (max-width: 560px) {
.brand-mark {
width: 38px;
height: 38px;
}
.brand-mark::before {
left: 10px;
}
.brand-mark::after {
right: 10px;
}
.eyebrow {
font-size: 8px;
}
.status-pill {
padding: 8px 10px;
font-size: 8px;
}
.metrics {
top: 68px;
left: 14px;
right: 14px;
width: auto;
padding: 13px;
}
.metric-grid {
grid-template-columns: repeat(4, 1fr);
}
.metric {
min-height: 72px;
border-right: 1px solid var(--line);
}
.metric:nth-child(even) {
border-right: 0;
}
.metric .value {
font-size: 14px;
}
.metric-footer {
display: none;
}
.controls {
max-height: 52vh;
padding: 17px;
}
}
</style>
</head>
<body>
<main id="viewport" aria-label="Interactive three-dimensional RC circuit"></main>
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<p class="eyebrow">Interactive electronics</p>
<h1>RC Circuit Lab</h1>
</div>
</div>
<div class="status-pill">
<span class="status-dot"></span>
<span id="statusText">Charging · Running</span>
</div>
</header>
<aside class="panel controls" aria-label="Circuit controls">
<div class="panel-heading">
<div>
<h2>Component controls</h2>
<p>Change R and C independently.</p>
</div>
<span class="mini-badge">9 V SOURCE</span>
</div>
<div class="mode-switch" role="group" aria-label="Circuit mode">
<button class="active" data-mode="charge" aria-pressed="true">Charge</button>
<button data-mode="discharge" aria-pressed="false">Discharge</button>
</div>
<div class="control">
<div class="control-label">
<label for="rNumber">Resistance</label>
<div class="number-wrap">
<input id="rNumber" type="number" min="10" max="100000" step="10" value="2200">
<span>Ω</span>
</div>
</div>
<input id="rSlider" type="range" min="0" max="1000" step="1" value="673" aria-label="Resistance slider">
</div>
<div class="control">
<div class="control-label">
<label for="cNumber">Capacitance</label>
<div class="number-wrap">
<input id="cNumber" type="number" min="0.1" max="10000" step="0.1" value="470">
<span>µF</span>
</div>
</div>
<input id="cSlider" type="range" min="0" max="1000" step="1" value="767" aria-label="Capacitance slider">
</div>
<div class="derived">
<span>Time constant · τ = RC</span>
<strong id="tauInline">1.03 s</strong>
</div>
<div class="formula" id="formula"></div>
<p class="initial-state" id="initialState"></p>
<div class="button-row">
<button id="runButton" type="button">Pause</button>
<button id="resetButton" type="button">Reset</button>
</div>
</aside>
<aside class="panel metrics" aria-label="Live circuit measurements">
<div class="metric-primary">
<span class="caption">Time constant</span>
<strong class="big-number" id="tauMetric">1.03 s</strong>
</div>
<div class="metric-grid">
<div class="metric">
<span class="caption">Capacitor voltage</span>
<strong class="value" id="voltageMetric">0.00 V</strong>
<div class="meter"><div id="voltageFill"></div></div>
</div>
<div class="metric">
<span class="caption">Signed current</span>
<strong class="value" id="currentMetric">+4.09 mA</strong>
<div class="meter current-meter"><div id="currentFill"></div></div>
</div>
<div class="metric">
<span class="caption">Elapsed / τ</span>
<strong class="value" id="phaseMetric">0.00 τ</strong>
</div>
<div class="metric">
<span class="caption">Stored charge</span>
<strong class="value" id="chargeMetric">0 µC</strong>
</div>
</div>
<div class="metric-footer">
<span>Positive current enters the capacitor's <strong>+</strong> terminal.</span>
<span>1 τ ≈ 4 s</span>
</div>
</aside>
<div class="scene-hint">
<span>↔</span>
Drag to orbit · Scroll to zoom · Double-click to frame
</div>
<div class="toast" id="toast" role="status" aria-live="polite"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// State and physics
// -------------------------------------------------------------------------
const SOURCE_VOLTAGE = 9;
const MAX_PHASE = 12;
const state = {
mode: "charge",
running: true,
resistance: 2200,
capacitance: 470e-6,
phase: 0,
voltage: 0,
current: SOURCE_VOLTAGE / 2200,
charge: 0
};
const $ = (id) => document.getElementById(id);
const ui = {
body: document.body,
status: $("statusText"),
run: $("runButton"),
reset: $("resetButton"),
tauInline: $("tauInline"),
tauMetric: $("tauMetric"),
voltage: $("voltageMetric"),
current: $("currentMetric"),
phase: $("phaseMetric"),
charge: $("chargeMetric"),
voltageFill: $("voltageFill"),
currentFill: $("currentFill"),
formula: $("formula"),
initialState: $("initialState"),
rNumber: $("rNumber"),
rSlider: $("rSlider"),
cNumber: $("cNumber"),
cSlider: $("cSlider"),
toast: $("toast")
};
const modeButtons = [...document.querySelectorAll("[data-mode]")];
let dotTravel = 0;
let toastTimer;
function clamp(value, min, max) {
return Math.min(max, Math.max(min, value));
}
function formatTimeConstant(seconds) {
if (seconds >= 1000) return `${(seconds / 1000).toFixed(2)} ks`;
if (seconds >= 1) return `${seconds.toFixed(2)} s`;
if (seconds >= 0.001) return `${(seconds * 1000).toFixed(2)} ms`;
return `${(seconds * 1e6).toFixed(2)} µs`;
}
function formatCurrent(amps) {
const absolute = Math.abs(amps);
const sign = amps >= 0 ? "+" : "−";
if (absolute >= 1) return `${sign}${absolute.toFixed(2)} A`;
if (absolute >= 0.001) return `${sign}${(absolute * 1000).toFixed(2)} mA`;
return `${sign}${(absolute * 1e6).toFixed(2)} µA`;
}
function formatCharge(coulombs) {
if (coulombs >= 0.001) return `${(coulombs * 1000).toFixed(2)} mC`;
if (coulombs >= 1e-6) return `${(coulombs * 1e6).toFixed(2)} µC`;
return `${(coulombs * 1e9).toFixed(2)} nC`;
}
function showToast(message) {
clearTimeout(toastTimer);
ui.toast.textContent = message;
ui.toast.classList.add("visible");
toastTimer = setTimeout(() => ui.toast.classList.remove("visible"), 2300);
}
function updateModeDetails() {
const charging = state.mode === "charge";
ui.body.classList.toggle("discharge", !charging);
modeButtons.forEach((button) => {
const active = button.dataset.mode === state.mode;
button.classList.toggle("active", active);
button.setAttribute("aria-pressed", String(active));
});
ui.formula.innerHTML = charging
? `
<strong>Charge</strong><br>
V<sub>C</sub> = V<sub>S</sub>(1 − e<sup>−t/τ</sup>)<br>
I(t) = (V<sub>S</sub>/R)e<sup>−t/τ</sup>
`
: `
<strong>Discharge</strong><br>
V<sub>C</sub> = V<sub>S</sub>e<sup>−t/τ</sup><br>
I(t) = −(V<sub>S</sub>/R)e<sup>−t/τ</sup>
`;
ui.initialState.innerHTML = charging
? `<strong>Reset state:</strong> discharged capacitor,
V<sub>C</sub>(0) = 0 V and I(0) = +V<sub>S</sub>/R.`
: `<strong>Reset state:</strong> pre-charged capacitor,
V<sub>C</sub>(0) = V<sub>S</sub> and I(0) = −V<sub>S</sub>/R.`;
}
function updatePhysics() {
const tau = state.resistance * state.capacitance;
const decay = Math.exp(-state.phase);
if (state.mode === "charge") {
state.voltage = SOURCE_VOLTAGE * (1 - decay);
state.current = (SOURCE_VOLTAGE / state.resistance) * decay;
} else {
state.voltage = SOURCE_VOLTAGE * decay;
state.current = -(SOURCE_VOLTAGE / state.resistance) * decay;
}
state.charge = state.capacitance * state.voltage;
}
function updateUI() {
const tau = state.resistance * state.capacitance;
const voltageRatio = clamp(state.voltage / SOURCE_VOLTAGE, 0, 1);
const currentRatio = clamp(
Math.abs(state.current) / (SOURCE_VOLTAGE / state.resistance),
0,
1
);
ui.tauInline.textContent = formatTimeConstant(tau);
ui.tauMetric.textContent = formatTimeConstant(tau);
ui.voltage.textContent = `${state.voltage.toFixed(2)} V`;
ui.current.textContent = formatCurrent(state.current);
ui.phase.textContent = `${state.phase.toFixed(2)} τ`;
ui.charge.textContent = formatCharge(state.charge);
ui.voltageFill.style.width = `${voltageRatio * 100}%`;
ui.currentFill.style.width = `${currentRatio * 100}%`;
const modeName = state.mode === "charge" ? "Charging" : "Discharging";
ui.status.textContent = `${modeName} · ${state.running ? "Running" : "Paused"}`;
ui.run.textContent = state.running ? "Pause" : "Run";
}
function resetSimulation(message = "") {
state.phase = 0;
dotTravel = 0;
updatePhysics();
updateModeDetails();
updateUI();
updateVisuals();
if (message) showToast(message);
}
function setMode(mode) {
state.mode = mode;
state.running = false;
resetSimulation(
mode === "charge"
? "Charging selected · capacitor reset to 0 V"
: "Discharging selected · capacitor pre-charged to 9 V"
);
}
function parameterChanged(message = true) {
// Resetting avoids an artificial jump in stored energy when C changes.
state.running = false;
resetSimulation(
message
? "R or C changed · returned to a valid t = 0 state"
: ""
);
}
function updateRangeProgress(input) {
const percent = (Number(input.value) - Number(input.min)) /
(Number(input.max) - Number(input.min)) * 100;
input.style.setProperty("--range-progress", `${percent}%`);
}
function resistanceFromSlider(value) {
return Math.round(10 ** (1 + (value / 1000) * 4));
}
function sliderFromResistance(resistance) {
return Math.round(
((Math.log10(clamp(resistance, 10, 100000)) - 1) / 4) * 1000
);
}
function capacitanceFromSlider(value) {
return 10 ** (-1 + (value / 1000) * 4);
}
function sliderFromCapacitance(capacitance) {
return Math.round(
((Math.log10(clamp(capacitance, 0.1, 10000)) + 1) / 4) * 1000
);
}
function applyResistance(value, announce = true) {
state.resistance = clamp(value, 10, 100000);
ui.rNumber.value = Math.round(state.resistance);
ui.rSlider.value = sliderFromResistance(state.resistance);
updateRangeProgress(ui.rSlider);
parameterChanged(announce);
}
function applyCapacitance(value, announce = true) {
state.capacitance = clamp(value, 0.1, 10000) * 1e-6;
ui.cNumber.value = Number((state.capacitance * 1e6).toFixed(3));
ui.cSlider.value = sliderFromCapacitance(state.capacitance * 1e6);
updateRangeProgress(ui.cSlider);
parameterChanged(announce);
}
ui.rSlider.addEventListener("input", () => {
applyResistance(resistanceFromSlider(Number(ui.rSlider.value)), false);
});
ui.cSlider.addEventListener("input", () => {
applyCapacitance(capacitanceFromSlider(Number(ui.cSlider.value)), false);
});
ui.rSlider.addEventListener("change", () => {
showToast("R or C changed · returned to a valid t = 0 state");
});
ui.cSlider.addEventListener("change", () => {
showToast("R or C changed · returned to a valid t = 0 state");
});
ui.rNumber.addEventListener("change", () => {
const value = Number(ui.rNumber.value);
if (!Number.isFinite(value)) {
ui.rNumber.value = Math.round(state.resistance);
return;
}
applyResistance(value, true);
});
ui.cNumber.addEventListener("change", () => {
const value = Number(ui.cNumber.value);
if (!Number.isFinite(value)) {
ui.cNumber.value = Number((state.capacitance * 1e6).toFixed(3));
return;
}
applyCapacitance(value, true);
});
modeButtons.forEach((button) => {
button.addEventListener("click", () => setMode(button.dataset.mode));
});
ui.run.addEventListener("click", () => {
if (!state.running && state.phase >= MAX_PHASE) {
resetSimulation();
}
state.running = !state.running;
updateUI();
});
ui.reset.addEventListener("click", () => {
state.running = false;
resetSimulation("Reset · initial conditions restored at t = 0");
});
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const viewport = $("viewport");
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0xd8d2c4, 14, 28);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
80
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x000000, 0);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
viewport.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xfff8e8, 0x536664, 2.15);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff3d7, 3.2);
keyLight.position.set(-4, 10, 6);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -8;
keyLight.shadow.camera.right = 8;
keyLight.shadow.camera.top = 7;
keyLight.shadow.camera.bottom = -7;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 25;
keyLight.shadow.bias = -0.0008;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0xa9ddeb, 1.25);
fillLight.position.set(7, 5, -8);
scene.add(fillLight);
const warmPoint = new THREE.PointLight(0xffb66b, 9, 14, 2);
warmPoint.position.set(-2, 4, 2);
scene.add(warmPoint);
const material = (options) =>
new THREE.MeshStandardMaterial({
flatShading: true,
...options
});
const boardBaseMaterial = material({
color: 0x203b3c,
roughness: 0.82,
metalness: 0.08
});
const boardTopMaterial = material({
color: 0x315955,
roughness: 0.88,
metalness: 0.04
});
const boardEdgeMaterial = material({
color: 0xb9b29e,
roughness: 0.8,
metalness: 0.08
});
const copperMaterial = material({
color: 0xe0a357,
roughness: 0.38,
metalness: 0.7
});
const darkMetalMaterial = material({
color: 0x26383b,
roughness: 0.42,
metalness: 0.68
});
const silverMaterial = material({
color: 0xd9dfdc,
roughness: 0.31,
metalness: 0.82
});
const redMaterial = material({
color: 0xe7624b,
roughness: 0.58,
metalness: 0.12
});
const blueMaterial = material({
color: 0x3f83a7,
roughness: 0.56,
metalness: 0.12
});
const resistorMaterial = material({
color: 0xe8c99a,
roughness: 0.78,
metalness: 0.03,
emissive: 0xff6d32,
emissiveIntensity: 0
});
const capacitorMaterial = material({
color: 0x4b7e83,
roughness: 0.62,
metalness: 0.05
});
const capacitorPlateMaterial = material({
color: 0xdde4df,
roughness: 0.3,
metalness: 0.72,
emissive: 0x37bfd5,
emissiveIntensity: 0
});
const groundMaterial = material({
color: 0xc7bfae,
roughness: 1,
metalness: 0
});
function addMesh(geometry, meshMaterial, position, parent = scene) {
const mesh = new THREE.Mesh(geometry, meshMaterial);
mesh.position.copy(position);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
const ground = addMesh(
new THREE.CircleGeometry(11.5, 12),
groundMaterial,
new THREE.Vector3(0, -0.18, 0)
);
ground.rotation.x = -Math.PI / 2;
ground.castShadow = false;
addMesh(
new THREE.BoxGeometry(9.8, 0.24, 6.25),
boardEdgeMaterial,
new THREE.Vector3(0, -0.015, 0)
);
addMesh(
new THREE.BoxGeometry(9.5, 0.09, 5.95),
boardBaseMaterial,
new THREE.Vector3(0, 0.13, 0)
);
addMesh(
new THREE.BoxGeometry(9.25, 0.035, 5.7),
boardTopMaterial,
new THREE.Vector3(0, 0.195, 0)
);
// Decorative PCB traces.
const traceMaterial = new THREE.LineBasicMaterial({
color: 0x5a8077,
transparent: true,
opacity: 0.42
});
const traceVertices = [];
const traces = [
[[-4.25, 0.22, -2.45], [-3.1, 0.22, -2.45]],
[[-3.1, 0.22, -2.45], [-3.1, 0.22, -2.0]],
[[4.3, 0.22, 2.4], [3.2, 0.22, 2.4]],
[[3.2, 0.22, 2.4], [3.2, 0.22, 2.05]],
[[-4.1, 0.22, 2.35], [-3.5, 0.22, 2.35]],
[[-3.5, 0.22, 2.35], [-3.5, 0.22, 1.9]],
[[4.2, 0.22, -2.4], [3.65, 0.22, -2.4]],
[[3.65, 0.22, -2.4], [3.65, 0.22, -2.05]],
[[0.1, 0.22, 2.55], [0.1, 0.22, 1.95]],
[[-0.2, 0.22, 2.55], [-0.2, 0.22, 2.1]]
];
traces.forEach(([a, b]) => {
traceVertices.push(...a, ...b);
});
const traceGeometry = new THREE.BufferGeometry();
traceGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(traceVertices, 3)
);
scene.add(new THREE.LineSegments(traceGeometry, traceMaterial));
// Corner screws.
const screwMaterial = material({
color: 0x9ba9a2,
roughness: 0.35,
metalness: 0.8
});
[
[-4.45, -2.65],
[4.45, -2.65],
[-4.45, 2.65],
[4.45, 2.65]
].forEach(([x, z]) => {
addMesh(
new THREE.CylinderGeometry(0.13, 0.13, 0.08, 8),
screwMaterial,
new THREE.Vector3(x, 0.26, z)
);
});
const wireY = 0.31;
const axisY = new THREE.Vector3(0, 1, 0);
function cylinderBetween(a, b, radius, meshMaterial, radialSegments = 8) {
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
const geometry = new THREE.CylinderGeometry(
radius,
radius,
length,
radialSegments
);
const mesh = addMesh(
geometry,
meshMaterial,
new THREE.Vector3().addVectors(a, b).multiplyScalar(0.5)
);
mesh.quaternion.setFromUnitVectors(axisY, direction.normalize());
return mesh;
}
function addNode(position, radius = 0.115) {
return addMesh(
new THREE.SphereGeometry(radius, 8, 6),
copperMaterial,
position
);
}
const sourcePositive = new THREE.Vector3(-3.45, wireY, -0.86);
const sourceNegative = new THREE.Vector3(-3.45, wireY, 0.86);
const resistorLeft = new THREE.Vector3(-1.25, wireY, -1.65);
const resistorRight = new THREE.Vector3(1.25, wireY, -1.65);
const capacitorTop = new THREE.Vector3(3.05, wireY, -0.62);
const capacitorBottom = new THREE.Vector3(3.05, wireY, 0.62);
const externalWires = [
[sourcePositive, new THREE.Vector3(-3.45, wireY, -1.65)],
[new THREE.Vector3(-3.45, wireY, -1.65), resistorLeft],
[resistorRight, new THREE.Vector3(3.05, wireY, -1.65)],
[new THREE.Vector3(3.05, wireY, -1.65), capacitorTop],
[capacitorBottom, new THREE.Vector3(3.05, wireY, 1.65)],
[new THREE.Vector3(3.05, wireY, 1.65), new THREE.Vector3(-3.45, wireY, 1.65)],
[new THREE.Vector3(-3.45, wireY, 1.65), sourceNegative]
];
externalWires.forEach(([a, b]) => {
cylinderBetween(a, b, 0.065, copperMaterial, 6);
});
[
new THREE.Vector3(-3.45, wireY, -1.65),
new THREE.Vector3(3.05, wireY, -1.65),
new THREE.Vector3(3.05, wireY, 1.65),
new THREE.Vector3(-3.45, wireY, 1.65)
].forEach((point) => addNode(point));
// Source: stylized low-poly 9 V battery block.
const sourceGroup = new THREE.Group();
sourceGroup.position.set(-3.45, 0, 0);
scene.add(sourceGroup);
const sourceBody = addMesh(
new THREE.BoxGeometry(1.22, 1.22, 1.58),
darkMetalMaterial,
new THREE.Vector3(-3.45, 0.83, 0),
sourceGroup
);
// The helper expects a local position when a parent is supplied.
sourceBody.position.set(0, 0.83, 0);
addMesh(
new THREE.BoxGeometry(0.2, 0.82, 1.61),
material({ color: 0xe9994f, roughness: 0.68 }),
new THREE.Vector3(0, 0.83, 0),
sourceGroup
);
const positiveTerminal = addMesh(
new THREE.CylinderGeometry(0.13, 0.13, 0.26, 8),
redMaterial,
new THREE.Vector3(0, wireY, -0.88),
sourceGroup
);
positiveTerminal.rotation.x = Math.PI / 2;
const negativeTerminal = addMesh(
new THREE.CylinderGeometry(0.13, 0.13, 0.26, 8),
blueMaterial,
new THREE.Vector3(0, wireY, 0.88),
sourceGroup
);
negativeTerminal.rotation.x = Math.PI / 2;
const ledMaterial = material({
color: 0xffa24f,
roughness: 0.28,
metalness: 0.05,
emissive: 0xff6e24,
emissiveIntensity: 1.5
});
const sourceLed = addMesh(
new THREE.SphereGeometry(0.14, 8, 6),
ledMaterial,
new THREE.Vector3(0, 1.55, 0),
sourceGroup
);
// Resistor.
const resistorGroup = new THREE.Group();
resistorGroup.position.set(0, 0.42, -1.65);
scene.add(resistorGroup);
const resistorBody = addMesh(
new THREE.CylinderGeometry(0.27, 0.27, 1.45, 10),
resistorMaterial,
new THREE.Vector3(0, 0, 0),
resistorGroup
);
resistorBody.rotation.z = Math.PI / 2;
cylinderBetween(
new THREE.Vector3(-1.25, wireY, -1.65),
new THREE.Vector3(-0.72, 0.42, -1.65),
0.045,
silverMaterial,
8
);
cylinderBetween(
new THREE.Vector3(1.25, wireY, -1.65),
new THREE.Vector3(0.72, 0.42, -1.65),
0.045,
silverMaterial,
8
);
const bandColors = [0x6c382c, 0xd5a03b, 0x6c382c, 0x9e5140];
[-0.46, -0.2, 0.08, 0.34].forEach((x, index) => {
const band = addMesh(
new THREE.CylinderGeometry(0.278, 0.278, 0.075, 10),
material({ color: bandColors[index], roughness: 0.7 }),
new THREE.Vector3(x, 0, 0),
resistorGroup
);
band.rotation.z = Math.PI / 2;
});
// Capacitor: two low-poly plates with a dielectric center.
const capacitorGroup = new THREE.Group();
capacitorGroup.position.set(3.05, 0.42, 0);
scene.add(capacitorGroup);
const backPlate = addMesh(
new THREE.CylinderGeometry(0.52, 0.52, 0.1, 12),
silverMaterial,
new THREE.Vector3(0, 0, -0.19),
capacitorGroup
);
backPlate.rotation.x = Math.PI / 2;
addMesh(
new THREE.CylinderGeometry(0.46, 0.46, 0.25, 12),
capacitorMaterial,
new THREE.Vector3(0, 0, 0),
capacitorGroup
);
const frontPlate = addMesh(
new THREE.CylinderGeometry(0.52, 0.52, 0.1, 12),
capacitorPlateMaterial,
new THREE.Vector3(0, 0, 0.19),
capacitorGroup
);
frontPlate.rotation.x = Math.PI / 2;
cylinderBetween(
new THREE.Vector3(3.05, wireY, -0.62),
new THREE.Vector3(3.05, 0.42, -0.24),
0.045,
silverMaterial,
8
);
cylinderBetween(
new THREE.Vector3(3.05, wireY, 0.62),
new THREE.Vector3(3.05, 0.42, 0.24),
0.045,
silverMaterial,
8
);
const haloMaterial = new THREE.MeshBasicMaterial({
color: 0x48c4d5,
transparent: true,
opacity: 0.18
});
const capacitorHalo = addMesh(
new THREE.TorusGeometry(0.66, 0.045, 6, 20),
haloMaterial,
new THREE.Vector3(3.05, 0.42, 0.29)
);
// Moving current particles.
const routePoints = [
new THREE.Vector3(-3.45, 0.39, -0.86),
new THREE.Vector3(-3.45, 0.39, -1.65),
new THREE.Vector3(-1.25, 0.39, -1.65),
new THREE.Vector3(1.25, 0.39, -1.65),
new THREE.Vector3(3.05, 0.39, -1.65),
new THREE.Vector3(3.05, 0.39, -0.62),
new THREE.Vector3(3.05, 0.39, 0.62),
new THREE.Vector3(3.05, 0.39, 1.65),
new THREE.Vector3(-3.45, 0.39, 1.65),
new THREE.Vector3(-3.45, 0.39, 0.86),
new THREE.Vector3(-3.45, 0.39, -0.86)
];
const routeLengths = [];
const routeCumulative = [0];
let routeTotalLength = 0;
for (let i = 0; i < routePoints.length - 1; i++) {
const length = routePoints[i].distanceTo(routePoints[i + 1]);
routeLengths.push(length);
routeTotalLength += length;
routeCumulative.push(routeTotalLength);
}
function sampleRoute(fraction) {
const distance = ((fraction % 1) + 1) % 1 * routeTotalLength;
for (let i = 0; i < routeLengths.length; i++) {
if (distance <= routeCumulative[i + 1]) {
const local = (distance - routeCumulative[i]) / routeLengths[i];
return new THREE.Vector3().lerpVectors(
routePoints[i],
routePoints[i + 1],
local
);
}
}
return routePoints[0].clone();
}
const dotMaterial = new THREE.MeshBasicMaterial({
color: 0xfff2a6,
transparent: true,
opacity: 0.95
});
const currentDots = [];
for (let i = 0; i < 18; i++) {
const dot = addMesh(
new THREE.SphereGeometry(0.075, 6, 5),
dotMaterial,
routePoints[0]
);
dot.castShadow = false;
currentDots.push(dot);
}
// A small arrow identifies the conventional-current direction.
const arrowMaterial = new THREE.MeshBasicMaterial({ color: 0xffd16c });
const currentArrow = addMesh(
new THREE.ConeGeometry(0.14, 0.34, 5),
arrowMaterial,
new THREE.Vector3(2.05, 0.58, -1.65)
);
currentArrow.rotation.z = -Math.PI / 2;
// -------------------------------------------------------------------------
// Canvas-texture labels
// -------------------------------------------------------------------------
function makeLabel(text, position, options = {}) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 160;
const context = canvas.getContext("2d");
context.fillStyle = options.background || "rgba(23, 42, 44, 0.88)";
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = options.color || "#fffdf7";
context.font = `800 ${options.fontSize || 74}px ui-monospace, monospace`;
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2, canvas.height / 2 + 3);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy());
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.position.copy(position);
sprite.scale.set(options.width || 0.8, options.height || 0.25, 1);
sprite.renderOrder = 10;
scene.add(sprite);
return sprite;
}
makeLabel("9 V SOURCE", new THREE.Vector3(-3.45, 1.98, 0), {
width: 1.2,
height: 0.34,
fontSize: 62
});
makeLabel("R", new THREE.Vector3(0, 1.18, -1.65), {
width: 0.45,
height: 0.31,
fontSize: 90
});
makeLabel("C", new THREE.Vector3(3.05, 1.38, 0), {
width: 0.45,
height: 0.31,
fontSize: 90
});
makeLabel("+", new THREE.Vector3(-4.22, 0.63, -0.9), {
width: 0.32,
height: 0.25,
fontSize: 95,
background: "rgba(218, 76, 57, 0.94)"
});
makeLabel("−", new THREE.Vector3(-4.22, 0.63, 0.9), {
width: 0.32,
height: 0.25,
fontSize: 95,
background: "rgba(51, 112, 145, 0.94)"
});
makeLabel("LOW-POLY RC BENCH", new THREE.Vector3(1.6, 0.42, 2.45), {
width: 1.8,
height: 0.25,
fontSize: 46,
background: "rgba(30, 61, 59, 0.76)"
});
// -------------------------------------------------------------------------
// Visual state updates
// -------------------------------------------------------------------------
const coldPlateColor = new THREE.Color(0xdde4df);
const chargedPlateColor = new THREE.Color(0x8ddce3);
const chargeColor = new THREE.Color(0xff7b42);
const dischargeColor = new THREE.Color(0x45c7d8);
const neutralArrow = new THREE.Color(0xffd16c);
function updateVisuals() {
const voltageRatio = clamp(state.voltage / SOURCE_VOLTAGE, 0, 1);
const currentRatio = clamp(
Math.abs(state.current) / (SOURCE_VOLTAGE / state.resistance),
0,
1
);
capacitorPlateMaterial.color.lerpColors(
coldPlateColor,
chargedPlateColor,
voltageRatio
);
capacitorPlateMaterial.emissiveIntensity = voltageRatio * 0.55;
capacitorHalo.scale.setScalar(0.93 + voltageRatio * 0.2);
haloMaterial.opacity = 0.08 + voltageRatio * 0.38;
resistorMaterial.emissive.set(
state.mode === "charge" ? 0xff6d32 : 0x42c7db
);
resistorMaterial.emissiveIntensity = Math.pow(currentRatio, 0.7) * 0.75;
const ledColor = state.mode === "charge" ? 0xff6e24 : 0x294c4d;
ledMaterial.color.set(ledColor);
ledMaterial.emissive.set(ledColor);
ledMaterial.emissiveIntensity = state.mode === "charge" ? 1.5 : 0.06;
dotMaterial.opacity = 0.15 + currentRatio * 0.8;
currentDots.forEach((dot) => {
dot.visible = currentRatio > 0.002;
});
currentArrow.rotation.z =
state.mode === "charge" ? -Math.PI / 2 : Math.PI / 2;
arrowMaterial.color.copy(
state.mode === "charge" ? chargeColor : dischargeColor
);
arrowMaterial.opacity = 0.35 + currentRatio * 0.65;
}
// -------------------------------------------------------------------------
// Camera controls implemented without Three.js addons
// -------------------------------------------------------------------------
const orbit = {
azimuth: 0.56,
elevation: 0.52,
distance: 13.1,
target: new THREE.Vector3(0, 0.45, 0)
};
function updateCamera() {
const horizontal = orbit.distance * Math.cos(orbit.elevation);
camera.position.set(
orbit.target.x + horizontal * Math.sin(orbit.azimuth),
orbit.target.y + orbit.distance * Math.sin(orbit.elevation),
orbit.target.z + horizontal * Math.cos(orbit.azimuth)
);
camera.lookAt(orbit.target);
}
function resetCamera() {
orbit.azimuth = 0.56;
orbit.elevation = 0.52;
orbit.distance = 13.1;
orbit.target.set(0, 0.45, 0);
updateCamera();
}
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
let activePointerId = null;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
activePointerId = event.pointerId;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging || event.pointerId !== activePointerId) return;
const deltaX = event.clientX - lastPointerX;
const deltaY = event.clientY - lastPointerY;
orbit.azimuth -= deltaX * 0.006;
orbit.elevation = clamp(
orbit.elevation + deltaY * 0.005,
0.22,
1.24
);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
updateCamera();
});
function endDrag(event) {
if (event.pointerId !== activePointerId) return;
dragging = false;
activePointerId = null;
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.distance = clamp(
orbit.distance + event.deltaY * 0.008,
8.2,
18
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
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);
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (state.running) {
// The simulation advances in normalized RC time.
// Approximately four real seconds elapse per time constant.
state.phase = Math.min(MAX_PHASE, state.phase + delta / 4);
const currentRatio = clamp(
Math.abs(state.current) / (SOURCE_VOLTAGE / state.resistance),
0,
1
);
dotTravel += delta * 0.075 * Math.pow(currentRatio, 0.72);
if (state.phase >= MAX_PHASE) {
state.running = false;
}
}
updatePhysics();
const direction = state.mode === "charge" ? 1 : -1;
currentDots.forEach((dot, index) => {
const fraction =
(index / currentDots.length + dotTravel * direction) % 1;
dot.position.copy(sampleRoute(fraction));
});
updateUI();
updateVisuals();
renderer.render(scene, camera);
}
// Initialize controls and scene.
ui.rSlider.value = sliderFromResistance(state.resistance);
ui.cSlider.value = sliderFromCapacitance(state.capacitance * 1e6);
updateRangeProgress(ui.rSlider);
updateRangeProgress(ui.cSlider);
updateCamera();
resetSimulation();
state.running = true;
updateUI();
animate();
</script>
</body>
</html>
```