GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / kuiper-belt / learn-the-kuiper/202610050609/modules

Descent (part 1)

A JavaScript file in the learn the kuiper folder of Kuiper Belt that maps 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 1529 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 / learn-the-kuiper/202610050609/modules/descent.js lines 1–700

Descent

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

geodesykuiper-belt / learn-the-kuiper/202610050609/modules/descent.js · lines 1–700 of 1035 · version 2026-10-05 06:09 · Entry point · pattern nearestToCentre (shared by 2 files)

What it does
It maps sat s, l sat and substations. Defines 70 functions or classes, including loadScript, ensureGridData, merc, unmercLat, decode. Side effects: changes the web page (DOM); reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: substations, 400kV, 132kV, 76kV, 27kV, 22kV.
Inputs & outputs
In: data source: gridatlas data; JSON file style.json; GeoJSON file kv.geojson. 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: Modes (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/modes.html). Reached from 4 other entry points, including Lesson (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/lesson.html); Menu (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050354/menu.html); Play (kuiper-belt, https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/play.html).
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 responds to click, pointerenter and pointerleave events.
Why it matters
Loaded by the Modes page at https://ventusltd.github.io/kuiper-belt/learn-the-kuiper/202610050609/modes.html.
Application
kuiper-belt · learn-the-kuiper/202610050609/modules · script
VEDIC
SWITCH (GG2050-VEDIC-000033): See Through / Kuiper · Computer science / Interactive visualisation. view, user_flag → selected_view
VEDIC
SEARCH (GG2050-VEDIC-000030): See Through / Kuiper · Computer science / Interactive visualisation. query, substation_names → match_count_and_indices
VEDIC
CHOOSE (GG2050-VEDIC-000031): See Through / Kuiper · Computer science / Interactive visualisation. query, match_list → selection_or_refusal
Uses
GridAtlas — Atlas Page (estate URL), Overlay (estate URL)
Used by
loaded by Modes (script src), mentioned in Standalone (comment link)
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, edge, camera, setTarget, wantMap, loadMap, go
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 learn-the-kuiper/202610050609/modules/descent.js:1-700 · blob ddb8b021cc84ebde41b09748a4015396b5387c9e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · 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.
(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 = 18;                // MapLibre zoom at the bottom of the fall
  var GA = 2.399963229728653;   // 2 pi (1 - 0.6180339887) radians (grid.js / pilot.mjs station clusters)
  var MAPLIBRE_JS = 'https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.js';    // GridAtlas shell index.html:133
  var MAPLIBRE_CSS = 'https://cdn.jsdelivr.net/npm/maplibre-gl@3.6.2/dist/maplibre-gl.css';  // GridAtlas shell index.html:8
  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';
  // 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';
    S.cx = W / 2; S.cy = H / 2;
    S.Rpx = Math.min(W, H) / 2 * (phone ? 0.94 : 0.88);
    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;
    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) {} }
    S.camKey = '';
  }

  function placeUI() {
    var bh = S.phone ? 56 : 72, W = S.W, H = S.H, port = S.port, land = S.land, pad = 'env(safe-area-inset-top)', bot = 'env(safe-area-inset-bottom)';
    var band = (W - 2 * S.Rpx) / 2, i;
    S.allBtns.forEach(function (b) { b.style.height = bh + 'px'; b.style.minWidth = bh + 'px'; b.style.padding = S.phone ? '0 8px' : '0 16px'; });
    S.xbtn.style.width = S.xbtn.style.height = '72px';
    S.satB.textContent = S.phone ? 'SAT' : 'SATELLITE';
    // mute: top right beside X, except on a phone held upright, where it joins the left stack
    if (port) { if (S.mute.parentNode !== S.grpUD) S.grpUD.insertBefore(S.mute, S.grpUD.firstChild); S.mute.style.position = 'static'; }
    else { if (S.mute.parentNode !== S.ui) S.ui.appendChild(S.mute); S.mute.style.position = 'absolute'; S.mute.style.top = 'calc(8px + ' + pad + ')'; S.mute.style.right = 'calc(' + (8 + 72 + 8) + 'px + env(safe-area-inset-right))'; }
    S.cap.style.fontSize = S.phone ? '24px' : '26px'; S.cap.style.maxHeight = land ? '86px' : '62px';
    var sTop, sLeft, sw, cTop, cardTop, cw, cl;
    if (port) {          // caption, then the search box, then the card, all above the porthole
      S.cap.style.top = 'calc(16px + ' + pad + ')'; S.cap.style.right = '96px';
      sTop = 84; sLeft = 12; sw = W - 24; cardTop = 182; cw = W - 24; cl = 12;
    } else if (land) {   // search across the top, caption and card in the left band
      var edge = function (y) { var dy = Math.min(S.Rpx, Math.abs(S.cy - y)); return S.cx - Math.sqrt(S.Rpx * S.Rpx - dy * dy); };
      sTop = 8; sLeft = 8; sw = Math.max(220, edge(60) - 18);
      S.cap.style.top = 'calc(72px + ' + pad + ')'; S.cap.style.right = (W - Math.max(band, edge(130)) + 4) + 'px';
      cardTop = 172; cw = band - 16; cl = 8;
    } else {             // desktop: caption top left, search top right, card on the left
      S.cap.style.top = 'calc(16px + ' + pad + ')'; S.cap.style.right = (W - S.cx + S.Rpx * 0.15) + 'px';
      sw = clamp(W - S.cx - 8 - 72 - 8 - bh - 12 - 40, 260, 440); sTop = 10; sLeft = W - (8 + 72 + 8 + bh + 12) - sw;
      cardTop = 112; cw = Math.max(300, Math.min(400, band + 80)); cl = 16;
    }
    S.search.style.left = sLeft + 'px'; S.search.style.top = 'calc(' + sTop + 'px + ' + pad + ')'; S.search.style.width = sw + 'px'; S.search.style.right = '';
    S.input.style.height = S.goB.style.height = (S.phone ? 52 : 56) + 'px';
    S.goB.style.minWidth = (S.phone ? 56 : 72) + 'px';
    S.note.style.left = sLeft + 'px'; S.note.style.width = sw + 'px'; S.note.style.right = '';
    S.note.style.top = 'calc(' + (sTop + 60) + 'px + ' + pad + ')';
    S.card.style.width = cw + 'px'; S.card.style.left = cl + 'px';
    S.card.style.top = 'calc(' + cardTop + 'px + ' + pad + ')';
    S.card.style.maxHeight = Math.max(110, port ? S.cy - S.Rpx * 0.3 - cardTop : H - cardTop - bh - 40) + 'px';
    // bottom-left: GRID SUBS SPIDER (GridAtlas position)
    S.grpBL.style.left = 'calc(8px + env(safe-area-inset-left))'; S.grpBL.style.bottom = 'calc(8px + ' + bot + ')';
    if (port) {
      S.grpView.style.flexDirection = 'column'; S.grpView.style.right = '8px'; S.grpView.style.bottom = 'calc(' + (bh + 16) + 'px + ' + bot + ')';
      S.grpUD.style.flexDirection = 'column'; S.grpUD.style.right = ''; S.grpUD.style.left = '8px'; S.grpUD.style.bottom = 'calc(' + (bh + 16) + 'px + ' + bot + ')';
    } else {
      S.grpView.style.flexDirection = 'row'; S.grpView.style.right = 'calc(8px + env(safe-area-inset-right))'; S.grpView.style.bottom = 'calc(8px + ' + bot + ')';
      S.grpUD.style.flexDirection = 'column'; S.grpUD.style.left = ''; S.grpUD.style.right = 'calc(8px + env(safe-area-inset-right))'; S.grpUD.style.bottom = 'calc(' + (bh + 16) + 'px + ' + bot + ')';
    }
    // attribution: in free black space, never over the porthole
    S.att.style.left = S.att.style.right = S.att.style.top = S.att.style.bottom = S.att.style.width = '';
    if (port) { S.att.style.left = (8 + bh + 10) + 'px'; S.att.style.width = Math.max(150, W - 2 * (8 + bh + 10) - 50) + 'px'; S.att.style.bottom = 'calc(' + (bh + 16) + 'px + ' + bot + ')'; S.att.style.textAlign = 'left'; }
    else if (land) { S.att.style.right = 'calc(8px + env(safe-area-inset-right))'; S.att.style.width = (band - 16) + 'px'; S.att.style.top = 'calc(84px + ' + pad + ')'; S.att.style.textAlign = 'right'; }
    else { S.att.style.right = '16px'; S.att.style.width = Math.max(240, band - 24) + 'px'; S.att.style.bottom = 'calc(' + (bh + 16 + 2 * (bh + 6) + 6) + 'px + ' + bot + ')'; S.att.style.textAlign = 'right'; }
    S.ro.style.display = S.phone ? 'none' : 'block';
    S.ro.style.bottom = 'calc(' + (bh + 16) + 'px + ' + bot + ')';
    void i;
  }

  // ---------------- 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
        });
      } 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) S.tileOK++; if (S && e && e.sourceId && /^ga/.test(e.sourceId) && e.isSourceLoaded) S.gaLines = true; });
      S.map.on('error', function () { if (S) S.tileErr++; });
    };
    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;
    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) mapFailed('net');
    }
  }
  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;
    S.view = v; if (byUser) S.viewTouched = true;
    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;
  }

  // ---------------- 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();
    S.flight = { phase: S.D > 0.15 ? 'up' : 'down', T: i };
    S.Dgoal = 0; S.speed = 3.2; hideCard();
    caption(S.flight.phase === 'up' ? 'UP TO THE STARS FIRST' : 'DOWN TO ' + nameOf(i).toUpperCase());
    if (S.flight.phase === 'down') { setTarget(i, false); S.Dgoal = DMAX; }
    if (S.view !== 'kuiper') loadMap();
  }

  // ---------------- 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 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'; setTarget(S.flight.T, false); S.Dgoal = DMAX; caption('DOWN TO ' + nameOf(S.flight.T).toUpperCase()); }
      else if (S.flight.phase === 'down' && S.D > DMAX - 0.02) { S.flight = null; S.speed = 2.4; arrive(); }
    }
    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
    var cam = camera(S.D);
    if (!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 (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.phone ? 1.8 : 2.1, hz = sz * 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 = '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 = 'lighter';
        if (!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 * 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();
    }
    // the outer ring states its own range: wafer units among the stars, metres or km over the Earth
    var lab;
    if (S.D < 1.5) lab = 'R ' + fmt(S.Rw);
    else {
      var lat = unmercLat(cam.y), mpp = 40075016.686 * Math.cos(lat * Math.PI / 180) / (S.D < 2 ? S.wsUK : cam.ws), m = mpp * R;
      lab = m >= 2000 ? fmt(m / 1000) + ' KM' : fmt(m) + ' M';
    }
    if (!S.phone || S.D > 2) {
      g.font = '24px ' + FONT; g.fillStyle = 'rgba(102,204,255,0.75)'; g.textAlign = 'left'; g.textBaseline = 'middle';
      if (S.port) { g.textAlign = 'center'; g.fillText(lab, cx, cy + R - 20); }
      else { var la = S.land ? -Math.PI / 4 : Math.PI / 4; g.fillText(lab, cx + Math.cos(la) * (R + 22), cy + Math.sin(la) * (R + 22) + (S.land ? -8 : 8)); }
    }
  }

  function sweep(g) {
    var cx = S.cx, cy = S.cy, R = S.Rpx, arm = -S.sw;
    if (!S.scan && !S.grab) return;
    g.save(); g.translate(cx, cy); g.rotate(arm);
    if (S.wedge) { g.fillStyle = S.wedge; g.beginPath(); g.moveTo(0, 0); g.arc(0, 0, R, 0, 0.62); g.closePath(); g.fill(); }
    else { for (var k = 0; k < 6; k++) { g.fillStyle = 'rgba(0,255,255,' + (0.025 * (6 - k) / 6).toFixed(3) + ')'; g.beginPath(); g.moveTo(0, 0); g.arc(0, 0, R, k * 0.1, (k + 1) * 0.1); g.closePath(); g.fill(); } }
    g.strokeStyle = 'rgba(0,255,255,0.7)'; g.lineWidth = 1.5; g.beginPath(); g.moveTo(0, 0); g.lineTo(R, 0); g.stroke();
    g.restore();
    // a soft ping when the arm crosses the selected substation
    if (S.T >= 0) {
      var a = Math.atan2(S.sy[S.T] - cy, S.sx[S.T] - cx), d = a - arm; d -= 6.283185307179586 * Math.floor(d / 6.283185307179586);
      if (d < 0.08 && !S.pinged) { S.pinged = true; if (S.D < 7.9) ping(7, 0.02); } else if (d > 0.3) S.pinged = false;
    }
  }

  function drawLines(g, cam, mapA, a) {
    var Ls = decodeLines(); if (!Ls) return;
    // when GridAtlas's own exact line files are drawing in the map, the simplified lines step back
    var ga = (S.mapState === 'ready' && S.gaLines) ? mapA : 0, alpha = a * (1 - ga) * 0.85;
    if (alpha < 0.01) return;
    var ws = S.D < 2 ? S.wsUK : cam.ws, x0 = S.D < 2 ? S.Cuk[0] : cam.x, y0 = S.D < 2 ? S.Cuk[1] : cam.y, cx = S.cx, cy = S.cy, W = S.W, H = S.H;
    var sets = [['grid132', '#00cc00', 1.2], ['grid400', '#0054ff', 2.2]];
    g.save(); g.beginPath(); g.arc(cx, cy, S.Rpx, 0, 2 * Math.PI); g.clip();
    g.globalAlpha = alpha;
    for (var q = 0; q < 2; q++) {
      var Lq = Ls[sets[q][0]]; if (!Lq) continue;
      var m = Lq.m, seg = Lq.seg, ns = Lq.ns;
      g.strokeStyle = sets[q][1]; g.lineWidth = sets[q][2]; g.beginPath();
      for (var e = 0; e < ns; e++) {
        var A = seg[2 * e], B = seg[2 * e + 1];
        var ax = cx + (m[2 * A] - x0) * ws, ay = cy + (m[2 * A + 1] - y0) * ws, bx = cx + (m[2 * B] - x0) * ws, by = cy + (m[2 * B + 1] - y0) * ws;
        if ((ax < 0 && bx < 0) || (ax > W && bx > W) || (ay < 0 && by < 0) || (ay > H && by > H)) continue;
        g.moveTo(ax, ay); g.lineTo(bx, by);
      }
      g.stroke();
    }
    g.restore();
  }

  function rimLights(g) {
    var cx = S.cx, cy = S.cy, R = S.Rpx + 22, n = S.mN, k;
    g.save(); g.globalCompositeOperation = 'lighter';
    if (n === 1 || S.mTotal === 1) {
      var j = S.mIdx[0], a = Math.atan2(S.sy[j] - cy, S.sx[j] - cx), rx = cx + Math.cos(a) * R, ry = cy + Math.sin(a) * R;
      var gr = g.createLinearGradient(rx, ry, S.sx[j], S.sy[j]);
      gr.addColorStop(0, 'rgba(255,176,0,0.9)'); gr.addColorStop(1, 'rgba(255,176,0,0.15)');
      g.strokeStyle = gr; g.lineWidth = 3; g.beginPath(); g.moveTo(rx, ry); g.lineTo(S.sx[j], S.sy[j]); g.stroke();
      g.fillStyle = 'rgba(255,176,0,0.95)'; g.beginPath(); g.arc(rx, ry, 7, 0, 2 * Math.PI); g.fill();
      g.strokeStyle = 'rgba(255,176,0,0.9)'; g.lineWidth = 2; g.beginPath(); g.arc(S.sx[j], S.sy[j], 12, 0, 2 * Math.PI); g.stroke();
    } else {
      g.fillStyle = 'rgba(255,176,0,0.55)';
      for (k = 0; k < n; k++) {
        var i = S.mIdx[k], b = Math.atan2(S.sy[i] - cy, S.sx[i] - cx);
        g.beginPath(); g.arc(cx + Math.cos(b) * R, cy + Math.sin(b) * R, 4, 0, 2 * Math.PI); g.fill();
      }
    }
    g.restore();
  }

  function drawTarget(g, cam) {
    var i = S.T, x = S.sx[i], y = S.sy[i], deep = S.D > 4.5;
    g.save(); g.strokeStyle = C.amber; g.lineWidth = 2;
    // crosshair with a clear middle, so the real compound stays visible under it
    var r = deep ? 26 : 12;
    g.beginPath(); g.arc(x, y, r, 0, 2 * Math.PI); g.stroke();
    if (deep) {
      g.lineWidth = 1.5; g.beginPath();
      g.moveTo(x - r - 14, y); g.lineTo(x - r + 6, y); g.moveTo(x + r - 6, y); g.lineTo(x + r + 14, y);
      g.moveTo(x, y - r - 14); g.lineTo(x, y - r + 6); g.moveTo(x, y + r - 6); g.lineTo(x, y + r + 14); g.stroke();
      g.fillStyle = C.amber; g.beginPath(); g.arc(x, y, 1.6, 0, 2 * Math.PI); g.fill();
    }
    // engineering leader from the substation to its card
    if (S.cardOn && S.D > 2.6) {
      var cr = S.card.getBoundingClientRect(), hr = S.host.getBoundingClientRect();
      var lx = cr.right - hr.left, ly = cr.top - hr.top + 24;
      if (S.port) { lx = cr.left - hr.left + cr.width * 0.5; ly = cr.bottom - hr.top; }
      g.setLineDash([6, 5]); g.strokeStyle = 'rgba(255,176,0,0.6)'; g.lineWidth = 1;
      var ang = Math.atan2(ly - y, lx - x);
      g.beginPath(); g.moveTo(x + Math.cos(ang) * (r + 4), y + Math.sin(ang) * (r + 4)); g.lineTo(lx, ly); g.stroke(); g.setLineDash([]);
    }
    g.restore();
  }

  function drawSpider(g, cam, now) {
    if (!S.spider || S.spider.from !== S.T) { S.spider = buildSpider(); S.spiderT0 = now; spiderCaption(); S.cardDirty = true; }
    var sp = S.spider; if (!sp) return;
    var cx = S.cx, cy = S.cy, R = S.Rpx, ws = cam.ws, x0 = S.sx[S.T], y0 = S.sy[S.T], t = (now - S.spiderT0) / 1000;
    var mpp = 40075016.686 * Math.cos(D0.lat[S.T] * Math.PI / 180) / ws;   // metres per screen pixel here
    g.save(); g.beginPath(); g.arc(cx, cy, R, 0, 2 * Math.PI); g.clip();
    for (var k = 0; k < sp.arrows.length && k < 60; k++) {
      var A = sp.arrows[k], tx = cx + (A.mx - cam.x) * ws, ty = cy + (A.my - cam.y) * ws;
      var dx = tx - x0, dy = ty - y0, len = Math.sqrt(dx * dx + dy * dy); if (len < 2) continue;
      var p = smooth((t - k * 0.15) / 1.1); if (p <= 0) continue;
      var ux = dx / len, uy = dy / len, ex = x0 + dx * p, ey = y0 + dy * p;
      var colr = A.kv >= 400 ? '#4d8bff' : (A.kv >= 275 ? '#ff5555' : (sp.kind === 'published' ? '#22ee77' : C.amber));