Prompt specification
Build or customize the Three.js 3D scene "Solenoid polarity exploration rig" 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: Solenoid polarity exploration rig
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/solenoid-polarity-exploration-rig-x1672
Scene Description Prompt:
Make a low-poly Three.js scene in a self-contained HTML file using cdnjs: solenoid polarity exploration rig. Allow reversing current and changing turn density in a simplified coil model; update field direction and magnitude consistently and explicitly distinguish electromagnet behavior from permanent magnetization.
Working Three.js Starter (solenoid-polarity-exploration-rig-x1672):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Solenoid Polarity Rig</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(9, 23, 39, 0.88);
--panel-border: rgba(142, 190, 224, 0.2);
--text: #e8f2fb;
--muted: #91a9bd;
--cyan: #54e5ff;
--amber: #ffb454;
--pink: #ff65a8;
--north: #ff6878;
--south: #5b91ff;
}
* {
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;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
}
header {
position: absolute;
top: 22px;
left: 24px;
max-width: 520px;
text-shadow: 0 2px 16px #000;
}
.eyebrow {
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
h1 {
margin: 5px 0 6px;
font-size: clamp(25px, 3vw, 38px);
line-height: 1.05;
letter-spacing: -0.035em;
}
header p {
max-width: 460px;
margin: 0;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.panel {
border: 1px solid var(--panel-border);
border-radius: 16px;
background: var(--panel);
box-shadow:
0 16px 45px rgba(0, 0, 0, 0.32),
inset 0 1px rgba(255, 255, 255, 0.035);
backdrop-filter: blur(14px);
}
.controls {
position: absolute;
top: 18px;
right: 18px;
width: 338px;
max-height: calc(100vh - 36px);
padding: 15px;
overflow: auto;
pointer-events: auto;
scrollbar-width: thin;
scrollbar-color: #294157 transparent;
}
.control-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
.control-title strong {
font-size: 13px;
letter-spacing: 0.04em;
}
.small-tag {
border: 1px solid rgba(84, 229, 255, 0.25);
border-radius: 999px;
padding: 3px 7px;
color: var(--cyan);
background: rgba(84, 229, 255, 0.07);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.1em;
}
.segmented {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 5px;
padding: 4px;
border-radius: 11px;
background: rgba(0, 0, 0, 0.25);
}
.mode-btn {
min-height: 38px;
border: 0;
border-radius: 8px;
color: var(--muted);
background: transparent;
cursor: pointer;
font: inherit;
font-size: 12px;
font-weight: 750;
transition: 160ms ease;
}
.mode-btn:hover {
color: var(--text);
background: rgba(255, 255, 255, 0.04);
}
.mode-btn.active {
color: #04111d;
background: var(--cyan);
box-shadow: 0 3px 14px rgba(84, 229, 255, 0.2);
}
.pane {
margin-top: 14px;
}
.pane[hidden] {
display: none;
}
.control-label {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin: 12px 1px 8px;
color: #c6d6e4;
font-size: 12px;
}
output {
color: var(--text);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
font-weight: 700;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 7px 0 9px;
border-radius: 99px;
appearance: none;
-webkit-appearance: none;
background: #26384c;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 17px;
height: 17px;
border: 3px solid #d9f7ff;
border-radius: 50%;
appearance: none;
-webkit-appearance: none;
background: var(--cyan);
box-shadow: 0 0 0 4px rgba(84, 229, 255, 0.12);
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border: 3px solid #d9f7ff;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 0 4px rgba(84, 229, 255, 0.12);
}
.range-ends {
display: flex;
justify-content: space-between;
color: #668096;
font-size: 9px;
}
.button-row {
display: flex;
gap: 7px;
margin-top: 10px;
}
button.action {
flex: 1;
min-height: 34px;
border: 1px solid rgba(145, 190, 222, 0.18);
border-radius: 9px;
color: #d9e7f3;
background: rgba(255, 255, 255, 0.045);
cursor: pointer;
font: inherit;
font-size: 11px;
font-weight: 750;
transition: 150ms ease;
}
button.action:hover {
border-color: rgba(84, 229, 255, 0.45);
background: rgba(84, 229, 255, 0.09);
}
button.action.primary {
border-color: rgba(84, 229, 255, 0.35);
color: var(--cyan);
background: rgba(84, 229, 255, 0.08);
}
.hint {
margin: 10px 0 0;
color: #829bb0;
font-size: 10.5px;
line-height: 1.5;
}
.divider {
height: 1px;
margin: 14px 0;
background: rgba(145, 190, 222, 0.13);
}
.toggles {
display: grid;
gap: 8px;
}
.toggle {
display: flex;
align-items: center;
gap: 8px;
color: #bdd0df;
font-size: 11px;
cursor: pointer;
}
.toggle input {
width: 15px;
height: 15px;
margin: 0;
accent-color: var(--cyan);
}
.formula {
margin-top: 13px;
padding: 11px;
border: 1px solid rgba(84, 229, 255, 0.13);
border-radius: 10px;
background: rgba(84, 229, 255, 0.045);
}
#formulaText {
color: #dcecf7;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
line-height: 1.5;
}
#modelNote {
margin-top: 7px;
color: #829bb0;
font-size: 10px;
line-height: 1.5;
}
.metrics {
position: absolute;
bottom: 20px;
left: 22px;
display: grid;
grid-template-columns: repeat(4, minmax(116px, 1fr));
gap: 8px;
width: min(650px, calc(100vw - 390px));
pointer-events: auto;
}
.metric {
min-height: 84px;
padding: 11px 12px;
}
.metric > span {
display: block;
margin-bottom: 5px;
color: #7891a6;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.13em;
}
.metric strong {
display: block;
color: #f0f7fc;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 15px;
line-height: 1.3;
}
.metric small {
display: block;
margin-top: 3px;
color: #8ba3b6;
font-size: 9px;
}
.legend {
position: absolute;
right: 18px;
bottom: 20px;
width: 338px;
padding: 11px 13px;
}
.legend-row {
display: flex;
align-items: center;
gap: 8px;
margin: 6px 0;
color: #9db2c4;
font-size: 10px;
}
.swatch {
width: 22px;
height: 4px;
border-radius: 99px;
background: var(--cyan);
box-shadow: 0 0 9px currentColor;
}
.swatch.current {
color: var(--amber);
background: var(--amber);
}
.swatch.north {
width: 10px;
height: 10px;
color: var(--north);
background: var(--north);
}
.swatch.south {
width: 10px;
height: 10px;
color: var(--south);
background: var(--south);
}
.camera-help {
position: absolute;
top: 24px;
left: 50%;
transform: translateX(-50%);
padding: 7px 11px;
border: 1px solid rgba(145, 190, 222, 0.13);
border-radius: 99px;
color: #7891a6;
background: rgba(7, 17, 31, 0.55);
font-size: 9px;
white-space: nowrap;
}
@media (max-width: 900px) {
header {
max-width: calc(100vw - 380px);
}
.metrics {
grid-template-columns: repeat(2, 1fr);
width: min(360px, calc(100vw - 390px));
}
.legend {
display: none;
}
}
@media (max-width: 700px) {
header {
top: 13px;
left: 14px;
max-width: calc(100vw - 28px);
}
header p,
.camera-help {
display: none;
}
.controls {
top: 96px;
right: 10px;
left: 10px;
width: auto;
max-height: 48vh;
padding: 12px;
}
.metrics {
right: 10px;
bottom: 10px;
left: 10px;
grid-template-columns: repeat(4, minmax(135px, 1fr));
width: auto;
overflow-x: auto;
}
.metric {
min-width: 135px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive solenoid polarity scene"></canvas>
<div class="hud">
<header>
<div class="eyebrow">Interactive electromagnetism</div>
<h1>Solenoid Polarity Rig</h1>
<p>
Reverse the current, change winding density, and compare a current-driven
electromagnet with a permanently magnetized body.
</p>
</header>
<section class="panel controls" aria-label="Solenoid controls">
<div class="control-title">
<strong>RIG CONTROLS</strong>
<span class="small-tag">LIVE MODEL</span>
</div>
<div class="segmented" role="group" aria-label="Magnetic source mode">
<button class="mode-btn active" data-mode="electromagnet" aria-pressed="true">
Electromagnet
</button>
<button class="mode-btn" data-mode="permanent" aria-pressed="false">
Permanent magnet
</button>
</div>
<div class="pane" id="electromagnetPane">
<label class="control-label" for="currentInput">
<span>Coil current, I</span>
<output id="currentOutput">+3.2 A</output>
</label>
<input id="currentInput" type="range" min="-5" max="5" step="0.1" value="3.2">
<div class="range-ends">
<span>−5 A</span>
<span>0 A</span>
<span>+5 A</span>
</div>
<div class="button-row">
<button class="action primary" id="reverseCurrent">Reverse current</button>
<button class="action" id="zeroCurrent">Set to zero</button>
</div>
<label class="control-label" for="densityInput">
<span>Turn density, n</span>
<output id="densityOutput">180 turns/m</output>
</label>
<input id="densityInput" type="range" min="40" max="350" step="5" value="180">
<div class="range-ends">
<span>40 turns/m</span>
<span id="turnCount">≈ 43 turns / 24 cm</span>
<span>350 turns/m</span>
</div>
<p class="hint">
Positive current follows the winding and produces a field toward +X by
the right-hand rule.
</p>
</div>
<div class="pane" id="permanentPane" hidden>
<div class="button-row">
<button class="action primary" id="flipMagnet">Flip magnet poles</button>
</div>
<label class="control-label" for="remanenceInput">
<span>Remanent field, Bᵣ</span>
<output id="remanenceOutput">120 mT</output>
</label>
<input id="remanenceInput" type="range" min="40" max="200" step="5" value="120">
<div class="range-ends">
<span>40 mT</span>
<span>200 mT</span>
</div>
<p class="hint">
The coil is disconnected: I = 0 A. This field is caused by permanent
magnetization, not by current or turn density.
</p>
</div>
<div class="divider"></div>
<div class="toggles">
<label class="toggle">
<input id="fieldToggle" type="checkbox" checked>
Show magnetic field lines and arrows
</label>
<label class="toggle">
<input id="currentToggle" type="checkbox" checked>
Show current direction in the winding
</label>
<label class="toggle">
<input id="labelsToggle" type="checkbox" checked>
Show pole and compass labels
</label>
</div>
<div class="formula">
<div id="formulaText"></div>
<div id="modelNote"></div>
</div>
</section>
<section class="metrics" aria-label="Live measurements">
<div class="panel metric">
<span>FIELD AT CORE</span>
<strong id="fieldValue">0.000 mT</strong>
<small id="fieldDirection">No preferred direction</small>
</div>
<div class="panel metric">
<span>COIL CURRENT</span>
<strong id="currentMetric">+3.2 A</strong>
<small id="currentSub">Current-driven field</small>
</div>
<div class="panel metric">
<span id="densityMetricTitle">TURN DENSITY</span>
<strong id="densityMetric">180 turns/m</strong>
<small id="densitySub">Ideal long solenoid</small>
</div>
<div class="panel metric">
<span>POLARITY</span>
<strong id="poleValue">Right: N</strong>
<small id="poleSub">Left: S</small>
</div>
</section>
<aside class="panel legend" aria-label="Scene legend">
<div class="legend-row">
<span class="swatch" id="fieldSwatch"></span>
<span id="fieldLegend">Magnetic field toward +X</span>
</div>
<div class="legend-row">
<span class="swatch current"></span>
<span>Conventional current in the winding</span>
</div>
<div class="legend-row">
<span class="swatch north"></span>
<span>North pole / north-seeking end</span>
<span class="swatch south"></span>
<span>South pole</span>
</div>
</aside>
<div class="camera-help">DRAG TO ORBIT · SCROLL TO ZOOM · RIGHT PANEL TO EXPERIMENT</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const MU_0 = 4 * Math.PI * 1e-7;
const COIL_LENGTH_METERS = 0.24;
const COIL_LENGTH = 4.8;
const COIL_RADIUS = 0.62;
const COIL_Y = 1.55;
const PERMANENT_DEFAULT = 0.120;
const state = {
mode: "electromagnet",
current: 3.2,
density: 180,
permanentSign: 1,
permanentStrength: PERMANENT_DEFAULT,
showField: true,
showCurrent: true,
showLabels: true
};
const $ = (id) => document.getElementById(id);
const canvas = $("scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 13, 27);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
80
);
const cameraState = {
theta: 0.68,
phi: 1.04,
radius: 10.8,
targetTheta: 0.68,
targetPhi: 1.04,
targetRadius: 10.8,
target: new THREE.Vector3(0, 1.15, 0)
};
const hemisphere = new THREE.HemisphereLight(0xb8e7ff, 0x08101b, 2.15);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(4, 8, 6);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -7;
keyLight.shadow.camera.right = 7;
keyLight.shadow.camera.top = 7;
keyLight.shadow.camera.bottom = -7;
keyLight.shadow.bias = -0.0008;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4b9fff, 1.8);
rimLight.position.set(-6, 4, -5);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xff9e43, 15, 9, 2);
warmLight.position.set(0, 1.5, 3);
scene.add(warmLight);
function material(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.72,
metalness: 0.18,
flatShading: true,
...options
});
}
function addBox(width, height, depth, mat, x, y, z) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
mat
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
return mesh;
}
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 createSprite(text, color, width = 512, height = 128) {
const spriteCanvas = document.createElement("canvas");
spriteCanvas.width = width;
spriteCanvas.height = height;
const context = spriteCanvas.getContext("2d");
const texture = new THREE.CanvasTexture(spriteCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const spriteMaterial = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(spriteMaterial);
sprite.renderOrder = 10;
const entry = {
sprite,
canvas: spriteCanvas,
context,
texture,
lastKey: ""
};
updateSprite(entry, text, color);
return entry;
}
function updateSprite(entry, text, color = "#dcecf7") {
const key = `${text}|${color}`;
if (entry.lastKey === key) return;
entry.lastKey = key;
const ctx = entry.context;
const { width, height } = entry.canvas;
ctx.clearRect(0, 0, width, height);
roundedRect(ctx, 4, 4, width - 8, height - 8, 20);
ctx.fillStyle = "rgba(5, 16, 28, 0.84)";
ctx.fill();
ctx.lineWidth = 4;
ctx.strokeStyle = `${color}88`;
ctx.stroke();
ctx.fillStyle = color;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = `800 ${Math.floor(height * 0.43)}px ui-monospace, monospace`;
ctx.fillText(text, width / 2, height / 2 + 2);
entry.texture.needsUpdate = true;
}
// Floor and grid.
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(32, 32),
material(0x091524, { roughness: 0.96, metalness: 0 })
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.01;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(26, 26, 0x2a4863, 0x14283b);
grid.position.y = 0.006;
grid.material.transparent = true;
grid.material.opacity = 0.32;
scene.add(grid);
// Supports.
const supportMaterial = material(0x25384c, { metalness: 0.52 });
const supportAccent = material(0x49657e, { metalness: 0.55 });
for (const x of [-1.65, 1.65]) {
addBox(1.05, 0.16, 1.18, supportMaterial, x, 0.08, 0);
addBox(0.66, 0.14, 0.9, supportAccent, x, 1.23, 0);
const post = new THREE.Mesh(
new THREE.CylinderGeometry(0.14, 0.18, 1.06, 8),
supportMaterial
);
post.position.set(x, 0.68, 0);
post.castShadow = true;
scene.add(post);
}
// Core.
const coreMaterial = material(0x66798a, {
roughness: 0.48,
metalness: 0.64
});
const core = new THREE.Mesh(
new THREE.CylinderGeometry(0.34, 0.34, COIL_LENGTH, 12),
coreMaterial
);
core.rotation.z = Math.PI / 2;
core.position.y = COIL_Y;
core.castShadow = true;
core.receiveShadow = true;
scene.add(core);
const leftCapMaterial = material(0x435363, {
emissive: 0x000000,
metalness: 0.5
});
const rightCapMaterial = material(0x435363, {
emissive: 0x000000,
metalness: 0.5
});
function makeCap(x, mat) {
const cap = new THREE.Mesh(
new THREE.CylinderGeometry(0.39, 0.39, 0.1, 12),
mat
);
cap.rotation.z = Math.PI / 2;
cap.position.set(x, COIL_Y, 0);
cap.castShadow = true;
scene.add(cap);
}
makeCap(-COIL_LENGTH / 2 - 0.04, leftCapMaterial);
makeCap(COIL_LENGTH / 2 + 0.04, rightCapMaterial);
// Helical winding.
class HelixCurve extends THREE.Curve {
constructor(turns, radius, length, centerY) {
super();
this.turns = turns;
this.radius = radius;
this.length = length;
this.centerY = centerY;
}
getPoint(t, target = new THREE.Vector3()) {
const angle = t * this.turns * Math.PI * 2;
return target.set(
this.length * (t - 0.5),
this.centerY + this.radius * Math.cos(angle),
this.radius * Math.sin(angle)
);
}
}
const windingMaterial = material(0xc77836, {
roughness: 0.42,
metalness: 0.72,
emissive: 0xff7c25,
emissiveIntensity: 0.08
});
const coilMesh = new THREE.Mesh(
new THREE.BufferGeometry(),
windingMaterial
);
coilMesh.castShadow = true;
scene.add(coilMesh);
let helix = null;
let turnCount = 0;
const wireMeshes = [];
function rebuildCoil() {
turnCount = Math.max(6, Math.round(state.density * COIL_LENGTH_METERS));
helix = new HelixCurve(turnCount, COIL_RADIUS, COIL_LENGTH, COIL_Y);
coilMesh.geometry.dispose();
coilMesh.geometry = new THREE.TubeGeometry(
helix,
Math.max(160, turnCount * 10),
0.065,
5,
false
);
for (const wire of wireMeshes) {
scene.remove(wire);
wire.geometry.dispose();
}
wireMeshes.length = 0;
const start = helix.getPoint(0);
const end = helix.getPoint(1);
const leftPath = new THREE.CatmullRomCurve3([
start.clone(),
new THREE.Vector3(-2.82, start.y, start.z),
new THREE.Vector3(-3.08, 0.58, 1.15),
new THREE.Vector3(-0.82, 0.28, 2.18)
]);
const rightPath = new THREE.CatmullRomCurve3([
end.clone(),
new THREE.Vector3(2.82, end.y, end.z),
new THREE.Vector3(3.08, 0.58, 1.15),
new THREE.Vector3(0.82, 0.28, 2.18)
]);
const wireMaterial = material(0xa55e2d, {
roughness: 0.5,
metalness: 0.68
});
for (const path of [leftPath, rightPath]) {
const wire = new THREE.Mesh(
new THREE.TubeGeometry(path, 45, 0.045, 5, false),
wireMaterial
);
wire.castShadow = true;
scene.add(wire);
wireMeshes.push(wire);
}
$("turnCount").textContent =
`≈ ${turnCount} turns / 24 cm`;
}
// Animated current arrows.
const currentArrowGroup = new THREE.Group();
scene.add(currentArrowGroup);
const currentArrowMaterial = material(0xffb454, {
roughness: 0.38,
metalness: 0.15,
emissive: 0xff7a19,
emissiveIntensity: 1.5
});
const currentArrowGeometry = new THREE.ConeGeometry(0.075, 0.19, 5);
const currentArrows = [];
for (let i = 0; i < 18; i++) {
const arrow = new THREE.Mesh(
currentArrowGeometry,
currentArrowMaterial
);
arrow.renderOrder = 5;
currentArrowGroup.add(arrow);
currentArrows.push(arrow);
}
// Magnetic field curves. Their internal section runs left-to-right for +X B.
const fieldGroup = new THREE.Group();
scene.add(fieldGroup);
const fieldLineMaterial = new THREE.MeshBasicMaterial({
color: 0x54e5ff,
transparent: true,
opacity: 0.4,
depthTest: false,
depthWrite: false
});
const fieldArrowMaterial = new THREE.MeshBasicMaterial({
color: 0x54e5ff,
transparent: true,
opacity: 0.92,
depthTest: false,
depthWrite: false
});
const fieldCurves = [];
const fieldArrowRecords = [];
const fieldArrowGeometry = new THREE.ConeGeometry(0.075, 0.22, 5);
const fieldAngles = [0, Math.PI / 2, Math.PI, Math.PI * 1.5];
function radialPoint(x, radius, angle) {
return new THREE.Vector3(
x,
COIL_Y + Math.cos(angle) * radius,
Math.sin(angle) * radius
);
}
for (const angle of fieldAngles) {
const points = [
radialPoint(-2.25, 0.07, angle),
radialPoint(-1.5, 0.07, angle),
radialPoint(0, 0.07, angle),
radialPoint(1.5, 0.07, angle),
radialPoint(2.25, 0.07, angle),
radialPoint(2.52, 0.42, angle),
radialPoint(2.32, 0.88, angle),
radialPoint(1.25, 1.22, angle),
radialPoint(0, 1.37, angle),
radialPoint(-1.25, 1.22, angle),
radialPoint(-2.32, 0.88, angle),
radialPoint(-2.52, 0.42, angle)
];
const curve = new THREE.CatmullRomCurve3(
points,
true,
"catmullrom",
0.5
);
fieldCurves.push(curve);
const line = new THREE.Mesh(
new THREE.TubeGeometry(curve, 120, 0.018, 4, true),
fieldLineMaterial
);
line.renderOrder = 2;
fieldGroup.add(line);
for (const t of [0.08, 0.22, 0.35, 0.56, 0.73, 0.88]) {
const arrow = new THREE.Mesh(
fieldArrowGeometry,
fieldArrowMaterial
);
arrow.renderOrder = 4;
fieldGroup.add(arrow);
fieldArrowRecords.push({ curve, t, arrow });
}
}
// Pole labels.
const poleLeft = createSprite("S", "#5b91ff", 256, 128);
const poleRight = createSprite("N", "#ff6878", 256, 128);
poleLeft.sprite.scale.set(0.62, 0.31);
poleRight.sprite.scale.set(0.62, 0.31);
poleLeft.sprite.position.set(-2.92, COIL_Y, 0);
poleRight.sprite.position.set(2.92, COIL_Y, 0);
scene.add(poleLeft.sprite, poleRight.sprite);
// Compass, placed where the external field points opposite to the core field.
const compass = new THREE.Group();
compass.position.set(0, 3.02, 0.25);
scene.add(compass);
const compassRing = new THREE.Mesh(
new THREE.TorusGeometry(0.34, 0.045, 6, 20),
material(0x91a9bd, { metalness: 0.68, roughness: 0.38 })
);
compassRing.rotation.x = Math.PI / 2;
compass.add(compassRing);
const compassNeedle = new THREE.Group();
compass.add(compassNeedle);
const needleNorth = new THREE.Mesh(
new THREE.BoxGeometry(0.31, 0.045, 0.075),
material(0xff6878, {
emissive: 0x7b1520,
emissiveIntensity: 0.4
})
);
needleNorth.position.x = 0.15;
compassNeedle.add(needleNorth);
const needleSouth = new THREE.Mesh(
new THREE.BoxGeometry(0.31, 0.045, 0.075),
material(0x5b91ff, {
emissive: 0x102c78,
emissiveIntensity: 0.4
})
);
needleSouth.position.x = -0.15;
compassNeedle.add(needleSouth);
const compassLabel = createSprite(
"COMPASS",
"#a9c5d9",
512,
128
);
compassLabel.sprite.scale.set(1.25, 0.31);
compassLabel.sprite.position.set(0, 3.55, 0.25);
scene.add(compassLabel.sprite);
// Power supply and integrated display.
addBox(
1.85,
0.78,
1.22,
material(0x172a3d, { roughness: 0.6, metalness: 0.4 }),
0,
0.42,
2.4
);
addBox(
1.98,
0.12,
1.32,
material(0x38536a, { metalness: 0.58 }),
0,
0.86,
2.4
);
const powerCanvas = document.createElement("canvas");
powerCanvas.width = 512;
powerCanvas.height = 160;
const powerContext = powerCanvas.getContext("2d");
const powerTexture = new THREE.CanvasTexture(powerCanvas);
powerTexture.colorSpace = THREE.SRGBColorSpace;
const powerDisplay = new THREE.Mesh(
new THREE.PlaneGeometry(1.35, 0.42),
new THREE.MeshBasicMaterial({ map: powerTexture })
);
powerDisplay.position.set(-0.08, 0.54, 3.018);
scene.add(powerDisplay);
const ledMaterial = material(0x233b4e, {
emissive: 0x000000,
emissiveIntensity: 0
});
const led = new THREE.Mesh(
new THREE.SphereGeometry(0.075, 8, 6),
ledMaterial
);
led.position.set(0.72, 0.54, 3.025);
scene.add(led);
const powerLabel = createSprite(
"POWER SOURCE",
"#a9c5d9",
512,
128
);
powerLabel.sprite.scale.set(1.6, 0.4);
powerLabel.sprite.position.set(0, 1.22, 2.4);
scene.add(powerLabel.sprite);
function updatePowerDisplay() {
const ctx = powerContext;
ctx.clearRect(0, 0, 512, 160);
roundedRect(ctx, 4, 4, 504, 152, 18);
ctx.fillStyle = "#06131e";
ctx.fill();
ctx.lineWidth = 5;
ctx.strokeStyle = state.mode === "permanent"
? "#5b91ff88"
: "#54e5ff88";
ctx.stroke();
ctx.fillStyle = state.mode === "permanent"
? "#9fb9ff"
: "#69e9ff";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = "800 42px ui-monospace, monospace";
ctx.fillText(
state.mode === "permanent"
? "COIL OFF"
: `I = ${state.current >= 0 ? "+" : "−"}${Math.abs(state.current).toFixed(1)} A`,
256,
65
);
ctx.fillStyle = "#7891a6";
ctx.font = "700 19px ui-monospace, monospace";
ctx.fillText(
state.mode === "permanent"
? "PERMANENT MAGNET MODE"
: "CONVENTIONAL CURRENT",
256,
116
);
powerTexture.needsUpdate = true;
}
// Camera controls implemented locally, without Three.js addons.
let dragging = false;
let pointerX = 0;
let pointerY = 0;
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.targetTheta -= dx * 0.006;
cameraState.targetPhi = THREE.MathUtils.clamp(
cameraState.targetPhi - dy * 0.005,
0.28,
1.48
);
});
function stopDragging(event) {
dragging = false;
if (event.pointerId !== undefined && canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", stopDragging);
canvas.addEventListener("pointercancel", stopDragging);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.targetRadius = THREE.MathUtils.clamp(
cameraState.targetRadius * Math.exp(event.deltaY * 0.001),
6.3,
17
);
},
{ passive: false }
);
function signedField() {
if (state.mode === "permanent") {
return state.permanentSign * state.permanentStrength;
}
return MU_0 * state.density * state.current;
}
function formatField(value) {
const millitesla = value * 1000;
if (Math.abs(millitesla) < 0.0005) return "0.000 mT";
if (Math.abs(millitesla) < 0.1) {
return `${millitesla.toFixed(3)} mT`;
}
return `${millitesla.toFixed(Math.abs(millitesla) < 10 ? 2 : 1)} mT`;
}
function signedCurrent(value) {
return `${value >= 0 ? "+" : "−"}${Math.abs(value).toFixed(1)} A`;
}
function updateRangeBackground(input) {
const min = Number(input.min);
const max = Number(input.max);
const value = Number(input.value);
const percent = ((value - min) / (max - min)) * 100;
input.style.background =
`linear-gradient(90deg, #54e5ff 0%, #54e5ff ${percent}%, ` +
`#26384c ${percent}%, #26384c 100%)`;
}
const upVector = new THREE.Vector3(0, 1, 0);
const tempPoint = new THREE.Vector3();
const tempTangent = new THREE.Vector3();
const tempQuaternion = new THREE.Quaternion();
function updateSceneState() {
const field = signedField();
const magnitude = Math.abs(field);
const sign = Math.sign(field);
const isPermanent = state.mode === "permanent";
$("currentOutput").textContent = signedCurrent(state.current);
$("densityOutput").textContent = `${state.density} turns/m`;
$("remanenceOutput").textContent =
`${Math.round(state.permanentStrength * 1000)} mT`;
$("fieldValue").textContent = formatField(magnitude);
$("fieldDirection").textContent =
magnitude < 1e-12
? "No preferred direction"
: sign > 0
? "Toward +X"
: "Toward −X";
$("currentMetric").textContent = isPermanent
? "0 A"
: signedCurrent(state.current);
$("currentSub").textContent = isPermanent
? "Coil disconnected"
: "Current-driven field";
$("densityMetricTitle").textContent = isPermanent
? "REMANENT FIELD"
: "TURN DENSITY";
$("densityMetric").textContent = isPermanent
? `${Math.round(state.permanentStrength * 1000)} mT`
: `${state.density} turns/m`;
$("densitySub").textContent = isPermanent
? "Independent of coil current"
: `≈ ${turnCount} turns shown`;
if (magnitude < 1e-12) {
$("poleValue").textContent = "No poles";
$("poleSub").textContent = "Ideal field is zero";
} else if (sign > 0) {
$("poleValue").textContent = "Right: N";
$("poleSub").textContent = "Left: S";
} else {
$("poleValue").textContent = "Right: S";
$("poleSub").textContent = "Left: N";
}
if (isPermanent) {
$("formulaText").textContent =
`B = ${state.permanentSign > 0 ? "+" : "−"}Bᵣ = ` +
`${state.permanentSign > 0 ? "+" : "−"}` +
`${Math.round(state.permanentStrength * 1000)} mT`;
$("modelNote").textContent =
"Permanent magnetization: the field persists with I = 0 A. " +
"Flipping the magnet reverses B and swaps the poles; coil current " +
"and turn density do not determine this field.";
} else {
$("formulaText").textContent =
`B = μ₀ n I = (4π×10⁻⁷)(${state.density})(${state.current}) = ` +
`${formatField(field)}`;
$("modelNote").textContent =
"Electromagnet: current creates the field. Reverse I to reverse B " +
"and swap N/S. At I = 0 the ideal field vanishes. This is a long-" +
"solenoid approximation; fringing and core enhancement are ignored.";
}
const fieldColor = sign < 0 ? 0xff65a8 : 0x54e5ff;
fieldLineMaterial.color.setHex(fieldColor);
fieldArrowMaterial.color.setHex(fieldColor);
const reference = isPermanent
? state.permanentStrength
: MU_0 * 350 * 5;
const normalized = THREE.MathUtils.clamp(magnitude / reference, 0, 1);
fieldLineMaterial.opacity = 0.16 + normalized * 0.34;
fieldArrowMaterial.opacity = 0.66 + normalized * 0.34;
fieldGroup.visible = state.showField && magnitude > 1e-12;
const arrowScale = 0.65 + normalized * 0.48;
for (const record of fieldArrowRecords) {
const point = record.curve.getPoint(record.t, tempPoint);
const tangent = record.curve.getTangent(record.t, tempTangent).normalize();
// Positive field travels left-to-right inside the core.
if (sign < 0) tangent.negate();
record.arrow.position.copy(point);
tempQuaternion.setFromUnitVectors(upVector, tangent);
record.arrow.quaternion.copy(tempQuaternion);
record.arrow.scale.setScalar(arrowScale);
}
currentArrowGroup.visible =
state.showCurrent &&
!isPermanent &&
Math.abs(state.current) > 1e-8;
const currentAmount = Math.abs(state.current) / 5;
if (isPermanent) {
windingMaterial.color.setHex(0x596574);
windingMaterial.emissive.setHex(0x000000);
windingMaterial.emissiveIntensity = 0;
coreMaterial.color.setHex(0x69465c);
} else {
windingMaterial.color
.setHex(0x9f572b)
.lerp(new THREE.Color(0xe39345), 0.25 + currentAmount * 0.75);
windingMaterial.emissive.setHex(0xff7c25);
windingMaterial.emissiveIntensity = 0.05 + currentAmount * 0.5;
coreMaterial.color.setHex(0x66798a);
}
ledMaterial.emissive.setHex(
!isPermanent && Math.abs(state.current) > 1e-8
? 0x38d7ff
: 0x000000
);
ledMaterial.emissiveIntensity =
!isPermanent && Math.abs(state.current) > 1e-8
? 1.4
: 0;
const hasPole = magnitude > 1e-12;
poleLeft.sprite.visible = hasPole && state.showLabels;
poleRight.sprite.visible = hasPole && state.showLabels;
compassLabel.sprite.visible = state.showLabels;
compassNeedle.visible = hasPole;
if (hasPole) {
const leftIsNorth = sign < 0;
updateSprite(
poleLeft,
leftIsNorth ? "N" : "S",
leftIsNorth ? "#ff6878" : "#5b91ff"
);
updateSprite(
poleRight,
leftIsNorth ? "S" : "N",
leftIsNorth ? "#5b91ff" : "#ff6878"
);
leftCapMaterial.color.setHex(leftIsNorth ? 0xa72d42 : 0x2855a8);
leftCapMaterial.emissive.setHex(leftIsNorth ? 0x701323 : 0x102e7a);
leftCapMaterial.emissiveIntensity = 0.42;
rightCapMaterial.color.setHex(leftIsNorth ? 0x2855a8 : 0xa72d42);
rightCapMaterial.emissive.setHex(leftIsNorth ? 0x102e7a : 0x701323);
rightCapMaterial.emissiveIntensity = 0.42;
// At the compass position the external field is opposite the core field.
compassNeedle.rotation.y = sign > 0 ? Math.PI : 0;
} else {
leftCapMaterial.color.setHex(0x435363);
rightCapMaterial.color.setHex(0x435363);
leftCapMaterial.emissive.setHex(0x000000);
rightCapMaterial.emissive.setHex(0x000000);
leftCapMaterial.emissiveIntensity = 0;
rightCapMaterial.emissiveIntensity = 0;
}
$("fieldSwatch").style.background = sign < 0 ? "#ff65a8" : "#54e5ff";
$("fieldSwatch").style.color = sign < 0 ? "#ff65a8" : "#54e5ff";
$("fieldLegend").textContent =
magnitude < 1e-12
? "Magnetic field is zero"
: sign > 0
? "Magnetic field toward +X"
: "Magnetic field toward −X";
$("flipMagnet").textContent =
state.permanentSign > 0
? "Flip magnet poles"
: "Flip magnet poles · right is S";
updatePowerDisplay();
}
function updateModeUI() {
const isPermanent = state.mode === "permanent";
$("electromagnetPane").hidden = isPermanent;
$("permanentPane").hidden = !isPermanent;
document.querySelectorAll(".mode-btn").forEach((button) => {
const active = button.dataset.mode === state.mode;
button.classList.toggle("active", active);
button.setAttribute("aria-pressed", String(active));
});
}
document.querySelectorAll(".mode-btn").forEach((button) => {
button.addEventListener("click", () => {
state.mode = button.dataset.mode;
updateModeUI();
updateSceneState();
});
});
$("currentInput").addEventListener("input", (event) => {
state.current = Number(event.target.value);
updateRangeBackground(event.target);
updateSceneState();
});
$("densityInput").addEventListener("input", (event) => {
state.density = Number(event.target.value);
updateRangeBackground(event.target);
rebuildCoil();
updateSceneState();
});
$("remanenceInput").addEventListener("input", (event) => {
state.permanentStrength = Number(event.target.value) / 1000;
updateRangeBackground(event.target);
updateSceneState();
});
$("reverseCurrent").addEventListener("click", () => {
state.current = -state.current;
$("currentInput").value = String(state.current);
updateRangeBackground($("currentInput"));
updateSceneState();
});
$("zeroCurrent").addEventListener("click", () => {
state.current = 0;
$("currentInput").value = "0";
updateRangeBackground($("currentInput"));
updateSceneState();
});
$("flipMagnet").addEventListener("click", () => {
state.permanentSign *= -1;
updateSceneState();
});
$("fieldToggle").addEventListener("change", (event) => {
state.showField = event.target.checked;
updateSceneState();
});
$("currentToggle").addEventListener("change", (event) => {
state.showCurrent = event.target.checked;
updateSceneState();
});
$("labelsToggle").addEventListener("change", (event) => {
state.showLabels = event.target.checked;
updateSceneState();
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
});
// Initial state.
rebuildCoil();
updateModeUI();
updateRangeBackground($("currentInput"));
updateRangeBackground($("densityInput"));
updateRangeBackground($("remanenceInput"));
updateSceneState();
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
// Smooth camera movement.
const smoothing = 1 - Math.exp(-dt * 9);
cameraState.theta +=
(cameraState.targetTheta - cameraState.theta) * smoothing;
cameraState.phi +=
(cameraState.targetPhi - cameraState.phi) * smoothing;
cameraState.radius +=
(cameraState.targetRadius - cameraState.radius) * smoothing;
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPhi * Math.cos(cameraState.theta),
cameraState.target.y +
cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z +
cameraState.radius * sinPhi * Math.sin(cameraState.theta)
);
camera.lookAt(cameraState.target);
// Animate current markers along the winding.
if (currentArrowGroup.visible && helix) {
const direction = Math.sign(state.current);
const speed = 0.075 * direction;
currentArrows.forEach((arrow, index) => {
const base = index / currentArrows.length;
const t = ((base + elapsed * speed) % 1 + 1) % 1;
helix.getPoint(t, tempPoint);
helix.getTangent(t, tempTangent).normalize();
if (direction < 0) tempTangent.negate();
const angle = t * helix.turns * Math.PI * 2;
tempPoint.y += Math.cos(angle) * 0.095;
tempPoint.z += Math.sin(angle) * 0.095;
arrow.position.copy(tempPoint);
tempQuaternion.setFromUnitVectors(upVector, tempTangent);
arrow.quaternion.copy(tempQuaternion);
const pulse = 1 + Math.sin(elapsed * 6 + index) * 0.06;
arrow.scale.setScalar(pulse);
});
}
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```