GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / kuiper-belt / see-through/202611020012

Descent (part 2)

A JavaScript file in the see through folder of Kuiper Belt that maps wafer meta and sat s, using Web Mercator and haversine, and uses data from the GridAtlas repository.

700 lines of JavaScript from kuiper-belt, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1544 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Descent geodesy · kuiper-belt / see-through/202611020012/descent.js lines 1–700

Descent

A JavaScript file in the see through folder of Kuiper Belt that maps wafer meta and sat s, using Web Mercator and haversine, and uses data from the GridAtlas repository.

geodesykuiper-belt / see-through/202611020012/descent.js · lines 1–700 of 1231 · version 2026-11-02 00:12 · Entry point · pattern nearestToCentre (shared by 2 files)

What it does
It maps wafer meta, sat s and l sat. Defines 84 functions or classes, including loadScript, ensureGridData, merc, unmercLat, decode. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: 400kV, 132kV, 76kV, 27kV, 22kV, 8kV.
Inputs & outputs
In: data source: gridatlas data; JSON file style.json; GeoJSON file kv.geojson; JSON file wafer-meta.json; browser storage (getItem). Out: interactive map; canvas drawing. Coordinate systems named: Web Mercator / EPSG:3857. Voltage levels named: 400kV, 132kV, 76kV, 27kV, 22kV, 8kV.
Downstream impact
Used directly by 1 file: Kuiper Belt — See Through Page (kuiper-belt, https://ventusltd.github.io/kuiper-belt/see-through/202610050513/).
What it achieves
It loads script (`loadScript`), decodes lines (`decodeLines`) and places ui (`placeUI`). `descent.js` SEE THROUGH, a LEARN THE KUIPER module (id 'descent'). Its code works with 400 kV and 132 kV. It reads `../../cosmos/wafer-meta.json`. It responds to pointerdown, pointerenter and pointerleave events.
Why it matters
Loaded by the See Through page at https://ventusltd.github.io/kuiper-belt/see-through/202610050513/.
Application
kuiper-belt · see-through/202611020012 · script
VEDIC
SWITCH (GG2050-VEDIC-000033): See Through / Kuiper · Computer science / Interactive visualisation. view, user_flag → selected_view
VEDIC
RISE (GG2050-VEDIC-000034): See Through / Kuiper · Computer science / Interactive visualisation. site, map_state, scene_module → scene_or_refusal
VEDIC
SEARCH (GG2050-VEDIC-000030): See Through / Kuiper · Computer science / Interactive visualisation. query, substation_names → match_count_and_indices
Uses
GridAtlas — Atlas Page (estate URL), Overlay (estate URL)
Used by
loaded by Kuiper Belt — See Through Page (script src)
Produces
loadScript, ensureGridData, merc, unmercLat, decode, arr, decodeLines, voltText, opText, nameOf, keyOfSub, bearingOf
Defines here
loadScript, ensureGridData, merc, unmercLat, decode, arr, decodeLines, voltText, opText, nameOf, keyOfSub, bearingOf, fmt, km, audio, ping, fallTone, el, clamp, smooth, ease, on, layout, placeUI, camera, setTarget, wantMap, loadMap, go, mapFailed
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
kuiper-belt@26fba12ab1b5bab8e71934ab86c58273e5f32682 see-through/202611020012/descent.js:1-700 · blob 5a81bceb9387a56535a99a5111be7c08ea1e4795 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: agent_infra · users: ai_agent · canonical: unknown
// descent.js  SEE THROUGH, a LEARN THE KUIPER module (id 'descent').
// See through the universe to one substation: one unbroken fall from the Kuiper star field, through the grid the stars
// gather into, down a round porthole to one real substation, with the real map and real satellite imagery showing through.
//   Stars:        every place from KuiperLaw.place (kuiper-law.js), keys as DRAW THE GRID gives them (grid.js keyOf).
//   Substations:  modules/grid-data.js names (OpenStreetMap, ODbL) plus the table below (lon, lat, voltage, operator)
//                 from the same public file, globalgrid2050.com/grid_substations.geojson. Built by descent/build_descent_data.py.
//   Lines (GRID): grid-data.js 400 kV and 132 kV networks (OpenStreetMap, ODbL), each frame fitted back to lon/lat.
//   Real map:     exactly what GridAtlas uses (see descent/DESCENT-MAP.md): MapLibre GL 3.6.2 from jsDelivr, the CARTO
//                 dark-matter style, Esri World Imagery for satellite, GridAtlas's own 400/275/132 kV line files.
//                 Network only; the module opens and works offline from file:// without it.
// A star is a line of code today, not a substation. The stars gather into the grid; they do not address it.
// NL-010 step 5 (CERN-OHL-S v2, as the rest of this file): the deep link in (#repo, #key with #space, #sub, #view, read after
// the names load and on hashchange), the link written on arrival, and the way home to the Kuiper by key (the X at the stars
// stage, the STAR KEY row, the credit line). Grammar: FIXES/NL-010/ROADMAP.md step 5.5 and team-3/STEPS.md 5.5.
// NL-010 Opus team 12 (see-through/202611020012, same licence): the link is read once the names are in AND the sky is
// settled; the sky is re-cut from ../../cosmos/wafer-meta.json address_space while nothing is chosen (ROADMAP 5.6); a #key
// that names a substation wins over #sub (identity, not search); #repo matches as the Kuiper's find box does (exact, then
// contains) and uses team 3's refusal words.
(function () {
  'use strict';
  var SCRIPT_SRC = (document.currentScript && document.currentScript.src) || '';
  var SUB = /*DATA-BEGIN*/{"n":5800,"lon":"3h5v,-tlv,-9nvn,-avw,-27x8,a6i3,2,-b7i1,65ki,-eoq,a1a,-40st,-332,t4,-2hox,41t,-48o,d0,-ef6,8y,14k7,-88d,384,-h9r,12w,7mp,-9hf,-4rn,2bdu,-n49,-11m,6kg,-75l,uzu,-uya,axn,bzr,-6xz,8m5,-dyf,-7uo,m1y,-jgg,2s2,-1bgw,1ixi,-1h2y,10s6,xpt,s81,4bs,-asb,-1dp,-1tgb,17zp,-1fyu,-8d8,wzk,e1,qq7,w6s,-2eqz,y3t,-1lq,168o,ce,-299w,zah,17hd,cix,-2iaj,5dr,rb0,1hvm,1i1,-1xv6,-  … [line shortened here: 84,948 characters; full line on GitHub]

  var C = { cyan: '#00ffff', sky: '#66ccff', amber: '#ffb000', green: '#22ee77', white: '#ffffff' };
  var FONT = '"Segoe UI", Arial, sans-serif';
  var NRULE = 20000;            // grid.js N: particle i carries key floor((i + 0.5) * SPACE / NRULE)
  var NSUB = 5800;
  var DMAX = 8;                 // the one control: D = 0 stars, 1 to 2 the stars gather, 2 to 8 the fall to one substation
  var ZEND = 16;                // MapLibre zoom at the bottom of the fall
  var GA = 2.399963229728653;   // 2 pi (1 - 0.6180339887) radians (grid.js / pilot.mjs station clusters)
  // See Through: MapLibre GL 4.7.1 vendored locally (the simulator overlay's version, overlay.html:4-5), one library for
  // the porthole and the 3D view. The original module loaded 3.6.2 from jsDelivr (GridAtlas shell index.html:8, :133).
  var MAPLIBRE_JS = SCRIPT_SRC.replace(/[^\/]*$/, '') + 'vendor/maplibre-gl.js';
  var MAPLIBRE_CSS = SCRIPT_SRC.replace(/[^\/]*$/, '') + 'vendor/maplibre-gl.css';
  var DARK_STYLE = 'https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json';       // GridAtlas engine :667
  var SAT_TILES = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'; // :1353
  var GA_DATA = 'https://ventusltd.github.io/gridatlas/atlas/releases/202608300453-atlas-v9/data/';
  var GA_LINES = [['400', '#0054ff', 2.5], ['275', '#ff0000', 2.0], ['132', '#00cc00', 1.5]]; // GridAtlas ukConfig, shell :145-149
  var ATTR_MAP = 'Data © OpenStreetMap contributors | © CARTO';                       // GridAtlas shell :39
  var ATTR_SAT = 'Imagery: Source: Esri, Vantor, Earthstar Geographics, and the GIS User Community';                                 // simulator overlay.html:43
  var ATTR_SUBS = 'Substations and lines © OpenStreetMap contributors, ODbL';
  var ATLAS_URL = 'https://ventusltd.github.io/gridatlas/atlas/';
  var SIM_URL = 'https://globalgrid2050.com/energy-transition-simulator/202609282123/overlay.html';
  var KUIPER_URL = '../../editions/';           // the Kuiper's pointer (kuiper-belt editions/index.html:7, :11, :12), same host
  var KUIPER_LAW_SHA = '96736f55c2137defcf02c898f8f2b0d04374d74b';
  // grid-data.js stores each network in its own frame: x = ax lon + bx, y = ay lat + by (fitted, descent/DESCENT-MAP.md)
  var FRAME = { substations: [0.09964309, 0.31622146, 0.16536946, -9.15422211],
    grid400: [0.15191996, 0.22101387, 0.25086508, -13.53743135], grid132: [0.12832519, 0.30976879, 0.21383207, -11.62522065] };
  // tower proportions used by the PYLONS drawing: 400 kV H 50 m, base half-width 6 m, arms 10.5 / 12 / 9 m at 0.62 / 0.77 /
  // 0.92 H (typical values stated in globalgrid2050 energy-transition-simulator/202609282123/mod/pylons-real.js:19-21)
  var TOWER = { H: 50, base: 6, armZ: [0.62, 0.77, 0.92], arm: [10.5, 12, 9] };

  var S = null;
  var D0 = null;   // decoded data, kept between opens

  // ---------------- data ----------------
  function loadScript(src, cb) {
    var s = document.createElement('script'); s.src = src;
    s.onload = function () { cb(true); }; s.onerror = function () { cb(false); };
    document.head.appendChild(s); return s;
  }
  function ensureGridData(cb) {
    if (window.KGGridData) return cb();
    loadScript(SCRIPT_SRC ? SCRIPT_SRC.replace(/descent\.js(\?.*)?$/, 'grid-data.js') : 'modules/grid-data.js', function () { cb(); });
  }
  function merc(lon, lat, out, i) {
    var la = Math.max(-85.05, Math.min(85.05, lat)) * Math.PI / 180;
    out[2 * i] = (lon + 180) / 360;
    out[2 * i + 1] = (1 - Math.log(Math.tan(Math.PI / 4 + la / 2)) / Math.PI) / 2;
  }
  function unmercLat(y) { return Math.atan(Math.sinh(Math.PI * (1 - 2 * y))) * 180 / Math.PI; }
  function decode() {
    if (D0) return D0;
    var G = window.KGGridData, n = SUB.n, i;
    function arr(s) { var a = s.split(','), o = new Int32Array(a.length); for (var k = 0; k < a.length; k++) o[k] = parseInt(a[k], 36); return o; }
    var dl = arr(SUB.lon), da = arr(SUB.lat), lon = new Float64Array(n), lat = new Float64Array(n), m = new Float64Array(2 * n);
    var L = 0, A = 0;
    for (i = 0; i < n; i++) { L += dl[i]; A += da[i]; lon[i] = L / 1e5; lat[i] = A / 1e5; merc(lon[i], lat[i], m, i); }
    var names = new Array(n), low = new Array(n), nm = (G && G.substations && G.substations.names) || {};
    for (i = 0; i < n; i++) { names[i] = nm[i] || ''; low[i] = names[i].toLowerCase(); }
    D0 = { n: n, lon: lon, lat: lat, m: m, v: arr(SUB.v), o: arr(SUB.o), names: names, low: low, lines: null };
    // UK frame: bounding box of every substation in Web Mercator
    var x0 = 9, x1 = -9, y0 = 9, y1 = -9;
    for (i = 0; i < n; i++) { var x = m[2 * i], y = m[2 * i + 1]; if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y; }
    D0.box = [x0, y0, x1, y1];
    return D0;
  }
  // GRID: the 400 kV and 132 kV networks of grid-data.js as Web Mercator segments
  function decodeLines() {
    var G = window.KGGridData; if (D0.lines || !G) return D0.lines;
    var out = {};
    ['grid400', 'grid132'].forEach(function (k) {
      var net = G[k]; if (!net) return;
      var f = FRAME[k], n = net.n, xy = net.xy, mm = new Float64Array(2 * n), i;
      for (i = 0; i < n; i++) merc((xy[2 * i] / 1e4 - f[1]) / f[0], (xy[2 * i + 1] / 1e4 - f[3]) / f[2], mm, i);
      var e = net.e, me = e.length / 2, seg = new Int32Array(2 * me), a = 0;
      for (i = 0; i < me; i++) { a += e[2 * i]; seg[2 * i] = a; seg[2 * i + 1] = a + e[2 * i + 1]; }
      out[k] = { m: mm, seg: seg, ns: me };
    });
    D0.lines = out; return out;
  }
  function voltText(i) {
    var v = SUB.vd[D0.v[i]] || ''; if (!v) return 'VOLTAGE NOT IN THE PUBLIC FILE';
    var parts = v.split(';'), o = [], k;
    for (k = 0; k < parts.length && k < 6; k++) { var x = parseFloat(parts[k]); o.push(isFinite(x) && x >= 1000 ? (x / 1000) + ' kV' : parts[k]); }
    return o.join(' / ');
  }
  function opText(i) { return SUB.od[D0.o[i]] || 'OPERATOR NOT IN THE PUBLIC FILE'; }
  function nameOf(i) { return D0.names[i] || 'SUBSTATION ' + i + ' (NO NAME IN THE PUBLIC FILE)'; }
  function keyOfSub(i) { return S.subKey[i]; }   // grid.js keyOf(i): the key of the star with index i, the one that lands here
  function bearingOf(p) { var b = (90 - p.deg) % 360; return b < 0 ? b + 360 : b; }
  function fmt(x) { return Math.round(x).toLocaleString('en-GB'); }
  function km(i, j) {   // great-circle distance, haversine, mean Earth radius 6371.0088 km
    var r = Math.PI / 180, p1 = D0.lat[i] * r, p2 = D0.lat[j] * r, dp = p2 - p1, dl = (D0.lon[j] - D0.lon[i]) * r;
    var a = Math.sin(dp / 2) * Math.sin(dp / 2) + Math.cos(p1) * Math.cos(p2) * Math.sin(dl / 2) * Math.sin(dl / 2);
    return 2 * 6371.0088 * Math.asin(Math.min(1, Math.sqrt(a)));
  }

  // ---------------- sound ----------------
  function audio() {
    if (!S || S.muted) return null;
    if (!S.ac) {
      try {
        S.ac = new (window.AudioContext || window.webkitAudioContext)();
        S.osc = S.ac.createOscillator(); S.og = S.ac.createGain(); S.osc.type = 'sine'; S.og.gain.value = 0;
        S.osc.connect(S.og); S.og.connect(S.ac.destination); S.osc.start();
      } catch (e) { S.ac = null; return null; }
    }
    if (S.ac.state === 'suspended') S.ac.resume();
    return S.ac;
  }
  function ping(semi, gain) {
    var ac = audio(); if (!ac) return;
    var t0 = ac.currentTime, o = ac.createOscillator(), g = ac.createGain();
    o.type = 'sine'; o.frequency.value = 440 * Math.pow(2, semi / 12);
    g.gain.setValueAtTime(0, t0); g.gain.linearRampToValueAtTime(gain || 0.04, t0 + 0.02);
    g.gain.exponentialRampToValueAtTime(0.0001, t0 + 0.5);
    o.connect(g); g.connect(ac.destination); o.start(t0); o.stop(t0 + 0.55);
  }
  function fallTone(speed) {   // a soft tone that falls in pitch as you descend
    if (!S.ac || !S.og) return;
    var t = S.ac.currentTime, g = S.muted ? 0 : Math.min(0.03, speed * 0.02);
    S.og.gain.setTargetAtTime(g, t, 0.08);
    S.osc.frequency.setTargetAtTime(520 * Math.pow(2, -S.D / 3.2), t, 0.08);
  }

  // ---------------- helpers ----------------
  function el(tag, css, text, parent) {
    var d = document.createElement(tag); if (css) d.style.cssText = css; if (text != null) d.textContent = text;
    if (parent) parent.appendChild(d); return d;
  }
  function clamp(x, a, b) { return x < a ? a : (x > b ? b : x); }
  function smooth(x) { x = clamp(x, 0, 1); return x * x * (3 - 2 * x); }
  function ease(v) { return v < 0.5 ? 4 * v * v * v : 1 - Math.pow(-2 * v + 2, 3) / 2; }
  function on(t, ev, fn, opt) { t.addEventListener(ev, fn, opt || false); S.listeners.push([t, ev, fn, opt || false]); }

  // ---------------- layout ----------------
  function layout() {
    var host = S.host, W = host.clientWidth || window.innerWidth, H = host.clientHeight || window.innerHeight;
    W = Math.max(200, W); H = Math.max(200, H);
    var phone = Math.min(W, H) < 600, dpr = Math.max(1, window.devicePixelRatio || 1);
    var sc = Math.min(dpr, 2); if (phone) sc = Math.min(sc, 2048 / W, 2048 / H);   // LIMITS-DESIGN.md canvas caps
    S.W = W; S.H = H; S.phone = phone; S.sc = sc; S.port = phone && H > W; S.land = phone && W >= H;
    S.cv.width = Math.round(W * sc); S.cv.height = Math.round(H * sc);
    S.cv.style.width = W + 'px'; S.cv.style.height = H + 'px';
    // Portrait uses the spare height; wide screens put controls beside the full circle.
    S.side = W >= H * 1.2;
    S.cx = W / 2; S.cy = H / 2;
    S.Rpx = (phone ? 0.47 : 0.44) * Math.min(W, H);
    if (!S.side) { S.cy = 148 + (H - 312) / 2; S.Rpx = Math.max(24, Math.min(S.Rpx, (H - 312) / 2)); }
    S.Rw = Math.sqrt(S.SPACE + 0.5);
    var b = D0.box, R2 = S.Rpx * 2 * 0.86;
    S.Cuk = [(b[0] + b[2]) / 2, (b[1] + b[3]) / 2];
    S.wsUK = Math.min(R2 / (b[2] - b[0]), R2 / (b[3] - b[1]));     // world pixels per Mercator unit at the UK view
    S.zUK = Math.log(S.wsUK / 512) / Math.LN2;
    if (!S.in3d) {   // in 3D the map fills the screen (see3d.js)
      S.mapEl.style.clipPath = 'circle(' + S.Rpx.toFixed(1) + 'px at ' + S.cx.toFixed(1) + 'px ' + S.cy.toFixed(1) + 'px)';
      S.mapEl.style.webkitClipPath = S.mapEl.style.clipPath;
    }
    // stars behind everything: one offscreen canvas per layout
    var bg = S.bg || (S.bg = document.createElement('canvas'));
    bg.width = S.cv.width; bg.height = S.cv.height;
    var g = bg.getContext('2d'), n = Math.min(4000, Math.round(W * H / 2600)), seed = 12345, i;
    g.setTransform(sc, 0, 0, sc, 0, 0); g.clearRect(0, 0, W, H);
    for (i = 0; i < n; i++) {
      seed = (seed * 1664525 + 1013904223) >>> 0; var x = seed / 4294967296 * W;
      seed = (seed * 1664525 + 1013904223) >>> 0; var y = seed / 4294967296 * H;
      seed = (seed * 1664525 + 1013904223) >>> 0; g.globalAlpha = 0.08 + 0.2 * seed / 4294967296;
      g.fillStyle = '#a0beff'; g.fillRect(x, y, 1, 1);
    }
    g.globalAlpha = 1;
    // the sweep wedge: one conic gradient (anticlockwise arm, the wedge trails behind it)
    var ctx = S.ctx;
    S.wedge = null;
    if (ctx.createConicGradient) {
      S.wedge = ctx.createConicGradient(0, 0, 0);
      S.wedge.addColorStop(0, 'rgba(0,255,255,0.16)'); S.wedge.addColorStop(0.1, 'rgba(0,255,255,0)'); S.wedge.addColorStop(1, 'rgba(0,255,255,0)');
    }
    S.layoutN = (S.layoutN || 0) + 1;
    placeUI();
    if (S.map) { try { S.map.resize(); } catch (e) {} }
    if (S.in3d && window.SeeThrough3D && window.SeeThrough3D.relayout) window.SeeThrough3D.relayout({ phone: S.phone, port: S.port, land: S.land, rx: S.Rpx, cx: S.cx, cy: S.cy });
    S.camKey = '';
  }

  function placeUI() {
    var W = S.W;
    S.viewBtns.forEach(function (b) { b.style.gridColumn = ''; });
    S.allBtns.forEach(function (b) { b.style.height = '44px'; b.style.minWidth = '44px'; b.style.padding = '0 8px'; });
    S.xbtn.style.width = S.xbtn.style.height = '44px';
    if (S.mute.parentNode !== S.ui) S.ui.appendChild(S.mute);
    S.mute.style.cssText += ';position:absolute;top:calc(8px + env(safe-area-inset-top));right:60px';
    S.cap.className = 'st-edge st-title';
    S.cap.style.cssText = 'position:absolute;left:8px;right:116px;top:calc(8px + env(safe-area-inset-top));font:400 16px/24px ' + FONT;
    S.search.style.cssText = 'position:absolute;display:' + (S.in3d ? 'none' : 'flex') + ';gap:8px;pointer-events:auto;left:8px;right:8px;top:calc(56px + env(safe-area-inset-top))';
    S.input.style.height = S.goB.style.height = '44px'; S.goB.style.minWidth = '56px';
    S.note.className = 'st-edge';
    S.note.style.cssText = 'position:absolute;left:8px;right:8px;top:calc(104px + env(safe-area-inset-top));font:400 14px/20px ' + FONT + ';display:' + (S.in3d ? 'none' : 'block');
    S.card.className = 'st-edge st-site';
    S.card.style.cssText = 'position:absolute;left:8px;right:8px;bottom:calc(132px + env(safe-area-inset-bottom));font:400 14px/22px ' + FONT + ';display:' + (S.cardOn && !S.in3d ? 'block' : 'none');
    S.grpView.style.cssText = 'position:absolute;display:flex;flex-direction:row;gap:6px;left:8px;right:8px;bottom:calc(82px + env(safe-area-inset-bottom));justify-content:center;pointer-events:none';
    S.grpBL.style.cssText = 'position:absolute;display:' + (S.in3d ? 'none' : 'flex') + ';gap:4px;left:8px;bottom:calc(34px + env(safe-area-inset-bottom));pointer-events:none';
    S.grpUD.style.cssText = 'position:absolute;display:' + (S.in3d ? 'none' : 'flex') + ';flex-direction:row;gap:4px;right:8px;bottom:calc(34px + env(safe-area-inset-bottom));pointer-events:none';
    S.att.className = 'st-edge st-attribution';
    S.att.style.cssText = 'position:absolute;left:8px;right:8px;bottom:calc(4px + env(safe-area-inset-bottom));font:400 11px/20px ' + FONT;
    S.netNote.className = 'st-edge st-network';
    S.netNote.style.cssText = 'position:absolute;left:8px;right:8px;top:calc(' + (S.in3d ? 56 : 126) + 'px + env(safe-area-inset-top));font:400 14px/20px ' + FONT + ';display:none';
    S.search.style.maxWidth = '420px';
    if (S.side && !S.in3d) {
      var side = Math.max(120, Math.floor(S.cx - S.Rpx - 20));
      S.search.style.right = ''; S.search.style.width = side + 'px';
      S.cap.style.right = ''; S.cap.style.width = side + 'px';
      S.note.style.right = ''; S.note.style.width = side + 'px';
      S.grpView.style.left = ''; S.grpView.style.width = '110px'; S.grpView.style.top = 'calc(64px + env(safe-area-inset-top))'; S.grpView.style.bottom = ''; S.grpView.style.flexDirection = 'column';
      S.grpBL.style.top = 'calc(132px + env(safe-area-inset-top))'; S.grpBL.style.bottom = ''; S.grpBL.style.width = side + 'px'; S.grpBL.style.flexWrap = 'wrap';
      S.grpUD.style.left = '8px'; S.grpUD.style.right = ''; S.grpUD.style.top = 'calc(228px + env(safe-area-inset-top))'; S.grpUD.style.bottom = '';
      S.card.style.right = ''; S.card.style.width = side + 'px'; S.card.style.bottom = 'calc(32px + env(safe-area-inset-bottom))';
      S.att.style.right = '8px'; S.att.style.left = ''; S.att.style.width = side + 'px';
      S.netNote.style.top = 'calc(280px + env(safe-area-inset-top))'; S.netNote.style.right = ''; S.netNote.style.width = side + 'px';
      // In short landscape the site/warning use the free lower-right corner.
      if (S.land) {
        S.grpView.style.width = side + 'px'; S.grpView.style.display = 'grid'; S.grpView.style.gridTemplateColumns = 'repeat(2,minmax(0,1fr))';
        S.viewBtns[0].style.gridColumn = S.b3d.style.gridColumn = '1 / -1';
        S.card.style.left = ''; S.card.style.right = '8px'; S.card.style.bottom = 'calc(48px + env(safe-area-inset-bottom))';
        S.netNote.style.left = ''; S.netNote.style.right = '8px'; S.netNote.style.top = ''; S.netNote.style.bottom = 'calc(72px + env(safe-area-inset-bottom))';
      }
    }
    S.cap.className += ' st-wrap'; S.att.className += ' st-wrap';
    if (S.in3d) {
      S.cap.style.right = '116px'; S.cap.style.width = ''; S.cap.style.maxWidth = '640px';
      S.att.style.left = '8px'; S.att.style.right = '8px'; S.att.style.width = ''; S.att.style.maxWidth = '960px';
      S.grpView.style.bottom = 'calc(64px + env(safe-area-inset-bottom))';
      if (S.land) { S.grpView.style.left = ''; S.grpView.style.width = '110px'; S.grpView.style.top = '64px'; S.grpView.style.bottom = ''; S.grpView.style.flexDirection = 'column'; }
    }
    S.ro.style.display = 'none'; networkStatus();
    if (S.homeA) { if (S.cardOn && !S.in3d && S.T >= 0) homeRow(); else S.homeA.style.display = 'none'; }   // NL-010 5.8 b
  }

  // ---------------- camera ----------------
  // z(D), the camera centre C(D) and the world scale ws = 512 * 2^z (MapLibre's own world size), shared by every layer
  function camera(D) {
    var cam = S.cam;
    if (D <= 2 || S.T < 0) {
      var z0 = D <= 2 ? S.zUK : S.zUK + (D - 2) * (ZEND - S.zUK) / (DMAX - 2);
      cam.z = z0; cam.ws = 512 * Math.pow(2, z0); cam.x = S.Cuk[0]; cam.y = S.Cuk[1];
    } else {
      var z = S.zUK + (D - 2) * (ZEND - S.zUK) / (DMAX - 2), ws = 512 * Math.pow(2, z), f = (S.wsUK / ws) * (1 - smooth((D - 2) / 2.5));
      var tx = D0.m[2 * S.T], ty = D0.m[2 * S.T + 1];
      cam.z = z; cam.ws = ws; cam.x = tx + (S.Cuk[0] - tx) * f; cam.y = ty + (S.Cuk[1] - ty) * f;
    }
    if (S.corrA > 0.001) { cam.x += S.corrX * S.corrA / cam.ws; cam.y += S.corrY * S.corrA / cam.ws; }
    return cam;
  }
  function setTarget(i, smoothly) {
    if (i === S.T) return;
    if (smoothly && S.D > 2) {          // keep the view continuous: carry the old camera as an offset that fades out
      var a = camera(S.D), ox = a.x, oy = a.y, ws = a.ws, oldA = S.corrA;
      S.corrA = 0; S.T = i; var b = camera(S.D);
      S.corrX = (ox - b.x) * ws; S.corrY = (oy - b.y) * ws; S.corrA = 1; void oldA;
    } else { S.T = i; S.corrA = 0; }
    S.spider = null; S.spiderT0 = performance.now();
    S.cardDirty = true;
  }

  // ---------------- the real map (GridAtlas's own library and sources) ----------------
  function wantMap() { return S.view !== 'kuiper'; }
  function loadMap() {
    if (S.mapState !== 'none') return;
    S.mapState = 'loading';
    var go = function () {
      if (!S) return;
      if (!window.maplibregl) { mapFailed('lib'); return; }
      try {
        var cam = camera(S.D);
        S.map = new window.maplibregl.Map({
          container: S.mapEl, style: DARK_STYLE, center: [cam.x * 360 - 180, unmercLat(cam.y)], zoom: Math.max(0, cam.z),
          interactive: false, attributionControl: false, pixelRatio: S.sc, fadeDuration: 150, maxZoom: 19.5, maxPitch: 85, antialias: true
        });
      } catch (e) { mapFailed('webgl'); return; }
      S.mapT0 = performance.now(); S.tileOK = 0; S.tileErr = 0;
      S.map.on('load', function () {
        if (!S || !S.map) return;
        try {
          // GridAtlas engine :1353-1354, verbatim tiles: the satellite raster, hidden until SATELLITE is chosen
          S.map.addSource('sat-s', { type: 'raster', tiles: [SAT_TILES], tileSize: 256 });
          S.map.addLayer({ id: 'l-sat', type: 'raster', source: 'sat-s', layout: { visibility: S.view === 'sat' ? 'visible' : 'none' } });
          GA_LINES.forEach(function (L) {
            S.map.addSource('ga' + L[0], { type: 'geojson', data: GA_DATA + 'grid_' + L[0] + 'kv.geojson' });
            S.map.addLayer({ id: 'ga' + L[0], type: 'line', source: 'ga' + L[0], layout: { visibility: S.grid ? 'visible' : 'none' },
              paint: { 'line-color': L[1], 'line-width': L[2], 'line-opacity': 0.9 } });
          });
        } catch (e) {}
        S.mapState = 'ready'; S.camKey = '';
      });
      S.map.on('data', function (e) { if (S && e && e.tile && e.tile.state === 'loaded') S.tileOK++; if (S && e && e.sourceId && /^ga/.test(e.sourceId) && e.isSourceLoaded) S.gaLines = true; });
      S.map.on('error', function (e) { if (!S) return; S.tileErr++; networkStatus((e && e.sourceId) || 'map', true); });
      S.map.on('sourcedata', function (e) {
        if (!S || !e || !e.sourceId || !e.tile || e.tile.state !== 'loaded') return;
        if (e.sourceId === 'sat-s') S.satOK = true;
        networkStatus(e.sourceId, false); networkStatus('map-timeout', false);
      });
    };
    if (window.maplibregl) { go(); return; }
    if (!document.querySelector('link[data-descent-maplibre]')) {
      var l = document.createElement('link'); l.rel = 'stylesheet'; l.href = MAPLIBRE_CSS; l.setAttribute('data-descent-maplibre', '1'); document.head.appendChild(l);
    }
    var done = false;
    S.libTimer = setTimeout(function () { if (!done) { done = true; mapFailed('lib'); } }, 12000);
    loadScript(MAPLIBRE_JS, function (ok) { if (done) return; done = true; clearTimeout(S && S.libTimer); if (ok && S) go(); else mapFailed('lib'); });
  }
  function mapFailed(why) {
    if (!S) return;
    S.mapState = 'failed'; S.mapWhy = why; networkStatus('map', true);
    if (S.map) { try { S.map.remove(); } catch (e) {} S.map = null; }
    S.mapEl.style.visibility = 'hidden';
    caption(why === 'webgl' ? 'THIS BROWSER CANNOT DRAW THE REAL MAP' : 'REAL MAP NEEDS THE INTERNET');
    S.attDirty = true;
  }
  function checkTiles(now) {   // tiles never arrived: say so in one line, keep the stars
    if (S.mapState === 'ready' || S.mapState === 'loading') {
      if (S.map && S.tileOK === 0 && now - S.mapT0 > 9000) networkStatus('map-timeout', true);
      if (S.satRequestedAt != null && !S.satOK && now - S.satRequestedAt > 9000) networkStatus('sat-s', true);
    }
  }
  function syncMap(alpha) {
    var m = S.map, vis = alpha > 0.005 && S.mapState === 'ready';
    if (vis !== S.mapVis) { S.mapVis = vis; S.mapEl.style.visibility = vis ? 'visible' : 'hidden'; }
    if (!vis || !m) return;
    if (Math.abs(alpha - S.mapA) > 0.01) { S.mapA = alpha; S.mapEl.style.opacity = alpha.toFixed(3); }
    var cam = S.cam, key = cam.x.toFixed(10) + cam.y.toFixed(10) + cam.z.toFixed(4);
    if (key !== S.camKey) {
      S.camKey = key;
      try { m.jumpTo({ center: [cam.x * 360 - 180, unmercLat(cam.y)], zoom: Math.max(0, cam.z) }); } catch (e) {}
    }
  }
  function setView(v, byUser) {
    if (v === S.view) return;
    if (v === '3d') { enter3d(byUser); return; }
    if (S.view === '3d') exit3d();
    S.view = v; if (byUser) S.viewTouched = true;
    if (v === 'sat') S.satRequestedAt = performance.now();
    S.viewBtns.forEach(function (b) { lit(b, b.dataset.v === v); });
    if (v !== 'kuiper') loadMap();
    if (S.map && S.mapState === 'ready') { try { S.map.setLayoutProperty('l-sat', 'visibility', v === 'sat' ? 'visible' : 'none'); } catch (e) {} }
    if (v === 'sat' && S.D > 2.5) caption('THE REAL GROUND, FROM ABOVE');
    else if (v === 'map' && S.D > 2.5) caption('THE REAL MAP');
    else if (v === 'kuiper') caption('THE STARS ONLY');
    S.attDirty = true;
  }

  // ---------------- stage 4: 3D (see3d.js), the same map tipped over ----------------
  function enter3d(byUser) {
    var X = window.SeeThrough3D;
    if (!X || S.T < 0) { caption('CHOOSE A SUBSTATION FIRST'); return; }
    if (!S.map || S.mapState !== 'ready') { caption(S.mapState === 'failed' ? 'REAL MAP NEEDS THE INTERNET' : 'MAP LOADING'); loadMap(); return; }
    S.prev3d = S.view === '3d' ? S.prev3d : S.view;
    S.view = '3d'; S.in3d = true; if (byUser) S.viewTouched = true; S.auto3d = 0;
    if (S.satRequestedAt == null) S.satRequestedAt = performance.now();
    S.viewBtns.forEach(function (b) { lit(b, b.dataset.v === '3d'); });
    try { S.map.setLayoutProperty('l-sat', 'visibility', 'visible'); } catch (e) {}
    S.flight = null; S.Dgoal = S.D; hideCard(); S.cv.style.pointerEvents = 'none';
    S.grpBL.style.display = 'none'; S.search.style.display = 'none'; S.note.style.display = 'none'; S.ro.style.display = 'none'; S.grpUD.style.display = 'none';
    S.mapEl.style.visibility = 'visible'; S.mapEl.style.opacity = '1';
    placeUI();
    X.enter({ map: S.map, host: S.host, mapEl: S.mapEl, ui: S.ui, att: S.att, cap: S.cap, phone: S.phone, port: S.port, land: S.land, rx: S.Rpx, cx: S.cx, cy: S.cy,
      rec: { i: S.T, name: D0.names[S.T], lat: D0.lat[S.T], lon: D0.lon[S.T], volt: SUB.vd[D0.v[S.T]] || '' },
      caption: caption, ping: ping, networkStatus: networkStatus });
    caption(nameOf(S.T).toUpperCase());
    S.attDirty = true;
  }
  function exit3d() {
    var X = window.SeeThrough3D; if (X) X.exit();
    S.in3d = false; S.cv.style.pointerEvents = '';
    S.grpBL.style.display = ''; S.search.style.display = ''; S.note.style.display = ''; S.grpUD.style.display = ''; S.ro.style.display = S.phone ? 'none' : 'block';
    S.camKey = ''; S.cardDirty = S.T >= 0; S.attDirty = true; layout();
  }

  // ---------------- search: type a name, lights guide the eye ----------------
  function doSearch() {
    var q = S.input.value || '';
    if (q.length > 80) { q = q.slice(0, 80); S.input.value = q; }
    q = q.trim().toLowerCase(); S.mN = 0; S.mTotal = 0;
    if (!q) { S.note.textContent = ''; S.q = ''; S.cap.style.visibility = 'visible'; return; }
    S.q = q;
    var low = D0.low, n = D0.n, cap = S.mIdx.length;
    for (var i = 0; i < n; i++) {
      if (low[i] && low[i].indexOf(q) >= 0) { if (S.mN < cap) S.mIdx[S.mN++] = i; S.mTotal++; }
    }
    if (S.land) S.cap.style.visibility = 'hidden';
    if (!S.mTotal) S.note.textContent = 'NO SUBSTATION NAME HERE CONTAINS THAT';
    else if (S.mTotal === 1) S.note.textContent = 'ONE MATCH. PRESS GO';
    else S.note.textContent = fmt(S.mTotal) + ' MATCHES' + (S.mTotal > S.mN ? ', ' + S.mN + ' LIT' : '') + '. KEEP TYPING';
  }
  function bestMatch() {
    if (!S.mN) return -1;
    for (var k = 0; k < S.mN; k++) if (D0.low[S.mIdx[k]] === S.q) return S.mIdx[k];
    return S.mIdx[0];
  }
  function goSearch() {
    doSearch();
    var i = bestMatch();
    if (i < 0) { S.note.textContent = S.q ? 'NO SUBSTATION NAME HERE CONTAINS THAT. TRY ANOTHER NAME' : 'TYPE A SUBSTATION NAME, THEN GO'; return; }
    S.input.blur(); S.note.textContent = ''; S.cap.style.visibility = 'visible';
    flyTo(i);
  }
  // the flight: first up to the whole Kuiper field, then down through the porthole to that exact substation
  function flyTo(i) {
    audio();
    if (S.in3d) { exit3d(); S.view = 'sat'; S.viewBtns.forEach(function (b) { lit(b, b.dataset.v === 'sat'); }); }
    S.flight = { phase: S.D > 0.15 ? 'up' : 'down', T: i, start: performance.now() };
    S.auto3d = 0; S.Dgoal = 0; S.speed = 3.2; hideCard();
    caption('DOWN TO ' + nameOf(i).toUpperCase());
    if (S.flight.phase === 'down') { S.D = 0; setTarget(i, false); }
    S.viewTouched = false; setView('map', false); loadMap();
  }

  // Absolute time makes the deliberate pauses independent of frame rate.
  function flightDepth(seconds) {
    var mid = 2 + (9 - S.zUK) * (DMAX - 2) / (ZEND - S.zUK);
    if (seconds <= 1) return 0;
    if (seconds <= 1.2) return smooth((seconds - 1) / 0.2);
    if (seconds <= 3.3) return 1 + smooth((seconds - 1.2) / 2.1);
    if (seconds <= 4) return 2 + (mid - 2) * smooth((seconds - 3.3) / 0.7);
    if (seconds <= 6) return mid; // Town labels stay at zoom 9 for two seconds.
    if (seconds <= 8) return mid + (DMAX - mid) * smooth((seconds - 6) / 2);
    return DMAX;
  }
  function back() {
    if (!S) return;
    S.flight = null; S.auto3d = 0; S.hold = 0;
    if (S.in3d) { setView('sat', true); S.D = S.Dgoal = DMAX; camera(S.D); syncMap(1); showCard(); return; }
    if (!M.standalone) { M.close(); return; }
    if (S.T < 0 && S.D < 0.01 && !S.input.value) { goHome(); return; }
    S.input.value = ''; S.q = ''; S.mN = S.mTotal = 0; S.note.textContent = '';
    S.T = -1; S.D = S.Dgoal = 0; S.corrA = 0; S.spider = null; S.spiderOn = false; lit(S.spB, false);
    S.cardDirty = false; hideCard(); S.viewTouched = false; S.stage = 0;
    setView('map', false); caption('SEE THROUGH'); layout(); syncMap(0);
    S.cv.style.visibility = 'visible'; S.ring = null; S.repoLit = null;
    try { history.replaceState(null, '', location.pathname + location.search); } catch (e) {}
  }

  // ---------------- SPIDER: the grid engine pack when present, otherwise nearest by distance ----------------
  function findSite(i) {   // feature-detected against modules/grid-engine-pack.js (KGEngine) and grid-topology-data.js
    var E = window.KGEngine, T = window.KGGridTopology; if (!E || !T) return null;
    try {
      if (typeof E.siteFor === 'function') { var s0 = E.siteFor(D0.lat[i], D0.lon[i], D0.names[i]); if (s0) return s0; }
      if (typeof E.matchSite === 'function') { var s1 = E.matchSite(D0.lat[i], D0.lon[i], D0.names[i]); if (s1) return s1; }
      var sites = T.sites || T.nodes || [], list = Array.isArray(sites) ? sites : Object.keys(sites).map(function (k) { var o = sites[k]; if (o && o.key == null) o.key = k; return o; });
      var best = null, bd = 1.5, nm = D0.low[i];
      for (var k = 0; k < list.length && k < 5000; k++) {
        var o = list[k]; if (!o) continue;
        var la = +(o.lat != null ? o.lat : o.latitude), lo = +(o.lon != null ? o.lon : (o.lng != null ? o.lng : o.longitude));
        if (!isFinite(la) || !isFinite(lo)) continue;
        var dx = (lo - D0.lon[i]) * 111.32 * Math.cos(la * Math.PI / 180), dy = (la - D0.lat[i]) * 110.57, d = Math.sqrt(dx * dx + dy * dy);
        var named = nm && o.name && String(o.name).toLowerCase().indexOf(nm.split(' ')[0]) >= 0;
        if (d < bd || (named && d < 5 && d < bd + 3)) { bd = d; best = o; }
      }
      return best ? (best.key != null ? best.key : (best.site != null ? best.site : best.id)) : null;
    } catch (e) { return null; }
  }
  function buildSpider() {
    var i = S.T; if (i < 0) return null;
    var E = window.KGEngine, out = { from: i, arrows: [], listed: [], kind: 'distance', caveat: '' };
    var site = findSite(i);
    if (site != null && E && typeof E.spiderFrom === 'function') {
      try {
        var res = E.spiderFrom(site, { maxHops: S.hops }) || [];
        for (var k = 0; k < res.length && k < 60; k++) {
          var r = res[k];
          if (r.hasCoordinates === false || !isFinite(+r.lat) || !isFinite(+r.lon)) { out.listed.push(String(r.toSite)); continue; }
          var mm = new Float64Array(2); merc(+r.lon, +r.lat, mm, 0);
          out.arrows.push({ mx: mm[0], my: mm[1], km: +r.km, label: (isFinite(+r.km) ? (+r.km).toFixed(1) + ' KM' : '') + (r.hops > 1 ? '  ' + r.hops + ' HOPS' : ''),
            name: String(r.toSite), kv: r.voltage, cable: /cable/i.test(String(r.kind || '')), corridor: r.corridorKm || r.corridor || null, hops: r.hops || 1 });
        }
        out.kind = 'published';
        var cv = E.caveats || E.CAVEATS || (E.spiderCaveats) || null;
        out.caveat = cv ? (Array.isArray(cv) ? cv.join('; ') : (typeof cv === 'object' ? Object.keys(cv).map(function (q) { return cv[q]; }).join('; ') : String(cv))) : '';
        return out;
      } catch (e) { /* fall through to distance */ }
    }
    var near = null;
    if (E && typeof E.nearestByDistance === 'function') {
      try { near = E.nearestByDistance(D0.lat[i], D0.lon[i], 7); } catch (e) { near = null; }
    }
    if (near && near.length) {
      for (var a = 0; a < near.length && out.arrows.length < 6; a++) {
        var q = near[a], la = +(q.lat != null ? q.lat : q.latitude), lo = +(q.lon != null ? q.lon : q.longitude);
        if (!isFinite(la) || !isFinite(lo)) continue;
        if (Math.abs(la - D0.lat[i]) < 1e-6 && Math.abs(lo - D0.lon[i]) < 1e-6) continue;
        var m2 = new Float64Array(2); merc(lo, la, m2, 0);
        out.arrows.push({ mx: m2[0], my: m2[1], km: +q.km, label: (+q.km).toFixed(1) + ' KM', name: String(q.name || ''), hops: 1 });
      }
      out.kind = 'engine-distance'; return out;
    }
    // no pack: our own great-circle nearest six from the public substation file (coincident duplicates skipped)
    var bestI = [-1, -1, -1, -1, -1, -1], bestD = [1e9, 1e9, 1e9, 1e9, 1e9, 1e9], j, t;
    for (j = 0; j < D0.n; j++) {
      if (j === i) continue; var d = km(i, j); if (d < 0.05 || d >= bestD[5]) continue;
      for (t = 5; t > 0 && bestD[t - 1] > d; t--) { bestD[t] = bestD[t - 1]; bestI[t] = bestI[t - 1]; }
      bestD[t] = d; bestI[t] = j;
    }
    for (t = 0; t < 6; t++) if (bestI[t] >= 0) out.arrows.push({ mx: D0.m[2 * bestI[t]], my: D0.m[2 * bestI[t] + 1], km: bestD[t], label: bestD[t].toFixed(1) + ' KM', name: nameOf(bestI[t]), sub: bestI[t], hops: 1 });
    return out;
  }
  function spiderCaption() {
    if (!S.spider) return;
    caption(S.spider.kind === 'published' ? 'PUBLISHED CIRCUITS, NESO ETYS 2025' : 'NEAREST BY DISTANCE, NOT CONNECTIONS');
  }

  // ---------------- drawing ----------------
  function frame(now) {
    if (!S) return;
    S.raf = requestAnimationFrame(frame);
    var xl = (M.standalone && S.T < 0 && S.D < 0.01 && !S.input.value) ? 'back to the Kuiper' : 'back';
    if (S.xLab !== xl) { S.xLab = xl; S.xbtn.setAttribute('aria-label', xl); }
    var t0 = performance.now(); if (S.last) S.fiv[S.fj++ % S.fiv.length] = now - S.last;
    var dt = Math.min(0.1, Math.max(0.001, (now - (S.last || now)) / 1000)); S.last = now;
    // the one control: D eases toward its goal, with a speed cap so a huge wheel turn is still a fall, not a cut
    if (S.hold) S.Dgoal = clamp(S.Dgoal + S.hold * dt * 1.3, 0, DMAX);
    var Dp = S.D, step = (S.Dgoal - S.D) * Math.min(1, dt * 3.2), cap = S.speed * dt;
    S.D += clamp(step, -cap, cap); if (Math.abs(S.Dgoal - S.D) < 1e-4) S.D = S.Dgoal;
    var moving = Math.abs(S.D - Dp) / dt;
    if (S.flight) {
      if (S.flight.phase === 'up' && S.D < 0.06) {
        S.flight.phase = 'down'; S.flight.start = now; S.D = 0; setTarget(S.flight.T, false);
      }
      if (S.flight.phase === 'down') {
        var seconds = (now - S.flight.start) / 1000;
        S.D = S.Dgoal = flightDepth(seconds);
        if (seconds >= 8 && !S.viewTouched && S.view !== 'sat') setView('sat', false);
        if (seconds >= 10) { S.flight = null; S.speed = 2.4; arrive(); if (!S.viewTouched) S.auto3d = now; }
      }
      moving = Math.abs(S.D - Dp) / dt;
    }
    if (S.D > 1.9 && S.T < 0) setTarget(nearestToCentre(), false);
    if (S.corrA > 0) S.corrA = Math.max(0, S.corrA - dt * 1.6);
    fallTone(moving);
    S.sw = (S.sw + (S.scan && !S.grab ? dt * Math.PI / 3 : 0)) % (2 * Math.PI);   // 60 degrees a second, anticlockwise
    checkTiles(now);
    if (S.in3d) {
      if (S.cv.style.visibility !== 'hidden') { S.cv.style.visibility = 'hidden'; }
      if (S.attDirty) { S.attDirty = false; attrib(); }
      return;
    }
    if (S.cv.style.visibility === 'hidden') S.cv.style.visibility = 'visible';
    // the arrival goes on into 3D by itself unless the player has chosen a view (owner: "the camera tips over")
    if (S.auto3d && now >= S.auto3d && !S.flight && S.D > DMAX - 0.05 && S.view === 'sat') { S.auto3d = 0; enter3d(false); return; }
    var cam = camera(S.D);
    if (!S.flight && !S.viewTouched && S.view === 'map' && cam.z >= 15 && S.mapState === 'ready') { setView('sat', false); }
    if (wantMap() && S.mapState === 'none' && S.D > 1.4) loadMap();
    checkTiles(now);
    var mapA = (wantMap() && S.mapState === 'ready') ? smooth((S.D - 2.3) / 0.9) : 0;
    syncMap(mapA);
    stageCaption();
    render(cam, mapA, now);
    if (S.cardDirty && S.T >= 0 && S.D > 2.6) { S.cardDirty = false; showCard(); }
    if (S.D < 2.4 && S.cardOn) hideCard();
    if (now - S.roT > 150) { S.roT = now; readout(cam); }
    if (S.attDirty) { S.attDirty = false; attrib(); }
    var ft = performance.now() - t0; S.ft[S.fi++ % S.ft.length] = ft;
    if (S.fi > 30 && S.fi % 30 === 0) { var avg = 0; for (var k = 0; k < S.ft.length; k++) avg += S.ft[k]; avg /= S.ft.length; S.lite = avg > 14; }
  }

  function nearestToCentre() {
    var best = 0, bd = 1e18, cx = S.Cuk[0], cy = S.Cuk[1];
    for (var i = 0; i < D0.n; i++) { if (!D0.names[i]) continue; var dx = D0.m[2 * i] - cx, dy = D0.m[2 * i + 1] - cy, d = dx * dx + dy * dy; if (d < bd) { bd = d; best = i; } }
    return best;
  }

  function render(cam, mapA, now) {
    var g = S.ctx, W = S.W, H = S.H, cx = S.cx, cy = S.cy, R = S.Rpx, D = S.D, i, n = S.NP;
    g.setTransform(S.sc, 0, 0, S.sc, 0, 0);
    g.globalCompositeOperation = 'source-over'; g.globalAlpha = 1;
    g.clearRect(0, 0, W, H);
    // black everywhere outside the porthole; inside it, black that thins as the real map fades in under it
    g.fillStyle = '#000'; g.beginPath(); g.rect(0, 0, W, H); g.arc(cx, cy, R, 0, 2 * Math.PI, true); g.fill('evenodd');
    if (mapA < 1) { g.globalAlpha = 1 - mapA; g.beginPath(); g.arc(cx, cy, R, 0, 2 * Math.PI); g.fill(); }
    g.globalAlpha = 1 - mapA * 0.85; g.drawImage(S.bg, 0, 0, W, H); g.globalAlpha = 1;

    // where each star is now: Kuiper place, blending to its substation (Web Mercator, the same mapping as the map)
    var u = clamp(D - 1, 0, 1), ks = R / S.Rw, ws = (D < 2 ? S.wsUK : cam.ws);
    var mx0 = D < 2 ? S.Cuk[0] : cam.x, my0 = D < 2 ? S.Cuk[1] : cam.y, col = 1 - smooth(D - 2), M = D0.m;
    var sx = S.sx, sy = S.sy, kx = S.kx, ky = S.ky, ps = S.pSub, ox = S.ox, oy = S.oy, dl = S.delay;
    for (i = 0; i < n; i++) {
      var s = ps[i], gx = cx + (M[2 * s] - mx0) * ws + ox[i] * col, gy = cy + (M[2 * s + 1] - my0) * ws + oy[i] * col;
      if (u <= 0) { sx[i] = cx + kx[i] * ks; sy[i] = cy - ky[i] * ks; }
      else if (u >= 1) { sx[i] = gx; sy[i] = gy; }
      else { var v = ease(clamp((u - dl[i]) / 0.7, 0, 1)), qx = cx + kx[i] * ks, qy = cy - ky[i] * ks; sx[i] = qx + (gx - qx) * v; sy[i] = qy + (gy - qy) * v; }
    }

    instruments(g, cam);
    if (D < 1 && (S.ring || S.repoLit)) {        // NL-010 5.5: amber is attention (kuiper-belt PALETTE.md)
      g.save(); g.globalAlpha = 1 - D; g.strokeStyle = C.amber; g.fillStyle = C.amber; g.lineWidth = 1.5;
      if (S.ring) { g.beginPath(); g.arc(cx + S.ring.x * ks, cy - S.ring.y * ks, 10, 0, 2 * Math.PI); g.stroke(); }
      if (S.repoLit) { g.beginPath(); for (var rl = 0; rl < S.repoLit.length; rl++) { var rq = S.repoLit[rl]; g.rect(sx[rq] - 1.5, sy[rq] - 1.5, 3, 3); } g.fill(); }
      g.restore();
    }
    if (S.grid && D > 1.6) drawLines(g, cam, mapA, smooth((D - 1.6) / 0.5));
    sweep(g);

    // the stars: the brightest thing on screen (halo, core, then the ones the arm has just crossed)
    var subsA = S.subs ? 1 : 1 - smooth((D - 1.2) / 0.8), sz = S.land ? Math.max(0.65, Math.min(1.05, S.Rpx / 180)) : (S.phone ? 1.8 : 2.1), hz = sz * (S.land ? 1.4 : 3.2), L = -12, Rr = W + 12, B = H + 12;
    g.save(); if (D >= 1.95) { g.beginPath(); g.arc(cx, cy, R, 0, 2 * Math.PI); g.clip(); }
    g.globalCompositeOperation = S.land ? 'source-over' : 'lighter';
    if (subsA > 0.01) {
      // halo and core: drawn into a cached layer, redrawn only when a star has moved
      var key = D.toFixed(5) + '|' + cam.x.toFixed(9) + cam.y.toFixed(9) + cam.z.toFixed(5) + '|' + subsA.toFixed(3) + (S.lite ? 'L' : '') + S.layoutN;
      var still = key === S.starKey;
      if (!still) {
        var sl = S.starCv, h = S.starCtx;
        if (sl.width !== S.cv.width || sl.height !== S.cv.height) { sl.width = S.cv.width; sl.height = S.cv.height; }
        h.setTransform(S.sc, 0, 0, S.sc, 0, 0); h.clearRect(0, 0, W, H); h.globalCompositeOperation = S.land ? 'source-over' : 'lighter';
        if (!S.land && !S.lite && Math.abs(S.D - S.Dgoal) < 0.01) {   // the halo only when the stars are at rest
          h.fillStyle = 'rgba(0,255,255,0.10)'; h.beginPath();
          for (i = 0; i < n; i++) { var x = sx[i], y = sy[i]; if (x > L && x < Rr && y > L && y < B) h.rect(x - hz / 2, y - hz / 2, hz, hz); }
          h.fill();
        }
        h.fillStyle = 'rgba(220,255,255,0.95)'; h.beginPath();
        for (i = 0; i < n; i++) { var x2 = sx[i], y2 = sy[i]; if (x2 > L && x2 < Rr && y2 > L && y2 < B) h.rect(x2 - sz / 2, y2 - sz / 2, sz, sz); }
        h.fill();
        S.starKey = key; S.bucketsOK = false;
      }
      g.globalAlpha = subsA; g.drawImage(S.starCv, 0, 0, W, H);
      // sweep light: stars in the 34 degrees behind the arm glow brighter. When the stars are still, they are sorted
      // once into 360 bearing buckets, so each frame only looks at the stars inside the wedge.
      if (S.scan || S.grab) {
        var arm = -S.sw, big = sz * (S.land ? 0.4 : 2.2), TW = 6.283185307179586, bs = S.bStart, bi = S.bItem;
        if (still && !S.bucketsOK) {
          var cnt = S.bCnt; cnt.fill(0);
          for (i = 0; i < n; i++) { var a0 = Math.atan2(sy[i] - cy, sx[i] - cx); a0 -= TW * Math.floor(a0 / TW); var q = (a0 * 360 / TW) | 0; if (q > 359) q = 359; S.bOf[i] = q; cnt[q]++; }
          bs[0] = 0; for (var q2 = 0; q2 < 360; q2++) bs[q2 + 1] = bs[q2] + cnt[q2];
          cnt.fill(0); for (i = 0; i < n; i++) { var qq = S.bOf[i]; bi[bs[qq] + cnt[qq]++] = i; }
          S.bucketsOK = true;
        }
        g.fillStyle = 'rgba(200,255,255,0.55)'; g.beginPath();
        if (still && S.bucketsOK) {
          var am = arm - TW * Math.floor(arm / TW), q0 = (am * 360 / TW) | 0;
          for (var w = 0; w < 36; w++) {
            var qb = (q0 + w) % 360;
            for (var t = bs[qb]; t < bs[qb + 1]; t++) {
              var j2 = bi[t], x4 = sx[j2], y4 = sy[j2]; if (x4 < L || x4 > Rr || y4 < L || y4 > B) continue;
              var d4 = Math.atan2(y4 - cy, x4 - cx) - arm; d4 -= TW * Math.floor(d4 / TW);
              if (d4 < 0.6) { var b4 = big * (1 - d4 / 0.6) + sz; g.rect(x4 - b4 / 2, y4 - b4 / 2, b4, b4); }
            }
          }
        } else {
          for (i = 0; i < n; i++) {
            var x3 = sx[i], y3 = sy[i]; if (x3 < L || x3 > Rr || y3 < L || y3 > B) continue;
            var dd = Math.atan2(y3 - cy, x3 - cx) - arm; dd -= TW * Math.floor(dd / TW);
            if (dd < 0.6) { var b = big * (1 - dd / 0.6) + sz; g.rect(x3 - b / 2, y3 - b / 2, b, b); }
          }
        }
        g.fill();
      }
    }
    // search lights: every matching star lit amber
    if (S.mN) {
      g.globalAlpha = 1; g.fillStyle = 'rgba(255,176,0,0.9)'; g.beginPath();
      for (var k = 0; k < S.mN; k++) { var j = S.mIdx[k]; g.rect(sx[j] - 3, sy[j] - 3, 6, 6); }
      g.fill();
    }
    g.restore(); g.globalCompositeOperation = 'source-over'; g.globalAlpha = 1;
    if (S.mN && S.q) rimLights(g);
    if (S.spiderOn && S.T >= 0 && D > 2.4) drawSpider(g, cam, now);
    if (S.T >= 0 && D > 1.0) drawTarget(g, cam);
  }

  function instruments(g, cam) {
    var cx = S.cx, cy = S.cy, R = S.Rpx, i;
    g.lineWidth = 1; g.strokeStyle = 'rgba(0,255,255,0.18)';
    for (i = 1; i <= 4; i++) { g.beginPath(); g.arc(cx, cy, R * i / 4, 0, 2 * Math.PI); g.stroke(); }
    g.strokeStyle = 'rgba(0,255,255,0.5)'; g.beginPath(); g.arc(cx, cy, R, 0, 2 * Math.PI); g.stroke();
    for (i = 0; i < 360; i += 5) {
      var a = (i - 90) * Math.PI / 180, l = i % 30 === 0 ? 14 : (i % 10 === 0 ? 8 : 4);
      g.strokeStyle = i % 30 === 0 ? 'rgba(0,255,255,0.45)' : 'rgba(0,255,255,0.22)';
      g.beginPath(); g.moveTo(cx + Math.cos(a) * (R + 3), cy + Math.sin(a) * (R + 3)); g.lineTo(cx + Math.cos(a) * (R + 3 + l), cy + Math.sin(a) * (R + 3 + l)); g.stroke();
    }
  }

  function sweep(g) {