Prompt specification
Build or customize the Three.js 3D scene "Waveform heating-equivalence 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: Waveform heating-equivalence explorer
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/waveform-heating-equivalence-explorer-x1604
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring alternating and direct electric currents. Let users choose constant, sinusoidal, or bounded pulsed current histories through an ideal resistor; calculate mean power from the actual squared-current average. Low-poly.
Working Three.js Starter (waveform-heating-equivalence-explorer-x1604):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ideal Resistor — Current History Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #071116;
--panel: rgba(10, 24, 31, 0.88);
--panel-solid: #0b1b22;
--border: rgba(139, 211, 224, 0.16);
--text: #e8f5f7;
--muted: #87a6af;
--cyan: #4de3ff;
--pink: #ff58aa;
--amber: #ffb547;
--green: #72e6a4;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#viewport {
position: absolute;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.topbar {
position: absolute;
top: 22px;
left: 24px;
z-index: 5;
pointer-events: none;
}
.eyebrow {
margin-bottom: 5px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(22px, 3vw, 38px);
font-weight: 720;
letter-spacing: -0.04em;
}
.subtitle {
max-width: 460px;
margin-top: 7px;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.scene-status {
position: absolute;
top: 126px;
left: 24px;
z-index: 5;
display: flex;
align-items: center;
gap: 9px;
padding: 8px 11px;
border: 1px solid var(--border);
border-radius: 999px;
background: rgba(7, 17, 22, 0.7);
color: #b7ccd1;
font-size: 11px;
letter-spacing: 0.05em;
backdrop-filter: blur(12px);
pointer-events: none;
}
.status-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 13px var(--cyan);
}
.scene-legend {
position: absolute;
left: 24px;
bottom: 22px;
z-index: 5;
display: flex;
flex-wrap: wrap;
gap: 9px 17px;
max-width: calc(100vw - 430px);
color: #a7bec5;
font-size: 11px;
pointer-events: none;
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
}
.legend-dot {
width: 8px;
height: 8px;
border-radius: 50%;
}
.legend-dot.cyan {
background: var(--cyan);
box-shadow: 0 0 9px rgba(77, 227, 255, 0.7);
}
.legend-dot.pink {
background: var(--pink);
box-shadow: 0 0 9px rgba(255, 88, 170, 0.7);
}
.legend-dot.amber {
background: var(--amber);
box-shadow: 0 0 9px rgba(255, 181, 71, 0.55);
}
#panel {
position: absolute;
z-index: 10;
top: 18px;
right: 18px;
bottom: 18px;
width: 370px;
overflow-y: auto;
padding: 19px;
border: 1px solid var(--border);
border-radius: 19px;
background: var(--panel);
box-shadow: 0 22px 70px rgba(0, 0, 0, 0.38);
backdrop-filter: blur(20px) saturate(1.15);
scrollbar-width: thin;
scrollbar-color: #29424b transparent;
}
.panel-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 16px;
}
.panel-heading h2 {
margin: 2px 0 0;
font-size: 20px;
letter-spacing: -0.025em;
}
.mode-badge {
flex: 0 0 auto;
padding: 5px 8px;
border: 1px solid rgba(77, 227, 255, 0.24);
border-radius: 6px;
background: rgba(77, 227, 255, 0.08);
color: var(--cyan);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.1em;
}
.section-label {
margin: 18px 0 9px;
color: #76949d;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.mode-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
.mode-button {
min-height: 57px;
padding: 8px 5px;
border: 1px solid var(--border);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
cursor: pointer;
transition:
border-color 160ms ease,
background 160ms ease,
transform 160ms ease;
}
.mode-button:hover {
border-color: rgba(77, 227, 255, 0.35);
transform: translateY(-1px);
}
.mode-button[aria-pressed="true"] {
border-color: rgba(77, 227, 255, 0.62);
background: rgba(77, 227, 255, 0.11);
box-shadow: inset 0 0 18px rgba(77, 227, 255, 0.04);
}
.mode-button strong,
.mode-button span {
display: block;
}
.mode-button strong {
font-size: 11px;
}
.mode-button span {
margin-top: 4px;
color: var(--muted);
font-size: 9px;
}
.mode-description {
min-height: 34px;
margin-top: 9px;
color: #91abb3;
font-size: 11px;
line-height: 1.45;
}
.parameter {
margin-top: 14px;
}
.parameter-row {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 7px;
}
.parameter-row label {
color: #c3d6da;
font-size: 11px;
}
.parameter-row output {
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 11px;
font-weight: 700;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 4px 0;
border-radius: 999px;
outline: none;
appearance: none;
background: #203640;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
border: 3px solid #0a1b22;
border-radius: 50%;
appearance: none;
background: var(--cyan);
box-shadow: 0 0 0 1px rgba(77, 227, 255, 0.55);
}
input[type="range"]::-moz-range-thumb {
width: 10px;
height: 10px;
border: 3px solid #0a1b22;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 0 1px rgba(77, 227, 255, 0.55);
}
input[type="range"]:disabled {
opacity: 0.28;
cursor: not-allowed;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
min-height: 72px;
padding: 11px;
border: 1px solid var(--border);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.metric-label {
display: block;
margin-bottom: 6px;
color: #7897a0;
font-size: 9px;
letter-spacing: 0.04em;
}
.metric-value {
display: block;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 17px;
font-weight: 750;
}
.metric-value.cyan {
color: var(--cyan);
}
.metric-value.amber {
color: var(--amber);
}
.metric-value.green {
color: var(--green);
}
.equation-card {
margin-top: 9px;
padding: 12px;
border: 1px solid rgba(255, 181, 71, 0.18);
border-radius: 10px;
background: rgba(255, 181, 71, 0.055);
}
.equation-card .formula {
color: #f7d39b;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 12px;
line-height: 1.5;
}
.equation-card p {
margin: 7px 0 0;
color: #8fa8af;
font-size: 10px;
line-height: 1.45;
}
#waveChart {
display: block;
width: 100%;
height: 150px;
border: 1px solid var(--border);
border-radius: 10px;
background: rgba(4, 12, 16, 0.55);
}
.chart-legend {
display: flex;
gap: 15px;
margin-top: 7px;
color: #839fa7;
font-size: 9px;
}
.chart-key {
display: flex;
align-items: center;
gap: 6px;
}
.chart-line {
width: 15px;
height: 2px;
background: var(--cyan);
}
.chart-line.square {
background: var(--amber);
opacity: 0.8;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 16px;
}
.button-row button {
min-height: 38px;
border: 1px solid var(--border);
border-radius: 9px;
background: rgba(255, 255, 255, 0.035);
cursor: pointer;
font-size: 11px;
font-weight: 650;
transition: background 150ms ease, border-color 150ms ease;
}
.button-row button:hover {
border-color: rgba(77, 227, 255, 0.35);
background: rgba(77, 227, 255, 0.08);
}
.button-row #pause {
grid-column: 1 / -1;
border-color: rgba(77, 227, 255, 0.28);
background: rgba(77, 227, 255, 0.09);
}
.note {
margin: 13px 0 0;
color: #6f8c95;
font-size: 9px;
line-height: 1.55;
}
@media (max-width: 760px) {
.topbar {
top: 14px;
left: 14px;
}
.subtitle {
max-width: calc(100vw - 28px);
font-size: 11px;
}
.scene-status {
top: 100px;
left: 14px;
}
#panel {
top: auto;
right: 9px;
bottom: 9px;
left: 9px;
width: auto;
max-height: 49vh;
padding: 14px;
border-radius: 15px;
}
.scene-legend {
top: 138px;
bottom: auto;
left: 14px;
max-width: calc(100vw - 28px);
font-size: 9px;
}
}
</style>
</head>
<body>
<div id="viewport" aria-label="Interactive low-poly electrical circuit"></div>
<header class="topbar">
<div class="eyebrow">Ideal Resistor Lab</div>
<h1>Current history → heat</h1>
<div class="subtitle">
Prescribe a direct, alternating, or bounded pulsed current through an ideal
resistor. Mean power is calculated from the period average of i²(t).
</div>
</header>
<div class="scene-status">
<span class="status-dot" id="statusDot"></span>
<span id="sceneStatusText">ALTERNATING CURRENT</span>
</div>
<div class="scene-legend">
<span class="legend-item">
<i class="legend-dot cyan"></i>Positive conventional current
</span>
<span class="legend-item">
<i class="legend-dot pink"></i>Negative conventional current
</span>
<span class="legend-item">
<i class="legend-dot amber"></i>Resistor heating
</span>
</div>
<aside id="panel">
<div class="panel-heading">
<div>
<div class="eyebrow">Control Deck</div>
<h2>Source settings</h2>
</div>
<span class="mode-badge" id="modeBadge">AC</span>
</div>
<div class="section-label">Current history</div>
<div class="mode-grid" role="group" aria-label="Current waveform">
<button class="mode-button" data-mode="constant" aria-pressed="false">
<strong>Constant</strong>
<span>Direct current</span>
</button>
<button class="mode-button" data-mode="sine" aria-pressed="true">
<strong>Sinusoidal</strong>
<span>Alternating</span>
</button>
<button class="mode-button" data-mode="pulse" aria-pressed="false">
<strong>Bounded pulse</strong>
<span>Pulsed DC</span>
</button>
</div>
<div class="mode-description" id="modeDescription"></div>
<div class="section-label">Parameters</div>
<div class="parameter">
<div class="parameter-row">
<label for="amplitude">Current amplitude</label>
<output id="amplitudeOutput" for="amplitude"></output>
</div>
<input id="amplitude" type="range" min="0.2" max="5" step="0.1" value="2">
</div>
<div class="parameter">
<div class="parameter-row">
<label for="resistance">Ideal resistance</label>
<output id="resistanceOutput" for="resistance"></output>
</div>
<input id="resistance" type="range" min="10" max="1000" step="10" value="100">
</div>
<div class="parameter">
<div class="parameter-row">
<label for="frequency">Wave frequency</label>
<output id="frequencyOutput" for="frequency"></output>
</div>
<input id="frequency" type="range" min="0.2" max="5" step="0.1" value="1">
</div>
<div class="parameter">
<div class="parameter-row">
<label for="duty">Pulse duty cycle</label>
<output id="dutyOutput" for="duty"></output>
</div>
<input id="duty" type="range" min="0.05" max="0.9" step="0.01" value="0.35">
</div>
<div class="section-label">Live measurements</div>
<div class="metric-grid">
<div class="metric">
<span class="metric-label">Instant current</span>
<strong class="metric-value cyan" id="currentMetric">0.00 A</strong>
</div>
<div class="metric">
<span class="metric-label">Instant power</span>
<strong class="metric-value amber" id="instantPowerMetric">0.0 W</strong>
</div>
<div class="metric">
<span class="metric-label">RMS current</span>
<strong class="metric-value" id="rmsMetric">0.00 A</strong>
</div>
<div class="metric">
<span class="metric-label">Mean power</span>
<strong class="metric-value green" id="meanPowerMetric">0.0 W</strong>
</div>
</div>
<div class="equation-card">
<div class="formula" id="meanSquareFormula"></div>
<p id="integrationNote"></p>
</div>
<div class="section-label">Waveform preview</div>
<canvas id="waveChart" aria-label="Current and squared-current waveform graph"></canvas>
<div class="chart-legend">
<span class="chart-key"><i class="chart-line"></i>i(t)</span>
<span class="chart-key"><i class="chart-line square"></i>i²(t)</span>
</div>
<div class="button-row">
<button id="pause" type="button" aria-pressed="false">Pause animation</button>
<button id="resetTime" type="button">Reset time</button>
<button id="resetCamera" type="button">Reset view</button>
</div>
<p class="note">
The source prescribes current; the ideal resistor stores no energy and
dissipates p(t) = R i²(t). Numerical quadrature is performed over one
complete period. Drag to orbit and use the wheel to zoom.
</p>
</aside>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------
// State and waveform mathematics
// ---------------------------------------------------------------------
const state = {
mode: "sine",
amplitude: 2,
resistance: 100,
frequency: 1,
duty: 0.35,
time: 0,
paused: false
};
const modeInfo = {
constant: {
badge: "DC",
scene: "DIRECT CURRENT",
description:
"Direct current: a fixed one-way current with constant magnitude."
},
sine: {
badge: "AC",
scene: "ALTERNATING CURRENT",
description:
"Alternating current: a sinusoid whose direction reverses every half-cycle."
},
pulse: {
badge: "PULSE",
scene: "BOUNDED PULSED CURRENT",
description:
"Unipolar bounded pulse: 0 ≤ i(t) ≤ A, using a smooth raised pulse."
}
};
function currentAt(t) {
const A = state.amplitude;
const f = state.frequency;
if (state.mode === "constant") {
return A;
}
if (state.mode === "sine") {
return A * Math.sin(2 * Math.PI * f * t);
}
// A smooth pulse that starts and ends at zero, so it remains bounded.
const phase = (f * t) % 1;
if (phase >= state.duty) {
return 0;
}
return (
A *
0.5 *
(1 - Math.cos((2 * Math.PI * phase) / state.duty))
);
}
function computeMeanSquare() {
// Midpoint quadrature over one complete period. This is intentionally
// based on the actual sampled squared-current history, not on mean i(t).
const period = 1 / state.frequency;
const samples = 8192;
let sum = 0;
for (let k = 0; k < samples; k++) {
const t = ((k + 0.5) / samples) * period;
const i = currentAt(t);
sum += i * i;
}
return sum / samples;
}
function formatNumber(value, digits = 2) {
if (!Number.isFinite(value)) return "—";
const abs = Math.abs(value);
if (abs >= 10000) return value.toExponential(2);
if (abs >= 100) return value.toFixed(Math.min(digits, 1));
return value.toFixed(digits);
}
// ---------------------------------------------------------------------
// DOM
// ---------------------------------------------------------------------
const viewport = document.querySelector("#viewport");
const modeButtons = [...document.querySelectorAll(".mode-button")];
const amplitudeInput = document.querySelector("#amplitude");
const resistanceInput = document.querySelector("#resistance");
const frequencyInput = document.querySelector("#frequency");
const dutyInput = document.querySelector("#duty");
const amplitudeOutput = document.querySelector("#amplitudeOutput");
const resistanceOutput = document.querySelector("#resistanceOutput");
const frequencyOutput = document.querySelector("#frequencyOutput");
const dutyOutput = document.querySelector("#dutyOutput");
const modeBadge = document.querySelector("#modeBadge");
const modeDescription = document.querySelector("#modeDescription");
const sceneStatusText = document.querySelector("#sceneStatusText");
const statusDot = document.querySelector("#statusDot");
const currentMetric = document.querySelector("#currentMetric");
const instantPowerMetric = document.querySelector("#instantPowerMetric");
const rmsMetric = document.querySelector("#rmsMetric");
const meanPowerMetric = document.querySelector("#meanPowerMetric");
const meanSquareFormula = document.querySelector("#meanSquareFormula");
const integrationNote = document.querySelector("#integrationNote");
const chartCanvas = document.querySelector("#waveChart");
const chartContext = chartCanvas.getContext("2d");
const pauseButton = document.querySelector("#pause");
const resetTimeButton = document.querySelector("#resetTime");
const resetCameraButton = document.querySelector("#resetCamera");
// ---------------------------------------------------------------------
// Three.js scene
// ---------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071116);
scene.fog = new THREE.Fog(0x071116, 13, 26);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
60
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
viewport.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0x9eddec, 0x142028, 1.65);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xc7f3ff, 3.1);
keyLight.position.set(-5, 10, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -9;
keyLight.shadow.camera.right = 9;
keyLight.shadow.camera.top = 9;
keyLight.shadow.camera.bottom = -9;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0xff65b4, 1.25);
rimLight.position.set(7, 4, -6);
scene.add(rimLight);
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x091820,
roughness: 0.94,
metalness: 0.05,
flatShading: true
});
const ground = new THREE.Mesh(
new THREE.CircleGeometry(13, 32),
groundMaterial
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.24;
ground.receiveShadow = true;
scene.add(ground);
const platformMaterial = new THREE.MeshStandardMaterial({
color: 0x102a32,
roughness: 0.78,
metalness: 0.16,
flatShading: true
});
const platform = new THREE.Mesh(
new THREE.BoxGeometry(12, 0.42, 6),
platformMaterial
);
platform.position.y = 0;
platform.receiveShadow = true;
platform.castShadow = true;
scene.add(platform);
const platformEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(platform.geometry),
new THREE.LineBasicMaterial({
color: 0x28505a,
transparent: true,
opacity: 0.55
})
);
platformEdges.position.copy(platform.position);
scene.add(platformEdges);
const grid = new THREE.GridHelper(10, 20, 0x2c525d, 0x17343d);
grid.position.y = 0.215;
grid.scale.z = 0.5;
grid.material.transparent = true;
grid.material.opacity = 0.32;
scene.add(grid);
// Closed, low-poly circuit path.
const pathPoints = [
new THREE.Vector3(-4.8, 0.86, -2.3),
new THREE.Vector3(4.8, 0.86, -2.3),
new THREE.Vector3(5.4, 0.86, -1.7),
new THREE.Vector3(5.4, 0.86, 1.7),
new THREE.Vector3(4.8, 0.86, 2.3),
new THREE.Vector3(2.9, 0.86, 2.3),
new THREE.Vector3(-2.7, 0.86, 2.3),
new THREE.Vector3(-4.8, 0.86, 2.3),
new THREE.Vector3(-5.4, 0.86, 1.7),
new THREE.Vector3(-5.4, 0.86, -1.7)
];
const circuitCurve = new THREE.CatmullRomCurve3(
pathPoints,
true,
"centripetal",
0.45
);
const wireMaterial = new THREE.MeshStandardMaterial({
color: 0xc47a42,
emissive: 0x351608,
emissiveIntensity: 0.25,
roughness: 0.44,
metalness: 0.72,
flatShading: true
});
const wire = new THREE.Mesh(
new THREE.TubeGeometry(circuitCurve, 180, 0.075, 6, true),
wireMaterial
);
wire.castShadow = true;
scene.add(wire);
// Low-poly current source.
const sourceGroup = new THREE.Group();
sourceGroup.position.set(-2.7, 0, 2.3);
scene.add(sourceGroup);
const sourceMaterial = new THREE.MeshStandardMaterial({
color: 0x294650,
emissive: 0x123c48,
emissiveIntensity: 0.35,
roughness: 0.52,
metalness: 0.48,
flatShading: true
});
const sourceBody = new THREE.Mesh(
new THREE.CylinderGeometry(0.5, 0.55, 1.35, 8),
sourceMaterial
);
sourceBody.position.y = 1.26;
sourceBody.castShadow = true;
sourceGroup.add(sourceBody);
const terminalMaterial = new THREE.MeshStandardMaterial({
color: 0xb9c5c8,
roughness: 0.3,
metalness: 0.8,
flatShading: true
});
for (const y of [0.42, 2.08]) {
const terminal = new THREE.Mesh(
new THREE.CylinderGeometry(0.13, 0.13, 0.46, 8),
terminalMaterial
);
terminal.position.y = y;
terminal.castShadow = true;
sourceGroup.add(terminal);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.51, 0.035, 4, 12),
new THREE.MeshStandardMaterial({
color: y > 1 ? 0xff5b9f : 0x4de3ff,
emissive: y > 1 ? 0x5b102f : 0x124858,
emissiveIntensity: 0.8,
flatShading: true
})
);
ring.rotation.x = Math.PI / 2;
ring.position.y = y > 1 ? 1.93 : 0.58;
sourceGroup.add(ring);
}
// Ideal resistor.
const resistorGroup = new THREE.Group();
resistorGroup.position.set(1.35, 0.86, 2.3);
scene.add(resistorGroup);
const resistorMaterial = new THREE.MeshStandardMaterial({
color: 0xd2a568,
emissive: 0x180b02,
emissiveIntensity: 0.12,
roughness: 0.67,
metalness: 0.12,
flatShading: true
});
const resistorBody = new THREE.Mesh(
new THREE.CylinderGeometry(0.34, 0.34, 2.15, 10),
resistorMaterial
);
resistorBody.rotation.z = Math.PI / 2;
resistorBody.castShadow = true;
resistorGroup.add(resistorBody);
const bandMaterial = new THREE.MeshStandardMaterial({
color: 0x25343b,
roughness: 0.65,
metalness: 0.15,
flatShading: true
});
for (const x of [-0.72, -0.38, 0.38, 0.72]) {
const band = new THREE.Mesh(
new THREE.TorusGeometry(0.345, 0.037, 4, 12),
bandMaterial
);
band.rotation.y = Math.PI / 2;
band.position.x = x;
resistorGroup.add(band);
}
function addAxialLead(x, length) {
const lead = new THREE.Mesh(
new THREE.CylinderGeometry(0.075, 0.075, length, 8),
terminalMaterial
);
lead.rotation.z = Math.PI / 2;
lead.position.x = x;
lead.castShadow = true;
resistorGroup.add(lead);
}
addAxialLead(-1.32, 0.55);
addAxialLead(1.32, 0.55);
const heatLight = new THREE.PointLight(0xff8a24, 0, 4.5, 2);
heatLight.position.set(1.35, 1.25, 2.45);
scene.add(heatLight);
// Canvas-texture labels, without external assets.
function createLabel(initialText) {
const canvas = document.createElement("canvas");
canvas.width = 640;
canvas.height = 112;
const ctx = canvas.getContext("2d");
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.9, 0.51, 1);
sprite.renderOrder = 10;
sprite.userData.setText = (text) => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "rgba(5, 18, 24, 0.88)";
ctx.fillRect(5, 10, 630, 92);
ctx.strokeStyle = "rgba(111, 207, 224, 0.38)";
ctx.lineWidth = 3;
ctx.strokeRect(5, 10, 630, 92);
ctx.fillStyle = "#dff7fb";
ctx.font = "700 31px ui-monospace, monospace";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 320, 57);
texture.needsUpdate = true;
};
sprite.userData.setText(initialText);
return sprite;
}
const sourceLabel = createLabel("PRESCRIBED I-SOURCE");
sourceLabel.position.set(-2.7, 2.65, 2.3);
scene.add(sourceLabel);
const resistorLabel = createLabel("IDEAL R · 100 Ω");
resistorLabel.position.set(1.35, 1.85, 2.3);
scene.add(resistorLabel);
// Instanced low-poly current markers.
const particleCount = 56;
const particleGeometry = new THREE.IcosahedronGeometry(0.09, 0);
const particleMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
emissive: 0x174955,
emissiveIntensity: 0.95,
roughness: 0.25,
metalness: 0.05,
flatShading: true
});
const particles = new THREE.InstancedMesh(
particleGeometry,
particleMaterial,
particleCount
);
particles.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
particles.castShadow = true;
particles.frustumCulled = false;
scene.add(particles);
const particlePhases = Array.from(
{ length: particleCount },
(_, i) => i / particleCount
);
const dummy = new THREE.Object3D();
const positiveColor = new THREE.Color(0x4de3ff);
const negativeColor = new THREE.Color(0xff58aa);
const zeroColor = new THREE.Color(0x6f8790);
// ---------------------------------------------------------------------
// Direct camera controls: orbit, pan-free, and wheel zoom
// ---------------------------------------------------------------------
const orbit = {
theta: 0.72,
phi: 1.03,
radius: 13.4,
target: new THREE.Vector3(0, 0.75, 0)
};
const defaultCamera = {
theta: 0.72,
phi: 1.03,
radius: 13.4
};
function applyCamera() {
const spherical = new THREE.Spherical(
orbit.radius,
orbit.phi,
orbit.theta
);
camera.position.setFromSpherical(spherical).add(orbit.target);
camera.lookAt(orbit.target);
}
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousPointerX;
const dy = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
orbit.theta -= dx * 0.007;
orbit.phi = THREE.MathUtils.clamp(
orbit.phi - dy * 0.006,
0.34,
1.43
);
applyCamera();
});
function endDrag(event) {
dragging = false;
if (
event.pointerId !== undefined &&
renderer.domElement.hasPointerCapture(event.pointerId)
) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
7.5,
23
);
applyCamera();
},
{ passive: false }
);
applyCamera();
// ---------------------------------------------------------------------
// UI and chart
// ---------------------------------------------------------------------
function updateControls() {
const info = modeInfo[state.mode];
modeButtons.forEach((button) => {
button.setAttribute(
"aria-pressed",
String(button.dataset.mode === state.mode)
);
});
modeBadge.textContent = info.badge;
modeDescription.textContent = info.description;
sceneStatusText.textContent = info.scene;
const accent =
state.mode === "sine"
? "#4de3ff"
: state.mode === "constant"
? "#72e6a4"
: "#ffb547";
statusDot.style.background = accent;
statusDot.style.boxShadow = `0 0 13px ${accent}`;
amplitudeOutput.textContent = `${state.amplitude.toFixed(1)} A`;
resistanceOutput.textContent = `${state.resistance.toFixed(0)} Ω`;
frequencyOutput.textContent = `${state.frequency.toFixed(1)} Hz`;
dutyOutput.textContent = `${Math.round(state.duty * 100)}%`;
frequencyInput.disabled = state.mode === "constant";
dutyInput.disabled = state.mode !== "pulse";
resistorLabel.userData.setText(
`IDEAL R · ${state.resistance.toFixed(0)} Ω`
);
}
function updateMeanMetrics() {
const meanSquare = computeMeanSquare();
const rms = Math.sqrt(meanSquare);
const meanPower = state.resistance * meanSquare;
rmsMetric.textContent = `${formatNumber(rms)} A`;
meanPowerMetric.textContent = `${formatNumber(meanPower, 1)} W`;
meanSquareFormula.textContent =
`P̄ = R⟨i²⟩ = ${state.resistance.toFixed(0)} × ` +
`${formatNumber(meanSquare, 3)} A² = ${formatNumber(meanPower, 1)} W`;
let analytic;
if (state.mode === "constant") {
analytic = "For constant current, ⟨i²⟩ = A².";
} else if (state.mode === "sine") {
analytic = "For a sinusoid, the exact check is ⟨i²⟩ = A²/2.";
} else {
analytic =
"For this raised pulse, the exact check is " +
"⟨i²⟩ = 3A²/(8D).";
}
integrationNote.textContent =
`${analytic} The displayed mean is obtained by numerically ` +
`integrating the actual i²(t) over one period.`;
}
function drawChart() {
const rect = chartCanvas.getBoundingClientRect();
if (rect.width < 1 || rect.height < 1) return;
const dpr = Math.min(window.devicePixelRatio, 2);
const width = rect.width;
const height = rect.height;
chartCanvas.width = Math.round(width * dpr);
chartCanvas.height = Math.round(height * dpr);
chartContext.setTransform(dpr, 0, 0, dpr, 0, 0);
chartContext.clearRect(0, 0, width, height);
const padding = {
left: 31,
right: 9,
top: 13,
bottom: 22
};
const plotWidth = width - padding.left - padding.right;
const plotHeight = height - padding.top - padding.bottom;
const centerY = padding.top + plotHeight / 2;
const A = state.amplitude;
chartContext.font = "9px ui-monospace, monospace";
chartContext.textBaseline = "middle";
// Grid.
for (const value of [-A, -A / 2, 0, A / 2, A]) {
const y =
centerY - (value / A) * (plotHeight / 2);
chartContext.strokeStyle =
value === 0 ? "rgba(139, 211, 224, 0.28)" : "rgba(139, 211, 224, 0.10)";
chartContext.lineWidth = 1;
chartContext.beginPath();
chartContext.moveTo(padding.left, y);
chartContext.lineTo(width - padding.right, y);
chartContext.stroke();
chartContext.fillStyle = "#6f8d96";
chartContext.textAlign = "right";
chartContext.fillText(
value === 0 ? "0" : `${value > 0 ? "+" : ""}${value.toFixed(1)}`,
padding.left - 5,
y
);
}
const duration =
state.mode === "constant"
? 1 / state.frequency
: 2 / state.frequency;
const period = 1 / state.frequency;
const divisions = state.mode === "constant" ? 1 : 2;
for (let i = 0; i <= divisions; i++) {
const x = padding.left + (i / divisions) * plotWidth;
chartContext.strokeStyle = "rgba(139, 211, 224, 0.10)";
chartContext.beginPath();
chartContext.moveTo(x, padding.top);
chartContext.lineTo(x, padding.top + plotHeight);
chartContext.stroke();
chartContext.fillStyle = "#6f8d96";
chartContext.textAlign = "center";
chartContext.fillText(
i === divisions ? `${divisions}T` : "0",
x,
height - 7
);
}
const samples = 500;
// i²(t), normalized to the same vertical scale.
chartContext.strokeStyle = "rgba(255, 181, 71, 0.72)";
chartContext.lineWidth = 1.4;
chartContext.beginPath();
for (let k = 0; k <= samples; k++) {
const fraction = k / samples;
const t = fraction * duration;
const i = currentAt(t);
const normalizedSquare = (i * i) / (A * A);
const x = padding.left + fraction * plotWidth;
const y = centerY - normalizedSquare * (plotHeight / 2);
if (k === 0) chartContext.moveTo(x, y);
else chartContext.lineTo(x, y);
}
chartContext.stroke();
// i(t).
chartContext.strokeStyle = "#4de3ff";
chartContext.lineWidth = 2;
chartContext.beginPath();
for (let k = 0; k <= samples; k++) {
const fraction = k / samples;
const t = fraction * duration;
const i = currentAt(t);
const x = padding.left + fraction * plotWidth;
const y = centerY - (i / A) * (plotHeight / 2);
if (k === 0) chartContext.moveTo(x, y);
else chartContext.lineTo(x, y);
}
chartContext.stroke();
// Period separators.
chartContext.setLineDash([3, 3]);
chartContext.strokeStyle = "rgba(139, 211, 224, 0.25)";
chartContext.lineWidth = 1;
for (let i = 1; i < divisions; i++) {
const x = padding.left + (i / divisions) * plotWidth;
chartContext.beginPath();
chartContext.moveTo(x, padding.top);
chartContext.lineTo(x, padding.top + plotHeight);
chartContext.stroke();
}
chartContext.setLineDash([]);
}
function updateLiveMetrics() {
const current = currentAt(state.time);
const instantaneousPower = state.resistance * current * current;
currentMetric.textContent = `${formatNumber(current)} A`;
instantPowerMetric.textContent =
`${formatNumber(instantaneousPower, 1)} W`;
}
modeButtons.forEach((button) => {
button.addEventListener("click", () => {
state.mode = button.dataset.mode;
state.time = 0;
updateControls();
updateMeanMetrics();
drawChart();
});
});
amplitudeInput.addEventListener("input", () => {
state.amplitude = Number(amplitudeInput.value);
updateControls();
updateMeanMetrics();
drawChart();
});
resistanceInput.addEventListener("input", () => {
state.resistance = Number(resistanceInput.value);
updateControls();
updateMeanMetrics();
});
frequencyInput.addEventListener("input", () => {
state.frequency = Number(frequencyInput.value);
updateControls();
updateMeanMetrics();
drawChart();
});
dutyInput.addEventListener("input", () => {
state.duty = Number(dutyInput.value);
updateControls();
updateMeanMetrics();
drawChart();
});
pauseButton.addEventListener("click", () => {
state.paused = !state.paused;
pauseButton.textContent = state.paused
? "Resume animation"
: "Pause animation";
pauseButton.setAttribute("aria-pressed", String(state.paused));
});
resetTimeButton.addEventListener("click", () => {
state.time = 0;
});
resetCameraButton.addEventListener("click", () => {
orbit.theta = defaultCamera.theta;
orbit.phi = defaultCamera.phi;
orbit.radius = defaultCamera.radius;
applyCamera();
});
const chartResizeObserver = new ResizeObserver(drawChart);
chartResizeObserver.observe(chartCanvas);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
drawChart();
});
// ---------------------------------------------------------------------
// Animation
// ---------------------------------------------------------------------
const clock = new THREE.Clock();
function updateParticles(current, dt) {
const normalizedCurrent = current / state.amplitude;
for (let i = 0; i < particleCount; i++) {
// Integrating the signed current makes negative AC reverse the markers.
particlePhases[i] += normalizedCurrent * dt * 0.9;
particlePhases[i] %= 1;
if (particlePhases[i] < 0) particlePhases[i] += 1;
const point = circuitCurve.getPointAt(particlePhases[i]);
const magnitude = Math.min(1, Math.abs(normalizedCurrent));
const scale = 0.62 + magnitude * 0.52;
dummy.position.copy(point);
dummy.scale.setScalar(scale);
dummy.rotation.set(0, state.time * 0.8 + i, 0);
dummy.updateMatrix();
particles.setMatrixAt(i, dummy.matrix);
const color =
Math.abs(current) < 0.015
? zeroColor
: current > 0
? positiveColor
: negativeColor;
particles.setColorAt(i, color);
}
particles.instanceMatrix.needsUpdate = true;
if (particles.instanceColor) {
particles.instanceColor.needsUpdate = true;
}
particleMaterial.emissive.set(
current >= 0 ? 0x174955 : 0x57163f
);
}
function updateHeating(current) {
const normalizedPower = Math.min(
1,
(state.resistance * current * current) /
Math.max(0.001, state.resistance * state.amplitude * state.amplitude)
);
resistorMaterial.emissive.setRGB(
normalizedPower * 0.95,
normalizedPower * 0.22,
normalizedPower * 0.025
);
resistorMaterial.emissiveIntensity = 0.08 + normalizedPower * 1.15;
heatLight.intensity = normalizedPower * 2.4;
heatLight.distance = 4.5;
sourceMaterial.emissive.set(current >= 0 ? 0x124b58 : 0x57163f);
sourceMaterial.emissiveIntensity =
0.2 + Math.min(1, Math.abs(current) / state.amplitude) * 0.5;
}
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
if (!state.paused) {
state.time += dt;
}
const current = currentAt(state.time);
updateParticles(current, state.paused ? 0 : dt);
updateHeating(current);
updateLiveMetrics();
renderer.render(scene, camera);
}
updateControls();
updateMeanMetrics();
updateLiveMetrics();
drawChart();
animate();
</script>
</body>
</html>
```