GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / cosmic / tools/explore/theme

Pilot

A JavaScript file in the theme folder of Cosmic that maps places, beacon, substations and overhead lines (OHL), and uses data from the GridAtlas repository.

700 lines of JavaScript from cosmic, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1155 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. Pilot render · cosmic / tools/explore/theme/pilot.js lines 1–700

Pilot

A JavaScript file in the theme folder of Cosmic that maps places, beacon, substations and overhead lines (OHL), and uses data from the GridAtlas repository.

rendercosmic / tools/explore/theme/pilot.js · lines 1–700 of 880 · Entry point · pattern makeView (shared by 2 files)

What it does
It maps places, beacon, substations and overhead lines (OHL). Defines 85 functions or classes, including noop, ease, turn, lattice, half. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain terms in the code: substations, overhead lines (OHL).
Inputs & outputs
In: data source: gridatlas data; JSON file places.json. Out: canvas drawing.
Downstream impact
Used directly by 1 file: Pilot (cosmic, https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html).
What it achieves
It sets origin (`setOrigin`), loads dem (`loadDem`) and sets basis (`setBasis`). Explore Code Pilot (HOTBAR-36; core flight, FAST MODE and window.PILOT contract v1: ALTIMETER-58 / Pilot-200 W01). It reads `places.json`. It responds to click, visibilitychange and keydown events.
Why it matters
Loaded by the page of the same name at https://ventusltd.github.io/cosmic/tools/explore/theme/pilot.html.
Application
cosmic · tools/explore/theme · script
Uses
GridAtlas — Index Page (estate URL)
Used by
loaded by Pilot (script src)
Produces
noop, ease, turn, lattice, half, sq, attach, warnOnce, clamp, fireReady, $, toLocal
Defines here
noop, ease, turn, lattice, half, sq, attach, warnOnce, clamp, fireReady, $, toLocal, toLL, setOrigin, tileXY, tileLL, loadDem, demAt, awsLL, groundLL, ground, camLL, dest, tileImg, tileGeo, pruneTiles, setBasis, cam3, scr, seg
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/theme/pilot.js:1-700 · blob 6a61f9737aa4fdc4ed08917bcc9481b0a7294d02 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
/* Explore Code Pilot (HOTBAR-36; core flight, FAST MODE and window.PILOT contract v1: ALTIMETER-58 / Pilot-200 W01).
   Plain script, no libraries, no CDN. Canvas 2D renderer with a pinhole camera in local metres round a floating origin.

   Places come only from places.json (theme/pilot.py): coordinates written in the estate's code files, each with
   the files that mention it and their keys. Grid lines and substations round a place are OpenStreetMap (ODbL) as
   published in the GridAtlas atlas-v9 release. Nothing here invents a location: flyTo(lat, lon) only goes where a
   caller (a code place, a module with real data, a URL #at=, or the person's own tap/entry) points it.

   Module contract: window.PILOT (see /tmp/vk/pilot200/CONTRACT.md, mirrored in SESSIONS/2026-12-05-EXPLORE-CODE-20/).
   Modules (theme/pilot-<name>.js) draw through PILOT.addLayer, steer through PILOT.flyTo and talk through PILOT.on/emit.

   Licence: Apache-2.0 for this file, with the grants noted per item (see theme/LICENSE-MANIFEST.md). Reused from the owner's own code (Ventus Ltd):
   - lattice(), attach(), KV and the vertex/infill tower rules. Originally CERN-OHL-S-2.0 (Ventusltd/globalgrid2050@9a12d0e24526a90dc1c75ac7d372c95e58d0c8ad energy-transition-simulator/202610290235/mod/pylons-real.js). Ventus Ltd additionally licenses this material under Apache-2.0 to the extent it holds the rights, effective 2026-12-05. Third-party material is excluded.
     The text came via Ventusltd/kuiper-belt@2b2d48dac5d132a2be9f127c430af5837c12e8c9 see-through/202610050356/model.js:150-167
     (Apache-2.0; the crossarm callback at lines 55-57 here equals model.js:163-165). Adapted to this renderer; tower
     shapes and sag are ESTIMATED by voltage class there and here; towers are ASSUMED at mapped line vertices.
   - ease() and turn() for the arrival flight. Originally CERN-OHL-S-2.0 (Ventusltd/globalgrid2050@9a12d0e24526a90dc1c75ac7d372c95e58d0c8ad solar-design-studio/202609271853-site-world/world/arrival.mjs). Ventus Ltd additionally licenses this material under Apache-2.0 to the extent it holds the rights, effective 2026-12-05. Third-party material is excluded.
   - Tile sources and credits as in globalgrid2050@9a12d0e24526a90dc1c75ac7d372c95e58d0c8ad
     energy-transition-simulator/202609282123/overlay.html lines 43-46 (Esri World Imagery; AWS Terrain Tiles).
   External hosts (page and modules) are allow-listed, each with its reason, in theme/test_pilot_static.py ALLOWED_HOSTS.
   Offline, the ground is a stylised grid. */
(function () {
  'use strict';
  var D = document, W = window;
  var REDUCED = !!(W.matchMedia && W.matchMedia('(prefers-reduced-motion: reduce)').matches);
  var SAT = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}';
  var DEM = 'https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png';
  var CREDIT = { sat: 'Imagery: Esri, Maxar, Earthstar Geographics', dem: 'Terrain: AWS Terrain Tiles (open)',
                 osm: 'Grid lines and substations © OpenStreetMap contributors, ODbL', off: 'Imagery offline: stylised grid' };
  var NO_NET = /[?&]offline=1/.test(location.search);
  var noop = function () {};
  // ---- from arrival.mjs (owner): smooth start/stop, shortest turn
  var ease = function (u) { return u * u * u * (u * (u * 6 - 15) + 10); };
  var turn = function (from, to) { var d = (to - from) % (2 * Math.PI); return d > Math.PI ? d - 2 * Math.PI : d < -Math.PI ? d + 2 * Math.PI : d; };

  // ---- from pylons-real.js (owner): estimated geometry by voltage class
  var KV = {
    '400': { H: 50, base: 6.0, armZ: [0.62, 0.77, 0.92], arm: [10.5, 12.0, 9.0], ins: 4.5, span: 360, a: 1500, col: '#4080ff' },
    '275': { H: 46, base: 5.5, armZ: [0.62, 0.77, 0.92], arm: [9.5, 11.0, 8.2], ins: 3.4, span: 340, a: 1400, col: '#ff4d4d' },
    '132': { H: 27, base: 3.2, armZ: [0.60, 0.76, 0.92], arm: [4.6, 5.3, 4.1], ins: 1.8, span: 280, a: 1100, col: '#33e666' }
  };
  var MERGE_M = 60, SEG = 10;
  function lattice(g) {
    var L = [], H = g.H, b = g.base, zw = g.armZ[0] * H - 2, w = b * 0.32, zt = g.armZ[2] * H + 1, wt = w * 0.8;
    var half = function (z) { return z <= zw ? b + (w - b) * z / zw : w + (wt - w) * (z - zw) / (zt - zw); };
    var lv = [0, zw * 0.3, zw * 0.58, zw * 0.8, zw].concat(g.armZ.map(function (f) { return f * H; }), [zt]);
    var sq = function (z) { var h = half(z); return [[-h, -h, z], [h, -h, z], [h, h, z], [-h, h, z]]; };
    for (var k = 0; k < lv.length; k++) {
      var A = sq(lv[k]);
      for (var i = 0; i < 4; i++) { var j = (i + 1) % 4; if (k > 0) L.push(A[i].concat(A[j])); }
      if (k + 1 < lv.length) { var B = sq(lv[k + 1]);
        for (i = 0; i < 4; i++) { j = (i + 1) % 4; L.push(A[i].concat(B[i]));
          if (lv[k] < zw) { L.push(A[i].concat(B[j])); L.push(A[j].concat(B[i])); } else L.push(A[i].concat(B[j])); } }
    }
    sq(zt).forEach(function (p) { L.push(p.concat([0, 0, H])); });
    g.armZ.forEach(function (f, k) { var z = f * H, h = half(z), a = g.arm[k];
      [-1, 1].forEach(function (s) { var tip = [0, s * a, z];
        L.push([-h, s * h, z].concat(tip), [h, s * h, z].concat(tip), [-h, s * h, z - 2.2].concat(tip), [h, s * h, z - 2.2].concat(tip), tip.concat([0, s * a, z - g.ins])); }); });
    return L;
  }
  function attach(g) { var P = []; g.armZ.forEach(function (f, k) { [-1, 1].forEach(function (s) { P.push([s * g.arm[k], f * g.H - g.ins]); }); }); P.push([0, g.H]); return P; }
  Object.keys(KV).forEach(function (k) { KV[k].lat = lattice(KV[k]); KV[k].att = attach(KV[k]); });

  // ======== window.PILOT: module contract v1 (W01-S01) ========
  var PILOT = W.PILOT = {}, bus = {}, mods = [], readyQ = [], isReady = false, warned = {};
  function warnOnce(k, e) { if (!warned[k]) { warned[k] = 1; try { console.warn('PILOT ' + k + ': ' + (e && e.message || e)); } catch (x) {} } }
  function clamp(v, a, b) { return v < a ? a : v > b ? b : v; }
  PILOT.version = '1';
  PILOT.reduced = REDUCED;
  PILOT.offline = NO_NET;
  PILOT.esc = function (s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]; }); };
  PILOT.on = function (n, fn) { (bus[n] = bus[n] || []).push(fn); return function () { PILOT.off(n, fn); }; };
  PILOT.off = function (n, fn) { var a = bus[n], i = a ? a.indexOf(fn) : -1; if (i >= 0) a.splice(i, 1); };
  PILOT.emit = function (n, d) { (bus[n] || []).slice().forEach(function (fn) { try { fn(d); } catch (e) { warnOnce('listener ' + n, e); } }); };
  PILOT.onFrame = function (fn) { return PILOT.on('frame', function (d) { fn(d.dt, d.now); }); };
  PILOT.ready = function (fn) { if (isReady) { try { fn(PILOT); } catch (e) { warnOnce('ready', e); } } else readyQ.push(fn); };
  function fireReady() { if (isReady) return; isReady = true; readyQ.splice(0).forEach(function (fn) { try { fn(PILOT); } catch (e) { warnOnce('ready', e); } }); PILOT.emit('ready', {}); }
  PILOT.module = function (name, info) { info = info || {}; mods = mods.filter(function (m) { return m.name !== name; }); mods.push({ name: String(name), version: String(info.version || ''), owner: String(info.owner || '') }); return PILOT; };
  PILOT.modules = function () { return mods.map(function (m) { return { name: m.name, version: m.version, owner: m.owner }; }); };

  // ---- state
  var cv = D.getElementById('pv'), cx = cv.getContext('2d');
  var $ = function (id) { return D.getElementById(id); };
  var DATA = null, P = null, idx = -1;
  var cam = { x: 0, y: -900, z: 260, yaw: 0, pitch: -0.32, speed: 0 };   // metres (local), radians, m/s
  var input = { yaw: 0, pitch: 0, thr: 0, lift: 0 };
  var flight = null, last = performance.now(), built = 0, frameNo = 0, fps = 60;
  var satFails = 0, demFails = 0, inflight = 0;
  var tiles = {}, nTiles = 0, dems = {}, satOK = false, demOK = false, satTried = false;
  var towers = [], subs = [], target = null;            // target: { lat, lon, label } beacon of the last flyTo
  var lat0 = 0, lon0 = 0, kx = 111320, originVer = 0;
  var FASTV = [140, 400, 1000, 2500], fast = 0, cruise = 0, settle = false, timeScale = 1;
  var imgPause = false, demPause = false, fovK = 1, streaks = 0, view = null;
  var mode = 'sat', modes = {}, layers = [], creditReg = {}, cardMode = 'place';

  // ---- floating origin (W01-S02): local metres x east, y north round (lat0, lon0)
  function toLocal(lat, lon) { return [(lon - lon0) * kx, (lat - lat0) * 111320]; }
  function toLL(x, y) { return [lat0 + y / 111320, lon0 + x / kx]; }
  function setOrigin(lat, lon) {
    var c = toLL(cam.x, cam.y), tw = towers.map(function (t) { return toLL(t.p[0], t.p[1]); });
    lat0 = lat; lon0 = lon; kx = 111320 * Math.cos(lat0 * Math.PI / 180); originVer++;
    var q = toLocal(c[0], c[1]); cam.x = q[0]; cam.y = q[1];
    towers.forEach(function (t, i) { t.p = toLocal(tw[i][0], tw[i][1]); });
    subs.forEach(function (s) { s.p = toLocal(s.lat, s.lon); });
    layers.forEach(function (l) { if (l.onOrigin) try { l.onOrigin(); } catch (e) { warnOnce('layer ' + l.id + ' onOrigin', e); } });
    PILOT.emit('origin', { lat0: lat0, lon0: lon0 });
  }
  PILOT.toLatLon = function (x, y) { return toLL(x, y); };
  PILOT.fromLatLon = function (lat, lon) { return toLocal(lat, lon); };
  PILOT._setOrigin = setOrigin;

  // ---- terrain height (Terrarium, z12) or 0
  var DZ = 12;
  function tileXY(lat, lon, z) { var n = Math.pow(2, z), x = (lon + 180) / 360 * n, r = lat * Math.PI / 180;
    return [x, (1 - Math.log(Math.tan(r) + 1 / Math.cos(r)) / Math.PI) / 2 * n]; }
  function tileLL(x, y, z) { var n = Math.pow(2, z), lon = x / n * 360 - 180, r = Math.atan(Math.sinh(Math.PI * (1 - 2 * y / n))); return [r * 180 / Math.PI, lon]; }
  function loadDem(tx, ty) {
    var k = tx + '/' + ty; if (dems[k] || NO_NET || demPause || (demFails >= 3 && !demOK)) return;
    dems[k] = { ok: false };
    var im = new Image(); im.crossOrigin = 'anonymous';
    im.onload = function () {
      try { var c = D.createElement('canvas'); c.width = c.height = 256; var g = c.getContext('2d'); g.drawImage(im, 0, 0);
        var d = g.getImageData(0, 0, 256, 256).data, h = new Float32Array(65536);
        for (var i = 0; i < 65536; i++) h[i] = d[i * 4] * 256 + d[i * 4 + 1] + d[i * 4 + 2] / 256 - 32768;
        dems[k] = { ok: true, h: h }; demOK = true; credits(); } catch (e) { dems[k] = { ok: false, err: 1 }; }
    };
    im.onerror = function () { dems[k] = { ok: false, err: 1 }; demFails++; };
    im.src = DEM.replace('{z}', DZ).replace('{x}', tx).replace('{y}', ty);
  }
  function demAt(lat, lon) { var t = tileXY(lat, lon, DZ); loadDem(Math.floor(t[0]), Math.floor(t[1])); }
  function awsLL(lat, lon) {
    if (!demOK) return 0;
    var t = tileXY(lat, lon, DZ), tx = Math.floor(t[0]), ty = Math.floor(t[1]);
    var d = dems[tx + '/' + ty]; if (!d || !d.ok) { if (!d) loadDem(tx, ty); return 0; }
    var px = Math.min(255, Math.max(0, Math.floor((t[0] - tx) * 256))), py = Math.min(255, Math.max(0, Math.floor((t[1] - ty) * 256)));
    return Math.max(0, d.h[py * 256 + px]);
  }
  // optional finer ground (pilot-lidar.js): fn(lat, lon, awsHeight) -> metres AMSL, or null to keep AWS
  var gsrc = null;
  PILOT.groundSource = function (fn) { gsrc = typeof fn === 'function' ? fn : null; return !!gsrc; };
  function groundLL(lat, lon) {
    var b = awsLL(lat, lon);
    if (gsrc) { try { var r = gsrc(lat, lon, b); if (r != null && isFinite(r)) return Math.max(-10, r); } catch (e) { warnOnce('groundSource', e); gsrc = null; } }
    return b;
  }
  function ground(x, y) { if (!demOK && !gsrc) return 0; var ll = toLL(x, y); return groundLL(ll[0], ll[1]); }

  // ---- helpers (W01-S03)
  var RAD = Math.PI / 180;
  PILOT.dist = function (la1, lo1, la2, lo2) {
    var a = Math.sin((la2 - la1) * RAD / 2), b = Math.sin((lo2 - lo1) * RAD / 2);
    var h = a * a + Math.cos(la1 * RAD) * Math.cos(la2 * RAD) * b * b; return 6378137 * 2 * Math.atan2(Math.sqrt(h), Math.sqrt(1 - h));   // engine atan2 form, R_ATLAS; replaced by PILOT.geo when pilot-estate.js loads
  };
  PILOT.bearing = function (la1, lo1, la2, lo2) {
    var y = Math.sin((lo2 - lo1) * RAD) * Math.cos(la2 * RAD), x = Math.cos(la1 * RAD) * Math.sin(la2 * RAD) - Math.sin(la1 * RAD) * Math.cos(la2 * RAD) * Math.cos((lo2 - lo1) * RAD);
    return ((Math.atan2(y, x) / RAD) % 360 + 360) % 360;
  };
  PILOT.ground = function (lat, lon) { try { return groundLL(+lat, +lon) || 0; } catch (e) { return 0; } };
  function camLL() { var ll = toLL(cam.x, cam.y), g = ground(cam.x, cam.y);
    return { lat: ll[0], lon: ll[1], alt: cam.z, agl: cam.z - g, hdg: ((cam.yaw / RAD) % 360 + 360) % 360, pitch: cam.pitch, speed: cam.speed }; }
  PILOT.camLL = camLL;
  PILOT.cam = cam;
  function dest(lat, lon, brg, m) {   // great-circle destination
    var b = brg * RAD, d = m / 6378137, p1 = lat * RAD, p2 = Math.asin(Math.sin(p1) * Math.cos(d) + Math.cos(p1) * Math.sin(d) * Math.cos(b));
    return [p2 / RAD, lon + Math.atan2(Math.sin(b) * Math.sin(d) * Math.cos(p1), Math.cos(d) - Math.sin(p1) * Math.sin(p2)) / RAD];
  }

  // ---- imagery tiles (z10-15 by height round the camera; W01-S11 pauses loading in the FAST arc cruise)
  function tileImg(x, y, z) {
    var k = z + '/' + x + '/' + y; if (tiles[k]) return tiles[k];
    if (NO_NET || imgPause || (satFails >= 8 && !satOK)) return { ok: false };
    if ((!satOK && satFails < 8 && inflight >= 3) || inflight >= 12) return { ok: false };   // probe gently until one tile works
    var t = tiles[k] = { im: new Image(), ok: false, x: x, y: y, z: z, ov: -1, used: frameNo }; nTiles++;
    inflight++; satTried = true;
    t.im.crossOrigin = 'anonymous';
    t.im.onload = function () { inflight--; t.ok = true; if (!satOK) { satOK = true; credits(); } };
    t.im.onerror = function () { inflight--; t.err = true; satFails++; credits(); };
    t.im.src = SAT.replace('{z}', z).replace('{y}', y).replace('{x}', x);
    return t;
  }
  function tileGeo(t) { if (t.ov !== originVer) { var a = tileLL(t.x, t.y, t.z), b = tileLL(t.x + 1, t.y + 1, t.z); t.nw = toLocal(a[0], a[1]); t.se = toLocal(b[0], b[1]); t.ov = originVer; } return t; }
  function pruneTiles() {
    if (nTiles < 360) return;
    Object.keys(tiles).map(function (k) { return [k, tiles[k].used]; }).sort(function (a, b) { return a[1] - b[1]; }).slice(0, 120)
      .forEach(function (e) { delete tiles[e[0]]; nTiles--; });
  }

  // ---- camera projection
  var Wd = 0, Ht = 0, F = 0, Fbase = 0, basis = null;
  function setBasis() {
    var sy = Math.sin(cam.yaw), cy = Math.cos(cam.yaw), sp = Math.sin(cam.pitch), cp = Math.cos(cam.pitch);
    var f = [sy, cy, 0], r = [cy, -sy, 0];
    basis = { r: r, fw: [f[0] * cp, f[1] * cp, sp], up: [-f[0] * sp, -f[1] * sp, cp] };
  }
  function cam3(x, y, z) {
    var dx = x - cam.x, dy = y - cam.y, dz = z - cam.z, b = basis;
    return [dx * b.r[0] + dy * b.r[1], dx * b.up[0] + dy * b.up[1] + dz * b.up[2], dx * b.fw[0] + dy * b.fw[1] + dz * b.fw[2]];
  }
  var NEAR = 2;
  function scr(c) { return [Wd / 2 + c[0] * F / c[2], Ht / 2 - c[1] * F / c[2]]; }
  function seg(a, b) {   // a, b camera coords; clip at near plane; returns screen pair or null
    if (a[2] < NEAR && b[2] < NEAR) return null;
    if (a[2] < NEAR) { var t = (NEAR - a[2]) / (b[2] - a[2]); a = [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, NEAR]; }
    else if (b[2] < NEAR) { t = (NEAR - b[2]) / (a[2] - b[2]); b = [b[0] + (a[0] - b[0]) * t, b[1] + (a[1] - b[1]) * t, NEAR]; }
    return [scr(a), scr(b)];
  }
  function line3(p, q) { var s = seg(cam3(p[0], p[1], p[2]), cam3(q[0], q[1], q[2])); if (!s) return; cx.moveTo(s[0][0], s[0][1]); cx.lineTo(s[1][0], s[1][1]); }

  // ---- view helper handed to layers each frame (W01-S13)
  function vProjectXYZ(x, y, z) { var c = cam3(x, y, z); if (c[2] < NEAR) return null; var s = scr(c); return { x: s[0], y: s[1], d: c[2] }; }
  function vProject(lat, lon, alt) { var p = toLocal(+lat, +lon); return vProjectXYZ(p[0], p[1], alt == null ? ground(p[0], p[1]) : +alt); }
  function vLine(a, b) {
    var p = toLocal(a[0], a[1]), q = toLocal(b[0], b[1]);
    line3([p[0], p[1], a[2] == null ? ground(p[0], p[1]) : a[2]], [q[0], q[1], b[2] == null ? ground(q[0], q[1]) : b[2]]);
  }
  function lodOf(agl, spd) { return Math.max(agl < 800 ? 0 : agl < 2500 ? 1 : agl < 6000 ? 2 : 3, spd > 900 ? 2 : spd > 300 ? 1 : 0); }
  function makeView() {
    var c = camLL(), R = Math.min(80000, 2500 + Math.max(0, c.agl) * 6), ah = R * 0.4;
    var ctr = toLL(cam.x + Math.sin(cam.yaw) * ah, cam.y + Math.cos(cam.yaw) * ah), dLat = R / 111320, dLon = R / (111320 * Math.cos(ctr[0] * RAD));
    return { w: Wd, h: Ht, f: F, cam: c, bbox: { s: ctr[0] - dLat, n: ctr[0] + dLat, w: ctr[1] - dLon, e: ctr[1] + dLon }, radius: R,
             lod: lodOf(c.agl, cam.speed), reduced: REDUCED, mode: mode, project: vProject, projectXYZ: vProjectXYZ, line: vLine };
  }

  // ---- build the place: towers along its real lines, substations (origin is already at the place)
  function dist(a, b) { return Math.hypot(b[0] - a[0], b[1] - a[1]); }
  function buildPlace() {
    towers = []; subs = [];
    (P.lines || []).forEach(function (ln) {
      var g = KV[ln.kv]; if (!g) return;
      var pts = ln.c.map(function (q) { return toLocal(q[1], q[0]); });
      var Pk = []; pts.forEach(function (p) { if (!Pk.length || dist(Pk[Pk.length - 1].p, p) >= MERGE_M) Pk.push({ p: p, est: false }); });
      var T = [];
      for (var i = 0; i < Pk.length; i++) {
        T.push(Pk[i]);
        if (i + 1 < Pk.length) { var d = dist(Pk[i].p, Pk[i + 1].p), n = Math.round(d / g.span) - 1;
          for (var k = 1; k <= n; k++) { var t = k / (n + 1), a = Pk[i].p, b = Pk[i + 1].p; T.push({ p: [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t], est: true }); } }
      }
      T.forEach(function (tw, i) {
        var dir = [0, 0];
        [i - 1, i + 1].forEach(function (j) { var o = T[j]; if (!o) return; var s = j < i ? 1 : -1, dx = (tw.p[0] - o.p[0]) * s, dy = (tw.p[1] - o.p[1]) * s, l = Math.hypot(dx, dy) || 1; dir[0] += dx / l; dir[1] += dy / l; });
        var l = Math.hypot(dir[0], dir[1]) || 1; tw.u = [dir[0] / l, dir[1] / l]; tw.kv = ln.kv; tw.next = T[i + 1] || null;
        tw.r = Math.hypot(tw.p[0], tw.p[1]);
        towers.push(tw);
      });
    });
    towers.sort(function (a, b) { return a.r - b.r; });
    towers = towers.slice(0, 220);
    towers.forEach(function (t) { t.gz = ground(t.p[0], t.p[1]); });
    subs = (P.subs || []).map(function (s) { var q = toLocal(s[0], s[1]); return { p: q, name: s[2] || 'Substation (unnamed in OSM)', lat: s[0], lon: s[1] }; });
    built = performance.now();
    demAt(P.lat, P.lon);
  }

  // ---- flights (W01-S04, S06): flyTo(lat, lon, opts) -> Promise; long hops use the FAST arc
  function cancelFlight(why) { if (!flight) return; var f = flight; flight = null; imgPause = false; f.reject(why || 'cancelled'); }
  function placeCam(lat, lon, z, yaw, pitch) { var q = toLocal(lat, lon); cam.x = q[0]; cam.y = q[1]; cam.z = z; cam.yaw = yaw; cam.pitch = pitch; }
  function arrive(info) {
    if (info.source === 'place') setHash({ place: idx, at: null });
    else setHash({ at: info.lat.toFixed(5) + ',' + info.lon.toFixed(5), place: null });
    PILOT.emit('arrive', info);
  }
  function flyTo(lat, lon, o) {
    o = o || {}; lat = +lat; lon = +lon;
    if (!isFinite(lat) || !isFinite(lon) || Math.abs(lat) > 85 || Math.abs(lon) > 180) { var bad = Promise.reject(new Error('flyTo: bad coordinate')); bad.catch(noop); return bad; }
    cancelFlight('cancelled');
    var c = camLL(), dkm = PILOT.dist(c.lat, c.lon, lat, lon) / 1000;
    var sd = o.dist == null ? 800 : Math.max(0, +o.dist || 0), agl = clamp(o.alt == null ? 230 : +o.alt || 0, 15, 6000);
    var hdg = o.hdg != null ? +o.hdg : (dkm > 0.05 ? PILOT.bearing(c.lat, c.lon, lat, lon) : c.hdg);
    var e = sd > 0 ? dest(lat, lon, hdg + 180, sd) : [lat, lon];
    var pitch = clamp(o.pitch != null ? +o.pitch : (sd > 0 ? -Math.atan2(agl, sd) : -1.45), -1.45, 0.3);
    var end = { lat: e[0], lon: e[1], agl: agl, z: groundLL(lat, lon) + agl, yaw: hdg * RAD, pitch: pitch, tlat: lat, tlon: lon };
    var info = { lat: lat, lon: lon, source: o.source ? String(o.source) : '', id: o.id == null ? null : o.id };
    target = o.beacon === false ? null : { lat: lat, lon: lon, label: o.label ? String(o.label) : '' };
    demAt(lat, lon);
    if (info.source !== 'place' && cardMode === 'place') showCard({ cap: 'FLYING TO', title: o.label || (lat.toFixed(5) + ', ' + lon.toFixed(5)), lat: lat, lon: lon }, true);
    PILOT.emit('depart', info);
    var p = new Promise(function (res, rej) {
      if (o.instant || REDUCED) {
        placeCam(end.lat, end.lon, end.z, end.yaw, end.pitch); cam.speed = 0; cruise = 0;
        if (Math.hypot(cam.x, cam.y) > 20000) setOrigin(lat, lon);
        arrive(info); res(info); return;
      }
      var arc = o.fast === true ? dkm > 0.5 : o.fast === false || o._swoop ? false : dkm > 5;
      flight = { from: { lat: c.lat, lon: c.lon, z: cam.z, yaw: cam.yaw, pitch: cam.pitch }, end: end, el: 0, arc: arc, info: info, resolve: res, reject: rej };
      if (o._swoop) {   // first arrival: the owner's arrival.mjs swoop, from behind and above
        var s0 = dest(end.lat, end.lon, hdg + 180 - 32, 3050); flight.from = { lat: s0[0], lon: s0[1], z: end.z + 1170, yaw: end.yaw - 0.5, pitch: -0.6 };
        placeCam(s0[0], s0[1], end.z + 1170, end.yaw - 0.5, -0.6);
      }
      flight.dyaw = turn(flight.from.yaw, end.yaw);
      if (arc) { flight.s = 3 + 2.2 * Math.log(Math.max(1, dkm)) / Math.LN2; flight.peak = Math.min(12000, 400 + dkm * 60); flight.cy = PILOT.bearing(c.lat, c.lon, end.lat, end.lon) * RAD; }
      else flight.s = o._swoop ? 3.2 : clamp(2.2 + dkm * 0.6, 2.2, 5);
      cam.speed = 0; cruise = 0;
    });
    p.catch(noop);
    return p;
  }
  function flyStep(rdt) {
    var f = flight, a = f.from, e = f.end, px = cam.x, py = cam.y;
    f.el += rdt; var u = Math.min(1, f.el / f.s), k = ease(u);
    if (!demPause) e.z = Math.max(e.z, groundLL(e.tlat, e.tlon) + e.agl);
    var la = a.lat + (e.lat - a.lat) * k, lo = a.lon + (e.lon - a.lon) * k, z = a.z + (e.z - a.z) * k, yaw, pitch;
    if (f.arc) {   // climb - cruise - dive; the view tips down at the country racing below
      var hp = Math.min(1, Math.sin(Math.PI * u) * 1.6);
      z = z * (1 - hp) + (Math.max(a.z, e.z) + f.peak) * hp;
      yaw = u < 0.15 ? a.yaw + turn(a.yaw, f.cy) * ease(u / 0.15) : u < 0.75 ? f.cy : f.cy + turn(f.cy, e.yaw) * ease((u - 0.75) / 0.25);
      pitch = u < 0.2 ? a.pitch + (-0.75 - a.pitch) * ease(u / 0.2) : u < 0.8 ? -0.75 : -0.75 + (e.pitch + 0.75) * ease((u - 0.8) / 0.2);
      imgPause = u > 0.15 && u < 0.85;
    } else { yaw = a.yaw + f.dyaw * k; pitch = a.pitch + (e.pitch - a.pitch) * k; }
    placeCam(la, lo, z, yaw, pitch);
    cam.speed = rdt > 0 ? Math.hypot(cam.x - px, cam.y - py) / rdt : 0;
    if (u >= 1) { flight = null; imgPause = false; cam.speed = 0; arrive(f.info); f.resolve(f.info); }
  }
  function flyToPlace(i, instant, first) {
    if (!DATA || !DATA.places.length) { var r = Promise.reject(new Error('no places')); r.catch(noop); return r; }
    idx = ((i % DATA.places.length) + DATA.places.length) % DATA.places.length; P = DATA.places[idx];
    cancelFlight('cancelled');
    setOrigin(P.lat, P.lon); buildPlace();
    // Frame the beacon with the nearest real line behind it: stand on the far side of the coordinate.
    var cxm = 0, cym = 0, nn = Math.min(20, towers.length);
    for (var q = 0; q < nn; q++) { cxm += towers[q].p[0]; cym += towers[q].p[1]; }
    var dir = nn ? [cxm / nn, cym / nn] : [420, 680];
    cardMode = 'place'; renderCard(); credits();
    return flyTo(P.lat, P.lon, { hdg: Math.atan2(dir[0], dir[1]) / RAD, dist: 800, alt: 230, pitch: -0.26, label: P.name, source: 'place', id: idx, instant: instant, _swoop: first });
  }
  PILOT.flyTo = flyTo;
  PILOT.flyToPlace = function (i, opts) { return flyToPlace(+i || 0, opts && opts.instant); };
  PILOT.places = function () { return DATA ? DATA.places : []; };
  PILOT.stop = function () { cancelFlight('cancelled'); if (steerFn) { steerFn = null; PILOT.emit('steer:cancel', { reason: 'stop' }); } cam.speed = 0; cruise = 0; };
  PILOT.setSpeed = function (mps) { cancelFlight('cancelled'); cruise = clamp(+mps || 0, 0, FASTV[fast]); };
  Object.defineProperty(PILOT, '_timeScale', { get: function () { return timeScale; }, set: function (v) { timeScale = clamp(+v || 1, 0.1, 50); } });

  // ---- FAST MODE (W01-S07..S10)
  var fb = D.createElement('button');
  fb.type = 'button'; fb.id = 'p-fast'; fb.className = 'pbtn'; fb.textContent = 'FAST'; fb.setAttribute('aria-pressed', 'false');
  fb.setAttribute('aria-label', 'Fast mode: tap to step up the speed level (off, 1, 2, 3)');
  D.body.appendChild(fb);
  function setFast(l) {
    l = clamp(Math.round(+l || 0), 0, 3); fast = l;
    if (l > 0) { cancelFlight('cancelled'); cruise = FASTV[l]; settle = false; }
    else { cruise = Math.min(cruise, 60); if (camLL().agl > 1500) settle = true; }
    fb.textContent = l ? 'FAST ' + l : 'FAST'; fb.setAttribute('aria-pressed', l ? 'true' : 'false'); fb.setAttribute('data-level', l);
    PILOT.emit('fast', { level: l });
  }
  fb.addEventListener('click', function () { setFast((fast + 1) % 4); });
  PILOT.setFast = setFast;
  PILOT.fast = function () { return fast; };

  // ---- HUD + card
  var HDG = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];
  function nearest() {
    var best = null, bd = 1e12;
    subs.forEach(function (s) { var d = Math.hypot(s.p[0] - cam.x, s.p[1] - cam.y); if (d < bd) { bd = d; best = { n: s.name, kind: 'substation (OSM)' }; } });
    towers.forEach(function (t) { var d = Math.hypot(t.p[0] - cam.x, t.p[1] - cam.y); if (d < bd) { bd = d; best = { n: t.kv + ' kV line ' + (t.est ? 'span (estimated tower)' : 'vertex'), kind: 'pylon' }; } });
    if (target) { var tp = toLocal(target.lat, target.lon), dp = Math.hypot(tp[0] - cam.x, tp[1] - cam.y); if (dp < bd) { bd = dp; best = { n: target.label || 'target', kind: 'target' }; } }
    return best ? { n: best.n, kind: best.kind, d: bd } : null;
  }
  function fmtD(m) { return m < 1000 ? Math.round(m) + ' m' : (m / 1000).toFixed(1) + ' km'; }
  function hud() {
    var c = view.cam, deg = c.hdg, n = nearest();
    $('h-hdg').textContent = String(Math.round(deg) % 360).padStart(3, '0') + '° ' + HDG[Math.round(deg / 45) % 8];
    $('h-alt').textContent = Math.round(c.agl) + ' m AGL' + (demOK ? ' · ' + Math.round(cam.z) + ' m AMSL' : '');
    $('h-spd').textContent = (fast ? 'FAST ' + fast + ' · ' : '') + Math.round(cam.speed * 3.6) + ' km/h';
    $('h-pos').textContent = c.lat.toFixed(5) + ', ' + c.lon.toFixed(5);
    $('h-near').textContent = n ? n.n + ' · ' + fmtD(n.d) : '—';
    var tape = $('h-tape'), s = '';
    for (var k = -4; k <= 4; k++) { var d = (Math.round(deg / 10) * 10 + k * 10 + 360) % 360; s += (d % 90 === 0 ? HDG[d / 45] : String(d).padStart(3, '0')) + '  '; }
    tape.textContent = s;
  }
  function credits() {
    var c = [];
    if (mode === 'sat') { if (satOK) c.push(CREDIT.sat); else if (satTried || NO_NET) c.push(CREDIT.off); }
    else if (modes[mode] && modes[mode].credit) c.push(modes[mode].credit);
    if (demOK) c.push(CREDIT.dem);
    layers.forEach(function (l) { if (l.visible !== false && l.credit) c.push(String(l.credit)); });
    Object.keys(creditReg).forEach(function (k) { c.push(creditReg[k]); });
    c = c.filter(function (x, i) { return x && c.indexOf(x) === i; });
    var el = $('credit'); el.textContent = c.join(' · '); el.title = c.join('\n');
    var tag = mode === 'sat' ? (satOK ? 'SAT' : 'GRID') : String((modes[mode] && modes[mode].title) || mode).toUpperCase().slice(0, 5);
    $('h-sat').textContent = tag; $('h-sat').className = mode !== 'sat' || satOK ? 'ok' : 'off';
  }
  PILOT.credit = function (id, text) { if (text == null || text === '') delete creditReg[id]; else creditReg[id] = String(text); credits(); };
    $('credit').addEventListener('click', function () { this.classList.toggle('open'); });
  function cardExtra() { var x = $('c-x'); if (!x) { x = D.createElement('div'); x.id = 'c-x'; $('card').insertBefore(x, $('c-ctx')); } return x; }
  function renderCard() {
    var cap = $('card').querySelector('.cap'); if (cap) cap.textContent = 'PLACE NAMED IN CODE';
    cardExtra().textContent = '';
    if (!P) return;
    $('c-name').textContent = P.name;
    $('c-ll').textContent = P.lat.toFixed(5) + ', ' + P.lon.toFixed(5) + ' · place ' + (idx + 1) + ' of ' + DATA.places.length;
    $('c-n').textContent = P.n_files + ' file' + (P.n_files === 1 ? '' : 's') + ' name this coordinate' + (P.other_names && P.other_names.length ? ' (also: ' + P.other_names.join(', ') + ')' : '');
    var ul = $('c-files'); ul.textContent = '';
    P.files.forEach(function (f) {
      var li = D.createElement('li');
      var a = D.createElement('a'); a.href = '../' + f.url; a.textContent = f.title + ' :' + f.line;
      var k = D.createElement('code'); k.textContent = f.key;
      li.appendChild(a); li.appendChild(k); ul.appendChild(li);
    });
    $('c-ctx').textContent = (P.lines || []).length + ' grid line runs and ' + (P.subs || []).length + ' substations within 6 km (OpenStreetMap, ODbL). Towers: assumed at mapped vertices, infill and shape estimated.';
  }
  function showCard(o, internal) {
    var el = $('card');
    if (!o) { cardMode = 'place'; renderCard(); return el; }
    cardMode = internal ? 'place' : 'ext';   // the core's own "flying to" card still yields to the code place card
    el.classList.remove('min');
    var cap = el.querySelector('.cap'); if (cap) cap.textContent = o.cap || 'SELECTED';
    $('c-name').textContent = o.title || '';
    var has = o.lat != null && o.lon != null && isFinite(o.lat) && isFinite(o.lon);
    $('c-ll').textContent = has ? (+o.lat).toFixed(5) + ', ' + (+o.lon).toFixed(5) : '';
    $('c-n').textContent = ''; $('c-files').textContent = ''; $('c-ctx').textContent = '';
    var x = cardExtra(); x.innerHTML = o.html || '';
    if (has && !internal) {
      var b = D.createElement('button'); b.type = 'button'; b.className = 'pbtn'; b.textContent = 'Fly here';
      b.addEventListener('click', function () { flyTo(+o.lat, +o.lon, { dist: 600, label: o.title, source: 'card', id: o.id }); });
      x.appendChild(b);
    }
    return el;
  }
  PILOT.card = function (o) { return showCard(o || null, false); };
  var noteT = 0;
  PILOT.note = function (text, ms) { var n = $('note'); n.textContent = String(text); n.hidden = false; clearTimeout(noteT); noteT = setTimeout(function () { n.hidden = true; }, ms || 5000); };

  // ---- HUD slots (W01-S16)
  var slots = {};
  function slotEl(name) {
    if (slots[name]) return slots[name];
    var el = D.createElement('div'); el.id = 'p-hud-' + name; el.className = 'p-hud p-hud-' + name; D.body.appendChild(el); slots[name] = el; layoutSlots(); return el;
  }
  function layoutSlots() {
    var hb = $('hud').getBoundingClientRect().bottom + 4, y = hb;
    if (slots.status) { slots.status.style.top = y + 'px'; y += slots.status.offsetHeight + (slots.status.offsetHeight ? 4 : 0); }
    if (slots.top) { slots.top.style.top = y + 'px'; y += slots.top.offsetHeight + (slots.top.offsetHeight ? 4 : 0); }
    if (slots.left) slots.left.style.top = y + 'px';
    if (slots.right) slots.right.style.top = y + 'px';
    if (slots.bottom) {
      var wide = W.innerWidth >= 900, card = $('card'), ref = wide ? $('pad') : (card.offsetHeight ? card : $('pad'));
      slots.bottom.style.bottom = (W.innerHeight - ref.getBoundingClientRect().top + 6) + 'px';
    }
  }
  PILOT.hud = function (slot, html) {
    var parts = String(slot || '').split(':'), base = parts[0], key = (parts[1] || '_').replace(/[^\w-]/g, '');
    if (!/^(top|left|right|bottom|status)$/.test(base)) { warnOnce('hud slot ' + base, 'unknown slot, using status'); base = 'status'; }
    var el = slotEl(base), sub = null;
    for (var i = 0; i < el.children.length; i++) if (el.children[i].getAttribute('data-key') === key) sub = el.children[i];
    if (!sub) { sub = D.createElement('div'); sub.className = 'p-hud-sub'; sub.setAttribute('data-key', key); el.appendChild(sub); }
    if (html == null || html === '') { sub.innerHTML = ''; sub.hidden = true; }
    else { if (typeof html === 'string') sub.innerHTML = html; else { sub.textContent = ''; sub.appendChild(html); } sub.hidden = false; }
    layoutSlots();
    return sub;
  };

  // ---- panel dock (W01-S17): bottom sheet on phones, side sheet from 900 px
  var panels = {}, openName = null, tabsEl = null, sheet = null, sheetT = null, sheetB = null;
  function ensureDock() {
    if (sheet) return;
    tabsEl = D.createElement('div'); tabsEl.id = 'p-tabs'; tabsEl.setAttribute('role', 'toolbar'); tabsEl.setAttribute('aria-label', 'Panels'); D.body.appendChild(tabsEl);
    sheet = D.createElement('section'); sheet.id = 'p-sheet'; sheet.hidden = true; sheet.setAttribute('aria-labelledby', 'p-sheet-t');
    var hd = D.createElement('header'); sheetT = D.createElement('h2'); sheetT.id = 'p-sheet-t';
    var x = D.createElement('button'); x.type = 'button'; x.className = 'pbtn'; x.textContent = '✕'; x.setAttribute('aria-label', 'Close panel'); x.addEventListener('click', closePanel);
    hd.appendChild(sheetT); hd.appendChild(x); sheet.appendChild(hd);
    sheetB = D.createElement('div'); sheetB.className = 'p-sheet-b'; sheet.appendChild(sheetB);
    D.body.appendChild(sheet); D.body.classList.add('p-has-tabs');
  }
  function openPanel(name) {
    var p = panels[name]; if (!p) return;
    if (openName && openName !== name) PILOT.emit('panel', { name: openName, open: false });
    Object.keys(panels).forEach(function (k) { panels[k].body.hidden = k !== name; panels[k].tab.setAttribute('aria-expanded', k === name ? 'true' : 'false'); });
    sheetT.textContent = p.title; sheet.hidden = false; openName = name; D.body.classList.add('p-panel-open');
    PILOT.emit('panel', { name: name, open: true });
  }
  function closePanel() {
    if (!openName) return; var n = openName; openName = null;
    if (panels[n]) panels[n].tab.setAttribute('aria-expanded', 'false');
    sheet.hidden = true; D.body.classList.remove('p-panel-open');
    PILOT.emit('panel', { name: n, open: false });
  }
  PILOT.panel = function (name, html, o) {
    o = o || {}; ensureDock(); name = String(name); var p = panels[name];
    if (!p) {
      var tab = D.createElement('button'); tab.type = 'button'; tab.className = 'pbtn'; tab.id = 'p-tab-' + name.replace(/[^\w-]/g, '');
      tab.setAttribute('aria-controls', 'p-sheet'); tab.setAttribute('aria-expanded', 'false');
      tab.addEventListener('click', function () { if (openName === name) closePanel(); else openPanel(name); });
      var body = D.createElement('div'); body.className = 'p-pbody'; body.hidden = true; sheetB.appendChild(body);
      p = panels[name] = { tab: tab, body: body, title: name }; tabsEl.appendChild(tab);
    }
    if (o.title) p.title = String(o.title);
    p.tab.textContent = p.title; p.tab.title = p.title;   // plain names, no code prefixes (UI review)
    if (html != null) { if (typeof html === 'string') p.body.innerHTML = html; else { p.body.textContent = ''; p.body.appendChild(html); } }
    if (openName === name) sheetT.textContent = p.title;
    if (o.open) openPanel(name); else if (o.open === false && openName === name) closePanel();
    return p.body;
  };
  PILOT.openPanel = openPanel;
  PILOT.closePanel = closePanel;

  // ---- data (W01-S19): memoised, de-duplicated fetches; offline mode never leaves this origin
  var memo = {};
  function fetchAny(url, o, kind) {
    o = o || {}; var key = kind + ' ' + url, host, same;
    try { var u = new URL(url, location.href); host = u.host; same = u.origin === location.origin; } catch (e) { host = String(url); same = false; }
    if (o.cache !== false && memo[key]) return memo[key];
    var p = new Promise(function (res, rej) {
      if (NO_NET && !same) { rej(new Error('offline: not fetching ' + host)); return; }
      var ctl = W.AbortController ? new AbortController() : null;
      var tm = setTimeout(function () { if (ctl) ctl.abort(); rej(new Error('timeout ' + host)); }, o.timeout || 20000);
      fetch(url, ctl ? { signal: ctl.signal } : {}).then(function (r) { if (!r.ok) throw new Error('HTTP ' + r.status + ' ' + host); return kind === 'json' ? r.json() : r.text(); })
        .then(function (d) { clearTimeout(tm); res(d); }, function (e) { clearTimeout(tm); var m = (e && e.message) || 'fetch failed'; rej(m.indexOf(host) >= 0 ? e : new Error(m + ' ' + host)); });
    });
    if (o.cache !== false) { memo[key] = p; p.catch(function () { if (memo[key] === p) delete memo[key]; }); }
    return p;
  }
  PILOT.data = { GA: 'https://ventusltd.github.io/gridatlas/',
    fetchJSON: function (url, o) { return fetchAny(url, o, 'json'); },
    fetchText: function (url, o) { return fetchAny(url, o, 'text'); } };

  // ---- URL hash state (keeps every module's keys)
  function hashPairs() { return location.hash.replace(/^#/, '').split('&').filter(Boolean).map(function (kv) { var i = kv.indexOf('='); return i < 0 ? [kv, ''] : [kv.slice(0, i), kv.slice(i + 1)]; }); }
  function setHash(obj) {
    var ps = hashPairs();
    Object.keys(obj).forEach(function (k) {
      var v = obj[k], i = -1; ps.forEach(function (p, j) { if (p[0] === k) i = j; });
      if (v == null || v === '') { if (i >= 0) ps.splice(i, 1); }
      else { var enc = encodeURIComponent(String(v)).replace(/%2C/gi, ','); if (i >= 0) ps[i][1] = enc; else ps.push([k, enc]); }
    });
    try { history.replaceState(null, '', location.pathname + location.search + (ps.length ? '#' + ps.map(function (p) { return p[0] + '=' + p[1]; }).join('&') : '')); } catch (e) {}
  }
  PILOT.hash = function (key, val) {
    if (arguments.length < 2) { var ps = hashPairs(); for (var i = 0; i < ps.length; i++) if (ps[i][0] === key) { try { return decodeURIComponent(ps[i][1]); } catch (e) { return ps[i][1]; } } return null; }
    var o = {}; o[key] = val; setHash(o); return val;
  };

  // ---- layers (W01-S12) and modes (W01-S15)
  PILOT.addLayer = function (l) {
    if (!l || !l.id) throw new Error('PILOT.addLayer needs an id');
    layers = layers.filter(function (x) { return x.id !== l.id; });
    if (l.order == null) l.order = 50; if (l.visible == null) l.visible = true; l._ms = 0;
    layers.push(l); layers.sort(function (a, b) { return a.order - b.order; });
    credits(); return l;
  };
  PILOT.removeLayer = function (id) { var n = layers.length; layers = layers.filter(function (l) { return l.id !== id; }); if (n !== layers.length) credits(); };
  PILOT.layer = function (id) { for (var i = 0; i < layers.length; i++) if (layers[i].id === id) return layers[i]; return null; };
  PILOT.layers = function () { return layers.slice(); };
  PILOT.setLayerVisible = function (id, on) { var l = PILOT.layer(id); if (l) { l.visible = !!on; credits(); } return l; };
  PILOT.registerMode = function (name, m) { if (!name || !m) return; modes[name] = m; if (name === mode) credits(); };
  PILOT.setMode = function (name) {
    if (!modes[name]) { warnOnce('mode ' + name, 'unknown mode (no-op)'); return mode; }
    if (name === mode) return mode;
    var old = modes[mode]; if (old && old.exit) try { old.exit(); } catch (e) { warnOnce('mode exit ' + mode, e); }
    mode = name; var m = modes[name]; if (m.enter) try { m.enter(); } catch (e) { warnOnce('mode enter ' + name, e); }
    credits(); PILOT.emit('mode', { name: name }); return mode;
  };
  PILOT.mode = function () { return mode; };

  // ---- draw
  function resize() {
    var dpr = Math.min(W.devicePixelRatio || 1, 2);
    Wd = cv.clientWidth; Ht = cv.clientHeight;
    cv.width = Math.round(Wd * dpr); cv.height = Math.round(Ht * dpr);
    cx.setTransform(dpr, 0, 0, dpr, 0, 0);
    Fbase = Math.max(Wd, Ht) * 0.62; F = Fbase * fovK;
    layoutSlots(); PILOT.emit('resize', { w: Wd, h: Ht });
  }
  function drawTri(im, s0, s1, s2, u0, u1, u2) {   // affine-map image triangle (u) onto screen triangle (s)
    var den = u0[0] * (u1[1] - u2[1]) + u1[0] * (u2[1] - u0[1]) + u2[0] * (u0[1] - u1[1]); if (!den) return;
    var a = (s0[0] * (u1[1] - u2[1]) + s1[0] * (u2[1] - u0[1]) + s2[0] * (u0[1] - u1[1])) / den,
        b = (s0[1] * (u1[1] - u2[1]) + s1[1] * (u2[1] - u0[1]) + s2[1] * (u0[1] - u1[1])) / den,
        c = (s0[0] * (u2[0] - u1[0]) + s1[0] * (u0[0] - u2[0]) + s2[0] * (u1[0] - u0[0])) / den,
        d = (s0[1] * (u2[0] - u1[0]) + s1[1] * (u0[0] - u2[0]) + s2[1] * (u1[0] - u0[0])) / den,
        e = (s0[0] * (u1[0] * u2[1] - u2[0] * u1[1]) + s1[0] * (u2[0] * u0[1] - u0[0] * u2[1]) + s2[0] * (u0[0] * u1[1] - u1[0] * u0[1])) / den,
        f = (s0[1] * (u1[0] * u2[1] - u2[0] * u1[1]) + s1[1] * (u2[0] * u0[1] - u0[0] * u2[1]) + s2[1] * (u0[0] * u1[1] - u1[0] * u0[1])) / den;
    cx.save(); cx.beginPath(); cx.moveTo(s0[0], s0[1]); cx.lineTo(s1[0], s1[1]); cx.lineTo(s2[0], s2[1]); cx.closePath(); cx.clip();
    var dpr = cv.width / Wd; cx.setTransform(a * dpr, b * dpr, c * dpr, d * dpr, e * dpr, f * dpr); cx.drawImage(im, 0, 0); cx.restore();
  }
  function drawSky() {
    var hy = Ht / 2 - Math.tan(cam.pitch) * F;
    var sky = cx.createLinearGradient(0, 0, 0, Math.max(1, hy)); sky.addColorStop(0, '#000'); sky.addColorStop(1, '#06202a');
    cx.fillStyle = sky; cx.fillRect(0, 0, Wd, Math.max(0, hy));
    cx.fillStyle = '#020507'; cx.fillRect(0, Math.max(0, hy), Wd, Ht);
  }
  function drawGrid(g, v) {   // offline / loading / high: stylised grid in the simulator's wire look, spacing grows with height
    var agl = Math.max(1, v.cam.agl), step = 100 * Math.pow(10, Math.max(0, Math.floor(Math.log(agl / 250) / Math.LN10))), big = step * 10, RR = step * 30;
    var gx = Math.round(cam.x / step) * step, gy = Math.round(cam.y / step) * step;
    cx.lineWidth = 1;
    for (var k = -RR; k <= RR; k += step) {
      cx.strokeStyle = (gx + k) % big === 0 ? 'rgba(0,255,255,.28)' : 'rgba(0,255,255,.09)';
      cx.beginPath(); line3([gx + k, gy - RR, 0], [gx + k, gy + RR, 0]); cx.stroke();
      cx.strokeStyle = (gy + k) % big === 0 ? 'rgba(0,255,255,.28)' : 'rgba(0,255,255,.09)';
      cx.beginPath(); line3([gx - RR, gy + k, 0], [gx + RR, gy + k, 0]); cx.stroke();
    }
  }
  var lastMissing = 1;
  function drawSat(g, v) {
    if (NO_NET || lastMissing || !satOK) drawGrid(g, v);
    if (NO_NET) return;
    var agl = Math.max(1, v.cam.agl), missing = 0;
    var z = clamp(15 - Math.round(Math.log(Math.max(1, agl / 450)) / Math.LN2), 10, 15);
    var ahead = clamp(agl / Math.tan(Math.max(0.12, -cam.pitch)), 300, 30000) * 0.6;
    var ll = toLL(cam.x + Math.sin(cam.yaw) * ahead, cam.y + Math.cos(cam.yaw) * ahead), t = tileXY(ll[0], ll[1], z), tx = Math.floor(t[0]), ty = Math.floor(t[1]);
    var flat = agl > 3000, R = Wd < 600 ? (z < 15 ? 2 : 1) : 2, N = flat ? 3 : Wd < 600 ? 4 : 6;
    var hz = function (X, Y) { return flat ? 0 : ground(X, Y); };
    for (var y = ty - R; y <= ty + R; y++) for (var x = tx - R; x <= tx + R; x++) {
      var tl = tileImg(x, y, z); if (!tl.ok) { missing++; continue; }
      tileGeo(tl); tl.used = frameNo;
      var w = tl.se[0] - tl.nw[0], h = tl.se[1] - tl.nw[1];
      for (var j = 0; j < N; j++) for (var i = 0; i < N; i++) {
        var c = [], u = [], ok = true;
        for (var m = 0; m < 4; m++) {
          var qx = i + (m === 1 || m === 2 ? 1 : 0), qy = j + (m >= 2 ? 1 : 0), X = tl.nw[0] + w * qx / N, Y = tl.nw[1] + h * qy / N, cc = cam3(X, Y, hz(X, Y));
          if (cc[2] < NEAR * 4) { ok = false; break; } c.push(scr(cc)); u.push([256 * qx / N, 256 * qy / N]);
        }
        if (!ok) continue;
        drawTri(tl.im, c[0], c[1], c[2], u[0], u[1], u[2]); drawTri(tl.im, c[0], c[2], c[3], u[0], u[2], u[3]);
      }
    }
    lastMissing = missing; pruneTiles();
  }
  modes.sat = { title: 'Satellite', ground: drawSat };
  modes.grid = { title: 'Grid', credit: CREDIT.off.replace('Imagery offline: ', 'Ground: '), ground: drawGrid };

  function drawPlaces(g, v, now) {
    var grow = REDUCED ? 1 : Math.min(1, (now - built) / 2200);   // pylons rise in order of distance: the build-up
    var pulse = REDUCED ? 0 : (now / 1000) % 1, far = v.lod >= 3 ? 0 : 7000;
    towers.forEach(function (t, n) {
      var share = Math.min(1, Math.max(0, grow * 1.4 - n / towers.length * 0.4)); if (share <= 0) return;
      var d = Math.hypot(t.p[0] - cam.x, t.p[1] - cam.y); if (d > far) return;
      var gk = KV[t.kv], u = t.u, vv = [-u[1], u[0]], o = t.p, gz = t.gz || 0;
      var X = function (a, l, z) { return [o[0] + u[0] * a + vv[0] * l, o[1] + u[1] * a + vv[1] * l, z * share + gz]; };
      cx.strokeStyle = d < 2500 ? 'rgba(210,220,230,.85)' : 'rgba(210,220,230,.45)'; cx.lineWidth = 1;
      cx.beginPath();
      if (d < 2200) gk.lat.forEach(function (s) { line3(X(s[0], s[1], s[2]), X(s[3], s[4], s[5])); });
      else { line3(X(0, 0, 0), X(0, 0, gk.H)); line3(X(0, -gk.arm[1], gk.armZ[1] * gk.H), X(0, gk.arm[1], gk.armZ[1] * gk.H)); }
      cx.stroke();
      if (t.next && share >= 1) {
        var nx = t.next, nv = [-nx.u[1], nx.u[0]], span = dist(o, nx.p), sag = span * span / (8 * gk.a);
        cx.strokeStyle = gk.col; cx.globalAlpha = .8; cx.beginPath();
        gk.att.forEach(function (at) {
          var A = X(0, at[0], at[1]), B = [nx.p[0] + nv[0] * at[0], nx.p[1] + nv[1] * at[0], at[1] + (nx.gz || 0)], prev = A;
          for (var k = 1; k <= SEG; k++) { var s = k / SEG, p = [A[0] + (B[0] - A[0]) * s, A[1] + (B[1] - A[1]) * s, A[2] + (B[2] - A[2]) * s - 4 * sag * s * (1 - s) * (at[0] ? 1 : 0.7)]; line3(prev, p); prev = p; }
        });
        cx.stroke(); cx.globalAlpha = 1;
        if (!REDUCED && d < 4000) {   // energy pulse travelling along the line
          var s = pulse, at = gk.att[2], A = X(0, at[0], at[1]), B = [nx.p[0] + nv[0] * at[0], nx.p[1] + nv[1] * at[0], at[1] + (nx.gz || 0)];
          var c3 = cam3(A[0] + (B[0] - A[0]) * s, A[1] + (B[1] - A[1]) * s, A[2] + (B[2] - A[2]) * s - 4 * sag * s * (1 - s));
          if (c3[2] > NEAR) { var q = scr(c3); cx.fillStyle = '#fff'; cx.shadowColor = gk.col; cx.shadowBlur = 8; cx.beginPath(); cx.arc(q[0], q[1], Math.max(1.5, 160 / c3[2]), 0, 7); cx.fill(); cx.shadowBlur = 0; }
        }
      }
    });
    subs.forEach(function (s) {
      var gz = ground(s.p[0], s.p[1]), sz = 30;
      cx.strokeStyle = '#ffae00'; cx.lineWidth = 1.5; cx.beginPath();
      var c = [[-sz, -sz], [sz, -sz], [sz, sz], [-sz, sz]];
      for (var i = 0; i < 4; i++) { var a = c[i], b = c[(i + 1) % 4]; line3([s.p[0] + a[0], s.p[1] + a[1], gz], [s.p[0] + b[0], s.p[1] + b[1], gz]); line3([s.p[0] + a[0], s.p[1] + a[1], gz], [s.p[0] + a[0], s.p[1] + a[1], gz + 8]); }
      cx.stroke();
      var l = cam3(s.p[0], s.p[1], gz + 30);
      if (l[2] > NEAR && l[2] < 4000) { var q = scr(l); cx.fillStyle = '#ffae00'; cx.font = '11px ui-monospace,monospace'; cx.fillText(s.name.slice(0, 28), q[0] + 4, q[1]); }
    });
  }
  function pickPlaces(sx, sy, v) {
    var best = null, bd = 24;
    subs.forEach(function (s) { var p = v.projectXYZ(s.p[0], s.p[1], ground(s.p[0], s.p[1]) + 15); if (p) { var d = Math.hypot(p.x - sx, p.y - sy); if (d < bd) { bd = d; best = s; } } });
    return best ? { title: best.name, cap: 'SUBSTATION (OPENSTREETMAP)', lat: best.lat, lon: best.lon,
      html: '<p class="dim">Mapped in OpenStreetMap (ODbL), as published in the GridAtlas atlas-v9 release, within 6 km of a place named in code.</p>' } : null;
  }
  function drawBeacon(g, v, now) {   // beacon at the target of the last flyTo (a code place or a module's real asset)
    if (!target) return;
    var tp = toLocal(target.lat, target.lon), bz = ground(tp[0], tp[1]), hgt = Math.max(160, v.cam.agl * 0.25), b0 = cam3(tp[0], tp[1], bz), b1 = cam3(tp[0], tp[1], bz + hgt);
    var sg = seg(b0, b1); if (!sg) return;
    var ph = REDUCED ? 1 : 0.6 + 0.4 * Math.sin(now / 300);
    cx.strokeStyle = 'rgba(0,255,255,' + ph + ')'; cx.lineWidth = 3; cx.beginPath(); cx.moveTo(sg[0][0], sg[0][1]); cx.lineTo(sg[1][0], sg[1][1]); cx.stroke();
    var rr = Math.max(40, v.cam.agl * 0.06);
    cx.beginPath(); for (var k = 0; k <= 32; k++) { var a = k / 32 * Math.PI * 2, r = rr + (REDUCED ? 0 : (now / 20) % 60 * rr / 40); line3([tp[0] + Math.cos(a) * r, tp[1] + Math.sin(a) * r, bz], [tp[0] + Math.cos(a + 0.2) * r, tp[1] + Math.sin(a + 0.2) * r, bz]); }
    cx.lineWidth = 1.5; cx.stroke();
    if (b1[2] > NEAR && target.label) { var q = scr(b1); cx.fillStyle = '#00ffff'; cx.font = 'bold 12px ui-monospace,monospace'; cx.fillText(target.label.slice(0, 40), q[0] + 6, q[1]); }
  }
  PILOT.addLayer({ id: 'places', title: 'Grid round places named in code (OpenStreetMap)', order: 40, credit: CREDIT.osm, draw: drawPlaces, pick: pickPlaces });
  PILOT.addLayer({ id: 'beacon', title: 'Target beacon', order: 80, draw: drawBeacon });

  function drawStreaks() {   // FAST MODE speed streaks (W01-S09), never under reduced motion
    if (REDUCED || cam.speed < 300) return;
    var n = Math.min(70, Math.round((cam.speed - 300) / 30)), m = Math.max(Wd, Ht) * 0.5, sp = Math.min(1, cam.speed / 2500);
    cx.save(); cx.strokeStyle = 'rgba(156,219,255,' + (0.15 + 0.25 * sp) + ')'; cx.lineWidth = 1; cx.beginPath();
    for (var i = 0; i < n; i++) { var a = Math.random() * 6.2832, r0 = (0.3 + Math.random() * 0.6) * m, len = r0 * (0.08 + 0.3 * sp), ca = Math.cos(a), sa = Math.sin(a);
      cx.moveTo(Wd / 2 + ca * r0, Ht / 2 + sa * r0); cx.lineTo(Wd / 2 + ca * (r0 + len), Ht / 2 + sa * (r0 + len)); }
    cx.stroke(); cx.restore(); streaks += n;
  }
  function drawLayers(now) {
    for (var i = 0; i < layers.length; i++) {
      var l = layers[i]; if (l.visible === false || !l.draw) continue;
      var t = performance.now(); cx.save();
      try { l.draw(cx, view, now); } catch (e) { warnOnce('layer ' + l.id, e); }
      cx.restore(); l._ms = l._ms * 0.9 + (performance.now() - t) * 0.1;
    }
  }

  // ---- frame loop
  function frame(now) {
    var raw = Math.min(0.1, Math.max(0, (now - last) / 1000)); last = now; frameNo++;
    if (raw > 0) fps = fps * 0.95 + (1 / raw) * 0.05;
    var dt = Math.min(0.05, raw) * timeScale, agl0 = cam.z - ground(cam.x, cam.y);
    demPause = agl0 > 3000 || imgPause;
    if (flight) flyStep(raw * timeScale);