Prompt specification
Build or customize the Three.js 3D scene "Potential and field comparison explorer" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Potential and field comparison explorer
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/potential-and-field-comparison-explorer-x1628
Scene Description Prompt:
Make a low-poly two-charge explorer showing electric potential and field separately, including their different zero points. One HTML file, Three.js from cdnjs.
Verify the behavior against the actual geometry and data in each relevant state. Use schematic labels for deliberately synthetic elements.
Technical checks: Compute the field by vector addition and the potential by scalar addition. For opposite charges, avoid zero-field markers between the charges, where the fields point in the same direction.
Return one complete HTML document. The file must run in a sandbox allowing inline scripts and the cdnjs Three.js r160 module. Construct procedural assets, use local event handlers and avoid remote assets, runtime network requests besides Three.js, pointer lock and native form submission. Keep the main requested geometry visible in the initial view.
Working Three.js Starter (potential-and-field-comparison-explorer-x1628):
```html
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Explorador de Duas Cargas — Potencial e Campo</title>
<style>
:root {
--bg: #07101b;
--panel: #0b1726;
--panel-2: #101f31;
--line: rgba(151, 190, 220, 0.16);
--text: #edf6ff;
--muted: #91a9bd;
--cyan: #59ddff;
--orange: #ff886d;
--yellow: #ffe084;
--green: #83f0bd;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button, input { font: inherit; }
#app {
display: grid;
grid-template-columns: 348px minmax(0, 1fr);
width: 100%;
height: 100%;
}
#panel {
position: relative;
z-index: 5;
overflow-y: auto;
padding: 24px 22px 18px;
background:
radial-gradient(circle at 10% 0%, rgba(89, 221, 255, 0.08), transparent 34%),
linear-gradient(180deg, #0c1929 0%, #091522 100%);
border-right: 1px solid var(--line);
box-shadow: 12px 0 40px rgba(0, 0, 0, 0.20);
scrollbar-width: thin;
scrollbar-color: #28445a transparent;
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 8px 0 8px;
font-size: 25px;
line-height: 1.13;
letter-spacing: -0.035em;
}
.intro {
margin: 0 0 20px;
color: var(--muted);
font-size: 12.5px;
line-height: 1.55;
}
.segmented {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 5px;
padding: 5px;
margin-bottom: 18px;
background: rgba(1, 8, 15, 0.56);
border: 1px solid var(--line);
border-radius: 13px;
}
.segmented button {
min-height: 39px;
border: 0;
border-radius: 9px;
color: var(--muted);
background: transparent;
cursor: pointer;
font-size: 12px;
font-weight: 750;
transition: 160ms ease;
}
.segmented button:hover { color: var(--text); }
.segmented button.active {
color: #06121d;
background: linear-gradient(135deg, #73e3ff, #52c9ee);
box-shadow: 0 5px 16px rgba(57, 196, 232, 0.19);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 19px 0 10px;
color: #cfe0ec;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.section-title::after {
content: "";
width: 38px;
height: 1px;
background: var(--line);
}
.control {
margin: 12px 0 15px;
}
.control-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 7px;
font-size: 11.5px;
color: var(--muted);
}
.control-row output {
min-width: 68px;
padding: 3px 7px;
text-align: right;
border-radius: 6px;
background: rgba(255, 255, 255, 0.045);
color: var(--text);
font-variant-numeric: tabular-nums;
font-size: 11px;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 5px 0;
appearance: none;
border-radius: 99px;
outline: none;
background: linear-gradient(90deg, #31516a, #1a3042);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
appearance: none;
border: 3px solid #d9f4ff;
border-radius: 50%;
background: #42c5ea;
box-shadow: 0 0 0 4px rgba(66, 197, 234, 0.13);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 3px solid #d9f4ff;
border-radius: 50%;
background: #42c5ea;
box-shadow: 0 0 0 4px rgba(66, 197, 234, 0.13);
}
.plus-range { accent-color: var(--orange); }
.minus-range { accent-color: var(--cyan); }
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
min-height: 92px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 12px;
background: linear-gradient(145deg, rgba(22, 42, 60, 0.78), rgba(11, 25, 39, 0.78));
}
.metric-label {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.metric-value {
margin-top: 8px;
color: var(--text);
font-size: 18px;
font-weight: 760;
font-variant-numeric: tabular-nums;
letter-spacing: -0.035em;
}
.metric-detail {
margin-top: 5px;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.reference {
margin-top: 8px;
padding: 11px 12px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(3, 10, 18, 0.34);
}
.reference-head {
display: flex;
align-items: center;
gap: 8px;
color: var(--text);
font-size: 11px;
font-weight: 750;
}
.dot {
width: 8px;
height: 8px;
flex: 0 0 auto;
border-radius: 50%;
}
.dot.potential { background: var(--yellow); box-shadow: 0 0 9px rgba(255,224,132,.45); }
.dot.field { background: var(--green); box-shadow: 0 0 9px rgba(131,240,189,.45); }
.reference p {
margin: 6px 0 0 16px;
color: var(--muted);
font-size: 10.5px;
line-height: 1.45;
}
.warning {
margin-top: 13px;
padding: 11px 12px;
border: 1px solid rgba(255, 224, 132, 0.28);
border-left: 3px solid var(--yellow);
border-radius: 9px;
color: #e9dfb7;
background: rgba(255, 224, 132, 0.055);
font-size: 10.5px;
line-height: 1.5;
}
.warning strong { color: var(--yellow); }
details {
margin-top: 15px;
color: var(--muted);
font-size: 10.5px;
line-height: 1.5;
}
summary {
cursor: pointer;
color: #bdd0de;
font-weight: 700;
}
.equation {
margin-top: 9px;
padding: 9px;
border-radius: 7px;
color: #c9d9e4;
background: rgba(0, 0, 0, 0.22);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9.5px;
white-space: pre-wrap;
}
.panel-foot {
margin-top: 18px;
padding-top: 13px;
border-top: 1px solid var(--line);
color: #6f879a;
font-size: 9.5px;
line-height: 1.5;
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 64% 42%, rgba(33, 75, 102, 0.22), transparent 43%),
#07101b;
}
#canvasHost {
position: absolute;
inset: 0;
}
#canvasHost canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#canvasHost canvas:active { cursor: grabbing; }
.hud {
position: absolute;
z-index: 3;
pointer-events: none;
}
#viewHud {
top: 22px;
left: 24px;
max-width: 430px;
}
.view-kicker {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 5px 8px;
border: 1px solid rgba(110, 213, 241, 0.19);
border-radius: 99px;
color: #91e9ff;
background: rgba(7, 20, 31, 0.66);
backdrop-filter: blur(8px);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.view-kicker::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 9px currentColor;
}
#viewTitle {
margin: 10px 0 4px;
font-size: 20px;
letter-spacing: -0.025em;
}
#viewSubtitle {
color: #91a9bd;
font-size: 11px;
line-height: 1.45;
}
#legend {
right: 20px;
bottom: 20px;
width: 220px;
padding: 12px 13px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(7, 17, 29, 0.78);
backdrop-filter: blur(9px);
}
#legendTitle {
margin-bottom: 8px;
color: #d6e7f3;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.legend-bar {
height: 7px;
border-radius: 99px;
background: linear-gradient(90deg, #4ed9ff, #173448 49%, #ff8067);
}
.legend-labels {
display: flex;
justify-content: space-between;
margin-top: 6px;
color: var(--muted);
font-size: 9px;
}
.field-key {
display: flex;
align-items: center;
gap: 9px;
color: var(--muted);
font-size: 9.5px;
}
.field-key svg { flex: 0 0 auto; }
#offscreen {
top: 22px;
right: 22px;
display: none;
max-width: 245px;
padding: 9px 11px;
border: 1px solid rgba(255, 224, 132, 0.25);
border-radius: 9px;
color: #e6dba9;
background: rgba(38, 31, 13, 0.78);
font-size: 9.5px;
line-height: 1.4;
}
#controlsHint {
left: 22px;
bottom: 20px;
color: rgba(171, 195, 212, 0.70);
font-size: 9.5px;
line-height: 1.45;
}
#resetView {
position: absolute;
z-index: 4;
top: 22px;
right: 22px;
padding: 7px 10px;
border: 1px solid var(--line);
border-radius: 8px;
color: #b9cfdd;
background: rgba(8, 20, 32, 0.75);
cursor: pointer;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.05em;
text-transform: uppercase;
}
#resetView:hover {
color: white;
border-color: rgba(101, 207, 239, 0.4);
}
#offscreen:not([hidden]) ~ #resetView { top: 88px; }
@media (max-width: 980px) {
html, body { overflow: auto; }
#app {
grid-template-columns: 1fr;
grid-template-rows: minmax(360px, 45vh) minmax(480px, 55vh);
height: auto;
min-height: 100%;
}
#panel {
grid-row: 1;
border-right: 0;
border-bottom: 1px solid var(--line);
}
#stage {
grid-row: 2;
min-height: 55vh;
}
#legend {
width: 185px;
right: 12px;
bottom: 12px;
}
#viewHud {
top: 15px;
left: 15px;
}
#controlsHint { display: none; }
}
</style>
</head>
<body>
<div id="app">
<aside id="panel">
<div class="eyebrow">Laboratório 02 · Eletrostática</div>
<h1>Explorador de duas cargas</h1>
<p class="intro">Potencial e campo têm naturezas diferentes. Alterne as vistas e compare suas superfícies e pontos nulos usando os mesmos dados.</p>
<div class="segmented" aria-label="Escolha da visualização">
<button type="button" id="modePotential">Potencial V</button>
<button type="button" id="modeField" class="active">Campo E</button>
</div>
<div class="section-title">Modelo</div>
<div class="control">
<div class="control-row">
<label for="qPlus">Carga positiva</label>
<output id="qPlusValue">+2,4 nC</output>
</div>
<input id="qPlus" class="plus-range" type="range" min="0.5" max="3.5" step="0.1" value="2.4">
</div>
<div class="control">
<div class="control-row">
<label for="qMinus">Carga negativa</label>
<output id="qMinusValue">−1,4 nC</output>
</div>
<input id="qMinus" class="minus-range" type="range" min="0.5" max="3.5" step="0.1" value="1.4">
</div>
<div class="control">
<div class="control-row">
<label for="distance">Distância entre cargas</label>
<output id="distanceValue">0,90 m</output>
</div>
<input id="distance" type="range" min="0.60" max="1.60" step="0.02" value="0.90">
</div>
<div class="section-title">Sonda no eixo</div>
<div class="control">
<div class="control-row">
<label for="probeX">Posição x do ponto P</label>
<output id="probeXValue">0,241 m</output>
</div>
<input id="probeX" type="range" min="-1.25" max="3.56" step="0.001" value="0.241">
</div>
<div class="metric-grid">
<div class="metric">
<div class="metric-label">Potencial V(P)</div>
<div class="metric-value" id="potentialMetric">—</div>
<div class="metric-detail" id="potentialMetricDetail">escalar</div>
</div>
<div class="metric">
<div class="metric-label">Campo |E(P)|</div>
<div class="metric-value" id="fieldMetric">—</div>
<div class="metric-detail" id="fieldMetricDetail">vetorial</div>
</div>
</div>
<div class="section-title">Referências nulas</div>
<div class="reference">
<div class="reference-head">
<span class="dot potential"></span>
<span id="potentialRefTitle">V = 0 · superfície</span>
</div>
<p id="potentialRef">Calculando a esfera de potencial nulo…</p>
</div>
<div class="reference">
<div class="reference-head">
<span class="dot field"></span>
<span id="fieldRefTitle">E = 0 · ponto no eixo</span>
</div>
<p id="fieldRef">Calculando o ponto de campo nulo…</p>
</div>
<div class="warning" id="zeroWarning">
<strong>Verificação:</strong> o valor nulo do campo deve ser calculado pela soma vetorial,
não por uma marcação presumida entre as cargas.
</div>
<details>
<summary>Equações e convenções</summary>
<div class="equation">V = k(q₊/r₊ − q₋/r₋)
E = k Σ qᵢ(r − rᵢ)/|r − rᵢ|³
k = 8,98755 V·m/nC
x₊ = −d/2, x₋ = +d/2</div>
</details>
<div class="panel-foot">
Modelo didático de cargas puntuales. As cores, o plano de corte e os tamanhos gráficos são esquemáticos;
os valores, direções e posições dos zeros são calculados a partir da geometria atual.
</div>
</aside>
<main id="stage">
<div id="canvasHost"></div>
<div id="viewHud" class="hud">
<div class="view-kicker" id="viewKicker">Modelo esquemático · cargas puntuales</div>
<div id="viewTitle">Campo elétrico</div>
<div id="viewSubtitle">Vetores muestran a direção de E; o comprimento é normalizado.</div>
</div>
<button type="button" id="resetView">Reenquadrar</button>
<div id="offscreen" class="hud" hidden></div>
<div id="controlsHint" class="hud">
Arraste para orbitar · roda para zoom<br>
Shift + arraste ou botão direito para deslocar
</div>
<div id="legend" class="hud">
<div id="legendTitle">Campo · direção de E</div>
<div class="field-key">
<svg width="48" height="18" viewBox="0 0 48 18" aria-hidden="true">
<path d="M2 9 H34" stroke="#ffe084" stroke-width="2"/>
<path d="M34 3 L45 9 L34 15 Z" fill="#ffe084"/>
</svg>
<span>comprimento normalizado<br>cor = magnitude |E|</span>
</div>
</div>
</main>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = id => document.getElementById(id);
const host = $("canvasHost");
const state = {
qPlus: 2.4,
qMinus: 1.4,
distance: 0.90,
probeX: 0.241,
mode: "field",
k: 8.9875517923
};
const format = (value, digits = 2) => new Intl.NumberFormat("pt-BR", {
minimumFractionDigits: digits,
maximumFractionDigits: digits
}).format(value);
const signed = (value, digits = 2) => {
const n = format(Math.abs(value), digits);
if (value > 0.000001) return `+${n}`;
if (value < -0.000001) return `−${n}`;
return n;
};
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07101b);
scene.fog = new THREE.FogExp2(0x07101b, 0.028);
const camera = new THREE.PerspectiveCamera(43, 1, 0.05, 160);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
host.appendChild(renderer.domElement);
const hemi = new THREE.HemisphereLight(0x9ddfff, 0x182338, 2.25);
scene.add(hemi);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.7);
keyLight.position.set(4, 7, 5);
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x4ad9ff, 28, 18, 2);
rimLight.position.set(4, 2, -3);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xff725d, 18, 13, 2);
warmLight.position.set(-4, 2, 2);
scene.add(warmLight);
const cameraState = {
target: new THREE.Vector3(1.0, 0.25, 0),
distance: 5.9,
theta: 0.48,
phi: 1.05
};
let cameraAnimation = null;
const commonGroup = new THREE.Group();
const potentialGroup = new THREE.Group();
const fieldGroup = new THREE.Group();
const axisGroup = new THREE.Group();
scene.add(commonGroup, potentialGroup, fieldGroup, axisGroup);
potentialGroup.visible = false;
fieldGroup.visible = true;
const floorGrid = new THREE.GridHelper(12, 24, 0x29465b, 0x172b3b);
floorGrid.position.y = -0.43;
floorGrid.material.transparent = true;
floorGrid.material.opacity = 0.32;
scene.add(floorGrid);
let seed = 7319;
const random = () => {
seed = (seed * 1664525 + 1013904223) >>> 0;
return seed / 4294967296;
};
const starPositions = [];
for (let i = 0; i < 190; i++) {
starPositions.push(
(random() - 0.5) * 16,
(random() - 0.5) * 9,
-3 - random() * 9
);
}
const starGeometry = new THREE.BufferGeometry();
starGeometry.setAttribute("position", new THREE.Float32BufferAttribute(starPositions, 3));
const stars = new THREE.Points(
starGeometry,
new THREE.PointsMaterial({
color: 0x8ab9d3,
size: 0.018,
transparent: true,
opacity: 0.42,
depthWrite: false
})
);
scene.add(stars);
function clearGroup(group, disposeGeometry = true, disposeMaterial = true) {
group.traverse(object => {
if (disposeGeometry && object.geometry) object.geometry.dispose();
if (disposeMaterial && object.material) {
const materials = Array.isArray(object.material) ? object.material : [object.material];
for (const material of materials) {
if (material.map) material.map.dispose();
material.dispose();
}
}
});
group.clear();
}
function makeTextSprite(text, color = "#eaf7ff", background = "rgba(6,18,29,0.78)") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.renderOrder = 20;
sprite.userData.canvas = canvas;
sprite.userData.context = context;
sprite.userData.texture = texture;
updateTextSprite(sprite, text, color, background);
return sprite;
}
function updateTextSprite(sprite, text, color = "#eaf7ff", background = "rgba(6,18,29,0.78)") {
const canvas = sprite.userData.canvas;
const context = sprite.userData.context;
const lines = text.split("\n");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = background;
context.fillRect(5, 10, canvas.width - 10, canvas.height - 20);
context.strokeStyle = "rgba(130,205,235,0.22)";
context.lineWidth = 2;
context.strokeRect(5, 10, canvas.width - 10, canvas.height - 20);
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = color;
const lineHeight = lines.length > 1 ? 35 : 44;
const startY = canvas.height / 2 - ((lines.length - 1) * lineHeight) / 2;
lines.forEach((line, index) => {
context.font = lines.length > 1
? `700 ${index === 0 ? 32 : 22}px system-ui, sans-serif`
: "700 31px system-ui, sans-serif";
context.fillText(line, canvas.width / 2, startY + index * lineHeight);
});
sprite.userData.texture.needsUpdate = true;
}
const chargePlus = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.145, 1),
new THREE.MeshStandardMaterial({
color: 0xff8067,
emissive: 0x5b160e,
emissiveIntensity: 0.9,
roughness: 0.52,
metalness: 0.08,
flatShading: true
})
);
const chargeMinus = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.145, 1),
new THREE.MeshStandardMaterial({
color: 0x55d9ff,
emissive: 0x073e53,
emissiveIntensity: 1.05,
roughness: 0.5,
metalness: 0.08,
flatShading: true
})
);
const plusHalo = new THREE.Mesh(
new THREE.TorusGeometry(0.205, 0.008, 4, 24),
new THREE.MeshBasicMaterial({ color: 0xff8067, transparent: true, opacity: 0.48 })
);
plusHalo.rotation.y = Math.PI / 2;
const minusHalo = new THREE.Mesh(
new THREE.TorusGeometry(0.205, 0.008, 4, 24),
new THREE.MeshBasicMaterial({ color: 0x55d9ff, transparent: true, opacity: 0.48 })
);
minusHalo.rotation.x = Math.PI / 2;
const plusLabel = makeTextSprite("+2,4 nC", "#ffad98");
const minusLabel = makeTextSprite("−1,4 nC", "#9beaff");
commonGroup.add(chargePlus, chargeMinus, plusHalo, minusHalo, plusLabel, minusLabel);
const probe = new THREE.Mesh(
new THREE.OctahedronGeometry(0.055, 0),
new THREE.MeshBasicMaterial({ color: 0xffe084 })
);
const probeRing = new THREE.Mesh(
new THREE.TorusGeometry(0.105, 0.009, 4, 22),
new THREE.MeshBasicMaterial({ color: 0xffe084, transparent: true, opacity: 0.78 })
);
probeRing.rotation.y = Math.PI / 2;
const arrowShaftGeometry = new THREE.CylinderGeometry(0.013, 0.013, 0.11, 5);
arrowShaftGeometry.translate(0, 0.055, 0);
const arrowHeadGeometry = new THREE.ConeGeometry(0.044, 0.075, 5);
arrowHeadGeometry.translate(0, 0.1475, 0);
const probeArrowMaterial = new THREE.MeshBasicMaterial({
color: 0xffe084,
transparent: true,
opacity: 0.96,
depthWrite: false
});
function makeArrowUnit(material) {
const arrow = new THREE.Group();
const shaft = new THREE.Mesh(arrowShaftGeometry, material);
const head = new THREE.Mesh(arrowHeadGeometry, material);
arrow.add(shaft, head);
return arrow;
}
const probeArrow = makeArrowUnit(probeArrowMaterial);
probeArrow.scale.set(1.8, 1.8, 1.8);
commonGroup.add(probe, probeRing, probeArrow);
const potentialMapMaterial = new THREE.MeshBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0.79,
side: THREE.DoubleSide,
depthWrite: false
});
const potentialMap = new THREE.Mesh(new THREE.BufferGeometry(), potentialMapMaterial);
potentialGroup.add(potentialMap);
const contourMaterial = new THREE.LineBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0.82
});
const contourLines = new THREE.LineSegments(new THREE.BufferGeometry(), contourMaterial);
potentialGroup.add(contourLines);
const potentialZeroGroup = new THREE.Group();
const fieldZeroGroup = new THREE.Group();
const fieldArrowContainer = new THREE.Group();
potentialGroup.add(potentialZeroGroup);
fieldGroup.add(fieldZeroGroup, fieldArrowContainer);
const fieldMaterialCache = new Map();
function fieldColor(magnitude) {
const t = THREE.MathUtils.clamp(Math.log10(1 + magnitude) / 3.0, 0, 1);
const low = new THREE.Color(0x1a6680);
const middle = new THREE.Color(0x53e2ff);
const high = new THREE.Color(0xffe084);
if (t < 0.55) return low.lerp(middle, t / 0.55);
return middle.lerp(high, (t - 0.55) / 0.45);
}
function getFieldMaterial(color) {
const key = color.getHex();
if (!fieldMaterialCache.has(key)) {
fieldMaterialCache.set(key, new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.78,
depthWrite: false
}));
}
return fieldMaterialCache.get(key);
}
function potentialColor(value) {
const magnitude = THREE.MathUtils.clamp(Math.log10(1 + Math.abs(value)) / 1.65, 0, 1);
const neutral = new THREE.Color(0x263b50);
const positive = new THREE.Color(0xff8067);
const negative = new THREE.Color(0x51d9ff);
const color = value >= 0
? neutral.clone().lerp(positive, magnitude)
: neutral.clone().lerp(negative, magnitude);
if (Math.abs(value) < 0.12) color.lerp(new THREE.Color(0xf3f8ff), 0.65);
return color;
}
function samplePotential(x, y, z) {
const a = state.distance / 2;
const rp = Math.hypot(x + a, y - 0.35, z);
const rn = Math.hypot(x - a, y - 0.35, z);
const epsilon = 0.012;
return state.k * (
state.qPlus / Math.max(rp, epsilon) -
state.qMinus / Math.max(rn, epsilon)
);
}
function sampleField(x, y, z, target = new THREE.Vector3()) {
const a = state.distance / 2;
const rp2 = (x + a) ** 2 + (y - 0.35) ** 2 + z ** 2;
const rn2 = (x - a) ** 2 + (y - 0.35) ** 2 + z ** 2;
const rP3 = Math.max(rp2, 0.012) ** 1.5;
const rN3 = Math.max(rn2, 0.012) ** 1.5;
target.set(
state.k * (state.qPlus * (x + a) / rP3 - state.qMinus * (x - a) / rN3),
state.k * (state.qPlus * (y - 0.35) / rP3 - state.qMinus * (y - 0.35) / rN3),
state.k * (state.qPlus * z / rP3 - state.qMinus * z / rN3)
);
return target;
}
function potentialZeroGeometry() {
const a = state.distance / 2;
const ratio = state.qPlus / state.qMinus;
if (Math.abs(ratio - 1) < 1e-9) {
return {
type: "plane",
center: 0,
radius: Math.max(1.25, a * 2.2),
intersections: [0]
};
}
const center = a * (ratio * ratio + 1) / (ratio * ratio - 1);
const radius = 2 * a * ratio / Math.abs(ratio * ratio - 1);
return {
type: "sphere",
center,
radius,
intersections: [center - radius, center + radius]
};
}
function fieldZeroPosition() {
const a = state.distance / 2;
const difference = state.qPlus - state.qMinus;
if (Math.abs(difference) < 1e-9) return null;
if (state.qPlus > state.qMinus) {
const ratio = Math.sqrt(state.qMinus / state.qPlus);
return a * (1 + ratio) / (1 - ratio);
}
const ratio = Math.sqrt(state.qPlus / state.qMinus);
return -a * (1 + ratio) / (1 - ratio);
}
function updateAxes() {
clearGroup(axisGroup, true, false);
const nullX = fieldZeroPosition();
const xMax = Math.max(1.35, nullX !== null && nullX < 5 ? nullX + 0.35 : 1.35);
const xMin = Math.min(-1.25, nullX !== null && nullX > -5 ? nullX - 0.35 : -1.25);
const lineGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(xMin, 0.35, 0),
new THREE.Vector3(xMax, 0.35, 0)
]);
axisGroup.add(new THREE.Line(
lineGeometry,
new THREE.LineBasicMaterial({ color: 0x7da5ba, transparent: true, opacity: 0.48 })
));
const tickPositions = [];
for (let x = Math.ceil(xMin * 2) / 2; x <= xMax; x += 0.5) {
tickPositions.push(x, 0.29, 0, x, 0.41, 0);
}
const tickGeometry = new THREE.BufferGeometry();
tickGeometry.setAttribute("position", new THREE.Float32BufferAttribute(tickPositions, 3));
axisGroup.add(new THREE.LineSegments(
tickGeometry,
new THREE.LineBasicMaterial({ color: 0x60879b, transparent: true, opacity: 0.36 })
));
const originLabel = makeTextSprite("x = 0", "#9db6c7", "rgba(6,18,29,0.58)");
originLabel.scale.set(0.40, 0.10, 1);
originLabel.position.set(0, 0.16, 0);
axisGroup.add(originLabel);
}
function updatePotentialMap() {
const a = state.distance / 2;
const zero = potentialZeroGeometry();
const xMin = Math.min(-a - 0.62, zero.center - zero.radius - 0.08);
const xMax = Math.max(a + 0.62, zero.center + zero.radius + 0.08);
const width = xMax - xMin;
const center = (xMin + xMax) / 2;
const depth = 2.05;
let geometry = new THREE.PlaneGeometry(width, depth, 25, 14).toNonIndexed();
geometry.rotateX(-Math.PI / 2);
const positions = geometry.attributes.position;
const colors = new Float32Array(positions.count * 3);
for (let triangle = 0; triangle < positions.count; triangle += 3) {
const cx = (positions.getX(triangle) + positions.getX(triangle + 1) + positions.getX(triangle + 2)) / 3 + center;
const cz = (positions.getZ(triangle) + positions.getZ(triangle + 1) + positions.getZ(triangle + 2)) / 3;
const value = samplePotential(cx, -0.28, cz);
const color = potentialColor(value);
for (let vertex = 0; vertex < 3; vertex++) {
const index = triangle + vertex;
colors[index * 3] = color.r;
colors[index * 3 + 1] = color.g;
colors[index * 3 + 2] = color.b;
}
}
geometry.setAttribute("color", new THREE.BufferAttribute(colors, 3));
potentialMap.geometry.dispose();
potentialMap.geometry = geometry;
potentialMap.position.set(center, -0.28, 0);
rebuildContours(xMin, xMax);
}
function rebuildContours(xMin, xMax) {
const nx = 112;
const nz = 66;
const values = new Float32Array((nx + 1) * (nz + 1));
const zMin = -1.02;
const zMax = 1.02;
for (let j = 0; j <= nz; j++) {
const z = zMin + (zMax - zMin) * j / nz;
for (let i = 0; i <= nx; i++) {
const x = xMin + (xMax - xMin) * i / nx;
values[j * (nx + 1) + i] = samplePotential(x, -0.269, z);
}
}
const levels = [-40, -20, -10, -5, -2, 0, 2, 5, 10, 20, 40];
const positions = [];
const colors = [];
const y = -0.265;
for (const level of levels) {
const lineColor = level === 0
? new THREE.Color(0xf5f4d9)
: level < 0
? new THREE.Color(0x66ddff)
: new THREE.Color(0xff927b);
for (let j = 0; j < nz; j++) {
for (let i = 0; i < nx; i++) {
const x0 = xMin + (xMax - xMin) * i / nx;
const x1 = xMin + (xMax - xMin) * (i + 1) / nx;
const z0 = zMin + (zMax - zMin) * j / nz;
const z1 = zMin + (zMax - zMin) * (j + 1) / nz;
const corners = [
[x0, z0, values[j * (nx + 1) + i]],
[x1, z0, values[j * (nx + 1) + i + 1]],
[x1, z1, values[(j + 1) * (nx + 1) + i + 1]],
[x0, z1, values[(j + 1) * (nx + 1) + i]]
];
const intersections = [];
for (let edge = 0; edge < 4; edge++) {
const a = corners[edge];
const b = corners[(edge + 1) % 4];
const crosses = (a[2] < level && b[2] >= level) || (b[2] < level && a[2] >= level);
if (crosses) {
const denominator = b[2] - a[2];
const t = Math.abs(denominator) < 1e-12 ? 0.5 : (level - a[2]) / denominator;
intersections.push([
a[0] + (b[0] - a[0]) * t,
a[1] + (b[1] - a[1]) * t
]);
}
}
for (let segment = 0; segment + 1 < intersections.length; segment += 2) {
const p = intersections[segment];
const q = intersections[segment + 1];
positions.push(p[0], y, p[1], q[0], y, q[1]);
colors.push(lineColor.r, lineColor.g, lineColor.b, lineColor.r, lineColor.g, lineColor.b);
}
}
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3));
contourLines.geometry.dispose();
contourLines.geometry = geometry;
}
function updatePotentialZero() {
clearGroup(potentialZeroGroup, true, true);
const zero = potentialZeroGeometry();
if (zero.type === "sphere") {
const surface = new THREE.Mesh(
new THREE.IcosahedronGeometry(zero.radius, 2),
new THREE.MeshBasicMaterial({
color: 0xffe084,
transparent: true,
opacity: 0.105,
side: THREE.DoubleSide,
depthWrite: false
})
);
surface.position.set(zero.center, 0.35, 0);
const wire = new THREE.LineSegments(
new THREE.EdgesGeometry(surface.geometry, 12),
new THREE.LineBasicMaterial({
color: 0xffe084,
transparent: true,
opacity: 0.46
})
);
surface.add(wire);
potentialZeroGroup.add(surface);
const label = makeTextSprite("V = 0\nsuperfície esférica", "#ffe9a7");
label.scale.set(0.86, 0.22, 1);
label.position.set(zero.center, 0.35 + zero.radius + 0.28, 0);
potentialZeroGroup.add(label);
} else {
const plane = new THREE.Mesh(
new THREE.PlaneGeometry(zero.radius * 2, zero.radius * 1.45),
new THREE.MeshBasicMaterial({
color: 0xffe084,
transparent: true,
opacity: 0.12,
side: THREE.DoubleSide,
depthWrite: false
})
);
plane.rotation.y = Math.PI / 2;
plane.position.set(0, 0.35, 0);
potentialZeroGroup.add(plane);
const edge = new THREE.LineSegments(
new THREE.EdgesGeometry(plane.geometry),
new THREE.LineBasicMaterial({ color: 0xffe084, transparent: true, opacity: 0.55 })
);
plane.add(edge);
const label = makeTextSprite("V = 0\nplano mediador", "#ffe9a7");
label.scale.set(0.86, 0.22, 1);
label.position.set(0, 1.15, 0);
potentialZeroGroup.add(label);
}
}
function updateFieldArrows() {
clearGroup(fieldArrowContainer, false, false);
const nullX = fieldZeroPosition();
const xMin = -1.23;
const xMax = Math.min(4.55, Math.max(1.35, nullX !== null ? nullX + 0.43 : 1.35));
const columns = 15;
const rows = [-0.05, 0.35, 0.75];
const layers = [0.18, -0.29];
const vector = new THREE.Vector3();
const direction = new THREE.Vector3();
const up = new THREE.Vector3(0, 1, 0);
for (const z of layers) {
for (const y of rows) {
for (let i = 0; i < columns; i++) {
const x = xMin + (xMax - xMin) * i / (columns - 1);
sampleField(x, y, z, vector);
const magnitude = vector.length();
if (magnitude < 1e-8) continue;
direction.copy(vector).normalize();
const color = fieldColor(magnitude);
const arrow = makeArrowUnit(getFieldMaterial(color));
arrow.position.set(x, y, z);
arrow.quaternion.setFromUnitVectors(up, direction);
const normalizedLength = THREE.MathUtils.clamp(Math.log10(1 + magnitude) / 3, 0, 1);
arrow.scale.set(1, 0.62 + normalizedLength * 0.95, 1);
fieldArrowContainer.add(arrow);
}
}
}
}
function updateFieldZero() {
clearGroup(fieldZeroGroup, true, true);
const nullX = fieldZeroPosition();
if (nullX === null) {
const label = makeTextSprite("E = 0 somente no infinito", "#a9f4ce");
label.scale.set(1.05, 0.22, 1);
label.position.set(0, 1.18, 0);
fieldZeroGroup.add(label);
return;
}
const marker = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.09, 1),
new THREE.MeshBasicMaterial({
color: 0x83f0bd,
wireframe: true,
transparent: true,
opacity: 0.96
})
);
marker.position.set(nullX, 0.35, 0);
fieldZeroGroup.add(marker);
for (let ring = 0; ring < 3; ring++) {
const torus = new THREE.Mesh(
new THREE.TorusGeometry(0.145 + ring * 0.025, 0.008, 4, 24),
new THREE.MeshBasicMaterial({
color: 0x83f0bd,
transparent: true,
opacity: 0.72
})
);
torus.position.copy(marker.position);
if (ring === 0) torus.rotation.y = Math.PI / 2;
if (ring === 1) torus.rotation.x = Math.PI / 2;
fieldZeroGroup.add(torus);
}
const label = makeTextSprite("E = 0\nponto no eixo", "#b6f7d9");
label.scale.set(0.82, 0.22, 1);
label.position.set(nullX, 0.94, 0);
fieldZeroGroup.add(label);
}
function updateProbe() {
const x = state.probeX;
probe.position.set(x, 0.35, 0);
probeRing.position.set(x, 0.35, 0);
const potential = samplePotential(x, 0.35, 0);
const field = sampleField(x, 0.35, 0);
const magnitude = field.length();
if (magnitude > 1e-10) {
const direction = field.clone().normalize();
probeArrow.position.set(x, 0.35, 0);
probeArrow.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction);
probeArrow.visible = state.mode === "field";
} else {
probeArrow.visible = false;
}
return { potential, field, magnitude };
}
function updateUI(probeValues) {
const a = state.distance / 2;
const zero = potentialZeroGeometry();
const nullX = fieldZeroPosition();
const { potential, field, magnitude } = probeValues;
$("qPlusValue").textContent = `+${format(state.qPlus, 1)} nC`;
$("qMinusValue").textContent = `−${format(state.qMinus, 1)} nC`;
$("distanceValue").textContent = `${format(state.distance, 2)} m`;
$("probeXValue").textContent = `${format(state.probeX, 3)} m`;
$("potentialMetric").textContent = `${signed(potential, 2)} V`;
$("potentialMetricDetail").textContent = potential > 0
? "região de potencial positivo"
: potential < 0
? "região de potencial negativo"
: "P está na superfície V = 0";
$("fieldMetric").textContent = `${format(magnitude, 2)} V/m`;
$("fieldMetricDetail").textContent =
`E = (${signed(field.x, 1)}, ${signed(field.y, 1)}, ${signed(field.z, 1)}) V/m`;
if (zero.type === "sphere") {
$("potentialRefTitle").textContent = "V = 0 · superfície esférica";
$("potentialRef").textContent =
`Esfera de centro x = ${format(zero.center, 3)} m e raio ${format(zero.radius, 3)} m. ` +
`No eixo, cruza V = 0 em x = ${format(zero.intersections[0], 3)} m e ` +
`x = ${format(zero.intersections[1], 3)} m.`;
} else {
$("potentialRefTitle").textContent = "V = 0 · plano mediador";
$("potentialRef").textContent =
"Para cargas opostas de mesma magnitude, a superfície nula é o plano x = 0.";
}
if (nullX === null) {
$("fieldRefTitle").textContent = "E = 0 · somente no infinito";
$("fieldRef").textContent =
"Com magnitudes iguais, não existe ponto finito de campo nulo no eixo.";
$("offscreen").hidden = true;
} else {
$("fieldRefTitle").textContent = "E = 0 · ponto no eixo";
$("fieldRef").textContent =
`Ponto nulo em x = ${format(nullX, 3)} m, ${nullX > 0 ? "à direita" : "à esquerda"} ` +
`da carga de menor magnitude. Não fica entre as duas cargas.`;
$("offscreen").hidden = Math.abs(nullX) <= 4.8;
$("offscreen").textContent =
`E = 0 está em x = ${format(nullX, 3)} m, fora do enquadramento atual. Reajuste os dados ou use “Reenquadrar”.`;
}
const betweenCharges = state.probeX > -a && state.probeX < a;
if (betweenCharges) {
$("zeroWarning").innerHTML =
`<strong>Correção do zero de campo:</strong> x = ${format(state.probeX, 3)} m está entre as cargas. ` +
`Aqui <strong>|E| = ${format(magnitude, 2)} V/m</strong> e Eₓ = ${signed(field.x, 2)} V/m; ` +
`portanto este ponto <strong>não é E = 0</strong>.`;
} else if (nullX !== null && Math.abs(state.probeX - nullX) < 0.002) {
$("zeroWarning").innerHTML =
`<strong>Ponto nulo:</strong> a sonda está no ponto finito x = ${format(nullX, 3)} m, onde ` +
`a soma vetorial dos campos das duas cargas é zero.`;
} else {
$("zeroWarning").innerHTML =
`<strong>Zeros diferentes:</strong> V = 0 descreve uma superfície, enquanto E = 0 é um ponto isolado ` +
`em x = ${nullX === null ? "∞" : format(nullX, 3) + " m"}.`;
}
}
function updateAll() {
const a = state.distance / 2;
chargePlus.position.set(-a, 0.35, 0);
chargeMinus.position.set(a, 0.35, 0);
plusHalo.position.copy(chargePlus.position);
minusHalo.position.copy(chargeMinus.position);
plusLabel.position.set(-a, 0.72, 0);
minusLabel.position.set(a, 0.72, 0);
updateTextSprite(plusLabel, `+${format(state.qPlus, 1)} nC`, "#ffad98");
updateTextSprite(minusLabel, `−${format(state.qMinus, 1)} nC`, "#9beaff");
updateAxes();
updatePotentialMap();
updatePotentialZero();
updateFieldArrows();
updateFieldZero();
const probeValues = updateProbe();
updateUI(probeValues);
updateProbeRange();
}
function updateProbeRange() {
const a = state.distance / 2;
const nullX = fieldZeroPosition();
let min = -a - 0.80;
let max = a + 0.80;
if (state.mode === "field" && nullX !== null) {
min = Math.min(min, Math.max(-5, nullX - 0.25));
max = Math.max(max, Math.min(5, nullX + 0.25));
}
const slider = $("probeX");
slider.min = min;
slider.max = max;
slider.value = THREE.MathUtils.clamp(state.probeX, min, max);
state.probeX = Number(slider.value);
}
function cameraGoalsForMode() {
const a = state.distance / 2;
const nullX = fieldZeroPosition();
const aspect = Math.max(0.55, camera.aspect);
const narrowFactor = Math.max(1, 1.05 / aspect);
if (state.mode === "potential") {
const zero = potentialZeroGeometry();
const xMin = Math.min(-a - 0.55, zero.center - zero.radius - 0.05);
const xMax = Math.max(a + 0.55, zero.center + zero.radius + 0.05);
return {
target: new THREE.Vector3((xMin + xMax) / 2, 0.24, 0),
distance: Math.max(3.45, (xMax - xMin) * 1.22) * narrowFactor,
theta: 0.54,
phi: 1.03
};
}
const visibleNull = nullX !== null && Math.abs(nullX) < 5 ? nullX : 1.35;
const xMin = -1.18;
const xMax = Math.max(1.35, visibleNull + 0.42);
return {
target: new THREE.Vector3((xMin + xMax) / 2, 0.24, 0),
distance: Math.max(5.75, (xMax - xMin) * 1.16) * narrowFactor,
theta: 0.47,
phi: 1.04
};
}
function moveCameraToMode(immediate = false) {
const goal = cameraGoalsForMode();
if (immediate) {
cameraState.target.copy(goal.target);
cameraState.distance = goal.distance;
cameraState.theta = goal.theta;
cameraState.phi = goal.phi;
cameraAnimation = null;
applyCamera();
return;
}
cameraAnimation = {
start: performance.now(),
duration: 720,
fromTarget: cameraState.target.clone(),
toTarget: goal.target.clone(),
fromDistance: cameraState.distance,
toDistance: goal.distance,
fromTheta: cameraState.theta,
toTheta: goal.theta,
fromPhi: cameraState.phi,
toPhi: goal.phi
};
}
function applyCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x + cameraState.distance * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.distance * Math.cos(cameraState.phi),
cameraState.target.z + cameraState.distance * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
function setMode(mode) {
state.mode = mode;
const isPotential = mode === "potential";
potentialGroup.visible = isPotential;
fieldGroup.visible = !isPotential;
probeArrow.visible = !isPotential;
$("modePotential").classList.toggle("active", isPotential);
$("modeField").classList.toggle("active", !isPotential);
$("viewKicker").textContent = isPotential
? "Modelo esquemático · potencial escalar"
: "Modelo esquemático · campo vetorial";
$("viewTitle").textContent = isPotential ? "Potencial elétrico" : "Campo elétrico";
$("viewSubtitle").textContent = isPotential
? "A superfície V = 0 e as curvas isopotenciais são calculadas para o plano de corte."
: "Os vetores dão a direção de E; o ponto E = 0 fica fora do segmento entre as cargas.";
$("legendTitle").textContent = isPotential
? "Potencial · corte y = −0,28 m"
: "Campo · direção de E";
$("legend").innerHTML = isPotential
? `<div id="legendTitle">Potencial · corte y = −0,28 m</div>
<div class="legend-bar"></div>
<div class="legend-labels"><span>V < 0</span><span>V = 0</span><span>V > 0</span></div>`
: `<div id="legendTitle">Campo · direção de E</div>
<div class="field-key">
<svg width="48" height="18" viewBox="0 0 48 18" aria-hidden="true">
<path d="M2 9 H34" stroke="#ffe084" stroke-width="2"/>
<path d="M34 3 L45 9 L34 15 Z" fill="#ffe084"/>
</svg>
<span>comprimento normalizado<br>cor = magnitude |E|</span>
</div>`;
updateProbeRange();
const values = updateProbe();
updateUI(values);
moveCameraToMode(false);
}
$("qPlus").addEventListener("input", event => {
state.qPlus = Number(event.target.value);
updateAll();
});
$("qMinus").addEventListener("input", event => {
state.qMinus = Number(event.target.value);
updateAll();
});
$("distance").addEventListener("input", event => {
state.distance = Number(event.target.value);
updateAll();
});
$("probeX").addEventListener("input", event => {
state.probeX = Number(event.target.value);
const values = updateProbe();
updateUI(values);
});
$("modePotential").addEventListener("click", () => setMode("potential"));
$("modeField").addEventListener("click", () => setMode("field"));
$("resetView").addEventListener("click", () => moveCameraToMode(false));
const canvas = renderer.domElement;
let dragging = false;
let previousX = 0;
let previousY = 0;
let activeButton = 0;
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("pointerdown", event => {
dragging = true;
activeButton = event.button;
previousX = event.clientX;
previousY = event.clientY;
cameraAnimation = null;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
const wantsPan = event.shiftKey || activeButton === 2;
if (wantsPan) {
camera.updateMatrixWorld();
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0);
const up = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 1);
const scale = cameraState.distance * 0.0014;
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(up, dy * scale);
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(cameraState.phi - dy * 0.006, 0.32, 1.48);
}
});
const endDrag = event => {
dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) canvas.releasePointerCapture(event.pointerId);
};
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraAnimation = null;
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance * Math.exp(event.deltaY * 0.001),
1.8,
16
);
}, { passive: false });
canvas.addEventListener("dblclick", () => moveCameraToMode(false));
function resize() {
const width = host.clientWidth;
const height = host.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / Math.max(1, height);
camera.updateProjectionMatrix();
}
window.addEventListener("resize", resize);
resize();
updateAll();
moveCameraToMode(true);
renderer.setAnimationLoop(now => {
if (cameraAnimation) {
const t = THREE.MathUtils.clamp((now - cameraAnimation.start) / cameraAnimation.duration, 0, 1);
const eased = t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
cameraState.target.lerpVectors(cameraAnimation.fromTarget, cameraAnimation.toTarget, eased);
cameraState.distance = THREE.MathUtils.lerp(cameraAnimation.fromDistance, cameraAnimation.toDistance, eased);
cameraState.theta = THREE.MathUtils.lerp(cameraAnimation.fromTheta, cameraAnimation.toTheta, eased);
cameraState.phi = THREE.MathUtils.lerp(cameraAnimation.fromPhi, cameraAnimation.toPhi, eased);
if (t >= 1) cameraAnimation = null;
}
applyCamera();
renderer.render(scene, camera);
});
</script>
</body>
</html>
```