Prompt specification
Build or customize the Three.js 3D scene "DC and sinusoidal AC waveform rails" 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: DC and sinusoidal AC waveform rails
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/dc-and-sinusoidal-ac-waveform-rails-x1601
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows alternating and direct electric currents. Build two virtual circuit loops beside current-versus-time plots, one constant and one sinusoidal; show directional reversal only in the alternating case. Low-poly.
Working Three.js Starter (dc-and-sinusoidal-ac-waveform-rails-x1601):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Current Lab — Direct and Alternating Electricity</title>
<style>
:root {
color-scheme: dark;
--bg: #070c15;
--panel: #0d1522;
--panel-2: #111c2b;
--border: #233249;
--text: #eef5ff;
--muted: #8da0b9;
--dc: #55e3ff;
--ac: #ffb45e;
--reverse: #ff637d;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background:
radial-gradient(circle at 20% 0%, rgba(42, 104, 142, 0.15), transparent 30rem),
radial-gradient(circle at 90% 10%, rgba(151, 79, 44, 0.12), transparent 28rem),
var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
.app {
width: min(1580px, 100%);
margin: 0 auto;
padding: 18px;
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 22px;
margin-bottom: 16px;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 260px;
}
.brand-mark {
position: relative;
width: 45px;
height: 45px;
flex: 0 0 auto;
border: 1px solid #38516e;
border-radius: 13px;
background: linear-gradient(145deg, #17283a, #0b1421);
box-shadow: inset 0 1px 0 rgba(255,255,255,0.08);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
border: 2px solid var(--dc);
border-radius: 50%;
}
.brand-mark::before {
inset: 9px;
border-right-color: transparent;
transform: rotate(-30deg);
}
.brand-mark::after {
width: 7px;
height: 7px;
left: 18px;
top: 18px;
border: 0;
background: var(--ac);
box-shadow: 0 0 12px var(--ac);
}
h1 {
margin: 0;
font-size: clamp(1.15rem, 2vw, 1.55rem);
line-height: 1.1;
letter-spacing: 0.08em;
}
.subtitle {
margin: 5px 0 0;
color: var(--muted);
font-size: 0.8rem;
letter-spacing: 0.025em;
}
.controls {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 9px;
flex-wrap: wrap;
}
.control-button,
.toggle {
min-height: 38px;
border: 1px solid var(--border);
border-radius: 10px;
background: #101b29;
color: var(--text);
padding: 8px 13px;
cursor: pointer;
transition: border-color 160ms ease, background 160ms ease, transform 160ms ease;
}
.control-button:hover,
.toggle:hover {
border-color: #45617f;
background: #152538;
}
.control-button:active,
.toggle:active {
transform: translateY(1px);
}
.control-button.primary {
min-width: 92px;
border-color: rgba(85, 227, 255, 0.45);
background: rgba(85, 227, 255, 0.11);
color: #b8f4ff;
}
.speed-control {
display: flex;
align-items: center;
gap: 9px;
min-height: 38px;
padding: 6px 11px;
border: 1px solid var(--border);
border-radius: 10px;
background: #101b29;
color: var(--muted);
font-size: 0.78rem;
}
.speed-control input {
width: 92px;
accent-color: var(--dc);
}
#speedValue {
width: 36px;
color: var(--text);
font-variant-numeric: tabular-nums;
}
.toggle {
display: flex;
align-items: center;
gap: 7px;
color: #c9d7e8;
font-size: 0.8rem;
}
.toggle input {
accent-color: var(--dc);
}
.workspace {
display: grid;
grid-template-columns: minmax(0, 1.48fr) minmax(350px, 0.72fr);
gap: 16px;
height: min(780px, calc(100vh - 126px));
min-height: 610px;
}
.scene-panel,
.chart-card {
overflow: hidden;
border: 1px solid var(--border);
border-radius: 18px;
background: linear-gradient(160deg, rgba(17, 29, 44, 0.96), rgba(9, 15, 25, 0.98));
box-shadow: 0 22px 60px rgba(0, 0, 0, 0.24);
}
.scene-panel {
position: relative;
min-width: 0;
}
#viewport {
position: absolute;
inset: 0;
overflow: hidden;
}
#viewport canvas.webgl {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
cursor: grab;
touch-action: none;
}
#viewport canvas.webgl:active {
cursor: grabbing;
}
.scene-overlay {
position: absolute;
z-index: 3;
pointer-events: none;
}
.scene-overlay.top {
top: 16px;
left: 16px;
right: 16px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 14px;
}
.scene-heading {
padding: 10px 12px;
border: 1px solid rgba(91, 120, 153, 0.32);
border-radius: 11px;
background: rgba(7, 13, 22, 0.76);
backdrop-filter: blur(8px);
}
.eyebrow {
color: var(--muted);
font-size: 0.64rem;
font-weight: 750;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.scene-heading strong {
display: block;
margin-top: 4px;
font-size: 0.9rem;
}
.legend {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 7px;
}
.legend-chip {
display: flex;
align-items: center;
gap: 7px;
padding: 7px 9px;
border: 1px solid rgba(91, 120, 153, 0.32);
border-radius: 999px;
background: rgba(7, 13, 22, 0.76);
color: #c7d5e6;
font-size: 0.7rem;
backdrop-filter: blur(8px);
}
.legend-dot {
width: 8px;
height: 8px;
border-radius: 50%;
box-shadow: 0 0 10px currentColor;
}
.legend-dot.dc {
color: var(--dc);
background: var(--dc);
}
.legend-dot.ac {
color: var(--ac);
background: var(--ac);
}
.scene-overlay.bottom {
left: 16px;
right: 16px;
bottom: 15px;
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 14px;
}
.instruction {
max-width: 360px;
padding: 9px 11px;
border: 1px solid rgba(91, 120, 153, 0.25);
border-radius: 10px;
background: rgba(7, 13, 22, 0.72);
color: #91a5bd;
font-size: 0.7rem;
line-height: 1.45;
backdrop-filter: blur(8px);
}
.instruction b {
color: #dbe9f8;
}
.status-stack {
display: flex;
gap: 8px;
}
.status-pill {
min-width: 112px;
padding: 8px 10px;
border: 1px solid rgba(91, 120, 153, 0.28);
border-radius: 10px;
background: rgba(7, 13, 22, 0.76);
backdrop-filter: blur(8px);
}
.status-pill span {
display: block;
color: var(--muted);
font-size: 0.6rem;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.status-pill strong {
display: block;
margin-top: 3px;
font-size: 0.8rem;
}
.status-pill.dc strong {
color: var(--dc);
}
.status-pill.ac strong {
color: var(--ac);
}
#loading {
position: absolute;
inset: 0;
z-index: 10;
display: grid;
place-items: center;
background: #09111c;
color: var(--muted);
font-size: 0.82rem;
letter-spacing: 0.08em;
text-transform: uppercase;
transition: opacity 250ms ease;
}
.charts-panel {
display: grid;
grid-template-rows: 1fr 1fr;
gap: 16px;
min-width: 0;
}
.chart-card {
display: flex;
flex-direction: column;
min-height: 0;
}
.chart-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 15px 16px 10px;
border-bottom: 1px solid rgba(62, 83, 108, 0.42);
}
.chart-title {
display: flex;
align-items: center;
gap: 9px;
}
.chart-title i {
width: 10px;
height: 10px;
border-radius: 3px;
transform: rotate(45deg);
}
.chart-title i.dc {
background: var(--dc);
box-shadow: 0 0 12px rgba(85, 227, 255, 0.7);
}
.chart-title i.ac {
background: var(--ac);
box-shadow: 0 0 12px rgba(255, 180, 94, 0.7);
}
.chart-title h2 {
margin: 0;
font-size: 0.88rem;
letter-spacing: 0.025em;
}
.chart-title p {
margin: 3px 0 0;
color: var(--muted);
font-size: 0.65rem;
}
.readout {
text-align: right;
}
.readout strong {
display: block;
font-size: 1rem;
font-variant-numeric: tabular-nums;
}
.readout span {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 0.61rem;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.chart-card.dc .readout strong {
color: var(--dc);
}
.chart-card.ac .readout strong {
color: var(--ac);
}
.plot-wrap {
position: relative;
flex: 1;
min-height: 180px;
}
.plot-wrap canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
}
.chart-foot {
padding: 0 16px 12px;
color: #71869f;
font-size: 0.64rem;
}
@media (max-width: 1050px) {
.workspace {
grid-template-columns: 1fr;
height: auto;
min-height: 0;
}
.scene-panel {
height: 650px;
}
.charts-panel {
height: 700px;
}
}
@media (max-width: 700px) {
.app {
padding: 10px;
}
.topbar {
align-items: flex-start;
flex-direction: column;
gap: 13px;
}
.controls {
justify-content: flex-start;
width: 100%;
}
.scene-panel {
height: 570px;
}
.scene-overlay.top,
.scene-overlay.bottom {
left: 10px;
right: 10px;
}
.legend {
max-width: 170px;
}
.scene-heading {
max-width: 180px;
}
.instruction {
display: none;
}
.status-stack {
width: 100%;
}
.status-pill {
flex: 1;
}
.charts-panel {
height: 650px;
}
}
</style>
</head>
<body>
<div class="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>CURRENT LAB</h1>
<p class="subtitle">Direct and alternating electric current · low-poly simulation</p>
</div>
</div>
<div class="controls">
<button class="control-button primary" id="playButton" type="button">Pause</button>
<label class="speed-control" for="speed">
Speed
<input id="speed" type="range" min="0.25" max="2" step="0.25" value="1">
<output id="speedValue" for="speed">1.00×</output>
</label>
<label class="toggle">
<input id="showCharges" type="checkbox" checked>
Charge packets
</label>
<button class="control-button" id="resetTime" type="button">Reset time</button>
<button class="control-button" id="resetView" type="button">Reset view</button>
</div>
</header>
<main class="workspace">
<section class="scene-panel" aria-label="Interactive three-dimensional circuit loops">
<div id="viewport">
<div id="loading">Loading 3D circuits…</div>
</div>
<div class="scene-overlay top">
<div class="scene-heading">
<div class="eyebrow">Virtual circuit bench</div>
<strong>Observe the direction of charge flow</strong>
</div>
<div class="legend">
<div class="legend-chip">
<span class="legend-dot dc"></span>
Direct current
</div>
<div class="legend-chip">
<span class="legend-dot ac"></span>
Alternating current
</div>
</div>
</div>
<div class="scene-overlay bottom">
<div class="instruction">
<b>Drag</b> to orbit the camera · <b>scroll or pinch</b> to zoom.
Cyan arrows stay one way; amber arrows reverse when the AC current changes sign.
</div>
<div class="status-stack">
<div class="status-pill dc">
<span>Direct loop</span>
<strong>ONE WAY</strong>
</div>
<div class="status-pill ac">
<span>Alternating loop</span>
<strong id="flowStatus">FORWARD</strong>
</div>
</div>
</div>
</section>
<aside class="charts-panel" aria-label="Current versus time graphs">
<section class="chart-card dc">
<div class="chart-header">
<div class="chart-title">
<i class="dc"></i>
<div>
<h2>Direct current</h2>
<p>Constant magnitude and direction</p>
</div>
</div>
<div class="readout">
<strong id="dcValue">+1.00 A</strong>
<span>DC</span>
</div>
</div>
<div class="plot-wrap">
<canvas id="dcPlot" aria-label="Direct current versus time graph"></canvas>
</div>
<div class="chart-foot">Rolling 8-second window · positive current remains positive.</div>
</section>
<section class="chart-card ac">
<div class="chart-header">
<div class="chart-title">
<i class="ac"></i>
<div>
<h2>Alternating current</h2>
<p>Sinusoidal magnitude with reversing direction</p>
</div>
</div>
<div class="readout">
<strong id="acValue">+1.00 A</strong>
<span id="acDirection">FORWARD</span>
</div>
</div>
<div class="plot-wrap">
<canvas id="acPlot" aria-label="Alternating current versus time graph"></canvas>
</div>
<div class="chart-foot">Negative current means the charge flow has reversed.</div>
</section>
</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";
const $ = (selector) => document.querySelector(selector);
const viewport = $("#viewport");
const loading = $("#loading");
const playButton = $("#playButton");
const speedInput = $("#speed");
const speedValue = $("#speedValue");
const showCharges = $("#showCharges");
const dcValue = $("#dcValue");
const acValue = $("#acValue");
const acDirection = $("#acDirection");
const flowStatus = $("#flowStatus");
const COLORS = {
dc: 0x55e3ff,
acPositive: 0xffb45e,
acNegative: 0xff637d,
wireNode: 0xb9cde1
};
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x080e18);
scene.fog = new THREE.FogExp2(0x080e18, 0.026);
const camera = new THREE.PerspectiveCamera(39, 1, 0.1, 60);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.domElement.className = "webgl";
renderer.domElement.setAttribute(
"aria-label",
"Three-dimensional direct-current and alternating-current circuit loops"
);
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
viewport.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xb9ddff, 0x172033, 2.25);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(3.5, 7, 5.5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -6;
keyLight.shadow.camera.right = 6;
keyLight.shadow.camera.top = 5;
keyLight.shadow.camera.bottom = -5;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 20;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x55dfff, 1.5);
rimLight.position.set(-5, 3, -4);
scene.add(rimLight);
const warmLight = new THREE.DirectionalLight(0xff9e57, 1.1);
warmLight.position.set(4, 2, -3);
scene.add(warmLight);
const grid = new THREE.GridHelper(12, 24, 0x2b3c53, 0x142033);
grid.position.y = -0.16;
grid.material.transparent = true;
grid.material.opacity = 0.34;
scene.add(grid);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(30, 30),
new THREE.MeshStandardMaterial({
color: 0x080e17,
roughness: 0.95,
metalness: 0.02
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.18;
floor.receiveShadow = true;
scene.add(floor);
// Small utility functions.
function clamp(value, min, max) {
return Math.min(max, Math.max(min, value));
}
function mod(value, divisor) {
return ((value % divisor) + divisor) % divisor;
}
function roundedRect(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + width, y, x + width, y + height, r);
ctx.arcTo(x + width, y + height, x, y + height, r);
ctx.arcTo(x, y + height, x, y, r);
ctx.arcTo(x, y, x + width, y, r);
ctx.closePath();
}
function makeBadge(text, color, options = {}) {
const canvas = document.createElement("canvas");
canvas.width = options.width || 512;
canvas.height = options.height || 128;
const ctx = canvas.getContext("2d");
const cssColor = `#${new THREE.Color(color).getHexString()}`;
roundedRect(ctx, 5, 5, canvas.width - 10, canvas.height - 10, 20);
ctx.fillStyle = "rgba(7, 14, 24, 0.90)";
ctx.fill();
ctx.lineWidth = 5;
ctx.strokeStyle = cssColor;
ctx.globalAlpha = 0.8;
ctx.stroke();
ctx.globalAlpha = 1;
ctx.fillStyle = cssColor;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = `800 ${options.fontSize || 42}px system-ui, sans-serif`;
ctx.fillText(text, canvas.width / 2, canvas.height / 2 + 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(options.scaleX || 1.55, options.scaleY || 0.39, 1);
sprite.renderOrder = 20;
return sprite;
}
function makeRod(a, b, radius, material, parent, radialSegments = 6) {
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
const geometry = new THREE.CylinderGeometry(
radius,
radius,
length,
radialSegments,
1,
false
);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeCircuit({ x, kind, color, label }) {
const group = new THREE.Group();
group.position.x = x;
scene.add(group);
const isDC = kind === "dc";
const plinthMaterial = new THREE.MeshStandardMaterial({
color: isDC ? 0x102332 : 0x29231e,
roughness: 0.82,
metalness: 0.18,
flatShading: true
});
const plinth = new THREE.Mesh(
new THREE.BoxGeometry(2.75, 0.12, 2.08),
plinthMaterial
);
plinth.position.y = -0.07;
plinth.receiveShadow = true;
plinth.castShadow = true;
group.add(plinth);
const trimMaterial = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.22,
roughness: 0.45,
metalness: 0.45,
flatShading: true
});
const wireMaterial = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.18,
roughness: 0.38,
metalness: 0.65,
flatShading: true
});
const terminalMaterial = new THREE.MeshStandardMaterial({
color: 0xd9e7f4,
emissive: 0x86a6c4,
emissiveIntensity: 0.12,
roughness: 0.3,
metalness: 0.82,
flatShading: true
});
const nodeMaterial = new THREE.MeshStandardMaterial({
color: COLORS.wireNode,
roughness: 0.3,
metalness: 0.8,
flatShading: true
});
// The source occupies the final section of the loop.
const points = [
new THREE.Vector3(-0.36, 0.25, 0.74),
new THREE.Vector3(-0.92, 0.25, 0.74),
new THREE.Vector3(-1.12, 0.25, 0.54),
new THREE.Vector3(-1.12, 0.25, -0.55),
new THREE.Vector3(-0.92, 0.25, -0.74),
new THREE.Vector3(0.92, 0.25, -0.74),
new THREE.Vector3(1.12, 0.25, -0.55),
new THREE.Vector3(1.12, 0.25, 0.54),
new THREE.Vector3(0.92, 0.25, 0.74),
new THREE.Vector3(0.36, 0.25, 0.74)
];
// Wire sections, with the source bridging the final gap.
for (let i = 0; i < points.length - 1; i++) {
makeRod(points[i], points[i + 1], 0.065, wireMaterial, group);
}
makeRod(
new THREE.Vector3(-0.36, 0.25, 0.74),
new THREE.Vector3(-0.25, 0.25, 0.74),
0.075,
terminalMaterial,
group
);
makeRod(
new THREE.Vector3(0.25, 0.25, 0.74),
new THREE.Vector3(0.36, 0.25, 0.74),
0.075,
terminalMaterial,
group
);
const nodeGeometry = new THREE.OctahedronGeometry(0.092, 0);
for (let i = 1; i < points.length - 1; i++) {
const node = new THREE.Mesh(nodeGeometry, nodeMaterial);
node.position.copy(points[i]);
node.position.y += 0.015;
node.castShadow = true;
group.add(node);
}
// Four low-poly supports make the circuit read as a physical bench model.
const supportMaterial = new THREE.MeshStandardMaterial({
color: 0x405267,
roughness: 0.65,
metalness: 0.55,
flatShading: true
});
for (const index of [2, 3, 6, 7]) {
const p = points[index];
makeRod(
new THREE.Vector3(p.x, 0.01, p.z),
new THREE.Vector3(p.x, 0.22, p.z),
0.035,
supportMaterial,
group
);
}
// Source / battery / AC generator.
let rotor = null;
if (isDC) {
const batteryMaterial = new THREE.MeshStandardMaterial({
color: 0x244a5e,
roughness: 0.48,
metalness: 0.38,
flatShading: true
});
const battery = new THREE.Mesh(
new THREE.BoxGeometry(0.5, 0.56, 0.46),
batteryMaterial
);
battery.position.set(0, 0.47, 0.74);
battery.castShadow = true;
battery.receiveShadow = true;
group.add(battery);
const cap = new THREE.Mesh(
new THREE.BoxGeometry(0.54, 0.08, 0.5),
trimMaterial
);
cap.position.set(0, 0.78, 0.74);
cap.castShadow = true;
group.add(cap);
const plus = makeBadge("+", 0x55e3ff, {
width: 128,
height: 128,
fontSize: 68,
scaleX: 0.24,
scaleY: 0.24
});
plus.position.set(-0.2, 1.08, 0.74);
group.add(plus);
const minus = makeBadge("−", 0xb9cde1, {
width: 128,
height: 128,
fontSize: 68,
scaleX: 0.24,
scaleY: 0.24
});
minus.position.set(0.2, 1.08, 0.74);
group.add(minus);
} else {
const generatorMaterial = new THREE.MeshStandardMaterial({
color: 0x59422c,
roughness: 0.52,
metalness: 0.42,
flatShading: true
});
const generator = new THREE.Mesh(
new THREE.CylinderGeometry(0.3, 0.32, 0.56, 8),
generatorMaterial
);
generator.position.set(0, 0.48, 0.74);
generator.castShadow = true;
generator.receiveShadow = true;
group.add(generator);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.25, 0.045, 6, 18),
trimMaterial
);
ring.rotation.x = Math.PI / 2;
ring.position.set(0, 0.79, 0.74);
ring.castShadow = true;
group.add(ring);
rotor = new THREE.Mesh(
new THREE.OctahedronGeometry(0.145, 0),
trimMaterial
);
rotor.position.set(0, 0.91, 0.74);
rotor.castShadow = true;
group.add(rotor);
const wave = makeBadge("~", COLORS.acPositive, {
width: 128,
height: 128,
fontSize: 68,
scaleX: 0.24,
scaleY: 0.24
});
wave.position.set(0, 1.18, 0.74);
group.add(wave);
}
const labelBadge = makeBadge(label, color, {
fontSize: 39,
scaleX: 1.58,
scaleY: 0.4
});
labelBadge.position.set(0, 0.83, -1.0);
group.add(labelBadge);
// Precompute path lengths for smooth particle motion.
const segmentLengths = [];
let totalLength = 0;
for (let i = 0; i < points.length; i++) {
const a = points[i];
const b = points[(i + 1) % points.length];
const length = a.distanceTo(b);
segmentLengths.push(length);
totalLength += length;
}
function samplePath(distance) {
let d = mod(distance, totalLength);
for (let i = 0; i < segmentLengths.length; i++) {
const length = segmentLengths[i];
if (d <= length) {
const a = points[i];
const b = points[(i + 1) % points.length];
const fraction = d / length;
const position = a.clone().lerp(b, fraction);
const tangent = b.clone().sub(a).normalize();
return { position, tangent };
}
d -= length;
}
return {
position: points[0].clone(),
tangent: points[1].clone().sub(points[0]).normalize()
};
}
// Moving charge packets.
const chargeMaterial = new THREE.MeshStandardMaterial({
color: isDC ? 0xd8fbff : 0xffedcf,
emissive: color,
emissiveIntensity: 1.25,
roughness: 0.25,
metalness: 0.25,
flatShading: true
});
const chargeGeometry = new THREE.IcosahedronGeometry(0.072, 0);
const particles = [];
for (let i = 0; i < 14; i++) {
const particle = new THREE.Mesh(chargeGeometry, chargeMaterial);
particle.castShadow = true;
group.add(particle);
particles.push({
mesh: particle,
offset: (i / 14) * totalLength
});
}
// Four-sided cone arrowheads visibly rotate to show flow direction.
const arrowMaterial = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.65,
roughness: 0.4,
metalness: 0.45,
transparent: true,
opacity: 0.95,
flatShading: true
});
const arrowGeometry = new THREE.ConeGeometry(0.115, 0.29, 4);
const arrows = [];
const arrowFractions = [0.09, 0.29, 0.5, 0.7, 0.86];
for (const fraction of arrowFractions) {
const arrow = new THREE.Mesh(arrowGeometry, arrowMaterial);
arrow.castShadow = true;
group.add(arrow);
arrows.push({ mesh: arrow, fraction });
}
return {
kind,
group,
points,
segmentLengths,
totalLength,
samplePath,
particles,
arrows,
chargeMaterial,
arrowMaterial,
rotor,
phase: 0,
current: 1,
flowSign: 1
};
}
const circuits = [
makeCircuit({
x: -1.62,
kind: "dc",
color: COLORS.dc,
label: "DIRECT CURRENT"
}),
makeCircuit({
x: 1.62,
kind: "ac",
color: COLORS.acPositive,
label: "ALTERNATING CURRENT"
})
];
// Custom camera controls: orbit by dragging and zoom by wheel/pinch.
const cameraState = {
radius: 7.25,
theta: 0,
phi: 0.84,
target: new THREE.Vector3(0, 0.25, 0)
};
const defaultCamera = { ...cameraState };
function updateCamera() {
const responsiveScale =
camera.aspect < 0.9 ? 1.48 :
camera.aspect < 1.2 ? 1.18 : 1;
const radius = cameraState.radius * responsiveScale;
const sinPhiRadius = Math.sin(cameraState.phi) * radius;
camera.position.set(
cameraState.target.x + sinPhiRadius * Math.sin(cameraState.theta),
cameraState.target.y + Math.cos(cameraState.phi) * radius,
cameraState.target.z + sinPhiRadius * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.radius = defaultCamera.radius;
cameraState.theta = defaultCamera.theta;
cameraState.phi = defaultCamera.phi;
cameraState.target.copy(defaultCamera.target);
updateCamera();
}
const pointers = new Map();
let lastPointer = null;
let lastPinchDistance = null;
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 1) {
lastPointer = {
x: event.clientX,
y: event.clientY
};
}
if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
lastPinchDistance = Math.hypot(a.x - b.x, a.y - b.y);
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointers.has(event.pointerId)) return;
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 1 && lastPointer) {
const dx = event.clientX - lastPointer.x;
const dy = event.clientY - lastPointer.y;
cameraState.theta -= dx * 0.006;
cameraState.phi = clamp(cameraState.phi - dy * 0.005, 0.3, 1.32);
lastPointer = {
x: event.clientX,
y: event.clientY
};
} else if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
const distance = Math.hypot(a.x - b.x, a.y - b.y);
if (lastPinchDistance) {
cameraState.radius = clamp(
cameraState.radius * (lastPinchDistance / distance),
4.5,
11
);
}
lastPinchDistance = distance;
}
updateCamera();
});
function endPointer(event) {
pointers.delete(event.pointerId);
if (pointers.size < 2) {
lastPinchDistance = null;
}
if (pointers.size === 1) {
const remaining = [...pointers.values()][0];
lastPointer = { x: remaining.x, y: remaining.y };
} else {
lastPointer = null;
}
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
4.5,
11
);
updateCamera();
},
{ passive: false }
);
function resizeScene() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
updateCamera();
}
if ("ResizeObserver" in window) {
new ResizeObserver(resizeScene).observe(viewport);
}
window.addEventListener("resize", resizeScene);
resizeScene();
let simulationTime = 0;
let speed = 1;
let paused = false;
const AC_PERIOD = 4;
const AC_OMEGA = (Math.PI * 2) / AC_PERIOD;
const AC_PHASE = Math.PI / 2;
function acCurrent(time) {
return Math.sin(AC_OMEGA * time + AC_PHASE);
}
function formatCurrent(value) {
if (Math.abs(value) < 0.005) return "0.00 A";
return `${value >= 0 ? "+" : "−"}${Math.abs(value).toFixed(2)} A`;
}
function updateCircuit(circuit, dt) {
const current =
circuit.kind === "dc"
? 1
: acCurrent(simulationTime);
circuit.current = current;
if (Math.abs(current) > 0.025) {
circuit.flowSign = Math.sign(current);
}
// The signed phase makes charges reverse exactly when the current changes sign.
circuit.phase = mod(
circuit.phase + current * dt * 1.05,
circuit.totalLength
);
for (const particle of circuit.particles) {
const sample = circuit.samplePath(circuit.phase + particle.offset);
particle.mesh.position.copy(sample.position);
particle.mesh.position.y += 0.13;
particle.mesh.visible = showCharges.checked;
}
const up = new THREE.Vector3(0, 1, 0);
for (const arrow of circuit.arrows) {
const sample = circuit.samplePath(
arrow.fraction * circuit.totalLength
);
const direction = sample.tangent.clone().multiplyScalar(circuit.flowSign);
arrow.mesh.position.copy(sample.position);
arrow.mesh.position.y += 0.21;
arrow.mesh.quaternion.setFromUnitVectors(up, direction);
}
if (circuit.kind === "ac") {
const positive = new THREE.Color(COLORS.acPositive);
const negative = new THREE.Color(COLORS.acNegative);
const displayColor = current < 0 ? negative : positive;
circuit.arrowMaterial.color.copy(displayColor);
circuit.arrowMaterial.emissive.copy(displayColor);
circuit.arrowMaterial.opacity = 0.38 + Math.abs(current) * 0.62;
circuit.chargeMaterial.emissive.copy(displayColor);
circuit.chargeMaterial.emissiveIntensity = 0.65 + Math.abs(current) * 0.9;
if (circuit.rotor) {
circuit.rotor.rotation.y += dt * 2.4;
circuit.rotor.rotation.x += dt * 1.1;
}
} else {
circuit.chargeMaterial.emissiveIntensity = 1.2;
}
}
function preparePlot(canvas) {
const rect = canvas.getBoundingClientRect();
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const width = Math.max(1, Math.round(rect.width * dpr));
const height = Math.max(1, Math.round(rect.height * dpr));
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
}
const ctx = canvas.getContext("2d");
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, rect.width, rect.height);
return { ctx, width: rect.width, height: rect.height };
}
function drawPlot(canvas, kind) {
const { ctx, width, height } = preparePlot(canvas);
if (width < 10 || height < 10) return;
const isDC = kind === "dc";
const lineColor = isDC ? "#55e3ff" : "#ffb45e";
const reverseColor = "#ff637d";
const maxCurrent = 1.35;
const margin = { left: 39, right: 12, top: 14, bottom: 29 };
const plotWidth = width - margin.left - margin.right;
const plotHeight = height - margin.top - margin.bottom;
if (plotWidth <= 0 || plotHeight <= 0) return;
const mapY = (value) =>
margin.top + ((maxCurrent - value) / (maxCurrent * 2)) * plotHeight;
const zeroY = mapY(0);
const startTime = simulationTime - 8;
// Positive and negative current regions.
ctx.fillStyle = "rgba(85, 227, 255, 0.035)";
ctx.fillRect(
margin.left,
margin.top,
plotWidth,
Math.max(0, zeroY - margin.top)
);
ctx.fillStyle = "rgba(255, 99, 125, 0.04)";
ctx.fillRect(
margin.left,
zeroY,
plotWidth,
Math.max(0, margin.top + plotHeight - zeroY)
);
// Grid.
ctx.lineWidth = 1;
ctx.font = "10px system-ui, sans-serif";
ctx.textBaseline = "middle";
for (const value of [1, 0, -1]) {
const y = mapY(value);
ctx.strokeStyle = value === 0
? "rgba(151, 172, 198, 0.42)"
: "rgba(79, 101, 128, 0.25)";
ctx.beginPath();
ctx.moveTo(margin.left, y);
ctx.lineTo(width - margin.right, y);
ctx.stroke();
ctx.fillStyle = value === 0 ? "#9fb0c5" : "#647991";
ctx.textAlign = "right";
ctx.fillText(
value > 0 ? "+1" : value < 0 ? "−1" : "0",
margin.left - 7,
y
);
}
ctx.textAlign = "center";
ctx.fillStyle = "#61758d";
ctx.fillText("A", margin.left - 19, margin.top + 5);
for (const fraction of [0, 0.5, 1]) {
const x = margin.left + fraction * plotWidth;
ctx.strokeStyle = "rgba(79, 101, 128, 0.2)";
ctx.beginPath();
ctx.moveTo(x, margin.top);
ctx.lineTo(x, margin.top + plotHeight);
ctx.stroke();
const label = fraction === 0 ? "−8 s" : fraction === 0.5 ? "−4 s" : "now";
ctx.fillStyle = fraction === 1 ? "#aabbd0" : "#61758d";
ctx.fillText(label, x, height - 10);
}
// Signal.
const gradient = ctx.createLinearGradient(0, margin.top, 0, margin.top + plotHeight);
gradient.addColorStop(0, isDC ? "rgba(85,227,255,0.18)" : "rgba(255,180,94,0.16)");
gradient.addColorStop(0.5, "rgba(85,227,255,0.025)");
gradient.addColorStop(1, "rgba(255,99,125,0.09)");
ctx.beginPath();
for (let px = 0; px <= plotWidth; px += 1.5) {
const time = startTime + (px / plotWidth) * 8;
const value = isDC ? 1 : acCurrent(time);
const x = margin.left + px;
const y = mapY(value);
if (px === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
ctx.save();
ctx.lineTo(width - margin.right, zeroY);
ctx.lineTo(margin.left, zeroY);
ctx.closePath();
ctx.fillStyle = gradient;
ctx.fill();
ctx.restore();
ctx.beginPath();
for (let px = 0; px <= plotWidth; px += 1.5) {
const time = startTime + (px / plotWidth) * 8;
const value = isDC ? 1 : acCurrent(time);
const x = margin.left + px;
const y = mapY(value);
if (px === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
ctx.strokeStyle = lineColor;
ctx.lineWidth = 2.4;
ctx.shadowBlur = 8;
ctx.shadowColor = lineColor;
ctx.stroke();
ctx.shadowBlur = 0;
// Live cursor at the right edge.
const current = isDC ? 1 : acCurrent(simulationTime);
const cursorX = width - margin.right;
const cursorY = mapY(current);
ctx.strokeStyle = "rgba(215, 231, 247, 0.42)";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(cursorX, margin.top);
ctx.lineTo(cursorX, margin.top + plotHeight);
ctx.stroke();
ctx.fillStyle = !isDC && current < 0 ? reverseColor : lineColor;
ctx.beginPath();
ctx.arc(cursorX, cursorY, 4.2, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = "rgba(255,255,255,0.75)";
ctx.lineWidth = 1;
ctx.stroke();
}
function updateReadouts() {
const alternating = acCurrent(simulationTime);
const direction =
Math.abs(alternating) < 0.025
? "ZERO CROSSING"
: alternating > 0
? "FORWARD"
: "REVERSED";
dcValue.textContent = formatCurrent(1);
acValue.textContent = formatCurrent(alternating);
acValue.style.color = alternating < 0 ? "#ff637d" : "#ffb45e";
acDirection.textContent = direction;
flowStatus.textContent = direction;
flowStatus.style.color =
alternating < 0 ? "#ff637d" :
Math.abs(alternating) < 0.025 ? "#9bacc1" :
"#ffb45e";
}
playButton.addEventListener("click", () => {
paused = !paused;
playButton.textContent = paused ? "Play" : "Pause";
});
speedInput.addEventListener("input", () => {
speed = Number(speedInput.value);
speedValue.textContent = `${speed.toFixed(2)}×`;
});
$("#resetTime").addEventListener("click", () => {
simulationTime = 0;
for (const circuit of circuits) {
circuit.phase = 0;
circuit.flowSign = 1;
}
});
$("#resetView").addEventListener("click", resetCamera);
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const realDelta = Math.min(clock.getDelta(), 0.05);
const simulationDelta = paused ? 0 : realDelta * speed;
if (!paused) {
simulationTime += simulationDelta;
}
for (const circuit of circuits) {
updateCircuit(circuit, simulationDelta);
}
updateReadouts();
drawPlot($("#dcPlot"), "dc");
drawPlot($("#acPlot"), "ac");
renderer.render(scene, camera);
}
animate();
requestAnimationFrame(() => {
loading.style.opacity = "0";
setTimeout(() => loading.remove(), 260);
});
</script>
</body>
</html>
```