Prompt specification
Build or customize the Three.js 3D scene "Generator parameter exploration bench" 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: Generator parameter exploration bench
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/generator-parameter-exploration-bench-x1640
Scene Description Prompt:
Create a standalone voxel scene in one HTML file using Three.js from cdnjs. Let users vary loop area, turn count, field strength, and angular speed; calculate ideal induced voltage and label mechanical and electrical loading effects omitted.
Working Three.js Starter (generator-parameter-exploration-bench-x1640):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Generator Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #071018;
--panel: rgba(10, 20, 29, 0.93);
--line: rgba(142, 202, 226, 0.16);
--text: #e8f4f8;
--muted: #8ca6b3;
--cyan: #58ddff;
--copper: #ffb05c;
--green: #78efb2;
--red: #ff6d68;
}
* {
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;
outline: none;
}
.brand {
position: fixed;
top: 20px;
left: 22px;
z-index: 5;
pointer-events: none;
}
.brand h1 {
margin: 0;
font-size: 18px;
font-weight: 800;
letter-spacing: 0.13em;
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.loading-badge {
display: inline-flex;
align-items: center;
gap: 8px;
margin-top: 13px;
padding: 7px 10px;
border: 1px solid rgba(255, 176, 92, 0.36);
border-radius: 5px;
background: rgba(48, 29, 10, 0.76);
color: #ffd29b;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
}
.loading-badge::before {
content: "";
width: 7px;
height: 7px;
border-radius: 2px;
background: var(--copper);
box-shadow: 0 0 12px rgba(255, 176, 92, 0.65);
}
.panel {
position: fixed;
z-index: 10;
top: 18px;
right: 18px;
width: 338px;
max-height: calc(100vh - 36px);
overflow-y: auto;
padding: 18px;
border: 1px solid var(--line);
border-radius: 12px;
background: var(--panel);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.38);
backdrop-filter: blur(15px);
}
.panel::-webkit-scrollbar {
width: 6px;
}
.panel::-webkit-scrollbar-thumb {
border-radius: 10px;
background: rgba(88, 221, 255, 0.25);
}
.eyebrow {
margin-bottom: 5px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.panel h2 {
margin: 0 0 6px;
font-size: 21px;
}
.subtitle {
margin: 0 0 18px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.control {
margin: 0 0 17px;
}
.control-heading {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 8px;
font-size: 12px;
}
.control-heading label {
color: #c8d8df;
font-weight: 650;
}
output {
color: var(--cyan);
font-variant-numeric: tabular-nums;
font-weight: 750;
white-space: nowrap;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 0;
border-radius: 10px;
appearance: none;
background:
linear-gradient(
90deg,
rgba(88, 221, 255, 0.7),
rgba(88, 221, 255, 0.1)
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 16px;
height: 16px;
border: 3px solid #09202a;
border-radius: 4px;
appearance: none;
background: var(--cyan);
box-shadow: 0 0 12px rgba(88, 221, 255, 0.45);
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border: 3px solid #09202a;
border-radius: 4px;
background: var(--cyan);
box-shadow: 0 0 12px rgba(88, 221, 255, 0.45);
}
.range-limits {
display: flex;
justify-content: space-between;
margin-top: 6px;
color: #607985;
font-size: 9px;
}
.divider {
height: 1px;
margin: 18px 0;
background: var(--line);
}
.section-title {
margin-bottom: 10px;
color: #a8bec9;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.metric {
min-height: 74px;
padding: 11px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255, 255, 255, 0.025);
}
.metric.primary {
border-color: rgba(88, 221, 255, 0.34);
background: rgba(25, 94, 115, 0.12);
}
.metric-label {
margin-bottom: 7px;
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.metric-value {
color: var(--text);
font-size: 20px;
font-weight: 780;
font-variant-numeric: tabular-nums;
}
.metric.primary .metric-value {
color: var(--cyan);
}
.metric-sub {
margin-top: 4px;
color: #69828e;
font-size: 9px;
}
.live-row {
display: flex;
justify-content: space-between;
gap: 10px;
margin-top: 10px;
padding: 9px 10px;
border-radius: 7px;
background: rgba(255, 255, 255, 0.035);
color: var(--muted);
font-size: 11px;
}
.live-row strong {
color: var(--green);
font-variant-numeric: tabular-nums;
}
.formula {
margin-top: 11px;
color: #9cb4c0;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.6;
text-align: center;
}
.note {
padding: 11px 12px;
border: 1px solid rgba(255, 176, 92, 0.22);
border-radius: 8px;
background: rgba(255, 176, 92, 0.06);
color: #c5aa8c;
font-size: 10px;
line-height: 1.55;
}
.note strong {
display: block;
margin-bottom: 4px;
color: #ffd09a;
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-top: 14px;
}
button {
padding: 9px 10px;
border: 1px solid rgba(88, 221, 255, 0.28);
border-radius: 6px;
background: rgba(88, 221, 255, 0.07);
color: #c9f4ff;
font: inherit;
font-size: 11px;
font-weight: 750;
cursor: pointer;
}
button:hover {
background: rgba(88, 221, 255, 0.14);
}
.wave-card {
position: fixed;
z-index: 8;
left: 22px;
bottom: 22px;
width: 390px;
padding: 13px 14px 11px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(8, 18, 26, 0.87);
box-shadow: 0 15px 50px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(12px);
}
.wave-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 5px;
}
.wave-header span:first-child {
color: #bed2db;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.wave-header span:last-child {
color: var(--green);
font-size: 10px;
font-variant-numeric: tabular-nums;
}
#waveCanvas {
display: block;
width: 100%;
height: 135px;
}
.camera-hint {
position: fixed;
z-index: 4;
right: 380px;
bottom: 23px;
color: rgba(184, 210, 220, 0.58);
font-size: 10px;
pointer-events: none;
}
@media (max-width: 800px) {
.brand {
top: 14px;
left: 14px;
}
.brand h1 {
font-size: 15px;
}
.loading-badge {
max-width: 270px;
font-size: 8px;
}
.panel {
top: auto;
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
max-height: 48vh;
padding: 15px;
}
.wave-card {
top: 75px;
bottom: auto;
left: 12px;
width: min(330px, calc(100vw - 24px));
}
.camera-hint {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel generator scene"></canvas>
<header class="brand">
<h1>VOXEL DYNAMO LAB</h1>
<p>Rotating loop · uniform magnetic field</p>
<div class="loading-badge">MECHANICAL + ELECTRICAL LOADING OMITTED</div>
</header>
<aside class="panel">
<div class="eyebrow">Interactive generator</div>
<h2>Ideal induced voltage</h2>
<p class="subtitle">
Change the machine parameters and inspect the sinusoidal voltage produced
by a rotating coil in a uniform field.
</p>
<div class="control">
<div class="control-heading">
<label for="area">Loop area</label>
<output id="areaOut">120 cm²</output>
</div>
<input id="area" type="range" min="20" max="400" step="5" value="120">
<div class="range-limits">
<span>20 cm²</span>
<span>400 cm²</span>
</div>
</div>
<div class="control">
<div class="control-heading">
<label for="turns">Turn count</label>
<output id="turnsOut">12 turns</output>
</div>
<input id="turns" type="range" min="1" max="50" step="1" value="12">
<div class="range-limits">
<span>1</span>
<span>50</span>
</div>
</div>
<div class="control">
<div class="control-heading">
<label for="field">Field strength</label>
<output id="fieldOut">180 mT</output>
</div>
<input id="field" type="range" min="10" max="500" step="5" value="180">
<div class="range-limits">
<span>10 mT</span>
<span>500 mT</span>
</div>
</div>
<div class="control">
<div class="control-heading">
<label for="speed">Angular speed</label>
<output id="speedOut">180 rpm</output>
</div>
<input id="speed" type="range" min="0" max="1800" step="10" value="180">
<div class="range-limits">
<span>0 rpm</span>
<span>1800 rpm</span>
</div>
</div>
<div class="divider"></div>
<div class="section-title">Calculated output</div>
<div class="metrics">
<div class="metric primary">
<div class="metric-label">Ideal peak voltage</div>
<div class="metric-value" id="peakValue">0.000 V</div>
<div class="metric-sub">Epeak = NBAω</div>
</div>
<div class="metric">
<div class="metric-label">Ideal RMS voltage</div>
<div class="metric-value" id="rmsValue">0.000 V</div>
<div class="metric-sub">For a sinusoidal waveform</div>
</div>
<div class="metric">
<div class="metric-label">Angular velocity</div>
<div class="metric-value" id="omegaValue">0.00</div>
<div class="metric-sub">rad/s</div>
</div>
<div class="metric">
<div class="metric-label">Output frequency</div>
<div class="metric-value" id="frequencyValue">0.00</div>
<div class="metric-sub">Hz · one electrical cycle/revolution</div>
</div>
</div>
<div class="live-row">
<span>Instantaneous ideal EMF</span>
<strong id="instantValue">0.000 V</strong>
</div>
<div class="live-row">
<span>Rotor angle</span>
<strong id="angleValue">0.00 rad</strong>
</div>
<div class="formula">
Φ(t) = N B A sin(ωt)<br>
e(t) = −N B A ω cos(ωt)
</div>
<div class="divider"></div>
<div class="note">
<strong>Ideal model boundaries</strong>
Mechanical loading effects—friction, inertia, aerodynamic drag, shaft
torque, and core losses—are omitted. Electrical loading effects—winding
resistance, inductance, back-EMF, brush/contact losses, saturation, and
external load—are also omitted. The commanded angular speed is therefore
treated as constant.
</div>
<div class="buttons">
<button id="pauseButton" type="button">Pause motion</button>
<button id="resetCamera" type="button">Reset camera</button>
</div>
</aside>
<section class="wave-card">
<div class="wave-header">
<span>Ideal induced-voltage waveform</span>
<span id="waveInstant">0.000 V</span>
</div>
<canvas id="waveCanvas"></canvas>
</section>
<div class="camera-hint">
Drag: orbit · Wheel: zoom · Shift-drag: pan · Double-click: reset
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const canvas = $("scene");
const waveCanvas = $("waveCanvas");
const waveContext = waveCanvas.getContext("2d");
const state = {
areaCm2: 120,
turns: 12,
fieldMt: 180,
rpm: 180,
omega: 0,
peakVoltage: 0,
rmsVoltage: 0,
angle: 0,
paused: false
};
// -------------------------------------------------------------------------
// Renderer, camera, lighting
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.1;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071018);
scene.fog = new THREE.FogExp2(0x071018, 0.035);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
80
);
const cameraState = {
theta: 0.78,
phi: 1.04,
radius: 9.1,
target: new THREE.Vector3(0, 0.05, 0)
};
const defaultCamera = {
theta: 0.78,
phi: 1.04,
radius: 9.1,
target: new THREE.Vector3(0, 0.05, 0)
};
function updateCamera() {
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);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xaeeaff, 0x111820, 1.65);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.35);
keyLight.position.set(4.5, 7, 5.5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -6;
keyLight.shadow.camera.right = 6;
keyLight.shadow.camera.top = 6;
keyLight.shadow.camera.bottom = -6;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 20;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x32d8ff, 18, 12, 2);
rimLight.position.set(-4, 1.5, -3);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xff9b4a, 11, 9, 2);
warmLight.position.set(3.5, -1, 3);
scene.add(warmLight);
// -------------------------------------------------------------------------
// Materials and reusable geometry
// -------------------------------------------------------------------------
const materials = {
base: new THREE.MeshStandardMaterial({
color: 0x101a22,
roughness: 0.88,
metalness: 0.18
}),
tile: new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.82,
metalness: 0.08
}),
shaft: new THREE.MeshStandardMaterial({
color: 0x8ca5b1,
roughness: 0.3,
metalness: 0.78
}),
support: new THREE.MeshStandardMaterial({
color: 0x243a46,
roughness: 0.58,
metalness: 0.45
}),
supportAccent: new THREE.MeshStandardMaterial({
color: 0x345c69,
roughness: 0.44,
metalness: 0.52
}),
copper: new THREE.MeshStandardMaterial({
color: 0xff9d42,
emissive: 0x4b1700,
emissiveIntensity: 0.6,
roughness: 0.3,
metalness: 0.7
}),
north: new THREE.MeshStandardMaterial({
color: 0x9f312f,
emissive: 0x4a0908,
emissiveIntensity: 0.25,
roughness: 0.58,
metalness: 0.28
}),
south: new THREE.MeshStandardMaterial({
color: 0x245b99,
emissive: 0x061e4d,
emissiveIntensity: 0.3,
roughness: 0.58,
metalness: 0.28
}),
field: new THREE.MeshStandardMaterial({
color: 0x54e5ff,
emissive: 0x0783a2,
emissiveIntensity: 1,
transparent: true,
opacity: 0.62,
depthWrite: false,
roughness: 0.3,
metalness: 0.05
}),
accent: new THREE.MeshStandardMaterial({
color: 0xffd05a,
emissive: 0x5b3100,
emissiveIntensity: 0.55,
roughness: 0.4,
metalness: 0.4
})
};
const unitBox = new THREE.BoxGeometry(1, 1, 1);
function addBox(parent, size, position, material, castShadow = true) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size.x, size.y, size.z),
material
);
mesh.position.copy(position);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function setInstanceTransform(mesh, index, position, scale) {
const dummy = new THREE.Object3D();
dummy.position.copy(position);
dummy.scale.copy(scale);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
}
// -------------------------------------------------------------------------
// Voxel platform
// -------------------------------------------------------------------------
const platform = new THREE.Group();
scene.add(platform);
addBox(
platform,
new THREE.Vector3(8.9, 0.24, 7.4),
new THREE.Vector3(0, -1.53, 0),
materials.base
);
const tileCountX = 17;
const tileCountZ = 15;
const tileMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.46, 0.075, 0.46),
materials.tile,
tileCountX * tileCountZ
);
tileMesh.receiveShadow = true;
const tileColor = new THREE.Color();
let tileIndex = 0;
for (let x = 0; x < tileCountX; x++) {
for (let z = 0; z < tileCountZ; z++) {
const px = (x - (tileCountX - 1) / 2) * 0.49;
const pz = (z - (tileCountZ - 1) / 2) * 0.49;
setInstanceTransform(
tileMesh,
tileIndex,
new THREE.Vector3(px, -1.37, pz),
new THREE.Vector3(1, 1, 1)
);
const variation = (x + z) % 3 === 0 ? 0.055 : 0.025;
tileColor.setHSL(0.55, 0.18, 0.095 + variation);
tileMesh.setColorAt(tileIndex, tileColor);
tileIndex++;
}
}
tileMesh.instanceMatrix.needsUpdate = true;
tileMesh.instanceColor.needsUpdate = true;
platform.add(tileMesh);
// -------------------------------------------------------------------------
// Magnet poles
// -------------------------------------------------------------------------
const magnetGroup = new THREE.Group();
scene.add(magnetGroup);
function buildMagnet(sign, material) {
const columns = 9;
const rows = 4;
const layers = 2;
const mesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.28, 0.28, 0.28),
material,
columns * rows * layers
);
mesh.castShadow = true;
mesh.receiveShadow = true;
const color = new THREE.Color();
let index = 0;
for (let layer = 0; layer < layers; layer++) {
for (let x = 0; x < columns; x++) {
for (let z = 0; z < rows; z++) {
const px = (x - (columns - 1) / 2) * 0.31;
const pz = (z - (rows - 1) / 2) * 0.31;
const py = sign * (1.05 + layer * 0.25);
setInstanceTransform(
mesh,
index,
new THREE.Vector3(px, py, pz),
new THREE.Vector3(1, 1, 1)
);
color.copy(material.color).offsetHSL(0, 0, (layer % 2) * 0.025);
mesh.setColorAt(index, color);
index++;
}
}
}
mesh.instanceMatrix.needsUpdate = true;
mesh.instanceColor.needsUpdate = true;
magnetGroup.add(mesh);
}
buildMagnet(1, materials.north);
buildMagnet(-1, materials.south);
// -------------------------------------------------------------------------
// 3D labels
// -------------------------------------------------------------------------
function createLabel(text, color, scale = 0.7) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 256;
labelCanvas.height = 128;
const context = labelCanvas.getContext("2d");
context.fillStyle = "rgba(5, 14, 20, 0.88)";
context.fillRect(5, 10, 246, 108);
context.strokeStyle = color;
context.lineWidth = 7;
context.strokeRect(8, 13, 240, 102);
context.fillStyle = color;
context.font = "800 64px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 128, 67);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(scale, scale * 0.5, 1);
sprite.renderOrder = 20;
return sprite;
}
const northLabel = createLabel("N", "#ff7772", 0.66);
northLabel.position.set(0, 1.2, 1.2);
scene.add(northLabel);
const southLabel = createLabel("S", "#67aaff", 0.66);
southLabel.position.set(0, -1.2, 1.2);
scene.add(southLabel);
const fieldLabel = createLabel("B", "#58ddff", 0.58);
fieldLabel.position.set(1.75, 0.15, 1.0);
scene.add(fieldLabel);
// -------------------------------------------------------------------------
// Shaft, supports, and rotor
// -------------------------------------------------------------------------
const rotor = new THREE.Group();
scene.add(rotor);
const shaftSegments = 25;
const shaftMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.135, 0.135, 0.135),
materials.shaft,
shaftSegments
);
shaftMesh.castShadow = true;
shaftMesh.receiveShadow = true;
for (let i = 0; i < shaftSegments; i++) {
const px = -1.82 + (i / (shaftSegments - 1)) * 3.64;
setInstanceTransform(
shaftMesh,
i,
new THREE.Vector3(px, 0, 0),
new THREE.Vector3(1, 1, 1)
);
}
shaftMesh.instanceMatrix.needsUpdate = true;
rotor.add(shaftMesh);
addBox(
rotor,
new THREE.Vector3(0.17, 0.23, 0.23),
new THREE.Vector3(1.94, 0, 0),
materials.accent
);
const supportGroup = new THREE.Group();
scene.add(supportGroup);
for (const x of [-1.62, 1.62]) {
addBox(
supportGroup,
new THREE.Vector3(0.42, 1.08, 0.62),
new THREE.Vector3(x, -0.79, 0),
materials.support
);
addBox(
supportGroup,
new THREE.Vector3(0.5, 0.18, 0.7),
new THREE.Vector3(x, -0.2, 0),
materials.supportAccent
);
for (const y of [-0.17, 0.17]) {
for (const z of [-0.19, 0.19]) {
addBox(
supportGroup,
new THREE.Vector3(0.34, 0.16, 0.17),
new THREE.Vector3(x, y, z),
materials.supportAccent
);
}
}
}
let coilMesh = null;
let coilDirty = true;
function rebuildCoil() {
if (coilMesh) {
rotor.remove(coilMesh);
coilMesh.geometry.dispose();
}
const areaM2 = state.areaCm2 * 1e-4;
const aspectRatio = 1.6;
// Scene units are scaled for legibility; the physical calculation uses A.
const visualScale = 5.0;
const width = Math.sqrt(areaM2 * aspectRatio) * visualScale;
const height = Math.sqrt(areaM2 / aspectRatio) * visualScale;
const turnSpacing = 0.016;
const voxelSpacing = 0.055;
const voxelSize = 0.048;
const corners = [
new THREE.Vector2(-width / 2, -height / 2),
new THREE.Vector2(width / 2, -height / 2),
new THREE.Vector2(width / 2, height / 2),
new THREE.Vector2(-width / 2, height / 2)
];
const positions = [];
for (let turn = 0; turn < state.turns; turn++) {
const z = (turn - (state.turns - 1) / 2) * turnSpacing;
for (let edge = 0; edge < 4; edge++) {
const start = corners[edge];
const end = corners[(edge + 1) % 4];
const length = start.distanceTo(end);
const steps = Math.max(2, Math.ceil(length / voxelSpacing));
for (let step = 0; step < steps; step++) {
const t = (step + 0.5) / steps;
positions.push(
new THREE.Vector3(
THREE.MathUtils.lerp(start.x, end.x, t),
THREE.MathUtils.lerp(start.y, end.y, t),
z
)
);
}
}
}
coilMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(voxelSize, voxelSize, voxelSize),
materials.copper,
positions.length
);
coilMesh.castShadow = true;
coilMesh.receiveShadow = true;
const color = new THREE.Color();
positions.forEach((position, index) => {
setInstanceTransform(
coilMesh,
index,
position,
new THREE.Vector3(1, 1, 1)
);
const turnShade = (index % 7) * 0.006;
color.setHSL(0.075, 0.72, 0.5 + turnShade);
coilMesh.setColorAt(index, color);
});
coilMesh.instanceMatrix.needsUpdate = true;
coilMesh.instanceColor.needsUpdate = true;
rotor.add(coilMesh);
}
rebuildCoil();
coilDirty = false;
// -------------------------------------------------------------------------
// Voxel field arrows
// -------------------------------------------------------------------------
const fieldGroup = new THREE.Group();
scene.add(fieldGroup);
let fieldMesh = null;
function rebuildField() {
if (fieldMesh) {
fieldGroup.remove(fieldMesh);
}
const normalized = THREE.MathUtils.clamp(
(state.fieldMt - 10) / 490,
0,
1
);
const columns = Math.max(3, Math.min(8, Math.round(3 + normalized * 5)));
const lanes = [-0.72, 0.72];
const positions = [];
const scales = [];
for (const z of lanes) {
for (let column = 0; column < columns; column++) {
const x =
(column - (columns - 1) / 2) * (2.4 / Math.max(columns - 1, 1));
// Vertical arrow shafts.
for (let y = 0.69; y >= -0.37; y -= 0.12) {
positions.push(new THREE.Vector3(x, y, z));
scales.push(new THREE.Vector3(0.052, 0.052, 0.052));
}
// Stepped voxel arrowheads pointing downward.
positions.push(new THREE.Vector3(x, -0.49, z));
scales.push(new THREE.Vector3(0.064, 0.064, 0.064));
positions.push(new THREE.Vector3(x - 0.065, -0.49, z));
scales.push(new THREE.Vector3(0.05, 0.05, 0.05));
positions.push(new THREE.Vector3(x + 0.065, -0.49, z));
scales.push(new THREE.Vector3(0.05, 0.05, 0.05));
positions.push(new THREE.Vector3(x, -0.61, z));
scales.push(new THREE.Vector3(0.074, 0.074, 0.074));
}
}
fieldMesh = new THREE.InstancedMesh(
unitBox,
materials.field,
positions.length
);
positions.forEach((position, index) => {
setInstanceTransform(fieldMesh, index, position, scales[index]);
});
fieldMesh.instanceMatrix.needsUpdate = true;
fieldGroup.add(fieldMesh);
materials.field.emissiveIntensity = 0.65 + normalized * 1.9;
materials.field.opacity = 0.4 + normalized * 0.42;
materials.north.emissiveIntensity = 0.18 + normalized * 0.48;
materials.south.emissiveIntensity = 0.2 + normalized * 0.52;
}
rebuildField();
// -------------------------------------------------------------------------
// Physics and user interface
// -------------------------------------------------------------------------
function formatVoltage(value) {
const magnitude = Math.abs(value);
if (magnitude < 0.001) return "0.000 V";
if (magnitude < 1) return `${value.toFixed(4)} V`;
if (magnitude < 10) return `${value.toFixed(3)} V`;
if (magnitude < 100) return `${value.toFixed(2)} V`;
return `${value.toFixed(1)} V`;
}
function updatePhysics() {
const areaM2 = state.areaCm2 * 1e-4;
const fieldTesla = state.fieldMt * 1e-3;
state.omega = (state.rpm * Math.PI * 2) / 60;
state.peakVoltage =
state.turns * fieldTesla * areaM2 * state.omega;
state.rmsVoltage = state.peakVoltage / Math.SQRT2;
$("areaOut").textContent = `${state.areaCm2} cm²`;
$("turnsOut").textContent = `${state.turns} turns`;
$("fieldOut").textContent = `${state.fieldMt} mT`;
$("speedOut").textContent =
`${state.rpm} rpm · ${state.omega.toFixed(2)} rad/s`;
$("peakValue").textContent = formatVoltage(state.peakVoltage);
$("rmsValue").textContent = formatVoltage(state.rmsVoltage);
$("omegaValue").textContent = state.omega.toFixed(2);
$("frequencyValue").textContent = (state.rpm / 60).toFixed(2);
}
$("area").addEventListener("input", (event) => {
state.areaCm2 = Number(event.target.value);
coilDirty = true;
updatePhysics();
});
$("turns").addEventListener("input", (event) => {
state.turns = Number(event.target.value);
coilDirty = true;
updatePhysics();
});
$("field").addEventListener("input", (event) => {
state.fieldMt = Number(event.target.value);
rebuildField();
updatePhysics();
});
$("speed").addEventListener("input", (event) => {
state.rpm = Number(event.target.value);
updatePhysics();
});
$("pauseButton").addEventListener("click", () => {
state.paused = !state.paused;
$("pauseButton").textContent = state.paused
? "Resume motion"
: "Pause motion";
});
$("resetCamera").addEventListener("click", resetCamera);
updatePhysics();
// -------------------------------------------------------------------------
// Direct camera controls: orbit, zoom, and shift-drag pan
// -------------------------------------------------------------------------
let dragging = false;
let panning = false;
let pointerX = 0;
let pointerY = 0;
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
panning = event.shiftKey;
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;
if (panning) {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3()
.crossVectors(forward, camera.up)
.normalize();
const scale = cameraState.radius * 0.0014;
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(forward, dy * scale);
cameraState.target.x = THREE.MathUtils.clamp(
cameraState.target.x,
-3,
3
);
cameraState.target.z = THREE.MathUtils.clamp(
cameraState.target.z,
-3,
3
);
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.28,
1.48
);
}
updateCamera();
});
function endPointer(event) {
dragging = false;
panning = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
4.4,
17
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetCamera);
function resetCamera() {
cameraState.theta = defaultCamera.theta;
cameraState.phi = defaultCamera.phi;
cameraState.radius = defaultCamera.radius;
cameraState.target.copy(defaultCamera.target);
updateCamera();
}
// -------------------------------------------------------------------------
// Waveform display
// -------------------------------------------------------------------------
function drawWave(angle) {
const rect = waveCanvas.getBoundingClientRect();
const width = Math.max(1, rect.width);
const height = Math.max(1, rect.height);
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const pixelWidth = Math.round(width * dpr);
const pixelHeight = Math.round(height * dpr);
if (
waveCanvas.width !== pixelWidth ||
waveCanvas.height !== pixelHeight
) {
waveCanvas.width = pixelWidth;
waveCanvas.height = pixelHeight;
}
const context = waveContext;
context.setTransform(dpr, 0, 0, dpr, 0, 0);
context.clearRect(0, 0, width, height);
const padding = {
left: 34,
right: 10,
top: 12,
bottom: 23
};
const plotWidth = width - padding.left - padding.right;
const plotHeight = height - padding.top - padding.bottom;
const centerY = padding.top + plotHeight / 2;
context.strokeStyle = "rgba(132, 180, 199, 0.12)";
context.lineWidth = 1;
for (let i = 0; i <= 4; i++) {
const x = padding.left + (plotWidth * i) / 4;
context.beginPath();
context.moveTo(x, padding.top);
context.lineTo(x, padding.top + plotHeight);
context.stroke();
}
for (let i = 0; i <= 2; i++) {
const y = padding.top + (plotHeight * i) / 2;
context.beginPath();
context.moveTo(padding.left, y);
context.lineTo(padding.left + plotWidth, y);
context.stroke();
}
context.fillStyle = "#6e8a97";
context.font = "9px system-ui, sans-serif";
context.textAlign = "center";
context.fillText("0", padding.left, height - 7);
context.fillText("π", padding.left + plotWidth / 2, height - 7);
context.fillText("2π", padding.left + plotWidth, height - 7);
context.textAlign = "right";
context.fillText(
`${state.peakVoltage.toFixed(1)}`,
padding.left - 6,
padding.top + 4
);
context.fillText("0", padding.left - 6, centerY + 3);
context.fillText(
`-${state.peakVoltage.toFixed(1)}`,
padding.left - 6,
padding.top + plotHeight + 3
);
context.beginPath();
for (let i = 0; i <= 220; i++) {
const phase = (i / 220) * Math.PI * 2;
const x = padding.left + (phase / (Math.PI * 2)) * plotWidth;
const y =
centerY - Math.cos(phase) * (state.peakVoltage / state.peakVoltage) *
(plotHeight / 2) * 0.88;
if (i === 0) context.moveTo(x, y);
else context.lineTo(x, y);
}
context.strokeStyle = "#58ddff";
context.lineWidth = 2;
context.shadowColor = "rgba(88, 221, 255, 0.45)";
context.shadowBlur = 8;
context.stroke();
context.shadowBlur = 0;
const markerX =
padding.left + (angle / (Math.PI * 2)) * plotWidth;
const markerY =
centerY -
Math.cos(angle) * (plotHeight / 2) * 0.88;
context.strokeStyle = "rgba(255, 208, 90, 0.8)";
context.lineWidth = 1;
context.beginPath();
context.moveTo(markerX, padding.top);
context.lineTo(markerX, padding.top + plotHeight);
context.stroke();
context.fillStyle = "#ffd05a";
context.beginPath();
context.arc(markerX, markerY, 4, 0, Math.PI * 2);
context.fill();
}
if ("ResizeObserver" in window) {
new ResizeObserver(() => drawWave(state.angle)).observe(waveCanvas);
}
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
let previousTime = performance.now();
let lastHudUpdate = 0;
renderer.setAnimationLoop((time) => {
const delta = Math.min((time - previousTime) / 1000, 0.05);
previousTime = time;
if (coilDirty) {
rebuildCoil();
coilDirty = false;
}
if (!state.paused) {
state.angle =
(state.angle + state.omega * delta) % (Math.PI * 2);
}
rotor.rotation.x = state.angle;
const instantaneous = state.peakVoltage * Math.cos(state.angle);
if (time - lastHudUpdate > 40) {
$("instantValue").textContent = formatVoltage(instantaneous);
$("waveInstant").textContent = formatVoltage(instantaneous);
$("angleValue").textContent = `${state.angle.toFixed(2)} rad`;
lastHudUpdate = time;
}
drawWave(state.angle);
renderer.render(scene, camera);
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
drawWave(state.angle);
});
</script>
</body>
</html>
```