Prompt specification
Build or customize the Three.js 3D scene "Moving test charge between potential levels" 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: Moving test charge between potential levels
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/moving-test-charge-between-potential-levels-x1626
Scene Description Prompt:
Make one HTML file using Three.js from cdnjs for this stylized scene: Animate a labeled test charge along two paths between the same endpoints in a static ideal field; show equal potential-energy change for both paths.
Working Three.js Starter (moving-test-charge-between-potential-levels-x1626):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Path Independence of ΔU in a Static Field</title>
<style>
:root{
--p1:#38bdf8; /* path 1 - inner arc */
--p2:#fbbf24; /* path 2 - outer detour */
--ok:#34d399;
--txt:#dbe7f5;
--dim:#8fa6c0;
--panel:rgba(7,14,28,.78);
--edge:rgba(120,170,220,.22);
}
*{box-sizing:border-box}
html,body{margin:0;height:100%;overflow:hidden;background:#04070f;color:var(--txt);
font-family:ui-sans-serif,system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif}
#stage{position:fixed;inset:0}
#stage canvas{display:block}
#labels{position:fixed;inset:0;pointer-events:none;z-index:3}
.lbl{position:absolute;left:0;top:0;white-space:nowrap;font-size:12px;font-variant-numeric:tabular-nums;
background:rgba(6,12,24,.72);border:1px solid var(--edge);border-radius:8px;padding:3px 8px;
box-shadow:0 4px 18px rgba(0,0,0,.55);color:#e6f1ff}
.lbl b{font-weight:600}
.lbl.src{border-color:rgba(99,140,255,.5);color:#bcd0ff}
.lbl.q{border-color:rgba(52,211,153,.6);color:#c7ffe9}
.lbl.a1{border-color:rgba(56,189,248,.55);color:#cdeeff}
.lbl.a2{border-color:rgba(251,191,36,.55);color:#ffeec2}
.panel{position:fixed;background:var(--panel);border:1px solid var(--edge);border-radius:14px;
backdrop-filter:blur(10px);box-shadow:0 12px 40px rgba(0,0,0,.55);z-index:4}
#hud{top:14px;left:14px;width:352px;padding:14px 15px 13px}
#hud h1{margin:0 0 3px;font-size:14.5px;letter-spacing:.2px;font-weight:650}
#hud .sub{margin:0 0 10px;font-size:11.5px;color:var(--dim);line-height:1.35}
.sect{font-size:10.5px;letter-spacing:.14em;text-transform:uppercase;color:#6f88a6;margin:10px 0 6px}
table{width:100%;border-collapse:collapse;font-size:11.5px;font-variant-numeric:tabular-nums}
td,th{padding:2.5px 0;text-align:right}
td:first-child,th:first-child{text-align:left}
th{color:#6f88a6;font-weight:500;font-size:10.5px;letter-spacing:.05em}
.rule{border-top:1px solid rgba(120,170,220,.14);margin-top:9px;padding-top:8px}
.c1{color:var(--p1)} .c2{color:var(--p2)} .ok{color:var(--ok)}
#livebox{margin-top:8px;padding:8px 9px;border:1px solid var(--edge);border-radius:10px;background:rgba(20,40,70,.35)}
#livebox .l1{font-size:11px;color:var(--dim);display:flex;justify-content:space-between}
#livebox .l1 span:last-child{color:#eaf3ff}
#bigU{font-size:19px;font-weight:650;margin-top:2px;font-variant-numeric:tabular-nums}
#bar{height:7px;border-radius:4px;background:rgba(255,255,255,.08);margin-top:7px;overflow:hidden}
#bar i{display:block;height:100%;width:0%;border-radius:4px;background:linear-gradient(90deg,#3b82f6,#a78bfa)}
#verdict{margin-top:9px;font-size:11.5px;line-height:1.45;padding:8px 9px;border-radius:10px;
border:1px solid rgba(52,211,153,.35);background:rgba(16,60,50,.35);color:#bff5df}
#verdict.pending{border-color:rgba(120,170,220,.25);background:rgba(20,32,52,.4);color:#a9bdd6}
.note{font-size:10.5px;color:#6f88a6;line-height:1.4;margin-top:8px}
#graphwrap{right:14px;bottom:14px;padding:10px 11px 6px}
#graph{display:block;width:330px;height:186px}
#ctl{left:50%;transform:translateX(-50%);bottom:14px;padding:8px 10px;display:flex;gap:7px;align-items:center;flex-wrap:wrap;justify-content:center}
button,select{font:inherit;font-size:11.5px;color:var(--txt);background:rgba(30,50,85,.65);
border:1px solid var(--edge);border-radius:8px;padding:5px 10px;cursor:pointer}
button:hover{background:rgba(48,80,135,.8);border-color:rgba(150,200,255,.45)}
button.on{background:rgba(56,189,248,.25);border-color:rgba(56,189,248,.6)}
label.chk{display:flex;align-items:center;gap:5px;font-size:11.5px;color:var(--dim);cursor:pointer}
#title{position:fixed;top:14px;left:50%;transform:translateX(-50%);z-index:4;text-align:center;pointer-events:none}
#title .t{font-size:13px;letter-spacing:.22em;text-transform:uppercase;color:#9fd6ff;opacity:.85}
#title .s{font-size:11px;color:#6f88a6;margin-top:3px}
@media (max-width:1000px){
#hud{width:300px;font-size:11px}
#graph{width:270px;height:160px}
}
@media (max-width:720px){
#hud{width:auto;right:14px}
#graphwrap{display:none}
}
</style>
</head>
<body>
<div id="stage"></div>
<div id="labels"></div>
<div id="title">
<div class="t">Static Ideal Field • Path Independence of ΔU</div>
<div class="s">One test charge, two routes, identical endpoints → identical potential-energy change</div>
</div>
<aside id="hud" class="panel">
<h1>Path independence of the potential-energy change</h1>
<p class="sub">Ideal point charge <b>Q</b> at the origin creates a static Coulomb field.
A labelled test charge <b>q</b> is carried from <b>A</b> to <b>B</b> along two different paths.</p>
<div class="sect">Source & test charge</div>
<table>
<tr><td>Source charge Q</td><td>+2.000 µC</td></tr>
<tr><td>Test charge q</td><td>+10.00 nC</td></tr>
<tr><td>k</td><td>8.988×10⁹ N·m²/C²</td></tr>
</table>
<div class="sect">Endpoints</div>
<table>
<tr><th></th><th>r</th><th>V = kQ/r</th><th>U = qV</th></tr>
<tr><td class="c1">A (start)</td><td id="rA">–</td><td id="vA">–</td><td id="uA">–</td></tr>
<tr><td class="c2">B (end)</td><td id="rB">–</td><td id="vB">–</td><td id="uB">–</td></tr>
</table>
<div class="sect">Live readout</div>
<div id="livebox">
<div class="l1"><span id="lpath">Path 1</span><span id="lprog">0 %</span></div>
<div id="bigU">U = –</div>
<div class="l1"><span id="lsub">r = – • V = – • E = –</span></div>
<div id="bar"><i></i></div>
</div>
<div class="sect">Result of the two routes</div>
<table>
<tr><th>Route</th><th>ΔU = U<sub>B</sub>−U<sub>A</sub></th><th>W<sub>field</sub> (numeric ∫F·dl)</th><th>match</th></tr>
<tr><td class="c1">1 · inner arc</td><td id="du1">–</td><td id="w1">–</td><td id="m1">…</td></tr>
<tr><td class="c2">2 · outer detour</td><td id="du2">–</td><td id="w2">–</td><td id="m2">…</td></tr>
</table>
<div id="verdict" class="pending">Measuring route 1 …</div>
<div class="note">E = kQ/r² is conservative (∮E·dl = 0), so the work done by the field — and therefore
ΔU = q(V<sub>B</sub>−V<sub>A</sub>) — depends only on the endpoints, not on the route.</div>
</aside>
<div id="graphwrap" class="panel">
<canvas id="graph"></canvas>
</div>
<div id="ctl" class="panel">
<button id="btnPlay">⏸ Pause</button>
<button id="btnRestart">↻ Restart</button>
<select id="speed">
<option value="0.5">0.5× speed</option>
<option value="1" selected>1× speed</option>
<option value="2">2× speed</option>
</select>
<button id="btnField" class="on">Field lines</button>
<button id="btnTop">Top view</button>
<button id="btn3d" class="on">3D view</button>
</div>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
/* ------------------------------------------------------------------ *
* Physics (SI units, scene units = metres) *
* ------------------------------------------------------------------ */
const K = 8.9875517873681764e9; // Coulomb constant
const Q = 2.0e-6; // source charge (+2 µC)
const q = 1.0e-8; // test charge (+10 nC)
const kQ = K * Q;
const kQq = kQ * q;
const pot = r => kQ / r; // electric potential V(r)
const energy = r => kQq / r; // potential energy U(r) = qV
const fieldMag= r => kQ / (r*r); // |E(r)|
/* ------------------------------------------------------------------ *
* Scene setup *
* ------------------------------------------------------------------ */
const stage = document.getElementById('stage');
const renderer = new THREE.WebGLRenderer({ antialias:true, powerPreference:'high-performance' });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x04070f);
scene.fog = new THREE.FogExp2(0x04070f, 0.30);
const camera = new THREE.PerspectiveCamera(50, innerWidth/innerHeight, 0.02, 60);
const CAM_TARGET = new THREE.Vector3(0.06, 0.0, 0.22);
const sph = new THREE.Spherical(2.05, 1.02, 0.85);
let camGoal = null;
function applyCam(){ camera.position.setFromSpherical(sph).add(CAM_TARGET); camera.lookAt(CAM_TARGET); }
applyCam();
scene.add(new THREE.AmbientLight(0xffffff, 0.35));
const srcLight = new THREE.PointLight(0x8fb0ff, 2.2, 4, 2); scene.add(srcLight);
/* --- custom orbit controls (no addons) --- */
const dom = renderer.domElement;
let dragging=false, lx=0, ly=0;
dom.style.touchAction='none';
dom.addEventListener('pointerdown', e=>{ dragging=true; lx=e.clientX; ly=e.clientY; dom.setPointerCapture(e.pointerId); camGoal=null; });
dom.addEventListener('pointermove', e=>{
if(!dragging) return;
const dx=e.clientX-lx, dy=e.clientY-ly; lx=e.clientX; ly=e.clientY;
sph.theta -= dx*0.006;
sph.phi = THREE.MathUtils.clamp(sph.phi - dy*0.006, 0.12, Math.PI-0.12);
});
const endDrag = e=>{ dragging=false; };
dom.addEventListener('pointerup', endDrag);
dom.addEventListener('pointercancel', endDrag);
dom.addEventListener('wheel', e=>{
e.preventDefault();
sph.radius = THREE.MathUtils.clamp(sph.radius * Math.exp(e.deltaY*0.0011), 0.35, 8);
camGoal=null;
}, {passive:false});
/* ------------------------------------------------------------------ *
* Geometry: source charge, field lines, equipotential rings *
* ------------------------------------------------------------------ */
function glowTexture(hex, size=160){
const c=document.createElement('canvas'); c.width=c.height=size;
const x=c.getContext('2d');
const g=x.createRadialGradient(size/2,size/2,0,size/2,size/2,size/2);
g.addColorStop(0.00, hex+'e6');
g.addColorStop(0.22, hex+'77');
g.addColorStop(0.55, hex+'22');
g.addColorStop(1.00, hex+'00');
x.fillStyle=g; x.fillRect(0,0,size,size);
const t=new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; return t;
}
/* source charge */
const srcMesh = new THREE.Mesh(
new THREE.SphereGeometry(0.055, 40, 28),
new THREE.MeshStandardMaterial({ color:0x6f8dff, emissive:0x2a44d8, emissiveIntensity:1.4, roughness:0.35, metalness:0.1 })
);
scene.add(srcMesh);
const srcGlow = new THREE.Sprite(new THREE.SpriteMaterial({
map:glowTexture('#6f8dff'), blending:THREE.AdditiveBlending, depthWrite:false, transparent:true }));
srcGlow.scale.setScalar(0.62); scene.add(srcGlow);
/* faint motion plane */
const planeDisc = new THREE.Mesh(new THREE.CircleGeometry(1.05, 96),
new THREE.MeshBasicMaterial({ color:0x1b3358, transparent:true, opacity:0.10, side:THREE.DoubleSide }));
planeDisc.rotation.x = -Math.PI/2; scene.add(planeDisc);
/* ---- field lines (radial spokes) + arrowheads ---- */
const fieldGroup = new THREE.Group(); scene.add(fieldGroup);
{
const pts=[];
const N=18, R0=0.075, R1=1.10;
for(let i=0;i<N;i++){
const a=i*2*Math.PI/N, dx=Math.cos(a), dz=Math.sin(a);
pts.push(dx*R0,0,dz*R0, dx*R1,0,dz*R1);
}
const g=new THREE.BufferGeometry();
g.setAttribute('position', new THREE.Float32BufferAttribute(pts,3));
fieldGroup.add(new THREE.LineSegments(g, new THREE.LineBasicMaterial({
color:0x2f5f9e, transparent:true, opacity:0.55 })));
const coneG=new THREE.ConeGeometry(0.022,0.075,14);
const coneM=new THREE.MeshBasicMaterial({ color:0x74b6ff, transparent:true, opacity:0.85 });
for(let i=0;i<N;i++){
const a=i*2*Math.PI/N, r=0.60;
const m=new THREE.Mesh(coneG, coneM);
m.position.set(Math.cos(a)*r,0,Math.sin(a)*r);
m.quaternion.setFromUnitVectors(new THREE.Vector3(0,1,0), new THREE.Vector3(Math.cos(a),0,Math.sin(a)));
fieldGroup.add(m);
}
/* equipotential rings (constant V ⇒ constant r) */
[0.15,0.30,0.50,0.80].forEach((r,i)=>{
const p=[]; const N2=128;
for(let j=0;j<=N2;j++){ const a=j/N2*2*Math.PI; p.push(Math.cos(a)*r,0,Math.sin(a)*r); }
const g=new THREE.BufferGeometry();
g.setAttribute('position', new THREE.Float32BufferAttribute(p,3));
fieldGroup.add(new THREE.Line(g, new THREE.LineBasicMaterial({
color: i===1?0x3f8fd0:0x2b4f7d, transparent:true, opacity: i===1?0.5:0.32 })));
});
}
/* ------------------------------------------------------------------ *
* Paths between the same endpoints *
* ------------------------------------------------------------------ */
const A = new THREE.Vector3(-0.25, 0, 0.05);
const B = new THREE.Vector3( 0.40, 0, 0.25);
/* Path 1: inner arc that swings close to the source (U peaks mid-path) */
const qc = new THREE.Vector3(0.05, 0, 0.12);
const path1 = new THREE.CubicBezierCurve3(
A,
A.clone().add(qc.clone().sub(A).multiplyScalar(2/3)),
B.clone().add(qc.clone().sub(B).multiplyScalar(2/3)),
B);
/* Path 2: outer detour that swings far away (U dips mid-path) */
const path2 = new THREE.CubicBezierCurve3(
A, new THREE.Vector3(-0.28,0,0.55), new THREE.Vector3(0.70,0,0.58), B);
path1.arcLengthDivisions = 2000; path2.arcLengthDivisions = 2000;
const PATHS = [
{ name:'Path 1 · inner arc', curve:path1, color:0x38bdf8, css:'#38bdf8', cls:'a1' },
{ name:'Path 2 · outer detour', curve:path2, color:0xfbbf24, css:'#fbbf24', cls:'a2' }
];
/* path tubes */
PATHS.forEach(p=>{
p.tube = new THREE.Mesh(
new THREE.TubeGeometry(p.curve, 260, 0.0075, 10, false),
new THREE.MeshBasicMaterial({ color:p.color, transparent:true, opacity:0.38 }));
scene.add(p.tube);
/* direction arrows */
[0.22,0.55,0.86].forEach(t=>{
const pt=p.curve.getPointAt(t), tg=p.curve.getTangentAt(t);
const cone=new THREE.Mesh(new THREE.ConeGeometry(0.022,0.062,12),
new THREE.MeshBasicMaterial({ color:p.color, transparent:true, opacity:0.95 }));
cone.position.copy(pt); cone.quaternion.setFromUnitVectors(new THREE.Vector3(0,1,0), tg.normalize());
scene.add(cone);
});
/* progressive trail */
const N=520, arr=new Float32Array(N*3);
p.trailGeo=new THREE.BufferGeometry();
p.trailGeo.setAttribute('position', new THREE.BufferAttribute(arr,3));
p.trailGeo.setDrawRange(0,0);
p.trail=new THREE.Line(p.trailGeo, new THREE.LineBasicMaterial({
color:p.color, transparent:true, opacity:0.95 }));
p.trailN=0; scene.add(p.trail);
});
/* endpoint markers */
function marker(pos, color){
const m=new THREE.Mesh(new THREE.OctahedronGeometry(0.032),
new THREE.MeshStandardMaterial({ color, emissive:color, emissiveIntensity:0.9, roughness:0.3 }));
m.position.copy(pos); scene.add(m); return m;
}
marker(A,0x7dd3fc); marker(B,0xfdba74);
/* ------------------------------------------------------------------ *
* Test charge + field vector *
* ------------------------------------------------------------------ */
const charge = new THREE.Group(); scene.add(charge);
const chargeMesh = new THREE.Mesh(new THREE.SphereGeometry(0.032,32,22),
new THREE.MeshStandardMaterial({ color:0xffffff, emissive:0x7fffd4, emissiveIntensity:1.5, roughness:0.25 }));
charge.add(chargeMesh);
const chargeGlow = new THREE.Sprite(new THREE.SpriteMaterial({
map:glowTexture('#9dffe0'), blending:THREE.AdditiveBlending, depthWrite:false, transparent:true }));
chargeGlow.scale.setScalar(0.30); charge.add(chargeGlow);
const eArrow = new THREE.ArrowHelper(new THREE.Vector3(1,0,0), new THREE.Vector3(), 0.15, 0x7dd3fc, 0.045, 0.028);
scene.add(eArrow);
/* ------------------------------------------------------------------ *
* HTML labels projected from 3D *
* ------------------------------------------------------------------ */
const labelLayer = document.getElementById('labels');
function makeLabel(html, cls){
const d=document.createElement('div'); d.className='lbl '+(cls||''); d.innerHTML=html;
labelLayer.appendChild(d); return d;
}
function place(el, vec, dx=0, dy=0){
const p=vec.clone().project(camera);
const x=(p.x*0.5+0.5)*innerWidth, y=(-p.y*0.5+0.5)*innerHeight;
el.style.transform=`translate(-50%,-50%) translate(${x+dx}px,${y+dy}px)`;
el.style.opacity = (p.z>1||p.z<-1)?0:1;
}
const lblSrc = makeLabel('<b>Q = +2.00 µC</b> source charge','src');
const lblChg = makeLabel('<b>+q = +10.0 nC</b> test charge','q');
const lblA = makeLabel('<b>A</b> start','a1');
const lblB = makeLabel('<b>B</b> end','a2');
const lblP1 = makeLabel('Path 1 · inner arc','a1');
const lblP2 = makeLabel('Path 2 · outer detour','a2');
const lblE = makeLabel('<b>E</b>');
/* ------------------------------------------------------------------ *
* Numeric work integration along each path (∫ F·dl) *
* ------------------------------------------------------------------ */
function workAlong(curve, n=6000){
let w=0, prev=null;
for(let i=0;i<=n;i++){
const p=curve.getPointAt(i/n);
const r=p.length();
if(prev){
const dr=p.clone().sub(prev);
const E=fieldMag(r);
w += q*E*p.clone().normalize().dot(dr);
}
prev=p;
}
return w;
}
const WORK = [workAlong(path1), workAlong(path2)];
/* endpoint quantities */
const rA=A.length(), rB=B.length();
const VA=pot(rA), VB=pot(rB), UA=energy(rA), UB=energy(rB);
const dU_true = UB-UA;
/* sampled U(t) for the graph */
const NS=220, SAMP=[[],[]];
PATHS.forEach((p,idx)=>{ for(let i=0;i<=NS;i++){ const t=i/NS; const q2=p.curve.getPointAt(t);
SAMP[idx].push({ t, U:energy(q2.length()), r:q2.length() }); } });
let Umin=Math.min(...SAMP.flat().map(s=>s.U)), Umax=Math.max(...SAMP.flat().map(s=>s.U));
Umin=Math.min(Umin,UA,UB); Umax=Math.max(Umax,UA,UB);
const pad=(Umax-Umin)*0.10; Umin-=pad; Umax+=pad;
/* ------------------------------------------------------------------ *
* HUD *
* ------------------------------------------------------------------ */
const $=id=>document.getElementById(id);
const fmtV = v => v>=1000 ? (v/1000).toFixed(2)+' kV' : v.toFixed(0)+' V';
const fmtM = j => (j*1e3).toFixed(4)+' mJ';
$('rA').textContent=rA.toFixed(4)+' m'; $('vA').textContent=fmtV(VA); $('uA').textContent=fmtM(UA);
$('rB').textContent=rB.toFixed(4)+' m'; $('vB').textContent=fmtV(VB); $('uB').textContent=fmtM(UB);
$('du1').textContent='−'+fmtM(Math.abs(dU_true));
$('du2').textContent='−'+fmtM(Math.abs(dU_true));
$('w1').textContent='+'+fmtM(WORK[0]);
$('w2').textContent='+'+fmtM(WORK[1]);
const eq1=Math.abs(WORK[0]-(-dU_true))<2e-9, eq2=Math.abs(WORK[1]-(-dU_true))<2e-9;
$('m1').innerHTML = eq1?'<span class="ok">✓</span>':'…';
$('m2').innerHTML = eq2?'<span class="ok">✓</span>':'…';
/* graph canvas */
const gc=$('graph'), gx=gc.getContext('2d');
function sizeGraph(){
const dpr=Math.min(window.devicePixelRatio,2);
const r=gc.getBoundingClientRect();
gc.width=Math.max(1,Math.round(r.width*dpr)); gc.height=Math.max(1,Math.round(r.height*dpr));
gx.setTransform(dpr,0,0,dpr,0,0);
}
function drawGraph(activeIdx, u){
const W=gc.width/(Math.min(window.devicePixelRatio,2)), H=gc.height/(Math.min(window.devicePixelRatio,2));
gx.clearRect(0,0,W,H);
const L=54,R=12,T=12,B=28, pw=W-L-R, ph=H-T-B;
const X=t=>L+t*pw, Y=v=>T+(Umax-v)/(Umax-Umin)*ph;
/* grid */
gx.strokeStyle='rgba(140,175,215,.12)'; gx.lineWidth=1;
for(let i=0;i<=4;i++){ const y=T+i*ph/4; gx.beginPath(); gx.moveTo(L,y); gx.lineTo(W-R,y); gx.stroke(); }
for(let i=0;i<=4;i++){ const x=L+i*pw/4; gx.beginPath(); gx.moveTo(x,T); gx.lineTo(x,H-B); gx.stroke(); }
/* endpoint levels */
[[UA,'#9fe8ff'],[UB,'#ffd89b']].forEach(([v,col])=>{
gx.setLineDash([4,4]); gx.strokeStyle=col+'aa'; gx.lineWidth=1;
gx.beginPath(); gx.moveTo(L,Y(v)); gx.lineTo(W-R,Y(v)); gx.stroke(); gx.setLineDash([]);
gx.fillStyle=col; gx.font='10px ui-monospace,monospace'; gx.textAlign='left';
gx.fillText((v*1e3).toFixed(3), L+3, Y(v)-3);
});
/* curves */
PATHS.forEach((p,idx)=>{
gx.strokeStyle=p.css; gx.lineWidth=2; gx.beginPath();
SAMP[idx].forEach((s,i)=>{ i? gx.lineTo(X(s.t),Y(s.U)) : gx.moveTo(X(s.t),Y(s.U)); });
gx.stroke();
});
/* active marker */
if(activeIdx>=0){
const s=SAMP[activeIdx][Math.round(u*NS)];
gx.fillStyle='#ffffff'; gx.beginPath(); gx.arc(X(s.t),Y(s.U),4,0,7); gx.fill();
gx.strokeStyle=PATHS[activeIdx].css; gx.lineWidth=2; gx.beginPath(); gx.arc(X(s.t),Y(s.U),4,0,7); gx.stroke();
}
/* axes */
gx.strokeStyle='rgba(160,195,235,.45)'; gx.lineWidth=1;
gx.beginPath(); gx.moveTo(L,T); gx.lineTo(L,H-B); gx.lineTo(W-R,H-B); gx.stroke();
gx.fillStyle='#7f98b6'; gx.font='10px ui-monospace,monospace';
gx.textAlign='center'; gx.fillText('route fraction →', L+pw/2, H-9);
gx.save(); gx.translate(13,T+ph/2); gx.rotate(-Math.PI/2); gx.textAlign='center';
gx.fillText('U (mJ)',0,0); gx.restore();
/* legend */
gx.textAlign='left'; gx.font='10px ui-monospace,monospace';
gx.fillStyle='#38bdf8'; gx.fillText('─ path 1', L+6, T+12);
gx.fillStyle='#fbbf24'; gx.fillText('─ path 2', L+66, T+12);
}
/* ------------------------------------------------------------------ *
* Animation state machine *
* ------------------------------------------------------------------ */
const DUR = { p1:5.2, p2:5.2, hold1:0.9, hold2:1.4 };
const S = { phase:'p1', t:0, u:0, speed:1, playing:true, done:[false,false] };
function setPhase(ph){ S.phase=ph; S.t=0; if(ph==='p1'||ph==='p2'){ const i=ph==='p1'?0:1; PATHS[i].trailN=0; PATHS[i].trailGeo.setDrawRange(0,0); } }
function update(dt){
if(!S.playing) return;
S.t += dt*S.speed;
if(S.phase==='p1'||S.phase==='p2'){
const i = S.phase==='p1'?0:1;
S.u = Math.min(1, S.t/DUR[S.phase]);
const p = PATHS[i].curve.getPointAt(S.u);
charge.position.copy(p);
/* trail */
const tr=PATHS[i], a=tr.trailGeo.attributes.position.array;
if(tr.trailN < a.length/3){
a[tr.trailN*3]=p.x; a[tr.trailN*3+1]=p.y+0.012; a[tr.trailN*3+2]=p.z; tr.trailN++;
tr.trailGeo.attributes.position.needsUpdate=true; tr.trailGeo.setDrawRange(0,tr.trailN);
}
if(S.t>=DUR[S.phase]){ S.done[i]=true; setPhase(S.phase==='p1'?'hold1':'hold2'); }
} else if(S.phase==='hold1'){
if(S.t>=DUR.hold1) setPhase('p2');
} else if(S.phase==='hold2'){
if(S.t>=DUR.hold2){ S.done=[false,false]; setPhase('p1'); }
}
}
/* live HUD */
let hudAcc=0;
function updateHUD(dt){
hudAcc+=dt; if(hudAcc<0.05) return; hudAcc=0;
const i = (S.phase==='p1'||S.phase==='p2') ? (S.phase==='p1'?0:1) : -1;
if(i>=0){
const p=PATHS[i].curve.getPointAt(S.u), r=p.length();
$('lpath').innerHTML = `<span style="color:${PATHS[i].css}">${PATHS[i].name}</span>`;
$('lprog').textContent=(S.u*100).toFixed(0)+' %';
$('bigU').innerHTML=`U = ${(energy(r)*1e3).toFixed(4)} <span style="font-size:12px;color:#8fa6c0">mJ</span>`;
$('lsub').innerHTML=`r = ${r.toFixed(3)} m • V = ${fmtV(pot(r))} • |E| = ${fieldMag(r).toExponential(2)} V/m`;
$('bar').firstElementChild.style.width=((energy(r)-Umin)/(Umax-Umin)*100).toFixed(1)+'%';
drawGraph(i,S.u);
} else {
$('lpath').textContent='(holding)';
$('lprog').textContent='—';
$('bigU').innerHTML='U = <span style="font-size:13px;color:#8fa6c0">qV is the same at A and B…</span>';
$('lsub').innerHTML=' ';
drawGraph(-1,0);
}
const v=$('verdict');
if(S.done[0]&&S.done[1]){
v.className='';
v.innerHTML=`✓ <b>Path-independent.</b> ΔU₁ = ΔU₂ = <b>−${Math.abs(dU_true*1e3).toFixed(4)} mJ</b>
(−${Math.abs(dU_true).toExponential(3).replace('e-','×10⁻')} J), and the numerically integrated work by the
field is <b>+${(WORK[0]*1e3).toFixed(4)} mJ</b> on <i>both</i> routes.`;
} else {
v.className='pending';
v.textContent = S.done[0] ? 'Route 1 measured ✓ — now running route 2 …' : 'Measuring route 1 …';
}
}
/* controls */
$('btnPlay').addEventListener('click', ()=>{
S.playing=!S.playing;
$('btnPlay').textContent = S.playing? '⏸ Pause' : '▶ Play';
});
$('btnRestart').addEventListener('click', ()=>{ S.done=[false,false]; setPhase('p1'); });
$('speed').addEventListener('change', e=>{ S.speed=parseFloat(e.target.value); });
$('btnField').addEventListener('click', e=>{
fieldGroup.visible=!fieldGroup.visible;
e.target.classList.toggle('on', fieldGroup.visible);
});
$('btnTop').addEventListener('click', ()=>{ camGoal={ radius:1.95, phi:0.14, theta:sph.theta }; $('btnTop').classList.add('on'); $('btn3d').classList.remove('on'); });
$('btn3d').addEventListener('click', ()=>{ camGoal={ radius:2.05, phi:1.02, theta:0.85 }; $('btn3d').classList.add('on'); $('btnTop').classList.remove('on'); });
/* resize */
function onResize(){
camera.aspect=innerWidth/innerHeight; camera.updateProjectionMatrix();
renderer.setSize(innerWidth,innerHeight);
sizeGraph(); drawGraph(-1,0);
}
addEventListener('resize', onResize);
sizeGraph();
/* ------------------------------------------------------------------ *
* Main loop *
* ------------------------------------------------------------------ */
let prev=performance.now();
function animate(now){
const dt=Math.min((now-prev)/1000, 0.05); prev=now;
update(dt);
if(camGoal){
sph.radius += (camGoal.radius-sph.radius)*0.12;
sph.phi += (camGoal.phi-sph.phi)*0.12;
sph.theta += (camGoal.theta-sph.theta)*0.12;
if(Math.abs(camGoal.radius-sph.radius)<1e-4 && Math.abs(camGoal.phi-sph.phi)<1e-4){ camGoal=null; }
}
applyCam();
/* source pulse */
const t=now/1000;
const pulse=1+0.06*Math.sin(t*2.0);
srcGlow.scale.setScalar(0.62*pulse);
srcLight.intensity=2.2*pulse;
/* field vector at the test charge */
const cp=charge.position.clone();
const r=cp.length();
eArrow.position.copy(cp);
eArrow.setDirection(cp.clone().normalize());
const elen=0.075+0.20*(0.25/Math.max(r,0.05));
eArrow.setLength(Math.min(elen,0.30), 0.042, 0.026);
/* labels */
place(lblSrc, new THREE.Vector3(0,0.10,0), 0, -14);
place(lblChg, cp, 0, -26);
place(lblA, A, -6, 20);
place(lblB, B, 6, 20);
place(lblP1, path1.getPointAt(0.5), 0, -18);
place(lblP2, path2.getPointAt(0.5), 0, -18);
place(lblE, cp.clone().add(cp.clone().normalize().multiplyScalar(elen)), 12, -6);
updateHUD(dt);
renderer.render(scene,camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```