Prompt specification
Build or customize the Three.js 3D scene "Superposed electric-field explorer" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Superposed electric-field explorer
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/superposed-electric-field-explorer-x1624
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing a low-poly electric-field exploration table. Put up to three movable point-charge markers above a square grid and a separate probe at a selected location. Draw each charge's contribution as a vector at the probe, then show their vector sum in a contrasting color. A nearby numeric panel reports both field and potential using one consistent reference convention. Exclude a small region around each charge and explicitly mark the singular case instead of producing enormous arrows. Include a symmetric arrangement where cancellation gives zero field at the midpoint even though the potential there is not zero. Move the probe along a marked line through that arrangement and retain a faint history of its previous vectors for comparison.
Working Three.js Starter (superposed-electric-field-explorer-x1624):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Low-Poly Electric Field Table</title>
<style>
:root {
color-scheme: light;
--ink: #17222d;
--muted: #647382;
--panel: rgba(250, 252, 253, 0.94);
--border: rgba(28, 49, 65, 0.14);
--cyan: #087f83;
--magenta: #c400c7;
--danger: #d92f55;
--good: #087f59;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--ink);
background: #dfe8ec;
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.brand {
position: fixed;
top: 20px;
left: 22px;
z-index: 2;
max-width: 440px;
pointer-events: none;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.65);
}
.brand h1 {
margin: 0;
font-size: clamp(22px, 2.6vw, 36px);
line-height: 1;
letter-spacing: -0.045em;
font-weight: 850;
}
.brand .subtitle {
margin-top: 7px;
font-size: 12px;
font-weight: 750;
letter-spacing: 0.12em;
text-transform: uppercase;
color: #3d5966;
}
.brand .instructions {
margin-top: 12px;
padding: 9px 12px;
display: inline-block;
border: 1px solid rgba(26, 53, 66, 0.12);
border-radius: 10px;
background: rgba(250, 253, 254, 0.78);
box-shadow: 0 8px 28px rgba(42, 67, 80, 0.08);
font-size: 12px;
line-height: 1.5;
color: #405663;
}
#panel {
position: fixed;
z-index: 3;
top: 14px;
right: 14px;
bottom: 14px;
width: 366px;
overflow: auto;
padding: 16px;
border: 1px solid rgba(23, 42, 55, 0.14);
border-radius: 18px;
background: var(--panel);
box-shadow:
0 20px 60px rgba(30, 56, 72, 0.17),
inset 0 1px 0 rgba(255, 255, 255, 0.8);
backdrop-filter: blur(14px);
scrollbar-width: thin;
}
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 13px;
}
.panel-title strong {
font-size: 13px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.unit-chip {
padding: 5px 8px;
border-radius: 999px;
background: #e5f2f2;
color: #116d70;
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
white-space: nowrap;
}
section {
padding: 13px 0;
border-top: 1px solid var(--border);
}
section:first-of-type {
border-top: 0;
padding-top: 0;
}
.section-title {
margin: 0 0 10px;
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px;
font-size: 11px;
font-weight: 850;
letter-spacing: 0.095em;
text-transform: uppercase;
color: #52636f;
}
.status {
display: flex;
align-items: flex-start;
gap: 10px;
padding: 10px 11px;
margin-bottom: 10px;
border: 1px solid rgba(8, 127, 89, 0.16);
border-radius: 11px;
background: rgba(8, 127, 89, 0.07);
}
.status .dot {
width: 9px;
height: 9px;
margin-top: 5px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--good);
box-shadow: 0 0 0 4px rgba(8, 127, 89, 0.09);
}
.status b {
display: block;
font-size: 12px;
line-height: 1.35;
}
.status small {
display: block;
margin-top: 2px;
font-size: 11px;
line-height: 1.4;
color: var(--muted);
}
.status.warning {
border-color: rgba(196, 0, 199, 0.2);
background: rgba(196, 0, 199, 0.07);
}
.status.warning .dot {
background: var(--magenta);
box-shadow: 0 0 0 4px rgba(196, 0, 199, 0.08);
}
.status.danger {
border-color: rgba(217, 47, 85, 0.22);
background: rgba(217, 47, 85, 0.08);
}
.status.danger .dot {
background: var(--danger);
box-shadow: 0 0 0 4px rgba(217, 47, 85, 0.09);
}
.coordinate {
display: flex;
justify-content: space-between;
align-items: baseline;
gap: 12px;
margin-bottom: 9px;
font-size: 11px;
color: var(--muted);
}
.coordinate b {
color: var(--ink);
font: 700 12px/1.3 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
min-width: 0;
padding: 10px;
border: 1px solid var(--border);
border-radius: 11px;
background: rgba(255, 255, 255, 0.64);
}
.metric label {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric strong {
display: block;
overflow: hidden;
color: #087f83;
font: 800 18px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
text-overflow: ellipsis;
}
.metric.potential strong {
color: #a300a5;
}
.metric small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.components {
display: flex;
gap: 8px;
margin-top: 8px;
}
.components span {
flex: 1;
padding: 7px 9px;
border-radius: 8px;
background: #edf2f4;
color: var(--muted);
font: 600 10px/1.3 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.components b {
float: right;
color: var(--ink);
}
.scale-note {
margin-top: 8px;
color: var(--muted);
font-size: 10px;
line-height: 1.4;
}
.contribution {
display: grid;
grid-template-columns: 48px 1fr;
gap: 8px;
padding: 8px 0;
border-bottom: 1px dashed rgba(31, 53, 67, 0.12);
}
.contribution:last-child {
border-bottom: 0;
padding-bottom: 0;
}
.contribution .name {
display: flex;
align-items: center;
gap: 6px;
font-size: 11px;
font-weight: 800;
}
.swatch {
display: inline-block;
width: 9px;
height: 9px;
flex: 0 0 auto;
border-radius: 50%;
}
.contribution .values {
min-width: 0;
color: #40515d;
font: 600 10px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace;
overflow-wrap: anywhere;
}
.contribution .values span {
display: block;
}
.contribution.singular .values {
color: var(--danger);
font-weight: 800;
}
.sum-note {
margin-top: 9px;
padding: 8px 9px;
border-radius: 8px;
background: rgba(196, 0, 199, 0.07);
color: #8d008f;
font-size: 10px;
line-height: 1.4;
}
button,
input[type="number"] {
font: inherit;
}
button {
cursor: pointer;
border: 1px solid rgba(23, 42, 55, 0.15);
border-radius: 8px;
background: #f8fafb;
color: var(--ink);
transition:
transform 0.12s ease,
background 0.12s ease,
opacity 0.12s ease;
}
button:hover:not(:disabled) {
transform: translateY(-1px);
background: #edf3f5;
}
button:active:not(:disabled) {
transform: translateY(0);
}
button:disabled {
cursor: not-allowed;
opacity: 0.42;
}
.charge-row {
display: grid;
grid-template-columns: 20px 34px 62px 1fr 28px;
align-items: center;
gap: 6px;
margin-bottom: 7px;
padding: 7px;
border: 1px solid var(--border);
border-radius: 10px;
background: rgba(255, 255, 255, 0.55);
}
.charge-row .swatch {
width: 11px;
height: 11px;
}
.charge-row button {
height: 28px;
}
.charge-row .sign {
color: #fff;
font-weight: 900;
}
.charge-row input {
width: 100%;
height: 28px;
padding: 3px 6px;
border: 1px solid rgba(23, 42, 55, 0.16);
border-radius: 7px;
background: white;
color: var(--ink);
font: 700 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.charge-row .remove {
color: var(--danger);
font-weight: 900;
}
.button-row {
display: flex;
gap: 7px;
margin-top: 9px;
}
.button-row button {
flex: 1;
min-height: 34px;
padding: 7px 9px;
font-size: 11px;
font-weight: 800;
}
.button-row .primary {
border-color: #087f83;
background: #087f83;
color: white;
}
.button-row .primary:hover:not(:disabled) {
background: #086e72;
}
.button-row .preset {
border-color: rgba(196, 0, 199, 0.25);
background: rgba(196, 0, 199, 0.06);
color: #940097;
}
.check-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 9px;
color: #40515d;
font-size: 11px;
font-weight: 700;
}
.check-row label {
display: flex;
align-items: center;
gap: 7px;
cursor: pointer;
}
input[type="checkbox"] {
accent-color: #087f83;
}
input[type="range"] {
width: 100%;
accent-color: #087f83;
cursor: pointer;
}
input[type="range"]:disabled {
opacity: 0.35;
cursor: not-allowed;
}
.range-labels {
display: flex;
justify-content: space-between;
margin-top: 3px;
color: var(--muted);
font: 600 9px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.small-note {
margin: 8px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.convention {
margin-bottom: 3px;
padding: 10px;
border: 1px solid rgba(23, 42, 55, 0.12);
border-radius: 10px;
background: #eef3f4;
color: #40515d;
font-size: 10px;
line-height: 1.5;
}
.convention b {
color: var(--ink);
}
.formula {
display: block;
margin: 6px 0;
padding: 6px;
border-radius: 6px;
background: rgba(255, 255, 255, 0.72);
color: #193541;
font: 700 10px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace;
overflow-wrap: anywhere;
}
.danger-note {
color: var(--danger);
font-weight: 750;
}
@media (max-width: 800px) {
.brand {
top: 13px;
left: 14px;
}
.brand h1 {
font-size: 23px;
}
.brand .instructions {
display: none;
}
#panel {
top: auto;
left: 9px;
right: 9px;
bottom: 9px;
width: auto;
max-height: 48vh;
border-radius: 14px;
}
}
</style>
</head>
<body>
<div id="viewport"></div>
<div class="brand">
<h1>Electric Field Table</h1>
<div class="subtitle">Low-poly point-charge explorer</div>
<div class="instructions">
Drag charges or the cyan probe · Click the grid to place the probe ·
Right-drag / Alt-drag to orbit · Scroll to zoom
</div>
</div>
<aside id="panel">
<div class="panel-title">
<strong>Field / Potential</strong>
<span class="unit-chip">1 grid unit = 10 cm</span>
</div>
<section>
<div id="status" class="status">
<span class="dot"></span>
<div>
<b id="statusTitle">INITIALIZING</b>
<small id="statusDetail">Computing the field…</small>
</div>
</div>
<div class="coordinate">
<span>Probe position, grid coordinates</span>
<b id="probeCoordinates">(0.00, 0.00)</b>
</div>
<div class="metrics">
<div class="metric">
<label>Resultant field |E|</label>
<strong id="fieldMagnitude">—</strong>
<small>volts per meter</small>
</div>
<div class="metric potential">
<label>Electric potential V</label>
<strong id="potential">—</strong>
<small>volts</small>
</div>
</div>
<div class="components">
<span>E<sub>x</sub> <b id="fieldX">—</b></span>
<span>E<sub>z</sub> <b id="fieldZ">—</b></span>
</div>
<div id="scaleNote" class="scale-note"></div>
</section>
<section>
<div class="section-title">
<span>Contributions at probe</span>
<span style="color:#c400c7">ΣE = magenta</span>
</div>
<div id="contributions"></div>
<div id="sumNote" class="sum-note"></div>
</section>
<section>
<div class="section-title">
<span>Point charges</span>
<span id="chargeCount">2 / 3</span>
</div>
<div id="chargeControls"></div>
<div class="button-row">
<button id="addCharge" class="primary">+ Add charge</button>
<button id="symmetric" class="preset">Symmetric pair</button>
</div>
<p class="small-note">
Positive charges have a “+” sign and negative charges have a “−” sign.
The sign button reverses the charge without changing its magnitude.
</p>
</section>
<section>
<div class="section-title">
<span>Probe line</span>
<span id="linePosition">50%</span>
</div>
<div class="check-row">
<label>
<input id="lineLock" type="checkbox" checked>
Snap probe to marked line
</label>
<span>First two charges define the line</span>
</div>
<input id="lineSlider" type="range" min="0" max="1000" value="500">
<div class="range-labels">
<span>Line start</span>
<span>Line end</span>
</div>
<p class="small-note">
With snapping enabled, dragging or clicking the probe projects it onto
the dashed teal line.
</p>
</section>
<section>
<div class="section-title">
<span>Vector history</span>
<span>Previous resultants</span>
</div>
<div class="check-row">
<label>
<input id="historyEnabled" type="checkbox" checked>
Show faint previous vectors
</label>
<button id="clearHistory" style="padding:5px 9px;font-size:10px">
Clear
</button>
</div>
<p class="small-note">
Ghost arrows stay at previous probe locations and use the same common
length scale as the current arrows.
</p>
</section>
<section>
<div class="section-title">Reference convention</div>
<div class="convention">
<b>Potential:</b> V(∞) = 0.
<b>Field direction:</b> away from positive charges and toward negative
charges.
<span class="formula">
E = Σ k qᵢ(r − rᵢ) / |r − rᵢ|³<br>
V = Σ k qᵢ / |r − rᵢ|
</span>
All terms use SI units after conversion. The table is coplanar, so
E<sub>y</sub> = 0.
<br><br>
<span class="danger-note">
Singular exclusion:
</span>
each charge has a marked radius of 0.62 grid units (6.2 cm). A probe
inside or on that radius reports undefined E and V, and no vectors are
drawn.
</div>
</section>
</aside>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Constants and state
// -------------------------------------------------------------------------
const K = 8.9875517923e9;
const METERS_PER_GRID_UNIT = 0.1;
const TABLE_HALF = 6;
const EXCLUSION_RADIUS = 0.62;
const SUM_COLOR = 0xc400c7;
const HISTORY_COLOR = 0x9c4aa8;
const PALETTE = [0xe65f4a, 0x4267d5, 0x15966d];
const viewport = document.getElementById("viewport");
const chargeControls = document.getElementById("chargeControls");
const contributions = document.getElementById("contributions");
const lineSlider = document.getElementById("lineSlider");
const lineLock = document.getElementById("lineLock");
const state = {
charges: [],
probe: { x: 0, z: 0 },
nextId: 1,
lineLocked: true,
line: {
a: new THREE.Vector2(-2, 0),
d: new THREE.Vector2(1, 0),
tMin: -4,
tMax: 8
},
currentArrows: [],
snapshot: null,
history: [],
historyEnabled: true,
singular: false,
zeroField: false,
currentScale: 1
};
// -------------------------------------------------------------------------
// Renderer, scene, camera, and custom camera controls
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdfe8ec);
scene.fog = new THREE.Fog(0xdfe8ec, 24, 43);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
viewport.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraControl = {
theta: 0.68,
phi: 0.82,
radius: 17,
target: new THREE.Vector3(0, 0, 0)
};
function updateCamera() {
const spherical = new THREE.Spherical(
cameraControl.radius,
cameraControl.phi,
cameraControl.theta
);
camera.position.setFromSpherical(spherical).add(cameraControl.target);
camera.lookAt(cameraControl.target);
}
updateCamera();
const ambient = new THREE.HemisphereLight(0xf5fbff, 0x7f8d91, 2.25);
scene.add(ambient);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(-6, 12, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -10;
keyLight.shadow.camera.right = 10;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 30;
keyLight.shadow.bias = -0.0005;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0xb9ddff, 1.1);
fillLight.position.set(8, 6, -7);
scene.add(fillLight);
// -------------------------------------------------------------------------
// Low-poly table
// -------------------------------------------------------------------------
const tableGroup = new THREE.Group();
scene.add(tableGroup);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(70, 70),
new THREE.MeshStandardMaterial({
color: 0xd7e1e4,
roughness: 1
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.47;
floor.receiveShadow = true;
scene.add(floor);
const tableBase = new THREE.Mesh(
new THREE.BoxGeometry(12.7, 0.44, 12.7),
new THREE.MeshStandardMaterial({
color: 0xb8c7ca,
roughness: 0.9,
flatShading: true
})
);
tableBase.position.y = -0.22;
tableBase.castShadow = true;
tableBase.receiveShadow = true;
tableGroup.add(tableBase);
const tableTop = new THREE.Mesh(
new THREE.BoxGeometry(12.35, 0.12, 12.35),
new THREE.MeshStandardMaterial({
color: 0xe9eff0,
roughness: 0.84,
flatShading: true
})
);
tableTop.position.y = 0.015;
tableTop.receiveShadow = true;
tableGroup.add(tableTop);
const grid = new THREE.GridHelper(12, 24, 0x789096, 0xa9b7ba);
grid.position.y = 0.083;
grid.material.transparent = true;
grid.material.opacity = 0.75;
tableGroup.add(grid);
const frameMaterial = new THREE.MeshStandardMaterial({
color: 0x647c83,
roughness: 0.75,
flatShading: true
});
const frameParts = [
[12.8, 0.16, 0.18, 0, 0.05, -6.32],
[12.8, 0.16, 0.18, 0, 0.05, 6.32],
[0.18, 0.16, 12.45, -6.32, 0.05, 0],
[0.18, 0.16, 12.45, 6.32, 0.05, 0]
];
for (const [w, h, d, x, y, z] of frameParts) {
const part = new THREE.Mesh(
new THREE.BoxGeometry(w, h, d),
frameMaterial
);
part.position.set(x, y, z);
part.castShadow = true;
part.receiveShadow = true;
tableGroup.add(part);
}
// -------------------------------------------------------------------------
// Text sprites
// -------------------------------------------------------------------------
function createLabelSprite(text, background, foreground = "#ffffff") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = background;
context.beginPath();
context.roundRect(6, 16, 500, 96, 22);
context.fill();
context.fillStyle = foreground;
context.textAlign = "center";
context.textBaseline = "middle";
context.font = "800 40px system-ui, sans-serif";
context.fillText(text, 256, 66);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.renderOrder = 20;
return sprite;
}
const lineLabel = createLabelSprite(
"MARKED PROBE LINE",
"rgba(8,127,131,0.90)",
"#ffffff"
);
lineLabel.scale.set(1.65, 0.41, 1);
scene.add(lineLabel);
const zeroFieldLabel = createLabelSprite(
"ΣE = 0",
"rgba(196,0,199,0.92)",
"#ffffff"
);
zeroFieldLabel.scale.set(1.25, 0.34, 1);
zeroFieldLabel.visible = false;
scene.add(zeroFieldLabel);
const singularLabel = createLabelSprite(
"SINGULAR",
"rgba(217,47,85,0.95)",
"#ffffff"
);
singularLabel.scale.set(1.25, 0.34, 1);
singularLabel.visible = false;
scene.add(singularLabel);
// -------------------------------------------------------------------------
// Charge and probe visuals
// -------------------------------------------------------------------------
const pickables = [];
function createSignSprite() {
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 128;
const context = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(0.42, 0.42, 1);
sprite.renderOrder = 18;
function paint(sign) {
context.clearRect(0, 0, 128, 128);
context.fillStyle = "rgba(255,255,255,0.96)";
context.beginPath();
context.arc(64, 64, 48, 0, Math.PI * 2);
context.fill();
context.strokeStyle = "#1b2b35";
context.lineWidth = 6;
context.stroke();
context.strokeStyle = "#1b2b35";
context.lineWidth = 10;
context.lineCap = "round";
context.beginPath();
context.moveTo(37, 64);
context.lineTo(91, 64);
context.stroke();
if (sign > 0) {
context.beginPath();
context.moveTo(64, 37);
context.lineTo(64, 91);
context.stroke();
}
texture.needsUpdate = true;
}
paint(1);
return { sprite, paint };
}
function createChargeVisual(charge) {
const group = new THREE.Group();
const marker = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.32, 0),
new THREE.MeshStandardMaterial({
color: charge.color,
roughness: 0.55,
metalness: 0.08,
flatShading: true
})
);
marker.position.y = 0.38;
marker.castShadow = true;
marker.receiveShadow = true;
marker.userData = { kind: "charge", id: charge.id };
group.add(marker);
pickables.push(marker);
const stem = new THREE.Mesh(
new THREE.CylinderGeometry(0.025, 0.025, 0.25, 6),
new THREE.MeshStandardMaterial({
color: 0x667b82,
roughness: 0.8
})
);
stem.position.y = 0.15;
group.add(stem);
const sign = createSignSprite();
sign.sprite.position.y = 0.91;
group.add(sign.sprite);
const exclusionDisk = new THREE.Mesh(
new THREE.CircleGeometry(EXCLUSION_RADIUS, 48),
new THREE.MeshBasicMaterial({
color: 0xff3d62,
transparent: true,
opacity: 0.075,
depthWrite: false,
side: THREE.DoubleSide
})
);
exclusionDisk.rotation.x = -Math.PI / 2;
exclusionDisk.position.y = 0.091;
group.add(exclusionDisk);
const ringPoints = [];
for (let i = 0; i <= 64; i++) {
const angle = (i / 64) * Math.PI * 2;
ringPoints.push(
new THREE.Vector3(
Math.cos(angle) * EXCLUSION_RADIUS,
0.103,
Math.sin(angle) * EXCLUSION_RADIUS
)
);
}
const exclusionRing = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(ringPoints),
new THREE.LineDashedMaterial({
color: 0xff4367,
dashSize: 0.11,
gapSize: 0.075,
transparent: true,
opacity: 0.9
})
);
exclusionRing.computeLineDistances();
group.add(exclusionRing);
group.position.set(charge.x, 0, charge.z);
scene.add(group);
charge.visual = { group, marker, sign, exclusionDisk, exclusionRing };
updateChargeVisual(charge);
}
function updateChargeVisual(charge) {
charge.visual.group.position.set(charge.x, 0, charge.z);
charge.visual.sign.paint(Math.sign(charge.q));
}
function removeChargeVisual(charge) {
if (!charge.visual) return;
scene.remove(charge.visual.group);
const markerIndex = pickables.indexOf(charge.visual.marker);
if (markerIndex >= 0) pickables.splice(markerIndex, 1);
charge.visual.marker.geometry.dispose();
charge.visual.marker.material.dispose();
charge.visual.sign.sprite.material.map.dispose();
charge.visual.sign.sprite.material.dispose();
charge.visual.exclusionDisk.geometry.dispose();
charge.visual.exclusionDisk.material.dispose();
charge.visual.exclusionRing.geometry.dispose();
charge.visual.exclusionRing.material.dispose();
}
const probeGroup = new THREE.Group();
scene.add(probeGroup);
const probeHalo = new THREE.Mesh(
new THREE.CircleGeometry(0.48, 32),
new THREE.MeshBasicMaterial({
color: 0x0cb9bc,
transparent: true,
opacity: 0.12,
depthWrite: false,
side: THREE.DoubleSide
})
);
probeHalo.rotation.x = -Math.PI / 2;
probeHalo.position.y = 0.095;
probeGroup.add(probeHalo);
const probeRing = new THREE.Mesh(
new THREE.TorusGeometry(0.36, 0.035, 6, 32),
new THREE.MeshBasicMaterial({ color: 0x0cb9bc })
);
probeRing.rotation.x = Math.PI / 2;
probeRing.position.y = 0.13;
probeGroup.add(probeRing);
const probeMarker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.24, 0),
new THREE.MeshStandardMaterial({
color: 0x0cb9bc,
emissive: 0x07595b,
emissiveIntensity: 0.28,
roughness: 0.42,
flatShading: true
})
);
probeMarker.position.y = 0.39;
probeMarker.castShadow = true;
probeMarker.userData = { kind: "probe" };
probeGroup.add(probeMarker);
pickables.push(probeMarker);
const probeStem = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, 0.18, 0),
new THREE.Vector3(0, 0.76, 0)
]),
new THREE.LineBasicMaterial({
color: 0x0aa4a7,
transparent: true,
opacity: 0.72
})
);
probeGroup.add(probeStem);
const zeroRing = new THREE.Mesh(
new THREE.RingGeometry(0.18, 0.235, 32),
new THREE.MeshBasicMaterial({
color: SUM_COLOR,
transparent: true,
opacity: 0.9,
side: THREE.DoubleSide,
depthTest: false,
depthWrite: false
})
);
zeroRing.rotation.x = -Math.PI / 2;
zeroRing.position.y = 0.77;
zeroRing.visible = false;
zeroRing.renderOrder = 10;
scene.add(zeroRing);
function updateProbeVisual() {
probeGroup.position.set(state.probe.x, 0, state.probe.z);
const color = state.singular ? 0xff3d5a : 0x0cb9bc;
probeMarker.material.color.set(color);
probeMarker.material.emissive.set(state.singular ? 0x8c102a : 0x07595b);
probeRing.material.color.set(color);
probeHalo.material.color.set(color);
probeHalo.material.opacity = state.singular ? 0.22 : 0.12;
singularLabel.visible = state.singular;
singularLabel.position.set(state.probe.x, 1.18, state.probe.z);
zeroFieldLabel.visible = state.zeroField && !state.singular;
zeroFieldLabel.position.set(state.probe.x, 1.18, state.probe.z);
zeroRing.visible = state.zeroField && !state.singular;
zeroRing.position.set(state.probe.x, 0.77, state.probe.z);
}
// -------------------------------------------------------------------------
// Marked probe line
// -------------------------------------------------------------------------
const lineGeometry = new THREE.BufferGeometry();
const lineObject = new THREE.Line(
lineGeometry,
new THREE.LineDashedMaterial({
color: 0x087f83,
dashSize: 0.24,
gapSize: 0.13,
transparent: true,
opacity: 0.68,
depthWrite: false
})
);
lineObject.renderOrder = 2;
scene.add(lineObject);
function clipLineToTable(a, d) {
let tMin = -Infinity;
let tMax = Infinity;
for (const [origin, direction] of [
[a.x, d.x],
[a.y, d.y]
]) {
if (Math.abs(direction) < 1e-8) {
if (Math.abs(origin) > TABLE_HALF) {
return null;
}
} else {
const t1 = (-TABLE_HALF - origin) / direction;
const t2 = (TABLE_HALF - origin) / direction;
tMin = Math.max(tMin, Math.min(t1, t2));
tMax = Math.min(tMax, Math.max(t1, t2));
}
}
if (!Number.isFinite(tMin) || !Number.isFinite(tMax) || tMin >= tMax) {
return null;
}
return { tMin, tMax };
}
function updateLineGeometry() {
let a;
let d;
if (state.charges.length >= 2) {
a = new THREE.Vector2(state.charges[0].x, state.charges[0].z);
d = new THREE.Vector2(
state.charges[1].x - state.charges[0].x,
state.charges[1].z - state.charges[0].z
);
} else if (state.charges.length === 1) {
a = new THREE.Vector2(state.charges[0].x, state.charges[0].z);
d = new THREE.Vector2(1, 0);
} else {
a = new THREE.Vector2(0, 0);
d = new THREE.Vector2(1, 0);
}
if (d.lengthSq() < 1e-8) {
d.set(1, 0);
} else {
d.normalize();
}
const clipped = clipLineToTable(a, d) ?? {
tMin: -TABLE_HALF,
tMax: TABLE_HALF
};
state.line.a.copy(a);
state.line.d.copy(d);
state.line.tMin = clipped.tMin;
state.line.tMax = clipped.tMax;
const p0 = a.clone().addScaledVector(d, clipped.tMin);
const p1 = a.clone().addScaledVector(d, clipped.tMax);
lineGeometry.dispose();
lineObject.geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(p0.x, 0.112, p0.y),
new THREE.Vector3(p1.x, 0.112, p1.y)
]);
lineObject.computeLineDistances();
lineLabel.position.set(p1.x, 0.45, p1.y);
lineLabel.visible = state.charges.length > 0;
if (state.lineLocked) {
const projected = projectToLine(state.probe);
state.probe.x = projected.x;
state.probe.z = projected.y;
}
syncLineSlider();
updateProbeVisual();
}
function projectToLine(point) {
const p = new THREE.Vector2(point.x, point.z);
const relative = p.clone().sub(state.line.a);
let t = relative.dot(state.line.d);
t = THREE.MathUtils.clamp(t, state.line.tMin, state.line.tMax);
return state.line.a.clone().addScaledVector(state.line.d, t);
}
function syncLineSlider() {
const relative = new THREE.Vector2(
state.probe.x,
state.probe.z
).sub(state.line.a);
const t = relative.dot(state.line.d);
const fraction =
(t - state.line.tMin) / (state.line.tMax - state.line.tMin);
const percentage = THREE.MathUtils.clamp(fraction, 0, 1) * 100;
lineSlider.value = String(Math.round(percentage * 10));
document.getElementById("linePosition").textContent =
`${percentage.toFixed(0)}%`;
lineSlider.disabled = !state.lineLocked;
}
// -------------------------------------------------------------------------
// Field calculations
// -------------------------------------------------------------------------
function calculateField() {
let singularIndex = -1;
for (let i = 0; i < state.charges.length; i++) {
const charge = state.charges[i];
const dx = state.probe.x - charge.x;
const dz = state.probe.z - charge.z;
const distanceGrid = Math.hypot(dx, dz);
if (distanceGrid <= EXCLUSION_RADIUS) {
singularIndex = i;
break;
}
}
if (singularIndex >= 0) {
return {
valid: false,
singularIndex,
contributions: [],
sum: { ex: 0, ez: 0, magnitude: 0 },
potential: NaN
};
}
const contributions = [];
let sumX = 0;
let sumZ = 0;
let potential = 0;
for (const charge of state.charges) {
const dxGrid = state.probe.x - charge.x;
const dzGrid = state.probe.z - charge.z;
const distanceGrid = Math.hypot(dxGrid, dzGrid);
const distanceMeters = distanceGrid * METERS_PER_GRID_UNIT;
const kq = K * charge.q * 1e-9;
const ex =
(kq * dxGrid * METERS_PER_GRID_UNIT) /
Math.pow(distanceMeters, 3);
const ez =
(kq * dzGrid * METERS_PER_GRID_UNIT) /
Math.pow(distanceMeters, 3);
const vi = kq / distanceMeters;
contributions.push({
chargeId: charge.id,
ex,
ez,
magnitude: Math.hypot(ex, ez),
potential: vi
});
sumX += ex;
sumZ += ez;
potential += vi;
}
return {
valid: true,
singularIndex: -1,
contributions,
sum: {
ex: sumX,
ez: sumZ,
magnitude: Math.hypot(sumX, sumZ)
},
potential
};
}
function disposeArrow(arrow) {
scene.remove(arrow);
arrow.line.geometry.dispose();
arrow.line.material.dispose();
arrow.cone.geometry.dispose();
arrow.cone.material.dispose();
}
function clearCurrentArrows() {
for (const arrow of state.currentArrows) {
disposeArrow(arrow);
}
state.currentArrows.length = 0;
}
function createArrow(color, origin, length, opacity = 1) {
const direction = new THREE.Vector3(1, 0, 0);
const arrow = new THREE.ArrowHelper(
direction,
origin.clone(),
Math.max(length, 0.001),
color,
Math.min(0.28, Math.max(0.08, length * 0.27)),
Math.min(0.15, Math.max(0.055, length * 0.13))
);
arrow.line.material.transparent = true;
arrow.line.material.opacity = opacity;
arrow.line.material.depthTest = false;
arrow.line.material.depthWrite = false;
arrow.line.renderOrder = 8;
arrow.cone.material.transparent = true;
arrow.cone.material.opacity = opacity;
arrow.cone.material.depthTest = false;
arrow.cone.material.depthWrite = false;
arrow.cone.renderOrder = 8;
scene.add(arrow);
return arrow;
}
function renderCurrentVectors(result, scale) {
clearCurrentArrows();
if (!result.valid) return;
const origin = new THREE.Vector3(
state.probe.x,
0.77,
state.probe.z
);
result.contributions.forEach((contribution, index) => {
const charge = state.charges.find(
(candidate) => candidate.id === contribution.chargeId
);
const direction = new THREE.Vector3(
contribution.ex,
0,
contribution.ez
).normalize();
const arrow = new THREE.ArrowHelper(
direction,
origin.clone(),
Math.max(contribution.magnitude * scale, 0.001),
charge.color,
Math.min(0.28, Math.max(0.08, contribution.magnitude * scale * 0.27)),
Math.min(0.15, Math.max(0.055, contribution.magnitude * scale * 0.13))
);
arrow.line.material.transparent = true;
arrow.line.material.opacity = 0.94;
arrow.line.material.depthTest = false;
arrow.line.material.depthWrite = false;
arrow.line.renderOrder = 9;
arrow.cone.material.transparent = true;
arrow.cone.material.opacity = 0.94;
arrow.cone.material.depthTest = false;
arrow.cone.material.depthWrite = false;
arrow.cone.renderOrder = 9;
scene.add(arrow);
state.currentArrows.push(arrow);
});
if (result.sum.magnitude > 1e-10) {
const direction = new THREE.Vector3(
result.sum.ex,
0,
result.sum.ez
).normalize();
const length = result.sum.magnitude * scale;
const arrow = new THREE.ArrowHelper(
direction,
origin.clone(),
Math.max(length, 0.001),
SUM_COLOR,
Math.min(0.31, Math.max(0.09, length * 0.27)),
Math.min(0.16, Math.max(0.06, length * 0.13))
);
arrow.line.material.transparent = true;
arrow.line.material.opacity = 1;
arrow.line.material.depthTest = false;
arrow.line.material.depthWrite = false;
arrow.line.renderOrder = 10;
arrow.cone.material.transparent = true;
arrow.cone.material.opacity = 1;
arrow.cone.material.depthTest = false;
arrow.cone.material.depthWrite = false;
arrow.cone.renderOrder = 10;
scene.add(arrow);
state.currentArrows.push(arrow);
}
}
// -------------------------------------------------------------------------
// Faint history of previous resultant vectors
// -------------------------------------------------------------------------
const historyGroup = new THREE.Group();
scene.add(historyGroup);
function disposeHistoryEntry(entry) {
if (entry.arrow) {
historyGroup.remove(entry.arrow);
entry.arrow.line.geometry.dispose();
entry.arrow.line.material.dispose();
entry.arrow.cone.geometry.dispose();
entry.arrow.cone.material.dispose();
}
if (entry.ring) {
historyGroup.remove(entry.ring);
entry.ring.geometry.dispose();
entry.ring.material.dispose();
}
}
function addHistorySnapshot(snapshot) {
if (!state.historyEnabled || !snapshot?.valid) return;
const last = state.history[state.history.length - 1];
if (
last &&
Math.hypot(last.x - snapshot.x, last.z - snapshot.z) < 0.12
) {
return;
}
state.history.push({
x: snapshot.x,
z: snapshot.z,
ex: snapshot.sum.ex,
ez: snapshot.sum.ez,
magnitude: snapshot.sum.magnitude
});
if (state.history.length > 18) {
const removed = state.history.shift();
disposeHistoryEntry(removed);
}
}
function renderHistory(scale) {
historyGroup.visible = state.historyEnabled;
if (!state.historyEnabled) return;
state.history.forEach((entry, index) => {
const ratio =
state.history.length <= 1
? 0
: index / (state.history.length - 1);
const opacity = 0.23 - ratio * 0.15;
if (!entry.arrow && entry.magnitude > 1e-10) {
const direction = new THREE.Vector3(entry.ex, 0, entry.ez).normalize();
const length = entry.magnitude * scale;
entry.arrow = new THREE.ArrowHelper(
direction,
new THREE.Vector3(entry.x, 0.59, entry.z),
Math.max(length, 0.001),
HISTORY_COLOR,
Math.min(0.22, Math.max(0.07, length * 0.25)),
Math.min(0.11, Math.max(0.045, length * 0.12))
);
entry.arrow.line.material.transparent = true;
entry.arrow.line.material.depthTest = false;
entry.arrow.line.material.depthWrite = false;
entry.arrow.cone.material.transparent = true;
entry.arrow.cone.material.depthTest = false;
entry.arrow.cone.material.depthWrite = false;
historyGroup.add(entry.arrow);
}
if (entry.arrow) {
const direction = new THREE.Vector3(entry.ex, 0, entry.ez).normalize();
const length = entry.magnitude * scale;
entry.arrow.position.set(entry.x, 0.59, entry.z);
entry.arrow.setDirection(direction);
entry.arrow.setLength(
Math.max(length, 0.001),
Math.min(0.22, Math.max(0.07, length * 0.25)),
Math.min(0.11, Math.max(0.045, length * 0.12))
);
entry.arrow.line.material.opacity = opacity;
entry.arrow.cone.material.opacity = opacity;
}
if (!entry.ring) {
entry.ring = new THREE.Mesh(
new THREE.TorusGeometry(0.25, 0.018, 5, 24),
new THREE.MeshBasicMaterial({
color: HISTORY_COLOR,
transparent: true,
opacity,
depthTest: false,
depthWrite: false
})
);
entry.ring.rotation.x = Math.PI / 2;
entry.ring.position.set(entry.x, 0.115, entry.z);
historyGroup.add(entry.ring);
}
entry.ring.material.opacity = opacity;
});
}
function clearHistory() {
for (const entry of state.history) {
disposeHistoryEntry(entry);
}
state.history.length = 0;
}
// -------------------------------------------------------------------------
// UI formatting and rendering
// -------------------------------------------------------------------------
function formatNumber(value) {
if (!Number.isFinite(value)) return "undefined";
if (Math.abs(value) < 1e-12) return "0";
const absolute = Math.abs(value);
if (absolute >= 1e6 || absolute < 0.001) {
return value.toExponential(2);
}
return value.toLocaleString(undefined, {
maximumFractionDigits: 2
});
}
function formatSigned(value) {
if (!Number.isFinite(value)) return "undefined";
if (Math.abs(value) < 1e-12) return "0";
return `${value > 0 ? "+" : ""}${formatNumber(value)}`;
}
function isSymmetricMidpoint() {
if (state.charges.length !== 2) return false;
const [a, b] = state.charges;
if (Math.abs(a.q - b.q) > 1e-9) return false;
const midpointX = (a.x + b.x) / 2;
const midpointZ = (a.z + b.z) / 2;
return (
Math.hypot(
state.probe.x - midpointX,
state.probe.z - midpointZ
) < 0.025
);
}
function updateUI(result, maximumMagnitude) {
const status = document.getElementById("status");
const statusTitle = document.getElementById("statusTitle");
const statusDetail = document.getElementById("statusDetail");
status.className = "status";
document.getElementById("probeCoordinates").textContent =
`(${state.probe.x.toFixed(2)}, ${state.probe.z.toFixed(2)})`;
if (!result.valid) {
status.classList.add("danger");
statusTitle.textContent = "SINGULAR REGION";
statusDetail.textContent =
`Probe is inside or on the ${EXCLUSION_RADIUS.toFixed(2)}-unit exclusion radius of charge ${result.singularIndex + 1}. E and V are undefined; vectors are suppressed.`;
document.getElementById("fieldMagnitude").textContent = "undefined";
document.getElementById("potential").textContent = "undefined";
document.getElementById("fieldX").textContent = "undefined";
document.getElementById("fieldZ").textContent = "undefined";
document.getElementById("scaleNote").textContent =
"No arrow scale is used in the singular region.";
contributions.innerHTML = state.charges
.map((charge, index) => {
const isSingular = index === result.singularIndex;
return `
<div class="contribution ${isSingular ? "singular" : ""}">
<div class="name">
<span class="swatch" style="background:#${charge.color.toString(16).padStart(6, "0")}"></span>
C${index + 1}
</div>
<div class="values">
<span>${
isSingular
? "inside excluded radius — undefined"
: "suppressed because total probe state is singular"
}</span>
</div>
</div>
`;
})
.join("");
document.getElementById("sumNote").textContent =
"ΣE is not drawn because one or more denominators vanish.";
return;
}
const symmetric = isSymmetricMidpoint();
const zeroField = result.sum.magnitude < 1e-8;
if (symmetric && zeroField && Math.abs(result.potential) > 1e-8) {
status.classList.add("warning");
statusTitle.textContent = "SYMMETRIC MIDPOINT CANCELLATION";
statusDetail.textContent =
`The two equal fields cancel, but the scalar potential remains ${formatSigned(result.potential)} V.`;
} else if (zeroField) {
status.classList.add("warning");
statusTitle.textContent = "ZERO RESULTANT FIELD";
statusDetail.textContent =
`The vector sum is zero. The potential at this location is ${formatSigned(result.potential)} V.`;
} else {
statusTitle.textContent = "FIELD DEFINED";
statusDetail.textContent =
"Colored arrows are individual contributions; the magenta arrow is their vector sum.";
}
document.getElementById("fieldMagnitude").textContent =
formatNumber(result.sum.magnitude);
document.getElementById("potential").textContent =
formatSigned(result.potential);
document.getElementById("fieldX").textContent =
formatSigned(result.sum.ex);
document.getElementById("fieldZ").textContent =
formatSigned(result.sum.ez);
if (maximumMagnitude > 0) {
const voltsPerGridUnit = maximumMagnitude / 1.7;
document.getElementById("scaleNote").textContent =
`Common arrow scale: 1 grid unit = ${formatNumber(voltsPerGridUnit)} V/m. Individual and resultant vectors share this scale.`;
} else {
document.getElementById("scaleNote").textContent =
"No charges are present, so E = 0 and V = 0.";
}
contributions.innerHTML = state.charges
.map((charge, index) => {
const contribution = result.contributions[index];
const hex = `#${charge.color.toString(16).padStart(6, "0")}`;
return `
<div class="contribution">
<div class="name">
<span class="swatch" style="background:${hex}"></span>
C${index + 1}
</div>
<div class="values">
<span>E = (${formatSigned(contribution.ex)}, ${formatSigned(contribution.ez)}) V/m</span>
<span>|Eᵢ| = ${formatNumber(contribution.magnitude)} V/m</span>
<span>Vᵢ = ${formatSigned(contribution.potential)} V</span>
</div>
</div>
`;
})
.join("");
document.getElementById("sumNote").textContent =
zeroField
? "ΣE = 0. A magenta ring marks the zero resultant at the probe."
: `ΣE = (${formatSigned(result.sum.ex)}, ${formatSigned(result.sum.ez)}) V/m; magnitude ${formatNumber(result.sum.magnitude)} V/m.`;
}
function computeAndRender() {
const result = calculateField();
state.singular = !result.valid;
state.zeroField =
result.valid && result.sum.magnitude < 1e-8;
let maximumMagnitude = 0;
if (result.valid) {
for (const contribution of result.contributions) {
maximumMagnitude = Math.max(
maximumMagnitude,
contribution.magnitude
);
}
maximumMagnitude = Math.max(
maximumMagnitude,
result.sum.magnitude
);
}
for (const entry of state.history) {
maximumMagnitude = Math.max(maximumMagnitude, entry.magnitude);
}
const scale =
maximumMagnitude > 0 ? 1.7 / maximumMagnitude : 1.7;
state.currentScale = scale;
renderCurrentVectors(result, scale);
renderHistory(scale);
updateProbeVisual();
updateUI(result, maximumMagnitude);
if (result.valid) {
state.snapshot = {
valid: true,
x: state.probe.x,
z: state.probe.z,
sum: { ...result.sum }
};
} else {
state.snapshot = null;
}
}
// -------------------------------------------------------------------------
// Charge controls
// -------------------------------------------------------------------------
function renderChargeControls() {
chargeControls.innerHTML = state.charges
.map((charge, index) => {
const sign = Math.sign(charge.q);
const magnitude = Math.abs(charge.q);
const hex = `#${charge.color.toString(16).padStart(6, "0")}`;
return `
<div class="charge-row" data-charge-id="${charge.id}">
<span class="swatch" style="background:${hex}"></span>
<button
class="sign"
type="button"
data-action="sign"
style="background:${hex}"
title="Reverse charge sign"
>${sign > 0 ? "+" : "−"}</button>
<input
type="number"
min="0.1"
max="20"
step="0.1"
value="${magnitude.toFixed(2)}"
data-action="magnitude"
aria-label="Charge ${index + 1} magnitude in nanocoulombs"
>
<span style="font-size:10px;color:#647382">nC</span>
<button
class="remove"
type="button"
data-action="remove"
title="Remove charge"
>×</button>
</div>
`;
})
.join("");
document.getElementById("chargeCount").textContent =
`${state.charges.length} / 3`;
document.getElementById("addCharge").disabled =
state.charges.length >= 3;
chargeControls.querySelectorAll(".charge-row").forEach((row) => {
const id = Number(row.dataset.chargeId);
const charge = state.charges.find((item) => item.id === id);
row.querySelector('[data-action="sign"]').addEventListener(
"click",
() => {
charge.q = -charge.q;
updateChargeVisual(charge);
renderChargeControls();
computeAndRender();
}
);
row.querySelector('[data-action="magnitude"]').addEventListener(
"change",
(event) => {
const parsed = Number.parseFloat(event.target.value);
const magnitude = Number.isFinite(parsed)
? THREE.MathUtils.clamp(Math.abs(parsed), 0.1, 20)
: Math.abs(charge.q);
charge.q = Math.sign(charge.q || 1) * magnitude;
event.target.value = magnitude.toFixed(2);
computeAndRender();
}
);
row.querySelector('[data-action="remove"]').addEventListener(
"click",
() => {
removeChargeVisual(charge);
state.charges = state.charges.filter((item) => item.id !== id);
renderChargeControls();
updateLineGeometry();
computeAndRender();
}
);
});
}
function addCharge() {
if (state.charges.length >= 3) return;
const index = state.charges.length;
const color = PALETTE[index % PALETTE.length];
const charge = {
id: state.nextId++,
x: 0,
z: 3.1,
q: 1,
color
};
let attempts = 0;
while (
attempts < 30 &&
state.charges.some(
(existing) =>
Math.hypot(existing.x - charge.x, existing.z - charge.z) < 1.4
)
) {
charge.z -= 0.65;
attempts++;
}
state.charges.push(charge);
createChargeVisual(charge);
renderChargeControls();
updateLineGeometry();
computeAndRender();
}
function loadSymmetricPair() {
for (const charge of state.charges) {
removeChargeVisual(charge);
}
state.charges = [
{
id: state.nextId++,
x: -2,
z: 0,
q: 2,
color: PALETTE[0]
},
{
id: state.nextId++,
x: 2,
z: 0,
q: 2,
color: PALETTE[1]
}
];
state.probe.x = 0;
state.probe.z = 0;
state.lineLocked = true;
lineLock.checked = true;
clearHistory();
for (const charge of state.charges) {
createChargeVisual(charge);
}
renderChargeControls();
updateLineGeometry();
computeAndRender();
}
// -------------------------------------------------------------------------
// Probe placement and dragging
// -------------------------------------------------------------------------
function setProbePosition(x, z, recordHistory = true) {
x = THREE.MathUtils.clamp(x, -TABLE_HALF, TABLE_HALF);
z = THREE.MathUtils.clamp(z, -TABLE_HALF, TABLE_HALF);
if (state.lineLocked) {
const projected = projectToLine({ x, z });
x = projected.x;
z = projected.y;
}
if (
recordHistory &&
state.snapshot?.valid &&
Math.hypot(
state.snapshot.x - x,
state.snapshot.z - z
) > 0.015
) {
addHistorySnapshot(state.snapshot);
}
state.probe.x = x;
state.probe.z = z;
syncLineSlider();
computeAndRender();
}
// -------------------------------------------------------------------------
// Pointer interaction and custom orbit controls
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const groundPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
let interaction = null;
function setRayFromEvent(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
function rayToGround(event) {
setRayFromEvent(event);
const point = new THREE.Vector3();
raycaster.ray.intersectPlane(groundPlane, point);
return point;
}
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
const orbiting = event.button === 2 || event.button === 1 || event.altKey;
if (orbiting) {
event.preventDefault();
interaction = {
kind: "orbit",
lastX: event.clientX,
lastY: event.clientY
};
renderer.domElement.setPointerCapture(event.pointerId);
return;
}
if (event.button !== 0) return;
setRayFromEvent(event);
const hits = raycaster.intersectObjects(pickables, false);
const ground = rayToGround(event);
if (hits.length > 0) {
const hitObject = hits[0].object;
const kind = hitObject.userData.kind;
if (kind === "charge") {
const charge = state.charges.find(
(item) => item.id === hitObject.userData.id
);
interaction = {
kind: "charge",
id: charge.id,
offsetX: ground.x - charge.x,
offsetZ: ground.z - charge.z
};
} else if (kind === "probe") {
interaction = {
kind: "probe",
offsetX: ground.x - state.probe.x,
offsetZ: ground.z - state.probe.z
};
}
renderer.domElement.setPointerCapture(event.pointerId);
event.preventDefault();
} else {
interaction = {
kind: "click",
startX: event.clientX,
startY: event.clientY
};
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!interaction) return;
if (interaction.kind === "orbit") {
const dx = event.clientX - interaction.lastX;
const dy = event.clientY - interaction.lastY;
cameraControl.theta -= dx * 0.007;
cameraControl.phi = THREE.MathUtils.clamp(
cameraControl.phi - dy * 0.006,
0.28,
1.42
);
interaction.lastX = event.clientX;
interaction.lastY = event.clientY;
updateCamera();
return;
}
const ground = rayToGround(event);
if (interaction.kind === "charge") {
const charge = state.charges.find(
(item) => item.id === interaction.id
);
if (!charge) return;
charge.x = THREE.MathUtils.clamp(
ground.x - interaction.offsetX,
-TABLE_HALF,
TABLE_HALF
);
charge.z = THREE.MathUtils.clamp(
ground.z - interaction.offsetZ,
-TABLE_HALF,
TABLE_HALF
);
updateChargeVisual(charge);
updateLineGeometry();
computeAndRender();
} else if (interaction.kind === "probe") {
setProbePosition(
ground.x - interaction.offsetX,
ground.z - interaction.offsetZ
);
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (!interaction) return;
if (interaction.kind === "click") {
const movement = Math.hypot(
event.clientX - interaction.startX,
event.clientY - interaction.startY
);
if (movement < 6) {
const ground = rayToGround(event);
setProbePosition(ground.x, ground.z);
}
}
interaction = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
interaction = null;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraControl.radius = THREE.MathUtils.clamp(
cameraControl.radius * Math.exp(event.deltaY * 0.001),
9,
28
);
updateCamera();
},
{ passive: false }
);
// -------------------------------------------------------------------------
// UI events
// -------------------------------------------------------------------------
document.getElementById("addCharge").addEventListener(
"click",
addCharge
);
document.getElementById("symmetric").addEventListener(
"click",
loadSymmetricPair
);
lineLock.addEventListener("change", () => {
state.lineLocked = lineLock.checked;
if (state.lineLocked) {
const projected = projectToLine(state.probe);
state.probe.x = projected.x;
state.probe.z = projected.y;
}
syncLineSlider();
computeAndRender();
});
lineSlider.addEventListener("input", () => {
if (!state.lineLocked) return;
const fraction = Number(lineSlider.value) / 1000;
const t = THREE.MathUtils.lerp(
state.line.tMin,
state.line.tMax,
fraction
);
const point = state.line.a
.clone()
.addScaledVector(state.line.d, t);
setProbePosition(point.x, point.y);
});
document.getElementById("historyEnabled").addEventListener(
"change",
(event) => {
state.historyEnabled = event.target.checked;
renderHistory(state.currentScale);
}
);
document.getElementById("clearHistory").addEventListener(
"click",
clearHistory
);
// -------------------------------------------------------------------------
// Initialization and animation loop
// -------------------------------------------------------------------------
state.charges = [
{
id: state.nextId++,
x: -2,
z: 0,
q: 2,
color: PALETTE[0]
},
{
id: state.nextId++,
x: 2,
z: 0,
q: 2,
color: PALETTE[1]
}
];
for (const charge of state.charges) {
createChargeVisual(charge);
}
renderChargeControls();
updateLineGeometry();
computeAndRender();
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
function animate() {
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
```