Prompt specification
Build or customize the Three.js 3D scene "Resistance-network topology playground" 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: Resistance-network topology playground
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/resistance-network-topology-playground-x1668
Scene Description Prompt:
Rewire low-poly resistors between series and parallel, calculating ideal equivalent resistance, total current, and branch values. Use Three.js from cdnjs in one HTML file.
Working Three.js Starter (resistance-network-topology-playground-x1668):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Resistor Lab — Series / Parallel</title>
<style>
:root {
color-scheme: dark;
--bg: #07100e;
--panel: #0c1916;
--panel-2: #10221d;
--line: #203b33;
--text: #e9f7f1;
--muted: #8ca89e;
--accent: #51e0c5;
--accent-2: #ffb454;
--accent-3: #ae7cff;
--danger: #ff6b6b;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
}
body {
overflow: hidden;
background:
radial-gradient(circle at 15% 10%, #12352b 0, transparent 35%),
var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#app {
display: grid;
grid-template-rows: 74px minmax(0, 1fr);
width: 100%;
height: 100%;
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 0 24px;
border-bottom: 1px solid var(--line);
background: rgba(7, 16, 14, 0.88);
backdrop-filter: blur(14px);
z-index: 10;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-icon {
display: grid;
place-items: center;
width: 40px;
height: 40px;
flex: 0 0 auto;
border: 1px solid #2c6657;
border-radius: 12px;
color: var(--accent);
background: linear-gradient(145deg, #15382e, #0a1c18);
box-shadow: inset 0 0 20px rgba(81, 224, 197, 0.08);
}
.brand-icon svg {
width: 25px;
height: 25px;
}
.brand h1 {
margin: 0;
font-size: 15px;
line-height: 1.1;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font-size: 12px;
}
.header-actions {
display: flex;
align-items: center;
gap: 12px;
}
.mode-switch {
display: flex;
gap: 4px;
padding: 4px;
border: 1px solid var(--line);
border-radius: 12px;
background: #091411;
}
.mode-switch button {
min-width: 100px;
padding: 9px 14px;
border: 0;
border-radius: 8px;
background: transparent;
color: var(--muted);
font-size: 12px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
cursor: pointer;
transition: 160ms ease;
}
.mode-switch button:hover {
color: var(--text);
background: #14251f;
}
.mode-switch button.active {
color: #06110e;
background: var(--accent);
box-shadow: 0 4px 18px rgba(81, 224, 197, 0.2);
}
.reset-view {
padding: 10px 13px;
border: 1px solid var(--line);
border-radius: 10px;
background: #0d1c18;
color: var(--muted);
cursor: pointer;
transition: 160ms ease;
}
.reset-view:hover {
border-color: #3e6c5e;
color: var(--text);
}
main {
display: grid;
grid-template-columns: minmax(0, 1fr) 370px;
min-height: 0;
}
.viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
border-right: 1px solid var(--line);
background:
radial-gradient(circle at 50% 44%, rgba(29, 76, 62, 0.2), transparent 48%),
#07110f;
}
canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.mode-badge {
position: absolute;
top: 20px;
left: 20px;
pointer-events: none;
}
.mode-badge strong {
display: block;
padding: 8px 11px;
border: 1px solid rgba(81, 224, 197, 0.32);
border-radius: 9px;
color: var(--accent);
background: rgba(8, 24, 19, 0.82);
font-size: 11px;
letter-spacing: 0.13em;
text-transform: uppercase;
backdrop-filter: blur(10px);
}
.mode-badge span {
display: block;
margin-top: 7px;
color: var(--muted);
font-size: 11px;
}
.legend {
position: absolute;
top: 20px;
right: 20px;
display: flex;
gap: 13px;
padding: 8px 11px;
border: 1px solid rgba(60, 94, 83, 0.45);
border-radius: 9px;
color: var(--muted);
background: rgba(8, 20, 17, 0.72);
font-size: 10px;
pointer-events: none;
backdrop-filter: blur(8px);
}
.legend span {
display: flex;
align-items: center;
gap: 6px;
}
.legend i {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 8px var(--accent);
}
.legend .wire-dot {
border-radius: 1px;
background: #72a99a;
box-shadow: none;
}
.hint {
position: absolute;
left: 20px;
bottom: 19px;
padding: 8px 11px;
border: 1px solid rgba(60, 94, 83, 0.4);
border-radius: 9px;
color: var(--muted);
background: rgba(8, 20, 17, 0.72);
font-size: 11px;
pointer-events: none;
backdrop-filter: blur(8px);
}
.inspector {
position: absolute;
right: 20px;
bottom: 19px;
width: 220px;
padding: 13px 15px;
border: 1px solid rgba(81, 224, 197, 0.25);
border-radius: 12px;
background: rgba(8, 22, 18, 0.86);
box-shadow: 0 15px 35px rgba(0, 0, 0, 0.24);
pointer-events: none;
backdrop-filter: blur(12px);
}
.eyebrow {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.inspector-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 7px 0 10px;
font-size: 15px;
font-weight: 750;
}
.inspector-title span {
color: var(--accent);
}
.inspector-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.inspector-grid div {
padding: 8px;
border-radius: 8px;
background: rgba(255, 255, 255, 0.035);
}
.inspector-grid small {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 9px;
text-transform: uppercase;
}
.inspector-grid b {
font-size: 12px;
}
aside {
min-height: 0;
overflow-y: auto;
padding: 16px;
background: rgba(7, 16, 14, 0.82);
scrollbar-width: thin;
scrollbar-color: #28483e transparent;
}
.card {
margin-bottom: 13px;
padding: 16px;
border: 1px solid var(--line);
border-radius: 14px;
background: linear-gradient(145deg, rgba(16, 34, 29, 0.96), rgba(10, 23, 19, 0.96));
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.12);
}
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 14px;
}
.card-title {
font-size: 11px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.ideal-pill {
padding: 4px 7px;
border: 1px solid #31594d;
border-radius: 999px;
color: var(--accent);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.12em;
}
.supply-row {
display: grid;
grid-template-columns: 1fr 87px;
align-items: center;
gap: 14px;
}
input[type="range"] {
width: 100%;
accent-color: var(--accent);
cursor: pointer;
}
.number-wrap {
display: flex;
align-items: center;
border: 1px solid #2c4b40;
border-radius: 9px;
background: #081511;
overflow: hidden;
}
.number-wrap input {
width: 100%;
min-width: 0;
padding: 9px 5px 9px 10px;
border: 0;
outline: 0;
color: var(--text);
background: transparent;
font-weight: 700;
}
.number-wrap span {
padding-right: 9px;
color: var(--muted);
font-size: 11px;
}
.range-labels {
display: flex;
justify-content: space-between;
margin-top: 8px;
color: #66877c;
font-size: 9px;
}
.resistor-list {
display: grid;
gap: 8px;
}
.resistor-row {
display: grid;
grid-template-columns: 10px 31px minmax(0, 1fr);
align-items: center;
gap: 9px;
padding: 8px;
border: 1px solid transparent;
border-radius: 9px;
transition: 150ms ease;
cursor: pointer;
}
.resistor-row:hover,
.resistor-row.selected {
border-color: #2a4b40;
background: rgba(255, 255, 255, 0.025);
}
.resistor-row.selected {
border-color: rgba(81, 224, 197, 0.35);
}
.swatch {
width: 9px;
height: 26px;
border-radius: 5px;
box-shadow: 0 0 12px currentColor;
}
.r1-color {
color: var(--accent);
background: var(--accent);
}
.r2-color {
color: var(--accent-2);
background: var(--accent-2);
}
.r3-color {
color: var(--accent-3);
background: var(--accent-3);
}
.resistor-name {
font-size: 12px;
font-weight: 750;
}
.resistor-row .number-wrap {
min-width: 0;
}
.resistor-row .number-wrap input {
padding-top: 7px;
padding-bottom: 7px;
font-size: 12px;
}
.metric-main {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 15px;
padding-bottom: 13px;
border-bottom: 1px solid var(--line);
}
.metric-main span {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.metric-main strong {
color: var(--accent);
font-size: 28px;
line-height: 1;
letter-spacing: -0.04em;
}
.metric-main .current-metric strong {
color: #fff;
}
.metric-sub {
margin-top: 5px;
color: #6f9185;
font-size: 9px;
}
.mini-metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 12px;
}
.mini-metrics div {
padding: 9px 10px;
border-radius: 9px;
background: rgba(255, 255, 255, 0.03);
}
.mini-metrics small {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 8px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.mini-metrics b {
font-size: 12px;
}
.table-heading {
display: flex;
justify-content: space-between;
margin: 16px 0 8px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 10px;
}
th {
padding: 0 4px 8px;
color: #65867b;
font-weight: 700;
text-align: right;
}
th:first-child,
td:first-child {
text-align: left;
}
td {
padding: 9px 4px;
border-top: 1px solid rgba(45, 77, 66, 0.55);
text-align: right;
white-space: nowrap;
}
td b {
color: #dff5ec;
}
.branch-summary {
margin-top: 12px;
padding: 10px;
border-left: 2px solid var(--accent);
border-radius: 0 8px 8px 0;
color: var(--muted);
background: rgba(81, 224, 197, 0.045);
font-size: 10px;
line-height: 1.5;
}
.formula {
margin-top: 12px;
padding: 11px;
border-radius: 9px;
color: #b8d1c8;
background: #07120f;
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 10px;
line-height: 1.65;
}
.formula strong {
color: var(--accent);
}
.footnote {
margin: 2px 4px 14px;
color: #607f74;
font-size: 9px;
line-height: 1.5;
}
@media (max-width: 900px) {
body {
overflow: auto;
}
#app {
height: auto;
min-height: 100%;
grid-template-rows: auto auto;
}
.topbar {
min-height: 74px;
padding: 12px;
flex-wrap: wrap;
}
.header-actions {
width: 100%;
justify-content: space-between;
}
.mode-switch {
flex: 1;
}
.mode-switch button {
flex: 1;
}
main {
display: block;
}
.viewport {
height: 58vh;
min-height: 440px;
border-right: 0;
border-bottom: 1px solid var(--line);
}
aside {
overflow: visible;
}
}
@media (max-width: 540px) {
.brand p,
.legend,
.inspector {
display: none;
}
.mode-switch button {
min-width: 0;
padding-inline: 8px;
}
.reset-view {
font-size: 11px;
}
.viewport {
min-height: 390px;
}
aside {
padding: 10px;
}
}
</style>
</head>
<body>
<div id="app">
<header class="topbar">
<div class="brand">
<div class="brand-icon" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7">
<path d="M3 12h3m2 0h3m4 0h3m3 0h2" />
<rect x="7" y="8" width="10" height="8" rx="2" />
<path d="M10 8v8M13 8v8" opacity=".55" />
</svg>
</div>
<div>
<h1>Resistor Lab</h1>
<p>Interactive series and parallel circuit analysis</p>
</div>
</div>
<div class="header-actions">
<div class="mode-switch" role="group" aria-label="Circuit topology">
<button id="seriesButton" class="active" aria-pressed="true">Series</button>
<button id="parallelButton" aria-pressed="false">Parallel</button>
</div>
<button id="resetView" class="reset-view" title="Reset the camera">Reset view</button>
</div>
</header>
<main>
<section class="viewport" id="viewport" aria-label="Interactive 3D circuit">
<canvas id="scene"></canvas>
<div class="mode-badge">
<strong id="modeBadge">Series Network</strong>
<span id="modeDescription">One path · shared current</span>
</div>
<div class="legend">
<span><i></i> Current flow</span>
<span><i class="wire-dot"></i> Conductor</span>
</div>
<div class="hint">Drag to orbit · Scroll to zoom · Click a resistor</div>
<div class="inspector">
<div class="eyebrow">Selected component</div>
<div class="inspector-title">
<b id="selectedName">R1</b>
<span id="selectedResistance">220 Ω</span>
</div>
<div class="inspector-grid">
<div>
<small>Current</small>
<b id="selectedCurrent">—</b>
</div>
<div>
<small>Voltage drop</small>
<b id="selectedVoltage">—</b>
</div>
</div>
</div>
</section>
<aside>
<section class="card">
<div class="card-header">
<div class="card-title">Source</div>
<div class="ideal-pill">Ideal DC</div>
</div>
<div class="supply-row">
<div>
<input
id="voltageRange"
type="range"
min="1"
max="24"
step="0.1"
value="12"
aria-label="Source voltage"
/>
<div class="range-labels">
<span>1 V</span>
<span>24 V</span>
</div>
</div>
<label class="number-wrap">
<input
id="voltageInput"
type="number"
min="1"
max="24"
step="0.1"
value="12"
aria-label="Source voltage value"
/>
<span>V</span>
</label>
</div>
</section>
<section class="card">
<div class="card-header">
<div class="card-title">Resistors</div>
<div class="ideal-pill">Editable</div>
</div>
<div class="resistor-list">
<div class="resistor-row selected" data-resistor-row="0">
<span class="swatch r1-color"></span>
<span class="resistor-name">R1</span>
<label class="number-wrap">
<input
data-resistor="0"
type="number"
min="1"
max="1000000"
step="1"
value="220"
aria-label="Resistance of R1"
/>
<span>Ω</span>
</label>
</div>
<div class="resistor-row" data-resistor-row="1">
<span class="swatch r2-color"></span>
<span class="resistor-name">R2</span>
<label class="number-wrap">
<input
data-resistor="1"
type="number"
min="1"
max="1000000"
step="1"
value="470"
aria-label="Resistance of R2"
/>
<span>Ω</span>
</label>
</div>
<div class="resistor-row" data-resistor-row="2">
<span class="swatch r3-color"></span>
<span class="resistor-name">R3</span>
<label class="number-wrap">
<input
data-resistor="2"
type="number"
min="1"
max="1000000"
step="1"
value="1000"
aria-label="Resistance of R3"
/>
<span>Ω</span>
</label>
</div>
</div>
</section>
<section class="card">
<div class="card-header">
<div class="card-title">Equivalent Analysis</div>
<div class="ideal-pill" id="networkCount">1 Branch</div>
</div>
<div class="metric-main">
<div>
<span>Equivalent resistance</span>
<strong id="eqValue">1.69 kΩ</strong>
<div class="metric-sub" id="eqExact">1,690 Ω</div>
</div>
<div class="current-metric">
<span>Total current</span>
<strong id="currentValue">7.10 mA</strong>
<div class="metric-sub">from ideal source</div>
</div>
</div>
<div class="mini-metrics">
<div>
<small>Source power</small>
<b id="sourcePower">85.2 mW</b>
</div>
<div>
<small>Network voltage</small>
<b id="networkVoltage">12.0 V</b>
</div>
</div>
<div class="table-heading">
<span id="tableTitle">Element values</span>
<span id="tableTopology">Series</span>
</div>
<table>
<thead>
<tr>
<th>Branch</th>
<th>Current</th>
<th>Drop</th>
<th>Power</th>
</tr>
</thead>
<tbody id="analysisRows"></tbody>
</table>
<div class="branch-summary" id="branchSummary"></div>
<div class="formula" id="formula"></div>
</section>
<p class="footnote">
Values assume ideal wires, an ideal voltage source, and no source or
meter resistance. Select a topology to physically rewire the model.
</p>
</aside>
</main>
</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 DOM
// -------------------------------------------------------------------------
const state = {
mode: "series",
voltage: 12,
resistances: [220, 470, 1000],
selected: 0
};
const viewport = document.getElementById("viewport");
const canvas = document.getElementById("scene");
const modeBadge = document.getElementById("modeBadge");
const modeDescription = document.getElementById("modeDescription");
const networkCount = document.getElementById("networkCount");
const tableTitle = document.getElementById("tableTitle");
const tableTopology = document.getElementById("tableTopology");
const analysisRows = document.getElementById("analysisRows");
const branchSummary = document.getElementById("branchSummary");
const formula = document.getElementById("formula");
const voltageRange = document.getElementById("voltageRange");
const voltageInput = document.getElementById("voltageInput");
const resistorInputs = [...document.querySelectorAll("[data-resistor]")];
const resistorRows = [...document.querySelectorAll("[data-resistor-row]")];
const colors = [0x51e0c5, 0xffb454, 0xae7cff];
const cssColors = ["#51e0c5", "#ffb454", "#ae7cff"];
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setClearColor(0x07110f, 1);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x07110f, 17, 30);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const cameraState = {
target: new THREE.Vector3(0, 0.1, 0),
theta: 0.56,
phi: 1.17,
radius: 12.6
};
function updateCamera() {
const { target, theta, phi, radius } = 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);
}
updateCamera();
scene.add(new THREE.HemisphereLight(0xbdeee2, 0x07100d, 1.9));
const keyLight = new THREE.DirectionalLight(0xe5fff6, 3.2);
keyLight.position.set(-3, 8, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -10;
keyLight.shadow.camera.right = 10;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -8;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 25;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x45c9b0, 18, 16, 2);
rimLight.position.set(5, 2, -3);
scene.add(rimLight);
const fillLight = new THREE.PointLight(0x8561ff, 12, 13, 2);
fillLight.position.set(-5, -1, 3);
scene.add(fillLight);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(40, 40),
new THREE.MeshStandardMaterial({
color: 0x07100e,
roughness: 0.95,
metalness: 0.05
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -2.7;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(24, 24, 0x21473c, 0x122b24);
grid.position.y = -2.67;
grid.material.transparent = true;
grid.material.opacity = 0.58;
scene.add(grid);
// -------------------------------------------------------------------------
// Low-poly source
// -------------------------------------------------------------------------
const source = new THREE.Group();
source.position.set(-4.55, 0, 0);
scene.add(source);
const sourceBody = new THREE.Mesh(
new THREE.BoxGeometry(1.08, 2.25, 0.72),
new THREE.MeshStandardMaterial({
color: 0x153a30,
roughness: 0.56,
metalness: 0.28,
flatShading: true
})
);
sourceBody.castShadow = true;
sourceBody.receiveShadow = true;
source.add(sourceBody);
const sourceEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(sourceBody.geometry),
new THREE.LineBasicMaterial({
color: 0x4d8f7c,
transparent: true,
opacity: 0.5
})
);
source.add(sourceEdges);
const displayPanel = new THREE.Mesh(
new THREE.BoxGeometry(0.76, 0.86, 0.06),
new THREE.MeshStandardMaterial({
color: 0x06120f,
roughness: 0.3,
metalness: 0.45
})
);
displayPanel.position.set(0, 0.05, 0.39);
source.add(displayPanel);
function createSourceLabel() {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 256;
labelCanvas.height = 128;
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false
});
const sprite = new THREE.Sprite(material);
sprite.position.set(0, 0.06, 0.46);
sprite.scale.set(1.25, 0.625, 1);
sprite.renderOrder = 20;
source.add(sprite);
return { canvas: labelCanvas, texture };
}
const sourceLabel = createSourceLabel();
function roundedRect(ctx, x, y, w, h, radius) {
const r = Math.min(radius, w / 2, h / 2);
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 drawSourceLabel() {
const ctx = sourceLabel.canvas.getContext("2d");
ctx.clearRect(0, 0, 256, 128);
roundedRect(ctx, 5, 8, 246, 112, 16);
ctx.fillStyle = "rgba(4, 20, 15, 0.94)";
ctx.fill();
ctx.strokeStyle = "#3a826f";
ctx.lineWidth = 3;
ctx.stroke();
ctx.textAlign = "center";
ctx.fillStyle = "#8ca89e";
ctx.font = "700 19px system-ui";
ctx.fillText("DC SOURCE", 128, 42);
ctx.fillStyle = "#51e0c5";
ctx.font = "800 43px system-ui";
ctx.fillText(`${state.voltage.toFixed(1)} V`, 128, 91);
sourceLabel.texture.needsUpdate = true;
}
const positiveTerminal = new THREE.Mesh(
new THREE.CylinderGeometry(0.13, 0.13, 0.36, 8),
new THREE.MeshStandardMaterial({
color: 0xff6868,
roughness: 0.34,
metalness: 0.68,
flatShading: true
})
);
positiveTerminal.position.set(0.55, 1.35, 0);
positiveTerminal.castShadow = true;
source.add(positiveTerminal);
const negativeTerminal = positiveTerminal.clone();
negativeTerminal.material = positiveTerminal.material.clone();
negativeTerminal.material.color.setHex(0x6ea8ff);
negativeTerminal.position.y = -1.35;
source.add(negativeTerminal);
const sourceTop = new THREE.Vector3(-4, 1.35, 0);
const sourceBottom = new THREE.Vector3(-4, -1.35, 0);
// -------------------------------------------------------------------------
// Resistor models and labels
// -------------------------------------------------------------------------
const seriesPositions = [
new THREE.Vector3(-1.4, 1.35, 0.05),
new THREE.Vector3(1.1, 1.35, 0.05),
new THREE.Vector3(3.6, 1.35, 0.05)
];
const parallelPositions = [
new THREE.Vector3(0.25, 2.15, 0.05),
new THREE.Vector3(0.25, 0.15, 0.05),
new THREE.Vector3(0.25, -1.85, 0.05)
];
const resistors = [];
function createResistor(index) {
const group = new THREE.Group();
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0xd4b98c,
roughness: 0.78,
metalness: 0.04,
flatShading: true,
emissive: 0x000000,
emissiveIntensity: 0
});
const body = new THREE.Mesh(
new THREE.CylinderGeometry(0.3, 0.3, 1.4, 8, 1, false),
bodyMaterial
);
body.rotation.z = Math.PI / 2;
body.castShadow = true;
body.receiveShadow = true;
body.userData.resistorIndex = index;
group.add(body);
const leadMaterial = new THREE.MeshStandardMaterial({
color: 0xb9c8c3,
roughness: 0.28,
metalness: 0.82,
flatShading: true
});
const leadGeometry = new THREE.CylinderGeometry(0.065, 0.065, 0.55, 6);
for (const side of [-1, 1]) {
const lead = new THREE.Mesh(leadGeometry, leadMaterial);
lead.rotation.z = Math.PI / 2;
lead.position.x = side * 0.975;
lead.castShadow = true;
group.add(lead);
}
const bandMaterial = new THREE.MeshStandardMaterial({
color: colors[index],
roughness: 0.5,
metalness: 0.18,
flatShading: true
});
for (const x of [-0.38, 0, 0.38]) {
const band = new THREE.Mesh(
new THREE.TorusGeometry(0.303, 0.035, 4, 8),
bandMaterial
);
band.rotation.y = Math.PI / 2;
band.position.x = x;
group.add(band);
}
const halo = new THREE.Mesh(
new THREE.TorusGeometry(0.43, 0.018, 4, 16),
new THREE.MeshBasicMaterial({
color: colors[index],
transparent: true,
opacity: 0.85,
depthWrite: false
})
);
halo.rotation.y = Math.PI / 2;
halo.visible = false;
group.add(halo);
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 256;
labelCanvas.height = 88;
const labelTexture = new THREE.CanvasTexture(labelCanvas);
labelTexture.colorSpace = THREE.SRGBColorSpace;
const label = new THREE.Sprite(
new THREE.SpriteMaterial({
map: labelTexture,
transparent: true,
depthTest: false
})
);
label.position.set(0, 0.72, 0.5);
label.scale.set(1.75, 0.6, 1);
label.renderOrder = 25;
group.add(label);
group.position.copy(seriesPositions[index]);
scene.add(group);
const resistor = {
group,
body,
bodyMaterial,
halo,
labelCanvas,
labelTexture
};
resistors.push(resistor);
return resistor;
}
for (let i = 0; i < 3; i++) createResistor(i);
function drawResistorLabel(index) {
const ctx = resistors[index].labelCanvas.getContext("2d");
const accent = cssColors[index];
const selected = state.selected === index;
ctx.clearRect(0, 0, 256, 88);
roundedRect(ctx, 4, 4, 248, 80, 13);
ctx.fillStyle = "rgba(5, 17, 14, 0.9)";
ctx.fill();
ctx.strokeStyle = selected ? accent : "#29483e";
ctx.lineWidth = selected ? 4 : 2;
ctx.stroke();
ctx.textAlign = "left";
ctx.fillStyle = accent;
ctx.font = "800 29px system-ui";
ctx.fillText(`R${index + 1}`, 18, 38);
ctx.textAlign = "right";
ctx.fillStyle = "#e8f6f0";
ctx.font = "750 24px system-ui";
ctx.fillText(formatResistance(state.resistances[index]), 238, 38);
ctx.textAlign = "left";
ctx.fillStyle = "#78998e";
ctx.font = "600 14px system-ui";
ctx.fillText(selected ? "SELECTED" : "CLICK TO INSPECT", 19, 65);
resistors[index].labelTexture.needsUpdate = true;
}
// -------------------------------------------------------------------------
// Wires
// -------------------------------------------------------------------------
const UP = new THREE.Vector3(0, 1, 0);
function createTopologyMaterial(color, emissive = 0x000000) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.38,
metalness: 0.58,
emissive,
emissiveIntensity: emissive ? 0.45 : 0,
transparent: true,
opacity: 1
});
}
function addSegment(group, a, b, material, radius = 0.055) {
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
const geometry = new THREE.CylinderGeometry(
radius,
radius,
length,
6,
1,
false
);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(UP, direction.clone().normalize());
mesh.castShadow = true;
group.add(mesh);
return mesh;
}
function addNode(group, point, material, radius = 0.105) {
const node = new THREE.Mesh(
new THREE.IcosahedronGeometry(radius, 0),
material
);
node.position.copy(point);
node.castShadow = true;
group.add(node);
return node;
}
function makeTopologyGroup() {
const group = new THREE.Group();
group.userData.fadeMaterials = [];
scene.add(group);
return group;
}
function setGroupOpacity(group, opacity) {
group.visible = opacity > 0.005;
for (const material of group.userData.fadeMaterials) {
material.opacity = opacity;
material.depthWrite = opacity > 0.97;
}
}
function buildSeriesWires() {
const group = makeTopologyGroup();
const wireMaterial = createTopologyMaterial(0x72ad9d, 0x102f27);
const nodeMaterial = createTopologyMaterial(0x9ddfcf, 0x173f34);
group.userData.fadeMaterials.push(wireMaterial, nodeMaterial);
const r1L = new THREE.Vector3(-2.65, 1.35, 0);
const r1R = new THREE.Vector3(-0.15, 1.35, 0);
const r2L = new THREE.Vector3(-0.15, 1.35, 0);
const r2R = new THREE.Vector3(2.35, 1.35, 0);
const r3L = new THREE.Vector3(2.35, 1.35, 0);
const r3R = new THREE.Vector3(4.85, 1.35, 0);
const cornerTop = new THREE.Vector3(5.08, 1.35, 0);
const cornerBottom = new THREE.Vector3(5.08, -1.35, 0);
addSegment(group, sourceTop, r1L, wireMaterial);
addSegment(group, r1R, r2L, wireMaterial);
addSegment(group, r2R, r3L, wireMaterial);
addSegment(group, r3R, cornerTop, wireMaterial);
addSegment(group, cornerTop, cornerBottom, wireMaterial);
addSegment(group, cornerBottom, sourceBottom, wireMaterial);
addNode(group, sourceTop, nodeMaterial);
addNode(group, sourceBottom, nodeMaterial);
addNode(group, cornerTop, nodeMaterial);
addNode(group, cornerBottom, nodeMaterial);
return group;
}
function buildParallelWires() {
const group = makeTopologyGroup();
const wireMaterial = createTopologyMaterial(0x72ad9d, 0x102f27);
const nodeMaterial = createTopologyMaterial(0x9ddfcf, 0x173f34);
group.userData.fadeMaterials.push(wireMaterial, nodeMaterial);
const splitX = -2.6;
const mergeX = 2.8;
const rows = [2.15, 0.15, -1.85];
const splitTop = new THREE.Vector3(splitX, rows[0], 0);
const splitBottom = new THREE.Vector3(splitX, rows[2], 0);
const mergeTop = new THREE.Vector3(mergeX, rows[0], 0);
const mergeBottom = new THREE.Vector3(mergeX, rows[2], 0);
const splitSource = new THREE.Vector3(splitX, 1.35, 0);
addSegment(group, sourceTop, splitSource, wireMaterial);
addSegment(group, splitTop, splitBottom, wireMaterial);
rows.forEach((y) => {
const left = new THREE.Vector3(-1.0, y, 0);
const right = new THREE.Vector3(1.5, y, 0);
addSegment(
group,
new THREE.Vector3(splitX, y, 0),
left,
wireMaterial
);
addSegment(
group,
right,
new THREE.Vector3(mergeX, y, 0),
wireMaterial
);
addNode(group, new THREE.Vector3(splitX, y, 0), nodeMaterial, 0.09);
addNode(group, new THREE.Vector3(mergeX, y, 0), nodeMaterial, 0.09);
});
addSegment(group, mergeTop, mergeBottom, wireMaterial);
const returnCornerA = new THREE.Vector3(3.65, -1.85, 0);
const returnCornerB = new THREE.Vector3(3.65, -1.35, 0);
addSegment(group, mergeBottom, returnCornerA, wireMaterial);
addSegment(group, returnCornerA, returnCornerB, wireMaterial);
addSegment(group, returnCornerB, sourceBottom, wireMaterial);
addNode(group, sourceTop, nodeMaterial);
addNode(group, sourceBottom, nodeMaterial);
addNode(group, returnCornerA, nodeMaterial);
addNode(group, returnCornerB, nodeMaterial);
return group;
}
const seriesWireGroup = buildSeriesWires();
const parallelWireGroup = buildParallelWires();
// -------------------------------------------------------------------------
// Animated current particles
// -------------------------------------------------------------------------
const particleGeometry = new THREE.SphereGeometry(0.075, 8, 6);
function createFlowPath(points, count, color = 0xa8fff0) {
const group = new THREE.Group();
const material = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0,
depthWrite: false
});
const cumulative = [0];
let totalLength = 0;
for (let i = 1; i < points.length; i++) {
totalLength += points[i].distanceTo(points[i - 1]);
cumulative.push(totalLength);
}
const particles = [];
for (let i = 0; i < count; i++) {
const particle = new THREE.Mesh(particleGeometry, material);
particle.renderOrder = 8;
group.add(particle);
particles.push(particle);
}
scene.add(group);
return {
group,
material,
particles,
points,
cumulative,
totalLength,
factor: 1
};
}
const flowSeries = new THREE.Group();
scene.add(flowSeries);
const seriesFlowPath = createFlowPath(
[
sourceTop.clone().setZ(0.37),
new THREE.Vector3(-2.65, 1.35, 0.37),
new THREE.Vector3(-0.15, 1.35, 0.37),
new THREE.Vector3(2.35, 1.35, 0.37),
new THREE.Vector3(4.85, 1.35, 0.37),
new THREE.Vector3(5.08, 1.35, 0.37),
new THREE.Vector3(5.08, -1.35, 0.37),
sourceBottom.clone().setZ(0.37)
],
16
);
flowSeries.add(seriesFlowPath.group);
const flowParallel = new THREE.Group();
scene.add(flowParallel);
const parallelCommonPaths = [
createFlowPath(
[
sourceTop.clone().setZ(0.37),
new THREE.Vector3(-2.6, 1.35, 0.37)
],
5
),
createFlowPath(
[
new THREE.Vector3(2.8, -1.85, 0.37),
new THREE.Vector3(3.65, -1.85, 0.37),
new THREE.Vector3(3.65, -1.35, 0.37),
sourceBottom.clone().setZ(0.37)
],
7
)
];
const parallelBranchPaths = [2.15, 0.15, -1.85].map((y) =>
createFlowPath(
[
new THREE.Vector3(-2.6, y, 0.37),
new THREE.Vector3(-1.0, y, 0.37),
new THREE.Vector3(1.5, y, 0.37),
new THREE.Vector3(2.8, y, 0.37)
],
8
)
);
flowParallel.add(parallelCommonPaths[0].group);
flowParallel.add(parallelCommonPaths[1].group);
parallelBranchPaths.forEach((path) => flowParallel.add(path.group));
function positionParticle(path, particle, progress) {
const distance = ((progress % 1) + 1) % 1 * path.totalLength;
let segment = 0;
while (
segment < path.cumulative.length - 2 &&
distance > path.cumulative[segment + 1]
) {
segment++;
}
const start = path.cumulative[segment];
const end = path.cumulative[segment + 1];
const local = end === start ? 0 : (distance - start) / (end - start);
particle.position
.copy(path.points[segment])
.lerp(path.points[segment + 1], local);
}
function animateFlowPath(path, elapsed, visualSpeed, opacity) {
path.group.visible = opacity > 0.005;
path.material.opacity = opacity * path.factor;
if (!path.group.visible) return;
path.particles.forEach((particle, index) => {
const progress =
index / path.particles.length +
(elapsed * visualSpeed) / path.totalLength;
positionParticle(path, particle, progress);
});
}
// -------------------------------------------------------------------------
// Circuit calculations and formatting
// -------------------------------------------------------------------------
function trimNumber(value, digits = 3) {
return Number(value.toFixed(digits)).toString();
}
function formatResistance(value) {
if (value >= 1e6) {
return `${trimNumber(value / 1e6)} MΩ`;
}
if (value >= 1e3) {
return `${trimNumber(value / 1e3)} kΩ`;
}
return `${trimNumber(value)} Ω`;
}
function formatCurrent(value) {
if (value >= 1) {
return `${value.toFixed(2)} A`;
}
const milliamps = value * 1000;
return `${milliamps.toFixed(milliamps < 10 ? 2 : 1)} mA`;
}
function formatPower(value) {
if (value >= 1) {
return `${value.toFixed(2)} W`;
}
if (value >= 0.001) {
return `${(value * 1000).toFixed(1)} mW`;
}
return `${(value * 1e6).toFixed(1)} µW`;
}
function calculateCircuit() {
const voltage = state.voltage;
const resistances = state.resistances;
if (state.mode === "series") {
const equivalent = resistances.reduce((sum, r) => sum + r, 0);
const totalCurrent = voltage / equivalent;
const elements = resistances.map((r) => {
const current = totalCurrent;
const drop = current * r;
const power = current * current * r;
return { current, drop, power };
});
return {
equivalent,
totalCurrent,
elements,
sourcePower: voltage * totalCurrent
};
}
const conductance = resistances.reduce((sum, r) => sum + 1 / r, 0);
const equivalent = 1 / conductance;
const totalCurrent = voltage / equivalent;
const elements = resistances.map((r) => {
const current = voltage / r;
const drop = voltage;
const power = voltage * current;
return { current, drop, power };
});
return {
equivalent,
totalCurrent,
elements,
sourcePower: voltage * totalCurrent
};
}
function updateSelectedAppearance() {
resistors.forEach((resistor, index) => {
const selected = state.selected === index;
resistor.halo.visible = selected;
resistor.bodyMaterial.emissive.setHex(selected ? colors[index] : 0x000000);
resistor.bodyMaterial.emissiveIntensity = selected ? 0.28 : 0;
});
resistorRows.forEach((row, index) => {
row.classList.toggle("selected", index === state.selected);
});
drawResistorLabel(0);
drawResistorLabel(1);
drawResistorLabel(2);
}
function updateUI() {
const result = calculateCircuit();
document.getElementById("eqValue").textContent =
formatResistance(result.equivalent);
document.getElementById("eqExact").textContent =
`${Math.round(result.equivalent).toLocaleString()} Ω`;
document.getElementById("currentValue").textContent =
formatCurrent(result.totalCurrent);
document.getElementById("sourcePower").textContent =
formatPower(result.sourcePower);
document.getElementById("networkVoltage").textContent =
`${state.voltage.toFixed(1)} V`;
analysisRows.innerHTML = result.elements
.map((element, index) => {
const label = state.mode === "parallel"
? `R${index + 1} branch`
: `R${index + 1}`;
return `
<tr>
<td>
<b style="color:${cssColors[index]}">${label}</b>
</td>
<td>${formatCurrent(element.current)}</td>
<td>${element.drop.toFixed(2)} V</td>
<td>${formatPower(element.power)}</td>
</tr>
`;
})
.join("");
if (state.mode === "series") {
modeBadge.textContent = "Series Network";
modeDescription.textContent = "One path · shared current";
networkCount.textContent = "1 Branch";
tableTitle.textContent = "Element values";
tableTopology.textContent = "Series";
branchSummary.textContent =
"All three resistors form one continuous branch, so the same current flows through every component.";
formula.innerHTML = `
<strong>R<sub>eq</sub></strong> = R1 + R2 + R3<br>
= ${state.resistances.join(" + ")} = ${Math.round(result.equivalent).toLocaleString()} Ω<br>
<strong>I<sub>total</sub></strong> = V / R<sub>eq</sub> =
${formatCurrent(result.totalCurrent)}
`;
} else {
modeBadge.textContent = "Parallel Network";
modeDescription.textContent = "Three paths · shared voltage";
networkCount.textContent = "3 Branches";
tableTitle.textContent = "Branch values";
tableTopology.textContent = "Parallel";
branchSummary.textContent =
"Each resistor forms an independent branch. Every branch receives the full source voltage, while branch currents add to give total current.";
formula.innerHTML = `
<strong>1/R<sub>eq</sub></strong> =
1/R1 + 1/R2 + 1/R3<br>
R<sub>eq</sub> = ${Math.round(result.equivalent).toLocaleString()} Ω<br>
<strong>I<sub>total</sub></strong> = ΣI<sub>branch</sub> =
${formatCurrent(result.totalCurrent)}
`;
}
const selected = result.elements[state.selected];
document.getElementById("selectedName").textContent =
`R${state.selected + 1}`;
document.getElementById("selectedResistance").textContent =
formatResistance(state.resistances[state.selected]);
document.getElementById("selectedCurrent").textContent =
formatCurrent(selected.current);
document.getElementById("selectedVoltage").textContent =
`${selected.drop.toFixed(2)} V`;
const branchRatios = result.elements.map((element) =>
result.totalCurrent > 0
? element.current / result.totalCurrent
: 0
);
parallelBranchPaths.forEach((path, index) => {
path.factor = 0.25 + 0.75 * Math.sqrt(branchRatios[index]);
});
drawSourceLabel();
updateSelectedAppearance();
}
// -------------------------------------------------------------------------
// Topology switching
// -------------------------------------------------------------------------
let topologyMix = 0;
let topologyTarget = 0;
function setMode(mode) {
state.mode = mode;
topologyTarget = mode === "parallel" ? 1 : 0;
const seriesActive = mode === "series";
const seriesButton = document.getElementById("seriesButton");
const parallelButton = document.getElementById("parallelButton");
seriesButton.classList.toggle("active", seriesActive);
parallelButton.classList.toggle("active", !seriesActive);
seriesButton.setAttribute("aria-pressed", String(seriesActive));
parallelButton.setAttribute("aria-pressed", String(!seriesActive));
updateUI();
}
document.getElementById("seriesButton").addEventListener("click", () => {
setMode("series");
});
document.getElementById("parallelButton").addEventListener("click", () => {
setMode("parallel");
});
// -------------------------------------------------------------------------
// Input handling
// -------------------------------------------------------------------------
function syncVoltage(value) {
const clamped = THREE.MathUtils.clamp(value, 1, 24);
state.voltage = Number(clamped.toFixed(1));
voltageRange.value = state.voltage;
voltageInput.value = state.voltage;
updateUI();
}
voltageRange.addEventListener("input", (event) => {
syncVoltage(Number(event.target.value));
});
voltageInput.addEventListener("input", (event) => {
const value = Number(event.target.value);
if (Number.isFinite(value) && value >= 1 && value <= 24) {
syncVoltage(value);
}
});
voltageInput.addEventListener("change", () => {
const value = Number(voltageInput.value);
syncVoltage(Number.isFinite(value) ? value : state.voltage);
});
resistorInputs.forEach((input, index) => {
input.addEventListener("input", (event) => {
const value = Number(event.target.value);
if (Number.isFinite(value) && value >= 1 && value <= 1e6) {
state.resistances[index] = value;
updateUI();
}
});
input.addEventListener("change", () => {
const value = Number(input.value);
state.resistances[index] = Number.isFinite(value)
? THREE.MathUtils.clamp(value, 1, 1e6)
: state.resistances[index];
input.value = state.resistances[index];
updateUI();
});
input.addEventListener("focus", () => {
selectResistor(index);
});
});
resistorRows.forEach((row, index) => {
row.addEventListener("click", (event) => {
if (event.target.tagName !== "INPUT") {
selectResistor(index);
}
});
});
function selectResistor(index) {
state.selected = index;
updateSelectedAppearance();
updateUI();
}
// -------------------------------------------------------------------------
// Direct camera controls and component picking
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const pointerState = {
down: false,
moved: false,
lastX: 0,
lastY: 0
};
function setPointerFromEvent(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function pickResistor(event) {
setPointerFromEvent(event);
raycaster.setFromCamera(pointer, camera);
const bodies = resistors.map((resistor) => resistor.body);
const hit = raycaster.intersectObjects(bodies, false)[0];
if (hit) {
selectResistor(hit.object.userData.resistorIndex);
}
}
canvas.addEventListener("pointerdown", (event) => {
pointerState.down = true;
pointerState.moved = false;
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!pointerState.down) {
setPointerFromEvent(event);
raycaster.setFromCamera(pointer, camera);
const bodies = resistors.map((resistor) => resistor.body);
const hovering = raycaster.intersectObjects(bodies, false).length > 0;
canvas.style.cursor = hovering ? "pointer" : "grab";
return;
}
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
if (Math.abs(dx) + Math.abs(dy) > 2) {
pointerState.moved = true;
}
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.58,
1.48
);
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
updateCamera();
});
canvas.addEventListener("pointerup", (event) => {
if (!pointerState.moved) {
pickResistor(event);
}
pointerState.down = false;
canvas.releasePointerCapture(event.pointerId);
});
canvas.addEventListener("pointercancel", () => {
pointerState.down = false;
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.008,
7.5,
19
);
updateCamera();
},
{ passive: false }
);
function resetCamera() {
cameraState.theta = 0.56;
cameraState.phi = 1.17;
cameraState.radius = 12.6;
cameraState.target.set(0, 0.1, 0);
updateCamera();
}
document.getElementById("resetView").addEventListener("click", resetCamera);
canvas.addEventListener("dblclick", resetCamera);
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLInputElement) return;
if (event.key.toLowerCase() === "s") setMode("series");
if (event.key.toLowerCase() === "p") setMode("parallel");
});
// -------------------------------------------------------------------------
// Resize and animation
// -------------------------------------------------------------------------
function resizeRenderer() {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / Math.max(height, 1);
camera.updateProjectionMatrix();
}
new ResizeObserver(resizeRenderer).observe(viewport);
resizeRenderer();
const clock = new THREE.Clock();
function animate() {
const delta = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
topologyMix +=
(topologyTarget - topologyMix) * (1 - Math.exp(-delta * 5.2));
resistors.forEach((resistor, index) => {
resistor.group.position.lerpVectors(
seriesPositions[index],
parallelPositions[index],
topologyMix
);
});
setGroupOpacity(seriesWireGroup, 1 - topologyMix);
setGroupOpacity(parallelWireGroup, topologyMix);
const result = calculateCircuit();
const visualSpeed =
1.5 * THREE.MathUtils.clamp(result.totalCurrent / 1.5, 0.4, 4);
animateFlowPath(
seriesFlowPath,
elapsed,
visualSpeed,
1 - topologyMix
);
parallelCommonPaths.forEach((path) => {
animateFlowPath(path, elapsed, visualSpeed, topologyMix);
});
parallelBranchPaths.forEach((path) => {
animateFlowPath(path, elapsed, visualSpeed, topologyMix);
});
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
drawSourceLabel();
updateUI();
animate();
</script>
</body>
</html>
```