Prompt specification
Build or customize the Three.js 3D scene "Classical orbit and probability-cloud comparison" 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: Classical orbit and probability-cloud comparison
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/classical-orbit-and-probability-cloud-comparison-x1930
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring an atom's nucleus and electron-density distribution. Place a historical orbit-style diagram beside a modern schematic density representation; label their roles and limitations rather than presenting both as equally literal physical pictures. A 3D cutaway view.
Working Three.js Starter (classical-orbit-and-probability-cloud-comparison-x1930):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Cutaway atom — nucleus and electron density</title>
<style>
:root{
--bg:#06090f;
--bg2:#0b111b;
--panel:rgba(14,20,30,.82);
--line:rgba(120,160,200,.18);
--ink:#e8f0f8;
--muted:#93a6bb;
--cyan:#5fd3ff;
--amber:#ffb454;
--rose:#ff6b7d;
--green:#63e6b8;
}
*{box-sizing:border-box}
html,body{margin:0;padding:0}
body{
background:
radial-gradient(1100px 700px at 18% -10%, #101c2e 0%, transparent 60%),
radial-gradient(900px 600px at 100% 0%, #16121f 0%, transparent 55%),
var(--bg);
color:var(--ink);
font:15px/1.55 "Inter",-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
-webkit-font-smoothing:antialiased;
}
.wrap{max-width:1520px;margin:0 auto;padding:26px 22px 60px}
header h1{
font-size:clamp(24px,3.2vw,40px);line-height:1.1;margin:6px 0 8px;font-weight:650;letter-spacing:-.02em;
}
.eyebrow{text-transform:uppercase;letter-spacing:.22em;font-size:11px;color:var(--cyan);opacity:.9}
.lede{color:var(--muted);max-width:74ch;margin:0 0 18px}
.lede b{color:#cfe0ef;font-weight:600}
.layout{display:grid;grid-template-columns:minmax(0,1fr) 336px;gap:16px;align-items:start}
@media (max-width:1080px){ .layout{grid-template-columns:1fr} }
/* ---------- stage ---------- */
.stage{
position:relative;border:1px solid var(--line);border-radius:16px;overflow:hidden;
background:radial-gradient(760px 520px at 50% 45%, #0d1725 0%, #070b12 62%, #05080d 100%);
box-shadow:0 24px 70px rgba(0,0,0,.55);
}
#canvas-host{position:absolute;inset:0}
#canvas-host canvas{display:block;width:100%;height:100%;touch-action:none;cursor:grab}
#canvas-host canvas:active{cursor:grabbing}
.stage{height:clamp(430px,62vh,700px)}
.hud{
position:absolute;left:14px;top:12px;z-index:5;display:flex;flex-wrap:wrap;gap:6px;pointer-events:none;
}
.chip{
font-size:11.5px;letter-spacing:.02em;padding:5px 9px;border-radius:999px;
background:rgba(8,14,22,.72);border:1px solid var(--line);color:var(--muted);backdrop-filter:blur(6px);
}
.chip b{color:#d7e6f4;font-weight:600}
.chip.cy{border-color:rgba(95,211,255,.35);color:#bfe9ff}
.stage-note{
position:absolute;right:14px;top:12px;z-index:5;max-width:290px;font-size:11.5px;color:var(--muted);
background:rgba(8,14,22,.72);border:1px solid var(--line);border-radius:10px;padding:8px 10px;backdrop-filter:blur(6px);
}
.stage-note b{color:#cfe0ef}
@media (max-width:760px){ .stage-note{display:none} }
.leaders{position:absolute;inset:0;z-index:3;pointer-events:none;width:100%;height:100%}
.leaders line{stroke:rgba(150,200,230,.45);stroke-width:1;stroke-dasharray:3 3}
.labels{position:absolute;inset:0;z-index:4;pointer-events:none}
.lab{
position:absolute;transform:translate(-50%,-50%);white-space:nowrap;font-size:11.5px;line-height:1.35;
padding:5px 9px;border-radius:8px;border:1px solid var(--line);
background:rgba(6,11,18,.82);backdrop-filter:blur(6px);color:#d8e6f3;max-width:230px;white-space:normal;
transition:opacity .2s;
}
.lab b{display:block;font-size:11px;letter-spacing:.06em;text-transform:uppercase;color:var(--cyan);font-weight:600}
.lab.amber b{color:var(--amber)}
.lab.amber{border-color:rgba(255,180,84,.32)}
.stage-foot{
position:absolute;left:0;right:0;bottom:0;z-index:5;padding:10px 14px;font-size:11.5px;color:var(--muted);
background:linear-gradient(to top, rgba(4,7,12,.92), rgba(4,7,12,0));display:flex;gap:14px;flex-wrap:wrap;align-items:center;
}
.stage-foot span{display:inline-flex;align-items:center;gap:6px}
.swatch{width:9px;height:9px;border-radius:50%;display:inline-block}
/* ---------- rail ---------- */
.rail{display:flex;flex-direction:column;gap:14px}
.panel{
border:1px solid var(--line);border-radius:14px;background:var(--panel);padding:14px 15px;backdrop-filter:blur(8px);
}
.panel h3{margin:0 0 10px;font-size:12px;letter-spacing:.16em;text-transform:uppercase;color:#bcd3e6;font-weight:600}
.ctl{display:flex;flex-direction:column;gap:9px;margin-bottom:12px}
.ctl label{font-size:12.5px;color:var(--muted);display:flex;justify-content:space-between;align-items:center;gap:8px}
.ctl label b{color:#d9e7f3;font-weight:600;font-variant-numeric:tabular-nums}
input[type=range]{width:100%;accent-color:var(--cyan)}
.toggles{display:grid;gap:7px;margin-top:4px}
.tg{display:flex;align-items:flex-start;gap:9px;font-size:12.5px;color:var(--muted);cursor:pointer;line-height:1.4}
.tg input{accent-color:var(--cyan);margin-top:2px}
.tg b{color:#d9e7f3;font-weight:600}
.tg .tag{font-size:10px;text-transform:uppercase;letter-spacing:.08em;border:1px solid var(--line);border-radius:5px;padding:1px 5px;color:#9fb3c8;white-space:nowrap}
.buttons{display:flex;gap:8px;flex-wrap:wrap;margin-top:12px}
button{
font:inherit;font-size:12.5px;color:#d9e7f3;background:rgba(30,44,62,.6);border:1px solid var(--line);
border-radius:9px;padding:7px 11px;cursor:pointer;transition:.15s;
}
button:hover{background:rgba(45,66,90,.75);border-color:rgba(95,211,255,.4)}
.panel p{margin:0 0 9px;font-size:12.8px;color:var(--muted)}
.panel ul{margin:0;padding-left:17px;font-size:12.8px;color:var(--muted)}
.panel li{margin-bottom:6px}
.panel li b,.panel p b{color:#d9e7f3;font-weight:600}
.kbd{font:11px ui-monospace,SFMono-Regular,Menlo,monospace;border:1px solid var(--line);border-radius:5px;padding:1px 5px;color:#bcd3e6}
#measure-log{font:11.5px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;color:#8fe3c0;background:rgba(0,0,0,.35);
border:1px solid var(--line);border-radius:9px;padding:8px 10px;margin-top:10px;min-height:38px;white-space:pre-line}
/* ---------- comparison ---------- */
.compare{margin-top:26px}
.compare h2{font-size:clamp(17px,2vw,23px);margin:0 0 6px;font-weight:620;letter-spacing:-.01em}
.compare .sub{color:var(--muted);margin:0 0 16px;max-width:86ch}
.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:16px}
.card{border:1px solid var(--line);border-radius:16px;background:var(--panel);padding:16px 17px;overflow:hidden}
.card .kicker{display:flex;align-items:center;gap:8px;font-size:11px;letter-spacing:.16em;text-transform:uppercase;font-weight:600}
.card .kicker .dot{width:8px;height:8px;border-radius:50%}
.card.hist .kicker{color:var(--amber)} .card.hist .kicker .dot{background:var(--amber)}
.card.mod .kicker{color:var(--cyan)} .card.mod .kicker .dot{background:var(--cyan)}
.card.note .kicker{color:var(--green)} .card.note .kicker .dot{background:var(--green)}
.card h3{margin:9px 0 4px;font-size:17px;font-weight:620;letter-spacing:-.01em}
.card .dates{color:var(--muted);font-size:12px;margin:0 0 12px}
.fig{background:#070c14;border:1px solid var(--line);border-radius:12px;padding:6px;margin-bottom:12px}
.fig svg{display:block;width:100%;height:auto}
.roles{display:grid;gap:10px}
.role{border-left:2px solid var(--line);padding-left:10px;font-size:12.8px;color:var(--muted)}
.role .t{font-size:10.5px;letter-spacing:.14em;text-transform:uppercase;color:#9fb3c8;font-weight:600;display:block;margin-bottom:3px}
.role.lit{border-left-color:rgba(95,211,255,.5)}
.role.lim{border-left-color:rgba(255,107,125,.45)}
.role b{color:#dfeaf4;font-weight:600}
.card .verdict{margin:12px 0 0;font-size:12.5px;color:#cfe0ef;border-top:1px dashed var(--line);padding-top:10px}
.fig-cap{font-size:11.5px;color:var(--muted);margin:8px 2px 0}
footer{margin-top:26px;color:#6f8296;font-size:12px;border-top:1px solid var(--line);padding-top:14px}
footer b{color:#9fb3c8}
@media (max-width:520px){ .wrap{padding:16px 12px 40px} }
</style>
</head>
<body>
<div class="wrap">
<header>
<div class="eyebrow">Interactive explainer · quantum mechanics vs. the textbook atom</div>
<h1>An atom, cut open: nucleus and electron density</h1>
<p class="lede">
A wedge of the electron region has been sliced away so you can look straight at the <b>nucleus</b> inside a
cloud of <b>electron probability density</b>. Below the cutaway, two familiar diagrams sit side by side:
the <b>historical orbit-style picture</b> (a teaching heuristic) and the <b>modern density picture</b>
(the literal quantum statement). They are not two equally literal portraits of the same object — each is
good at different things, and each fails at others.
</p>
</header>
<div class="layout">
<!-- ================= 3D STAGE ================= -->
<section class="stage" id="stage">
<div id="canvas-host"></div>
<div class="hud">
<span class="chip cy"><b>3D cutaway</b> · wedge removed</span>
<span class="chip">drag = orbit · wheel = zoom · click cloud = measurement</span>
</div>
<div class="stage-note">
<b>What you are looking at:</b> cyan/white haze = probability density |ψ|² of a schematic
1s·2s·2p mixture; the two flat cut planes show the same density in cross‑section.
</div>
<svg class="leaders" id="leaders"></svg>
<div class="labels" id="labels">
<div class="lab" id="lab-nucleus"><b>Nucleus</b>protons + neutrons (illustrative 8p + 8n)</div>
<div class="lab" id="lab-density"><b>Electron density</b>|ψ|² — probability, not a trail</div>
<div class="lab" id="lab-shell"><b>Iso-density surface</b>outer cut boundary (schematic threshold)</div>
<div class="lab" id="lab-cut"><b>Cut plane</b>density in cross-section</div>
<div class="lab amber" id="lab-orbit"><b>Interpretive overlay</b>historical orbit heuristic — not a physical path</div>
</div>
<div class="stage-foot">
<span><i class="swatch" style="background:#ff6b7d"></i>protons</span>
<span><i class="swatch" style="background:#9fb6cc"></i>neutrons</span>
<span><i class="swatch" style="background:#ffd8a8"></i>1s density</span>
<span><i class="swatch" style="background:#66f0c8"></i>2s density</span>
<span><i class="swatch" style="background:#8ab6ff"></i>2p density</span>
<span><i class="swatch" style="background:#ffb454"></i>orbit overlay (heuristic)</span>
<span style="margin-left:auto">Not to scale: nucleus drawn ≈10³× too large (true ratio ≈10⁵:1)</span>
</div>
</section>
<!-- ================= RAIL ================= -->
<aside class="rail">
<div class="panel">
<h3>View controls</h3>
<div class="ctl">
<label for="cut">Cutaway opening <b id="cut-val">96°</b></label>
<input type="range" id="cut" min="30" max="170" value="96" step="1">
</div>
<div class="toggles">
<label class="tg"><input type="checkbox" id="t-cloud" checked><span><b>Electron density cloud</b><br>the modern, literal part</span></label>
<label class="tg"><input type="checkbox" id="t-shell" checked><span><b>Iso-density surfaces</b><br>nested constant-|ψ|² shells</span></label>
<label class="tg"><input type="checkbox" id="t-orbit"><span><b>Historical orbit overlay</b> <span class="tag">heuristic</span><br>amber rings, interpretive only</span></label>
<label class="tg"><input type="checkbox" id="t-labels" checked><span><b>Labels</b></span></label>
<label class="tg"><input type="checkbox" id="t-spin" checked><span><b>Slow auto-rotation</b></span></label>
</div>
<div class="buttons">
<button id="btn-reset">Reset view</button>
<button id="btn-clear">Clear measurements</button>
</div>
<div id="measure-log">No measurements yet — click the density cloud.</div>
</div>
<div class="panel">
<h3>How to read the cutaway</h3>
<ul>
<li><b>The cutaway is a viewing convenience.</b> An atom has no wall and no wedge; the flat planes are
where a slice was taken so you can see inside.</li>
<li><b>The haze is a probability distribution.</b> Brightness = chance of finding an electron there.
It is not a gas, not a smeared electron, and not a path.</li>
<li><b>One measurement = one dot.</b> Click the cloud: each click samples a fresh location from |ψ|² and
drops a marker. Repeated clicks scatter — that is why the picture looks fuzzy.</li>
<li><b>The amber rings are an overlay.</b> They repeat the Bohr-style picture inside the same scene to
show how the two representations relate — and where they do not.</li>
</ul>
</div>
<div class="panel">
<h3>Scope of this model</h3>
<p>Real many-electron atoms have no closed-form wavefunction, so the orbital mixture, the nuclear
composition and the iso-density thresholds here are <b>illustrative</b>. The physics being illustrated —
<b>quantized states, probability density, measurement outcomes</b> — is not.</p>
</div>
</aside>
</div>
<!-- ================= COMPARISON ================= -->
<section class="compare">
<h2>Two diagrams of the same atom — and what each can and cannot claim</h2>
<p class="sub">The left panel is a <b>historical teaching model</b>: useful, but a heuristic, and physically wrong in
ways that matter. The right panel is the <b>modern quantum-mechanical statement</b>: physically correct about
probability, but easy to over-read as a picture of a smeared electron. Read them as answers to different
questions, not as competing portraits.</p>
<div class="cards">
<!-- HISTORICAL -->
<article class="card hist">
<div class="kicker"><span class="dot"></span>Historical model</div>
<h3>Bohr-style orbits: the “solar-system atom”</h3>
<p class="dates">Rutherford's nucleus (1911) → Bohr's quantized planetary model (1913) → widely taught through the 20th century</p>
<div class="fig">
<svg viewBox="0 0 640 400" role="img" aria-label="Diagram of a historical orbit-style atom with electrons drawn on fixed elliptical paths">
<defs>
<radialGradient id="nucGrad" cx="38%" cy="32%">
<stop offset="0%" stop-color="#ff9aa6"/><stop offset="60%" stop-color="#e8455a"/><stop offset="100%" stop-color="#7d1f2c"/>
</radialGradient>
<marker id="ah" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
<path d="M0,0 L10,5 L0,10 z" fill="#ffb454"/>
</marker>
</defs>
<g id="hist-orbits"></g>
<circle cx="320" cy="200" r="30" fill="url(#nucGrad)" stroke="#ffd0d6" stroke-width="1.5"/>
<text x="320" y="205" text-anchor="middle" font-size="11" fill="#fff">nucleus</text>
<g font-size="12" fill="#c8d6e4">
<text x="320" y="378" text-anchor="middle" fill="#ffb454">electrons drawn on fixed paths (illustration of the model)</text>
<text x="24" y="30" fill="#8ea3b8">energy levels n = 1, 2, 3 …</text>
</g>
<g stroke="#ffb454" stroke-width="1" fill="none" opacity=".85">
<path d="M92 150 q26 -16 52 0" marker-end="url(#ah)"/>
</g>
</svg>
</div>
<p class="fig-cap">Drawings of a point-like electron orbiting a point-like nucleus on a definite, closed path.</p>
<div class="roles">
<div class="role lit"><span class="t">Role — what it is good for</span>
A <b>heuristic and pedagogical model</b>. It introduced the idea of <b>quantized energy levels</b> and shells,
which is why it survives in classrooms: it explains line spectra via <b>hν = ΔE</b>, the shell structure behind
the periodic table, and chemical reactivity in a single glance. It is the standard first scaffold for
thinking about atoms.</div>
<div class="role lim"><span class="t">Limitations — what it cannot claim</span>
The electrons are <b>not</b> on those tracks. A classical electron on a fixed orbit would <b>radiate</b> and spiral
into the nucleus (an "atom" would collapse), so the picture is not dynamically possible. The model has no orbital
<b>shape</b>, <b>orientation</b>, <b>spin</b> or many-electron distribution, cannot explain intensity, bond geometry
or the periodic exceptions, and was superseded by quantum mechanics in 1926.</div>
</div>
<p class="verdict"><b>Status:</b> a useful cartoon about <i>quantization</i>, not a claim about <i>motion</i>.</p>
</article>
<!-- MODERN -->
<article class="card mod">
<div class="kicker"><span class="dot"></span>Modern representation</div>
<h3>Wavefunction density: the “probability-cloud atom”</h3>
<p class="dates">de Broglie & Heisenberg (1924–27) → Schrödinger equation → the picture used in chemistry and physics today</p>
<div class="fig">
<svg viewBox="0 0 640 400" role="img" aria-label="Schematic density map of an atom showing shaded probability density with iso-density contours and individual measurement points">
<defs>
<clipPath id="figClip"><rect x="0" y="0" width="640" height="400" rx="10"/></clipPath>
</defs>
<g clip-path="url(#figClip)">
<rect width="640" height="400" fill="#070c14"/>
<image id="dens-image" x="0" y="0" width="640" height="400" preserveAspectRatio="none"/>
<g id="dens-dots"></g>
</g>
<g font-size="12" fill="#bcd3e6">
<text x="26" y="34">shading = |ψ|², the probability density</text>
<text x="26" y="54" fill="#8ea3b8">iso-density contours (constant probability)</text>
<text x="26" y="376" fill="#8fe3c0">one measurement = one dot, at one place</text>
</g>
</svg>
</div>
<p class="fig-cap">A slice through the same schematic density mixture used in the 3D cutaway, plus two sample
measurement outcomes. Dots are <i>separate</i> measurements — not a trajectory.</p>
<div class="roles">
<div class="role lit"><span class="t">Role — what it is good for</span>
This one is <b>physically literal</b>. The wavefunction <b>ψ(r)</b> is the quantum state; <b>|ψ|² d³r</b> is the
probability of finding the electron in a small volume. Density maps and iso-density surfaces are what
<b>experiments actually measure</b> — electron scattering, X-ray absorption, spectroscopy. It also predicts orbital
shapes and orientations, spins, bonding and spectra quantitatively.</div>
<div class="role lim"><span class="t">Limitations — what it cannot claim</span>
The cloud is <b>not</b> a smeared electron, not a gas, and not a trail. A measurement collapses it to a
<b>single localized detection</b>; the blur is our inability to know the outcome in advance. The picture depends on
a chosen <b>representation</b> (orbital basis, isosurface threshold), many-electron atoms have no closed-form ψ,
and a 3D rendering is a slice of information, not the state itself.</div>
</div>
<p class="verdict"><b>Status:</b> the correct statement about <i>where an electron might be found</i>, not about
<i>where it is smeared</i>.</p>
</article>
<!-- NOTE -->
<article class="card note">
<div class="kicker"><span class="dot"></span>How to use the two together</div>
<h3>Neither picture <i>is</i> the atom</h3>
<p class="dates">A short reading guide</p>
<ul style="color:var(--muted);font-size:12.8px;padding-left:17px;margin:0 0 12px">
<li><b>Ask what each answers.</b> "Why are there discrete energies and a periodic table?" → the orbit picture
(roughly). "Where is the electron likely to be detected?" → the density picture (exactly).</li>
<li><b>Do not mix their vocabularies.</b> "Electrons orbit" imports the wrong physics; "the electron is a cloud"
imports the wrong ontology. Neither is a literal snapshot.</li>
<li><b>The nucleus is the literal part.</b> Protons and neutrons are localized constituents with a measured
radius ≈10⁻¹⁵ m — that part of the picture is real, unlike the classical trajectory.</li>
<li><b>The cloud is a statistical statement</b> about a state that also carries spin, energy and quantum numbers —
none of which the haze shows.</li>
</ul>
<div class="role lim"><span class="t">Common misconception to avoid</span>
"The electron is smeared out in a cloud" is as wrong as "the electron spins like a planet." The electron is
detected in one place; the cloud encodes the <b>prior probability</b> of that outcome. Schrödinger–Newton is the
cleanest way to keep both facts in view.</div>
<p class="verdict"><b>Suggested reading:</b> Bohr, <i>Phil. Mag.</i> 1913; Schrödinger, <i>Phys. Rev.</i> 1926;
Feynman Lectures, Vol. III ch. 19–20; Atkins & Friedman, <i>Quanta, Waves and Particles</i>.</p>
</article>
</div>
</section>
<footer>
<b>Built with:</b> Three.js r160 core ES module from cdnjs only — camera orbit/zoom/pan, cutaway geometry, procedural
density textures and the point cloud are all hand-written in this file; no addons are loaded.
<b>Physics caveats:</b> orbital mixture, nuclear composition and density thresholds are schematic; the atom is not to scale.
</footer>
</div>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
/* ============================================================
Scene setup
============================================================ */
const host = document.getElementById('canvas-host');
const renderer = new THREE.WebGLRenderer({ antialias:true, alpha:true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setClearColor(0x000000, 0);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.outputColorSpace = THREE.SRGBColorSpace;
host.appendChild(renderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(42, 1, 0.05, 300);
scene.add(new THREE.AmbientLight(0x445a72, 1.15));
const key = new THREE.DirectionalLight(0xffffff, 2.4); key.position.set(4, 6, 5); scene.add(key);
const fill = new THREE.DirectionalLight(0x7fb4ff, 1.25); fill.position.set(-6, -2, -3); scene.add(fill);
const rim = new THREE.PointLight(0x66d8ff, 12, 30); rim.position.set(0, 0, 0); scene.add(rim);
/* ============================================================
Constants / model parameters
============================================================ */
const R = 2.6; // outer iso-density surface radius (world units)
const A0 = 0.55; // Bohr-radius-like scale used for the schematic mixture
const NUC_R = 0.30; // nucleus radius (heavily exaggerated)
const NUCLEON_R = 0.082;
/* ============================================================
Custom camera controls (no addons)
============================================================ */
const view = { az: 0.85, pol: 1.16, rad: 9.2 };
const goal = { ...view };
const target = new THREE.Vector3(0, 0, 0);
const goalTarget = new THREE.Vector3(0, 0, 0);
function applyCamera(){
const sp = Math.sin(view.pol), cp = Math.cos(view.pol);
camera.position.set(
target.x + view.rad * sp * Math.cos(view.az),
target.y + view.rad * cp,
target.z + view.rad * sp * Math.sin(view.az)
);
camera.lookAt(target);
}
applyCamera();
const pointers = new Map();
let dragging = false, panning = false, lastX = 0, lastY = 0, pinchDist = 0;
renderer.domElement.addEventListener('pointerdown', e => {
renderer.domElement.setPointerCapture(e.pointerId);
pointers.set(e.pointerId, { x:e.clientX, y:e.clientY });
if (pointers.size === 1){ dragging = true; panning = e.shiftKey || e.button === 2; lastX = e.clientX; lastY = e.clientY; }
if (pointers.size === 2){
const [a,b] = [...pointers.values()];
pinchDist = Math.hypot(a.x-b.x, a.y-b.y);
}
});
renderer.domElement.addEventListener('pointermove', e => {
if (!pointers.has(e.pointerId)) return;
pointers.set(e.pointerId, { x:e.clientX, y:e.clientY });
if (pointers.size === 2){
const [a,b] = [...pointers.values()];
const d = Math.hypot(a.x-b.x, a.y-b.y);
if (pinchDist > 0) goal.rad = clamp(goal.rad * (pinchDist / d), 3.2, 26);
pinchDist = d; return;
}
if (!dragging) return;
const dx = e.clientX - lastX, dy = e.clientY - lastY;
lastX = e.clientX; lastY = e.clientY;
if (panning){
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0);
const up = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 1);
const s = goal.rad * 0.0016;
goalTarget.addScaledVector(right, -dx*s).addScaledVector(up, dy*s);
} else {
goal.az -= dx * 0.006;
goal.pol = clamp(goal.pol + dy * 0.006, 0.14, Math.PI - 0.14);
}
});
const endPointer = e => {
pointers.delete(e.pointerId);
if (pointers.size < 2) pinchDist = 0;
if (pointers.size === 0) dragging = false;
};
renderer.domElement.addEventListener('pointerup', endPointer);
renderer.domElement.addEventListener('pointercancel', endPointer);
renderer.domElement.addEventListener('contextmenu', e => e.preventDefault());
renderer.domElement.addEventListener('wheel', e => {
e.preventDefault();
goal.rad = clamp(goal.rad * (1 + Math.sign(e.deltaY) * 0.09), 3.2, 26);
}, { passive:false });
function clamp(v,a,b){ return Math.max(a, Math.min(b, v)); }
function lerp(a,b,t){ return a + (b-a)*t; }
/* ============================================================
Procedural density texture (used on the cut planes + panel)
============================================================ */
function densValue(x){ // x = radius in units of A0, normalised 0..1
const s1 = Math.exp(-2*x);
const s2 = Math.pow(Math.max(0, 2-x), 2) * Math.exp(-x) / 4;
const p2 = Math.pow(x,4) * Math.exp(-x) / 4.6875;
return (0.35*s1 + 0.20*s2 + 0.45*p2) / 0.55;
}
function makeDensityCanvas(size, palette){
const c = document.createElement('canvas'); c.width = c.height = size;
const ctx = c.getContext('2d');
const img = ctx.createImageData(size, size);
const d = img.data;
const levels = [0.03, 0.07, 0.15, 0.30, 0.50];
for (let y = 0; y < size; y++){
for (let x = 0; x < size; x++){
const ux = (x + 0.5)/size*2 - 1, uy = (y + 0.5)/size*2 - 1;
const rho = Math.hypot(ux, uy) * R; // world units
const v = densValue(rho / A0);
let rr = palette.lo[0], gg = palette.lo[1], bb = palette.lo[2], aa = 0;
if (v > 0.008){
const t = Math.pow(Math.min(1, v), 0.55);
rr = lerp(palette.lo[0], palette.hi[0], t);
gg = lerp(palette.lo[1], palette.hi[1], t);
bb = lerp(palette.lo[2], palette.hi[2], t);
aa = Math.min(0.95, 0.10 + 0.90*Math.pow(v, 0.65));
}
// contour detection against neighbours
let isLine = false;
for (const lv of levels){
const e = 0.004;
const vxp = densValue((Math.hypot(ux+e, uy)*R)/A0);
const vxm = densValue((Math.hypot(ux-e, uy)*R)/A0);
const vyp = densValue((Math.hypot(ux, uy+e)*R)/A0);
const vym = densValue((Math.hypot(ux, uy-e)*R)/A0);
if ((v-lv)*(vxp-lv) < 0 || (v-lv)*(vxm-lv) < 0 || (v-lv)*(vyp-lv) < 0 || (v-lv)*(vym-lv) < 0){
isLine = true; break;
}
}
if (isLine){ rr = palette.line[0]; gg = palette.line[1]; bb = palette.line[2]; aa = 0.85; }
const i = (y*size + x)*4;
d[i] = rr; d[i+1] = gg; d[i+2] = bb; d[i+3] = aa*255;
}
}
ctx.putImageData(img, 0, 0);
return c;
}
const cutPalette = { lo:[6,40,58], hi:[210,248,255], line:[255,255,255] };
const panelPalette = { lo:[8,34,52], hi:[120,225,250], line:[190,240,255] };
const cutTexture = new THREE.CanvasTexture(makeDensityCanvas(512, cutPalette));
cutTexture.colorSpace = THREE.SRGBColorSpace;
const panelCanvas = makeDensityCanvas(700, panelPalette);
document.getElementById('dens-image').setAttribute('href', panelCanvas.toDataURL('image/png'));
/* ============================================================
Nucleus
============================================================ */
const nucleusGroup = new THREE.Group();
scene.add(nucleusGroup);
{
const pMat = new THREE.MeshStandardMaterial({ color:0xff5f72, roughness:0.45, metalness:0.05, emissive:0x3a0a12, emissiveIntensity:0.5 });
const nMat = new THREE.MeshStandardMaterial({ color:0x9fb6cc, roughness:0.55, metalness:0.05, emissive:0x16222e, emissiveIntensity:0.5 });
const proto = new THREE.SphereGeometry(NUCLEON_R, 20, 16);
const total = 16, protons = 8;
for (let i = 0; i < total; i++){
const t = (i + 0.5) / total;
const y = 1 - 2*t;
const r = Math.sqrt(Math.max(0, 1 - y*y));
const phi = i * Math.PI * (3 - Math.sqrt(5));
const jitter = 0.86 + Math.random()*0.28;
const px = Math.cos(phi)*r*NUC_R*jitter;
const py = y*NUC_R*jitter;
const pz = Math.sin(phi)*r*NUC_R*jitter;
const m = new THREE.Mesh(proto, i < protons ? pMat : nMat);
m.position.set(px, py, pz);
m.rotation.set(Math.random()*3, Math.random()*3, Math.random()*3);
nucleusGroup.add(m);
}
// glow
const gc = document.createElement('canvas'); gc.width = gc.height = 128;
const gx = gc.getContext('2d');
const grd = gx.createRadialGradient(64,64,0, 64,64,64);
grd.addColorStop(0, 'rgba(255,220,200,0.75)');
grd.addColorStop(0.35, 'rgba(255,150,140,0.22)');
grd.addColorStop(1, 'rgba(255,120,120,0)');
gx.fillStyle = grd; gx.fillRect(0,0,128,128);
const gt = new THREE.CanvasTexture(gc);
const glow = new THREE.Sprite(new THREE.SpriteMaterial({ map:gt, blending:THREE.AdditiveBlending, depthWrite:false, transparent:true }));
glow.scale.set(1.9, 1.9, 1);
nucleusGroup.add(glow);
}
/* ============================================================
Electron density point cloud (schematic 1s / 2s / 2p mixture)
============================================================ */
const ORBS = [
{ key:'1s', n:12000, col:[1.00,0.85,0.66], size:0.030 },
{ key:'2s', n: 7000, col:[0.40,0.94,0.78], size:0.040 },
{ key:'2px', n: 5000, col:[0.54,0.71,1.00], size:0.045 },
{ key:'2py', n: 5000, col:[0.66,0.55,1.00], size:0.045 },
{ key:'2pz', n: 5000, col:[0.42,0.84,1.00], size:0.045 },
];
function gamma(k){ let s = 0; for (let i=0;i<k;i++) s += Math.log(Math.random()); return -s; }
function uniformDir(){
const z = 2*Math.random() - 1, a = 2*Math.random()*Math.PI;
const s = Math.sqrt(Math.max(0,1-z*z));
return [s*Math.cos(a), z, s*Math.sin(a)];
}
function sampleDir(orb){
// rejection sampling on |Y|^2 for the p orbitals
for (let k=0; k<200; k++){
const z = 2*Math.random() - 1, a = 2*Math.random()*Math.PI;
const st = Math.sqrt(Math.max(0,1-z*z));
let p;
if (orb === '2px') p = st*st*Math.cos(a)*Math.cos(a);
else if (orb === '2py') p = st*st*Math.sin(a)*Math.sin(a);
else p = z*z;
if (Math.random() < p) return [st*Math.cos(a), z, st*Math.sin(a)];
}
return uniformDir();
}
function samplePosition(orb){
let r, dir;
if (orb === '1s'){
r = A0 * 0.5 * gamma(3);
dir = uniformDir();
} else if (orb === '2s'){
for(;;){
const x = gamma(3);
if (Math.random() < Math.min(1, Math.pow(Math.max(0,2-x)/2, 2))){ r = A0*x; break; }
}
dir = uniformDir();
} else {
r = A0 * gamma(5);
dir = sampleDir(orb);
}
return new THREE.Vector3(dir[0]*r, dir[1]*r, dir[2]*r);
}
const cloudUniforms = {
uCutHalf:{ value:0.84 }, uWedge:{ value:new THREE.Vector3(1,0,0) },
uScale:{ value:600 }, uFade:{ value:1 }
};
const cloudMat = new THREE.ShaderMaterial({
uniforms: cloudUniforms,
vertexShader:`
attribute vec3 aColor;
attribute float aSize;
uniform float uCutHalf;
uniform vec3 uWedge;
uniform float uScale;
varying vec3 vColor;
varying float vKeep;
void main(){
vec3 dir = normalize(position);
float ang = acos(clamp(dot(dir, uWedge), -1.0, 1.0));
vKeep = smoothstep(uCutHalf - 0.10, uCutHalf + 0.02, ang);
vColor = aColor;
vec4 mv = modelViewMatrix * vec4(position, 1.0);
gl_PointSize = max(1.0, aSize * uScale / max(0.001, -mv.z));
gl_Position = projectionMatrix * mv;
}`,
fragmentShader:`
varying vec3 vColor;
varying float vKeep;
void main(){
vec2 uv = gl_PointCoord - 0.5;
float d = length(uv);
float a = smoothstep(0.5, 0.06, d);
if (a * vKeep < 0.004) discard;
gl_FragColor = vec4(vColor, a * vKeep * 0.55);
}`,
transparent:true, depthWrite:false, blending:THREE.AdditiveBlending
});
const cloud = (() => {
let total = 0; ORBS.forEach(o => total += o.n);
const pos = new Float32Array(total*3), col = new Float32Array(total*3), siz = new Float32Array(total);
let k = 0;
for (const o of ORBS){
for (let i = 0; i < o.n; i++){
const p = samplePosition(o.key);
pos[k*3] = p.x; pos[k*3+1] = p.y; pos[k*3+2] = p.z;
col[k*3] = o.col[0]; col[k*3+1] = o.col[1]; col[k*3+2] = o.col[2];
siz[k] = o.size * (0.7 + Math.random()*0.7);
k++;
}
}
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.BufferAttribute(pos, 3));
g.setAttribute('aColor', new THREE.BufferAttribute(col, 3));
g.setAttribute('aSize', new THREE.BufferAttribute(siz, 1));
const m = new THREE.Points(g, cloudMat);
m.renderOrder = 4;
m.frustumCulled = false;
return m;
})();
scene.add(cloud);
/* ============================================================
Iso-density shells (hologram shader)
============================================================ */
function shellMaterial(color, alpha, power){
return new THREE.ShaderMaterial({
uniforms:{ uColor:{ value:new THREE.Color(color) }, uAlpha:{ value:alpha }, uPower:{ value:power } },
vertexShader:`
varying vec3 vN; varying vec3 vP;
void main(){
vN = normalize(normalMatrix * normal);
vec4 mv = modelViewMatrix * vec4(position,1.0);
vP = mv.xyz;
gl_Position = projectionMatrix * mv;
}`,
fragmentShader:`
uniform vec3 uColor; uniform float uAlpha; uniform float uPower;
varying vec3 vN; varying vec3 vP;
void main(){
vec3 V = normalize(-vP);
float f = pow(1.0 - abs(dot(normalize(vN), V)), uPower);
float a = uAlpha * (0.05 + 0.95*f);
gl_FragColor = vec4(uColor, a);
}`,
transparent:true, side:THREE.DoubleSide, depthWrite:false, blending:THREE.AdditiveBlending
});
}
const isoGroup = new THREE.Group();
[
{ r:R, c:0x4fc3ff, a:0.55 },
{ r:R*0.53,c:0x74d7ff, a:0.34 },
{ r:R*0.26,c:0xbfeeff, a:0.24 }
].forEach(s => {
const m = new THREE.Mesh(new THREE.SphereGeometry(s.r, 64, 48), shellMaterial(s.c, s.a, 2.4));
m.renderOrder = 3; isoGroup.add(m);
});
scene.add(isoGroup);
/* ============================================================
Cutaway: outer shell with a wedge removed + two flat cut planes
============================================================ */
const cutGroup = new THREE.Group(); // rotates so the opening faces the camera
scene.add(cutGroup);
let cutAngle = THREE.MathUtils.degToRad(96);
let cutGeo = null, face1 = null, face2 = null, arc1 = null, arc2 = null;
const faceMat = new THREE.MeshBasicMaterial({
map: cutTexture, transparent:true, opacity:0.92, side:THREE.DoubleSide, depthWrite:false
});
const outerShellMat = shellMaterial(0x54c8ff, 0.5, 2.2);
const arcMat = new THREE.LineBasicMaterial({ color:0xbfeaff, transparent:true, opacity:0.9 });
function halfDiscGeometry(tangent, normal){
const shape = new THREE.Shape();
shape.moveTo(0, -R);
shape.absarc(0, 0, R, -Math.PI/2, Math.PI/2, false);
shape.lineTo(0, -R);
const g = new THREE.ShapeGeometry(shape, 72);
const m = new THREE.Matrix4().makeBasis(tangent, new THREE.Vector3(0,1,0), normal);
g.applyMatrix4(m);
return g;
}
function arcGeometry(tangent){
const pts = [];
for (let i = 0; i <= 96; i++){
const a = -Math.PI/2 + Math.PI * i/96;
pts.push(new THREE.Vector3(
tangent.x*Math.cos(a)*R, Math.sin(a)*R, tangent.z*Math.cos(a)*R
));
}
return new THREE.BufferGeometry().setFromPoints(pts);
}
function rebuildCutaway(angle){
cutAngle = angle;
if (cutGeo){ cutGeo.dispose(); face1.geometry.dispose(); face2.geometry.dispose();
arc1.geometry.dispose(); arc2.geometry.dispose();
cutGroup.remove(cutGeo, face1, face2, arc1, arc2); }
const half = angle/2;
cutGeo = new THREE.SphereGeometry(R, 96, 64, half, Math.PI*2 - angle);
const outer = new THREE.Mesh(cutGeo, outerShellMat);
outer.renderOrder = 5;
cutGroup.add(outer);
const p1 = half, p2 = -half;
const t1 = new THREE.Vector3(Math.sin(p1), 0, Math.cos(p1));
const n1 = new THREE.Vector3(-Math.cos(p1), 0, Math.sin(p1));
const t2 = new THREE.Vector3(Math.sin(p2), 0, Math.cos(p2));
const n2 = new THREE.Vector3(-Math.cos(p2), 0, Math.sin(p2));
face1 = new THREE.Mesh(halfDiscGeometry(t1, n1), faceMat); face1.renderOrder = 2;
face2 = new THREE.Mesh(halfDiscGeometry(t2.clone().negate(), n2.clone().negate()), faceMat); face2.renderOrder = 2;
arc1 = new THREE.Line(arcGeometry(t1), arcMat); arc1.renderOrder = 6;
arc2 = new THREE.Line(arcGeometry(t2.clone().negate()), arcMat); arc2.renderOrder = 6;
cutGroup.add(face1, face2, arc1, arc2);
cloudUniforms.uCutHalf.value = angle/2;
const cutSlider = document.getElementById('cut');
document.getElementById('cut-val').textContent = Math.round(THREE.MathUtils.radToDeg(angle)) + '°';
}
rebuildCutaway(cutAngle);
/* ============================================================
Historical orbit overlay (heuristic, off by default)
============================================================ */
const orbitGroup = new THREE.Group();
orbitGroup.visible = false;
scene.add(orbitGroup);
const orbitRings = [];
[
{ r:0.95, tilt:[-0.55, 0.25, 0.4], dur:7.0 },
{ r:1.55, tilt:[ 0.35, 1.15,-0.9], dur:11.0 },
{ r:2.15, tilt:[-1.05,-0.45, 0.9], dur:16.0 }
].forEach((o, idx) => {
const geo = new THREE.TorusGeometry(o.r, 0.008, 6, 160);
const ring = new THREE.Mesh(geo, new THREE.MeshBasicMaterial({ color:0xffb454, transparent:true, opacity:0.42 }));
ring.rotation.set(o.tilt[0], o.tilt[1], o.tilt[2]);
orbitGroup.add(ring);
const e = new THREE.Mesh(new THREE.SphereGeometry(0.045, 14, 12),
new THREE.MeshBasicMaterial({ color:0xffd79a }));
orbitGroup.add(e);
orbitRings.push({ ring, e, ...o });
});
/* ============================================================
Measurement markers (probability-weighted single detections)
============================================================ */
const markerTex = (() => {
const c = document.createElement('canvas'); c.width = c.height = 128;
const x = c.getContext('2d');
const g = x.createRadialGradient(64,64,0,64,64,64);
g.addColorStop(0, 'rgba(255,255,255,1)');
g.addColorStop(0.22, 'rgba(150,240,255,0.95)');
g.addColorStop(0.5, 'rgba(80,200,255,0.25)');
g.addColorStop(1, 'rgba(60,180,255,0)');
x.fillStyle = g; x.fillRect(0,0,128,128);
return new THREE.CanvasTexture(c);
})();
const markers = [];
const measureLog = document.getElementById('measure-log');
let measureCount = 0;
function addMeasurement(){
const pick = Math.random();
const orb = pick < 0.55 ? '1s' : (pick < 0.75 ? '2s' : '2px');
const p = samplePosition(orb);
const s = new THREE.Sprite(new THREE.SpriteMaterial({ map:markerTex, blending:THREE.AdditiveBlending, depthWrite:false, transparent:true }));
s.position.copy(p); s.scale.setScalar(0.30); s.renderOrder = 8;
scene.add(s);
markers.push({ s, t:0 });
measureCount++;
const r = p.length();
const rr = (r / A0).toFixed(2);
const lines = measureLog.textContent.split('\n').filter(Boolean);
lines.unshift(`#${measureCount} ${orb} r ≈ ${rr} a₀ (one outcome)`);
measureLog.textContent = lines.slice(0,4).join('\n');
}
/* ============================================================
UI wiring
============================================================ */
const ui = {
cut: document.getElementById('cut'),
cloud: document.getElementById('t-cloud'),
shell: document.getElementById('t-shell'),
orbit: document.getElementById('t-orbit'),
labels:document.getElementById('t-labels'),
spin: document.getElementById('t-spin')
};
ui.cut.addEventListener('input', () => {
rebuildCutaway(THREE.MathUtils.degToRad(+ui.cut.value));
});
ui.cloud.addEventListener('change', () => { cloud.visible = ui.cloud.checked; });
ui.shell.addEventListener('change', () => { isoGroup.visible = ui.shell.checked; });
ui.orbit.addEventListener('change', () => { orbitGroup.visible = ui.orbit.checked; });
ui.labels.addEventListener('change', () => { document.getElementById('labels').style.display = ui.labels.checked ? '' : 'none';
document.getElementById('leaders').style.display = ui.labels.checked ? '' : 'none'; });
document.getElementById('btn-reset').addEventListener('click', () => {
goal.az = 0.85; goal.pol = 1.16; goal.rad = 9.2; goalTarget.set(0,0,0);
});
document.getElementById('btn-clear').addEventListener('click', () => {
while (markers.length){ const m = markers.pop(); scene.remove(m.s); m.s.material.dispose(); }
measureCount = 0; measureLog.textContent = 'No measurements yet — click the density cloud.';
});
renderer.domElement.addEventListener('click', e => { addMeasurement(); });
/* ---------- labels + leader lines ---------- */
const labelDefs = [
{ id:'lab-nucleus', anchor:() => new THREE.Vector3(0.20, 0.40, 0.20), off:[92,-26], show:() => true },
{ id:'lab-density', anchor:() => new THREE.Vector3(-1.05, 1.15, 0.75), off:[-30,-72], show:() => cloud.visible },
{ id:'lab-shell', anchor:() => new THREE.Vector3(0, R*0.99, 0).add(new THREE.Vector3(0,0,-0.2)), off:[86,-46], show:() => true },
{ id:'lab-cut', anchor:() => {
const t = new THREE.Vector3(Math.sin(cutAngle/2), 0, Math.cos(cutAngle/2));
return cutGroup.localToWorld(t.clone().multiplyScalar(R*0.55).add(new THREE.Vector3(0,0.10,0)));
}, off:[64, 66], show:() => true },
{ id:'lab-orbit', anchor:() => new THREE.Vector3(1.6, 0.15, 0.9), off:[92, 44], show:() => orbitGroup.visible }
];
const leaderSvg = document.getElementById('leaders');
labelDefs.forEach(def => {
def.el = document.getElementById(def.id);
const line = document.createElementNS('http://www.w3.org/2000/svg','line');
leaderSvg.appendChild(line); def.line = line;
});
/* ============================================================
Historical orbit diagram in the comparison card (SVG + SMIL)
============================================================ */
(function buildHistoricalDiagram(){
const svg = document.getElementById('hist-orbits');
const cx = 320, cy = 200;
const orbs = [
{ rx:96, ry:36, tilt:-16, dur:7, col:'#ffb454', off:0 },
{ rx:158, ry:62, tilt:12, dur:11, col:'#ffc987', off:2 },
{ rx:222, ry:90, tilt:-7, dur:16, col:'#e0a05f', off:4 }
];
orbs.forEach((o, idx) => {
const a = o.tilt * Math.PI/180;
let d = '';
const N = 180;
for (let i = 0; i <= N; i++){
const t = i/N * Math.PI*2;
const x = o.rx*Math.cos(t), y = o.ry*Math.sin(t);
const X = cx + x*Math.cos(a) - y*Math.sin(a);
const Y = cy + x*Math.sin(a) + y*Math.cos(a);
d += (i===0 ? 'M' : 'L') + X.toFixed(2) + ',' + Y.toFixed(2) + ' ';
}
const path = document.createElementNS('http://www.w3.org/2000/svg','path');
path.setAttribute('d', d);
path.setAttribute('fill','none');
path.setAttribute('stroke', o.col);
path.setAttribute('stroke-width','1.4');
path.setAttribute('opacity','0.75');
svg.appendChild(path);
const dot = document.createElementNS('http://www.w3.org/2000/svg','circle');
dot.setAttribute('r','6'); dot.setAttribute('fill','#ffd79a');
dot.setAttribute('stroke','#6b4a1e'); dot.setAttribute('stroke-width','1');
const anim = document.createElementNS('http://www.w3.org/2000/svg','animateMotion');
anim.setAttribute('dur', o.dur + 's');
anim.setAttribute('repeatCount','indefinite');
anim.setAttribute('begin', (-o.off) + 's');
anim.setAttribute('path', d);
dot.appendChild(anim);
svg.appendChild(dot);
});
})();
/* ============================================================
Measurement dots in the modern panel
============================================================ */
(function panelDots(){
const g = document.getElementById('dens-dots');
const spots = [[262,168],[352,246],[398,150],[300,214]];
spots.forEach(([x,y], i) => {
const c = document.createElementNS('http://www.w3.org/2000/svg','circle');
c.setAttribute('cx', x); c.setAttribute('cy', y); c.setAttribute('r', i===3 ? 6 : 4.5);
c.setAttribute('fill', i===3 ? '#ffffff' : '#8fe3c0');
c.setAttribute('stroke', i===3 ? '#8fe3c0' : 'none');
c.setAttribute('stroke-width','1.5');
c.setAttribute('opacity', i===3 ? 1 : 0.75);
g.appendChild(c);
});
})();
/* ============================================================
Resize
============================================================ */
function resize(){
const w = host.clientWidth, h = host.clientHeight;
renderer.setSize(w, h, false);
camera.aspect = w/h;
camera.updateProjectionMatrix();
cloudUniforms.uScale.value = h / (2*Math.tan(THREE.MathUtils.degToRad(camera.fov)/2));
}
new ResizeObserver(resize).observe(host);
resize();
/* ============================================================
Animation loop
============================================================ */
const clock = new THREE.Clock();
const tmp = new THREE.Vector3();
let labelTick = 0;
function animate(){
const dt = Math.min(0.05, clock.getDelta());
const t = clock.elapsedTime;
if (ui.spin.checked) goal.az += dt * 0.12;
view.az = lerp(view.az, goal.az, 1 - Math.pow(0.001, dt));
view.pol = lerp(view.pol, goal.pol, 1 - Math.pow(0.001, dt));
view.rad = lerp(view.rad, goal.rad, 1 - Math.pow(0.001, dt));
target.lerp(goalTarget, 1 - Math.pow(0.002, dt));
applyCamera();
// keep the cutaway opening facing the viewer
const camDir = tmp.set(camera.position.x - target.x, 0, camera.position.z - target.z).normalize();
const desiredYaw = Math.atan2(camDir.z, -camDir.x);
let delta = desiredYaw - cutGroup.rotation.y;
while (delta > Math.PI) delta -= Math.PI*2;
while (delta < -Math.PI) delta += Math.PI*2;
cutGroup.rotation.y += delta * (1 - Math.pow(0.002, dt));
cloudUniforms.uWedge.value.copy(camDir);
// orbit overlay motion
if (orbitGroup.visible){
orbitRings.forEach((o, i) => {
const a = t * (Math.PI*2 / o.dur) * 0.7 + i*1.1;
const local = new THREE.Vector3(Math.cos(a)*o.r, Math.sin(a)*o.r, 0);
o.e.position.copy(local.applyEuler(new THREE.Euler(o.tilt[0], o.tilt[1], o.tilt[2])));
});
}
// marker pop animation
for (let i = markers.length - 1; i >= 0; i--){
const m = markers[i]; m.t += dt;
const k = Math.min(1, m.t/0.45);
m.s.scale.setScalar(0.10 + 0.34*k);
m.s.material.opacity = m.t > 3 ? Math.max(0, 1 - (m.t-3)/1.5) : 1;
if (m.t > 4.5){ scene.remove(m.s); m.s.material.dispose(); markers.splice(i,1); }
}
// labels (projected manually — no CSS2DRenderer needed)
labelTick += dt;
if (labelTick > 0.05){
labelTick = 0;
const w = host.clientWidth, h = host.clientHeight;
leaderSvg.setAttribute('viewBox', `0 0 ${w} ${h}`);
labelDefs.forEach(def => {
if (!def.show()){ def.el.style.opacity = 0; def.line.style.opacity = 0; return; }
const p = def.anchor().clone().project(camera);
const x = (p.x*0.5 + 0.5)*w, y = (-p.y*0.5 + 0.5)*h;
const lx = x + def.off[0], ly = y + def.off[1];
def.el.style.left = lx + 'px'; def.el.style.top = ly + 'px';
def.el.style.opacity = (p.z < 1) ? 1 : 0;
def.line.setAttribute('x1', x); def.line.setAttribute('y1', y);
def.line.setAttribute('x2', lx); def.line.setAttribute('y2', ly);
def.line.style.opacity = (p.z < 1) ? 1 : 0;
});
}
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
```