# Recreate this site as a single HTML file: Caldera — a continuous WebGL descent into a volcanic crater

## What it is
This is a one-page site for **Caldera Thermal**, a fictional geothermal power company. The whole page is one continuous three.js world, and scroll flies the camera through it in a single unbroken shot:
1. Dawn over a high snowfield.
2. Down a slope streaked with sulphur-stained fumaroles.
3. Over a caldera rim, where falling snow turns to ash and then to rising embers.
4. Down to a geothermal plant on a crater floor of cracked basalt plates with lava glowing in the seams.

Each section is a designed shot: a wide snowfield with the sun just behind the eastern ridge; steam vents and obsidian blades on the slope; the rim looking down into the crater; low over the cracked lava crust; a hero wide of the plant. Six content panels (what we do, how it works, sites, numbers, invest/careers, contact) are real HTML sections pinned to anchor points beside each shot. Titles decode from glyph noise as each panel arrives. A monospaced HUD reads depth (m), air temperature (°C) and pressure (kPa) live from the camera. **Signature:** click or tap anywhere to send a *seismic pulse*. The camera shakes, the lava cracks flare, a ring travels across the crater floor and through the steam plumes, the synthesised soundtrack thumps, and the HUD logs "SEISMIC EVENT 004 · M2.3 · 412 M AWAY".

## Page shell & libraries
- One `index.html` with inline CSS and JS. three.js **0.170.0** comes from jsDelivr through an import map:
  - `"three": "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js"`
  - `"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/"`
- Dynamically import `three`, `GLTFLoader`, `EffectComposer`, `RenderPass`, `UnrealBloomPass` and `ShaderPass`, so the fallback page never downloads three.js.
- Google Fonts: **Instrument Serif** (400, italic), **Hanken Grotesk** (400/500/600), **Geist Mono** (400/500).
- A tiny inline `<head>` script picks the path before first paint:
  - WebGL2 available and no `prefers-reduced-motion` → `html.gl.loading`;
  - otherwise (or with `?static`) → `html.still`.
- No other libraries. Smooth scroll is a damped value: `prog += (target - prog) * (1 - exp(-dt*3.2))`.

## Tokens
- **Palette:** ink `#0c0a09`, basalt `#161311`, bone (text) `#ede6dc`, ash (muted) `#a59d93`, ember `#ff6a1f`, ember-light `#ffb15c`, sulphur `#e6cf62`. Hairlines are `rgba(237,230,220,.16)`, strong lines `.32`.
- **Type:**
  - Display is Instrument Serif: hero `clamp(48px,7.6vw,128px)`, line-height .9, tracking −.025em; panel titles `clamp(32px,3vw,44px)`. Italic in ember-light is the accent ("*still warm.*").
  - Body is Hanken Grotesk at 15–16px / 1.55.
  - Every label, HUD value and button is Geist Mono in caps: 10–12px, tracking .08–.16em. HUD values are 26px, tabular numbers.
- **Shape:** radius 2px everywhere. Panels are square, with 12px ember-light corner brackets on the top-left and bottom-right. No glassmorphism: panels are `rgba(13,11,10,.82)` with only a 3px backdrop blur.
- **Spacing:** 16px side gutter, panel padding 26px (18px on phones), 44px minimum hit targets.

## Layout & structure
1. **Preloader** (full-screen ink):
   - "Caldera" in 168px serif with an italic ember "e", and a monospaced readiness log in which every line is a real step: three modules, 6/6 assets, terrain tri count, particle count + tier, `compileAsync` program count, 3 warm frames of the full post stack.
   - A gradient progress bar and a 3-digit percentage.
   - When ready, two buttons: **Descend with sound** / **Descend silently**. This is also the audio-unlocking gesture.
2. **Canvas:** fixed, full-viewport WebGL canvas behind everything, plus an animated SVG-noise grain overlay (7% opacity, overlay blend).
3. **HUD** (fixed, pointer-events only on controls; dark scrims at the top 110px and bottom 150px for legibility):
   - top-left: crater mark + "CALDERA" wordmark and `01 What … 06 Contact` nav, with the current stop marked by an ember square;
   - top-right: **Pulse** and **Sound** chips (four animated equaliser bars when sound is on) and an **Index** menu button below 1100px;
   - left: a vertical depth gauge (0 m snowfield → rim → −1,100 m floor) with a glowing ember marker;
   - centre: a thin reticle with the event line under it;
   - bottom-left: DEPTH, AIR TEMP and PRESSURE;
   - bottom-right: `03 / 06 — SITES`, a progress line, and coordinates with live heading.
4. **Hero** (fixed over the start of the scroll; it fades out by 6% progress and drifts up): kicker, the "We drill where the planet is *still warm.*" headline, a lede with real numbers (412 MW, 288 °C, three kilometres), a "Begin the descent ↓" button and "1,100 m to the crater floor". A 12° dark gradient scrim sits under the text.
5. **Panels** (each `<section>` has an `h2` that decodes):
   - 01 *Heat, piped up from three kilometres.*: three lettered rows (Exploration / Drilling / Operations).
   - 02 *One loop, never vented.*: a 4-step range slider (Well 288 °C → Separator 14 bar → Turbine 71 MW → Reinject 82 °C) with a live readout card.
   - 03 *Three fields, one rift.*: tabs Ostra / Halde / Sulphur Ward, each with a status dot, a 3-cell spec grid (output, wells, brine) and copy.
   - 04 *Measured, not promised.*: a 2×2 stat grid that counts up (412 MW, 288 °C, 11 g/kWh, 97.8 %).
   - 05 *Come down with us.*: Invest/Careers tabs. Invest has a "Request the data room" button. Careers lists three roles with Apply buttons, which prefill the contact form's topic and message, then fly to it.
   - 06 *Write to the control room.*: name, email, topic select, message and a submit button; the fictional-company footnote.
6. **Scroll track:** a 1050vh empty div that gives the descent its length. The stops sit at progress 0, .165, .33, .495, .66, .815 and .965.

## The world (three.js)
- **Terrain:**
  - One JS `height(x,z)`, built on seeded 2D gradient noise. It combines:
    - a snow plateau at 1,000 m falling to the rim, with broad swells (fbm .0011, ±60);
    - erosion gullies running straight down the slope: `(1-|noise(x*.0075+warp, z*.0019)|)^5 * 42`, plus a 3-octave ridged texture;
    - mountain ranges east, west and south, using a **domain-warped Musgrave ridged multifractal**: 7 octaves, lacunarity 2.07, gain 2.1, H .9, warp .6×fbm, base scale 1/900, amplitude ×1300. This gives sharp ridgelines and branching gullies, with no rounded lumps;
    - a Gaussian rim ridge (+95, σ110) at r = 540;
    - a bowl blending to a 20 m floor inside r = 280 (`pow(inside,.5)`), with ridged cliff bands on the inner wall (`(ridged-.45)*110*wall`);
    - a perfectly level pad under the plant, rotated with it, blending out over 90 units.
  - The mesh is a 4800×5000 plane with 220/320/400 segments by tier. The same function clamps the camera (≥16 above the surface) and ray-marches the pulse.
- **Sun and shadows:** a low dawn sun (direction `(0.3,0.066,0.95)`, 3.8° elevation). Before reveal, soft shadows are ray-marched once on the CPU across the height grid: from every vertex, step toward the sun (step `max(7, t*.035)`, up to 4.2 km) and keep the penumbra minimum `0.5 + d/(t*.035+3)`. The result is stored as an `aShadow` vertex attribute.
- **Terrain shader** (custom ShaderMaterial):
  - triplanar basalt (Poly Haven "dark_rock") at two scales, with a whiteout triplanar normal map; cool grey outside the caldera, warmer inside;
  - snow only above 470–560 m on gentle slopes: a crisp `smoothstep(.70,.76,n.y)` that relaxes to .48 at high altitude, so ridges stay wind-scoured rock with crisp snow lines;
  - snow normals, sun glints, and blue skylight in shadow;
  - a back-lit rim light on ridgelines: `pow(1-NV,4)*pow(dot(-V,sun),3)`;
  - sulphur stains (ochre) around 5 fumaroles, with snow melted there;
  - a warm lava bounce on the inner walls.
- **Lava crust:** on the crater floor, a domain-warped **cellular crust** (Voronoi with exact edge distance, 30-unit plates) plus a second cell network at ×3.1 that only appears within .2 of a main seam.
  - Seam width varies 0.018–0.075 with noise and an "activity" field.
  - Emission across a seam ramps: black crust → deep red (×2.5) → orange (×4.5) → white-yellow core (×9).
  - Cooling crust shows faint red mottling near the seams. 28% of plates are sunk (darker), and every plate's normal tilts slightly.
  - The seams flicker per cell. A pulse ring travels across them.
- **Sky:** low-sun physical-ish model: a warm horizon band around the sun's azimuth (`skyHor 1.05,.56,.30`), cool horizon elsewhere (`.46,.52,.66`), zenith `.075,.13,.28`, Mie-like glow `pow(mu,4)` and `pow(mu,50)`, and an HDR disc. PMREM of it lights the PBR plant.
- **Aerial perspective:** analytic exponential height fog in every shader. **Its colour is the horizon sky in the view direction**, so every ridge fades into the sky behind it: warm toward the sun, cool away. Density .00032 on the snowfield, .001 in the crater, where the colour turns to smoky ember `(.12,.075,.06)`.
- **Distant ranges:** three 360° silhouette rings (R 4300 / 5700 / 7300) whose crests come from ridged noise. They are shaded progressively paler and cooler with distance (`mix(body, haze, .42/.62/.80)`), with a sun-side rim light on the crests and faint snow caps away from the sun.
- **Obsidian:**
  - ~36 instanced blades (two Poly Haven CC0 rock meshes, scale .55 × 2.2–4 × .7) in 9 clusters, placed for the slope and floor shots.
  - The shader does screen-space refraction against a half-resolution opaque render, with separate IORs per channel (R 1.46, G 1.50, B 1.555) for dispersion.
  - Thickness-based smoky absorption, Fresnel sky reflection, a sun glint, and a thin-film rainbow sheen.
  - Inside the crater, a strong lava bounce on the edges: `(max(-R.y,0)*3+.4)*(.7+lava)`.
- **Steam:** 360k / 220k / 120k GPU points across 10 vents: 5 slope fumaroles, 3 crater plumes, and the plant's 2 cooling stacks at their real tops.
  - Vertex-shader life cycle, cone spread, billow, wind, and the pulse ripple.
  - Bokeh DOF sizing, and forward-scatter toward the sun.
  - Inside the crater, the sun term is cut by 85% and the plumes are **uplit by the lava from below** (`(1-smoothstep(20,300,y))*.9`). Crater alpha drops to .04 so the floor reads through them.
- **Snow → ash:** 42k / 28k / 14k camera-wrapped points that turn from snow to ash to rising embers.
- **Plant:**
  - The image-to-3D GLB (quantised, 1024 JPEG) is scaled ×104, so the hall is about 160 m long and the stacks 75 m.
  - Its plinth is **sunk 2 units under the levelled pad**, so no slab edge shows; the floor shader turns the pad into dark gravel, with contact darkening that hugs the hall footprint (`mix(.25,1,smoothstep(0,26,hallE))`).
  - The amber window band glows.
  - Four matte-clad pipelines on low instanced supports run in expansion loops from wellheads (with blinking beacons) and dive into the ground at both ends.
  - Three warm point lights high over the floor uplight it.

## Behaviour & interaction
- **Camera:**
  - Seven designed shots, one per stop (position + look target), on two centripetal Catmull-Rom curves:
    - snowfield `(-380,1190,-2600)→(330,1010,-1430)`;
    - slope `(-10,1045,-1700)→(-230,880,-1180)`;
    - lower slope `(150,870,-1240)→(-60,600,-700)`;
    - rim `(30,775,-640)→(0,20,60)`;
    - inner wall `(250,340,-300)→(-70,20,110)`;
    - floor `(-235,72,-150)→(-140,14,-20)`;
    - plant `(-235,52,-45)→(70,76,110)`.
  - Progress maps to the curve parameter per segment, with 75% smoothstep easing, so the camera settles on every shot.
  - ±0.8 breathing bob, and pointer parallax (yaw .035, pitch .025 rad, eased .04).
  - Panels anchor 92 units ahead of the camera pose at their stop, offset ±34 to the side.
- **Panels:**
  - Each frame, project the anchor to the screen and place the panel beside the point.
  - Scale `clamp(95/dist,.72,1.12)`, clamped inside the viewport using the scaled size.
  - Opacity is `1 - smoothstep(.035,.075,|progress - stop|)`. The last panel holds after its stop.
  - A panel is interactive above 0.6 opacity. On arrival its h2 scrambles: glyphs `▚▞▙▟░▒/\<>_#+=0-9`, each character resolving at `i/n*0.65*dur + rand*0.35*dur`, dur 950 ms. Its stats count up over 1.3 s with ease-out-quart.
- **Seismic pulse** (canvas click, the Pulse chip, or the P key):
  - March the view ray against `height()` to find the epicentre.
  - Then:
    - camera shake `shake²*3.2`, decaying `exp(-2.6t)`;
    - lava ×(1 + 1.6·M/2·exp(−1.4t));
    - a floor/steam ring at 230 units/s, σ48–55, decaying `exp(-0.9..1.1t)`;
    - a warm flash in the grade `exp(-6t)`;
    - snowflakes jitter;
    - a 78→26 Hz sine thump plus a low-passed noise burst;
    - a HUD event line for 2.6 s.
- **HUD values:** updated at 15 Hz.
  - Depth = camera drop scaled to 1,100 m.
  - Temperature: −14 °C at the top, rising to about +62 °C at the floor, plus a pulse spike.
  - Pressure = `101.325*exp(-elev/8434)`, with elevation 2,380 m minus depth.
  - Heading comes from the camera's forward vector.
- **Sound** (WebAudio, no files):
  - wind: white noise → band-pass at 520 Hz, Q .7, with a 0.07 Hz LFO of ±260 Hz, plus a 1650 Hz Q9 whistle;
  - rumble: brown noise → low-pass 110 Hz, plus 36 and 53.5 Hz sines with a 0.21 Hz tremolo;
  - a depth crossfade, a compressor, master gain .75;
  - unlocked by the preloader button or the first pointer/key gesture; the mute choice is stored in localStorage (try/catch); suspended while the tab is hidden.
- **Post:**
  - RenderPass → UnrealBloom (strength .55, radius .6, threshold 1.7, so only lava, sun and embers bloom) → one grade pass, all in HalfFloat linear with a depth texture.
  - The grade pass does, in order:
    - heat haze: the UV shimmers by `(below.r - 1.4·below.b)` sampled 3% lower;
    - DOF: a 16-tap golden-angle gather, with CoC = `|depth - focus|/depth * aperture` (.26 desktop, .18 phone); focus eases to the active panel's distance (1400 at the top);
    - CA .0016;
    - ACES fitted;
    - a split-tone (cool shadows on the snow → warm in the crater);
    - sRGB, vignette, animated grain .045.
- **Performance:**
  - Before reveal, `renderer.compileAsync` plus three warm frames.
  - An adaptive pixel ratio drops by 0.2 (to a floor of .65) after 1.5 s above 26 ms per frame.
  - Pause on `visibilitychange`.
  - Tiers come from pointer, viewport and `hardwareConcurrency`.

## Responsive
- **1440:** full nav, the depth gauge on the left (the hero is padded 104px to clear it), and panels beside their projected anchors.
- **768–1100:** the nav collapses into an **Index** menu button (aria-expanded, Esc closes) and the gauge hides.
- **390:**
  - the readouts move under the top bar at 18px; the bottom-right block hides;
  - panels are full width minus 32px, bottom-anchored with only slight projected parallax, `max-height: 100svh - 170px` with internal scroll;
  - the camera fov goes from 50 to 64 in portrait, the form rows stack, and the low particle tier is used.
- No horizontal scroll at any width.

## Accessibility & reduced motion
- A skip link, semantic sections with `aria-labelledby`, and h2s with `tabindex=-1`.
- Scramble text keeps the real title in a visually hidden span; the animated copy is `aria-hidden`.
- Tabs follow the ARIA pattern (roving tabindex, arrow / Home / End). The range has `aria-valuetext`.
- Form errors are linked by `aria-describedby` with `aria-invalid`, and the first invalid field gets focus. The success message is in a `role=status` region.
- Tabbing into any panel flies the camera to that stop. The Pulse key is ignored while typing.
- Visible 2px ember focus rings. Muted text is #a59d93 on ink (6.9:1).
- `prefers-reduced-motion` → the still-frame page (below); the CSS also kills all transitions and animations.

## Fallbacks
- No WebGL2, reduced motion, `?static`, an init error or a lost context all lead to `html.still`:
  - a sticky slim header with the wordmark and sound toggle;
  - the hero over `assets/still-1.webp`;
  - each panel in normal flow over a full-bleed still from the same scene (still-1…4) with a side gradient.
- All UI still works, and the sound still crossfades by section. Nothing is lost except the flight.

## Assets
- `assets/basalt-albedo.webp`, `assets/basalt-normal.webp`: Poly Haven "dark_rock" 1k (CC0), the triplanar rock.
- `assets/snow-normal.webp`: Poly Haven "snow_02" normal (CC0).
- `assets/shard-a.glb`, `assets/shard-b.glb`: Poly Haven "moon_rock_03/05" geometry only (CC0), instanced as obsidian blades.
- `assets/plant.glb` (1.5 MB): a geothermal station scale model (dark corrugated turbine hall with an amber window band, two concrete cooling stacks, looping silver pipelines, a separator tank, a basalt plinth), made by image-to-3D from a generated studio product shot. Quantised positions/normals/UVs, 1024 JPEG textures.
- `assets/still-1.webp` … `still-4.webp`: frames rendered from the live scene (snowfield, lower slope, crater floor, plant hero) for the still-frame page.

## Make it yours
This prompt rebuilds one exact site. If everyone ships it unchanged, the sites will look alike. Before you paste it, change these lines so the result is yours. Each change is one edit to the prompt; the structure and the interactions stay intact.

1. **Brand and offer.** Swap Caldera Thermal for your own company (a mine, a winery in a quarry, a data centre in a glacier, a deep-sea cable firm). Keep six panels, one number-heavy panel with four stats, and one form, so the stops along the 1050vh track stay evenly spaced.
2. **The descent.** Re-theme the journey and keep the one continuous camera path: down a kelp forest to a trench vent, down a mine shaft to a crystal cavern, through cloud to a desert canyon floor. Change `height()` (plateau, rim, bowl), the snow line and the crack emission ramp to suit, and keep the five-act structure (open, slope, threshold, interior, destination).
3. **The pulse.** Keep "click sends something through the world" but make it native to your story: a sonar ping that lights bioluminescence, a blast charge that shakes dust loose, a lightning strike that flashes the clouds. Reuse the same ring, shake, flare and thump parameters.
4. **Palette.** Replace the ink, bone, ember and sulphur tokens, the sky horizon and zenith, and the two fog colours. Keep bone text at ≥ 4.5:1 on ink, and keep one hot accent for emission so the bloom threshold still isolates it.
5. **Type pairing.** Swap Instrument Serif + Hanken Grotesk for another display serif or grotesk with a plain body face, and keep a true monospace for the HUD (JetBrains Mono, IBM Plex Mono, Space Mono).
6. **Assets.** Replace the plant GLB with your own hero object (studio product shot → image-to-3D, then quantise and use 1024 textures, ≤ 1.5 MB). Pick different CC0 rock or ground scans for the terrain and glass blades. Re-render the four stills from your own scene.
7. **HUD readings.** Choose three live values that mean something in your world (depth, salinity and lux for the ocean; altitude, wind and visibility for a summit) and drive them from the camera, as depth, temperature and pressure are driven here.
8. **Copy.** Rewrite every headline in your own voice with real specifics ("brine at 288 °C", not "unlock clean energy").

Tell your AI: *"Build exactly as specified, but with these changes: …"*, then list your edits.

---

## Reference implementation (use verbatim)

The complete working `index.html`. Every number in the spec above is in this file; if the two ever seem to differ, the code wins. Images and models referenced as `assets/...` can be downloaded from https://copytheprompt.design/demos/volcano-crater-scroll-descent-webgl/assets/ or replaced with your own (see Make it yours).

````html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Caldera Thermal — geothermal power from inside the crater</title>
<meta name="description" content="Caldera Thermal builds and runs geothermal plants inside active volcanic systems. Scroll to descend from the snowfield to the crater floor.">
<meta name="theme-color" content="#0c0a09">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Geist+Mono:wght@400;500&family=Hanken+Grotesk:wght@400;500;600&family=Instrument+Serif:ital@0;1&display=swap" rel="stylesheet">
<script>
/* Decide the rendering path before first paint: live WebGL descent, or the still-frame page. */
(function () {
  var d = document.documentElement, ok = false;
  try { var c = document.createElement('canvas'); ok = !!(c.getContext('webgl2')); } catch (e) {}
  var rm = window.matchMedia && matchMedia('(prefers-reduced-motion: reduce)').matches;
  if (ok && !rm && !/[?&]static\b/.test(location.search)) d.classList.add('gl', 'loading');
  else d.classList.add('still');
})();
</script>
<style>
:root{
  --ink:#0c0a09; --basalt:#161311; --basalt-2:#1f1a17; --line:rgba(237,230,220,.16); --line-2:rgba(237,230,220,.32);
  --bone:#ede6dc; --ash:#a59d93; --ash-2:#8a837a; --ember:#ff6a1f; --ember-2:#ffb15c; --sulphur:#e6cf62; --snow:#f2f4f6;
  --mono:"Geist Mono", ui-monospace, "SFMono-Regular", Menlo, monospace;
  --sans:"Hanken Grotesk", system-ui, sans-serif;
  --serif:"Instrument Serif", "Times New Roman", serif;
  --r:2px; --gut:16px;
}
*{box-sizing:border-box}
html{background:var(--ink);color:var(--bone);-webkit-text-size-adjust:100%}
body{margin:0;font-family:var(--sans);font-size:16px;line-height:1.55;background:var(--ink);overflow-x:hidden}
a{color:inherit}
button,input,select,textarea{font:inherit;color:inherit}
:focus-visible{outline:2px solid var(--ember-2);outline-offset:3px}
.sr{position:absolute!important;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}
.skip{position:fixed;left:12px;top:-60px;z-index:100;background:var(--bone);color:var(--ink);padding:10px 14px;font:500 13px var(--mono);text-decoration:none}
.skip:focus{top:12px}
.mono{font-family:var(--mono);font-size:11px;letter-spacing:.08em;text-transform:uppercase}

/* ---------- canvas + grain ---------- */
#gl{position:fixed;inset:0;width:100%;height:100%;display:block;z-index:0;touch-action:pan-y}
html.still #gl{display:none}
.grain{position:fixed;inset:-50%;z-index:3;pointer-events:none;opacity:.07;mix-blend-mode:overlay;
  background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.9' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");}
html.gl .grain{animation:grain 1.2s steps(6) infinite}
@keyframes grain{0%{transform:translate(0,0)}20%{transform:translate(-3%,2%)}40%{transform:translate(2%,-4%)}60%{transform:translate(-4%,-1%)}80%{transform:translate(3%,3%)}100%{transform:translate(0,0)}}

/* ---------- preloader ---------- */
#loader{display:none}
html.gl #loader{display:flex}
#loader{position:fixed;inset:0;z-index:50;background:var(--ink);flex-direction:column;justify-content:space-between;padding:max(24px,env(safe-area-inset-top)) 24px 28px;transition:opacity .9s cubic-bezier(.6,0,.2,1),visibility .9s}
#loader.out{opacity:0;visibility:hidden}
.ld-top{display:flex;justify-content:space-between;gap:16px;color:var(--ash)}
.ld-mid{max-width:760px}
.ld-mark{font-family:var(--serif);font-size:clamp(56px,11vw,168px);line-height:.86;letter-spacing:-.02em;margin:0 0 22px;color:var(--bone)}
.ld-mark i{color:var(--ember-2)}
.ld-log{list-style:none;margin:0;padding:0;font:400 12px/1.9 var(--mono);color:var(--ash);min-height:11.5em}
.ld-log li{display:flex;gap:12px;white-space:nowrap;overflow:hidden}
.ld-log li b{font-weight:400;color:var(--bone);min-width:2.4em}
.ld-log li span:last-child{margin-left:auto;color:var(--sulphur)}
.ld-log li.wait span:last-child{color:var(--ash-2)}
.ld-bot{display:grid;gap:18px}
.ld-bar{height:2px;background:var(--line);position:relative;overflow:hidden}
.ld-bar i{position:absolute;inset:0;transform-origin:0 50%;transform:scaleX(0);background:linear-gradient(90deg,var(--ember),var(--ember-2));transition:transform .35s ease-out}
.ld-row{display:flex;justify-content:space-between;align-items:flex-end;gap:16px;flex-wrap:wrap}
.ld-pct{font:400 clamp(40px,6vw,72px)/1 var(--mono);letter-spacing:-.04em}
.ld-go{display:flex;gap:10px;flex-wrap:wrap;opacity:0;pointer-events:none;transform:translateY(8px);transition:opacity .5s,transform .5s}
#loader.ready .ld-go{opacity:1;pointer-events:auto;transform:none}
.btn{appearance:none;border:1px solid var(--line-2);background:transparent;color:var(--bone);padding:13px 18px;font:500 12px var(--mono);letter-spacing:.1em;text-transform:uppercase;border-radius:var(--r);cursor:pointer;display:inline-flex;align-items:center;gap:10px;text-decoration:none;min-height:44px}
.btn:hover{border-color:var(--bone)}
.btn.hot{background:var(--ember);border-color:var(--ember);color:#160801}
.btn.hot:hover{background:var(--ember-2);border-color:var(--ember-2)}

/* ---------- HUD ---------- */
.hud{display:none}
html.gl .hud{display:block}
.hud::before,.hud::after{content:"";position:absolute;left:0;right:0;pointer-events:none;z-index:-1}
.hud::before{top:0;height:110px;background:linear-gradient(rgba(12,10,9,.5),rgba(12,10,9,0))}
.hud::after{bottom:0;height:150px;background:linear-gradient(rgba(12,10,9,0),rgba(12,10,9,.6))}
.hud{position:fixed;inset:0;z-index:20;pointer-events:none;color:var(--bone);text-shadow:0 1px 10px rgba(0,0,0,.55)}
.hud a,.hud button{pointer-events:auto}
.hud-top{position:absolute;left:var(--gut);right:var(--gut);top:max(14px,env(safe-area-inset-top));display:flex;align-items:center;gap:20px}
.brand{display:flex;align-items:center;gap:10px;text-decoration:none;font:500 13px var(--mono);letter-spacing:.24em}
.brand svg{width:22px;height:22px}
.nav{display:flex;gap:2px;margin-left:18px}
.nav a{font:400 11px var(--mono);letter-spacing:.08em;text-transform:uppercase;text-decoration:none;color:var(--ash);padding:8px 9px;border-radius:var(--r)}
.nav a:hover,.nav a[aria-current="true"]{color:var(--bone)}
.nav a[aria-current="true"]::before{content:"";display:inline-block;width:5px;height:5px;margin-right:7px;background:var(--ember);vertical-align:2px}
.hud-actions{margin-left:auto;display:flex;gap:8px}
.chip{appearance:none;background:rgba(12,10,9,.42);border:1px solid var(--line-2);color:var(--bone);font:500 11px var(--mono);letter-spacing:.1em;text-transform:uppercase;padding:0 12px;height:36px;border-radius:var(--r);display:inline-flex;align-items:center;gap:9px;cursor:pointer}
.chip:hover{border-color:var(--bone)}
.bars{display:inline-flex;gap:2px;align-items:flex-end;height:12px}
.bars i{width:2px;background:currentColor;height:3px;transition:height .2s}
.chip[aria-pressed="true"] .bars i{animation:eq 1s ease-in-out infinite}
.chip[aria-pressed="true"] .bars i:nth-child(2){animation-delay:-.3s}.chip[aria-pressed="true"] .bars i:nth-child(3){animation-delay:-.6s}.chip[aria-pressed="true"] .bars i:nth-child(4){animation-delay:-.15s}
@keyframes eq{0%,100%{height:3px}50%{height:12px}}
.menu-btn{display:none}
.hud-read{position:absolute;left:var(--gut);bottom:max(18px,env(safe-area-inset-bottom));display:flex;gap:28px}
.read{display:grid;gap:2px}
.read .k{font:400 10px var(--mono);letter-spacing:.14em;color:var(--ash)}
.read .v{font:400 26px/1 var(--mono);letter-spacing:-.03em;font-variant-numeric:tabular-nums}
.read .v small{font-size:12px;color:var(--ash);margin-left:3px;letter-spacing:0}
.read.hot .v{color:var(--ember-2)}
.hud-br{position:absolute;right:var(--gut);bottom:max(18px,env(safe-area-inset-bottom));text-align:right;display:grid;gap:6px;justify-items:end}
.hud-br .sec{font:400 11px var(--mono);letter-spacing:.12em;color:var(--bone)}
.hud-br .coord{font:400 10px var(--mono);letter-spacing:.1em;color:var(--ash)}
.prog{width:180px;height:2px;background:var(--line);position:relative}
.prog i{position:absolute;inset:0;transform-origin:0 50%;transform:scaleX(0);background:var(--bone)}
.gauge{position:absolute;left:var(--gut);top:50%;transform:translateY(-50%);height:46vh;width:60px}
.gauge .rail{position:absolute;left:0;top:0;bottom:0;width:9px;background:repeating-linear-gradient(to bottom,var(--line-2) 0 1px,transparent 1px 10%) ,repeating-linear-gradient(to bottom,var(--line) 0 1px,transparent 1px 2%);background-size:9px 100%,5px 100%;background-repeat:no-repeat}
.gauge .lab{position:absolute;left:16px;white-space:nowrap;font:400 9px var(--mono);letter-spacing:.14em;color:var(--ash);transform:translateY(-50%)}
.gauge .mk{position:absolute;left:-3px;top:0;width:15px;height:2px;background:var(--ember);box-shadow:0 0 12px var(--ember)}
.reticle{position:absolute;left:50%;top:50%;width:28px;height:28px;margin:-14px 0 0 -14px;opacity:.5}
.reticle::before,.reticle::after{content:"";position:absolute;background:var(--bone)}
.reticle::before{left:13px;top:0;width:1px;height:28px}.reticle::after{top:13px;left:0;height:1px;width:28px}
.event{position:absolute;left:50%;top:calc(50% + 30px);transform:translateX(-50%);font:500 11px var(--mono);letter-spacing:.14em;color:var(--ember-2);opacity:0;transition:opacity .4s;white-space:nowrap}
.event.on{opacity:1}
.hint{position:absolute;left:50%;bottom:max(22px,env(safe-area-inset-bottom));transform:translateX(-50%);font:400 10px var(--mono);letter-spacing:.16em;color:var(--ash);text-align:center;transition:opacity .6s}

/* ---------- hero ---------- */
.hero::before{content:"";position:absolute;inset:0;z-index:-1;pointer-events:none;background:linear-gradient(12deg,rgba(12,10,9,.78) 0%,rgba(12,10,9,.45) 34%,rgba(12,10,9,0) 62%)}
.hero{position:relative;z-index:10;isolation:isolate;min-height:100vh;min-height:100svh;display:flex;flex-direction:column;justify-content:flex-end;padding:120px var(--gut) 132px}
html.gl .hero{position:fixed;inset:0;pointer-events:none}
html.gl .hero a{pointer-events:auto}
.hero .kick{color:var(--bone);opacity:.82;margin:0 0 18px;display:flex;gap:14px;flex-wrap:wrap}
.hero .kick span+span::before{content:"/";margin-right:14px;color:var(--ember-2)}
.hero h1{font-family:var(--serif);font-weight:400;font-size:clamp(48px,7.6vw,128px);line-height:.9;letter-spacing:-.025em;margin:0;max-width:11.5em}
.hero h1 em{color:var(--ember-2);font-style:italic}
.hero p.lede{max-width:34em;font-size:clamp(16px,1.25vw,19px);margin:26px 0 0;color:#e2dbd1}
.hero .cue{margin-top:28px;display:flex;gap:12px;align-items:center;flex-wrap:wrap}

/* ---------- panels ---------- */
#track{display:none}
html.gl #track{display:block;height:1050vh}
.panels{position:relative;z-index:10}
.panel{position:relative;width:min(440px,100%);background:rgba(13,11,10,.82);border:1px solid var(--line);padding:26px 26px 24px;color:var(--bone)}
.panel::before,.panel::after{content:"";position:absolute;width:12px;height:12px;border:1px solid var(--ember-2);pointer-events:none}
.panel::before{left:-1px;top:-1px;border-right:0;border-bottom:0}
.panel::after{right:-1px;bottom:-1px;border-left:0;border-top:0}
html.gl .panel{position:fixed;left:0;top:0;opacity:0;pointer-events:none;will-change:transform,opacity;backdrop-filter:blur(3px);-webkit-backdrop-filter:blur(3px);max-height:calc(100svh - 150px);overflow:auto;scrollbar-width:thin}
html.gl .panel.live{pointer-events:auto}
.p-head{display:flex;justify-content:space-between;gap:12px;color:var(--ash);margin-bottom:16px}
.p-head b{color:var(--ember-2);font-weight:500}
.panel h2{font-family:var(--serif);font-weight:400;font-size:clamp(32px,3vw,44px);line-height:1;letter-spacing:-.015em;margin:0 0 14px;outline:none}
.panel h2 [aria-hidden]{white-space:pre-wrap}
.panel p{margin:0 0 14px;color:#ddd5cb;font-size:15px}
.list{list-style:none;margin:0;padding:0;border-top:1px solid var(--line)}
.list li{display:grid;grid-template-columns:28px 1fr;gap:10px;padding:12px 0;border-bottom:1px solid var(--line);font-size:14.5px;color:#ddd5cb}
.list li b{display:block;color:var(--bone);font-weight:600;font-size:15px}
.list li .n{font:400 11px var(--mono);color:var(--ember-2);padding-top:3px}
/* stage slider */
.stage{margin-top:6px}
.stage label{display:flex;justify-content:space-between;color:var(--ash)}
.stage input[type=range]{width:100%;margin:12px 0 6px;accent-color:var(--ember);height:28px}
.stage-ticks{display:grid;grid-template-columns:repeat(4,1fr);font:400 10px var(--mono);letter-spacing:.06em;color:var(--ash);text-transform:uppercase}
.stage-ticks span:nth-child(2){text-align:center;transform:translateX(-12%)}.stage-ticks span:nth-child(3){text-align:center;transform:translateX(12%)}.stage-ticks span:last-child{text-align:right}
.stage-out{margin-top:14px;padding:14px;border:1px solid var(--line);display:grid;grid-template-columns:1fr auto;gap:6px 14px;align-items:baseline}
.stage-out h3{margin:0;font:600 16px var(--sans)}
.stage-out .fig{font:400 22px/1 var(--mono);color:var(--ember-2);text-align:right;font-variant-numeric:tabular-nums}
.stage-out p{grid-column:1/-1;margin:0;font-size:14px}
/* tabs */
.tabs{display:flex;border:1px solid var(--line);margin-bottom:14px}
.tabs button{flex:1;appearance:none;background:transparent;border:0;border-right:1px solid var(--line);padding:10px 8px;font:500 11px var(--mono);letter-spacing:.06em;text-transform:uppercase;color:var(--ash);cursor:pointer;min-height:44px}
.tabs button:last-child{border-right:0}
.tabs button[aria-selected="true"]{background:var(--bone);color:var(--ink)}
.tabs button:hover:not([aria-selected="true"]){color:var(--bone)}
.site-meta{display:grid;grid-template-columns:repeat(3,1fr);gap:1px;background:var(--line);border:1px solid var(--line);margin:4px 0 14px}
.site-meta div{background:var(--basalt);padding:10px}
.site-meta dt{font:400 10px var(--mono);letter-spacing:.1em;color:var(--ash);text-transform:uppercase}
.site-meta dd{margin:2px 0 0;font:400 18px var(--mono);font-variant-numeric:tabular-nums}
.status{display:inline-flex;align-items:center;gap:8px;font:500 10.5px var(--mono);letter-spacing:.1em;text-transform:uppercase;color:var(--sulphur)}
.status::before{content:"";width:7px;height:7px;border-radius:50%;background:currentColor;box-shadow:0 0 10px currentColor}
.status.build{color:var(--ember-2)}
/* numbers */
.stats{display:grid;grid-template-columns:1fr 1fr;gap:1px;background:var(--line);border:1px solid var(--line)}
.stat{background:var(--basalt);padding:16px 14px 14px}
.stat .big{font:400 clamp(34px,3.2vw,44px)/1 var(--mono);letter-spacing:-.05em;font-variant-numeric:tabular-nums}
.stat .big small{font-size:14px;letter-spacing:0;color:var(--ash);margin-left:4px}
.stat p{font-size:13px;margin:8px 0 0;color:var(--ash)}
/* roles */
.roles{list-style:none;padding:0;margin:0;border-top:1px solid var(--line)}
.roles li{display:flex;justify-content:space-between;align-items:center;gap:12px;padding:12px 0;border-bottom:1px solid var(--line)}
.roles b{font-weight:600}
.roles span{display:block;font:400 11px var(--mono);color:var(--ash);letter-spacing:.04em}
.link-btn{appearance:none;background:none;border:0;border-bottom:1px solid var(--ember-2);color:var(--ember-2);font:500 11px var(--mono);letter-spacing:.1em;text-transform:uppercase;padding:6px 0;cursor:pointer;min-height:32px}
/* form */
form{display:grid;gap:12px}
.f{display:grid;gap:5px}
.f label{font:400 10.5px var(--mono);letter-spacing:.1em;text-transform:uppercase;color:var(--ash)}
.f input,.f select,.f textarea{background:rgba(237,230,220,.04);border:1px solid var(--line-2);border-radius:var(--r);padding:11px 12px;font-size:15px;min-height:44px;color:var(--bone)}
.f select option{background:var(--basalt)}
.f textarea{min-height:84px;resize:vertical}
.f input:focus,.f select:focus,.f textarea:focus{outline:none;border-color:var(--ember-2);box-shadow:0 0 0 1px var(--ember-2)}
.f [aria-invalid="true"]{border-color:#ff8a6a}
.err{font-size:12.5px;color:#ffab92;min-height:0}
.row2{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.form-ok{border:1px solid var(--sulphur);color:var(--sulphur);padding:12px;font-size:14px}
.foot{margin-top:18px;padding-top:14px;border-top:1px solid var(--line);font:400 10.5px/1.7 var(--mono);color:var(--ash);letter-spacing:.04em}

/* ---------- still-frame page (no WebGL / reduced motion) ---------- */
html.still .hero{background:linear-gradient(180deg,rgba(12,10,9,.2),rgba(12,10,9,.85)),url(assets/still-1.webp) center/cover}
html.still .panels{display:grid;gap:0}
html.still .stop{min-height:92vh;display:flex;align-items:center;padding:64px var(--gut);background-size:cover;background-position:center}
html.still .stop:nth-child(odd){justify-content:flex-end}
html.still .stop[data-still="1"]{background-image:linear-gradient(90deg,rgba(12,10,9,.75),rgba(12,10,9,.2)),url(assets/still-1.webp)}
html.still .stop[data-still="2"]{background-image:linear-gradient(90deg,rgba(12,10,9,.2),rgba(12,10,9,.75)),url(assets/still-2.webp)}
html.still .stop[data-still="3"]{background-image:linear-gradient(90deg,rgba(12,10,9,.75),rgba(12,10,9,.25)),url(assets/still-3.webp)}
html.still .stop[data-still="4"]{background-image:linear-gradient(90deg,rgba(12,10,9,.25),rgba(12,10,9,.75)),url(assets/still-4.webp)}
.still-bar{display:none}
html.still .still-bar{display:flex;position:sticky;top:0;z-index:30;align-items:center;gap:12px;padding:10px var(--gut);background:rgba(12,10,9,.9);border-bottom:1px solid var(--line)}
html.still .still-bar .brand{margin-right:auto}
html.gl .stop{display:contents}

/* ---------- responsive ---------- */
@media (min-width:1101px){ html.gl .hero{padding-left:104px} }
@media (max-width:1100px){ .nav{display:none} .menu-btn{display:inline-flex} .gauge{display:none} }
@media (max-width:720px){
  .hud-read{gap:16px;bottom:auto;top:calc(max(14px,env(safe-area-inset-top)) + 48px)}
  .read .v{font-size:18px}
  .hud-br{display:none}
  .reticle{display:none} .event{top:38%}
  .hero{padding-bottom:110px}
  .hero h1{font-size:clamp(44px,12.5vw,64px)}
  .hero p.lede{font-size:15.5px}
  .panel{padding:20px 18px 18px}
  html.gl .panel{width:calc(100vw - 2 * var(--gut));max-height:calc(100svh - 170px)}
  .chip .t{display:none}
  .row2{grid-template-columns:1fr}
  html.still .stop{padding:48px var(--gut);min-height:auto}
}
.menu{display:none;position:absolute;right:var(--gut);top:calc(max(14px,env(safe-area-inset-top)) + 46px);background:rgba(13,11,10,.94);border:1px solid var(--line-2);padding:6px;pointer-events:auto;min-width:200px}
.menu.open{display:grid}
.menu a{padding:12px 12px;text-decoration:none;font:400 12px var(--mono);letter-spacing:.08em;text-transform:uppercase}
.menu a:hover{background:rgba(237,230,220,.06)}
@media (prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important;scroll-behavior:auto!important}}
</style>
</head>
<body>
<a class="skip" href="#what" data-go="1">Skip to content</a>
<canvas id="gl" aria-hidden="true"></canvas>
<div class="grain" aria-hidden="true"></div>

<!-- preloader: reports real readiness steps -->
<div id="loader" role="dialog" aria-modal="true" aria-labelledby="ld-title">
  <div class="ld-top mono"><span>Caldera Thermal</span><span>Descent rig · build 26</span></div>
  <div class="ld-mid">
    <p class="ld-mark" id="ld-title">Cald<i>e</i>ra</p>
    <ul class="ld-log" id="ld-log" aria-live="polite"></ul>
  </div>
  <div class="ld-bot">
    <div class="ld-bar"><i id="ld-bar"></i></div>
    <div class="ld-row">
      <div class="ld-pct" id="ld-pct" aria-hidden="true">000</div>
      <div class="ld-go">
        <button class="btn hot" id="go-sound" type="button">Descend with sound</button>
        <button class="btn" id="go-quiet" type="button">Descend silently</button>
      </div>
    </div>
  </div>
</div>

<!-- still-frame header (no WebGL / reduced motion) -->
<header class="still-bar">
  <a class="brand" href="#top"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" aria-hidden="true"><path d="M1 19 L8 7 L10.5 10 L13.5 10 L16 7 L23 19"/><path d="M10.5 10 Q12 14 13.5 10" stroke="#ff6a1f"/></svg>CALDERA</a>
  <button class="chip" type="button" data-sound aria-pressed="false"><span class="bars" aria-hidden="true"><i></i><i></i><i></i><i></i></span><span class="t">Sound</span><span class="sr">Ambient sound</span></button>
</header>

<!-- HUD -->
<div class="hud" id="hud">
  <div class="hud-top">
    <a class="brand" href="#top" data-go="0" aria-label="Caldera Thermal — back to the snowfield"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" aria-hidden="true"><path d="M1 19 L8 7 L10.5 10 L13.5 10 L16 7 L23 19"/><path d="M10.5 10 Q12 14 13.5 10" stroke="#ff6a1f"/></svg>CALDERA</a>
    <nav class="nav" aria-label="Sections">
      <a href="#what" data-go="1">01 What</a><a href="#how" data-go="2">02 How</a><a href="#sites" data-go="3">03 Sites</a><a href="#numbers" data-go="4">04 Numbers</a><a href="#invest" data-go="5">05 Invest</a><a href="#contact" data-go="6">06 Contact</a>
    </nav>
    <div class="hud-actions">
      <button class="chip" type="button" id="pulse-btn" title="Send a seismic pulse (P)"><svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.3" aria-hidden="true"><path d="M0 7h3l1.5-4 2.5 8 2-6 1.2 2H14"/></svg><span class="t">Pulse</span><span class="sr">Send a seismic pulse</span></button>
      <button class="chip" type="button" data-sound aria-pressed="false"><span class="bars" aria-hidden="true"><i></i><i></i><i></i><i></i></span><span class="t">Sound</span><span class="sr">Ambient sound</span></button>
      <button class="chip menu-btn" type="button" id="menu-btn" aria-expanded="false" aria-controls="menu">Index</button>
    </div>
  </div>
  <nav class="menu" id="menu" aria-label="Sections">
    <a href="#what" data-go="1">01 What we do</a><a href="#how" data-go="2">02 How it works</a><a href="#sites" data-go="3">03 Sites</a><a href="#numbers" data-go="4">04 Numbers</a><a href="#invest" data-go="5">05 Invest / careers</a><a href="#contact" data-go="6">06 Contact</a>
  </nav>
  <div class="gauge" aria-hidden="true">
    <div class="rail"></div>
    <span class="lab" style="top:0">0 m</span>
    <span class="lab" style="top:52%">rim</span>
    <span class="lab" style="top:100%">−1,100</span>
    <i class="mk" id="gauge-mk"></i>
  </div>
  <div class="reticle" aria-hidden="true"></div>
  <div class="event" id="event" aria-live="polite"></div>
  <div class="hud-read" role="group" aria-label="Live readings">
    <div class="read"><span class="k">DEPTH</span><span class="v" id="r-depth">0<small>m</small></span></div>
    <div class="read" id="r-temp-w"><span class="k">AIR TEMP</span><span class="v" id="r-temp">−14.0<small>°C</small></span></div>
    <div class="read"><span class="k">PRESSURE</span><span class="v" id="r-press">74.6<small>kPa</small></span></div>
  </div>
  <div class="hud-br" aria-hidden="true">
    <span class="sec" id="r-sec">00 / 06 — SNOWFIELD</span>
    <div class="prog"><i id="r-prog"></i></div>
    <span class="coord" id="r-coord">N 64°02′11″ · W 017°19′40″ · HDG 172°</span>
  </div>
  <p class="hint" id="hint">SCROLL TO DESCEND · CLICK ANYWHERE TO SEND A SEISMIC PULSE</p>
</div>

<main id="top">
  <header class="hero" id="hero">
    <p class="kick mono"><span>Caldera Thermal</span><span>Geothermal power</span><span>Since 2011</span></p>
    <h1>We drill where the planet is <em>still warm.</em></h1>
    <p class="lede">Caldera builds and runs geothermal plants inside active volcanic systems. 412 MW of steady power comes from brine at 288 °C, drawn from three kilometres under a snowfield. This page follows the heat down.</p>
    <div class="cue"><a class="btn" href="#what" data-go="1">Begin the descent ↓</a><span class="mono" style="color:var(--bone);opacity:.8">1,100 m to the crater floor</span></div>
  </header>

  <div class="panels" id="panels">
    <div class="stop" data-still="1">
    <section class="panel" id="what" data-i="1" data-side="1" aria-labelledby="h-what">
      <div class="p-head mono"><span><b>01</b> / What we do</span><span>Upper slope · 2,310 m</span></div>
      <h2 id="h-what" tabindex="-1" data-scramble>Heat, piped up from three kilometres.</h2>
      <p>We find, drill and run geothermal fields that sit on live magma. We operate every plant ourselves, with no hand-off to a contractor after commissioning.</p>
      <ul class="list">
        <li><span class="n">A</span><span><b>Exploration</b>Magnetotelluric surveys map the reservoir before a rig is booked. Two dry wells in fifteen years.</span></li>
        <li><span class="n">B</span><span><b>Drilling</b>Directional wells to 3,100 m, cased in titanium alloy wherever the brine turns acidic.</span></li>
        <li><span class="n">C</span><span><b>Operations</b>Run around the clock from a control room on the crater floor. 97.8 % availability last year.</span></li>
      </ul>
    </section>
    </div>

    <div class="stop" data-still="2">
    <section class="panel" id="how" data-i="2" data-side="-1" aria-labelledby="h-how">
      <div class="p-head mono"><span><b>02</b> / How it works</span><span>Fumarole field · 2,050 m</span></div>
      <h2 id="h-how" tabindex="-1" data-scramble>One loop, never vented.</h2>
      <p>The brine comes up, gives its heat to a turbine and goes back down the same day. Drag the slider to follow one litre through the loop.</p>
      <div class="stage">
        <label class="mono" for="stage">Follow the fluid <output id="stage-n" for="stage">1 / 4</output></label>
        <input type="range" id="stage" min="1" max="4" step="1" value="1" aria-describedby="stage-desc">
        <div class="stage-ticks" aria-hidden="true"><span>Well</span><span>Separator</span><span>Turbine</span><span>Reinject</span></div>
        <div class="stage-out" id="stage-desc" aria-live="polite">
          <h3 id="stage-t">Production well</h3><span class="fig" id="stage-f">288 °C</span>
          <p id="stage-p">Brine rises 3,100 m under its own pressure through a 13⅜-inch cased bore.</p>
        </div>
      </div>
    </section>
    </div>

    <div class="stop" data-still="3">
    <section class="panel" id="sites" data-i="3" data-side="1" aria-labelledby="h-sites">
      <div class="p-head mono"><span><b>03</b> / Sites</span><span>Caldera rim · 1,640 m</span></div>
      <h2 id="h-sites" tabindex="-1" data-scramble>Three fields, one rift.</h2>
      <div class="tabs" role="tablist" aria-label="Sites">
        <button role="tab" id="t-ostra" aria-selected="true" aria-controls="site-panel" data-site="0">Ostra</button>
        <button role="tab" id="t-halde" aria-selected="false" aria-controls="site-panel" data-site="1" tabindex="-1">Halde</button>
        <button role="tab" id="t-ward" aria-selected="false" aria-controls="site-panel" data-site="2" tabindex="-1">Sulphur Ward</button>
      </div>
      <div id="site-panel" role="tabpanel" aria-labelledby="t-ostra" tabindex="0">
        <span class="status" id="site-status">Operating since 2014</span>
        <dl class="site-meta">
          <div><dt>Output</dt><dd id="site-mw">212 MW</dd></div>
          <div><dt>Wells</dt><dd id="site-wells">19</dd></div>
          <div><dt>Brine</dt><dd id="site-temp">288 °C</dd></div>
        </dl>
        <p id="site-copy">The plant you are descending into. It sits on the caldera floor 420 m below the rim. Its two cooling stacks are the plumes you saw from the snowfield.</p>
      </div>
    </section>
    </div>

    <div class="stop" data-still="3">
    <section class="panel" id="numbers" data-i="4" data-side="-1" aria-labelledby="h-numbers">
      <div class="p-head mono"><span><b>04</b> / Numbers</span><span>Inner wall · 1,380 m</span></div>
      <h2 id="h-numbers" tabindex="-1" data-scramble>Measured, not promised.</h2>
      <div class="stats">
        <div class="stat"><div class="big" data-count="412">412<small>MW</small></div><p>Installed across three fields</p></div>
        <div class="stat"><div class="big" data-count="288">288<small>°C</small></div><p>Mean reservoir temperature</p></div>
        <div class="stat"><div class="big" data-count="11">11<small>g/kWh</small></div><p>Lifecycle CO₂e, metered 2025</p></div>
        <div class="stat"><div class="big" data-count="97.8" data-dec="1">97.8<small>%</small></div><p>Plant availability, 12 months</p></div>
      </div>
    </section>
    </div>

    <div class="stop" data-still="4">
    <section class="panel" id="invest" data-i="5" data-side="1" aria-labelledby="h-invest">
      <div class="p-head mono"><span><b>05</b> / Invest · Careers</span><span>Crater floor · 1,160 m</span></div>
      <h2 id="h-invest" tabindex="-1" data-scramble>Come down with us.</h2>
      <div class="tabs" role="tablist" aria-label="Invest or work with us">
        <button role="tab" id="t-inv" aria-selected="true" aria-controls="p-inv" data-tab="inv">Invest</button>
        <button role="tab" id="t-car" aria-selected="false" aria-controls="p-car" data-tab="car" tabindex="-1">Careers · 3 open</button>
      </div>
      <div id="p-inv" role="tabpanel" aria-labelledby="t-inv" tabindex="0">
        <p>Our Series C is open to institutional partners: €180 m for two 45 MW binary-cycle units at Halde Rift. Offtake is contracted at a fixed price for 25 years.</p>
        <button class="btn hot" type="button" data-topic="Invest" data-to-contact>Request the data room</button>
      </div>
      <div id="p-car" role="tabpanel" aria-labelledby="t-car" tabindex="0" hidden>
        <ul class="roles">
          <li><div><b>Reservoir engineer</b><span>Ostra · full time · on rotation</span></div><button class="link-btn" type="button" data-topic="Careers" data-role="Reservoir engineer" data-to-contact>Apply</button></li>
          <li><div><b>Drilling supervisor</b><span>Halde · 14 days on / 14 off</span></div><button class="link-btn" type="button" data-topic="Careers" data-role="Drilling supervisor" data-to-contact>Apply</button></li>
          <li><div><b>Control room operator</b><span>Ostra · night shift</span></div><button class="link-btn" type="button" data-topic="Careers" data-role="Control room operator" data-to-contact>Apply</button></li>
        </ul>
      </div>
    </section>
    </div>

    <div class="stop" data-still="4">
    <section class="panel" id="contact" data-i="6" data-side="-1" aria-labelledby="h-contact">
      <div class="p-head mono"><span><b>06</b> / Contact</span><span>Control room · 1,140 m</span></div>
      <h2 id="h-contact" tabindex="-1" data-scramble>Write to the control room.</h2>
      <form id="form" novalidate>
        <div class="row2">
          <div class="f"><label for="f-name">Name</label><input id="f-name" name="name" autocomplete="name" required aria-describedby="e-name"><span class="err" id="e-name"></span></div>
          <div class="f"><label for="f-mail">Email</label><input id="f-mail" name="email" type="email" autocomplete="email" required aria-describedby="e-mail"><span class="err" id="e-mail"></span></div>
        </div>
        <div class="f"><label for="f-topic">About</label>
          <select id="f-topic" name="topic"><option>General</option><option>Invest</option><option>Careers</option><option>Press</option></select></div>
        <div class="f"><label for="f-msg">Message</label><textarea id="f-msg" name="message" required aria-describedby="e-msg"></textarea><span class="err" id="e-msg"></span></div>
        <button class="btn hot" type="submit">Send to Ostra control</button>
        <div id="form-status" role="status" aria-live="polite"></div>
      </form>
      <p class="foot">Caldera Thermal is a fictional company. Ostra Caldera, Halde Rift and Sulphur Ward are invented places. Rock and snow scans are CC0 from Poly Haven.</p>
    </section>
    </div>
  </div>
</main>
<div id="track" aria-hidden="true"></div>

<script type="importmap">
{ "imports": {
  "three": "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js",
  "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/"
} }
</script>
<script type="module">
/* =====================================================================
   CALDERA — one continuous descent. Snowfield → fumarole slope → rim → crater floor.
   ===================================================================== */
const root = document.documentElement;
const $ = (s, el = document) => el.querySelector(s);
const $$ = (s, el = document) => [...el.querySelectorAll(s)];
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
const lerp = (a, b, t) => a + (b - a) * t;
const smoothstep = (a, b, x) => { const t = clamp((x - a) / (b - a), 0, 1); return t * t * (3 - 2 * t); };
const store = { get(k) { try { return localStorage.getItem(k); } catch (e) { return null; } }, set(k, v) { try { localStorage.setItem(k, v); } catch (e) {} } };

/* Section stops along the descent (scroll progress 0..1) */
const STOPS = [0, 0.165, 0.33, 0.495, 0.66, 0.815, 0.965];
const SEC_NAMES = ['SNOWFIELD', 'WHAT WE DO', 'HOW IT WORKS', 'SITES', 'NUMBERS', 'INVEST · CAREERS', 'CONTACT'];

/* ---------------- scramble / decode text ---------------- */
const GLYPHS = '▚▞▙▟░▒/\\<>_#+=0123456789ABCDEFXZ';
function prepScramble(el) {
  if (el.dataset.ready) return;
  const text = el.textContent.trim();
  el.textContent = '';
  const sr = document.createElement('span'); sr.className = 'sr'; sr.textContent = text;
  const vis = document.createElement('span'); vis.setAttribute('aria-hidden', 'true'); vis.textContent = text;
  el.append(sr, vis); el.dataset.ready = '1'; el._vis = vis; el._text = text;
}
function scramble(el, dur = 950) {
  prepScramble(el);
  const vis = el._vis, text = el._text, n = text.length, t0 = performance.now();
  const at = [...text].map((c, i) => (i / n) * dur * 0.65 + Math.random() * dur * 0.35);
  cancelAnimationFrame(el._raf);
  const step = (now) => {
    const t = now - t0; let out = '';
    for (let i = 0; i < n; i++) {
      const c = text[i];
      out += (c === ' ' || t >= at[i]) ? c : GLYPHS[(Math.random() * GLYPHS.length) | 0];
    }
    vis.textContent = out;
    if (t < dur) el._raf = requestAnimationFrame(step); else vis.textContent = text;
  };
  el._raf = requestAnimationFrame(step);
}
$$('[data-scramble]').forEach(prepScramble);

/* ---------------- count-up ---------------- */
function countUp(el) {
  const to = parseFloat(el.dataset.count), dec = +(el.dataset.dec || 0), small = el.querySelector('small').outerHTML;
  if (root.classList.contains('still')) return;
  const t0 = performance.now(), dur = 1300;
  const f = (now) => { const t = clamp((now - t0) / dur, 0, 1), e = 1 - Math.pow(1 - t, 4);
    el.innerHTML = (to * e).toFixed(dec) + small; if (t < 1) requestAnimationFrame(f); };
  requestAnimationFrame(f);
}

/* =====================================================================
   SOUND — synthesised wind that hands over to a deep rumble with depth.
   ===================================================================== */
const Sound = (() => {
  let ctx = null, master, windG, whistleG, rumbleG, bp, lfo, started = false;
  let muted = store.get('caldera-muted') === '1';
  let depth = 0;
  const btns = $$('[data-sound]');
  const sync = () => btns.forEach(b => { b.setAttribute('aria-pressed', String(started && !muted)); b.querySelector('.t').textContent = started && !muted ? 'Sound on' : 'Sound off'; });
  function noiseBuf(brown) {
    const len = ctx.sampleRate * 3, b = ctx.createBuffer(2, len, ctx.sampleRate);
    for (let ch = 0; ch < 2; ch++) { const d = b.getChannelData(ch); let last = 0;
      for (let i = 0; i < len; i++) { const w = Math.random() * 2 - 1; if (brown) { last = (last + 0.02 * w) / 1.02; d[i] = last * 3.5; } else d[i] = w; } }
    return b;
  }
  function build() {
    const AC = window.AudioContext || window.webkitAudioContext; if (!AC) return false;
    ctx = new AC();
    master = ctx.createGain(); master.gain.value = 0; master.connect(ctx.destination);
    const comp = ctx.createDynamicsCompressor(); comp.threshold.value = -18; comp.connect(master);
    // wind: white noise → wandering band-pass
    const wn = ctx.createBufferSource(); wn.buffer = noiseBuf(false); wn.loop = true;
    bp = ctx.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.value = 520; bp.Q.value = 0.7;
    lfo = ctx.createOscillator(); lfo.frequency.value = 0.07; const lg = ctx.createGain(); lg.gain.value = 260; lfo.connect(lg).connect(bp.frequency);
    windG = ctx.createGain(); windG.gain.value = 0.0; wn.connect(bp).connect(windG).connect(comp);
    const wh = ctx.createBiquadFilter(); wh.type = 'bandpass'; wh.frequency.value = 1650; wh.Q.value = 9;
    const lfo2 = ctx.createOscillator(); lfo2.frequency.value = 0.13; const lg2 = ctx.createGain(); lg2.gain.value = 420; lfo2.connect(lg2).connect(wh.frequency);
    whistleG = ctx.createGain(); whistleG.gain.value = 0; wn.connect(wh).connect(whistleG).connect(comp);
    // rumble: brown noise low-passed + two detuned sub sines
    const bn = ctx.createBufferSource(); bn.buffer = noiseBuf(true); bn.loop = true;
    const lp = ctx.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 110;
    rumbleG = ctx.createGain(); rumbleG.gain.value = 0; bn.connect(lp).connect(rumbleG).connect(comp);
    const s1 = ctx.createOscillator(); s1.frequency.value = 36; const s2 = ctx.createOscillator(); s2.frequency.value = 53.5;
    const sg = ctx.createGain(); sg.gain.value = 0.22; s1.connect(sg); s2.connect(sg); sg.connect(rumbleG);
    const trem = ctx.createOscillator(); trem.frequency.value = 0.21; const tg = ctx.createGain(); tg.gain.value = 0.08; trem.connect(tg).connect(sg.gain);
    [wn, bn, lfo, lfo2, s1, s2, trem].forEach(n => n.start());
    return true;
  }
  function start() {
    if (started) { if (ctx.state === 'suspended' && !document.hidden) ctx.resume(); return; }
    if (!build()) return; started = true;
    if (ctx.state === 'suspended') ctx.resume();
    setMute(muted); sync();
  }
  function setMute(m) {
    muted = m; store.set('caldera-muted', m ? '1' : '0');
    if (ctx) master.gain.setTargetAtTime(m ? 0 : 0.75, ctx.currentTime, 0.4);
    sync();
  }
  function setDepth(d) {
    depth = d; if (!ctx || muted) return;
    const t = ctx.currentTime;
    windG.gain.setTargetAtTime(0.32 * (1 - smoothstep(0.35, 0.85, d)) + 0.04, t, 0.3);
    whistleG.gain.setTargetAtTime(0.05 * (1 - smoothstep(0.2, 0.6, d)), t, 0.3);
    rumbleG.gain.setTargetAtTime(0.9 * smoothstep(0.3, 1.0, d) + 0.03, t, 0.3);
  }
  function thump(mag = 1) {
    if (!ctx || muted) return;
    const t = ctx.currentTime;
    const o = ctx.createOscillator(), g = ctx.createGain();
    o.frequency.setValueAtTime(78, t); o.frequency.exponentialRampToValueAtTime(26, t + 1.1);
    g.gain.setValueAtTime(0.0001, t); g.gain.exponentialRampToValueAtTime(0.9 * mag, t + 0.03); g.gain.exponentialRampToValueAtTime(0.0001, t + 1.6);
    o.connect(g).connect(master); o.start(t); o.stop(t + 1.7);
    const n = ctx.createBufferSource(); n.buffer = noiseBuf(true); const f = ctx.createBiquadFilter(); f.type = 'lowpass'; f.frequency.value = 240;
    const ng = ctx.createGain(); ng.gain.setValueAtTime(0.0001, t); ng.gain.exponentialRampToValueAtTime(0.7 * mag, t + 0.05); ng.gain.exponentialRampToValueAtTime(0.0001, t + 2.2);
    n.connect(f).connect(ng).connect(master); n.start(t); n.stop(t + 2.3);
  }
  btns.forEach(b => b.addEventListener('click', (e) => { e.stopPropagation(); if (!started) { muted = false; start(); setMute(false); } else setMute(!muted); }));
  document.addEventListener('visibilitychange', () => { if (!ctx) return; if (document.hidden) ctx.suspend(); else if (started) ctx.resume(); });
  // unlock on the first real gesture (unless the visitor muted on an earlier visit)
  const unlock = (e) => { if (e.target.closest && e.target.closest('[data-sound],#go-quiet')) return; if (!muted && root.classList.contains('gl') && !root.classList.contains('loading')) { start(); off(); } };
  const off = () => ['pointerdown', 'keydown'].forEach(ev => window.removeEventListener(ev, unlock, true));
  ['pointerdown', 'keydown'].forEach(ev => window.addEventListener(ev, unlock, true));
  sync();
  return { start, setMute, setDepth, thump, get muted() { return muted; } };
})();

/* =====================================================================
   UI that works in every mode: slider, tabs, roles → form, validation
   ===================================================================== */
const STAGES = [
  ['Production well', '288 °C', 'Brine rises 3,100 m under its own pressure through a 13⅜-inch cased bore.'],
  ['Separator', '14 bar', 'Pressure drops, and a fifth of the brine flashes to steam. The rest carries its heat to a binary loop.'],
  ['Turbine hall', '71 MW', 'Dry steam spins two condensing turbines. The binary loop adds 9 MW from what the steam leaves behind.'],
  ['Reinjection', '82 °C', 'Cooled brine goes back down 1.4 km away, which keeps the reservoir pressure up. Nothing is vented to the snowfield.'],
];
const stage = $('#stage');
stage.addEventListener('input', () => { const s = STAGES[stage.value - 1];
  $('#stage-n').textContent = `${stage.value} / 4`; $('#stage-t').textContent = s[0]; $('#stage-f').textContent = s[1]; $('#stage-p').textContent = s[2];
  stage.setAttribute('aria-valuetext', `${s[0]}, ${s[1]}`); });
stage.setAttribute('aria-valuetext', 'Production well, 288 °C');

const SITES = [
  { mw: '212 MW', wells: '19', temp: '288 °C', status: 'Operating since 2014', build: false, copy: 'The plant you are descending into. It sits on the caldera floor 420 m below the rim. Its two cooling stacks are the plumes you saw from the snowfield.' },
  { mw: '118 MW', wells: '11', temp: '262 °C', status: 'Operating since 2019', build: false, copy: 'A fissure-swarm field 40 km north. It has a mostly binary-cycle fleet, built low and grey so it disappears into the lava plain in summer.' },
  { mw: '82 MW', wells: '6 / 9', temp: '301 °C', status: 'Drilling · online 2027', build: true, copy: 'Our hottest reservoir yet, and our most acidic. The wells are titanium-lined from 1,800 m down. The first unit spins in spring 2027.' },
];
let siteIdx = 0;
function tabs(list, onSelect) {
  const tabsEl = $$('[role=tab]', list);
  const select = (t, focus) => { tabsEl.forEach(x => { const on = x === t; x.setAttribute('aria-selected', String(on)); x.tabIndex = on ? 0 : -1; }); if (focus) t.focus(); onSelect(t); };
  tabsEl.forEach((t, i) => {
    t.addEventListener('click', () => select(t));
    t.addEventListener('keydown', (e) => { let j = null;
      if (e.key === 'ArrowRight') j = (i + 1) % tabsEl.length; else if (e.key === 'ArrowLeft') j = (i - 1 + tabsEl.length) % tabsEl.length; else if (e.key === 'Home') j = 0; else if (e.key === 'End') j = tabsEl.length - 1;
      if (j !== null) { e.preventDefault(); select(tabsEl[j], true); } });
  });
}
tabs($('#sites .tabs'), (t) => { siteIdx = +t.dataset.site; const s = SITES[siteIdx];
  $('#site-panel').setAttribute('aria-labelledby', t.id);
  $('#site-mw').textContent = s.mw; $('#site-wells').textContent = s.wells; $('#site-temp').textContent = s.temp; $('#site-copy').textContent = s.copy;
  const st = $('#site-status'); st.textContent = s.status; st.classList.toggle('build', s.build); });
tabs($('#invest .tabs'), (t) => { const inv = t.dataset.tab === 'inv'; $('#p-inv').hidden = !inv; $('#p-car').hidden = inv; });

/* jump between sections — in the live world this scrolls the camera to the stop */
let goTo = (i) => { const el = i === 0 ? $('#top') : $$('.panel')[i - 1]; el.scrollIntoView({ behavior: 'smooth' }); };
$$('[data-go]').forEach(a => a.addEventListener('click', (e) => { e.preventDefault(); $('#menu').classList.remove('open'); $('#menu-btn').setAttribute('aria-expanded', 'false'); goTo(+a.dataset.go, true); }));
$('#menu-btn').addEventListener('click', () => { const m = $('#menu'), o = !m.classList.contains('open'); m.classList.toggle('open', o); $('#menu-btn').setAttribute('aria-expanded', String(o)); });
document.addEventListener('keydown', (e) => { if (e.key === 'Escape') { $('#menu').classList.remove('open'); $('#menu-btn').setAttribute('aria-expanded', 'false'); } });

$$('[data-to-contact]').forEach(b => b.addEventListener('click', () => {
  $('#f-topic').value = b.dataset.topic;
  if (b.dataset.role) { const m = $('#f-msg'); if (!m.value.trim()) m.value = `Applying for: ${b.dataset.role}. `; }
  goTo(6, true); setTimeout(() => $('#f-name').focus({ preventScroll: true }), 50);
}));

const form = $('#form');
function check(field, errEl, ok, msg) { field.setAttribute('aria-invalid', String(!ok)); errEl.textContent = ok ? '' : msg; return ok; }
form.addEventListener('submit', (e) => {
  e.preventDefault();
  const n = $('#f-name'), m = $('#f-mail'), t = $('#f-msg');
  const a = check(n, $('#e-name'), n.value.trim().length >= 2, 'Tell us who is writing (2+ characters).');
  const b = check(m, $('#e-mail'), /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(m.value.trim()), 'That email address does not look complete.');
  const c = check(t, $('#e-msg'), t.value.trim().length >= 20, `A little more detail, please: ${Math.max(0, 20 - t.value.trim().length)} more characters.`);
  const st = $('#form-status');
  if (!(a && b && c)) { st.innerHTML = ''; (a ? (b ? t : m) : n).focus(); return; }
  st.innerHTML = `<p class="form-ok">Logged as ticket OST-${(Date.now() % 100000).toString().padStart(5, '0')}. A person in the control room reads every message, so expect a reply within two working days.</p>`;
  form.reset(); [n, m, t].forEach(x => x.removeAttribute('aria-invalid'));
});
['#f-name', '#f-mail', '#f-msg'].forEach(s => $(s).addEventListener('input', (e) => { if (e.target.getAttribute('aria-invalid') === 'true') e.target.setAttribute('aria-invalid', 'false'); }));

/* =====================================================================
   STILL-FRAME MODE (no WebGL, reduced motion, or a failed start)
   ===================================================================== */
function toStill(reason) {
  if (reason) console.warn('Caldera: showing still frames —', reason);
  root.classList.remove('gl', 'loading'); root.classList.add('still');
  goTo = (i) => { const el = i === 0 ? $('#top') : $$('.panel')[i - 1]; el.scrollIntoView({ behavior: 'auto' }); if (i) el.querySelector('h2').focus({ preventScroll: true }); };
  $$('.stat .big').forEach(el => { el.dataset.done = '1'; });
  const io = new IntersectionObserver((es) => es.forEach(en => { if (en.isIntersecting) { const i = +en.target.dataset.i || 0; Sound.setDepth(i / 6); } }), { threshold: 0.4 });
  $$('.panel').forEach(p => io.observe(p));
}
if (root.classList.contains('still')) toStill();
else initWorld().catch(err => toStill(err && err.message ? err.message : String(err)));

/* =====================================================================
   THE WORLD
   ===================================================================== */
async function initWorld() {
  const log = $('#ld-log'), bar = $('#ld-bar'), pct = $('#ld-pct');
  let shown = 0, target = 0;
  const steps = {};
  const addStep = (id, label) => { const li = document.createElement('li'); li.className = 'wait'; li.innerHTML = `<b>${String(Object.keys(steps).length + 1).padStart(2, '0')}</b><span>${label}</span><span>…</span>`; log.append(li); steps[id] = li; };
  const doneStep = (id, note) => { const li = steps[id]; if (!li) return; li.className = ''; li.lastChild.textContent = note || 'OK'; };
  const progress = (v) => { target = Math.max(target, v); };
  const tickPct = () => { shown += (target - shown) * 0.18; pct.textContent = String(Math.round(shown * 100)).padStart(3, '0'); bar.style.transform = `scaleX(${shown})`; if (!root.classList.contains('loading')) return; requestAnimationFrame(tickPct); };
  requestAnimationFrame(tickPct);

  addStep('mod', 'Renderer modules · three r170');
  const [THREE, { GLTFLoader }, { EffectComposer }, { RenderPass }, { UnrealBloomPass }, { ShaderPass }] = await Promise.all([
    import('three'), import('three/addons/loaders/GLTFLoader.js'), import('three/addons/postprocessing/EffectComposer.js'),
    import('three/addons/postprocessing/RenderPass.js'), import('three/addons/postprocessing/UnrealBloomPass.js'), import('three/addons/postprocessing/ShaderPass.js')]);
  doneStep('mod'); progress(0.12);

  /* ---------- tiering ---------- */
  const coarse = matchMedia('(pointer: coarse)').matches, small = Math.min(innerWidth, innerHeight) < 600;
  const cores = navigator.hardwareConcurrency || 4;
  const q = new URLSearchParams(location.search);
  const CAPTURE = q.has('capture'); // test hook: render one frame on demand (headless screenshots)
  const tier = ['low', 'mid', 'high'].includes(q.get('tier')) ? q.get('tier') : (coarse || small) ? 'low' : cores >= 8 ? 'high' : 'mid';
  const T = { high: { steam: 360000, snow: 42000, seg: 400, dpr: 1.75 }, mid: { steam: 220000, snow: 28000, seg: 320, dpr: 1.5 }, low: { steam: 120000, snow: 14000, seg: 220, dpr: 1.5 } }[tier];

  const canvas = $('#gl');
  const renderer = new THREE.WebGLRenderer({ canvas, antialias: false, powerPreference: 'high-performance', stencil: false });
  if (!renderer.capabilities.isWebGL2) throw new Error('WebGL2 unavailable');
  let dpr = Math.min(devicePixelRatio || 1, T.dpr);
  renderer.setPixelRatio(dpr); renderer.setSize(innerWidth, innerHeight, false);
  renderer.toneMapping = THREE.NoToneMapping;
  canvas.addEventListener('webglcontextlost', (e) => { e.preventDefault(); toStill('WebGL context lost'); });

  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(innerWidth < innerHeight ? 64 : 50, innerWidth / innerHeight, 1, 14000);

  /* ---------- assets ---------- */
  addStep('assets', 'Scans · basalt, snow, obsidian, plant');
  const manager = new THREE.LoadingManager();
  let loaded = 0; const TOTAL = 6;
  manager.onProgress = () => { loaded++; progress(0.12 + 0.38 * loaded / TOTAL); };
  const texL = new THREE.TextureLoader(manager), gltfL = new GLTFLoader(manager);
  const tex = (u, srgb) => new Promise((res, rej) => texL.load(u, t => { t.wrapS = t.wrapT = THREE.RepeatWrapping; t.anisotropy = 4; if (srgb) t.colorSpace = THREE.SRGBColorSpace; res(t); }, undefined, () => rej(new Error('texture ' + u))));
  const glb = (u) => new Promise((res, rej) => gltfL.load(u, res, undefined, () => rej(new Error('model ' + u))));
  const [tAlb, tNor, tSnowN, gShardA, gShardB, gPlant] = await Promise.all([
    tex('assets/basalt-albedo.webp', true), tex('assets/basalt-normal.webp'), tex('assets/snow-normal.webp'),
    glb('assets/shard-a.glb'), glb('assets/shard-b.glb'), glb('assets/plant.glb')]);
  doneStep('assets', '6 / 6'); progress(0.5);

  /* ---------- terrain field (shared by mesh, camera, shadows and pulse raycast) ---------- */
  const RIM = 540, FLOOR_R = 280;
  // seeded 2D gradient noise
  const PERM = new Uint8Array(512);
  { const p = [...Array(256).keys()]; let s = 1337; for (let i = 255; i > 0; i--) { s = (s * 16807) % 2147483647; const j = s % (i + 1); [p[i], p[j]] = [p[j], p[i]]; } for (let i = 0; i < 512; i++) PERM[i] = p[i & 255]; }
  const GX = [1, -1, 1, -1, 1.41, -1.41, 0, 0], GZ = [1, 1, -1, -1, 0, 0, 1.41, -1.41];
  function pnoise(x, z) {
    const xi = Math.floor(x), zi = Math.floor(z), xf = x - xi, zf = z - zi, X = xi & 255, Z = zi & 255;
    const u = xf * xf * xf * (xf * (xf * 6 - 15) + 10), v = zf * zf * zf * (zf * (zf * 6 - 15) + 10);
    const g = (h, dx, dz) => GX[h & 7] * dx + GZ[h & 7] * dz;
    const a = g(PERM[PERM[X] + Z], xf, zf), b = g(PERM[PERM[X + 1] + Z], xf - 1, zf), c = g(PERM[PERM[X] + Z + 1], xf, zf - 1), d = g(PERM[PERM[X + 1] + Z + 1], xf - 1, zf - 1);
    return lerp(lerp(a, b, u), lerp(c, d, u), v) * 0.72;
  }
  const fbm = (x, z, o) => { let s = 0, a = 0.5, f = 1; for (let i = 0; i < o; i++) { s += a * pnoise(x * f, z * f); f *= 2.02; a *= 0.5; } return s; };
  // Musgrave ridged multifractal: sharp crests, branching gullies, no rounded lumps
  function ridged(x, z, o) {
    let sum = 0, f = 1, w = 1, norm = 0;
    for (let i = 0; i < o; i++) { let s = 1 - Math.abs(pnoise(x * f, z * f)); s *= s; s *= w; w = clamp(s * 2.1, 0, 1); const a = Math.pow(f, -0.9); sum += s * a; norm += a; f *= 2.07; }
    return sum / norm;
  }
  function range(x, z) { // domain-warped ridged multifractal
    const s = 1 / 900, wx = x * s + 0.6 * fbm(x * s * 0.8 + 5.2, z * s * 0.8 + 1.3, 3), wz = z * s + 0.6 * fbm(x * s * 0.8 - 3.7, z * s * 0.8 + 8.1, 3);
    return ridged(wx, wz, 7);
  }
  const PLANT_S = 104, PLANT_ROT = Math.PI * 0.82;
  const PAD = { x: 0, z: 180, h: 24, c: Math.cos(PLANT_ROT), s: Math.sin(PLANT_ROT), half: 0.97 * PLANT_S };
  function height(x, z) {
    const r = Math.hypot(x, z), ax = Math.abs(x);
    const tN = smoothstep(-1800, -420, z);
    let h = lerp(1000, 470, tN) + fbm(x * 0.0011 + 3.1, z * 0.0011 - 1.7, 3) * 60;
    // erosion gullies running straight down the slope
    const gw = fbm(x * 0.004, z * 0.004, 2) * 0.7;
    const gul = 1 - Math.abs(pnoise(x * 0.0075 + gw, z * 0.0019));
    h -= Math.pow(gul, 5) * 42 * smoothstep(-2300, -1500, z) * (1 - smoothstep(-760, -520, z));
    h += (ridged(x * 0.004 + gw, z * 0.0026, 3) - 0.35) * 40 * tN * (1 - smoothstep(-760, -520, z));
    h -= smoothstep(-200, 900, z) * 230;
    // mountain ranges east, west and south
    const mm = Math.max(smoothstep(900, 1900, ax), smoothstep(900, 1900, z));
    if (mm > 0) h += mm * (range(x, z) * 1300 - 120);
    // caldera: rim ridge, cliff-banded inner wall, level floor
    h += Math.exp(-(((r - RIM) / 110) ** 2)) * 95;
    const inside = smoothstep(RIM + 30, FLOOR_R, r);
    if (inside > 0) {
      const floorH = 20 + fbm(x * 0.006 + 9, z * 0.006 + 4, 2) * 6;
      let hh = lerp(h, floorH, Math.pow(inside, 0.5));
      const wall = inside * (1 - inside) * 4;
      if (wall > 0.01) hh += (ridged(x * 0.0065, z * 0.0065, 4) - 0.45) * 110 * wall;
      h = hh;
    }
    // level pad under the plant so its plinth disappears into the crater floor
    const dx = x - PAD.x, dz = z - PAD.z;
    const lx = Math.abs(dx * PAD.c - dz * PAD.s), lz = Math.abs(dx * PAD.s + dz * PAD.c);
    const e = Math.max(lx, lz) - PAD.half;
    if (e < 90) h = lerp(PAD.h, Math.max(h, PAD.h - 4), smoothstep(0, 90, e));
    return h;
  }

  addStep('terrain', 'Terrain · ridged caldera field');
  const TW = 4800, TD = 5000, TZ = -300;
  const NX = T.seg, NZ = Math.round(T.seg * TD / TW), DX = TW / NX, DZ = TD / NZ, X0 = -TW / 2, Z0 = TZ - TD / 2;
  const tg = new THREE.PlaneGeometry(TW, TD, NX, NZ);
  tg.rotateX(-Math.PI / 2); tg.translate(0, 0, TZ);
  const HG = new Float32Array((NX + 1) * (NZ + 1));
  { const p = tg.attributes.position; for (let i = 0; i < p.count; i++) { const y = height(p.getX(i), p.getZ(i)); p.setY(i, y);
      HG[Math.round((p.getZ(i) - Z0) / DZ) * (NX + 1) + Math.round((p.getX(i) - X0) / DX)] = y; } tg.computeVertexNormals(); }
  const hAt = (x, z) => { const fx = clamp((x - X0) / DX, 0, NX - 1.001), fz = clamp((z - Z0) / DZ, 0, NZ - 1.001), ix = fx | 0, iz = fz | 0, u = fx - ix, v = fz - iz, k = iz * (NX + 1) + ix;
    return lerp(lerp(HG[k], HG[k + 1], u), lerp(HG[k + NX + 1], HG[k + NX + 2], u), v); };
  doneStep('terrain', `${(tg.index.count / 3 / 1000).toFixed(0)}k tris`); progress(0.55);

  /* ---------- low sun: soft terrain shadows marched across the height grid ---------- */
  addStep('shadow', 'Sun shadows · 3.8° elevation');
  const SUN = new THREE.Vector3(0.3, 0.066, 0.95).normalize();
  { const p = tg.attributes.position, sh = new Float32Array(p.count);
    for (let i = 0; i < p.count; i++) {
      const x0 = p.getX(i), y0 = p.getY(i) + 3, z0 = p.getZ(i); let s = 1, t = 6;
      while (t < 4200) { const x = x0 + SUN.x * t, z = z0 + SUN.z * t; if (x < X0 || x > -X0 || z < Z0 || z > Z0 + TD) break;
        const d = y0 + SUN.y * t - hAt(x, z); s = Math.min(s, clamp(0.5 + d / (t * 0.035 + 3), 0, 1)); if (s <= 0) break; t += Math.max(7, t * 0.035); }
      sh[i] = s * s * (3 - 2 * s); }
    tg.setAttribute('aShadow', new THREE.BufferAttribute(sh, 1)); }
  doneStep('shadow'); progress(0.6);

  /* ---------- shared GLSL ---------- */
  const U = {
    uTime: { value: 0 }, uLava: { value: 0 }, uAsh: { value: 0 }, uDesc: { value: 0 },
    sunDir: { value: SUN }, sunCol: { value: new THREE.Color(1.0, 0.6, 0.36).multiplyScalar(3.0) },
    skyTop: { value: new THREE.Color(0.075, 0.13, 0.28) }, skyHor: { value: new THREE.Color(1.05, 0.56, 0.3) },
    fogCol: { value: new THREE.Color(0.12, 0.075, 0.06) },
    fogDensity: { value: 0.0011 }, fogFalloff: { value: 0.0012 },
    uPulse: { value: new THREE.Vector4(0, -999, 0, 99) },
  };
  const NOISE = `
  vec3 permute(vec3 x){return mod(((x*34.0)+1.0)*x,289.0);}
  float snoise(vec2 v){const vec4 C=vec4(0.211324865405187,0.366025403784439,-0.577350269189626,0.024390243902439);vec2 i=floor(v+dot(v,C.yy));vec2 x0=v-i+dot(i,C.xx);vec2 i1=(x0.x>x0.y)?vec2(1.0,0.0):vec2(0.0,1.0);vec4 x12=x0.xyxy+C.xxzz;x12.xy-=i1;i=mod(i,289.0);vec3 p=permute(permute(i.y+vec3(0.0,i1.y,1.0))+i.x+vec3(0.0,i1.x,1.0));vec3 m=max(0.5-vec3(dot(x0,x0),dot(x12.xy,x12.xy),dot(x12.zw,x12.zw)),0.0);m=m*m;m=m*m;vec3 x=2.0*fract(p*C.www)-1.0;vec3 h=abs(x)-0.5;vec3 ox=floor(x+0.5);vec3 a0=x-ox;m*=1.79284291400159-0.85373472095314*(a0*a0+h*h);vec3 g;g.x=a0.x*x0.x+h.x*x0.y;g.yz=a0.yz*x12.xz+h.yz*x12.yw;return 130.0*dot(m,g);}`;
  const ATMOS = `
  uniform vec3 sunDir, sunCol, skyTop, skyHor, fogCol; uniform float fogDensity, fogFalloff, uDesc;
  // low-sun physical-ish sky: warm horizon band around the sun's azimuth, cool elsewhere
  vec3 skyBase(vec3 d){
    float h = max(d.y, 0.0);
    vec2 az = normalize(d.xz + 1e-5), saz = normalize(sunDir.xz);
    float s = max(dot(az, saz), 0.0);
    vec3 hor = mix(vec3(0.46, 0.52, 0.66), skyHor, pow(s, 2.5));
    vec3 c = mix(hor, skyTop, pow(h, 0.45));
    float mu = max(dot(d, sunDir), 0.0);
    c += sunCol * (0.045 * pow(mu, 4.0) + 0.28 * pow(mu, 50.0));
    c = mix(c, hor * 0.8, smoothstep(0.02, -0.15, d.y));
    return c;
  }
  vec3 skyColor(vec3 d){ return skyBase(d) + sunCol * 16.0 * smoothstep(0.99955, 0.99975, dot(d, sunDir)); }
  // analytic exponential height fog; its colour is the horizon sky in the view direction,
  // so distance fades every ridge into the sky behind it (aerial perspective)
  float fogAmount(vec3 wp, out vec3 fc){
    vec3 ro = cameraPosition; vec3 rd = wp - ro; float dist = length(rd); rd /= max(dist, 1e-3);
    float a = fogDensity * exp(-ro.y * fogFalloff);
    float b = rd.y * fogFalloff;
    float f = abs(b) > 1e-5 ? a * (1.0 - exp(-dist * b)) / b : a * dist;
    vec3 hz = skyBase(normalize(vec3(rd.x, 0.012 + max(rd.y, 0.0) * 0.4, rd.z)));
    fc = mix(hz * 0.78, fogCol, uDesc);
    return clamp(1.0 - exp(-f), 0.0, 1.0);
  }
  vec3 applyFog(vec3 col, vec3 wp){ vec3 fc; float f = fogAmount(wp, fc); return mix(col, fc, f); }`;

  /* ---------- sky ---------- */
  const skyMat = new THREE.ShaderMaterial({
    uniforms: U, side: THREE.BackSide, depthWrite: false,
    vertexShader: `varying vec3 vDir; void main(){ vDir = normalize(position); vec4 p = projectionMatrix * modelViewMatrix * vec4(position,1.0); gl_Position = p.xyww; }`,
    fragmentShader: `${ATMOS} varying vec3 vDir; void main(){ vec3 d = normalize(vDir); gl_FragColor = vec4(mix(skyColor(d), fogCol * 1.6 + skyTop * 0.2, uDesc * smoothstep(0.35, 0.0, d.y) * 0.7), 1.0); }`,
  });
  const sky = new THREE.Mesh(new THREE.SphereGeometry(9000, 48, 24), skyMat); sky.frustumCulled = false; sky.renderOrder = -2;
  scene.add(sky);

  /* ---------- distant ranges: three layered silhouettes, cooler and paler with distance ---------- */
  const ringMat = (depth) => new THREE.ShaderMaterial({
    uniforms: { ...U, uDepth: { value: depth } }, depthWrite: true,
    vertexShader: `attribute float aT; varying float vT; varying vec3 vWP; void main(){ vT = aT; vec4 w = modelMatrix * vec4(position, 1.0); vWP = w.xyz; gl_Position = projectionMatrix * viewMatrix * w; }`,
    fragmentShader: `${ATMOS} uniform float uDepth; varying float vT; varying vec3 vWP;
      void main(){
        vec3 dir = normalize(vWP - cameraPosition);
        vec3 haze = skyBase(normalize(vec3(dir.x, 0.015, dir.z)));
        vec3 body = mix(vec3(0.05, 0.065, 0.1), haze, uDepth);
        vec3 c = mix(haze, body, 0.3 + 0.7 * pow(vT, 1.5));
        float toward = pow(max(dot(normalize(dir.xz), normalize(sunDir.xz)), 0.0), 10.0);
        c += sunCol * smoothstep(0.9, 1.0, vT) * toward * 0.35 * (1.0 - uDepth);   // rim light on the crests
        c += vec3(0.5, 0.55, 0.65) * smoothstep(0.82, 0.95, vT) * (1.0 - toward) * 0.12 * (1.0 - uDepth); // snow caps away from the sun
        c = mix(c, fogCol * 1.4, uDesc * 0.85);
        gl_FragColor = vec4(c, 1.0);
      }`,
  });
  const sunAz = Math.atan2(SUN.z, SUN.x);
  [[4300, 0.42, 1500, 1050], [5700, 0.62, 1700, 1200], [7300, 0.8, 1900, 1400]].forEach(([R, depth, base, amp], k) => {
    const N = 720, pos = new Float32Array((N + 1) * 2 * 3), at = new Float32Array((N + 1) * 2), idx = [];
    for (let i = 0; i <= N; i++) {
      const a = (i / N) * Math.PI * 2, cx = Math.cos(a), cz = Math.sin(a);
      let rr = ridged(cx * 3.2 + k * 7.1, cz * 3.2 - k * 3.3, 6);
      const nearSun = Math.exp(-(((Math.atan2(Math.sin(a - sunAz), Math.cos(a - sunAz))) / 0.09) ** 2));
      const top = base + amp * (rr - 0.3) + nearSun * (k === 0 ? 140 : 60);
      pos.set([cx * R, -400, cz * R], i * 6); pos.set([cx * R, top, cz * R], i * 6 + 3); at[i * 2] = 0; at[i * 2 + 1] = 1;
      if (i < N) { const b = i * 2; idx.push(b, b + 1, b + 2, b + 1, b + 3, b + 2); }
    }
    const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.BufferAttribute(pos, 3)); g.setAttribute('aT', new THREE.BufferAttribute(at, 1)); g.setIndex(idx);
    const m = new THREE.Mesh(g, ringMat(depth)); m.material.side = THREE.DoubleSide; m.frustumCulled = false; m.renderOrder = -1 - k * 0.1; scene.add(m);
  });

  /* environment for the PBR plant: PMREM of the same sky */
  const pmrem = new THREE.PMREMGenerator(renderer);
  { const s2 = new THREE.Scene(); const sk = new THREE.Mesh(new THREE.SphereGeometry(100, 32, 16), skyMat); s2.add(sk); scene.environment = pmrem.fromScene(s2, 0, 1, 1000).texture; }
  scene.environmentIntensity = 0.45;

  /* ---------- fumaroles & plumes ---------- */
  const plantPos = new THREE.Vector3(PAD.x, PAD.h, PAD.z);
  const toWorld = (lx, ly, lz) => new THREE.Vector3(PAD.x + (lx * PAD.c + lz * PAD.s) * PLANT_S, PAD.h - 2 + (ly + 0.27) * PLANT_S, PAD.z + (-lx * PAD.s + lz * PAD.c) * PLANT_S);
  const stackA = toWorld(-0.3, 0.46, -0.5), stackB = toWorld(0.3, 0.46, -0.5);
  const VENTS = [ // x, z, plume height, hot(0..1), y override
    [-150, -1380, 115, 0], [120, -1310, 90, 0], [-150, -940, 130, 0], [160, -880, 100, 0], [-250, -1560, 80, 0],
    [-40, -215, 260, 1], [215, 30, 220, 1], [185, 125, 170, 1],
    [stackA.x, stackA.z, 210, 0.3, stackA.y], [stackB.x, stackB.z, 200, 0.3, stackB.y],
  ];
  const ventP = VENTS.map(v => new THREE.Vector4(v[0], v[4] != null ? v[4] : height(v[0], v[1]) + 2, v[1], v[2]));
  const ventQ = VENTS.map(v => new THREE.Vector4(v[3], 0, 0, 0));
  U.uVents = { value: ventP.slice(0, 5).map(v => new THREE.Vector4(v.x, v.y, v.z, 40)) };
  U.uPlant = { value: plantPos };
  U.uPad = { value: new THREE.Vector4(PAD.x, PAD.z, PAD.c, PAD.s) };

  /* ---------- terrain material ---------- */
  const terrMat = new THREE.ShaderMaterial({
    uniforms: { ...U, tAlb: { value: tAlb }, tNor: { value: tNor }, tSnowN: { value: tSnowN } },
    vertexShader: `attribute float aShadow; varying float vSh; varying vec3 vWP; varying vec3 vN; void main(){ vSh = aShadow; vec4 w = modelMatrix*vec4(position,1.0); vWP = w.xyz; vN = normal; gl_Position = projectionMatrix*viewMatrix*w; }`,
    fragmentShader: `
    precision highp float;
    ${ATMOS}
    ${NOISE}
    uniform sampler2D tAlb, tNor, tSnowN; uniform float uTime, uLava; uniform vec4 uVents[5]; uniform vec4 uPad; uniform vec4 uPulse;
    varying vec3 vWP; varying vec3 vN; varying float vSh;
    vec3 tri(sampler2D t, vec3 p, vec3 n, float s){ vec3 w = pow(abs(n), vec3(4.0)); w /= (w.x+w.y+w.z);
      return texture2D(t,p.zy*s).rgb*w.x + texture2D(t,p.xz*s).rgb*w.y + texture2D(t,p.xy*s).rgb*w.z; }
    vec3 triN(sampler2D t, vec3 p, vec3 n, float s, float k){ vec3 w = pow(abs(n), vec3(4.0)); w /= (w.x+w.y+w.z);
      vec3 tx = texture2D(t,p.zy*s).xyz*2.0-1.0, ty = texture2D(t,p.xz*s).xyz*2.0-1.0, tz = texture2D(t,p.xy*s).xyz*2.0-1.0;
      tx.xy*=k; ty.xy*=k; tz.xy*=k;
      tx = vec3(tx.xy + n.zy, abs(tx.z)*n.x); ty = vec3(ty.xy + n.xz, abs(ty.z)*n.y); tz = vec3(tz.xy + n.xy, abs(tz.z)*n.z);
      return normalize(tx.zyx*w.x + ty.xzy*w.y + tz.xyz*w.z); }
    vec2 h2(vec2 p){ p = vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3))); return fract(sin(p) * 43758.5453); }
    // cellular crust: x = distance to the nearest cell edge, y = cell id, zw = cell centre offset
    vec4 crust(vec2 x){
      vec2 n = floor(x), f = fract(x), mg, mr; float md = 8.0;
      for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) { vec2 g = vec2(float(i), float(j)); vec2 r = g + h2(n + g) - f; float d = dot(r, r); if (d < md) { md = d; mr = r; mg = g; } }
      md = 8.0;
      for (int j = -2; j <= 2; j++) for (int i = -2; i <= 2; i++) { vec2 g = mg + vec2(float(i), float(j)); vec2 r = g + h2(n + g) - f; if (dot(mr - r, mr - r) > 1e-5) md = min(md, dot(0.5 * (mr + r), normalize(r - mr))); }
      return vec4(md, h2(n + mg + 3.7).x, mr);
    }
    // emission across a crack: white-yellow core → orange → deep red → black crust
    vec3 lavaRamp(float t){
      vec3 c = mix(vec3(0.0), vec3(0.55, 0.03, 0.005) * 2.5, smoothstep(0.0, 0.35, t));
      c = mix(c, vec3(1.0, 0.34, 0.04) * 4.5, smoothstep(0.35, 0.7, t));
      c = mix(c, vec3(1.0, 0.86, 0.55) * 9.0, smoothstep(0.8, 1.0, t));
      return c;
    }
    void main(){
      vec3 n = normalize(vN); vec3 p = vWP; float r = length(p.xz);
      float inside = smoothstep(${RIM + 30}.0, ${FLOOR_R}.0, r);
      float floorK = smoothstep(0.72, 0.95, inside) * smoothstep(0.82, 0.96, n.y);
      // pad around the plant (local box distance)
      vec2 dp = p.xz - uPad.xy; vec2 lp = abs(vec2(dp.x * uPad.z - dp.y * uPad.w, dp.x * uPad.w + dp.y * uPad.z));
      float padE = max(lp.x, lp.y) - ${(PAD.half).toFixed(1)};
      float hallE = max(lp.x - ${(0.8 * PLANT_S).toFixed(1)}, lp.y - ${(0.72 * PLANT_S).toFixed(1)});
      vec3 V = normalize(cameraPosition - p);
      vec3 rockA = tri(tAlb,p,n,0.019), rockB = tri(tAlb,p,n,0.0043);
      vec3 rock = mix(rockA, rockB, 0.5) * mix(vec3(0.42,0.43,0.47), vec3(0.36,0.31,0.28), inside);
      vec3 N = triN(tNor,p,n,0.019,1.3);
      // snow: only on gentle slopes and above the snow line, crisp edge, wind-scoured ridges
      float sn = snoise(p.xz*0.0035)*60.0 + snoise(p.xz*0.019)*14.0;
      float alt = smoothstep(470.0, 560.0, p.y + sn) * (1.0 - inside);
      float hi = smoothstep(900.0, 1700.0, p.y);
      float gentle = smoothstep(0.70 - hi * 0.22, 0.76 - hi * 0.2, n.y + snoise(p.xz*0.03)*0.04);
      float snow = alt * gentle;
      // sulphur staining and melt halos around the slope fumaroles
      float stain = 0.0;
      for(int i=0;i<5;i++){ vec4 v = uVents[i]; vec2 d = p.xz - v.xz; d.y = d.y > 0.0 ? d.y*0.35 : d.y*1.2; stain += exp(-dot(d,d)/(v.w*v.w)); }
      stain = clamp(stain, 0.0, 1.0);
      vec3 col = rock;
      float ash = clamp((1.0-snow) * smoothstep(620.0, 300.0, p.y + sn*0.5) * smoothstep(0.55, 0.85, n.y), 0.0, 1.0);
      col = mix(col, vec3(0.1, 0.094, 0.09), ash * 0.8);
      float streak = smoothstep(0.1, 0.9, snoise(vec2(p.x*0.06, p.z*0.007))*0.5+0.5);
      col = mix(col, mix(vec3(0.5,0.38,0.14), vec3(0.18,0.14,0.1), streak*0.6), stain*0.8*(1.0-inside));
      snow *= 1.0 - smoothstep(0.08, 0.6, stain);
      vec3 snowCol = mix(vec3(0.93,0.95,0.98), vec3(0.6,0.58,0.58), smoothstep(640.0, 470.0, p.y + sn));
      N = normalize(mix(N, triN(tSnowN,p,n,0.035,0.7), snow));
      col = mix(col, snowCol, snow);
      vec3 emit = vec3(0.0);
      float sunk = 0.0;
      // the crater floor: cracked basalt plates with lava in the seams
      if (floorK > 0.001) {
        vec2 q = p.xz / 30.0; q += vec2(snoise(q * 0.35), snoise(q * 0.35 + 5.1)) * 0.45;
        vec4 c1 = crust(q);
        vec4 c2 = crust(q * 3.1 + c1.y * 11.0);
        float activity = clamp(smoothstep(-0.05, 0.6, snoise(p.xz * 0.0045 + 1.7)) + exp(-pow(length(p.xz - vec2(-150.0, -45.0)) / 110.0, 2.0)), 0.0, 1.0) * smoothstep(-25.0, 50.0, padE);
        float w = mix(0.018, 0.075, smoothstep(-0.6, 0.8, snoise(p.xz * 0.02))) * (0.35 + 0.65 * activity);
        float t1 = 1.0 - smoothstep(0.0, w, c1.x);
        float t2 = (1.0 - smoothstep(0.0, w * 0.35, c2.x)) * 0.3 * smoothstep(0.2, 0.0, c1.x);
        float t = max(t1, t2) * activity;
        float flick = 0.85 + 0.15 * sin(uTime * 1.7 + c1.y * 40.0) * sin(uTime * 2.3 + p.x * 0.03);
        float pd = distance(p.xz, uPulse.xz); float ring = exp(-pow((pd - uPulse.w * 230.0) / 55.0, 2.0)) * exp(-uPulse.w * 0.9);
        // cooling crust: dark glassy basalt, faint glow mottling near the seams, some plates sunk
        sunk = step(0.72, c1.y);
        vec3 crustC = rockA * vec3(0.2, 0.18, 0.17) * (1.0 - sunk * 0.45);
        float mott = smoothstep(0.1, 0.8, snoise(p.xz * 0.11 + c1.y * 9.0) * 0.5 + 0.5) * exp(-c1.x / 0.12) * activity;
        col = mix(col, crustC, floorK);
        N = normalize(mix(N, normalize(N + vec3(c1.z, 0.0, c1.w) * (0.35 + sunk * 0.4)), floorK));
        emit = (lavaRamp(t) + vec3(0.9, 0.12, 0.02) * mott * 0.6) * flick * (1.0 + uLava * 1.2 + ring * 3.0) * floorK;
        col *= 1.0 - smoothstep(0.0, 1.0, t) * floorK;
      }
      // the plant pad: gravel, with contact darkening hugging the turbine hall
      float pad = 1.0 - smoothstep(-10.0, 30.0, padE);
      col = mix(col, rockB * vec3(0.24, 0.22, 0.21), pad);
      float ao = mix(0.25, 1.0, smoothstep(0.0, 26.0, hallE));
      float NV = max(dot(N, V), 0.0);
      float ndl = max(dot(N, sunDir), 0.0) * vSh;
      vec3 hemi = mix(vec3(0.05,0.045,0.045), skyTop*1.6 + vec3(0.025,0.03,0.04), N.y*0.5+0.5);
      vec3 lit = col * (sunCol*ndl + hemi) * ao;
      // back-lit rim light on ridgelines when the sun sits behind them
      float back = pow(max(dot(-V, sunDir), 0.0), 3.0);
      lit += sunCol * 0.55 * pow(1.0 - NV, 4.0) * back * vSh * (0.4 + snow);
      // snow: soft sheen and sparse crystal glints
      vec3 Hh = normalize(sunDir + V);
      float g = step(0.982, fract(sin(dot(floor(p*2.1), vec3(12.9898,78.233,37.719)))*43758.5453));
      lit += snow * vSh * (g * pow(max(dot(N,Hh),0.0), 40.0) * 5.0 + pow(max(dot(N,Hh),0.0), 12.0) * 0.08) * sunCol;
      // warm bounce from the lava lake onto the inner walls and the floor
      lit += col * vec3(1.0, 0.3, 0.07) * inside * (0.5 + uLava * 0.6) * (1.0 - N.y * 0.5) * 0.9;
      lit += emit;
      gl_FragColor = vec4(applyFog(lit, p), 1.0);
    }`,
  });
  const terrain = new THREE.Mesh(tg, terrMat); terrain.frustumCulled = false; scene.add(terrain);

  /* ---------- lights for the PBR plant + pipes ---------- */
  const sunL = new THREE.DirectionalLight(0xffb98a, 2.0); sunL.position.copy(SUN).multiplyScalar(1000); scene.add(sunL);
  scene.add(new THREE.HemisphereLight(0x55688f, 0x5a1c06, 0.7));
  const lavaL = new THREE.PointLight(0xff5a18, 26000, 700, 1.5); lavaL.position.set(-60, 140, -40); scene.add(lavaL);
  const lavaL2 = new THREE.PointLight(0xff4a10, 18000, 600, 1.5); lavaL2.position.set(170, 130, 40); scene.add(lavaL2);
  const plantL = new THREE.PointLight(0xff8a3c, 16000, 420, 1.4); plantL.position.copy(toWorld(0, -0.2, -1.6)); scene.add(plantL);

  /* ---------- geothermal plant (image-to-3D GLB), plinth sunk into the levelled floor ---------- */
  const glow = { value: 2.6 };
  const plant = gPlant.scene;
  plant.traverse(o => { if (o.isMesh) {
    const m = o.material; m.side = THREE.FrontSide; m.envMapIntensity = 0.6;
    m.onBeforeCompile = (s) => { s.uniforms.uGlow = glow;
      s.fragmentShader = s.fragmentShader.replace('void main() {', 'uniform float uGlow;\nvoid main() {').replace('#include <emissivemap_fragment>',
        `#include <emissivemap_fragment>
        float amber = smoothstep(0.25, 0.45, diffuseColor.r - diffuseColor.b) * smoothstep(0.42, 0.62, diffuseColor.r);
        totalEmissiveRadiance += vec3(1.0, 0.52, 0.18) * amber * uGlow;`); };
  } });
  plant.scale.setScalar(PLANT_S); plant.rotation.y = PLANT_ROT;
  plant.position.set(PAD.x, PAD.h - 2 + 0.27 * PLANT_S, PAD.z);
  scene.add(plant);

  /* steam pipelines from the wellheads, on low supports, diving into the ground at both ends */
  const pipeMat = new THREE.MeshStandardMaterial({ color: 0x3c3e41, metalness: 0.3, roughness: 0.7, envMapIntensity: 0.15 });
  const headMat = new THREE.MeshStandardMaterial({ color: 0x2a2523, metalness: 0.6, roughness: 0.5 });
  const beaconMat = new THREE.MeshBasicMaterial({ color: new THREE.Color(4, 0.5, 0.15) });
  const beacons = [];
  const supGeo = new THREE.CylinderGeometry(0.5, 0.7, 1, 6), sups = [];
  [[-300, -40], [-170, -210], [300, 120], [90, -250]].forEach(([x, z], k) => {
    const y0 = height(x, z), a = new THREE.Vector3(x, y0, z);
    const b = toWorld(k % 2 ? 0.98 : -0.98, -0.27, (k - 1.5) * 0.25);
    const pts = []; for (let i = 0; i <= 30; i++) { const t = i / 30, px = lerp(a.x, b.x, t), pz = lerp(a.z, b.z, t);
      const loop = Math.sin(t * Math.PI * 4) * 9 * smoothstep(0.1, 0.2, t) * (1 - smoothstep(0.8, 0.9, t)); const dx = b.z - a.z, dz = -(b.x - a.x), L = Math.hypot(dx, dz);
      const qx = px + dx / L * loop, qz = pz + dz / L * loop, gy = height(qx, qz);
      const lift = 4 * smoothstep(0.0, 0.06, t) * (1 - smoothstep(0.94, 1.0, t)) - 2.5;
      pts.push(new THREE.Vector3(qx, gy + lift, qz)); if (i % 3 === 1 && lift > 0) sups.push([qx, gy, qz, lift]); }
    const curve = new THREE.CatmullRomCurve3(pts);
    scene.add(new THREE.Mesh(new THREE.TubeGeometry(curve, 160, 1.4, 10, false), pipeMat));
    const head = new THREE.Mesh(new THREE.CylinderGeometry(3, 5, 10, 12), headMat); head.position.set(x, y0 + 3, z); scene.add(head);
    const bc = new THREE.Mesh(new THREE.SphereGeometry(1.1, 10, 8), beaconMat.clone()); bc.position.set(x, y0 + 9, z); scene.add(bc); beacons.push(bc);
  });
  { const im = new THREE.InstancedMesh(supGeo, headMat, sups.length); sups.forEach(([x, y, z, l], i) => im.setMatrixAt(i, new THREE.Matrix4().compose(new THREE.Vector3(x, y + l / 2, z), new THREE.Quaternion(), new THREE.Vector3(1, l + 1, 1)))); scene.add(im); }

  /* ---------- obsidian formations: screen-space refraction with per-channel dispersion ---------- */
  const sceneRT = new THREE.WebGLRenderTarget(2, 2, { type: THREE.HalfFloatType, samples: 0 });
  const obsMat = new THREE.ShaderMaterial({
    uniforms: { ...U, tScene: { value: sceneRT.texture }, uRes: { value: new THREE.Vector2(1, 1) } },
    vertexShader: `
      varying vec3 vN, vWP; varying vec4 vClip; varying vec3 vObj;
      void main(){
        mat4 m = modelMatrix;
        #ifdef USE_INSTANCING
          m = modelMatrix * instanceMatrix;
        #endif
        vec4 wp = m * vec4(position, 1.0); vWP = wp.xyz; vObj = position;
        vN = normalize(mat3(m) * normal);
        vClip = projectionMatrix * viewMatrix * wp; gl_Position = vClip;
      }`,
    fragmentShader: `
      precision highp float;
      ${ATMOS}
      uniform sampler2D tScene; uniform float uLava, uTime;
      varying vec3 vN, vWP; varying vec4 vClip; varying vec3 vObj;
      void main(){
        vec3 N = normalize(vN);
        // conchoidal fracture ripples: obsidian breaks in shell-like curves
        float rip = sin(dot(vObj, vec3(310.0, 170.0, 260.0)) + sin(vObj.y*420.0)*2.0);
        N = normalize(N + 0.05 * rip * normalize(cross(N, vec3(0.3,1.0,0.2))));
        vec3 V = normalize(cameraPosition - vWP);
        float NV = clamp(dot(N, V), 0.0, 1.0);
        float F = 0.045 + 0.955 * pow(1.0 - NV, 5.0);
        vec2 suv = vClip.xy / vClip.w * 0.5 + 0.5;
        vec3 vn = normalize((viewMatrix * vec4(N, 0.0)).xyz);
        vec3 vv = normalize((viewMatrix * vec4(-V, 0.0)).xyz);
        float thick = mix(1.0, 0.22, pow(1.0 - NV, 1.6));
        vec3 rr = refract(vv, vn, 1.0/1.46), rg = refract(vv, vn, 1.0/1.50), rb = refract(vv, vn, 1.0/1.555);
        float k = 0.16 * thick;
        vec3 tr = vec3(texture2D(tScene, suv + rr.xy*k).r, texture2D(tScene, suv + rg.xy*k).g, texture2D(tScene, suv + rb.xy*k).b);
        // smoky volcanic glass: thick cores go black, thin edges pass tinted light
        vec3 absorb = exp(-vec3(1.5, 1.8, 2.0) * thick * thick * 1.4) * vec3(0.9, 0.85, 0.8);
        vec3 trans = tr * absorb;
        vec3 R = reflect(-V, N);
        vec3 refl = skyColor(R) + sunCol * 9.0 * pow(max(dot(R, sunDir), 0.0), 500.0);
        float crater = smoothstep(620.0, 320.0, length(vWP.xz)) * (1.0 - smoothstep(0.0, 420.0, vWP.y));
        refl += vec3(1.0, 0.3, 0.06) * (max(-R.y, 0.0) * 3.0 + 0.4) * (0.7 + uLava) * crater;
        // rainbow-obsidian sheen (thin-film interference), strongest at grazing angles
        vec3 film = 0.5 + 0.5 * cos(6.2831 * (NV * 2.2 + vec3(0.0, 0.33, 0.67)));
        vec3 c = mix(trans, refl * 1.3, F) + film * F * 0.25 + sunCol * 2.0 * pow(max(dot(reflect(-V, normalize(vN)), sunDir), 0.0), 80.0);
        gl_FragColor = vec4(applyFog(c, vWP), 1.0);
      }`,
  });
  const shardGeos = [gShardA, gShardB].map(g => { let geo; g.scene.traverse(o => { if (o.isMesh && !geo) geo = o.geometry; }); geo.computeBoundingBox(); return geo; });
  const CLUSTERS = [[-160, -1200, 5], [190, -1020, 4], [-110, -820, 5], [40, -760, 4], [-230, -320, 5], [250, -30, 4], [-330, 40, 3], [150, 330, 3], [-320, -1900, 4]];
  const rnd = (() => { let s = 7; return () => (s = (s * 16807) % 2147483647) / 2147483647; })();
  const perGeo = [[], []];
  CLUSTERS.forEach(([cx, cz, n]) => { for (let i = 0; i < n; i++) {
    const x = cx + (rnd() - 0.5) * 80, z = cz + (rnd() - 0.5) * 80, s = 420 + rnd() * 560;
    const m = new THREE.Matrix4().compose(new THREE.Vector3(x, height(x, z) - 6, z),
      new THREE.Quaternion().setFromEuler(new THREE.Euler((rnd() - 0.5) * 0.5, rnd() * 6.28, (rnd() - 0.5) * 0.5)),
      new THREE.Vector3(s * 0.55, s * (2.2 + rnd() * 1.8), s * 0.7));
    perGeo[i % 2].push(m); } });
  const obsidian = shardGeos.map((g, i) => { const im = new THREE.InstancedMesh(g, obsMat, perGeo[i].length); perGeo[i].forEach((m, j) => im.setMatrixAt(j, m)); im.layers.set(1); im.frustumCulled = false; scene.add(im); return im; });

  /* ---------- steam plumes: tiered GPU particles ---------- */
  addStep('steam', `Steam · ${(T.steam / 1000) | 0}k particles · ${tier} tier`);
  const wsum = VENTS.reduce((s, v) => s + Math.pow(v[2], 1.25), 0);
  const sp = new Float32Array(T.steam * 3), sx = new Float32Array(T.steam * 2);
  { let o = 0; VENTS.forEach((v, vi) => { const n = vi === VENTS.length - 1 ? T.steam - o : Math.round(T.steam * Math.pow(v[2], 1.25) / wsum);
      for (let i = 0; i < n && o < T.steam; i++, o++) { sp[o * 3] = Math.random(); sp[o * 3 + 1] = Math.random(); sp[o * 3 + 2] = Math.random(); sx[o * 2] = Math.random(); sx[o * 2 + 1] = vi; } }); }
  const steamG = new THREE.BufferGeometry();
  steamG.setAttribute('position', new THREE.BufferAttribute(sp, 3)); steamG.setAttribute('aX', new THREE.BufferAttribute(sx, 2));
  const steamMat = new THREE.ShaderMaterial({
    uniforms: { ...U, uVP: { value: ventP }, uVQ: { value: ventQ }, uScale: { value: 800 }, uFocus: { value: 120 }, uWind: { value: new THREE.Vector3(0.55, 0, 0.25) } },
    transparent: true, depthWrite: false, blending: THREE.NormalBlending,
    vertexShader: `
      ${ATMOS}
      attribute vec2 aX; uniform vec4 uVP[10]; uniform vec4 uVQ[10]; uniform float uTime, uScale, uFocus, uLava; uniform vec3 uWind; uniform vec4 uPulse;
      varying float vA; varying vec3 vC; varying float vF; varying vec3 vFC;
      void main(){
        int vi = int(aX.y + 0.5); vec4 v = uVP[vi]; float hot = uVQ[vi].x; float H = v.w;
        vec3 s = position; float s4 = aX.x;
        float life = fract(uTime * (0.035 + s.x*0.03) * (130.0 / H + 0.3) + s.y);
        float ang = s.z * 6.2831853, rad = sqrt(s4);
        vec3 p = v.xyz;
        float spread = mix(0.05, 0.5, pow(life, 0.8)) * H;
        p.y += life * H * 1.7;
        p.xz += vec2(cos(ang), sin(ang)) * rad * spread;
        float bt = uTime * 0.25;
        p += vec3(sin(p.y*0.021 + bt + s.x*6.0), 0.0, cos(p.y*0.017 - bt + s.y*6.0)) * H * 0.2 * life;
        p += uWind * life * life * H * 1.4;
        // seismic ripple: a ring that shoves the plume outward and up
        float d = distance(p.xz, uPulse.xz), ring = uPulse.w * 230.0;
        float kk = exp(-pow((d - ring)/48.0, 2.0)) * exp(-uPulse.w * 1.1);
        p.xz += normalize(p.xz - uPulse.xz + 0.001) * kk * 26.0; p.y += kk * 16.0;
        vec4 mv = viewMatrix * vec4(p, 1.0);
        gl_Position = projectionMatrix * mv;
        float dist = max(-mv.z, 1.0);
        float coc = clamp(abs(dist - uFocus) / dist, 0.0, 2.0);
        float wsize = mix(0.12, 0.42, life) * (0.5 + s.x) * H * 0.16 + 1.5;
        gl_PointSize = clamp(wsize * uScale / dist * (1.0 + coc * 0.9), 1.0, 90.0);
        float env = smoothstep(0.0, 0.07, life) * (1.0 - life) * (1.0 - life);
        vA = env * mix(0.085, 0.04, smoothstep(620.0, 320.0, length(p.xz))) / (1.0 + coc * 1.6);
        vec3 toP = normalize(p - cameraPosition);
        float fwd = pow(max(dot(toP, sunDir), 0.0), 5.0);
        vec3 lit = mix(skyTop * 1.4 + vec3(0.16, 0.15, 0.15), sunCol * 0.42, smoothstep(0.0, 1.0, life*0.8 + 0.25));
        lit *= 1.0 + fwd * 3.5 * (1.0 - uDesc * 0.6);
        float crater = smoothstep(620.0, 320.0, length(p.xz));
        lit *= 1.0 - crater * 0.85;
        lit += vec3(1.0, 0.33, 0.08) * hot * pow(1.0 - life, 2.5) * 3.2 * (1.0 + uLava * 1.5);
        lit += vec3(1.0, 0.3, 0.07) * crater * (1.0 - smoothstep(20.0, 300.0, p.y)) * 0.9 * (1.0 + uLava * 1.5);
        vC = lit;
        vF = fogAmount(p, vFC);
      }`,
    fragmentShader: `
      varying float vA; varying vec3 vC; varying float vF; varying vec3 vFC;
      void main(){ vec2 q = gl_PointCoord*2.0-1.0; float r2 = dot(q,q); if (r2 > 1.0) discard;
        float a = vA * exp(-r2 * 3.2); gl_FragColor = vec4(mix(vC, vFC, vF*0.85), a); }`,
  });
  const steam = new THREE.Points(steamG, steamMat); steam.frustumCulled = false; steam.layers.set(2); scene.add(steam);
  doneStep('steam'); progress(0.64);

  /* ---------- snow that turns to ash (and embers) as you descend ---------- */
  const fp = new Float32Array(T.snow * 3), fs = new Float32Array(T.snow);
  for (let i = 0; i < T.snow; i++) { fp[i * 3] = Math.random(); fp[i * 3 + 1] = Math.random(); fp[i * 3 + 2] = Math.random(); fs[i] = Math.random(); }
  const flakeG = new THREE.BufferGeometry(); flakeG.setAttribute('position', new THREE.BufferAttribute(fp, 3)); flakeG.setAttribute('aS', new THREE.BufferAttribute(fs, 1));
  const flakeMat = new THREE.ShaderMaterial({
    uniforms: { ...U, uCam: { value: new THREE.Vector3() }, uBox: { value: 150 }, uScale: { value: 800 }, uLight: { value: 1 } },
    transparent: true, depthWrite: false,
    vertexShader: `
      attribute float aS; uniform vec3 uCam; uniform float uTime, uBox, uAsh, uScale, uLava; uniform vec4 uPulse;
      varying float vA; varying vec3 vC;
      void main(){
        float ember = step(0.984, aS) * smoothstep(0.5, 0.9, uAsh);
        vec3 b = position * uBox;
        float fall = mix(7.5, 2.6, uAsh) * (0.6 + aS * 0.8);
        b.y -= uTime * fall * (1.0 - ember * 2.4);
        b.x += sin(uTime * 0.6 + aS * 30.0) * 3.0 + uTime * mix(5.0, 1.5, uAsh);
        b.z += cos(uTime * 0.45 + aS * 17.0) * 3.0;
        vec3 p = mod(b - uCam, uBox) - uBox * 0.5 + uCam;
        p.y += exp(-uPulse.w * 3.0) * sin(uTime * 40.0 + aS * 9.0) * 0.6;
        vec4 mv = viewMatrix * vec4(p, 1.0);
        gl_Position = projectionMatrix * mv;
        float d = max(-mv.z, 0.5);
        float coc = clamp(abs(d - 22.0) / d, 0.0, 3.0);
        float ws = mix(0.11, 0.07, uAsh) * (0.6 + aS * 0.9) * (1.0 + ember * 0.3);
        gl_PointSize = clamp(ws * uScale / d * (1.0 + coc * 0.9 * (1.0 - ember*0.7)), 1.0, mix(26.0, 9.0, ember));
        vA = 0.7 / (1.0 + coc * 3.0) * smoothstep(uBox * 0.5, uBox * 0.3, length(p - uCam)) * smoothstep(3.0, 9.0, d);
        vec3 ash = mix(vec3(0.38, 0.36, 0.34), vec3(0.1, 0.09, 0.085), fract(aS * 7.31));
        vC = mix(vec3(1.25, 1.22, 1.2), ash, uAsh);
        vC = mix(vC, vec3(7.0, 1.9, 0.35) * (1.0 + uLava), ember);
        vA = mix(vA, 1.0, ember);
      }`,
    fragmentShader: `varying float vA; varying vec3 vC; void main(){ vec2 q = gl_PointCoord*2.0-1.0; float r2 = dot(q,q); if (r2>1.0) discard; gl_FragColor = vec4(vC, vA * (1.0 - r2)); }`,
  });
  const flakes = new THREE.Points(flakeG, flakeMat); flakes.frustumCulled = false; flakes.layers.set(2); scene.add(flakes);

  /* ---------- the camera journey: one designed shot per section, eased so the camera settles on each ---------- */
  const SHOTS = [ // position, look target — one per stop
    [-380, 1190, -2600, 330, 1010, -1430],    // snowfield: wide, sun just behind the eastern ridge, long shadows
    [-10, 1045, -1700, -230, 880, -1180],    // slope: fumaroles in the foreground
    [150, 870, -1240, -60, 600, -700],       // lower slope: obsidian midground
    [30, 775, -640, 0, 20, 60],              // rim: looking down into the crater
    [250, 340, -300, -70, 20, 110],          // inner wall
    [-235, 72, -150, -140, 14, -20],         // floor: low and close on the cracks
    [-235, 52, -45, 70, 76, 110],            // the plant: hero wide
  ];
  const posC = new THREE.CatmullRomCurve3(SHOTS.map(p => new THREE.Vector3(p[0], p[1], p[2])), false, 'centripetal');
  const lookC = new THREE.CatmullRomCurve3(SHOTS.map(p => new THREE.Vector3(p[3], p[4], p[5])), false, 'centripetal');
  const _p = new THREE.Vector3(), _l = new THREE.Vector3();
  function shotU(t) { // scroll progress to curve parameter, easing in and out of every stop
    if (t >= STOPS[6]) return 1;
    let i = 0; while (i < 5 && t >= STOPS[i + 1]) i++;
    const f = clamp((t - STOPS[i]) / (STOPS[i + 1] - STOPS[i]), 0, 1);
    return (i + lerp(f, f * f * (3 - 2 * f), 0.75)) / 6;
  }
  function pose(t, outP, outL) { const u = shotU(clamp(t, 0, 1)); posC.getPoint(u, outP); lookC.getPoint(u, outL); outP.y = Math.max(outP.y, height(outP.x, outP.z) + 16); return outP; }
  const Y0 = pose(0, _p, _l).y, Y1 = pose(1, _p, _l).y;

  /* panel anchors: a point in the world beside each designed shot */
  const panels = $$('.panel');
  const anchors = panels.map((el, k) => { const t = STOPS[k + 1], side = +el.dataset.side;
    const P = pose(t, new THREE.Vector3(), new THREE.Vector3()); const L = lookC.getPoint(shotU(t), new THREE.Vector3());
    const f = L.clone().sub(P).normalize(), r = new THREE.Vector3().crossVectors(f, new THREE.Vector3(0, 1, 0)).normalize();
    return P.clone().addScaledVector(f, 92).addScaledVector(r, side * 34).add(new THREE.Vector3(0, 3, 0)); });

  /* ---------- post: bloom → haze + DOF + CA + ACES + grade + grain ---------- */
  const rt = new THREE.WebGLRenderTarget(innerWidth * dpr, innerHeight * dpr, { type: THREE.HalfFloatType, depthTexture: new THREE.DepthTexture(1, 1, THREE.UnsignedIntType) });
  const composer = new EffectComposer(renderer, rt);
  composer.setPixelRatio(dpr); composer.setSize(innerWidth, innerHeight);
  const renderPass = new RenderPass(scene, camera); composer.addPass(renderPass);
  const bloom = new UnrealBloomPass(new THREE.Vector2(innerWidth, innerHeight), 0.55, 0.6, 1.7); composer.addPass(bloom);
  const grade = new ShaderPass({
    uniforms: { tDiffuse: { value: null }, tDepth: { value: null }, uRes: { value: new THREE.Vector2() }, uTime: { value: 0 }, uHaze: { value: 0 }, uFocus: { value: 120 },
      uAperture: { value: 0.5 }, uFlash: { value: 0 }, uExposure: { value: 1 }, cameraNear: { value: camera.near }, cameraFar: { value: camera.far }, uDesc: { value: 0 } },
    vertexShader: `varying vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }`,
    fragmentShader: `
      precision highp float;
      uniform sampler2D tDiffuse, tDepth; uniform vec2 uRes; uniform float uTime, uHaze, uFocus, uAperture, uFlash, uExposure, cameraNear, cameraFar, uDesc;
      varying vec2 vUv;
      float linD(float d){ float z = d*2.0-1.0; return 2.0*cameraNear*cameraFar/(cameraFar+cameraNear - z*(cameraFar-cameraNear)); }
      vec3 aces(vec3 x){ return clamp((x*(2.51*x+0.03))/(x*(2.43*x+0.59)+0.14), 0.0, 1.0); }
      float h12(vec2 p){ return fract(sin(dot(p, vec2(12.9898,78.233)))*43758.5453); }
      void main(){
        vec2 uv = vUv;
        // heat haze: shimmer rises off hot (red-dominant) pixels below this one
        vec3 below = texture2D(tDiffuse, uv - vec2(0.0, 0.03)).rgb;
        float heat = clamp((below.r - below.b*1.4) * 0.5, 0.0, 1.5) * uHaze;
        uv += vec2(sin(uv.y*95.0 - uTime*5.5 + sin(uv.x*37.0)*2.0), cos(uv.x*71.0 + uTime*4.3)) * 0.0022 * heat;
        // depth of field: 16-tap golden-angle gather sized by circle of confusion
        float dep = linD(texture2D(tDepth, uv).x);
        float coc = clamp(abs(dep - uFocus) / dep * uAperture, 0.0, 1.0);
        vec3 blur = vec3(0.0);
        for (int i = 0; i < 16; i++){ float fi = float(i); float a = fi*2.39996; float r = sqrt(fi+0.5)/4.0;
          blur += texture2D(tDiffuse, uv + vec2(cos(a), sin(a)) * r * coc * 9.0 / uRes).rgb; }
        blur /= 16.0;
        vec2 dir = uv - 0.5; float ca = 0.0016;
        vec3 sharp = vec3(texture2D(tDiffuse, uv + dir*ca).r, texture2D(tDiffuse, uv).g, texture2D(tDiffuse, uv - dir*ca).b);
        vec3 col = mix(sharp, blur, smoothstep(0.04, 0.35, coc));
        col *= uExposure;
        col += uFlash * vec3(1.0, 0.45, 0.15) * 0.25;
        col = aces(col);
        // grade: cool shadows on the snowfield, warmer blacks in the crater
        float l = dot(col, vec3(0.2126, 0.7152, 0.0722));
        col = mix(col, col * mix(vec3(0.92, 0.98, 1.08), vec3(1.08, 0.96, 0.88), uDesc), 1.0 - l);
        col = pow(col, vec3(1.0/2.2));
        float vig = smoothstep(1.15, 0.35, length((vUv - 0.5) * vec2(1.0, 0.85)));
        col *= mix(0.62, 1.0, vig);
        col += (h12(vUv * uRes + fract(uTime) * 91.7) - 0.5) * 0.045;
        gl_FragColor = vec4(col, 1.0);
      }`,
  });
  composer.addPass(grade);

  /* ---------- sizing ---------- */
  function resize() {
    const w = innerWidth, h = innerHeight;
    camera.aspect = w / h; camera.fov = w < h ? 64 : 50; camera.updateProjectionMatrix();
    renderer.setPixelRatio(dpr); renderer.setSize(w, h, false);
    composer.setPixelRatio(dpr); composer.setSize(w, h);
    sceneRT.setSize(Math.round(w * dpr * 0.5), Math.round(h * dpr * 0.5));
    obsMat.uniforms.uRes.value.set(w, h);
    grade.uniforms.uRes.value.set(w * dpr, h * dpr);
    const s = (h * dpr * 0.5) / Math.tan(THREE.MathUtils.degToRad(camera.fov * 0.5));
    steamMat.uniforms.uScale.value = s; flakeMat.uniforms.uScale.value = s;
  }
  resize();
  addEventListener('resize', resize);

  /* ---------- prewarm: compile every program, render warm frames ---------- */
  addStep('compile', 'Shaders · compile + prewarm');
  pose(0, camera.position, _l); camera.lookAt(_l);
  camera.layers.enableAll();
  await renderer.compileAsync(scene, camera);
  doneStep('compile', `${renderer.info.programs.length} programs`); progress(0.88);
  addStep('warm', 'First frames · post stack');

  /* ---------- state ---------- */
  const clock = new THREE.Clock();
  let prog = 0, progT = 0, time = 0, pulseT = 99, pulseMag = 0, shake = 0;
  const mouse = { x: 0, y: 0, sx: 0, sy: 0 };
  const read = { depth: $('#r-depth'), temp: $('#r-temp'), press: $('#r-press'), sec: $('#r-sec'), prog: $('#r-prog'), coord: $('#r-coord'), mk: $('#gauge-mk'), tempW: $('#r-temp-w') };
  const navLinks = $$('.nav a[data-go]');
  let lastHud = 0, activeIdx = -1, frameMs = 16, slowFor = 0;
  const panelState = panels.map(() => ({ live: false }));
  const scrollMax = () => Math.max(1, document.documentElement.scrollHeight - innerHeight);
  const readScroll = () => { progT = clamp(scrollY / scrollMax(), 0, 1); };
  addEventListener('scroll', readScroll, { passive: true });

  goTo = (i, focus) => {
    const y = STOPS[i] * scrollMax();
    const far = Math.abs(scrollY - y) > innerHeight * 4;
    window.scrollTo({ top: y + (i ? 2 : 0), behavior: far ? 'auto' : 'smooth' });
    if (far) prog = progT = STOPS[i];
    if (focus && i) panels[i - 1].querySelector('h2').focus({ preventScroll: true });
  };
  /* keyboard users: tabbing into a panel flies the camera to it */
  panels.forEach((p, k) => p.addEventListener('focusin', () => { if (Math.abs(progT - STOPS[k + 1]) > 0.03) goTo(k + 1); }));

  addEventListener('pointermove', (e) => { mouse.x = e.clientX / innerWidth * 2 - 1; mouse.y = e.clientY / innerHeight * 2 - 1; }, { passive: true });

  /* ---------- seismic pulse ---------- */
  const evEl = $('#event'); let evTimer = 0, quakeN = 0;
  function pulse(clientX, clientY) {
    let origin = null;
    if (clientX != null) { // march the view ray against the height field
      const ndc = new THREE.Vector2(clientX / innerWidth * 2 - 1, -(clientY / innerHeight) * 2 + 1);
      const ray = new THREE.Raycaster(); ray.setFromCamera(ndc, camera);
      const o = ray.ray.origin, d = ray.ray.direction; let t = 0;
      for (let i = 0; i < 400; i++) { t += 6 + t * 0.02; const x = o.x + d.x * t, y = o.y + d.y * t, z = o.z + d.z * t; if (y < height(x, z)) { origin = new THREE.Vector3(x, y, z); break; } }
    }
    if (!origin) { const f = new THREE.Vector3(); camera.getWorldDirection(f); origin = camera.position.clone().addScaledVector(f, 220); origin.y = height(origin.x, origin.z); }
    U.uPulse.value.set(origin.x, origin.y, origin.z, 0);
    pulseT = 0; pulseMag = 1.6 + Math.random() * 1.1; shake = 1;
    Sound.thump(0.6 + (pulseMag - 1.6));
    quakeN++;
    evEl.textContent = `SEISMIC EVENT ${String(quakeN).padStart(3, '0')} · M${pulseMag.toFixed(1)} · ${Math.round(origin.distanceTo(camera.position))} M AWAY`;
    evEl.classList.add('on'); clearTimeout(evTimer); evTimer = setTimeout(() => evEl.classList.remove('on'), 2600);
    $('#hint').style.opacity = 0;
  }
  canvas.addEventListener('click', (e) => pulse(e.clientX, e.clientY));
  $('#pulse-btn').addEventListener('click', () => pulse(innerWidth / 2, innerHeight * 0.62));
  addEventListener('keydown', (e) => { if ((e.key === 'p' || e.key === 'P') && !e.target.closest('input,textarea,select') && !e.metaKey && !e.ctrlKey) pulse(innerWidth / 2, innerHeight * 0.62); });

  /* ---------- per-frame ---------- */
  const fwd = new THREE.Vector3(), right = new THREE.Vector3(), tmp = new THREE.Vector3(), up = new THREE.Vector3(0, 1, 0);
  const fogTop = new THREE.Color(0.58, 0.56, 0.62), fogLow = new THREE.Color(0.12, 0.075, 0.06);
  const narrow = () => innerWidth < 720;
  const hero = $('#hero');
  let running = true;

  function frame() {
    if (!running) return;
    const dt = Math.min(clock.getDelta(), 0.05); time += dt;
    frameMs += (dt * 1000 - frameMs) * 0.05;
    // adaptive resolution: drop pixel ratio when frames stay slow
    if (frameMs > 26 && !CAPTURE) { slowFor += dt; if (slowFor > 1.5 && dpr > 0.65) { dpr = Math.max(0.65, dpr - 0.2); resize(); slowFor = 0; } } else slowFor = 0;

    prog += (progT - prog) * (1 - Math.exp(-dt * 3.2));
    const d = prog;
    pose(d, camera.position, _l);
    // breathing drift + pointer parallax + quake shake
    mouse.sx += (mouse.x - mouse.sx) * 0.04; mouse.sy += (mouse.y - mouse.sy) * 0.04;
    camera.position.y += Math.sin(time * 0.6) * 0.8;
    pulseT += dt; shake *= Math.exp(-dt * 2.6);
    const sh = shake * shake * 3.2;
    camera.position.x += (Math.sin(time * 37) + Math.sin(time * 23.7)) * sh; camera.position.y += Math.sin(time * 41.3) * sh;
    camera.lookAt(_l);
    fwd.subVectors(_l, camera.position).normalize(); right.crossVectors(fwd, up).normalize();
    camera.rotateY(-mouse.sx * 0.035); camera.rotateX(-mouse.sy * 0.025);

    // world response to depth
    const desc = smoothstep(0.25, 0.85, d);
    U.uTime.value = time; U.uDesc.value = desc; U.uAsh.value = smoothstep(0.22, 0.6, d);
    U.uLava.value = 1.6 * pulseMag / 2 * Math.exp(-pulseT * 1.4) * (pulseT < 20 ? 1 : 0);
    U.uPulse.value.w = pulseT;
    U.fogCol.value.copy(fogLow);
    U.fogDensity.value = lerp(0.00032, 0.0010, desc);
    U.fogFalloff.value = lerp(0.0011, 0.004, desc);
    const lf = (1 + U.uLava.value) * (0.9 + 0.1 * Math.sin(time * 3.1));
    lavaL.intensity = 9000 * lf; lavaL2.intensity = 6000 * lf; plantL.intensity = 6000 * (0.95 + 0.05 * lf);
    sunL.intensity = lerp(2.0, 0.15, desc);
    glow.value = 2.6 * (0.92 + 0.08 * Math.sin(time * 1.7));
    beacons.forEach((b, i) => { b.visible = ((time + i * 0.37) % 1.6) < 0.25; });
    flakeMat.uniforms.uCam.value.copy(camera.position);

    // panels: project each anchor into the screen and let it ride past the camera
    let nearest = 0, nd = 9;
    STOPS.forEach((s, i) => { const dd = Math.abs(d - s); if (dd < nd) { nd = dd; nearest = i; } });
    let focus = lerp(1400, 160, smoothstep(0.0, 0.2, d));
    panels.forEach((el, k) => {
      const t = STOPS[k + 1], gap = d - t, last = k === panels.length - 1;
      let vis = 1 - smoothstep(0.035, 0.075, Math.abs(gap));
      if (last && gap > 0) vis = 1;
      const ps = panelState[k];
      tmp.copy(anchors[k]); const dist = tmp.distanceTo(camera.position); tmp.project(camera);
      if (tmp.z > 1) vis = 0;
      if (vis > 0.001) {
        const w = el.offsetWidth, h = el.offsetHeight, side = +el.dataset.side;
        let sx = (tmp.x * 0.5 + 0.5) * innerWidth, sy = (-tmp.y * 0.5 + 0.5) * innerHeight;
        let sc = clamp(95 / dist, 0.72, 1.12), x, y;
        if (narrow()) { sc = clamp(0.92 + (sc - 0.9) * 0.3, 0.9, 1.02); x = (innerWidth - w) / 2; y = clamp(innerHeight - h - 22 + (sy - innerHeight * 0.5) * 0.08, 110, innerHeight - h - 12); }
        else { const sw = w * sc, shh = h * sc, minX = innerWidth > 1100 ? 104 : 24; x = side > 0 ? sx + 18 : sx - sw - 18; y = sy - shh * 0.5; x = clamp(x, minX, innerWidth - sw - 24); y = clamp(y, 76, Math.max(76, innerHeight - shh - 96)); }
        el.style.transform = `translate3d(${x.toFixed(1)}px, ${y.toFixed(1)}px, 0) scale(${sc.toFixed(3)})`;
        el.style.transformOrigin = '0 0';
        if (vis > 0.5) focus = dist;
      }
      el.style.opacity = vis.toFixed(3);
      const live = vis > 0.6;
      if (live !== ps.live) { ps.live = live; el.classList.toggle('live', live);
        if (live) { scramble(el.querySelector('h2')); $$('[data-count]', el).forEach(countUp); } }
    });
    // hero
    const heroO = 1 - smoothstep(0.012, 0.06, d);
    hero.style.opacity = heroO.toFixed(3); hero.style.visibility = heroO < 0.01 ? 'hidden' : 'visible';
    hero.style.transform = `translate3d(0, ${(-d * 900).toFixed(1)}px, 0)`;

    // DOF focus follows the panel in view, else rides ahead
    const gu = grade.uniforms;
    gu.uFocus.value += (focus - gu.uFocus.value) * 0.08;
    steamMat.uniforms.uFocus.value = gu.uFocus.value;
    gu.uAperture.value = narrow() ? 0.18 : 0.26;
    gu.uTime.value = time; gu.uDesc.value = desc;
    gu.uHaze.value = smoothstep(0.55, 0.9, d) * (1 + U.uLava.value);
    gu.uFlash.value = Math.exp(-pulseT * 6) * (pulseT < 5 ? 1 : 0);
    gu.uExposure.value = lerp(0.82, 1.25, desc);
    gu.tDepth.value = composer.readBuffer.depthTexture;

    // render: opaque world (no glass, no particles) → refraction buffer, then the full frame
    camera.layers.set(0);
    renderer.setRenderTarget(sceneRT); renderer.render(scene, camera); renderer.setRenderTarget(null);
    camera.layers.enableAll();
    composer.render(dt);

    // HUD at ~15 Hz
    if (time - lastHud > 0.066) { lastHud = time;
      const depthM = Math.max(0, Y0 - camera.position.y + 0) * (1100 / (Y0 - Y1));
      const near = clamp(1 - camera.position.y / 600, 0, 1);
      const temp = lerp(-14, 9, smoothstep(0.0, 0.45, d)) + lerp(0, 52, smoothstep(0.45, 1, d)) + near * 6 + U.uLava.value * 9 + Math.sin(time * 1.3) * 0.25;
      const elev = 2380 - depthM;
      const press = 101.325 * Math.exp(-elev / 8434) + Math.sin(time * 0.9) * 0.04 + U.uLava.value * 0.6;
      read.depth.innerHTML = `${Math.round(depthM).toLocaleString('en-US')}<small>m</small>`;
      read.temp.innerHTML = `${temp < 0 ? '−' : '+'}${Math.abs(temp).toFixed(1)}<small>°C</small>`;
      read.tempW.classList.toggle('hot', temp > 30);
      read.press.innerHTML = `${press.toFixed(1)}<small>kPa</small>`;
      read.prog.style.transform = `scaleX(${d.toFixed(4)})`;
      read.mk.style.top = `${(clamp(depthM / 1100, 0, 1) * 100).toFixed(2)}%`;
      const hdg = (Math.atan2(fwd.x, -fwd.z) * 180 / Math.PI + 360) % 360;
      read.coord.textContent = `N 64°${String(2 + Math.floor(d * 3)).padStart(2, '0')}′${String(Math.floor(11 + d * 40) % 60).padStart(2, '0')}″ · W 017°19′40″ · HDG ${Math.round(hdg).toString().padStart(3, '0')}°`;
      if (nearest !== activeIdx) { activeIdx = nearest; read.sec.textContent = `${String(nearest).padStart(2, '0')} / 06 — ${SEC_NAMES[nearest]}`;
        navLinks.forEach(a => a.setAttribute('aria-current', String(+a.dataset.go === nearest && nearest > 0))); }
      $('#hint').style.opacity = d > 0.04 ? 0 : '';
      Sound.setDepth(d);
    }
    if (!CAPTURE) requestAnimationFrame(frame);
  }
  document.addEventListener('visibilitychange', () => { if (document.hidden) running = false; else if (!running) { running = true; clock.getDelta(); if (!CAPTURE) requestAnimationFrame(frame); } });

  // warm frames: let the post stack and refraction buffer allocate before reveal
  readScroll(); prog = progT;
  for (let i = 0; i < 3; i++) { await new Promise(r => requestAnimationFrame(r)); camera.layers.set(0); renderer.setRenderTarget(sceneRT); renderer.render(scene, camera); renderer.setRenderTarget(null); camera.layers.enableAll(); grade.uniforms.tDepth.value = composer.readBuffer.depthTexture; composer.render(0.016); progress(0.88 + 0.04 * (i + 1)); }
  doneStep('warm'); progress(1);
  requestAnimationFrame(frame);

  /* ---------- reveal ---------- */
  const loader = $('#loader');
  await new Promise(r => setTimeout(r, 350));
  loader.classList.add('ready');
  $('#go-sound').focus({ preventScroll: true });
  const enter = (withSound) => {
    if (!root.classList.contains('loading')) return;
    root.classList.remove('loading'); loader.classList.add('out'); loader.setAttribute('aria-hidden', 'true');
    if (withSound) { Sound.setMute(false); Sound.start(); } else Sound.setMute(true);
    setTimeout(() => { loader.hidden = true; }, 950);
  };
  $('#go-sound').addEventListener('click', () => enter(true));
  $('#go-quiet').addEventListener('click', () => enter(false));
  window.__caldera = { enter, pulse, goTo, renderAt(p, t) { progT = prog = p; if (t != null) time = t; frame(); }, get prog() { return prog; }, tier, steam: T.steam, renderer };
}
</script>
</body>
</html>

````
