Prompt specification
Build or customize the Three.js 3D scene "Dipole field comparison display" 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: Dipole field comparison display
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/dipole-field-comparison-display-x1622
Scene Description Prompt:
Plot a stylized positive-negative charge pair with calculated electric-field arrows and mathematical field-line guides. Create one HTML file with Three.js from cdnjs.
Working Three.js Starter (dipole-field-comparison-display-x1622):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Positive–Negative Dipole Field</title>
<style>
:root {
color-scheme: dark;
--bg: #050812;
--panel: rgba(8, 15, 31, 0.76);
--border: rgba(139, 213, 255, 0.18);
--cyan: #6cecff;
--yellow: #ffd166;
--pink: #ff577d;
--blue: #4f8cff;
--muted: #93a7c3;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
color: #eef7ff;
}
#scene {
position: fixed;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
#hud {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 5;
}
.panel {
position: absolute;
border: 1px solid var(--border);
border-radius: 16px;
background:
linear-gradient(145deg, rgba(18, 31, 57, 0.78), rgba(5, 10, 23, 0.72));
box-shadow:
0 18px 60px rgba(0, 0, 0, 0.28),
inset 0 1px 0 rgba(255, 255, 255, 0.035);
backdrop-filter: blur(16px) saturate(125%);
-webkit-backdrop-filter: blur(16px) saturate(125%);
}
#title-panel {
top: 22px;
left: 22px;
padding: 18px 20px 16px;
max-width: 390px;
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.22em;
text-transform: uppercase;
}
h1 {
margin: 7px 0 7px;
font-size: clamp(22px, 2.3vw, 32px);
line-height: 1.05;
letter-spacing: -0.035em;
}
.subtitle {
margin: 0;
max-width: 340px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.hint {
margin-top: 11px;
color: #7288a6;
font-size: 10px;
letter-spacing: 0.035em;
}
#formula-panel {
top: 22px;
right: 22px;
width: min(355px, calc(100vw - 44px));
padding: 17px 18px;
}
.panel-heading {
margin-bottom: 12px;
color: #dbeaff;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.equation {
overflow-x: auto;
padding: 11px 12px;
border: 1px solid rgba(108, 236, 255, 0.1);
border-radius: 11px;
background: rgba(0, 0, 0, 0.18);
color: #e8f8ff;
font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
font-size: 12px;
line-height: 1.6;
white-space: nowrap;
}
.method {
display: flex;
align-items: flex-start;
gap: 9px;
margin-top: 10px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.method strong {
display: block;
margin-bottom: 1px;
color: #ddecff;
font-size: 11px;
}
.method-dot {
flex: 0 0 auto;
width: 7px;
height: 7px;
margin-top: 4px;
border-radius: 50%;
background: var(--yellow);
box-shadow: 0 0 10px currentColor;
}
.method-dot.cyan {
background: var(--cyan);
}
#controls-panel {
bottom: 22px;
left: 50%;
width: min(520px, calc(100vw - 44px));
padding: 14px 16px;
transform: translateX(-50%);
pointer-events: auto;
}
.control-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
margin-bottom: 9px;
}
.control-top label {
color: #c9d9ed;
font-size: 11px;
font-weight: 700;
}
#separation-output {
min-width: 38px;
color: var(--cyan);
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 12px;
text-align: right;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
border-radius: 999px;
outline: none;
accent-color: var(--cyan);
cursor: pointer;
}
.control-bottom {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 12px;
}
.toggles,
.buttons {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
.toggle,
button {
display: inline-flex;
align-items: center;
gap: 6px;
border: 0;
color: #b9cbe0;
background: transparent;
font: inherit;
font-size: 10px;
cursor: pointer;
user-select: none;
}
.toggle input {
width: 13px;
height: 13px;
margin: 0;
accent-color: var(--cyan);
}
button {
padding: 6px 9px;
border: 1px solid rgba(108, 236, 255, 0.16);
border-radius: 8px;
background: rgba(108, 236, 255, 0.055);
transition:
color 150ms ease,
border-color 150ms ease,
background 150ms ease,
transform 150ms ease;
}
button:hover {
color: #fff;
border-color: rgba(108, 236, 255, 0.45);
background: rgba(108, 236, 255, 0.12);
}
button:active {
transform: translateY(1px);
}
#legend-panel {
bottom: 22px;
left: 22px;
width: 190px;
padding: 13px 14px;
}
.legend-row {
display: flex;
align-items: center;
gap: 9px;
margin-top: 8px;
color: var(--muted);
font-size: 10px;
}
.swatch {
flex: 0 0 auto;
width: 22px;
height: 8px;
border-radius: 999px;
}
.swatch.positive {
background: var(--pink);
box-shadow: 0 0 10px rgba(255, 87, 125, 0.65);
}
.swatch.negative {
background: var(--blue);
box-shadow: 0 0 10px rgba(79, 140, 255, 0.65);
}
.swatch.line {
background: var(--cyan);
box-shadow: 0 0 10px rgba(108, 236, 255, 0.65);
}
.magnitude-gradient {
height: 7px;
margin-top: 11px;
border-radius: 999px;
background: linear-gradient(90deg, #47d9ff, #9de6a7, #ffd166);
box-shadow: 0 0 14px rgba(108, 236, 255, 0.15);
}
.gradient-labels {
display: flex;
justify-content: space-between;
margin-top: 4px;
color: #7186a2;
font-size: 9px;
}
#readout-panel {
right: 22px;
bottom: 22px;
width: 245px;
padding: 13px 14px;
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 10px;
line-height: 1.75;
}
#readout-panel .panel-heading {
margin-bottom: 5px;
font-family: Inter, ui-sans-serif, system-ui, sans-serif;
}
#readout-panel b {
display: inline-block;
width: 47px;
color: #68809f;
font-weight: 500;
}
#readout-panel .vector {
color: var(--yellow);
}
#loading {
position: fixed;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
background: #050812;
color: var(--cyan);
font-size: 11px;
letter-spacing: 0.2em;
text-transform: uppercase;
transition: opacity 350ms ease;
}
#loading.hidden {
opacity: 0;
pointer-events: none;
}
@media (max-width: 900px) {
#legend-panel {
display: none;
}
#readout-panel {
bottom: 150px;
}
}
@media (max-width: 650px) {
#title-panel {
top: 12px;
left: 12px;
max-width: calc(100vw - 24px);
padding: 13px 15px;
}
.subtitle,
.hint {
display: none;
}
#formula-panel {
top: 105px;
right: 12px;
width: calc(100vw - 24px);
padding: 13px 14px;
}
#formula-panel .method {
display: none;
}
#controls-panel {
bottom: 12px;
width: calc(100vw - 24px);
}
#readout-panel {
right: 12px;
bottom: 145px;
width: 210px;
}
.control-bottom {
align-items: flex-start;
flex-direction: column;
}
}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<div id="hud">
<section id="title-panel" class="panel">
<div class="eyebrow">Interactive Electrostatics</div>
<h1>Positive–Negative Dipole</h1>
<p class="subtitle">
Electric-field vectors sampled directly from Coulomb’s law, with
mathematical field-line guides integrated through the field.
</p>
<div class="hint">
DRAG TO ORBIT · WHEEL TO ZOOM · SHIFT-DRAG TO PAN · HOVER TO SAMPLE E
</div>
</section>
<section id="formula-panel" class="panel">
<div class="panel-heading">Field model</div>
<div class="equation">
E(r) = k [ q₊(r−r₊)/|r−r₊|³<br />
+ q₋(r−r₋)/|r−r₋|³ ]<br />
q₊ = +1, q₋ = −1, k = 9
</div>
<div class="method">
<span class="method-dot"></span>
<div>
<strong>Calculated arrows</strong>
Each arrow is a normalized sample of E(x, y).
</div>
</div>
<div class="method">
<span class="method-dot cyan"></span>
<div>
<strong>Mathematical guides</strong>
RK4 integration of dr/ds = E/|E| through the vector field.
</div>
</div>
</section>
<section id="controls-panel" class="panel">
<div class="control-top">
<label for="separation">Charge separation</label>
<output id="separation-output">2.4</output>
</div>
<input
id="separation"
type="range"
min="1.6"
max="3.6"
step="0.1"
value="2.4"
aria-label="Charge separation"
/>
<div class="control-bottom">
<div class="toggles">
<label class="toggle">
<input id="show-arrows" type="checkbox" checked />
Field arrows
</label>
<label class="toggle">
<input id="show-lines" type="checkbox" checked />
Field lines
</label>
<label class="toggle">
<input id="auto-rotate" type="checkbox" />
Auto orbit
</label>
</div>
<div class="buttons">
<button id="face-view" type="button">Face view</button>
<button id="reset-view" type="button">Reset</button>
</div>
</div>
</section>
<section id="legend-panel" class="panel">
<div class="panel-heading">Legend</div>
<div class="legend-row">
<span class="swatch positive"></span>
Positive charge, q = +1
</div>
<div class="legend-row">
<span class="swatch negative"></span>
Negative charge, q = −1
</div>
<div class="legend-row">
<span class="swatch line"></span>
Integrated field line
</div>
<div class="magnitude-gradient"></div>
<div class="gradient-labels">
<span>Lower |E|</span>
<span>Higher |E|</span>
</div>
</section>
<section id="readout-panel" class="panel">
<div class="panel-heading">Live field sample</div>
<div id="readout">
<b>x</b><span>—</span><br />
<b>y</b><span>—</span><br />
<b>E</b><span>—</span><br />
<b>|E|</b><span>—</span>
</div>
</section>
</div>
<div id="loading">Initializing vector field</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const separationInput = document.querySelector("#separation");
const separationOutput = document.querySelector("#separation-output");
const showArrowsInput = document.querySelector("#show-arrows");
const showLinesInput = document.querySelector("#show-lines");
const autoRotateInput = document.querySelector("#auto-rotate");
const readout = document.querySelector("#readout");
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.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x050812);
scene.fog = new THREE.FogExp2(0x050812, 0.035);
const camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
0.1,
100
);
const clock = new THREE.Clock();
const K = 9;
const Q = 1;
const CHARGE_RADIUS = 0.28;
let separation = Number(separationInput.value);
let elapsedTime = 0;
const chargePositions = {
positive: { x: -separation / 2, y: 0 },
negative: { x: separation / 2, y: 0 }
};
// -------------------------------------------------------------------------
// Custom camera controls — no addons
// -------------------------------------------------------------------------
const orbit = {
radius: 9.6,
theta: 0.55,
phi: 1.22,
target: new THREE.Vector3(0, 0, 0)
};
const defaultOrbit = {
radius: 9.6,
theta: 0.55,
phi: 1.22,
target: new THREE.Vector3(0, 0, 0)
};
function updateCamera() {
const sinPhi = Math.sin(orbit.phi);
const cosPhi = Math.cos(orbit.phi);
camera.position.set(
orbit.radius * sinPhi * Math.sin(orbit.theta),
orbit.radius * cosPhi,
orbit.radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(orbit.target);
camera.updateMatrixWorld();
}
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
function resetCamera() {
orbit.radius = defaultOrbit.radius;
orbit.theta = defaultOrbit.theta;
orbit.phi = defaultOrbit.phi;
orbit.target.copy(defaultOrbit.target);
updateCamera();
}
const pointers = new Map();
let gestureMode = "rotate";
let previousPinchDistance = 0;
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
canvas.setPointerCapture(event.pointerId);
if (pointers.size === 1) {
gestureMode =
event.button === 2 || event.shiftKey ? "pan" : "rotate";
}
if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
previousPinchDistance = Math.hypot(a.x - b.x, a.y - b.y);
}
});
canvas.addEventListener("pointermove", (event) => {
const previous = pointers.get(event.pointerId);
if (previous) {
const dx = event.clientX - previous.x;
const dy = event.clientY - previous.y;
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 1 && gestureMode === "rotate") {
orbit.theta -= dx * 0.006;
orbit.phi = clamp(orbit.phi - dy * 0.006, 0.12, Math.PI - 0.12);
}
if (pointers.size === 1 && gestureMode === "pan") {
const right = new THREE.Vector3()
.setFromMatrixColumn(camera.matrix, 0);
const up = new THREE.Vector3()
.setFromMatrixColumn(camera.matrix, 1);
const scale = orbit.radius * 0.00135;
orbit.target
.addScaledVector(right, -dx * scale)
.addScaledVector(up, dy * scale);
}
if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
const distance = Math.hypot(a.x - b.x, a.y - b.y);
if (previousPinchDistance > 0 && distance > 0) {
orbit.radius = clamp(
orbit.radius * (previousPinchDistance / distance),
4.2,
18
);
}
previousPinchDistance = distance;
}
}
updateHoverSample(event);
});
function releasePointer(event) {
pointers.delete(event.pointerId);
if (pointers.size < 2) {
previousPinchDistance = 0;
}
}
canvas.addEventListener("pointerup", releasePointer);
canvas.addEventListener("pointercancel", releasePointer);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius = clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
4.2,
18
);
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetCamera);
document.querySelector("#face-view").addEventListener("click", () => {
orbit.theta = 0;
orbit.phi = Math.PI / 2;
orbit.radius = 9.6;
orbit.target.set(0, 0, 0);
});
document.querySelector("#reset-view").addEventListener("click", resetCamera);
// -------------------------------------------------------------------------
// Lighting and static background
// -------------------------------------------------------------------------
scene.add(new THREE.AmbientLight(0xb8d6ff, 1.15));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.3);
keyLight.position.set(4, 7, 10);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4a7dff, 1.25);
rimLight.position.set(-7, -2, 5);
scene.add(rimLight);
const backdrop = new THREE.Mesh(
new THREE.PlaneGeometry(12.4, 8.2),
new THREE.MeshBasicMaterial({
color: 0x071020,
transparent: true,
opacity: 0.58,
depthWrite: false
})
);
backdrop.position.z = -0.16;
scene.add(backdrop);
const grid = new THREE.GridHelper(12, 24, 0x315175, 0x172943);
grid.rotation.x = Math.PI / 2;
grid.position.z = -0.13;
grid.material.transparent = true;
grid.material.opacity = 0.46;
grid.material.depthWrite = false;
scene.add(grid);
const xAxis = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(-5.8, 0, -0.08),
11.6,
0x526b8c,
0.18,
0.09
);
const yAxis = new THREE.ArrowHelper(
new THREE.Vector3(0, 1, 0),
new THREE.Vector3(0, -3.8, -0.08),
7.6,
0x526b8c,
0.18,
0.09
);
scene.add(xAxis, yAxis);
// Subtle background stars.
const starCount = 650;
const starPositions = new Float32Array(starCount * 3);
for (let i = 0; i < starCount; i++) {
starPositions[i * 3] = (Math.random() - 0.5) * 32;
starPositions[i * 3 + 1] = (Math.random() - 0.5) * 22;
starPositions[i * 3 + 2] = -4 - Math.random() * 18;
}
const starGeometry = new THREE.BufferGeometry();
starGeometry.setAttribute(
"position",
new THREE.BufferAttribute(starPositions, 3)
);
const stars = new THREE.Points(
starGeometry,
new THREE.PointsMaterial({
color: 0x9ccaff,
size: 0.035,
transparent: true,
opacity: 0.5,
depthWrite: false
})
);
scene.add(stars);
// -------------------------------------------------------------------------
// Text and glow helpers
// -------------------------------------------------------------------------
function roundedRect(ctx, x, y, width, height, radius) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(
x + width,
y + height,
x + width - radius,
y + height
);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
}
function makeTextSprite(text, color = "#ffffff", background = null) {
const textCanvas = document.createElement("canvas");
textCanvas.width = 512;
textCanvas.height = 180;
const ctx = textCanvas.getContext("2d");
if (background) {
roundedRect(ctx, 12, 16, 488, 148, 38);
ctx.fillStyle = background;
ctx.fill();
ctx.strokeStyle = "rgba(155, 220, 255, 0.28)";
ctx.lineWidth = 3;
ctx.stroke();
}
ctx.fillStyle = color;
ctx.font = "700 92px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 256, 94);
const texture = new THREE.CanvasTexture(textCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false,
toneMapped: false
});
const sprite = new THREE.Sprite(material);
sprite.renderOrder = 20;
return sprite;
}
function hexToRgb(hex) {
const value = parseInt(hex.replace("#", ""), 16);
return {
r: (value >> 16) & 255,
g: (value >> 8) & 255,
b: value & 255
};
}
function makeGlowTexture(hex) {
const glowCanvas = document.createElement("canvas");
glowCanvas.width = 256;
glowCanvas.height = 256;
const ctx = glowCanvas.getContext("2d");
const { r, g, b } = hexToRgb(hex);
const gradient = ctx.createRadialGradient(
128,
128,
4,
128,
128,
128
);
gradient.addColorStop(0, `rgba(255,255,255,0.95)`);
gradient.addColorStop(0.12, `rgba(${r},${g},${b},0.78)`);
gradient.addColorStop(0.38, `rgba(${r},${g},${b},0.24)`);
gradient.addColorStop(1, `rgba(${r},${g},${b},0)`);
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 256, 256);
const texture = new THREE.CanvasTexture(glowCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
const xLabel = makeTextSprite("x", "#7188a9");
xLabel.position.set(5.92, -0.08, 0);
xLabel.scale.set(0.34, 0.12, 1);
scene.add(xLabel);
const yLabel = makeTextSprite("y", "#7188a9");
yLabel.position.set(0.08, 3.86, 0);
yLabel.scale.set(0.34, 0.12, 1);
scene.add(yLabel);
// -------------------------------------------------------------------------
// Charge objects
// -------------------------------------------------------------------------
function createCharge(hex, sign, glowHex) {
const group = new THREE.Group();
const sphere = new THREE.Mesh(
new THREE.SphereGeometry(CHARGE_RADIUS, 48, 32),
new THREE.MeshPhysicalMaterial({
color: hex,
emissive: hex,
emissiveIntensity: 0.52,
roughness: 0.22,
metalness: 0.12,
clearcoat: 0.8,
clearcoatRoughness: 0.18
})
);
group.add(sphere);
const glow = new THREE.Sprite(
new THREE.SpriteMaterial({
map: makeGlowTexture(glowHex),
color: 0xffffff,
transparent: true,
opacity: 0.62,
blending: THREE.AdditiveBlending,
depthTest: false,
depthWrite: false,
toneMapped: false
})
);
glow.scale.set(1.65, 1.65, 1);
glow.renderOrder = 8;
group.add(glow);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.37, 0.008, 8, 96),
new THREE.MeshBasicMaterial({
color: hex,
transparent: true,
opacity: 0.62,
depthWrite: false
})
);
ring.scale.y = 1.12;
group.add(ring);
const tiltedRing = new THREE.Mesh(
new THREE.TorusGeometry(0.405, 0.005, 6, 80),
new THREE.MeshBasicMaterial({
color: hex,
transparent: true,
opacity: 0.26,
depthWrite: false
})
);
tiltedRing.rotation.x = 0.88;
tiltedRing.rotation.y = 0.24;
group.add(tiltedRing);
const label = makeTextSprite(sign, "#ffffff");
label.position.set(0, 0, 0.315);
label.scale.set(0.37, 0.37, 1);
group.add(label);
const light = new THREE.PointLight(hex, 7, 4, 2);
light.position.z = 0.8;
group.add(light);
group.userData = { sphere, glow, ring, tiltedRing };
scene.add(group);
return group;
}
const positiveCharge = createCharge(0xff416b, "+", "#ff416b");
const negativeCharge = createCharge(0x397dff, "−", "#397dff");
function updateChargePositions() {
chargePositions.positive.x = -separation / 2;
chargePositions.positive.y = 0;
chargePositions.negative.x = separation / 2;
chargePositions.negative.y = 0;
positiveCharge.position.set(chargePositions.positive.x, 0, 0);
negativeCharge.position.set(chargePositions.negative.x, 0, 0);
}
// -------------------------------------------------------------------------
// Electric-field calculation
// -------------------------------------------------------------------------
function fieldAt(x, y) {
const px = chargePositions.positive.x;
const py = chargePositions.positive.y;
const nx = chargePositions.negative.x;
const ny = chargePositions.negative.y;
const dpx = x - px;
const dpy = y - py;
const dnx = x - nx;
const dny = y - ny;
const rp2 = dpx * dpx + dpy * dpy;
const rn2 = dnx * dnx + dny * dny;
const rp3 = rp2 * Math.sqrt(rp2);
const rn3 = rn2 * Math.sqrt(rn2);
const positiveTerm = K * Q / rp3;
const negativeTerm = K * Q / rn3;
const ex = positiveTerm * dpx - negativeTerm * dnx;
const ey = positiveTerm * dpy - negativeTerm * dny;
return {
ex,
ey,
magnitude: Math.hypot(ex, ey)
};
}
function unitFieldAt(x, y) {
const field = fieldAt(x, y);
if (field.magnitude < 1e-10) {
return null;
}
return {
x: field.ex / field.magnitude,
y: field.ey / field.magnitude
};
}
// -------------------------------------------------------------------------
// Instanced field arrows
// -------------------------------------------------------------------------
const arrowGroup = new THREE.Group();
scene.add(arrowGroup);
const arrowSamples = [];
const sampleStepX = 0.60;
const sampleStepY = 0.50;
for (let x = -4.5; x <= 4.5 + 1e-6; x += sampleStepX) {
for (let y = -3.0; y <= 3.0 + 1e-6; y += sampleStepY) {
arrowSamples.push({ x, y });
}
}
const shaftGeometry = new THREE.CylinderGeometry(0.016, 0.016, 1, 7);
const headGeometry = new THREE.ConeGeometry(0.052, 0.14, 9);
const arrowMaterial = new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.93,
toneMapped: false
});
const arrowShafts = new THREE.InstancedMesh(
shaftGeometry,
arrowMaterial,
arrowSamples.length
);
const arrowHeads = new THREE.InstancedMesh(
headGeometry,
arrowMaterial,
arrowSamples.length
);
arrowShafts.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
arrowHeads.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
arrowShafts.frustumCulled = false;
arrowHeads.frustumCulled = false;
arrowGroup.add(arrowShafts, arrowHeads);
const dummy = new THREE.Object3D();
const up = new THREE.Vector3(0, 1, 0);
const direction = new THREE.Vector3();
const lowArrowColor = new THREE.Color(0x47d9ff);
const highArrowColor = new THREE.Color(0xffd166);
const arrowColor = new THREE.Color();
function rebuildArrows() {
const referenceMagnitude =
(K * Q) / Math.pow(separation * 0.4, 2);
arrowSamples.forEach((sample, index) => {
const distanceToPositive = Math.hypot(
sample.x - chargePositions.positive.x,
sample.y - chargePositions.positive.y
);
const distanceToNegative = Math.hypot(
sample.x - chargePositions.negative.x,
sample.y - chargePositions.negative.y
);
const field = fieldAt(sample.x, sample.y);
const hidden =
distanceToPositive < 0.52 ||
distanceToNegative < 0.52 ||
field.magnitude < 1e-9;
if (hidden) {
dummy.position.set(sample.x, sample.y, 0.10);
dummy.quaternion.identity();
dummy.scale.set(0, 0, 0);
dummy.updateMatrix();
arrowShafts.setMatrixAt(index, dummy.matrix);
arrowHeads.setMatrixAt(index, dummy.matrix);
return;
}
direction.set(field.ex, field.ey, 0).normalize();
dummy.quaternion.setFromUnitVectors(up, direction);
const normalizedMagnitude =
Math.sqrt(field.magnitude / referenceMagnitude);
const strength = clamp(normalizedMagnitude / 2.6, 0, 1);
const totalLength = 0.18 + strength * 0.56;
const headLength = Math.min(0.14, totalLength * 0.34);
const shaftLength = totalLength - headLength;
dummy.position.set(
sample.x,
sample.y,
0.10
);
dummy.scale.set(1, shaftLength, 1);
dummy.updateMatrix();
arrowShafts.setMatrixAt(index, dummy.matrix);
dummy.position.set(
sample.x + direction.x * (shaftLength + headLength * 0.5),
sample.y + direction.y * (shaftLength + headLength * 0.5),
0.10
);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
arrowHeads.setMatrixAt(index, dummy.matrix);
arrowColor.lerpColors(
lowArrowColor,
highArrowColor,
strength
);
arrowShafts.setColorAt(index, arrowColor);
arrowHeads.setColorAt(index, arrowColor);
});
arrowShafts.instanceMatrix.needsUpdate = true;
arrowHeads.instanceMatrix.needsUpdate = true;
if (arrowShafts.instanceColor) {
arrowShafts.instanceColor.needsUpdate = true;
}
if (arrowHeads.instanceColor) {
arrowHeads.instanceColor.needsUpdate = true;
}
}
// -------------------------------------------------------------------------
// Field-line integration
//
// The streamline equation is:
// dr/ds = E(r) / |E(r)|
//
// A fourth-order Runge–Kutta integrator traces the tangent field.
// -------------------------------------------------------------------------
const fieldLinesGroup = new THREE.Group();
scene.add(fieldLinesGroup);
const fieldLineTubeMaterial = new THREE.MeshBasicMaterial({
color: 0x66eaff,
transparent: true,
opacity: 0.24,
depthWrite: false,
toneMapped: false
});
const fieldLineDashMaterial = new THREE.LineDashedMaterial({
color: 0xa9f6ff,
transparent: true,
opacity: 0.72,
dashSize: 0.095,
gapSize: 0.055,
depthWrite: false,
toneMapped: false
});
let fieldPaths = [];
function traceFieldLine(angle) {
const seedRadius = CHARGE_RADIUS + 0.026;
const step = 0.028;
const maxSteps = 850;
const maxRadius = 9.0;
let x =
chargePositions.positive.x + seedRadius * Math.cos(angle);
let y =
chargePositions.positive.y + seedRadius * Math.sin(angle);
const points = [
new THREE.Vector3(x, y, 0.025)
];
for (let iteration = 0; iteration < maxSteps; iteration++) {
const k1 = unitFieldAt(x, y);
if (!k1) break;
const k2 = unitFieldAt(
x + 0.5 * step * k1.x,
y + 0.5 * step * k1.y
);
if (!k2) break;
const k3 = unitFieldAt(
x + 0.5 * step * k2.x,
y + 0.5 * step * k2.y
);
if (!k3) break;
const k4 = unitFieldAt(
x + step * k3.x,
y + step * k3.y
);
if (!k4) break;
const nextX =
x +
(step / 6) *
(k1.x + 2 * k2.x + 2 * k3.x + k4.x);
const nextY =
y +
(step / 6) *
(k1.y + 2 * k2.y + 2 * k3.y + k4.y);
const distanceToNegative = Math.hypot(
nextX - chargePositions.negative.x,
nextY - chargePositions.negative.y
);
if (distanceToNegative <= CHARGE_RADIUS + 0.012) {
points.push(new THREE.Vector3(nextX, nextY, 0.025));
break;
}
x = nextX;
y = nextY;
points.push(new THREE.Vector3(x, y, 0.025));
if (Math.hypot(x, y) > maxRadius) {
break;
}
}
return points;
}
function disposeFieldLineGeometry() {
for (const child of [...fieldLinesGroup.children]) {
child.geometry.dispose();
}
fieldLinesGroup.clear();
}
function rebuildFieldLines() {
disposeFieldLineGeometry();
fieldPaths = [];
const lineCount = 36;
for (let index = 0; index < lineCount; index++) {
const angle = (index / lineCount) * Math.PI * 2;
const points = traceFieldLine(angle);
if (points.length < 3) {
continue;
}
fieldPaths.push(points);
// Soft tubular underlay gives the guide more visual presence.
const curve = new THREE.CatmullRomCurve3(
points,
false,
"centripetal"
);
const tubeGeometry = new THREE.TubeGeometry(
curve,
Math.min(260, points.length - 1),
0.0065,
5,
false
);
const tube = new THREE.Mesh(
tubeGeometry,
fieldLineTubeMaterial
);
tube.renderOrder = 3;
fieldLinesGroup.add(tube);
// Dashed mathematical overlay.
const lineGeometry = new THREE.BufferGeometry().setFromPoints(
points.map((point) => {
const clone = point.clone();
clone.z += 0.012;
return clone;
})
);
const dashedLine = new THREE.Line(
lineGeometry,
fieldLineDashMaterial
);
dashedLine.computeLineDistances();
dashedLine.renderOrder = 4;
fieldLinesGroup.add(dashedLine);
}
flowMesh.count = Math.min(fieldPaths.length, flowMesh.instanceMatrix.count);
flowMesh.visible = showLinesInput.checked;
}
// -------------------------------------------------------------------------
// Moving field-direction particles
// -------------------------------------------------------------------------
const flowMesh = new THREE.InstancedMesh(
new THREE.SphereGeometry(0.031, 10, 8),
new THREE.MeshBasicMaterial({
color: 0xc8fbff,
transparent: true,
opacity: 0.92,
depthWrite: false,
toneMapped: false
}),
36
);
flowMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
flowMesh.frustumCulled = false;
flowMesh.renderOrder = 6;
scene.add(flowMesh);
function updateFlowParticles(time) {
const count = Math.min(fieldPaths.length, flowMesh.count);
for (let index = 0; index < count; index++) {
const points = fieldPaths[index];
const u = (time * 0.037 + index * 0.137) % 1;
const scaled = u * (points.length - 1);
const lower = Math.floor(scaled);
const upper = Math.min(lower + 1, points.length - 1);
const fraction = scaled - lower;
const a = points[lower];
const b = points[upper];
const fadeIn = clamp(u / 0.035, 0, 1);
const fadeOut = clamp((1 - u) / 0.035, 0, 1);
const scale = Math.min(fadeIn, fadeOut);
dummy.position.set(
THREE.MathUtils.lerp(a.x, b.x, fraction),
THREE.MathUtils.lerp(a.y, b.y, fraction),
0.052
);
dummy.quaternion.identity();
dummy.scale.setScalar(scale);
dummy.updateMatrix();
flowMesh.setMatrixAt(index, dummy.matrix);
}
flowMesh.instanceMatrix.needsUpdate = true;
}
// -------------------------------------------------------------------------
// Live pointer sampling
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointerNDC = new THREE.Vector2();
const fieldPlane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
const planeIntersection = new THREE.Vector3();
const hoverMarker = new THREE.Mesh(
new THREE.SphereGeometry(0.038, 16, 12),
new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.9,
depthTest: false,
toneMapped: false
})
);
hoverMarker.visible = false;
hoverMarker.renderOrder = 15;
scene.add(hoverMarker);
function formatNumber(value) {
if (Math.abs(value) >= 1000 || (Math.abs(value) < 0.001 && value !== 0)) {
return value.toExponential(2);
}
return value.toFixed(3);
}
function updateHoverSample(event) {
const rect = canvas.getBoundingClientRect();
pointerNDC.x =
((event.clientX - rect.left) / rect.width) * 2 - 1;
pointerNDC.y =
-((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointerNDC, camera);
const hit = raycaster.ray.intersectPlane(
fieldPlane,
planeIntersection
);
if (!hit) {
hoverMarker.visible = false;
readout.innerHTML =
"<b>x</b>—<br><b>y</b>—<br><b>E</b>—<br><b>|E|</b>—";
return;
}
const field = fieldAt(hit.x, hit.y);
hoverMarker.position.set(hit.x, hit.y, 0.09);
hoverMarker.visible = true;
readout.innerHTML = `
<b>x</b>${formatNumber(hit.x)}<br>
<b>y</b>${formatNumber(hit.y)}<br>
<b class="vector">E</b>(${formatNumber(field.ex)}, ${formatNumber(field.ey)})<br>
<b>|E|</b>${formatNumber(field.magnitude)}
`;
}
canvas.addEventListener("pointerleave", () => {
hoverMarker.visible = false;
readout.innerHTML =
"<b>x</b>—<br><b>y</b>—<br><b>E</b>—<br><b>|E|</b>—";
});
// -------------------------------------------------------------------------
// UI and scene rebuilding
// -------------------------------------------------------------------------
let rebuildScheduled = false;
function scheduleSceneRebuild() {
if (rebuildScheduled) return;
rebuildScheduled = true;
requestAnimationFrame(() => {
rebuildScheduled = false;
updateChargePositions();
rebuildArrows();
rebuildFieldLines();
});
}
separationInput.addEventListener("input", () => {
separation = Number(separationInput.value);
separationOutput.value = separation.toFixed(1);
scheduleSceneRebuild();
});
showArrowsInput.addEventListener("change", () => {
arrowGroup.visible = showArrowsInput.checked;
});
showLinesInput.addEventListener("change", () => {
fieldLinesGroup.visible = showLinesInput.checked;
flowMesh.visible = showLinesInput.checked;
});
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 and animation loop
// -------------------------------------------------------------------------
updateChargePositions();
rebuildArrows();
rebuildFieldLines();
updateCamera();
renderer.setAnimationLoop(() => {
const delta = Math.min(clock.getDelta(), 0.05);
elapsedTime += delta;
if (autoRotateInput.checked && pointers.size === 0) {
orbit.theta += delta * 0.12;
}
updateCamera();
const pulse = 1 + Math.sin(elapsedTime * 2.2) * 0.045;
positiveCharge.userData.glow.scale.setScalar(1.65 * pulse);
negativeCharge.userData.glow.scale.setScalar(1.65 * pulse);
positiveCharge.userData.glow.material.opacity =
0.57 + Math.sin(elapsedTime * 2.2) * 0.07;
negativeCharge.userData.glow.material.opacity =
0.57 + Math.sin(elapsedTime * 2.2 + 1.1) * 0.07;
positiveCharge.userData.tiltedRing.rotation.z += delta * 0.18;
negativeCharge.userData.tiltedRing.rotation.z -= delta * 0.16;
stars.rotation.z = Math.sin(elapsedTime * 0.025) * 0.025;
if (showLinesInput.checked) {
updateFlowParticles(elapsedTime);
}
renderer.render(scene, camera);
});
document.querySelector("#loading").classList.add("hidden");
</script>
</body>
</html>
```