Prompt specification
Build or customize the Three.js 3D scene "Electric landscape analogy exhibit" 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: Electric landscape analogy exhibit
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/electric-landscape-analogy-exhibit-x1627
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing electric potential and equipotential surfaces. Compose a height-map analogy beside the actual charge geometry; explicitly state where gravitational terrain intuition helps and where it does not represent literal electric-space height. Voxel style.
Working Three.js Starter (electric-landscape-analogy-exhibit-x1627):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Electric Potential — Voxel Field Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #050a10;
--panel: #08131d;
--panel-edge: #183040;
--text: #eaf4f7;
--muted: #8da5b2;
--positive: #ff8a5c;
--negative: #53d7ff;
--field: #ffd166;
--accent: #8cf0c4;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background:
radial-gradient(circle at 15% 0%, #10283a 0%, transparent 35%),
radial-gradient(circle at 90% 15%, #162132 0%, transparent 32%),
var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
padding: 22px;
}
button,
input,
select {
font: inherit;
}
.app {
width: min(1500px, 100%);
margin: 0 auto;
}
.hero {
display: flex;
justify-content: space-between;
align-items: end;
gap: 30px;
margin-bottom: 18px;
}
.eyebrow {
color: var(--accent);
font-size: 0.73rem;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
h1 {
margin: 5px 0 7px;
font-size: clamp(1.65rem, 3vw, 2.75rem);
line-height: 1;
letter-spacing: -0.04em;
}
.hero p {
max-width: 760px;
margin: 0;
color: var(--muted);
font-size: 0.94rem;
line-height: 1.55;
}
.equation {
flex: 0 0 auto;
padding: 13px 17px;
border: 1px solid var(--panel-edge);
border-radius: 10px;
background: rgba(7, 17, 26, 0.75);
color: #d8f4eb;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.88rem;
text-align: center;
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.18);
}
.toolbar {
display: flex;
flex-wrap: wrap;
align-items: end;
gap: 12px;
margin-bottom: 14px;
padding: 13px;
border: 1px solid var(--panel-edge);
border-radius: 13px;
background: rgba(7, 17, 26, 0.82);
box-shadow: 0 14px 35px rgba(0, 0, 0, 0.16);
}
.control {
display: grid;
gap: 6px;
min-width: 150px;
}
.control.grow {
flex: 1 1 220px;
}
.control label,
.control-title {
color: #a8bec9;
font-size: 0.7rem;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.control output {
float: right;
color: var(--accent);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.74rem;
}
select,
.reset-button {
min-height: 36px;
border: 1px solid #284153;
border-radius: 8px;
background: #0c1b27;
color: var(--text);
}
select {
width: 100%;
padding: 7px 31px 7px 10px;
cursor: pointer;
}
input[type="range"] {
width: 100%;
height: 28px;
margin: 0;
accent-color: var(--accent);
cursor: pointer;
}
.check {
display: flex;
align-items: center;
gap: 8px;
min-height: 36px;
color: #c3d4dc;
font-size: 0.83rem;
cursor: pointer;
user-select: none;
}
.check input {
width: 16px;
height: 16px;
accent-color: var(--accent);
}
.reset-button {
padding: 8px 13px;
cursor: pointer;
font-weight: 700;
}
.reset-button:hover,
select:hover {
border-color: var(--accent);
}
.viewer-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
}
.panel {
position: relative;
height: clamp(480px, 61vh, 680px);
overflow: hidden;
border: 1px solid var(--panel-edge);
border-radius: 15px;
background: #071019;
box-shadow:
0 24px 70px rgba(0, 0, 0, 0.28),
inset 0 0 0 1px rgba(255, 255, 255, 0.018);
isolation: isolate;
}
.panel canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
.panel canvas:active {
cursor: grabbing;
}
.panel-head {
position: absolute;
z-index: 3;
top: 0;
left: 0;
right: 0;
padding: 17px 18px 45px;
pointer-events: none;
background: linear-gradient(
to bottom,
rgba(4, 10, 16, 0.94),
rgba(4, 10, 16, 0.58) 58%,
transparent
);
}
.panel-index {
color: var(--accent);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.69rem;
font-weight: 800;
letter-spacing: 0.12em;
}
.panel h2 {
margin: 5px 0 5px;
font-size: clamp(1.05rem, 1.7vw, 1.38rem);
letter-spacing: -0.025em;
}
.panel-subtitle {
max-width: 570px;
margin: 0;
color: #9eb2bd;
font-size: 0.77rem;
line-height: 1.45;
}
.panel-foot {
position: absolute;
z-index: 3;
right: 0;
bottom: 0;
left: 0;
padding: 38px 16px 14px;
pointer-events: none;
background: linear-gradient(
to top,
rgba(4, 10, 16, 0.94),
rgba(4, 10, 16, 0.48) 62%,
transparent
);
}
.legend {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 9px 15px;
color: #b8cad3;
font-size: 0.7rem;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 10px;
height: 10px;
border-radius: 2px;
box-shadow: 0 0 10px currentColor;
}
.swatch.positive {
color: var(--positive);
background: var(--positive);
}
.swatch.negative {
color: var(--negative);
background: var(--negative);
}
.swatch.surface {
color: #a69cff;
background: rgba(166, 156, 255, 0.65);
}
.swatch.field {
color: var(--field);
background: var(--field);
}
.levels {
margin-top: 8px;
color: #738b99;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.66rem;
}
.world-label {
position: absolute;
z-index: 4;
display: none;
padding: 4px 7px;
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 5px;
background: rgba(3, 9, 14, 0.86);
color: var(--text);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.72rem;
font-weight: 800;
pointer-events: none;
transform: translate(-50%, -100%);
white-space: nowrap;
}
.world-label.positive {
border-color: rgba(255, 138, 92, 0.7);
color: #ffb38f;
}
.world-label.negative {
border-color: rgba(83, 215, 255, 0.7);
color: #a7edff;
}
.tooltip {
position: absolute;
z-index: 6;
display: none;
max-width: 250px;
padding: 7px 9px;
border: 1px solid #3a5668;
border-radius: 6px;
background: rgba(3, 9, 14, 0.94);
color: #e6f4f7;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.67rem;
line-height: 1.45;
pointer-events: none;
box-shadow: 0 8px 22px rgba(0, 0, 0, 0.32);
}
.interaction-hint {
position: absolute;
z-index: 3;
top: 88px;
right: 15px;
padding: 5px 8px;
border: 1px solid rgba(67, 96, 112, 0.55);
border-radius: 5px;
background: rgba(4, 11, 17, 0.68);
color: #78909d;
font-size: 0.62rem;
pointer-events: none;
}
.guide-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
margin-top: 14px;
}
.note {
padding: 17px 19px;
border: 1px solid var(--panel-edge);
border-radius: 13px;
background: rgba(8, 19, 29, 0.76);
}
.note h2 {
margin: 0 0 9px;
font-size: 0.98rem;
}
.note ul {
margin: 0;
padding-left: 18px;
color: #a7bbc5;
font-size: 0.8rem;
line-height: 1.62;
}
.note strong {
color: #e3f1f5;
}
.note.helpful {
border-top: 3px solid var(--accent);
}
.note.caution {
border-top: 3px solid var(--negative);
}
.note.caution strong {
color: #b8efff;
}
footer {
padding: 16px 3px 4px;
color: #637b89;
font-size: 0.7rem;
line-height: 1.55;
}
@media (max-width: 920px) {
body {
padding: 12px;
}
.hero {
display: block;
}
.equation {
display: inline-block;
margin-top: 13px;
}
.viewer-grid,
.guide-grid {
grid-template-columns: 1fr;
}
.panel {
height: 58vh;
min-height: 440px;
}
}
@media (max-width: 560px) {
.toolbar {
align-items: stretch;
}
.control,
.control.grow {
min-width: calc(50% - 8px);
flex: 1 1 calc(50% - 8px);
}
.interaction-hint {
display: none;
}
}
</style>
</head>
<body>
<main class="app">
<header class="hero">
<div>
<div class="eyebrow">Voxel field lab</div>
<h1>Electric potential, in two complementary views</h1>
<p>
Explore actual three-dimensional equipotential shells beside a signed
height-map analogy of the potential in the plane <em>y = 0</em>.
Drag to orbit, scroll to zoom, and hover over blocks for values.
</p>
</div>
<div class="equation">
V(r) = Σ kqᵢ / |r − rᵢ|<br>
E(r) = −∇V(r)
</div>
</header>
<section class="toolbar" aria-label="Visualization controls">
<div class="control grow">
<label for="pattern">Charge arrangement</label>
<select id="pattern">
<option value="dipole">Opposite charges: +Q, −Q</option>
<option value="like">Like charges: +Q, +Q</option>
<option value="negative">Like charges: −Q, −Q</option>
</select>
</div>
<div class="control grow">
<label for="strength">
Charge strength
<output id="strengthOutput">1.0 Q</output>
</label>
<input id="strength" type="range" min="0.6" max="1.8" step="0.1" value="1">
</div>
<div class="control grow">
<label for="separation">
Separation
<output id="separationOutput">2.6</output>
</label>
<input id="separation" type="range" min="1.8" max="3.6" step="0.1" value="2.6">
</div>
<label class="check">
<input id="showSurfaces" type="checkbox" checked>
Equipotential shells
</label>
<label class="check">
<input id="showField" type="checkbox" checked>
E-field arrows
</label>
<button id="resetViews" class="reset-button" type="button">
Reset views
</button>
</section>
<section class="viewer-grid">
<article class="panel" id="actualPanel">
<canvas
id="actualCanvas"
aria-label="Interactive three-dimensional charges and voxelized equipotential surfaces"
></canvas>
<div class="panel-head">
<div class="panel-index">01 / ACTUAL GEOMETRY</div>
<h2>Three-dimensional potential</h2>
<p class="panel-subtitle">
Solid voxel clusters are charges. Translucent blocks mark sampled
equipotential shells <em>V = constant</em> throughout ordinary 3D space.
</p>
</div>
<div class="interaction-hint">Drag: orbit · Wheel: zoom · Right-drag: pan</div>
<div id="actualPositiveLabel" class="world-label positive">+Q</div>
<div id="actualNegativeLabel" class="world-label negative">−Q</div>
<div id="actualTooltip" class="tooltip"></div>
<div class="panel-foot">
<div class="legend">
<span class="legend-item">
<span class="swatch positive"></span> positive charge
</span>
<span class="legend-item">
<span class="swatch negative"></span> negative charge
</span>
<span class="legend-item">
<span class="swatch surface"></span> equipotential shell
</span>
<span class="legend-item">
<span class="swatch field"></span> E = −∇V
</span>
</div>
<div id="actualLevels" class="levels"></div>
</div>
</article>
<article class="panel" id="terrainPanel">
<canvas
id="terrainCanvas"
aria-label="Interactive voxel height map of electric potential"
></canvas>
<div class="panel-head">
<div class="panel-index">02 / HEIGHT-MAP ANALOGY</div>
<h2>Potential as signed voxel terrain</h2>
<p class="panel-subtitle">
The slice <em>V(x, 0, z)</em> is plotted as height: positive values
rise and negative values form pits. This vertical axis is a graph
convention, not literal electric-space height.
</p>
</div>
<div class="interaction-hint">Hover: sample V(x, 0, z)</div>
<div id="terrainPositiveLabel" class="world-label positive">+Q</div>
<div id="terrainNegativeLabel" class="world-label negative">−Q</div>
<div id="terrainTooltip" class="tooltip"></div>
<div class="panel-foot">
<div class="legend">
<span class="legend-item">
<span class="swatch positive"></span> positive V / hill
</span>
<span class="legend-item">
<span class="swatch negative"></span> negative V / pit
</span>
<span class="legend-item">
<span class="swatch" style="color:#405562;background:#405562"></span>
near V = 0
</span>
</div>
<div class="levels">
Plot convention: height ∝ V · Zero plane: V = 0 · Displayed slice: y = 0
</div>
</div>
</article>
</section>
<section class="guide-grid">
<article class="note helpful">
<h2>Where gravitational terrain intuition helps</h2>
<ul>
<li>
A scalar potential can be <strong>graphed as terrain</strong>, so
“uphill” means increasing potential and “downhill” means decreasing
potential.
</li>
<li>
Since <strong>E = −∇V</strong>, the electric-field direction on this
graph points toward decreasing <em>V</em>, analogous to downhill motion
under gravity.
</li>
<li>
Equipotential lines on a terrain map correspond conceptually to the
traces that equipotential surfaces would make if sliced.
</li>
<li>
A positive charge appears as a potential hill and a negative charge
as a potential well, making the direction of the field easier to read.
</li>
</ul>
</article>
<article class="note caution">
<h2>Where the analogy stops</h2>
<ul>
<li>
The terrain height is <strong>not a literal height of electric
space</strong>. Electric potential is a scalar assigned to points in
ordinary three-dimensional space; it does not bend space or create
a preferred physical “up.”
</li>
<li>
In the actual panel, the field lives in the full 3D volume. The right
panel shows only the <strong>two-dimensional slice y = 0</strong> and
converts a number into a vertical plotting axis.
</li>
<li>
Electric field lines are visualization curves in space, not paths that
charges physically climb or slide along.
</li>
<li>
Gravity’s field is also proportional to a potential gradient in many
familiar situations, but gravity and electrostatics remain different
physical systems.
</li>
</ul>
</article>
</section>
<footer>
Surface shells are finite-resolution voxel samples of V = constant.
Terrain height uses an arbitrary visual scale and may be clipped near point
charges. Drag either canvas to orbit; scroll to zoom; right-drag or
Shift-drag to pan.
</footer>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------
// State and DOM
// ---------------------------------------------------------------------
const state = {
pattern: "dipole",
strength: 1,
separation: 2.6,
showSurfaces: true,
showField: true
};
const actualCanvas = document.querySelector("#actualCanvas");
const terrainCanvas = document.querySelector("#terrainCanvas");
const actualPanel = document.querySelector("#actualPanel");
const terrainPanel = document.querySelector("#terrainPanel");
const patternInput = document.querySelector("#pattern");
const strengthInput = document.querySelector("#strength");
const separationInput = document.querySelector("#separation");
const strengthOutput = document.querySelector("#strengthOutput");
const separationOutput = document.querySelector("#separationOutput");
const showSurfacesInput = document.querySelector("#showSurfaces");
const showFieldInput = document.querySelector("#showField");
const resetViewsButton = document.querySelector("#resetViews");
const actualPositiveLabel = document.querySelector("#actualPositiveLabel");
const actualNegativeLabel = document.querySelector("#actualNegativeLabel");
const terrainPositiveLabel = document.querySelector("#terrainPositiveLabel");
const terrainNegativeLabel = document.querySelector("#terrainNegativeLabel");
const actualTooltip = document.querySelector("#actualTooltip");
const terrainTooltip = document.querySelector("#terrainTooltip");
const actualLevels = document.querySelector("#actualLevels");
const SOFTENING = 0.34;
const TERRAIN_CELL = 0.22;
const TERRAIN_HEIGHT_SCALE = 1.05;
let charges = [];
let actualSurfaceMeshes = [];
let terrainTopMesh = null;
let actualLabelData = [];
let terrainLabelData = [];
// ---------------------------------------------------------------------
// Small direct camera controller; no Three.js addons are used.
// ---------------------------------------------------------------------
class VoxelOrbitController {
constructor(camera, element, options = {}) {
this.camera = camera;
this.element = element;
this.dragging = false;
this.pointerId = null;
this.lastX = 0;
this.lastY = 0;
this.target = new THREE.Vector3(...(options.target || [0, 0, 0]));
this.desiredTarget = this.target.clone();
this.radius = options.radius || 10;
this.theta = options.theta ?? 0.7;
this.phi = options.phi ?? 1.0;
this.desiredRadius = this.radius;
this.desiredTheta = this.theta;
this.desiredPhi = this.phi;
this.offset = new THREE.Vector3();
this.spherical = new THREE.Spherical();
element.addEventListener("pointerdown", (event) => {
if (event.button !== 0 && event.button !== 2) return;
this.dragging = true;
this.pointerId = event.pointerId;
this.lastX = event.clientX;
this.lastY = event.clientY;
element.setPointerCapture(event.pointerId);
});
element.addEventListener("pointermove", (event) => {
if (!this.dragging || event.pointerId !== this.pointerId) return;
const dx = event.clientX - this.lastX;
const dy = event.clientY - this.lastY;
this.lastX = event.clientX;
this.lastY = event.clientY;
if (event.button === 2 || event.shiftKey) {
const panScale = this.desiredRadius * 0.0015;
this.desiredTarget.x -= dx * panScale;
this.desiredTarget.z -= dy * panScale;
} else {
this.desiredTheta -= dx * 0.006;
this.desiredPhi -= dy * 0.006;
this.desiredPhi = THREE.MathUtils.clamp(
this.desiredPhi,
0.16,
Math.PI - 0.16
);
}
});
const endDrag = (event) => {
if (event.pointerId !== this.pointerId) return;
this.dragging = false;
this.pointerId = null;
if (element.hasPointerCapture(event.pointerId)) {
element.releasePointerCapture(event.pointerId);
}
};
element.addEventListener("pointerup", endDrag);
element.addEventListener("pointercancel", endDrag);
element.addEventListener("contextmenu", (event) => event.preventDefault());
element.addEventListener(
"wheel",
(event) => {
event.preventDefault();
const factor = Math.exp(event.deltaY * 0.001);
this.desiredRadius = THREE.MathUtils.clamp(
this.desiredRadius * factor,
4.5,
22
);
},
{ passive: false }
);
}
setView({ radius, theta, phi, target }) {
if (radius !== undefined) {
this.radius = this.desiredRadius = radius;
}
if (theta !== undefined) {
this.theta = this.desiredTheta = theta;
}
if (phi !== undefined) {
this.phi = this.desiredPhi = phi;
}
if (target) {
this.target.set(...target);
this.desiredTarget.set(...target);
}
this.update(1);
}
update(dt) {
const smoothing = 1 - Math.exp(-10 * dt);
this.radius = THREE.MathUtils.lerp(
this.radius,
this.desiredRadius,
smoothing
);
this.theta = THREE.MathUtils.lerp(
this.theta,
this.desiredTheta,
smoothing
);
this.phi = THREE.MathUtils.lerp(
this.phi,
this.desiredPhi,
smoothing
);
this.target.lerp(this.desiredTarget, smoothing);
this.spherical.set(this.radius, this.phi, this.theta);
this.offset.setFromSpherical(this.spherical);
this.camera.position.copy(this.target).add(this.offset);
this.camera.lookAt(this.target);
}
}
// ---------------------------------------------------------------------
// Renderer setup
// ---------------------------------------------------------------------
function makeRenderer(canvas) {
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.75));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.18;
return renderer;
}
const actualRenderer = makeRenderer(actualCanvas);
const terrainRenderer = makeRenderer(terrainCanvas);
actualRenderer.shadowMap.enabled = true;
actualRenderer.shadowMap.type = THREE.PCFSoftShadowMap;
const actualScene = new THREE.Scene();
actualScene.background = new THREE.Color(0x071019);
actualScene.fog = new THREE.Fog(0x071019, 13, 27);
const terrainScene = new THREE.Scene();
terrainScene.background = new THREE.Color(0x071019);
terrainScene.fog = new THREE.Fog(0x071019, 13, 27);
const actualCamera = new THREE.PerspectiveCamera(43, 1, 0.1, 70);
const terrainCamera = new THREE.PerspectiveCamera(43, 1, 0.1, 70);
const actualControls = new VoxelOrbitController(actualCamera, actualCanvas, {
radius: 11.4,
theta: 0.72,
phi: 1.03,
target: [0, -0.1, 0]
});
const terrainControls = new VoxelOrbitController(
terrainCamera,
terrainCanvas,
{
radius: 11.8,
theta: 0,
phi: 0.72,
target: [0, 0, 0]
}
);
function addLights(scene, shadows = false) {
const hemisphere = new THREE.HemisphereLight(0xa9d9ef, 0x081018, 1.65);
scene.add(hemisphere);
const key = new THREE.DirectionalLight(0xfff1da, 2.8);
key.position.set(5.5, 8, 6);
key.castShadow = shadows;
if (shadows) {
key.shadow.mapSize.set(1024, 1024);
key.shadow.camera.left = -7;
key.shadow.camera.right = 7;
key.shadow.camera.top = 7;
key.shadow.camera.bottom = -7;
key.shadow.camera.near = 1;
key.shadow.camera.far = 25;
key.shadow.bias = -0.0003;
}
scene.add(key);
const rim = new THREE.DirectionalLight(0x5bbcff, 1.15);
rim.position.set(-6, 3.5, -5);
scene.add(rim);
}
addLights(actualScene, true);
addLights(terrainScene, false);
const actualGround = new THREE.Mesh(
new THREE.BoxGeometry(9.7, 0.12, 7.1),
new THREE.MeshStandardMaterial({
color: 0x09141e,
roughness: 0.96,
metalness: 0
})
);
actualGround.position.y = -3.34;
actualGround.receiveShadow = true;
actualScene.add(actualGround);
const actualGrid = new THREE.GridHelper(9.6, 24, 0x244151, 0x142733);
actualGrid.position.y = -3.265;
actualGrid.material.transparent = true;
actualGrid.material.opacity = 0.64;
actualScene.add(actualGrid);
const chargeGroup = new THREE.Group();
const surfaceGroup = new THREE.Group();
const fieldGroup = new THREE.Group();
actualScene.add(chargeGroup, surfaceGroup, fieldGroup);
const terrainDynamic = new THREE.Group();
terrainScene.add(terrainDynamic);
// A custom zero-level reference grid for the terrain panel.
{
const positions = [];
const xMin = -4.6;
const xMax = 4.6;
const zMin = -3;
const zMax = 3;
for (let x = xMin; x <= xMax + 0.001; x += 9.2 / 20) {
positions.push(x, 0.012, zMin, x, 0.012, zMax);
}
for (let z = zMin; z <= zMax + 0.001; z += 6 / 12) {
positions.push(xMin, 0.012, z, xMax, 0.012, z);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
const lines = new THREE.LineSegments(
geometry,
new THREE.LineBasicMaterial({
color: 0x385361,
transparent: true,
opacity: 0.42
})
);
terrainScene.add(lines);
}
// ---------------------------------------------------------------------
// Potential model
// ---------------------------------------------------------------------
function makeCharges() {
const half = state.separation / 2;
const q = state.strength;
if (state.pattern === "like") {
return [
{ x: -half, q: +q },
{ x: +half, q: +q }
];
}
if (state.pattern === "negative") {
return [
{ x: -half, q: -q },
{ x: +half, q: -q }
];
}
return [
{ x: -half, q: +q },
{ x: +half, q: -q }
];
}
function potentialWithCharges(x, y, z, sourceCharges) {
let value = 0;
for (const charge of sourceCharges) {
const dx = x - charge.x;
const dy = y;
const dz = z;
const denominator = Math.sqrt(
dx * dx + dy * dy + dz * dz + SOFTENING * SOFTENING
);
value += charge.q / denominator;
}
return value;
}
function potential(x, y, z) {
return potentialWithCharges(x, y, z, charges);
}
function getEquipotentialLevels() {
const ratios = [0.28, 0.48, 0.78, 1.18];
const levels = [];
if (state.pattern !== "negative") {
for (const ratio of ratios) {
levels.push(state.strength * ratio);
}
}
if (state.pattern !== "like") {
for (const ratio of ratios) {
levels.push(-state.strength * ratio);
}
}
return levels.sort((a, b) => a - b);
}
function formatLevel(value) {
const sign = value > 0 ? "+" : "−";
return `${sign}${Math.abs(value).toFixed(2)}`;
}
// ---------------------------------------------------------------------
// Scene construction helpers
// ---------------------------------------------------------------------
function clearGroup(group) {
while (group.children.length) {
const child = group.children.pop();
if (child.geometry) child.geometry.dispose();
if (Array.isArray(child.material)) {
child.material.forEach((material) => material.dispose());
} else if (child.material) {
child.material.dispose();
}
}
}
const dummy = new THREE.Object3D();
const yAxis = new THREE.Vector3(0, 1, 0);
function setInstanceTransform(mesh, index, position, quaternion, scale) {
dummy.position.copy(position);
dummy.quaternion.copy(quaternion);
dummy.scale.copy(scale);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
}
function buildVoxelCharge(charge) {
const spacing = 0.16;
const radius = 0.53;
const positions = [];
for (let ix = -4; ix <= 4; ix++) {
for (let iy = -4; iy <= 4; iy++) {
for (let iz = -4; iz <= 4; iz++) {
const x = ix * spacing;
const y = iy * spacing;
const z = iz * spacing;
if (x * x + y * y + z * z <= radius * radius) {
positions.push(new THREE.Vector3(x, y, z));
}
}
}
}
const positive = charge.q > 0;
const color = positive ? 0xff8054 : 0x48cfff;
const emissive = positive ? 0x8d260c : 0x075b86;
const geometry = new THREE.BoxGeometry(
spacing * 0.94,
spacing * 0.94,
spacing * 0.94
);
const material = new THREE.MeshStandardMaterial({
color,
emissive,
emissiveIntensity: positive ? 0.62 : 0.72,
roughness: 0.42,
metalness: 0.05
});
const mesh = new THREE.InstancedMesh(
geometry,
material,
positions.length
);
positions.forEach((position, index) => {
setInstanceTransform(
mesh,
index,
position.add(new THREE.Vector3(charge.x, 0, 0)),
new THREE.Quaternion(),
new THREE.Vector3(1, 1, 1)
);
});
mesh.instanceMatrix.needsUpdate = true;
mesh.castShadow = true;
mesh.frustumCulled = false;
return mesh;
}
function buildEquipotentialSurfaces() {
actualSurfaceMeshes = [];
const levels = getEquipotentialLevels();
if (!levels.length) return;
const nx = 53;
const ny = 37;
const nz = 37;
const xMin = -4.68;
const yMin = -3.24;
const zMin = -3.24;
const step = 0.18;
const values = new Float32Array(nx * ny * nz);
for (let k = 0; k < nz; k++) {
const z = zMin + k * step;
for (let j = 0; j < ny; j++) {
const y = yMin + j * step;
for (let i = 0; i < nx; i++) {
const x = xMin + i * step;
const index = i + nx * (j + ny * k);
values[index] = potentialWithCharges(x, y, z, charges);
}
}
}
const buckets = levels.map(() => []);
const ratios = [0.28, 0.48, 0.78, 1.18];
for (let k = 0; k < nz - 1; k++) {
for (let j = 0; j < ny - 1; j++) {
for (let i = 0; i < nx - 1; i++) {
const indices = [
i + nx * (j + ny * k),
i + 1 + nx * (j + ny * k),
i + nx * (j + 1 + ny * k),
i + 1 + nx * (j + 1 + ny * k),
i + nx * (j + ny * (k + 1)),
i + 1 + nx * (j + ny * (k + 1)),
i + nx * (j + 1 + ny * (k + 1)),
i + 1 + nx * (j + 1 + ny * (k + 1))
];
let min = Infinity;
let max = -Infinity;
for (const index of indices) {
min = Math.min(min, values[index]);
max = Math.max(max, values[index]);
}
if (min === max) continue;
const center = new THREE.Vector3(
xMin + (i + 0.5) * step,
yMin + (j + 0.5) * step,
zMin + (k + 0.5) * step
);
levels.forEach((level, levelIndex) => {
if (level >= min && level <= max) {
buckets[levelIndex].push(center.clone());
}
});
}
}
}
levels.forEach((level, levelIndex) => {
const bucket = buckets[levelIndex];
if (!bucket.length) return;
const ratioIndex = ratios.findIndex(
(ratio) => Math.abs(ratio - Math.abs(level) / state.strength) < 0.02
);
const positive = level > 0;
const color = new THREE.Color();
if (positive) {
color.setHSL(0.045, 0.9, 0.43 + ratioIndex * 0.045);
} else {
color.setHSL(0.535, 0.86, 0.47 + ratioIndex * 0.045);
}
const geometry = new THREE.BoxGeometry(
step * 0.72,
step * 0.72,
step * 0.72
);
const material = new THREE.MeshStandardMaterial({
color,
emissive: color.clone().multiplyScalar(0.48),
emissiveIntensity: 0.55,
roughness: 0.38,
metalness: 0.02,
transparent: true,
opacity: 0.37,
depthWrite: false
});
const mesh = new THREE.InstancedMesh(
geometry,
material,
bucket.length
);
bucket.forEach((position, index) => {
setInstanceTransform(
mesh,
index,
position,
new THREE.Quaternion(),
new THREE.Vector3(1, 1, 1)
);
});
mesh.instanceMatrix.needsUpdate = true;
mesh.userData.level = level;
mesh.userData.label = formatLevel(level);
mesh.renderOrder = 1;
mesh.frustumCulled = false;
actualSurfaceMeshes.push(mesh);
surfaceGroup.add(mesh);
});
}
function buildFieldArrows() {
const shaftTransforms = [];
const headTransforms = [];
for (let x = -4.15; x <= 4.15; x += 0.62) {
for (let z = -2.85; z <= 2.85; z += 0.62) {
const tooClose = charges.some(
(charge) => Math.hypot(x - charge.x, z) < 0.88
);
if (tooClose) continue;
const h = 0.075;
const dvdx =
(potential(x + h, 0, z) - potential(x - h, 0, z)) / (2 * h);
const dvdz =
(potential(x, 0, z + h) - potential(x, 0, z - h)) / (2 * h);
const field = new THREE.Vector3(-dvdx, 0, -dvdz);
const magnitude = field.length();
if (magnitude < 0.045) continue;
const direction = field.normalize();
const length = THREE.MathUtils.clamp(
0.16 + Math.log1p(magnitude * 2.2) * 0.18,
0.16,
0.62
);
const origin = new THREE.Vector3(x, 0.035, z);
const center = origin.clone().addScaledVector(direction, length * 0.5);
const quaternion = new THREE.Quaternion().setFromUnitVectors(
yAxis,
direction
);
shaftTransforms.push({
position: center,
quaternion,
scale: new THREE.Vector3(0.047, length, 0.047)
});
const headSizes = [0.145, 0.108, 0.071];
const offsets = [0.035, 0.105, 0.175];
headSizes.forEach((size, index) => {
headTransforms.push({
position: origin
.clone()
.addScaledVector(direction, length - offsets[index]),
quaternion: new THREE.Quaternion(),
scale: new THREE.Vector3(size, size, size)
});
});
}
}
if (!shaftTransforms.length) return;
const shaftMaterial = new THREE.MeshBasicMaterial({
color: 0xffd166
});
const shaft = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
shaftMaterial,
shaftTransforms.length
);
shaftTransforms.forEach((transform, index) => {
setInstanceTransform(
shaft,
index,
transform.position,
transform.quaternion,
transform.scale
);
});
shaft.instanceMatrix.needsUpdate = true;
shaft.renderOrder = 3;
shaft.frustumCulled = false;
fieldGroup.add(shaft);
const head = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshBasicMaterial({ color: 0xffe39a }),
headTransforms.length
);
headTransforms.forEach((transform, index) => {
setInstanceTransform(
head,
index,
transform.position,
transform.quaternion,
transform.scale
);
});
head.instanceMatrix.needsUpdate = true;
head.renderOrder = 4;
head.frustumCulled = false;
fieldGroup.add(head);
}
function buildActualScene() {
clearGroup(chargeGroup);
clearGroup(surfaceGroup);
clearGroup(fieldGroup);
charges = makeCharges();
actualLabelData = [];
for (const charge of charges) {
const mesh = buildVoxelCharge(charge);
chargeGroup.add(mesh);
actualLabelData.push({
element: charge.q > 0 ? actualPositiveLabel : actualNegativeLabel,
position: new THREE.Vector3(charge.x, 0.78, 0),
visible: true
});
}
buildEquipotentialSurfaces();
buildFieldArrows();
surfaceGroup.visible = state.showSurfaces;
fieldGroup.visible = state.showField;
}
// ---------------------------------------------------------------------
// Voxel terrain construction
// ---------------------------------------------------------------------
function buildTerrain() {
clearGroup(terrainDynamic);
terrainTopMesh = null;
const nx = 40;
const nz = 26;
const xMin = -4.6;
const xMax = 4.6;
const zMin = -3;
const zMax = 3;
const fills = [];
const tops = [];
for (let iz = 0; iz < nz; iz++) {
const z = zMin + ((iz + 0.5) * (zMax - zMin)) / nz;
for (let ix = 0; ix < nx; ix++) {
const x = xMin + ((ix + 0.5) * (xMax - xMin)) / nx;
const value = potentialWithCharges(x, 0, z, charges);
const rawHeight = THREE.MathUtils.clamp(
value * TERRAIN_HEIGHT_SCALE,
-2.86,
2.86
);
const quantized = THREE.MathUtils.clamp(
Math.round(rawHeight / TERRAIN_CELL),
-13,
13
);
const magnitude = Math.abs(quantized);
const positive = value >= 0;
const topY =
quantized > 0
? (quantized - 0.5) * TERRAIN_CELL
: quantized < 0
? -(magnitude - 0.5) * TERRAIN_CELL
: -0.5 * TERRAIN_CELL;
tops.push({
position: new THREE.Vector3(x, topY, z),
color:
value > 0.045
? new THREE.Color().setHSL(0.045, 0.9, 0.57)
: value < -0.045
? new THREE.Color().setHSL(0.535, 0.86, 0.59)
: new THREE.Color().setHSL(0.48, 0.13, 0.20),
value
});
for (let j = 0; j < Math.max(0, magnitude - 1); j++) {
const y = positive
? (j + 0.5) * TERRAIN_CELL
: -(j + 0.5) * TERRAIN_CELL;
const color = positive
? new THREE.Color().setHSL(0.045, 0.55, 0.17 + j * 0.012)
: new THREE.Color().setHSL(0.535, 0.52, 0.16 + j * 0.012);
fills.push({
position: new THREE.Vector3(x, y, z),
color
});
}
}
}
const fillMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.9,
metalness: 0.01
});
const fillMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(
TERRAIN_CELL * 0.95,
TERRAIN_CELL * 0.95,
TERRAIN_CELL * 0.95
),
fillMaterial,
fills.length
);
fills.forEach((item, index) => {
setInstanceTransform(
fillMesh,
index,
item.position,
new THREE.Quaternion(),
new THREE.Vector3(1, 1, 1)
);
fillMesh.setColorAt(index, item.color);
});
fillMesh.instanceMatrix.needsUpdate = true;
if (fillMesh.instanceColor) fillMesh.instanceColor.needsUpdate = true;
fillMesh.frustumCulled = false;
terrainDynamic.add(fillMesh);
const topMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.7,
metalness: 0.025
});
const topMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(
TERRAIN_CELL * 0.97,
TERRAIN_CELL * 0.97,
TERRAIN_CELL * 0.97
),
topMaterial,
tops.length
);
tops.forEach((item, index) => {
setInstanceTransform(
topMesh,
index,
item.position,
new THREE.Quaternion(),
new THREE.Vector3(1, 1, 1)
);
topMesh.setColorAt(index, item.color);
});
topMesh.instanceMatrix.needsUpdate = true;
if (topMesh.instanceColor) topMesh.instanceColor.needsUpdate = true;
topMesh.frustumCulled = false;
terrainTopMesh = topMesh;
terrainDynamic.add(topMesh);
terrainLabelData = [];
for (const charge of charges) {
const value = potentialWithCharges(charge.x, 0, 0, charges);
const rawHeight = THREE.MathUtils.clamp(
value * TERRAIN_HEIGHT_SCALE,
-2.86,
2.86
);
const quantized = Math.round(rawHeight / TERRAIN_CELL);
terrainLabelData.push({
element: charge.q > 0 ? terrainPositiveLabel : terrainNegativeLabel,
position: new THREE.Vector3(
charge.x,
quantized * TERRAIN_CELL + 0.35,
0
),
visible: true
});
}
}
// ---------------------------------------------------------------------
// Labels and hover readouts
// ---------------------------------------------------------------------
function updateWorldLabel(labelData, camera, canvas) {
const rect = canvas.getBoundingClientRect();
for (const item of labelData) {
const projected = item.position.clone().project(camera);
const visible =
item.visible &&
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.08 &&
Math.abs(projected.y) < 1.08;
item.element.style.display = visible ? "block" : "none";
if (!visible) continue;
const x = (projected.x * 0.5 + 0.5) * rect.width;
const y = (-projected.y * 0.5 + 0.5) * rect.height;
item.element.style.left = `${x}px`;
item.element.style.top = `${y}px`;
}
}
const actualRaycaster = new THREE.Raycaster();
const terrainRaycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
actualCanvas.addEventListener("pointermove", (event) => {
if (actualControls.dragging) {
actualTooltip.style.display = "none";
return;
}
const rect = actualCanvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
actualRaycaster.setFromCamera(pointer, actualCamera);
const hits = actualRaycaster.intersectObjects(actualSurfaceMeshes, false);
if (!hits.length) {
actualTooltip.style.display = "none";
return;
}
const level = hits[0].object.userData.label;
actualTooltip.textContent = `Equipotential shell: V = ${level}`;
actualTooltip.style.display = "block";
actualTooltip.style.left = `${event.clientX - rect.left + 12}px`;
actualTooltip.style.top = `${event.clientY - rect.top + 12}px`;
});
actualCanvas.addEventListener("pointerleave", () => {
actualTooltip.style.display = "none";
});
terrainCanvas.addEventListener("pointermove", (event) => {
if (terrainControls.dragging || !terrainTopMesh) {
terrainTooltip.style.display = "none";
return;
}
const rect = terrainCanvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
terrainRaycaster.setFromCamera(pointer, terrainCamera);
const hits = terrainRaycaster.intersectObject(terrainTopMesh, false);
if (!hits.length) {
terrainTooltip.style.display = "none";
return;
}
const point = hits[0].point;
const value = potentialWithCharges(point.x, 0, point.z, charges);
terrainTooltip.textContent =
`x = ${point.x.toFixed(2)}, z = ${point.z.toFixed(2)}\n` +
`V(x, 0, z) = ${value.toFixed(3)}`;
terrainTooltip.style.whiteSpace = "pre-line";
terrainTooltip.style.display = "block";
terrainTooltip.style.left = `${event.clientX - rect.left + 12}px`;
terrainTooltip.style.top = `${event.clientY - rect.top + 12}px`;
});
terrainCanvas.addEventListener("pointerleave", () => {
terrainTooltip.style.display = "none";
});
// ---------------------------------------------------------------------
// Controls, resizing, and rebuild scheduling
// ---------------------------------------------------------------------
function updateReadouts() {
strengthOutput.textContent = `${Number(strengthInput.value).toFixed(1)} Q`;
separationOutput.textContent = Number(
separationInput.value
).toFixed(1);
const levels = getEquipotentialLevels();
actualLevels.textContent =
`Equipotential values: ${levels.map(formatLevel).join(", ")} · ` +
`shell blocks are finite-resolution samples`;
}
let rebuildTimer = null;
function scheduleRebuild() {
updateReadouts();
clearTimeout(rebuildTimer);
rebuildTimer = setTimeout(() => {
buildActualScene();
buildTerrain();
}, 75);
}
patternInput.addEventListener("change", () => {
state.pattern = patternInput.value;
scheduleRebuild();
});
strengthInput.addEventListener("input", () => {
state.strength = Number(strengthInput.value);
scheduleRebuild();
});
separationInput.addEventListener("input", () => {
state.separation = Number(separationInput.value);
scheduleRebuild();
});
showSurfacesInput.addEventListener("change", () => {
state.showSurfaces = showSurfacesInput.checked;
surfaceGroup.visible = state.showSurfaces;
});
showFieldInput.addEventListener("change", () => {
state.showField = showFieldInput.checked;
fieldGroup.visible = state.showField;
});
resetViewsButton.addEventListener("click", () => {
actualControls.setView({
radius: 11.4,
theta: 0.72,
phi: 1.03,
target: [0, -0.1, 0]
});
terrainControls.setView({
radius: 11.8,
theta: 0,
phi: 0.72,
target: [0, 0, 0]
});
});
function fitRenderer(renderer, camera, panel) {
const width = Math.max(1, panel.clientWidth);
const height = Math.max(1, panel.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(() => {
fitRenderer(actualRenderer, actualCamera, actualPanel);
fitRenderer(terrainRenderer, terrainCamera, terrainPanel);
});
resizeObserver.observe(actualPanel);
resizeObserver.observe(terrainPanel);
fitRenderer(actualRenderer, actualCamera, actualPanel);
fitRenderer(terrainRenderer, terrainCamera, terrainPanel);
updateReadouts();
buildActualScene();
buildTerrain();
// ---------------------------------------------------------------------
// Animation loop
// ---------------------------------------------------------------------
let previousTime = performance.now();
function animate(time) {
const dt = Math.min((time - previousTime) / 1000, 0.05);
previousTime = time;
actualControls.update(dt);
terrainControls.update(dt);
actualRenderer.render(actualScene, actualCamera);
terrainRenderer.render(terrainScene, terrainCamera);
updateWorldLabel(actualLabelData, actualCamera, actualCanvas);
updateWorldLabel(terrainLabelData, terrainCamera, terrainCanvas);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```